# get_guide: assets

This is a subtopic for exports/screenshots/assets/SVG import/image layers. If you have not already loaded the parent topic, call `get_guide` with `topic: "use"` first. The `use` topic also requires the `mcp` topic to be loaded before any Sketch MCP tool call.

# Export and assets — deep dive

Use after calling `get_guide` with `topic: "use"`, section "run_code Playbook: Mandatory constraints", when you need full `sketch.export` options, are writing assets to disk, importing SVG, or assigning images to layers. For image bytes in MCP responses, use `get_screenshot` — do not return export buffers from `run_code`.

When creating new UI, use placeholder rectangles or image slots until the layout is stable. Import, generate, export, or assign real image assets only after the surrounding containers, spacing, and stack order have passed screenshot validation.

## `sketch.export` signature

```javascript
sketch.export(objectOrArray, options)
```

`objectOrArray` is a layer, an array of layers, a page, or an array of pages. `options` is a dictionary. In MCP workflows, always set `output` to an absolute directory path so files land on disk — project assets dir, or a temp folder (e.g. `/tmp/sketch-exports`) when you only need a short-lived handoff. Do not use `output: false` or omit `output` to return buffers from `run_code`.

### Options

- `output` — absolute path string (required in MCP). Default: `~/Documents/Sketch Exports`. Directory where files are written (project path or temp). Omit or set `false` only in non-MCP plugin scripts — not in `run_code`.
- `filename` — string. Default: layer name. Use with extension (`'icon.png'`). Without, Sketch falls back to the layer name.
- `formats` — array or comma-separated string. Default: `['png']`. `'png'`, `'jpg'`, `'webp'`, `'svg'`, `'pdf'`, `'json'`. Multiple formats produce multiple files.
- `scales` — array of numbers (as strings). Default: `['1.0']`. `['1.0', '2.0', '3.0']` for `@1x/@2x/@3x`
- `use-id-for-name` — boolean. Default: `false`. Use layer `objectID` instead of `name` in filenames
- `overwriting` — boolean. Default: `false`. Allow overwriting existing files
- `trimmed` — boolean. Default: `false`. Trim transparent space from raster exports
- `compact` — boolean. Default: `false`. SVG: produce more compact output
- `include-namespaces` — boolean. Default: `false`. SVG: include extra attributes
- `save-for-web` — boolean. Default: `false`. PNG: strip color profile and metadata
- `compression` — number `[0..1]`. Default: `1.0`. JPG: 0 = max compression, 1 = max quality
- `progressive` — boolean. Default: `false`. JPG: progressive encoding
- `group-contents-only` — boolean. Default: `false`. Group: export only the bounding rectangle of children

### Safe export pattern (file on disk)

```javascript
const sketch = require('sketch');
const doc = sketch.getSelectedDocument();
var layer = sketch.find('#' + layerId, doc)[0];

sketch.export(layer, {
  output: '/absolute/path/to/project/public/assets',  // absolute path is required
  filename: 'icon-apple.png',                          // include extension
  formats: ['png'],
  scales: ['1.0', '2.0', '3.0'],
  overwriting: true,
});

console.log(JSON.stringify({ ok: true, file: 'icon-apple.png' }));
```

Verify with the shell (`ls`) after the `run_code` call — Sketch reports success but a missing directory or permission error can still leave you with no file. Log the full path in JSON (`{ ok: true, path: '/tmp/sketch-exports/icon-apple.png' }`) so the agent or shell can read it next.

For one-off exports, create the temp dir in the shell first if needed (`mkdir -p /tmp/sketch-exports`), then point `output` there.

### JSON export (model inspection)

```javascript
sketch.export(layer, {
  output: '/absolute/path/to/dump',
  filename: layer.name + '.json',
  formats: ['json'],
  overwriting: true,
});
console.log(JSON.stringify({ ok: true, file: layer.name + '.json' }));
```

`formats: 'json'` is the only multi-format that can be mixed; everything else requires either a single format or a single `output` target.

## Images in MCP responses

Use `get_screenshot` (`targetDocumentID` + `layerID`) for visual verification and any image the agent must see in the tool result.

For handoff assets (icons, logos, bitmaps for code), export to disk with `sketch.export` and log the absolute path in JSON; read the files from the shell or copy into the project. A temp directory is fine when you are not committing assets yet.

## Image overrides on instances

```javascript
const sketch = require('sketch');
const doc = sketch.getSelectedDocument();
var instance = sketch.find('#' + instanceId, doc)[0];

var prefix = 'HOST/...AFFECTED-LAYER';
var imgOverride = instance.overrides.find(function (o) { return o.id === prefix + '_' + 'image'; });
imgOverride.value = { path: '/tmp/logo.png' };

var resize = instance.overrides.find(function (o) { return o.id === prefix + '_' + 'imageResizeBehavior'; });
if (resize) resize.value = 2;
```

## Assigning images to Image layers directly

For an Image layer that isn't a symbol instance:

```javascript
imageLayer.image = { path: '/absolute/path/image.png' };  // from disk
imageLayer.image = { base64: 'iVBOR...' };                // from base64
```

The Image layer's frame doesn't change automatically — set `imageLayer.frame` to match the desired aspect.

## Importing SVG as a new layer

```javascript
const sketch = require('sketch');
const doc = sketch.getSelectedDocument();
var svg = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24">'
        + '<circle cx="12" cy="12" r="10" fill="#575fff"/>'
        + '</svg>';
var layer = sketch.createLayerFromData(svg, 'svg');
layer.parent = doc.selectedPage;
layer.frame = { x: 0, y: 0, width: 24, height: 24 };
console.log(JSON.stringify({ ok: true, id: layer.id, type: layer.type }));
```

`createLayerFromData(data, 'svg')` produces a `Group` containing the parsed SVG. For PDF/Bitmap content, use `Image` layers with `image = { path }`.

## Troubleshooting exports

### Export produced no file or empty file

1. Make `output` absolute.
2. Pass both `filename` and extension.
3. If the file already exists, set `overwriting: true`.
4. Create missing parent directories with shell `mkdir -p` before the export call.
5. Do not export from a symbol instance's `expandedLayers`. Screenshot the instance when rendered overrides matter, or export a stable document layer.

After every export, verify with the shell:

```bash
ls -la "/abs/out/dir"
```

## Common pitfalls

- `fs is not a core package` — Sketch's JS runtime doesn't expose Node's `fs`. Don't try to write files from within `run_code`; use `sketch.export` or have the agent shell out separately.
- Missing `output` directory — Sketch creates intermediate directories, but only the last segment. If `/a/b/c` doesn't exist and you ask for `/a/b/c/d/file.png`, only `d/` is created; deeper missing parents may silently fail. Build the path with the shell first if uncertain.
- No `overwriting: true` — Re-running a script that exports to an existing file will not overwrite by default and will fail silently for that file.
- `scales` as numbers vs strings — Both forms are accepted, but `['2.0']` is the documented shape; integers also work (`[2]`).
- Relative `output` paths — Don't use them. The Sketch JS runtime's notion of cwd is unrelated to your shell's. Pass an absolute path or you'll get files in unexpected locations.
- `output: false` / buffer return in `run_code` — Not for MCP. Use `get_screenshot` for images; use `sketch.export` with an absolute `output` + `filename` for assets on disk.

## Quick recipes

```javascript
// Export the currently selected layer at 2x PNG to a dir
const sketch = require('sketch');
const doc = sketch.getSelectedDocument();
var sel = doc.selectedLayers.layers[0];
sketch.export(sel, {
  output: '/Users/me/Desktop/exports',
  filename: sel.name + '.png',
  formats: ['png'],
  scales: ['2.0'],
  overwriting: true,
});
console.log(JSON.stringify({ ok: true, file: sel.name + '.png' }));
```

```javascript
// Export every top-level Frame on the current page as 1x PNG
const sketch = require('sketch');
const doc = sketch.getSelectedDocument();
var frames = doc.selectedPage.canvasLevelFrames;
frames.forEach(function (f) {
  sketch.export(f, {
    output: '/abs/out',
    filename: f.name + '.png',
    formats: ['png'],
    overwriting: true,
  });
});
console.log(JSON.stringify({ ok: true, count: frames.length }));
```
