Script functions
A canvas script is a synchronous JavaScript string passed to canvases.execute. The global document is the string "document", used as the root container. Reads see earlier writes in the same call. Scripts have no fetch, timers, file APIs or module imports; perform network and file operations in the outer codemode program.
Function reference
Node is an object from the node reference; VariableSet maps names to {type,value} definitions. Function names are case-sensitive. Void functions return undefined inside the script. The outer execute result does not use the last expression; use Print for output.
Insert
Insert(parent: string, node: Node): string
Appends a node tree to document or a frame/group, assigning fresh IDs recursively; returns its root ID. node.type is required; negative sizes and percentage/viewport/calc sizes are rejected. Cannot insert into instance descendants.
Copy
Copy(path: string, parent: string, overrides?: object): string
Creates a ref for reusable sources and a deep copy for ordinary sources. overrides merges root properties; descendants overrides/replaces by unique name or source ID. Returns the new ID; copying an instance child path is unsupported.
Update
Update(path: string, patch: object): void
Shallow-merges ordinary node properties; null deletes a property. Cannot change id/type/ref or supply children. Instance child paths merge into the instance descendants map. On a ref root, descendants merges keys with existing entries; a new object replaces the old object at the same key.
Replace
Replace(path: string, node: Node): string
Deletes an ordinary subtree and inserts a fresh tree at the same parent/order, returning a new ID; records two operations. For an instance child, records a descendants replacement in one operation; the replacement is addressed by its new ID alone.
Move
Move(path: string, parent?: string, index?: number): void
Omitted parent retains the current parent. index is zero-based among siblings after removing this node; omission appends, out-of-range values clamp. Cycles and instance child paths are rejected.
Delete
Delete(path: string): void
Deletes the node and all descendants. document is protected. Cannot delete instance descendants; hide them with Update(path,{enabled:false}).
SetVariables
SetVariables(variables: VariableSet, replace?: boolean): void
Merges by variable name by default; replace:true replaces the variable set, retaining previously registered theme-axis values. Names cannot start with $; definitions need type/value. Theme axes are collected from value arrays.
GetVariables
GetVariables(): {variables: VariableSet, themes: object}
Returns raw variable definitions and theme axes, not scalar values resolved for a theme.
Get
Get(path?: string, visitor?: function, options?: object): Node / unknown[]
Without a visitor, requires a specific node and returns its subtree. Whole-document reads require a visitor. Arguments are recognized by type; omit path to visit all roots. Details below.
FindEmptySpace
FindEmptySpace({width, height, direction?, padding?, nodeId?}): {x:number,y:number}
Returns a position adjacent to the world-space union of top-level nodes or nodeId. direction defaults to right, padding to 0; no nodes gives {x:0,y:0}. Not a recursive hole search; width/height offset left/up placements.
Print
Print(...values: unknown[]): void
Writes strings as-is and JSON-serializes other values, joining with spaces in result prints. Throws above the cumulative 65536 limit.
TakeScreenshot
TakeScreenshot(nodeIds: string[]): void
Records at most 4 IDs; extras are silently ignored. Does not deduplicate or render. Pass execute result screenshots IDs to images.list.
Export and Generate have global names but throw when called. There is no script function to export .pen or generate images.
Get visitors
Get(path, visitor, options) traverses depth-first, visiting parents first. Non-undefined visitor returns form the result array in order; nodes returning undefined add nothing. Each visited node is a shallow snapshot without children. Mutating it does not write to the canvas; use Update.
| options | Default | Behavior |
|---|---|---|
| depth | Unlimited | Root is 0; limits descendant levels. Without a visitor, children beyond this depth appear as ”…” |
| resolveInstances | false | Refs are visitor leaves by default; true visits expanded instance children |
| resolveVariables | false | Raw single-node reads retain references by default; true uses expanded reads |
| includePathGeometry | Unset | Currently does not filter geometry; do not rely on it to reduce output |
Visitors always receive expanded nodes with variables resolved; resolveVariables:false does not restore raw references in a visitor. Single-node reads taking the expansion path (resolveInstances/resolveVariables true, or an instance child path) also return resolved values; there are no independent two-stage resolution switches.
| ctx field | Contents |
|---|---|
| node | Same object as the visitor’s first argument |
| parentCtx | Visited parent’s ctx; undefined at traversal roots |
| depth | Depth relative to this traversal root |
| index | Current sibling index; each top-level root is 0 |
| bounds | Lazily computed {x,y,width,height}, relative to the parent, not world coordinates |
| problems | “partially clipped”, “fully clipped” or undefined; does not include FIT_FILL_CYCLE |
| skipChildren() | Skip this node’s descendants |
Get(document) without a visitor fails. Use Get(document, visitor) or Get(visitor) for the whole canvas. Instance node IDs are paths, with multiple / segments for nested instances. Bounds for a replacement’s new ID can currently be all zero in a visitor; do not treat that ID as an independently stored node for nodes.list.
This script inserts, copies, updates, moves, replaces, deletes and reads bounds. Area is 320 × 160, Copied is 80 × 32, Changed is 40 × 40, and the empty position is {x:340,y:0}.
const area = Insert(document, { type: "frame", name: "Area", layout: "none", width: 320, height: 160, fill: "#FFFFFF"});const original = Insert(area, { type: "rectangle", name: "Original", x: 16, y: 16, width: 64, height: 32, fill: "#3366FF"});const copied = Copy(original, area, { name: "Copied", x: 96 });Update(copied, { width: 80 });Move(copied, area, 0);const changed = Replace(original, { type: "ellipse", name: "Changed", x: 16, y: 64, width: 40, height: 40, fill: "#00AA66"});const temporary = Insert(area, { type: "rectangle", width: 1, height: 1 });Delete(temporary);Get(area, (node, ctx) => { if (ctx.problems) Print(node.id, ctx.problems); return { id: node.id, bounds: ctx.bounds, depth: ctx.depth, index: ctx.index };}).forEach(item => Print(item));Print(FindEmptySpace({ width: 100, height: 80, direction: "right", padding: 20 }));TakeScreenshot([area]);Globals across calls
Successful calls on the same canvas save global-object properties and restore them for the next call. Values that round-trip through JSON persist: null, strings, finite numbers, booleans, plain objects and arbitrarily nested arrays. Functions, undefined, Symbols, BigInts, cycles and built-in objects such as Date and Map do not persist, including when nested in an object or array. Each serialized variable is limited to 256 KiB; the saved JSON of all variables, including names, is limited to 1 MiB, measured in UTF-8 bytes. Globals whose values are functions are silently skipped without warnings. Functions do not persist and must be defined again on each execute. Other skipped variables produce warnings with code GLOBAL_NOT_KEPT and a message containing the variable name and reason. The response globals list contains only names actually saved. Undeclared assignment (such as savedFrame = ...), var and globalThis properties can persist; top-level const/let bindings are local to this call and do not persist. Failed calls do not save new globals.
First call:
savedFrame = Insert(document, { type: "frame", name: "Saved", width: 200, height: 80, fill: "#FFFFFF"});var savedCount = 1;const localOnly = "not persisted";Get(savedFrame, (node, ctx) => Print(node.name, ctx.bounds));Next call on the same canvas (prints 2 undefined and changes width to 240):
savedCount += 1;Update(savedFrame, { width: 240 });Print(savedCount, typeof localOnly);Get(savedFrame, (node, ctx) => Print(node.name, ctx.bounds));Rollback, repairs and limits
An uncaught exception or rejected operation rolls back the entire execute, including earlier writes and new globals. Error responses use {error:{code,message,details}}; script failure details include edit_id and may include line, column and rejection. Rejected operations throw with rejection information; swallowing an exception can let a call succeed, so do not assume it still fails.
Within ten minutes, submit edit_id and edits to rerun the repaired full script. edits applies {find,replace,all?} replacements sequentially. With default all:false, find must occur exactly once in the source at that step. Missing or multiple matches raise SCRIPT_ERROR. all:true replaces all matches but still fails if none exist. A repaired script restarts from the beginning, not the failing position. If edit_id is unknown or expired, send corrected script source.
Request shape (failed_edit_id is the value returned by this failure; use describe to check how your SDK exception exposes the response):
{ "edit_id": "failed_edit_id", "edits": [{ "find": "fontSize: 320", "replace": "fontSize: 32" }]}Each call records at most 5000 operations, 65536 JavaScript string units of Print output and 4 TakeScreenshot IDs. Script size is limited to 65536 JavaScript string units; VM memory is 32 MiB, stack 1 MiB, and at most 20000 interrupt polls. String counts are not UTF-8 byte counts. See limits and errors for recovery rules.