{"id":101686,"plugin_id":"plugin_connector_68df038e0ba48191908c8434991bbac2","kind":"skill","collection_source":"plugin_package","comparison_source":"plugin_package","observed_at":"2026-11-17T18:12:25.270Z","digest":"8620bf58045ca8bcf8820b09eac44181da76900a6ce672b9647797379ff5d5e0","against":98484,"payload":{"description":"**MANDATORY prerequisite** — you MUST invoke this skill BEFORE every `use_figma` tool call. NEVER call `use_figma` directly without loading this skill first. Skipping it causes common, hard-to-debug failures. Trigger whenever the user wants to perform a write action or a unique read action that requires JavaScript execution in the Figma file context — e.g. create/edit/delete nodes, set up variables or tokens, build components and variants, modify auto-layout or fills, bind variables to properties, or inspect file structure programmatically.","included_files":[{"relative_path":"references/api-reference.md","size_in_bytes":16608},{"relative_path":"references/common-patterns.md","size_in_bytes":12359},{"relative_path":"references/component-patterns.md","size_in_bytes":26483},{"relative_path":"references/critical-rules-deep.md","size_in_bytes":11775},{"relative_path":"references/effect-style-patterns.md","size_in_bytes":2574},{"relative_path":"references/fig-builder.md","size_in_bytes":39843},{"relative_path":"references/gotchas.md","size_in_bytes":53636},{"relative_path":"references/plugin-api-standalone.d.ts","size_in_bytes":443167},{"relative_path":"references/plugin-api-standalone.index.md","size_in_bytes":40482},{"relative_path":"references/text-style-patterns.md","size_in_bytes":5914},{"relative_path":"references/validation-and-recovery.md","size_in_bytes":3973},{"relative_path":"references/variable-patterns.md","size_in_bytes":14937},{"relative_path":"references/working-with-design-systems/wwds-components--creating.md","size_in_bytes":2199},{"relative_path":"references/working-with-design-systems/wwds-components--using.md","size_in_bytes":3170},{"relative_path":"references/working-with-design-systems/wwds-components.md","size_in_bytes":4402},{"relative_path":"references/working-with-design-systems/wwds-effect-styles.md","size_in_bytes":3649},{"relative_path":"references/working-with-design-systems/wwds-text-styles.md","size_in_bytes":5519},{"relative_path":"references/working-with-design-systems/wwds-variables--creating.md","size_in_bytes":1559},{"relative_path":"references/working-with-design-systems/wwds-variables--using.md","size_in_bytes":2273},{"relative_path":"references/working-with-design-systems/wwds-variables.md","size_in_bytes":5183},{"relative_path":"references/working-with-design-systems/wwds.md","size_in_bytes":5220}],"name":"figma-use","skill_md_contents":"---\nname: figma-use\ndescription: \"**MANDATORY prerequisite** — you MUST invoke this skill BEFORE every `use_figma` tool call. NEVER call `use_figma` directly without loading this skill first. Skipping it causes common, hard-to-debug failures. Trigger whenever the user wants to perform a write action or a unique read action that requires JavaScript execution in the Figma file context — e.g. create/edit/delete nodes, set up variables or tokens, build components and variants, modify auto-layout or fills, bind variables to properties, or inspect file structure programmatically.\"\ndisable-model-invocation: false\n---\n# use_figma — Figma Plugin API Skill\nUse the `use_figma` tool to execute JavaScript in Figma files via the Plugin API. All detailed reference docs live in `references/`.\n\nWhen available, call `create_session` with `fileKey` and `description` before file reads or edits (create the file first if needed), then pass the returned `sessionId` unchanged to every call that accepts it, including follow-ups and work across files.\n\n**Always include `figma-use` in the comma-separated `skillNames` parameter when calling `use_figma`. If this skill was loaded via an MCP resource, you MUST prefix the name with `resource:` (e.g. `resource:figma-use`).** This is a logging parameter used to track skill usage — it does not affect execution.\n\n**If Figma MCP tools appear as deferred tools, batch-load all their schemas in a single `ToolSearch` call** using the `select:` syntax — e.g. `ToolSearch query=\"select:use_figma,get_screenshot,get_metadata,create_new_file\"`. One round trip beats six.\n\n**MANDATORY for visible design changes:** Before the first mutating `use_figma` call, load [figma-generate-design](../figma-generate-design/SKILL.md) alongside this skill and include both names in every mutating call’s `skillNames`. This applies from a single visible property or element to a full page, screen, or composed multi-section view—even when the user calls that view a component. `figma-use` provides the Plugin API rules; `figma-generate-design` provides design-system discovery through `search_design_system`, asset importing, and incremental assembly.\n\n**If the task involves creating or building a standalone component or a component library in Figma** (even a single component as the deliverable), also load [figma-generate-library](../figma-generate-library/SKILL.md). It owns the component-creation workflow — variable foundations first, variant sets, then design token bindings — that `figma-use` alone doesn't cover. Build the token/variable foundation before the component, then bind the component's `fills`/`cornerRadius`/spacing to those variables rather than inlining literals where a token exists. For components that exist to be reused **inside a screen you are building**, follow [figma-generate-design → componentization](../figma-generate-design/references/componentization.md) instead.\n\n**3D transforms:** For perspective, depth, X/Y tilt, isometric cubes, or other static 3D poses, load [figma-3d-transforms](../figma-3d-transforms/SKILL.md) when available. It owns the gated `transform3d`, `scene3d`, and `transformOrigin` API guidance, including fields that may be absent from the general typings. Follow this skill's node-creation rules, then apply the 3D poses to the resulting nodes. If the 3D skill or APIs are unavailable, explain that 3D authoring is not enabled in this session. Flat in-plane rotation uses `node.rotation` and does not need the 3D skill.\n\nFor other APIs, load [plugin-api-standalone.index.md](references/plugin-api-standalone.index.md) to understand what is possible. When you are asked to write plugin API code, use this context to grep [plugin-api-standalone.d.ts](references/plugin-api-standalone.d.ts) for relevant types, methods, and properties. This is the definitive source of truth for the general API surface. It is a large typings file, so do not load it all at once, grep for relevant sections as needed.\n\nIMPORTANT: Whenever you work with design systems, start with [working-with-design-systems/wwds.md](references/working-with-design-systems/wwds.md) to understand the key concepts, processes, and guidelines for working with design systems in Figma. Then load the more specific references for components, variables, text styles, and effect styles as needed.\n\n## $fig — the plan-based builder API (ALL NODE CREATION MUST USE THIS)\n\n`$fig` is a global that is responsible for all node creation. It auto-flushes at script end (no `$fig.done()` needed), handles font preloading, batches mutations, and orders property assignment correctly. **Use it for all node creation and mutation operations.** Never use `figma.createFrame()`, `figma.createText()` or any `figma.create*` methods. They do not exist in this environment.\n\n**Constructors queue creation, not inert templates.** Every `$fig` node constructor like `$fig.frame(...)` queues a node creation in the plan, even if its returned plan node is never used, returned, or screenshotted. Unattached nodes become top-level nodes at flush. Plan nodes meant to be used as children should be appended or used in `$fig.frame(opts, children)` **before flushing**.\n\n**layoutSizingHorizontal/Vertical = 'FILL' is for auto-layout children only.** Do not set FILL for top-level nodes.\n\n### Plan nodes vs real nodes\n\n`$fig.component(...)`, `$fig.variants(...)`, `$fig.instance(...)`, `$fig.get(...)`, and `$fig.frame(...)` return **plan nodes**, not raw Plugin API nodes. `await $fig.done()` materializes the plan nodes and makes `planNode.node` available for accessing real nodes. Do not use plan nodes like real nodes.\n\n- Use `planNode.set({ name, x, y })` and `planNode.append(childPlanNode)` for queued mutations. Do not make direct assignments like `planNode.x = 100`. Do not mix plan nodes into raw plugin APIs like `node.appendChild(planNode)`.\n- Prefer `$fig.instance(componentPlanNode, opts)` or `planNode.instance(componentPlanNode, opts)` to create instances of plan component nodes, with no intermediate flush.\n- Use `planNode.node` only when you need raw state or an operation `$fig` or plan nodes do not expose. Flush pending changes first. Do not mix raw plugin code amongst pending changes.\n\n### `$fig` quick reference\n\nThis is the full `$fig` surface. Open [references/fig-builder.md](references/fig-builder.md) for worked details: gridding variant sets, style handle semantics, variable aliasing, query screenshots, and mid-script materialization.\n\n| Need | Call |\n|---|---|\n| Create nodes | `$fig.autoLayout(opts, children?)` (hugs both axes; default `HORIZONTAL`), `$fig.frame`, `$fig.text({ characters, fontName, fontSize, fills })`, `$fig.rectangle`, `$fig.ellipse`, `$fig.polygon`, `$fig.star`, `$fig.line`, `$fig.vector`, `$fig.section`, `$fig.page`: all `(opts?, children?)` |\n| Create from SVG | `$fig.svg(svgString, opts?)` builds a vector node tree; `$fig.svgComponent(svgString, opts?)` builds it as a main component (icons). |\n| Group and boolean | `$fig.group`, `$fig.union`, `$fig.subtract`, `$fig.intersect`, `$fig.exclude`: all `(opts?, children?)` |\n| Add children | `parent.append(a, b)`, `parent.addAt(index, child)`, or call a constructor on the plan node: `card.text({ ... })` |\n| Components | `$fig.component(opts, children)`; variant set: `$fig.variants({ name }, [$fig.component({ name: 'State=Default' }, [...]), ...])`. Variants stack at (0,0), so grid them afterward (fig-builder.md). |\n| Component properties | On a layer inside the component: `.textProp('Label')`, `.booleanProp('Show Icon')`, `.instanceSwapProp('Icon')`, `.slotProp('Content')` (on a descendant frame) |\n| Instances | `$fig.instance(compRef, { props: { Label: 'Save', State: 'Hover' } })`, where `compRef` is a component plan node, a node ID, or a library `componentKey` / `componentSetKey` (import is queued); existing instance: `$fig.get(id).set({ props: { ... } })` |\n| Existing nodes | `$fig.get(idOrLibraryKey)`; `$fig.query(selector, scope?)` with CSS-like selectors (`'FRAME[name*=Card] TEXT'`) |\n| Query results | `length`, `first()`, `last()`, `at(i)`, `find(fn)`, `filter(fn)`, `slice(start, end?)`, `query(selector)`, `each(fn)` / `forEach(fn)`, `map(fn)`, `values(paths)`, `toArray()`, `set(props)`, `moveTo(parent, index?)`, `replace(newNode)`, `remove()`, `screenshot(opts?)` |\n| Edit, move, delete | Plan node: `.set(props)`, `.replace(newNode)`, `.moveTo(parent, index?)`, `.clone(props?)`, `.remove()`, `.reorderChildren(children)`, `.gradient(type, stops, transform?)`, `.image(hash, scaleMode?)`. Global: `$fig.set(target, props)`, `$fig.delete(...nodes)`, `$fig.move(target, parent, index?)`, `$fig.clone(target, props?)`, `$fig.append(parent, child)`, `$fig.addAt(parent, index, child)`, `$fig.replace(old, new)`, `$fig.reorder(parent, children)`, `$fig.gradient(node, type, stops, transform?)`, `$fig.image(node, hash, scaleMode?)` |\n| Variables | `const tokens = $fig.varCollection({ name, modes: ['Light', 'Dark'] })`, then `tokens.colorVar({ name, values: { Light: '#FFFFFF', Dark: '#000000' }, scopes })`, `.numVar`, `.stringVar`, `.boolVar`; existing: `$fig.getVar(idOrLibraryKey)` |\n| Bind a variable | Pass the handle as the value: `paddingLeft: space`, `cornerRadius: radius` (all four corners), `fills: [{ type: 'SOLID', color: brand }]` |\n| Styles | Create with `$fig.paintStyle` / `$fig.textStyle` / `$fig.effectStyle({ name, ... })`; existing: `$fig.getStyle(nameOrIdOrKey)`; apply with `fills: style`, `effects: style`, `textStyle: style` |\n| Screenshot | `node.screenshot({ scale?, contentsOnly? })`: queued, no `await`, one per node |\n| Real nodes and IDs | `await $fig.done()`, then `planNode.node` (null before the flush). Without it, the script auto-flushes and returns the created IDs. |\n\nLibrary keys (`componentKey`, `componentSetKey`, and style or variable `key` values) come from `search_design_system`; `$fig.get`, `$fig.instance`, `$fig.getStyle`, and `$fig.getVar` queue their import in the plan.\n\n**Icons:** **Prefer real vector icons:** import the icon's SVG source (inline `<svg>`, the `.svg` asset, or the source icon-library glyph — e.g. lucide/heroicons) via `$fig.svg(...)` rather than approximating an icon with a typed emoji/Unicode glyph (★ ⚙ 🔍 ☰ ▾) or a plain rectangle. A simple glyph or shape is a fine fallback when the real SVG genuinely can't be obtained — just reach for the SVG first. (Don't reconstruct an icon from rotated line/rect primitives, though — that renders broken.) Full recipe (viewBox+width/height sizing, `currentColor`, INSTANCE_SWAP for design-system icons): [figma-generate-design → Icons](../figma-generate-design/SKILL.md#icons-import-the-svg-never-reconstruct-from-rotated-primitives).\n\n### Copy these patterns\n\n**Build an auto-layout frame with children — single call:**\n```js\n$fig.autoLayout(\n  // fixed width; omit height to hug vertically\n  { name: 'Todo List', layoutMode: 'VERTICAL', width: 480 },\n  ['item 1', 'item 2', 'item 3'].map((item) =>\n    $fig.autoLayout(\n      // FILL is valid because this item is attached to the auto-layout Todo List\n      { name: 'Todo Item', layoutSizingHorizontal: 'FILL' },\n      [$fig.text({ characters: item, fontName: { family: 'Inter', style: 'Bold' } })],\n    ),\n  ),\n).screenshot() // Composition check; do not repeat unless a relevant change needs visual verification.\n```\n\n**Repeated UI (list items, cards, nav items, table rows, day cells): build ONE component, then place instances.** Do not build N near-identical frames. TEXT/BOOLEAN props carry the per-item differences:\n```js\nconst ITEMS = [\n  { title: 'Inbox', count: '12' },\n  { title: 'Drafts', count: '' },\n  // ...from the source data\n]\nconst item = $fig.component({ name: 'Nav Item', layoutMode: 'HORIZONTAL', itemSpacing: 8 }, [\n  $fig.text({ characters: 'Label' }).textProp('Label'),\n  $fig.text({ characters: '0' }).textProp('Count').booleanProp('Show Count'),\n])\n$fig.autoLayout({ name: 'Nav', layoutMode: 'VERTICAL', width: 240 },\n  ITEMS.map((v) => $fig.instance(item, {\n    layoutSizingHorizontal: 'FILL',\n    props: { Label: v.title, Count: v.count, 'Show Count': v.count !== '' },\n  })),\n).screenshot()\n```\nWhen building a screen, keep main components outside the view: in the file's existing component area, or off to the side of the wrapper. Return `item.node.id` (after `await $fig.done()`) when a later call needs more instances: `$fig.instance('ID', { props })`. Only genuinely one-off containers stay plain frames. See [figma-generate-design → componentization](../figma-generate-design/references/componentization.md).\n\n**Source-defined or repeated icons: import the SVG once into a component, then place instances.** Reuse a compatible local or library icon component when one exists. Otherwise, when the source uses an icon component (even once inside the requested component) or repeats an icon, create one local main component with `$fig.svgComponent(svgStr, opts)`. It converts the imported SVG's outer frame into the component, preserving its children without adding a wrapper. Keep that main component in the existing component area, outside the composed view. Insert instances into parent components and their variants so the icon remains a reusable dependency. Direct SVG children are appropriate for genuinely one-off artwork that the source does not define as a reusable component.\n```js\n// Read this exact SVG from the source asset or icon library first.\nconst chevronSvg = '<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"m9 6 6 6-6 6\" stroke=\"#111827\" stroke-width=\"2\"/></svg>'\nconst chevron = $fig.svgComponent(chevronSvg, { name: 'ChevronRight', width: 24, height: 24 })\nconst iconButton = $fig.component({ name: 'IconButton', layoutMode: 'HORIZONTAL' }, [\n  $fig.instance(chevron),\n])\nconst preview = $fig.autoLayout({ name: 'Preview', x: 400, layoutMode: 'HORIZONTAL' }, [\n  $fig.instance(iconButton),\n  $fig.instance(iconButton),\n])\nawait $fig.done()\nreturn { iconId: chevron.node.id, buttonId: iconButton.node.id, previewId: preview.node.id }\n```\nA later call can reuse the returned icon ID with `$fig.instance(iconId)`. The SVG is imported only in the main icon component, and each button contains an icon instance.\n\n**Update existing nodes — by query or by id:**\n```js\n$fig.query('FRAME[name=Header] TEXT[name=Title]').set({ characters: 'New Title', fontSize: 24 })\n$fig.get('1:42').set({ opacity: 0.8, cornerRadius: 12 })\n```\n\n**Add a node inside an existing node**\n```js\n$fig.get('1:42').append($fig.autoLayout({ name: 'New Frame' }))\n```\n\n`parent.append(a, b, c)` and `$fig.append(parent, a, b, c)` append every child in order and return the parent for chaining.\n\n**Create variants and place an instance**\n```js\nconst SIZES = ['Small', 'Medium', 'Large']\nconst buttonComponentSet = $fig.variants({ name: 'Button' }, SIZES.map((size) => $fig.component({ name: `Size=${size}`, layoutMode: 'HORIZONTAL', /** other props */ })))\nconst buttonInst = $fig.instance(buttonComponentSet, { props: { Size: 'Medium' } })\n$fig.get('DESTINATION_FRAME_ID').append(buttonInst)\n// Creation and placement are queued; no intermediate done() is needed.\n```\nSelect variants through `props` on the component set. This also works with published sets when individual variant references are unavailable.\nIf an earlier measurement required `await $fig.done()`, continue using plan node `.set(...)` and `.append(...)` for changes and placement.\n\n> ⚠️ `$fig.variants` does **not** position the variants — they stack at (0,0) and the set renders as one collapsed, overlapping element. You must grid the variants and resize the set afterward. See [`fig-builder.md`](references/fig-builder.md#required-follow-up--grid-the-variants-fig-build--raw-layout) for the required follow-up recipe.\n\n> **Building a component — even a single one? Binding tokenized values is part of finishing the job, not a preference.** A component is **not complete** while any value that *has* a corresponding design token — one that already exists in the file, or that you created from the source — is still a hardcoded literal. When a token exists for a `fills` color / `cornerRadius` / padding / `itemSpacing`, bind it: build a `$fig.varCollection` (primitive tier + semantic tier aliased to it) and pass the variable **handle straight into the property**. **Anti-pattern to avoid:** do NOT copy resolved token values into local JS constants (e.g. `const VARIANTS = [{ bg: '#2c2c2c' }]`) and paint with resolved literal colors — that silently bypasses variables even though the source defines tokens. This applies to a single component as much as a full design system. **Only bind values that actually have a token** — values with genuinely no token (one-off geometry, icon pixel sizes, static 1px dividers) correctly stay literal; don't invent tokens to bind. **If you create the variables in one `use_figma` call and build the component in a later one, rehydrate the handles first** (`$fig.getVar(id)` or `figma.variables.getVariableByIdAsync` using the IDs you returned) — a handle from a previous call isn't in scope. Worked recipe: [fig-builder.md → Building a component with bound variables](references/fig-builder.md#building-a-component-with-bound-variables-the-default-for-components).\n\n**Create an instance of a component**\n```js\n// First arg can be a component plan wrapper, a node ID ('1:2'), OR a library asset key\n// from `search_design_system` results (the `componentKey` or `componentSetKey` field, according to `assetType`).\n$fig.instance('1:2', { name: 'Cancel Btn', props: { label: 'Cancel'}})\n```\n\n**Consume styles/variables**\n```js\n$fig.autoLayout({ name: 'Card', itemSpacing: spacingVar, fills: fillStyle })\n\n// Looked up by asset key from `search_design_system` (the `key` field)\n$fig.autoLayout({ fills: $fig.getStyle(BG_STYLE_KEY) })\n$fig.rectangle({ fills: [{ type: 'SOLID', color: $fig.getVar(BRAND_VAR_KEY) }] })\n```\n\n**Use design-system assets by key (from `search_design_system`)**\n\n`search_design_system` returns `componentKey` for components, `componentSetKey` for component sets, and `key` for styles and variables. Pass these straight into the unified `$fig` lookup — the plan queues the library import automatically, so you don't need a separate `await figma.importComponentByKeyAsync(...)` / `importStyleByKeyAsync(...)` / `importVariableByKeyAsync(...)` step.\n```js\n// One call site, many input shapes — node IDs, real variable/style ids,\n// AND 40-char asset keys (e.g. '49c8754d4b898e176148650df612a47998a8c4a1')\nconst btn        = $fig.get(BUTTON_KEY)                    // component / component set\nconst instance   = $fig.instance(BUTTON_SET_KEY, {         // create an instance from a set\n  props: { Size: 'md', Variant: 'primary' },\n})\nconst heading    = $fig.getStyle(HEADING_TEXT_STYLE_KEY)   // paint / text / effect / grid style\nconst brand      = $fig.getVar(BRAND_COLOR_VAR_KEY)        // variable\n\n$fig.text({ characters: 'Hello', textStyle: heading })\n$fig.rectangle({ fills: [{ type: 'SOLID', color: brand }] })\n```\n\n**Discover a set's variant props from its key** — `search_design_system` returns a set's `componentSetKey`, not its variant properties. This is **two `use_figma` calls**: call 1 `return`s the set's property definitions and its variants so their props come back to you in the tool result; then, knowing the valid props, call 2 instantiates the variant you want.\n```js\nconst setHandle = $fig.get(BUTTON_SET_KEY)\nawait $fig.done()\nconst set = setHandle.node\nif (!set || set.type !== 'COMPONENT_SET') {\n  throw new Error(`Key ${BUTTON_SET_KEY} is not a COMPONENT_SET`)\n}\nreturn {\n  componentPropertyDefinitions: set.componentPropertyDefinitions,\n  variants: set.children\n    .filter((c) => c.type === 'COMPONENT')\n    .map((c) => ({ name: c.name, variantProperties: c.variantProperties })),\n}\n```\n```js\n// Call 2 — instantiate with props you picked from call 1's output\n$fig.instance(BUTTON_SET_KEY, { props: { Size: 'Large', Kind: 'Secondary' } })\n```\n\n**Bulk component swap — `$fig.query().set()`:**\n```js\nconst chevron = $fig.get('CHEVRON_KEY')\n$fig.query('INSTANCE[name=arrow_drop_down]').set({ mainComponent: chevron })\n```\n\n**`.query()` and `.values()` for search and projecting child values**\n```js\nconst menuArrows = $fig\n  .query('PAGE[name=Menu] INSTANCE[mainComponent.name*=arrow], PAGE[name=Menu] INSTANCE[mainComponent.name*=chevron]')\n  .values(['id', 'name', 'mainComponent.name', 'mainComponent.id']);\n\n// Use quotes for multi-word selector values\nconst expandComponents = $fig\n  .query('COMPONENT[name*=expand], COMPONENT[name*=chevron_down], COMPONENT[name*=chevron_up], COMPONENT[name*=\"multi word name\"]')\n  .values(['id', 'name']);\n```\n\n**Perform operations on another page:**\n\nPage context resets to the first page at the start of each `use_figma` call. When an operation needs another current page, switch with `await figma.setCurrentPageAsync(page)` before queuing the plan; never assign `figma.currentPage` directly. Switch at most once per call. Split work requiring multiple current-page contexts into independent calls, one per page; issue independent calls in parallel. A scoped FigQuery search does not itself require a separate call for every page.\n```js\n// Switch to a specific page (loads its content)\nconst targetPage = figma.root.children.find((p) => p.name === \"My Page\");\nawait figma.setCurrentPageAsync(targetPage);\n$fig.query('INSTANCE[name=arrow_drop_down]').set({ ... })\n```\n\n**Gradient via helper — no manual transform matrix needed:**\n```js\nconst node = $fig.rectangle({ width: 240, height: 120 })\n$fig.gradient(node, 'LINEAR', [\n  { pos: 0, color: figma.util.rgba('#000000') },\n  { pos: 1, color: figma.util.rgba('#ffffff') },\n])\n```\n\n**Literal colors — use the built-in utilities, available in every call:**\n```js\n$fig.rectangle({ fills: [figma.util.solidPaint('#2563eb80')] }) // alpha becomes paint opacity\nconst rgb = figma.util.rgb('#2563eb') // { r, g, b }; ignores input alpha\nconst rgba = figma.util.rgba('#2563eb80') // { r, g, b, a }; for gradient stops/effects\n```\nUse these utilities directly instead of defining a hex parser or relying on helpers from a previous `use_figma` call. For token-backed properties, keep passing the variable handle directly; converting its resolved color to a paint would lose the binding.\n\n**Chaining on plan nodes — alternative to children array:**\n```js\nconst card = $fig.autoLayout({ name: 'Card', layoutMode: 'VERTICAL' })\ncard.text({ characters: 'Title', fontSize: 20 })\ncard.text({ characters: 'Description', fontSize: 14 })\n```\n\n### When to use the raw Figma Plugin API\n\nKeep raw Plugin API code that reads or changes document state separate from planned creation and mutations. Run it before `$fig` code, or after an explicit `await $fig.done()` that flushes all pending changes. Do not pass plan nodes to raw methods such as `regularNode.appendChild(planNode)` or `insertChild`; use `$fig.get(regularNode.id).append(planNode)` or `.addAt(index, planNode)` instead. Planned changes are not visible to raw reads such as `regularNode.children` until the plan is flushed. After flushing, use `planNode.node` when a raw API needs the real node. Pure color helpers such as `figma.util.solidPaint`, `.rgb`, and `.rgba` can be used inside `$fig` expressions.\n\nUse the raw API only in these cases:\n\n- **Color conversion:** `figma.util.solidPaint`, `.rgb`, and `.rgba` convert literal colors for `$fig` properties without creating or mutating nodes.\n- **Mid-script async result needed:** `await figma.setCurrentPageAsync(...)`, `await figma.loadFontAsync(...)` — must complete before subsequent plan steps can use the result. (Importing library components is NOT one of these cases: pass the matching `componentKey` or `componentSetKey` straight into `$fig.get(...)` / `$fig.instance(...)` and pass variant property values in `props`. `$fig` queues the library import in the plan and resolves the variant for you.)\n- **Mid-script real node state read:** measured `width` / `height` after auto-layout, computed colors, getStyledTextSegments — materialize mid-script, then read `.node` on the plan node. See [references/fig-builder.md](references/fig-builder.md) for the mid-script inspection pattern.\n- **Things `$fig` genuinely doesn't expose:** `node.setRangeFontName(...)`, etc. — access via `planNode.node` (see [references/fig-builder.md](references/fig-builder.md)).\n\n## Critical Rules\n\n1. **Only use `$fig` for creating / bulk-editing nodes** (`$fig.autoLayout(...)`, `$fig.text(...)`, `$fig.query(...).set(...)`). Raw Plugin API is the fallback — use it only when `$fig` can't express the operation (intermediate node-state reads, non-SceneNode types like Variables). Library components are NOT a reason to leave `$fig`: `$fig.get(componentKey)` / `$fig.instance(componentSetKey, { props })` queue the library import and resolve the variant for you. See [references/fig-builder.md](references/fig-builder.md) and [references/critical-rules-deep.md](references/critical-rules-deep.md) for worked WRONG/RIGHT examples.\n\n2. **Do not use `findOne`, `findAll`, `findAllWithCriteria`, `findChildren`, `findChild` directly for node searching** They are more verbose, error-prone, and less efficient than `query()`.  Additionally, do not use recursion to search.\n   `frame.query('[boundVariables.*]')` filters nodes by non-empty bindings: `{ boundVariables: { width: alias } }` matches; `{ boundVariables: {} }` or `{ fills: [paint] }` does not. Selector `*` expands array elements or object values.\n\n3. **Keep automatic result reporting for pure `$fig` scripts.** The runtime auto-flushes and returns a `FigDoneResult` with created/updated node IDs. Use `await $fig.done()` before reading materialized state or deferred query results, and `return` any additional evidence needed. Include IDs for raw mutations in custom results. JS variables and plan handles do not survive between calls: pass returned IDs as string literals and resolve them again with `$fig.get`, `$fig.getVar`, or `$fig.getStyle`. Keep workflow state outside the Figma file.\n\n4. **Size construction calls for safe retry and validate from evidence.** Batch related creation and edits when failures remain recoverable; a complete section or page may be one call. Split for page-context changes, difficult partial recovery, or a targeted retry after failure—not merely to create validation checkpoints. Use returned IDs and relevant counts, names, or bounds as structural evidence; add a separate check only when evidence is missing or a relevant mutation invalidates it. Normally take one screenshot after composition and one after a visual fix. The latest passing screenshot is final; stop when requirements pass. For work spanning calls, the placeholder workflow below remains useful: populate or replace each placeholder and clear `placeholder` when finished.\n\n```js\n$fig.autoLayout({ name: 'Screen', layoutMode: 'VERTICAL', width: 390 }, [\n  $fig.autoLayout({ name: 'Header', layoutSizingHorizontal: 'FILL', placeholder: true }),\n  $fig.autoLayout({ name: 'Content', layoutSizingHorizontal: 'FILL', placeholder: true }),\n])\n```\n\n5. **Plain JS with top-level `await`.** Code is auto-wrapped in async. Do NOT wrap in `(async () => {})()`.\n\n6. **Use built-in utilities for literal colors.** `figma.util.solidPaint('#2563eb80')` creates a complete solid paint with opacity. For individual color fields, use `figma.util.rgb(...)` for `{r,g,b}` (solid paints; ignores alpha) and `figma.util.rgba(...)` for `{r,g,b,a}` (gradient stops/effects). Channels are 0–1; solid-paint opacity belongs outside `color`. The utilities are available in every call — no custom hex parser needed. Token-backed properties still take variable handles directly. See [references/critical-rules-deep.md](references/critical-rules-deep.md) for WRONG/RIGHT.\n\n7. **No `curl` / `wget` / `Read` of Figma URLs from `Bash`.** Figma file access ONLY via `use_figma` and `mcp__figma__*` tools. After `get_screenshot`, the image is inlined in the tool result — do NOT re-fetch or re-Read it.\n\n8. **Empty / unsupported responses are terminal.** Accept and move on — don't try alternative bypass paths.\n\n9. **Verify node-type before touching a property.** Only `FRAME / COMPONENT / COMPONENT_SET / INSTANCE / GROUP / SECTION / PAGE` have `.children`. `GROUP` has no `fills` / `strokes` / `cornerRadius`. `TEXT` has no `cornerRadius` / `padding*` / `layoutMode`. `layoutPositioning='ABSOLUTE'` needs parent with `layoutMode !== 'NONE'`. Check `'<prop>' in node` or grep [references/plugin-api-standalone.d.ts](references/plugin-api-standalone.d.ts). Full list in [references/critical-rules-deep.md](references/critical-rules-deep.md).\n\n10. **Reuse evidence while it remains valid.** Do not repeat metadata reads or screenshots when nothing relevant changed. Reinspect when a mutation, external change, or recovery requirement invalidates earlier evidence.\n\n11. **Stop once requirements pass.** Gather enough evidence to establish correctness; avoid redundant checks, but do not leave known defects unresolved to meet a call limit.\n\n12. **On any `use_figma` error, obey `safeToRetryWithoutCanvasRead`.** If `true`, correct the identified error and retry without adding a diagnostic canvas read. If `false`, read the canvas, determine what changed, then make changes. If the same API or property error occurs twice, inspect its definition and fix the root cause before retrying; do not keep shrinking batches or changing selectors around the same invalid mutation. A generic error message alone does not establish the cause or prove that nothing changed. See [validation-and-recovery.md](references/validation-and-recovery.md).\n\n13. **NEVER call `mcp__figma__get_design_context`. FORBIDDEN.** This tool requires a selection (no selection exists in this environment), so every call will fail. The error is not recoverable — calling it just burns a tool slot and forces a retry. For structured reads of the file, use `mcp__figma__get_metadata` (for top-level frame discovery) and `use_figma` with `$fig.query()` instead. **Never call `get_design_context` for any reason.**\n\n14. **≤3 codebase `Read` calls when the task references source code.** Beyond that, grep only. The 4th codebase Read is forbidden — write your `use_figma` script with what you have.\n\n15. **Must use auto-layout unless you have a compelling reason not to.** Create auto-layout frames with `$fig.autoLayout(...)` instead of absolutely-positioning nodes.  New auto-layout frames are created with both axes hugging content. Explicitly assign `layoutSizingHorizontal` or `layoutSizingVertical` to `'FILL'` for auto-layout children if you want them to fill the auto-layout container's counter axis.\n\n16. **Gradient paints need ALL fields:** `type`, `gradientStops`, `gradientTransform` (a `[[a,b,tx],[c,d,ty]]` matrix). Missing any throws validation error. See [references/critical-rules-deep.md](references/critical-rules-deep.md).\n\n17. **Discover available fonts, esp. for style variations.** Use `await figma.listAvailableFontsAsync()` to discover available fonts for `$fig.text({ fontName: ... })`.\n\n18. **Set variable `scopes` explicitly when creating variables.** The default `ALL_SCOPES` pollutes every property picker. Use specific scopes — `['FRAME_FILL', 'SHAPE_FILL']` for backgrounds, `['TEXT_FILL']` for text, `['GAP']` for spacing, `['CORNER_RADIUS']` for radii; primitives that shouldn't appear in pickers get `[]`. In `$fig`, pass `scopes` to `colorVar` / `numVar`; in the raw API, set `variable.scopes`. There is no `STROKE` scope (use `STROKE_COLOR` or `STROKE_FLOAT`), and variable names cannot contain `.` (`space/0-5`, not `space/0.5`); [references/fig-builder.md](references/fig-builder.md) lists every scope and naming rule. See [references/variable-patterns.md](references/variable-patterns.md).\n\n19. **Never read `componentPropertyDefinitions`, `componentProperties`, or `valuesByMode` across a collection.** Resolve specific node IDs first, then read the property bundle only for those IDs. Reading one resolved node is safe; mapping these getters over `findAll*` results, `children`, or `getLocalVariables*` is the single largest cause of oversized returns.\n\n20. **Broad reads return `id`, `name`, `type` and counts only.** Fetch details for selected IDs in later calls. Return each file-wide inventory — variables, text styles, effect styles, paint styles, components, pages — in its own call; do not combine them into one return.\n\n21. **When a read may be large, measure the serialized return before returning it.** Bytes, not array length: `.slice()` bounds row count but not per-item size. If over budget, narrow the ID set or split across calls. Never drop required IDs or silently truncate.\n\n### Bulk mutation of existing nodes (swap/update/replace)\n\nFor tasks like \"swap N icons\", \"update M colors\", \"replace K instances\":\n1. **DISCOVER + MUTATE** together when safe: use scoped `$fig.query()` and planned mutations; return coverage evidence when the automatic result is insufficient.\n2. **VERIFY** only what the mutation result does not establish. Check visual results when needed.\n3. **FIX** any remaining defects with targeted changes, then report once requirements pass.\n\nChoose call boundaries for recoverability, not a fixed call budget. On failure, follow Rule 12. See [validation-and-recovery.md](references/validation-and-recovery.md).\n\n## Node property gotchas\n\nDo not guess node properties or assume CSS-like properties. Accessing non-existent properties will throw `TypeError: node.foo: no such property 'foo' on TYPE node`. Each throw burns a retry. [plugin-api-standalone.index.md](references/plugin-api-standalone.index.md) contains the list of all symbols in the API. Use that file and grep the full API typings in [plugin-api-standalone.d.ts](references/plugin-api-standalone.d.ts) for the full definitions.\n\n- **Only `FRAME` / `COMPONENT` / `COMPONENT_SET` / `INSTANCE` / `GROUP` / `SECTION` / `PAGE` have `.children`.** `RECTANGLE`, `TEXT`, `ELLIPSE`, `POLYGON`, `STAR`, `VECTOR`, `LINE`, `SLICE`, `STICKY`, `SHAPE_WITH_TEXT`, `STAMP`, `CONNECTOR`, `TABLE`, `WIDGET`, `EMBED`, `MEDIA` do NOT. Check `'children' in node` before accessing a node's children.\n- **Narrow before accessing `characters` or `description`.** Use typed query selectors or a capability guard for text-capable nodes. Set component purpose/usage in `description` only on `COMPONENT` or `COMPONENT_SET`. Optional chaining does not protect unsupported property access.\n- **`GROUP` has NO `fills` / `strokes` / `cornerRadius`.** Apply paints/radii on the child shapes inside.\n- **Figma auto-layout != CSS flexbox.** There is no such thing as margin.\n- **`TEXT` DOES NOT HAVE container properties.** Text has font / size / decoration / fills. Do not use container properties like padding, layout mode, item spacing, etc.\n- **`INSTANCE` descendants are read-only for structural ops** — you cannot `appendChild` / `insertChild` into an instance child. Edit the source `COMPONENT` or detach first.\n- **Never use `primaryAxisSizingMode` or `counterAxisSizingMode` on a node. ** Use `layoutSizingHorizontal` or `layoutSizingVertical` with 'FIXED' | 'HUG' | 'FILL'. Use 'FILL' only when the parent has auto-layout.\n- **There is NO `instance.swapMainComponent(...)`.** Use `instance.setProperties({...})` with the component-property variant value, OR `$fig.query(...).set({props: {...}})`. There IS `instance.swapComponent(component)` (different method name).\n\n## References\n\n- [references/fig-builder.md](references/fig-builder.md) — full `$fig` API and worked patterns; start with the quick reference above\n- [references/critical-rules-deep.md](references/critical-rules-deep.md) — WRONG/RIGHT examples, full node-type pitfall list, bulk-mutation template, syntax-bug checklist\n- [references/gotchas.md](references/gotchas.md) — raw Plugin API edge cases\n- [references/plugin-api-standalone.d.ts](references/plugin-api-standalone.d.ts) — type definitions (grep, don't read whole)\n- [references/plugin-api-standalone.index.md](references/plugin-api-standalone.index.md) — API navigation\n- [references/common-patterns.md](references/common-patterns.md), [component-patterns.md](references/component-patterns.md), [variable-patterns.md](references/variable-patterns.md), [text-style-patterns.md](references/text-style-patterns.md), [effect-style-patterns.md](references/effect-style-patterns.md) — pattern playbooks\n- [references/working-with-design-systems/](references/working-with-design-systems/) — design system workflows\n- [references/validation-and-recovery.md](references/validation-and-recovery.md) — error recovery patterns\n"},"changes":[{"path":"/included_files","type":"changed","before":[{"relative_path":"references/api-reference.md","size_in_bytes":16595},{"relative_path":"references/common-patterns.md","size_in_bytes":14410},{"relative_path":"references/component-patterns.md","size_in_bytes":24172},{"relative_path":"references/effect-style-patterns.md","size_in_bytes":3215},{"relative_path":"references/gotchas.md","size_in_bytes":53636},{"relative_path":"references/plugin-api-patterns.md","size_in_bytes":16288},{"relative_path":"references/plugin-api-standalone.d.ts","size_in_bytes":403158},{"relative_path":"references/plugin-api-standalone.index.md","size_in_bytes":35296},{"relative_path":"references/text-style-patterns.md","size_in_bytes":6947},{"relative_path":"references/validation-and-recovery.md","size_in_bytes":3973},{"relative_path":"references/variable-patterns.md","size_in_bytes":14663},{"relative_path":"references/working-with-design-systems/wwds-components--creating.md","size_in_bytes":2199},{"relative_path":"references/working-with-design-systems/wwds-components--using.md","size_in_bytes":2608},{"relative_path":"references/working-with-design-systems/wwds-components.md","size_in_bytes":4402},{"relative_path":"references/working-with-design-systems/wwds-effect-styles.md","size_in_bytes":3649},{"relative_path":"references/working-with-design-systems/wwds-text-styles.md","size_in_bytes":5519},{"relative_path":"references/working-with-design-systems/wwds-variables--creating.md","size_in_bytes":1559},{"relative_path":"references/working-with-design-systems/wwds-variables--using.md","size_in_bytes":2273},{"relative_path":"references/working-with-design-systems/wwds-variables.md","size_in_bytes":5183},{"relative_path":"references/working-with-design-systems/wwds.md","size_in_bytes":5220}],"after":[{"relative_path":"references/api-reference.md","size_in_bytes":16608},{"relative_path":"references/common-patterns.md","size_in_bytes":12359},{"relative_path":"references/component-patterns.md","size_in_bytes":26483},{"relative_path":"references/critical-rules-deep.md","size_in_bytes":11775},{"relative_path":"references/effect-style-patterns.md","size_in_bytes":2574},{"relative_path":"references/fig-builder.md","size_in_bytes":39843},{"relative_path":"references/gotchas.md","size_in_bytes":53636},{"relative_path":"references/plugin-api-standalone.d.ts","size_in_bytes":443167},{"relative_path":"references/plugin-api-standalone.index.md","size_in_bytes":40482},{"relative_path":"references/text-style-patterns.md","size_in_bytes":5914},{"relative_path":"references/validation-and-recovery.md","size_in_bytes":3973},{"relative_path":"references/variable-patterns.md","size_in_bytes":14937},{"relative_path":"references/working-with-design-systems/wwds-components--creating.md","size_in_bytes":2199},{"relative_path":"references/working-with-design-systems/wwds-components--using.md","size_in_bytes":3170},{"relative_path":"references/working-with-design-systems/wwds-components.md","size_in_bytes":4402},{"relative_path":"references/working-with-design-systems/wwds-effect-styles.md","size_in_bytes":3649},{"relative_path":"references/working-with-design-systems/wwds-text-styles.md","size_in_bytes":5519},{"relative_path":"references/working-with-design-systems/wwds-variables--creating.md","size_in_bytes":1559},{"relative_path":"references/working-with-design-systems/wwds-variables--using.md","size_in_bytes":2273},{"relative_path":"references/working-with-design-systems/wwds-variables.md","size_in_bytes":5183},{"relative_path":"references/working-with-design-systems/wwds.md","size_in_bytes":5220}]},{"path":"/skill_md_contents","type":"changed","before":"---\nname: figma-use\ndescription: \"**MANDATORY prerequisite** — you MUST invoke this skill BEFORE every `use_figma` tool call. NEVER call `use_figma` directly without loading this skill first. Skipping it causes common, hard-to-debug failures. Trigger whenever the user wants to perform a write action or a unique read action that requires JavaScript execution in the Figma file context — e.g. create/edit/delete nodes, set up variables or tokens, build components and variants, modify auto-layout or fills, bind variables to properties, or inspect file structure programmatically.\"\ndisable-model-invocation: false\n---\n# use_figma — Figma Plugin API Skill\nUse the `use_figma` tool to execute JavaScript in Figma files via the Plugin API. All detailed reference docs live in `references/`.\n\nWhen available, call `create_session` with `fileKey` and `description` before file reads or edits (create the file first if needed), then pass the returned `sessionId` unchanged to every call that accepts it, including follow-ups and work across files.\n\n**Always include `figma-use` in the comma-separated `skillNames` parameter when calling `use_figma`. If this skill was loaded via an MCP resource, you MUST prefix the name with `resource:` (e.g. `resource:figma-use`).** This is a logging parameter used to track skill usage — it does not affect execution.\n\n**If Figma MCP tools appear as deferred tools, batch-load all their schemas in a single `ToolSearch` call** using the `select:` syntax — e.g. `ToolSearch query=\"select:use_figma,get_screenshot,get_metadata,create_new_file\"`. One round trip beats six.\n\n**MANDATORY for visible design changes:** Before the first mutating `use_figma` call, load [figma-generate-design](../figma-generate-design/SKILL.md) alongside this skill and include both names in every mutating call’s `skillNames`. This applies from a single visible property or element to a full page, screen, or composed multi-section view—even when the user calls that view a component. `figma-use` provides the Plugin API rules; `figma-generate-design` provides design-system discovery through `search_design_system`, asset importing, and incremental assembly.\n\n**Reusable library exception:** If the primary deliverable is a reusable component, component set, variant system, variable/token collection, style foundation, or other library asset intended for reuse or publication, load [figma-generate-library](../figma-generate-library/SKILL.md) instead. It provides the component-creation workflow—variable foundations, variant sets, and design-token bindings—that `figma-use` alone does not cover. For tasks that include both library assets and a composed design that uses them, load both companion skills. Read-only `use_figma` calls need neither.\n\n**3D transforms:** For perspective, depth, X/Y tilt, isometric cubes, or other static 3D poses, load [figma-3d-transforms](../figma-3d-transforms/SKILL.md) when available. It owns the gated `transform3d`, `scene3d`, and `transformOrigin` API guidance, including fields that may be absent from the general typings. Follow this skill's node-creation rules, then apply the 3D poses to the resulting nodes. If the 3D skill or APIs are unavailable, explain that 3D authoring is not enabled in this session. Flat in-plane rotation uses `node.rotation` and does not need the 3D skill.\n\nFor other APIs, load [plugin-api-standalone.index.md](references/plugin-api-standalone.index.md) to understand what is possible. When you are asked to write plugin API code, use this context to grep [plugin-api-standalone.d.ts](references/plugin-api-standalone.d.ts) for relevant types, methods, and properties. This is the definitive source of truth for the general API surface. It is a large typings file, so do not load it all at once, grep for relevant sections as needed.\n\nIMPORTANT: Whenever you work with design systems, start with [working-with-design-systems/wwds.md](references/working-with-design-systems/wwds.md) to understand the key concepts, processes, and guidelines for working with design systems in Figma. Then load the more specific references for components, variables, text styles, and effect styles as needed.\n\n## 1. Critical Rules\n1.  **Use `return` to send data back.** The return value is JSON-serialized automatically (objects, arrays, strings, numbers). Do NOT call `figma.closePlugin()` or wrap code in an async IIFE — this is handled for you.\n2.  **Write plain JavaScript with top-level `await` and `return`.** Code is automatically wrapped in an async context. Do NOT wrap in `(async () => { ... })()`.\n3.  `figma.notify()` **throws \"not implemented\"** — never use it\n3a. **Return node IDs and keep workflow state outside the Figma file.** Set human-readable component purpose and usage in `node.description` only on a `COMPONENT` or `COMPONENT_SET` — never on a frame or instance.\n3b. **Narrow before accessing type-specific properties.** Check `node.type`, use a capability guard such as `\"characters\" in node`, or prefilter with `findAllWithCriteria`. `characters` requires a text-capable node; optional chaining does not protect unsupported property access.\n4.  `console.log()` is NOT returned — use `return` for output\n5.  **Size construction calls for safe retry and validate from evidence.** Do not split a working operation solely to create validation checkpoints. Batch related work when the resulting script remains safe to retry; a complete section or page may be built in one call. Split when crossing page context, when partial execution would be difficult to recover, or after an actual failure requires a targeted retry. Return affected IDs and relevant counts, names, or bounds from each write—this counts as structural validation. Run a separate structural check only when required evidence is missing or after a relevant mutation. Normally take one screenshot after composition and one after a visual fix. The most recent passing screenshot is the final check; do not repeat it when nothing relevant changed. Stop once requirements pass.\n6.  Colors are **0–1 range** (not 0–255): `{r: 1, g: 0, b: 0}` = red. Paint `color` objects use `{r, g, b}` **only — no `a` field**; opacity goes at the paint level (`{ type: 'SOLID', color: {...}, opacity: 0.5 }`).\n7.  Fills/strokes are **read-only arrays** — clone, modify, reassign\n8.  **Every text edit follows the canonical recipe: load font → `await` → mutate → return affected node IDs.** Skipping the load throws `Cannot write to node with unloaded font \"<family> <style>\"`. The rule covers more than `characters` — it applies to any operation on nodes with unloaded fonts (`appendChild`, `insertChild`, `setBoundVariable`, `setExplicitVariableModeForCollection`, `setValueForMode`, `findAll` callbacks touching text). When mutating existing text, load the node's *current* fonts via `getStyledTextSegments(['fontName'])`, not a hardcoded default. Inter is preloaded in most environments so other families surface this bug more often — the recipe is the same for every font. Use `await figma.listAvailableFontsAsync()` first if the style string is unverified — **never guess** (`\"SemiBold\"` vs `\"Semi Bold\"` is a common footgun). For `FONT_FAMILY`-scoped variables, load every value across every relevant mode before `setBoundVariable(\"fontFamily\", …)`, `setValueForMode`, or `setExplicitVariableModeForCollection`. `lineHeight`/`letterSpacing` take `{unit, value}`, not bare numbers. See [Canonical text-edit recipe](references/gotchas.md#canonical-text-edit-recipe-font-load--await--mutate--return-ids).\n9.  **Pages load incrementally** — use `await figma.setCurrentPageAsync(page)` to switch pages and load their content. The sync setter `figma.currentPage = page` does **NOT** work and throws `\"Setting figma.currentPage is not supported\"`. Page context resets to the **first page** at the start of every `use_figma` call, so re-switch each call; switch **at most once per call** and fan multi-page work out in parallel — see [Page Rules](#2-page-rules-critical) and [gotchas.md](references/gotchas.md#set-current-page-once-per-use_figma-call--split-multi-page-work-into-parallel-calls).\n10. `setBoundVariableForPaint` returns a **NEW** paint — must capture and reassign\n11. `createVariable` accepts collection **object or ID string** (object preferred)\n12. **`layoutSizingHorizontal/Vertical` is value-restricted by structural context — `FIXED` always works, `HUG` and `FILL` do not.** `'HUG'` is valid only on an auto-layout frame itself OR on a **TEXT** child of one. `'FILL'` is valid only on a child of an auto-layout frame that is also not absolute-positioned, not inside an immutable frame, and not a canvas-grid child. Practical consequence: append to an auto-layout parent FIRST, then set `HUG`/`FILL` — a newly-created or unparented node can't satisfy the rule yet. The property itself exists on every `SceneNode`; the error is value-rejection, not \"no such property\". See [Gotchas](references/gotchas.md#layoutsizinghorizontallayoutsizingvertical-value-rules-fixed-hug-fill).\n12a. **Use auto-layout for containers that hold related children.** When children have a structural relationship — stacked, side-by-side, aligned, gapped, hugged — wrap them in `figma.createAutoLayout()`, not `figma.createFrame()` with absolute `x`/`y`. Absolute coordinates govern where a container sits on the canvas; auto-layout governs how its children relate inside it. Skipping the container leaves no protection against text reflow, content changes, or overlap.\n12b. **`layoutSizing*` and `*AxisSizingMode` are different enums — don't cross them.** `layoutSizingHorizontal`/`layoutSizingVertical` (set on a **child**) take `'FIXED'|'HUG'|'FILL'`; `primaryAxisSizingMode`/`counterAxisSizingMode` (set on the **frame** itself) take `'FIXED'|'AUTO'`. So `layoutSizingVertical = 'AUTO'` is invalid (use `'HUG'`), and `counterAxisSizingMode = 'FILL'` throws `Expected 'FIXED' | 'AUTO', received 'FILL'` (use `'FIXED'`/`'AUTO'`). Two more errors from the same setter — `Error: in set_layoutSizingHorizontal: node must be an auto-layout frame or a child of an auto-layout frame` and `Error: in set_layoutSizingHorizontal: FILL can only be set on children of auto-layout frames` — mean the node isn't in an auto-layout context yet; **recommendation: make the parent auto-layout (`figma.createAutoLayout()`) and `appendChild` the node before setting** (see Rule 12). See [Gotchas](references/gotchas.md#layoutsizing-vs-axissizingmode-two-different-sizing-enums).\n12c. **`resize()` resets sizing modes to `FIXED`, so call it BEFORE setting `layoutSizing*`.** A wrapping **TEXT** block needs `textAutoResize = 'HEIGHT'` plus an explicit FIXED width (`resize()`), NOT `FILL` alone — the default `WIDTH_AND_HEIGHT` mode ignores `FILL` and collapses the node to a near-zero-width thread. Verify `node.width > 0` afterward.\n13. **Position new top-level nodes away from (0,0).** Nodes appended directly to the page default to (0,0). Scan `figma.currentPage.children` to find a clear position (e.g., to the right of the rightmost node). This only applies to page-level nodes — nodes nested inside other frames or auto-layout containers are positioned by their parent. See [Gotchas](references/gotchas.md).\n14. **On `use_figma` error, obey `safeToRetryWithoutCanvasRead`.** If `true`, fix the error and retry. If `false`, read the canvas, determine what changed, then make changes. See [Error Recovery](#7-error-recovery--self-correction).\n15. **MUST `return` ALL created/mutated node IDs.** Whenever a script creates new nodes or mutates existing ones on the canvas, collect every affected node ID and return them in a structured object (e.g. `return { createdNodeIds: [...], mutatedNodeIds: [...] }`). This is essential for subsequent calls to reference, validate, or clean up those nodes. No state persists across `use_figma` calls, so pass IDs from previous calls as **string literals**, not variables. See [common-patterns.md](references/common-patterns.md) for worked multi-step examples.\n16. **Always set `variable.scopes` explicitly when creating variables.** The default `ALL_SCOPES` pollutes every property picker — almost never what you want. Use specific scopes like `[\"FRAME_FILL\", \"SHAPE_FILL\"]` for backgrounds, `[\"TEXT_FILL\"]` for text colors, `[\"GAP\"]` for spacing, etc. See [variable-patterns.md](references/variable-patterns.md) for the full list.\n17. **`await` every Promise.** Never leave a Promise unawaited — unawaited async calls (e.g. `figma.loadFontAsync(...)` without `await`, or `figma.setCurrentPageAsync(page)` without `await`) will fire-and-forget, causing silent failures or race conditions. The script may return before the async operation completes, leading to missing data or half-applied changes.\n18. **Never read `componentPropertyDefinitions` from a variant component.** Narrow the owner first: use the node itself when it is a `COMPONENT_SET`, use a `COMPONENT` only when its parent is not a `COMPONENT_SET`, and otherwise promote a variant `COMPONENT` to its parent set. Optional chaining does not make the getter safe. See [Component-property owner narrowing](references/component-patterns.md#component-property-owner-narrowing).\n19. **Never read `componentPropertyDefinitions`, `componentProperties`, or `valuesByMode` across a collection.** Resolve specific node IDs first, then read the property bundle only for those IDs. Reading one resolved node is safe; mapping these getters over `findAll*` results, `children`, or `getLocalVariables*` is the single largest cause of oversized returns.\n20. **Broad reads return `id`, `name`, `type` and counts only.** Fetch details for selected IDs in later calls. Return each file-wide inventory — variables, text styles, effect styles, paint styles, components, pages — in its own call; do not combine them into one return.\n21. **When a read may be large, measure the serialized return before returning it.** Bytes, not array length: `.slice()` bounds row count but not per-item size. If over budget, narrow the ID set or split across calls. Never drop required IDs or silently truncate.\n> For detailed WRONG/CORRECT examples of each rule, see [Gotchas & Common Mistakes](references/gotchas.md).\n\n## 2. Page Rules (Critical)\n\nThe async-only setter and the per-call context reset are covered in Rule 9. This section elaborates the one rule that needs a worked example: **switch pages at most once per script, and fan multi-page work out in parallel.**\n\nNever loop over `figma.root.children` and switch pages inside the loop — each switch reloads the file. If the work spans multiple pages, **split it into N `use_figma` calls (one per target page) and emit them in parallel** — a single assistant message containing N `use_figma` tool-use blocks. The harness runs them concurrently; each script sets `currentPage` exactly once.\n\n> **Explicit instruction:** when fanning out, you MUST issue the N tool calls in **one message**. Do not send them across multiple turns. Do not await one before issuing the next. Sequential per-page calls waste the entire benefit of splitting.\n\n```js\n// AVOID — switches pages N times in one script, reloads the file each time\nfor (const page of figma.root.children) {\n  await figma.setCurrentPageAsync(page);\n  // ... touch this page ...\n}\n\n// PREFER — read-only discovery call to get page IDs, then in the NEXT message\n// emit N parallel use_figma tool calls (one per page), each setting currentPage once.\n```\n\nDefault to parallel fan-out for any multi-page work — reads and writes alike. You can also call `use_figma` multiple times to build incrementally (e.g. `return` metadata about existing nodes, then modify them in a subsequent script). See [gotchas.md → Set current page once per `use_figma` call](references/gotchas.md#set-current-page-once-per-use_figma-call--split-multi-page-work-into-parallel-calls) for the full rationale.\n\n## 3. `return` Is Your Output Channel\n\nThe agent sees **ONLY** the value you `return` — `console.log()` is invisible (Rule 4), and thrown errors are auto-captured (let them propagate or `throw` explicitly). The hard requirement is Rule 15: every script that creates or mutates canvas nodes **MUST** return all affected node IDs plus any actionable status in a structured object — e.g. `return { createdNodeIds: [...], mutatedNodeIds: [...], count: 5, errors: [] }` — so subsequent calls can reference, validate, or clean them up.\n\n## 4. Editor Mode\n\n`use_figma` works in **design mode** (editorType `\"figma\"`, the default). FigJam (`\"figjam\"`) and Slides (`\"slides\"`) have different sets of available node types — most design nodes are blocked in FigJam, and FigJam-only nodes are blocked in Slides.\n\n**Tell the editor from the URL:** Design = `figma.com/design/...`, FigJam = `figma.com/board/...`, Slides = `figma.com/slides/...`. Confirm before assuming an API is available.\n\nAvailable in design mode: Rectangle, Frame, Component, Text, Ellipse, Star, Line, Vector, Polygon, BooleanOperation, Slice, Page, Section, TextPath.\n\n**Blocked** in design mode: Sticky, Connector, ShapeWithText, CodeBlock, Slide, SlideRow, SlideGrid, InteractiveSlideElement, Webpage.\n\nAvailable in Slides mode: Rectangle, Frame, Component, Text, Ellipse, Star, Line, Vector, Polygon, BooleanOperation, Slice, Section, TextPath, Slide, SlideRow, SlideGrid, InteractiveSlideElement.\n\n**Blocked** in Slides mode: Sticky, Connector, ShapeWithText, CodeBlock, Webpage, Page.\n\n**Design-only APIs (not just node types):** `figma.createPage()` is available only in Design files (`figma.com/design/...`). In both FigJam (`figma.com/board/...`) and Slides (`figma.com/slides/...`) it throws `TypeError: figma.createPage no such property 'createPage' on the figma global object`. Do not emit `figma.createPage()` in FigJam or Slides workflows.\n\n> **Slides note:** There is no dedicated read tool for Slides files yet. Use `use_figma` with read-only scripts for inspection (see Section 6 \"Inspect first\" pattern), and `get_screenshot` / `await node.screenshot()` for visual context. For Slides-specific API guidance, load the [figma-use-slides](../figma-use-slides/SKILL.md) skill.\n\n## 5. Efficient APIs — Prefer These Over Verbose Alternatives\n\nThese APIs reduce boilerplate, eliminate ordering errors, and compress token output. **Always prefer them over the verbose alternatives.**\n\n### `node.query(selector)` — CSS-like node search\n\nFind nodes within a subtree using CSS-like selectors. Replaces verbose `findAll` + filter loops.\n\n```js\n// BEFORE — verbose traversal\nconst texts = frame.findAll(n => n.type === 'TEXT' && n.name === 'Title')\n\n// AFTER — one-liner with query\nconst texts = frame.query('TEXT[name=Title]')\n```\n\n**Selector syntax:**\n- Type: `FRAME`, `TEXT`, `RECTANGLE`, `ELLIPSE`, `COMPONENT`, `INSTANCE`, `SECTION` (case-insensitive)\n- Attribute exact: `[name=Card]`, `[visible=true]`, `[opacity=0.5]`\n- Attribute substring: `[name*=art]` (contains), `[name^=Header]` (starts-with), `[name$=Nav]` (ends-with)\n- Dot-path traversal: `[fills.0.type=SOLID]`, `[fills.*.type=SOLID]` (wildcard index)\n- Instance matching: `[mainComponent=nodeId]`, `[mainComponent.name=Button]`\n- Combinators: `FRAME > TEXT` (direct child), `FRAME TEXT` (any descendant), `A + B` (adjacent sibling), `A ~ B` (general sibling)\n- Pseudo-classes: `:first-child`, `:last-child`, `:nth-child(2)`, `:not(TYPE)`, `:is(FRAME, RECTANGLE)`, `:where(TEXT, ELLIPSE)`\n- Node ID: `#nodeId` or bare GUID\n- Comma: `TEXT, RECTANGLE` (union)\n- Wildcard: `*` (any type)\n\n**QueryResult methods:**\n| Method | Description |\n|---|---|\n| `.length` | Number of matched nodes |\n| `.first()` | First matched node (or `null`) |\n| `.last()` | Last matched node (or `null`) |\n| `.toArray()` | Convert to regular array |\n| `.each(fn)` | Iterate with callback, returns `this` for chaining |\n| `.map(fn)` | Map to new array |\n| `.filter(fn)` | Filter to new QueryResult |\n| `.values(keys)` | Extract property values: `.values(['name', 'x', 'y'])` → `[{name, x, y}, ...]` |\n| `.set(props)` | Set properties on all matched nodes (see `node.set()` below) |\n| `.query(selector)` | Sub-query within matched nodes |\n| `for...of` | Iterable — works in `for` loops |\n\n**Scope:** `node.query()` searches within that node's subtree. To search the whole page: `figma.currentPage.query('...')`. There is no global `figma.query()`.\n\n**Examples:**\n```js\n// Recolor all text inside cards\nfigma.currentPage.query('FRAME[name^=Card] TEXT').set({\n  fills: [{type: 'SOLID', color: {r: 0.2, g: 0.2, b: 0.8}}]\n})\n\n// Get names and positions of all frames\nreturn figma.currentPage.query('FRAME').values(['name', 'x', 'y'])\n\n// Find the first component named \"Button\"\nconst btn = figma.currentPage.query('COMPONENT[name=Button]').first()\n\n// Find all instances of a specific component\nfigma.currentPage.query(`INSTANCE[mainComponent=${compId}]`)\n\n// Find nodes with solid fills using dot-path traversal\nfigma.currentPage.query('[fills.0.type=SOLID]')\n```\n\n### `node.set(props)` — batch property updates\n\nSet multiple properties in one call. Returns `this` for chaining.\n\n```js\n// BEFORE — one line per property\nframe.opacity = 0.5\nframe.cornerRadius = 8\nframe.name = \"Card\"\n\n// AFTER — single call\nframe.set({ opacity: 0.5, cornerRadius: 8, name: \"Card\" })\n```\n\n**Priority key ordering:** `layoutMode` is always applied before other properties (like `width`/`height`) regardless of object key order. This prevents the common bug where `resize()` behaves differently depending on whether `layoutMode` is set.\n\n**Width/height handling:** `width` and `height` are routed through `node.resize()` automatically — setting `{ width: 200 }` calls `resize(200, currentHeight)`.\n\n**Chaining with query:**\n```js\n// Find all rectangles named \"Divider\" and update them\nfigma.currentPage.query('RECTANGLE[name=Divider]').set({\n  fills: [{type: 'SOLID', color: {r: 0.9, g: 0.9, b: 0.9}}],\n  cornerRadius: 2\n})\n```\n\n### `figma.createAutoLayout(direction?, props?)` — auto-layout frames\n\nCreates a frame with auto-layout already enabled and both axes hugging content. **This is the default container whenever children have a structural relationship to each other (see Rule 12a).**\n\n```js\n// BEFORE — manual setup, easy to get ordering wrong\nconst frame = figma.createFrame()\nframe.layoutMode = 'VERTICAL'\nframe.primaryAxisSizingMode = 'AUTO'\nframe.counterAxisSizingMode = 'AUTO'\nframe.layoutSizingHorizontal = 'HUG'\nframe.layoutSizingVertical = 'HUG'\n\n// AFTER — one call, layout ready\nconst frame = figma.createAutoLayout('VERTICAL')\n```\n\nChildren can immediately use `layoutSizingHorizontal/Vertical = 'FILL'` after being appended — no need to set sizing modes manually.\n\nAccepts an optional props object as the first or second argument:\n```js\nfigma.createAutoLayout({ name: 'Card', itemSpacing: 12 })               // HORIZONTAL + props\nfigma.createAutoLayout('VERTICAL', { name: 'Column', itemSpacing: 8 })  // VERTICAL + props\n```\n\n### `node.placeholder` — shimmer overlay for AI-in-progress feedback\n\nSets a visual shimmer overlay on a node indicating work is in progress. **Always remove the shimmer when done** — leftover shimmers confuse users and indicate incomplete work.\n\n```js\n// Mark as in-progress\nframe.placeholder = true\n\n// ... build out the content ...\n\n// MUST remove when done — never leave shimmers on finished nodes\nframe.placeholder = false\n```\n\nWhen building complex layouts, set `placeholder = true` on sections before populating them, then set `placeholder = false` on each section as it's completed.\n\n### `await node.screenshot(opts?)` — inline screenshots\n\nCapture a node as a PNG and return it inline in the response. Eliminates the need for a separate `get_screenshot` call.\n\n```js\n// Take a screenshot of a frame (returned inline in the tool response)\nawait frame.screenshot()\n\n// Custom scale (default auto-scales: 0.5x or capped so max dimension ≤ 1024px)\nawait frame.screenshot({ scale: 2 })\n\n// Include overlapping content from sibling nodes\nawait frame.screenshot({ contentsOnly: false })\n```\n\n**When to use:** Follow Rule 5. Take a composition screenshot when visual evidence is needed. If a visual fix follows, take one post-fix screenshot; that passing screenshot is final. Do not take an additional unchanged “final” screenshot.\n\n**Auto-naming:** The image caption includes node metadata — `\"Card (300x150 at 0,60).png\"` — giving spatial context without parsing the image.\n\n**Default scaling:** Uses 0.5x scale, but automatically caps so the largest output dimension never exceeds 1024px. Explicit `{ scale: N }` bypasses the cap.\n\n## 6. Incremental Workflow (How to Avoid Bugs)\n\nThe most common causes of waste are unnecessary fragmentation, redundant validation, and scripts that cannot be retried safely. **Use Rule 5's safe-retry and evidence-based validation contract.**\n\n### Key rules\n\n- **Choose call boundaries for recoverability, not validation cadence.** Batch related creation, property updates, parenting, and targeted diagnostics when safe. A complete page may be one call; do not split it into header/content/footer calls merely to validate each section. **Slides override:** in Slides files, slides are isolated subtrees — the relevant limit is complexity per slide, not total nodes across slides. Building 3–5 new slides in one call is safe, and so is applying the same edit (e.g. adding a footer, recoloring a heading) across every slide in the deck in a single call. See [figma-use-slides](../figma-use-slides/SKILL.md) for the deck-building workflow.\n- **Build top-down, starting with placeholders.** Create the outer structure first with `placeholder = true` on each section, then incrementally replace placeholders with real content in subsequent calls.\n\n### The pattern\n\n1. **Inspect first.** Before creating anything, run a read-only `use_figma` to discover what already exists in the file — pages, components, variables, naming conventions. Match what's there.\n2. **Build the skeleton.** Create the top-level structure with placeholder sections. Set `placeholder = true` on each section so the user sees progress.\n3. **Fill in content in retry-safe batches.** Multiple related sections may be populated together when the operation remains safe to retry. Set each section's `placeholder = false` when done.\n4. **Return IDs from every call** (Rule 15) — you'll need created node/variable/collection IDs as inputs to subsequent calls.\n5. **Return validation evidence from writes.** Return IDs and the relevant counts, names, hierarchy, or bounds. Add a separate audit only for missing evidence or after a mutation invalidates earlier evidence. Follow Rule 5 for visual checks.\n6. **Fix before moving on.** If validation reveals a problem, fix it before proceeding to the next step. Don't build on a broken foundation.\n\n### Suggested step order for complex tasks\n\n```\nStep 1: Inspect file — discover existing pages, components, variables, conventions\nStep 2: Create tokens/variables (if needed)\n       → return collection, variable, and mode counts\nStep 3: Create individual components\n       → return component IDs and relevant child/variant counts\nStep 4: Compose layouts from component instances\n       → return layout IDs/bounds + take a composition screenshot\nStep 5: Apply a targeted visual fix only if needed\n       → take one post-fix screenshot; this is final\nStep 6: Stop if nothing relevant changed\n```\n\n### What to validate at each step\n\n| After... | Check with `get_metadata` | Check with `get_screenshot` |\n|---|---|---|\n| Creating variables | Collection count, variable count, mode names | — |\n| Creating components | Child count, variant names, property definitions | Variants visible, not collapsed, grid readable |\n| Binding variables | Node properties reflect bindings | Colors/tokens resolved correctly |\n| Composing layouts | Instance nodes have mainComponent, hierarchy correct | No cropped/clipped text, no overlapping elements, correct spacing |\n\n## 7. Error Recovery & Self-Correction\n\nOn any `use_figma` error, obey `safeToRetryWithoutCanvasRead` (Rule 14): `true` → correct the identified error and retry without adding a diagnostic canvas read; `false` → read the canvas, determine what changed, then make changes. If the same API or property error occurs twice, inspect its definition once and fix the root cause before retrying; do not continue decomposing the operation around the same invalid mutation. Errors whose fix is already a Critical Rule are diagnosed there — `\"not implemented\"` (`figma.notify`, Rule 3), the `layoutSizing*` HUG/FILL rejections (Rules 12, 12b), `\"Setting figma.currentPage is not supported\"` (Rule 9), `componentPropertyDefinitions` on a variant (Rule 18), and `characters`/`description` on the wrong node type (Rules 3a, 3b). The rows below cover failures the contract doesn't name:\n\n| Error message | Likely cause | How to fix |\n|---|---|---|\n| Property value out of range | Color channel > 1 (used 0–255 instead of 0–1) | Divide by 255 |\n| `\"Cannot read properties of null\"` | Node doesn't exist (wrong ID, wrong page) | Check page context, verify ID |\n| Script hangs / no response | Infinite loop or unresolved promise | Check for `while(true)` or missing `await`; ensure code terminates |\n| `\"The node with id X does not exist\"` | Parent instance was implicitly detached by a child `detachInstance()`, changing IDs | Re-discover nodes by traversal from a stable (non-instance) parent frame |\n\n### When the script succeeds but the result looks wrong\n\nCall `get_metadata` for structural correctness (hierarchy, counts, positions) and `get_screenshot` for visual correctness — look closely for cropped/clipped text (line heights cutting off content) and overlapping elements, which are common and easy to miss. Identify whether the discrepancy is structural or visual, then write a **targeted** fix script that modifies only the broken parts — don't recreate everything.\n\n> For the full validation workflow, see [Validation & Error Recovery](references/validation-and-recovery.md).\n\n## 8. Pre-Flight Checklist\nBefore submitting ANY `use_figma` call, re-read the script against the operating contract in [Section 1](#1-critical-rules). Every gate that used to be enumerated here now lives there — a script that violates any of these is not ready to submit:\n\n- [ ] **Output** — uses `return` (not `figma.closePlugin()`), not wrapped in an async IIFE, no `console.log()` as output; `return`s structured data with ALL created/mutated node IDs (Rules 1, 2, 4, 15)\n- [ ] **Color & fills** — 0–1 range; paint `color` is `{r, g, b}` only (no `a`); fills/strokes reassigned as new arrays (Rules 6, 7)\n- [ ] **Type narrowing** — `characters`, `description`, and `componentPropertyDefinitions` guarded/narrowed before access (Rules 3a, 3b, 18)\n- [ ] **Pages** — switches use `await figma.setCurrentPageAsync(page)`, at most once per call (Rule 9)\n- [ ] **Layout & sizing** — related children in `figma.createAutoLayout()`; top-level nodes positioned away from (0,0); `HUG`/`FILL` set after `appendChild`; `resize()` before sizing modes; wrapping TEXT uses `textAutoResize='HEIGHT'` + FIXED width (Rules 12, 12a, 12b, 12c, 13)\n- [ ] **Text** — canonical font recipe with style names verified via `listAvailableFontsAsync()`; `lineHeight`/`letterSpacing` as `{unit, value}`; `FONT_FAMILY` variables load every mode's value first (Rule 8)\n- [ ] **Async & state** — every Promise `await`ed; multi-step IDs passed as string literals (Rules 15, 17)\n\n## 9. Discover Conventions Before Creating\n\n**Always inspect the Figma file before creating anything.** Different files use different naming conventions, variable structures, and component patterns. Your code should match what's already there, not impose new conventions.\n\nWhen in doubt about any convention (naming, scoping, structure), check the Figma file first, then the user's codebase. Only fall back to common patterns when neither exists.\n\n### Quick inspection scripts\n\n**List all pages and top-level nodes:**\n```js\nconst pages = figma.root.children.map(p => `${p.name} id=${p.id} children=${p.children.length}`);\nreturn pages.join('\\n');\n```\n\n**List existing components across all pages:**\n\n`search_design_system` is an option for published components. For on-canvas components, use the two-step fan-out — **don't loop pages inside one script.**\n\nStep 1: one read-only `use_figma` to get page IDs:\n```js\nreturn figma.root.children.map(p => ({ id: p.id, name: p.name }));\n```\n\nStep 2: in the **next assistant turn, emit one `use_figma` per page in parallel** (a single message containing N tool-use blocks). Each runs:\n```js\nconst page = await figma.getNodeByIdAsync(PAGE_ID);\nawait figma.setCurrentPageAsync(page);\n// findAllWithCriteria uses an indexed type lookup — hundreds of times faster\n// than the findAll(n => n.type === '…') side-effect-in-predicate antipattern.\nconst matches = page.findAllWithCriteria({ types: ['COMPONENT', 'COMPONENT_SET'] });\nreturn matches.map(n => ({ page: page.name, name: n.name, type: n.type, id: n.id }));\n```\n\n**List existing variable collections and their conventions:**\n```js\nconst collections = await figma.variables.getLocalVariableCollectionsAsync();\nconst results = collections.map(c => ({\n  name: c.name, id: c.id,\n  varCount: c.variableIds.length,\n  modes: c.modes.map(m => m.name)\n}));\nreturn results;\n```\n\n## 10. Reference Docs\n\nLoad these as needed based on what your task involves:\n\n| Doc | When to load | What it covers |\n|-----|-------------|----------------|\n| [gotchas.md](references/gotchas.md) | Before any `use_figma` | Every known pitfall with WRONG/CORRECT code examples — start with the [canonical text-edit recipe](references/gotchas.md#canonical-text-edit-recipe-font-load--await--mutate--return-ids) |\n| [common-patterns.md](references/common-patterns.md) | Need working code examples | Script scaffolds: shapes, text, auto-layout, variables, components, multi-step workflows |\n| [plugin-api-patterns.md](references/plugin-api-patterns.md) | Creating/editing nodes | Fills, strokes, Auto Layout, effects, grouping, cloning, styles |\n| [api-reference.md](references/api-reference.md) | Need exact API surface | Node creation, variables API, core properties, what works and what doesn't |\n| [validation-and-recovery.md](references/validation-and-recovery.md) | Multi-step writes or error recovery | `get_metadata` vs `get_screenshot` workflow, mandatory error recovery steps |\n| [component-patterns.md](references/component-patterns.md) | Creating components/variants | combineAsVariants, component properties, INSTANCE_SWAP, variant layout, discovering existing components, metadata traversal |\n| [variable-patterns.md](references/variable-patterns.md) | Creating/binding variables | Collections, modes, scopes, aliasing, binding patterns, discovering existing variables |\n| [text-style-patterns.md](references/text-style-patterns.md) | Creating/applying text styles | Type ramps, font discovery via `listAvailableFontsAsync`, listing styles, applying styles to nodes |\n| [effect-style-patterns.md](references/effect-style-patterns.md) | Creating/applying effect styles | Drop shadows, listing styles, applying styles to nodes |\n| [plugin-api-standalone.index.md](references/plugin-api-standalone.index.md) | Need to understand the full API surface | Index of all types, methods, and properties in the Plugin API |\n| [plugin-api-standalone.d.ts](references/plugin-api-standalone.d.ts) | Need exact type signatures | Full typings file — grep for specific symbols, don't load all at once |\n\n## 11. Snippet examples\n\nYou will see snippets throughout documentation here. These snippets contain useful plugin API code that can be repurposed. Use them as is, or as starter code as you go. If there are key concepts that are best documented as generic snippets, call them out and write to disk so you can reuse in the future.\n","after":"---\nname: figma-use\ndescription: \"**MANDATORY prerequisite** — you MUST invoke this skill BEFORE every `use_figma` tool call. NEVER call `use_figma` directly without loading this skill first. Skipping it causes common, hard-to-debug failures. Trigger whenever the user wants to perform a write action or a unique read action that requires JavaScript execution in the Figma file context — e.g. create/edit/delete nodes, set up variables or tokens, build components and variants, modify auto-layout or fills, bind variables to properties, or inspect file structure programmatically.\"\ndisable-model-invocation: false\n---\n# use_figma — Figma Plugin API Skill\nUse the `use_figma` tool to execute JavaScript in Figma files via the Plugin API. All detailed reference docs live in `references/`.\n\nWhen available, call `create_session` with `fileKey` and `description` before file reads or edits (create the file first if needed), then pass the returned `sessionId` unchanged to every call that accepts it, including follow-ups and work across files.\n\n**Always include `figma-use` in the comma-separated `skillNames` parameter when calling `use_figma`. If this skill was loaded via an MCP resource, you MUST prefix the name with `resource:` (e.g. `resource:figma-use`).** This is a logging parameter used to track skill usage — it does not affect execution.\n\n**If Figma MCP tools appear as deferred tools, batch-load all their schemas in a single `ToolSearch` call** using the `select:` syntax — e.g. `ToolSearch query=\"select:use_figma,get_screenshot,get_metadata,create_new_file\"`. One round trip beats six.\n\n**MANDATORY for visible design changes:** Before the first mutating `use_figma` call, load [figma-generate-design](../figma-generate-design/SKILL.md) alongside this skill and include both names in every mutating call’s `skillNames`. This applies from a single visible property or element to a full page, screen, or composed multi-section view—even when the user calls that view a component. `figma-use` provides the Plugin API rules; `figma-generate-design` provides design-system discovery through `search_design_system`, asset importing, and incremental assembly.\n\n**If the task involves creating or building a standalone component or a component library in Figma** (even a single component as the deliverable), also load [figma-generate-library](../figma-generate-library/SKILL.md). It owns the component-creation workflow — variable foundations first, variant sets, then design token bindings — that `figma-use` alone doesn't cover. Build the token/variable foundation before the component, then bind the component's `fills`/`cornerRadius`/spacing to those variables rather than inlining literals where a token exists. For components that exist to be reused **inside a screen you are building**, follow [figma-generate-design → componentization](../figma-generate-design/references/componentization.md) instead.\n\n**3D transforms:** For perspective, depth, X/Y tilt, isometric cubes, or other static 3D poses, load [figma-3d-transforms](../figma-3d-transforms/SKILL.md) when available. It owns the gated `transform3d`, `scene3d`, and `transformOrigin` API guidance, including fields that may be absent from the general typings. Follow this skill's node-creation rules, then apply the 3D poses to the resulting nodes. If the 3D skill or APIs are unavailable, explain that 3D authoring is not enabled in this session. Flat in-plane rotation uses `node.rotation` and does not need the 3D skill.\n\nFor other APIs, load [plugin-api-standalone.index.md](references/plugin-api-standalone.index.md) to understand what is possible. When you are asked to write plugin API code, use this context to grep [plugin-api-standalone.d.ts](references/plugin-api-standalone.d.ts) for relevant types, methods, and properties. This is the definitive source of truth for the general API surface. It is a large typings file, so do not load it all at once, grep for relevant sections as needed.\n\nIMPORTANT: Whenever you work with design systems, start with [working-with-design-systems/wwds.md](references/working-with-design-systems/wwds.md) to understand the key concepts, processes, and guidelines for working with design systems in Figma. Then load the more specific references for components, variables, text styles, and effect styles as needed.\n\n## $fig — the plan-based builder API (ALL NODE CREATION MUST USE THIS)\n\n`$fig` is a global that is responsible for all node creation. It auto-flushes at script end (no `$fig.done()` needed), handles font preloading, batches mutations, and orders property assignment correctly. **Use it for all node creation and mutation operations.** Never use `figma.createFrame()`, `figma.createText()` or any `figma.create*` methods. They do not exist in this environment.\n\n**Constructors queue creation, not inert templates.** Every `$fig` node constructor like `$fig.frame(...)` queues a node creation in the plan, even if its returned plan node is never used, returned, or screenshotted. Unattached nodes become top-level nodes at flush. Plan nodes meant to be used as children should be appended or used in `$fig.frame(opts, children)` **before flushing**.\n\n**layoutSizingHorizontal/Vertical = 'FILL' is for auto-layout children only.** Do not set FILL for top-level nodes.\n\n### Plan nodes vs real nodes\n\n`$fig.component(...)`, `$fig.variants(...)`, `$fig.instance(...)`, `$fig.get(...)`, and `$fig.frame(...)` return **plan nodes**, not raw Plugin API nodes. `await $fig.done()` materializes the plan nodes and makes `planNode.node` available for accessing real nodes. Do not use plan nodes like real nodes.\n\n- Use `planNode.set({ name, x, y })` and `planNode.append(childPlanNode)` for queued mutations. Do not make direct assignments like `planNode.x = 100`. Do not mix plan nodes into raw plugin APIs like `node.appendChild(planNode)`.\n- Prefer `$fig.instance(componentPlanNode, opts)` or `planNode.instance(componentPlanNode, opts)` to create instances of plan component nodes, with no intermediate flush.\n- Use `planNode.node` only when you need raw state or an operation `$fig` or plan nodes do not expose. Flush pending changes first. Do not mix raw plugin code amongst pending changes.\n\n### `$fig` quick reference\n\nThis is the full `$fig` surface. Open [references/fig-builder.md](references/fig-builder.md) for worked details: gridding variant sets, style handle semantics, variable aliasing, query screenshots, and mid-script materialization.\n\n| Need | Call |\n|---|---|\n| Create nodes | `$fig.autoLayout(opts, children?)` (hugs both axes; default `HORIZONTAL`), `$fig.frame`, `$fig.text({ characters, fontName, fontSize, fills })`, `$fig.rectangle`, `$fig.ellipse`, `$fig.polygon`, `$fig.star`, `$fig.line`, `$fig.vector`, `$fig.section`, `$fig.page`: all `(opts?, children?)` |\n| Create from SVG | `$fig.svg(svgString, opts?)` builds a vector node tree; `$fig.svgComponent(svgString, opts?)` builds it as a main component (icons). |\n| Group and boolean | `$fig.group`, `$fig.union`, `$fig.subtract`, `$fig.intersect`, `$fig.exclude`: all `(opts?, children?)` |\n| Add children | `parent.append(a, b)`, `parent.addAt(index, child)`, or call a constructor on the plan node: `card.text({ ... })` |\n| Components | `$fig.component(opts, children)`; variant set: `$fig.variants({ name }, [$fig.component({ name: 'State=Default' }, [...]), ...])`. Variants stack at (0,0), so grid them afterward (fig-builder.md). |\n| Component properties | On a layer inside the component: `.textProp('Label')`, `.booleanProp('Show Icon')`, `.instanceSwapProp('Icon')`, `.slotProp('Content')` (on a descendant frame) |\n| Instances | `$fig.instance(compRef, { props: { Label: 'Save', State: 'Hover' } })`, where `compRef` is a component plan node, a node ID, or a library `componentKey` / `componentSetKey` (import is queued); existing instance: `$fig.get(id).set({ props: { ... } })` |\n| Existing nodes | `$fig.get(idOrLibraryKey)`; `$fig.query(selector, scope?)` with CSS-like selectors (`'FRAME[name*=Card] TEXT'`) |\n| Query results | `length`, `first()`, `last()`, `at(i)`, `find(fn)`, `filter(fn)`, `slice(start, end?)`, `query(selector)`, `each(fn)` / `forEach(fn)`, `map(fn)`, `values(paths)`, `toArray()`, `set(props)`, `moveTo(parent, index?)`, `replace(newNode)`, `remove()`, `screenshot(opts?)` |\n| Edit, move, delete | Plan node: `.set(props)`, `.replace(newNode)`, `.moveTo(parent, index?)`, `.clone(props?)`, `.remove()`, `.reorderChildren(children)`, `.gradient(type, stops, transform?)`, `.image(hash, scaleMode?)`. Global: `$fig.set(target, props)`, `$fig.delete(...nodes)`, `$fig.move(target, parent, index?)`, `$fig.clone(target, props?)`, `$fig.append(parent, child)`, `$fig.addAt(parent, index, child)`, `$fig.replace(old, new)`, `$fig.reorder(parent, children)`, `$fig.gradient(node, type, stops, transform?)`, `$fig.image(node, hash, scaleMode?)` |\n| Variables | `const tokens = $fig.varCollection({ name, modes: ['Light', 'Dark'] })`, then `tokens.colorVar({ name, values: { Light: '#FFFFFF', Dark: '#000000' }, scopes })`, `.numVar`, `.stringVar`, `.boolVar`; existing: `$fig.getVar(idOrLibraryKey)` |\n| Bind a variable | Pass the handle as the value: `paddingLeft: space`, `cornerRadius: radius` (all four corners), `fills: [{ type: 'SOLID', color: brand }]` |\n| Styles | Create with `$fig.paintStyle` / `$fig.textStyle` / `$fig.effectStyle({ name, ... })`; existing: `$fig.getStyle(nameOrIdOrKey)`; apply with `fills: style`, `effects: style`, `textStyle: style` |\n| Screenshot | `node.screenshot({ scale?, contentsOnly? })`: queued, no `await`, one per node |\n| Real nodes and IDs | `await $fig.done()`, then `planNode.node` (null before the flush). Without it, the script auto-flushes and returns the created IDs. |\n\nLibrary keys (`componentKey`, `componentSetKey`, and style or variable `key` values) come from `search_design_system`; `$fig.get`, `$fig.instance`, `$fig.getStyle`, and `$fig.getVar` queue their import in the plan.\n\n**Icons:** **Prefer real vector icons:** import the icon's SVG source (inline `<svg>`, the `.svg` asset, or the source icon-library glyph — e.g. lucide/heroicons) via `$fig.svg(...)` rather than approximating an icon with a typed emoji/Unicode glyph (★ ⚙ 🔍 ☰ ▾) or a plain rectangle. A simple glyph or shape is a fine fallback when the real SVG genuinely can't be obtained — just reach for the SVG first. (Don't reconstruct an icon from rotated line/rect primitives, though — that renders broken.) Full recipe (viewBox+width/height sizing, `currentColor`, INSTANCE_SWAP for design-system icons): [figma-generate-design → Icons](../figma-generate-design/SKILL.md#icons-import-the-svg-never-reconstruct-from-rotated-primitives).\n\n### Copy these patterns\n\n**Build an auto-layout frame with children — single call:**\n```js\n$fig.autoLayout(\n  // fixed width; omit height to hug vertically\n  { name: 'Todo List', layoutMode: 'VERTICAL', width: 480 },\n  ['item 1', 'item 2', 'item 3'].map((item) =>\n    $fig.autoLayout(\n      // FILL is valid because this item is attached to the auto-layout Todo List\n      { name: 'Todo Item', layoutSizingHorizontal: 'FILL' },\n      [$fig.text({ characters: item, fontName: { family: 'Inter', style: 'Bold' } })],\n    ),\n  ),\n).screenshot() // Composition check; do not repeat unless a relevant change needs visual verification.\n```\n\n**Repeated UI (list items, cards, nav items, table rows, day cells): build ONE component, then place instances.** Do not build N near-identical frames. TEXT/BOOLEAN props carry the per-item differences:\n```js\nconst ITEMS = [\n  { title: 'Inbox', count: '12' },\n  { title: 'Drafts', count: '' },\n  // ...from the source data\n]\nconst item = $fig.component({ name: 'Nav Item', layoutMode: 'HORIZONTAL', itemSpacing: 8 }, [\n  $fig.text({ characters: 'Label' }).textProp('Label'),\n  $fig.text({ characters: '0' }).textProp('Count').booleanProp('Show Count'),\n])\n$fig.autoLayout({ name: 'Nav', layoutMode: 'VERTICAL', width: 240 },\n  ITEMS.map((v) => $fig.instance(item, {\n    layoutSizingHorizontal: 'FILL',\n    props: { Label: v.title, Count: v.count, 'Show Count': v.count !== '' },\n  })),\n).screenshot()\n```\nWhen building a screen, keep main components outside the view: in the file's existing component area, or off to the side of the wrapper. Return `item.node.id` (after `await $fig.done()`) when a later call needs more instances: `$fig.instance('ID', { props })`. Only genuinely one-off containers stay plain frames. See [figma-generate-design → componentization](../figma-generate-design/references/componentization.md).\n\n**Source-defined or repeated icons: import the SVG once into a component, then place instances.** Reuse a compatible local or library icon component when one exists. Otherwise, when the source uses an icon component (even once inside the requested component) or repeats an icon, create one local main component with `$fig.svgComponent(svgStr, opts)`. It converts the imported SVG's outer frame into the component, preserving its children without adding a wrapper. Keep that main component in the existing component area, outside the composed view. Insert instances into parent components and their variants so the icon remains a reusable dependency. Direct SVG children are appropriate for genuinely one-off artwork that the source does not define as a reusable component.\n```js\n// Read this exact SVG from the source asset or icon library first.\nconst chevronSvg = '<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"m9 6 6 6-6 6\" stroke=\"#111827\" stroke-width=\"2\"/></svg>'\nconst chevron = $fig.svgComponent(chevronSvg, { name: 'ChevronRight', width: 24, height: 24 })\nconst iconButton = $fig.component({ name: 'IconButton', layoutMode: 'HORIZONTAL' }, [\n  $fig.instance(chevron),\n])\nconst preview = $fig.autoLayout({ name: 'Preview', x: 400, layoutMode: 'HORIZONTAL' }, [\n  $fig.instance(iconButton),\n  $fig.instance(iconButton),\n])\nawait $fig.done()\nreturn { iconId: chevron.node.id, buttonId: iconButton.node.id, previewId: preview.node.id }\n```\nA later call can reuse the returned icon ID with `$fig.instance(iconId)`. The SVG is imported only in the main icon component, and each button contains an icon instance.\n\n**Update existing nodes — by query or by id:**\n```js\n$fig.query('FRAME[name=Header] TEXT[name=Title]').set({ characters: 'New Title', fontSize: 24 })\n$fig.get('1:42').set({ opacity: 0.8, cornerRadius: 12 })\n```\n\n**Add a node inside an existing node**\n```js\n$fig.get('1:42').append($fig.autoLayout({ name: 'New Frame' }))\n```\n\n`parent.append(a, b, c)` and `$fig.append(parent, a, b, c)` append every child in order and return the parent for chaining.\n\n**Create variants and place an instance**\n```js\nconst SIZES = ['Small', 'Medium', 'Large']\nconst buttonComponentSet = $fig.variants({ name: 'Button' }, SIZES.map((size) => $fig.component({ name: `Size=${size}`, layoutMode: 'HORIZONTAL', /** other props */ })))\nconst buttonInst = $fig.instance(buttonComponentSet, { props: { Size: 'Medium' } })\n$fig.get('DESTINATION_FRAME_ID').append(buttonInst)\n// Creation and placement are queued; no intermediate done() is needed.\n```\nSelect variants through `props` on the component set. This also works with published sets when individual variant references are unavailable.\nIf an earlier measurement required `await $fig.done()`, continue using plan node `.set(...)` and `.append(...)` for changes and placement.\n\n> ⚠️ `$fig.variants` does **not** position the variants — they stack at (0,0) and the set renders as one collapsed, overlapping element. You must grid the variants and resize the set afterward. See [`fig-builder.md`](references/fig-builder.md#required-follow-up--grid-the-variants-fig-build--raw-layout) for the required follow-up recipe.\n\n> **Building a component — even a single one? Binding tokenized values is part of finishing the job, not a preference.** A component is **not complete** while any value that *has* a corresponding design token — one that already exists in the file, or that you created from the source — is still a hardcoded literal. When a token exists for a `fills` color / `cornerRadius` / padding / `itemSpacing`, bind it: build a `$fig.varCollection` (primitive tier + semantic tier aliased to it) and pass the variable **handle straight into the property**. **Anti-pattern to avoid:** do NOT copy resolved token values into local JS constants (e.g. `const VARIANTS = [{ bg: '#2c2c2c' }]`) and paint with resolved literal colors — that silently bypasses variables even though the source defines tokens. This applies to a single component as much as a full design system. **Only bind values that actually have a token** — values with genuinely no token (one-off geometry, icon pixel sizes, static 1px dividers) correctly stay literal; don't invent tokens to bind. **If you create the variables in one `use_figma` call and build the component in a later one, rehydrate the handles first** (`$fig.getVar(id)` or `figma.variables.getVariableByIdAsync` using the IDs you returned) — a handle from a previous call isn't in scope. Worked recipe: [fig-builder.md → Building a component with bound variables](references/fig-builder.md#building-a-component-with-bound-variables-the-default-for-components).\n\n**Create an instance of a component**\n```js\n// First arg can be a component plan wrapper, a node ID ('1:2'), OR a library asset key\n// from `search_design_system` results (the `componentKey` or `componentSetKey` field, according to `assetType`).\n$fig.instance('1:2', { name: 'Cancel Btn', props: { label: 'Cancel'}})\n```\n\n**Consume styles/variables**\n```js\n$fig.autoLayout({ name: 'Card', itemSpacing: spacingVar, fills: fillStyle })\n\n// Looked up by asset key from `search_design_system` (the `key` field)\n$fig.autoLayout({ fills: $fig.getStyle(BG_STYLE_KEY) })\n$fig.rectangle({ fills: [{ type: 'SOLID', color: $fig.getVar(BRAND_VAR_KEY) }] })\n```\n\n**Use design-system assets by key (from `search_design_system`)**\n\n`search_design_system` returns `componentKey` for components, `componentSetKey` for component sets, and `key` for styles and variables. Pass these straight into the unified `$fig` lookup — the plan queues the library import automatically, so you don't need a separate `await figma.importComponentByKeyAsync(...)` / `importStyleByKeyAsync(...)` / `importVariableByKeyAsync(...)` step.\n```js\n// One call site, many input shapes — node IDs, real variable/style ids,\n// AND 40-char asset keys (e.g. '49c8754d4b898e176148650df612a47998a8c4a1')\nconst btn        = $fig.get(BUTTON_KEY)                    // component / component set\nconst instance   = $fig.instance(BUTTON_SET_KEY, {         // create an instance from a set\n  props: { Size: 'md', Variant: 'primary' },\n})\nconst heading    = $fig.getStyle(HEADING_TEXT_STYLE_KEY)   // paint / text / effect / grid style\nconst brand      = $fig.getVar(BRAND_COLOR_VAR_KEY)        // variable\n\n$fig.text({ characters: 'Hello', textStyle: heading })\n$fig.rectangle({ fills: [{ type: 'SOLID', color: brand }] })\n```\n\n**Discover a set's variant props from its key** — `search_design_system` returns a set's `componentSetKey`, not its variant properties. This is **two `use_figma` calls**: call 1 `return`s the set's property definitions and its variants so their props come back to you in the tool result; then, knowing the valid props, call 2 instantiates the variant you want.\n```js\nconst setHandle = $fig.get(BUTTON_SET_KEY)\nawait $fig.done()\nconst set = setHandle.node\nif (!set || set.type !== 'COMPONENT_SET') {\n  throw new Error(`Key ${BUTTON_SET_KEY} is not a COMPONENT_SET`)\n}\nreturn {\n  componentPropertyDefinitions: set.componentPropertyDefinitions,\n  variants: set.children\n    .filter((c) => c.type === 'COMPONENT')\n    .map((c) => ({ name: c.name, variantProperties: c.variantProperties })),\n}\n```\n```js\n// Call 2 — instantiate with props you picked from call 1's output\n$fig.instance(BUTTON_SET_KEY, { props: { Size: 'Large', Kind: 'Secondary' } })\n```\n\n**Bulk component swap — `$fig.query().set()`:**\n```js\nconst chevron = $fig.get('CHEVRON_KEY')\n$fig.query('INSTANCE[name=arrow_drop_down]').set({ mainComponent: chevron })\n```\n\n**`.query()` and `.values()` for search and projecting child values**\n```js\nconst menuArrows = $fig\n  .query('PAGE[name=Menu] INSTANCE[mainComponent.name*=arrow], PAGE[name=Menu] INSTANCE[mainComponent.name*=chevron]')\n  .values(['id', 'name', 'mainComponent.name', 'mainComponent.id']);\n\n// Use quotes for multi-word selector values\nconst expandComponents = $fig\n  .query('COMPONENT[name*=expand], COMPONENT[name*=chevron_down], COMPONENT[name*=chevron_up], COMPONENT[name*=\"multi word name\"]')\n  .values(['id', 'name']);\n```\n\n**Perform operations on another page:**\n\nPage context resets to the first page at the start of each `use_figma` call. When an operation needs another current page, switch with `await figma.setCurrentPageAsync(page)` before queuing the plan; never assign `figma.currentPage` directly. Switch at most once per call. Split work requiring multiple current-page contexts into independent calls, one per page; issue independent calls in parallel. A scoped FigQuery search does not itself require a separate call for every page.\n```js\n// Switch to a specific page (loads its content)\nconst targetPage = figma.root.children.find((p) => p.name === \"My Page\");\nawait figma.setCurrentPageAsync(targetPage);\n$fig.query('INSTANCE[name=arrow_drop_down]').set({ ... })\n```\n\n**Gradient via helper — no manual transform matrix needed:**\n```js\nconst node = $fig.rectangle({ width: 240, height: 120 })\n$fig.gradient(node, 'LINEAR', [\n  { pos: 0, color: figma.util.rgba('#000000') },\n  { pos: 1, color: figma.util.rgba('#ffffff') },\n])\n```\n\n**Literal colors — use the built-in utilities, available in every call:**\n```js\n$fig.rectangle({ fills: [figma.util.solidPaint('#2563eb80')] }) // alpha becomes paint opacity\nconst rgb = figma.util.rgb('#2563eb') // { r, g, b }; ignores input alpha\nconst rgba = figma.util.rgba('#2563eb80') // { r, g, b, a }; for gradient stops/effects\n```\nUse these utilities directly instead of defining a hex parser or relying on helpers from a previous `use_figma` call. For token-backed properties, keep passing the variable handle directly; converting its resolved color to a paint would lose the binding.\n\n**Chaining on plan nodes — alternative to children array:**\n```js\nconst card = $fig.autoLayout({ name: 'Card', layoutMode: 'VERTICAL' })\ncard.text({ characters: 'Title', fontSize: 20 })\ncard.text({ characters: 'Description', fontSize: 14 })\n```\n\n### When to use the raw Figma Plugin API\n\nKeep raw Plugin API code that reads or changes document state separate from planned creation and mutations. Run it before `$fig` code, or after an explicit `await $fig.done()` that flushes all pending changes. Do not pass plan nodes to raw methods such as `regularNode.appendChild(planNode)` or `insertChild`; use `$fig.get(regularNode.id).append(planNode)` or `.addAt(index, planNode)` instead. Planned changes are not visible to raw reads such as `regularNode.children` until the plan is flushed. After flushing, use `planNode.node` when a raw API needs the real node. Pure color helpers such as `figma.util.solidPaint`, `.rgb`, and `.rgba` can be used inside `$fig` expressions.\n\nUse the raw API only in these cases:\n\n- **Color conversion:** `figma.util.solidPaint`, `.rgb`, and `.rgba` convert literal colors for `$fig` properties without creating or mutating nodes.\n- **Mid-script async result needed:** `await figma.setCurrentPageAsync(...)`, `await figma.loadFontAsync(...)` — must complete before subsequent plan steps can use the result. (Importing library components is NOT one of these cases: pass the matching `componentKey` or `componentSetKey` straight into `$fig.get(...)` / `$fig.instance(...)` and pass variant property values in `props`. `$fig` queues the library import in the plan and resolves the variant for you.)\n- **Mid-script real node state read:** measured `width` / `height` after auto-layout, computed colors, getStyledTextSegments — materialize mid-script, then read `.node` on the plan node. See [references/fig-builder.md](references/fig-builder.md) for the mid-script inspection pattern.\n- **Things `$fig` genuinely doesn't expose:** `node.setRangeFontName(...)`, etc. — access via `planNode.node` (see [references/fig-builder.md](references/fig-builder.md)).\n\n## Critical Rules\n\n1. **Only use `$fig` for creating / bulk-editing nodes** (`$fig.autoLayout(...)`, `$fig.text(...)`, `$fig.query(...).set(...)`). Raw Plugin API is the fallback — use it only when `$fig` can't express the operation (intermediate node-state reads, non-SceneNode types like Variables). Library components are NOT a reason to leave `$fig`: `$fig.get(componentKey)` / `$fig.instance(componentSetKey, { props })` queue the library import and resolve the variant for you. See [references/fig-builder.md](references/fig-builder.md) and [references/critical-rules-deep.md](references/critical-rules-deep.md) for worked WRONG/RIGHT examples.\n\n2. **Do not use `findOne`, `findAll`, `findAllWithCriteria`, `findChildren`, `findChild` directly for node searching** They are more verbose, error-prone, and less efficient than `query()`.  Additionally, do not use recursion to search.\n   `frame.query('[boundVariables.*]')` filters nodes by non-empty bindings: `{ boundVariables: { width: alias } }` matches; `{ boundVariables: {} }` or `{ fills: [paint] }` does not. Selector `*` expands array elements or object values.\n\n3. **Keep automatic result reporting for pure `$fig` scripts.** The runtime auto-flushes and returns a `FigDoneResult` with created/updated node IDs. Use `await $fig.done()` before reading materialized state or deferred query results, and `return` any additional evidence needed. Include IDs for raw mutations in custom results. JS variables and plan handles do not survive between calls: pass returned IDs as string literals and resolve them again with `$fig.get`, `$fig.getVar`, or `$fig.getStyle`. Keep workflow state outside the Figma file.\n\n4. **Size construction calls for safe retry and validate from evidence.** Batch related creation and edits when failures remain recoverable; a complete section or page may be one call. Split for page-context changes, difficult partial recovery, or a targeted retry after failure—not merely to create validation checkpoints. Use returned IDs and relevant counts, names, or bounds as structural evidence; add a separate check only when evidence is missing or a relevant mutation invalidates it. Normally take one screenshot after composition and one after a visual fix. The latest passing screenshot is final; stop when requirements pass. For work spanning calls, the placeholder workflow below remains useful: populate or replace each placeholder and clear `placeholder` when finished.\n\n```js\n$fig.autoLayout({ name: 'Screen', layoutMode: 'VERTICAL', width: 390 }, [\n  $fig.autoLayout({ name: 'Header', layoutSizingHorizontal: 'FILL', placeholder: true }),\n  $fig.autoLayout({ name: 'Content', layoutSizingHorizontal: 'FILL', placeholder: true }),\n])\n```\n\n5. **Plain JS with top-level `await`.** Code is auto-wrapped in async. Do NOT wrap in `(async () => {})()`.\n\n6. **Use built-in utilities for literal colors.** `figma.util.solidPaint('#2563eb80')` creates a complete solid paint with opacity. For individual color fields, use `figma.util.rgb(...)` for `{r,g,b}` (solid paints; ignores alpha) and `figma.util.rgba(...)` for `{r,g,b,a}` (gradient stops/effects). Channels are 0–1; solid-paint opacity belongs outside `color`. The utilities are available in every call — no custom hex parser needed. Token-backed properties still take variable handles directly. See [references/critical-rules-deep.md](references/critical-rules-deep.md) for WRONG/RIGHT.\n\n7. **No `curl` / `wget` / `Read` of Figma URLs from `Bash`.** Figma file access ONLY via `use_figma` and `mcp__figma__*` tools. After `get_screenshot`, the image is inlined in the tool result — do NOT re-fetch or re-Read it.\n\n8. **Empty / unsupported responses are terminal.** Accept and move on — don't try alternative bypass paths.\n\n9. **Verify node-type before touching a property.** Only `FRAME / COMPONENT / COMPONENT_SET / INSTANCE / GROUP / SECTION / PAGE` have `.children`. `GROUP` has no `fills` / `strokes` / `cornerRadius`. `TEXT` has no `cornerRadius` / `padding*` / `layoutMode`. `layoutPositioning='ABSOLUTE'` needs parent with `layoutMode !== 'NONE'`. Check `'<prop>' in node` or grep [references/plugin-api-standalone.d.ts](references/plugin-api-standalone.d.ts). Full list in [references/critical-rules-deep.md](references/critical-rules-deep.md).\n\n10. **Reuse evidence while it remains valid.** Do not repeat metadata reads or screenshots when nothing relevant changed. Reinspect when a mutation, external change, or recovery requirement invalidates earlier evidence.\n\n11. **Stop once requirements pass.** Gather enough evidence to establish correctness; avoid redundant checks, but do not leave known defects unresolved to meet a call limit.\n\n12. **On any `use_figma` error, obey `safeToRetryWithoutCanvasRead`.** If `true`, correct the identified error and retry without adding a diagnostic canvas read. If `false`, read the canvas, determine what changed, then make changes. If the same API or property error occurs twice, inspect its definition and fix the root cause before retrying; do not keep shrinking batches or changing selectors around the same invalid mutation. A generic error message alone does not establish the cause or prove that nothing changed. See [validation-and-recovery.md](references/validation-and-recovery.md).\n\n13. **NEVER call `mcp__figma__get_design_context`. FORBIDDEN.** This tool requires a selection (no selection exists in this environment), so every call will fail. The error is not recoverable — calling it just burns a tool slot and forces a retry. For structured reads of the file, use `mcp__figma__get_metadata` (for top-level frame discovery) and `use_figma` with `$fig.query()` instead. **Never call `get_design_context` for any reason.**\n\n14. **≤3 codebase `Read` calls when the task references source code.** Beyond that, grep only. The 4th codebase Read is forbidden — write your `use_figma` script with what you have.\n\n15. **Must use auto-layout unless you have a compelling reason not to.** Create auto-layout frames with `$fig.autoLayout(...)` instead of absolutely-positioning nodes.  New auto-layout frames are created with both axes hugging content. Explicitly assign `layoutSizingHorizontal` or `layoutSizingVertical` to `'FILL'` for auto-layout children if you want them to fill the auto-layout container's counter axis.\n\n16. **Gradient paints need ALL fields:** `type`, `gradientStops`, `gradientTransform` (a `[[a,b,tx],[c,d,ty]]` matrix). Missing any throws validation error. See [references/critical-rules-deep.md](references/critical-rules-deep.md).\n\n17. **Discover available fonts, esp. for style variations.** Use `await figma.listAvailableFontsAsync()` to discover available fonts for `$fig.text({ fontName: ... })`.\n\n18. **Set variable `scopes` explicitly when creating variables.** The default `ALL_SCOPES` pollutes every property picker. Use specific scopes — `['FRAME_FILL', 'SHAPE_FILL']` for backgrounds, `['TEXT_FILL']` for text, `['GAP']` for spacing, `['CORNER_RADIUS']` for radii; primitives that shouldn't appear in pickers get `[]`. In `$fig`, pass `scopes` to `colorVar` / `numVar`; in the raw API, set `variable.scopes`. There is no `STROKE` scope (use `STROKE_COLOR` or `STROKE_FLOAT`), and variable names cannot contain `.` (`space/0-5`, not `space/0.5`); [references/fig-builder.md](references/fig-builder.md) lists every scope and naming rule. See [references/variable-patterns.md](references/variable-patterns.md).\n\n19. **Never read `componentPropertyDefinitions`, `componentProperties`, or `valuesByMode` across a collection.** Resolve specific node IDs first, then read the property bundle only for those IDs. Reading one resolved node is safe; mapping these getters over `findAll*` results, `children`, or `getLocalVariables*` is the single largest cause of oversized returns.\n\n20. **Broad reads return `id`, `name`, `type` and counts only.** Fetch details for selected IDs in later calls. Return each file-wide inventory — variables, text styles, effect styles, paint styles, components, pages — in its own call; do not combine them into one return.\n\n21. **When a read may be large, measure the serialized return before returning it.** Bytes, not array length: `.slice()` bounds row count but not per-item size. If over budget, narrow the ID set or split across calls. Never drop required IDs or silently truncate.\n\n### Bulk mutation of existing nodes (swap/update/replace)\n\nFor tasks like \"swap N icons\", \"update M colors\", \"replace K instances\":\n1. **DISCOVER + MUTATE** together when safe: use scoped `$fig.query()` and planned mutations; return coverage evidence when the automatic result is insufficient.\n2. **VERIFY** only what the mutation result does not establish. Check visual results when needed.\n3. **FIX** any remaining defects with targeted changes, then report once requirements pass.\n\nChoose call boundaries for recoverability, not a fixed call budget. On failure, follow Rule 12. See [validation-and-recovery.md](references/validation-and-recovery.md).\n\n## Node property gotchas\n\nDo not guess node properties or assume CSS-like properties. Accessing non-existent properties will throw `TypeError: node.foo: no such property 'foo' on TYPE node`. Each throw burns a retry. [plugin-api-standalone.index.md](references/plugin-api-standalone.index.md) contains the list of all symbols in the API. Use that file and grep the full API typings in [plugin-api-standalone.d.ts](references/plugin-api-standalone.d.ts) for the full definitions.\n\n- **Only `FRAME` / `COMPONENT` / `COMPONENT_SET` / `INSTANCE` / `GROUP` / `SECTION` / `PAGE` have `.children`.** `RECTANGLE`, `TEXT`, `ELLIPSE`, `POLYGON`, `STAR`, `VECTOR`, `LINE`, `SLICE`, `STICKY`, `SHAPE_WITH_TEXT`, `STAMP`, `CONNECTOR`, `TABLE`, `WIDGET`, `EMBED`, `MEDIA` do NOT. Check `'children' in node` before accessing a node's children.\n- **Narrow before accessing `characters` or `description`.** Use typed query selectors or a capability guard for text-capable nodes. Set component purpose/usage in `description` only on `COMPONENT` or `COMPONENT_SET`. Optional chaining does not protect unsupported property access.\n- **`GROUP` has NO `fills` / `strokes` / `cornerRadius`.** Apply paints/radii on the child shapes inside.\n- **Figma auto-layout != CSS flexbox.** There is no such thing as margin.\n- **`TEXT` DOES NOT HAVE container properties.** Text has font / size / decoration / fills. Do not use container properties like padding, layout mode, item spacing, etc.\n- **`INSTANCE` descendants are read-only for structural ops** — you cannot `appendChild` / `insertChild` into an instance child. Edit the source `COMPONENT` or detach first.\n- **Never use `primaryAxisSizingMode` or `counterAxisSizingMode` on a node. ** Use `layoutSizingHorizontal` or `layoutSizingVertical` with 'FIXED' | 'HUG' | 'FILL'. Use 'FILL' only when the parent has auto-layout.\n- **There is NO `instance.swapMainComponent(...)`.** Use `instance.setProperties({...})` with the component-property variant value, OR `$fig.query(...).set({props: {...}})`. There IS `instance.swapComponent(component)` (different method name).\n\n## References\n\n- [references/fig-builder.md](references/fig-builder.md) — full `$fig` API and worked patterns; start with the quick reference above\n- [references/critical-rules-deep.md](references/critical-rules-deep.md) — WRONG/RIGHT examples, full node-type pitfall list, bulk-mutation template, syntax-bug checklist\n- [references/gotchas.md](references/gotchas.md) — raw Plugin API edge cases\n- [references/plugin-api-standalone.d.ts](references/plugin-api-standalone.d.ts) — type definitions (grep, don't read whole)\n- [references/plugin-api-standalone.index.md](references/plugin-api-standalone.index.md) — API navigation\n- [references/common-patterns.md](references/common-patterns.md), [component-patterns.md](references/component-patterns.md), [variable-patterns.md](references/variable-patterns.md), [text-style-patterns.md](references/text-style-patterns.md), [effect-style-patterns.md](references/effect-style-patterns.md) — pattern playbooks\n- [references/working-with-design-systems/](references/working-with-design-systems/) — design system workflows\n- [references/validation-and-recovery.md](references/validation-and-recovery.md) — error recovery patterns\n"}],"summary":"Fields changed: 2. /included_files, /skill_md_contents.","summary_kind":"deterministic","summary_metadata":{}}