Plugin API and runtime overview
NGIN is a web interface and vector design environment. Its Plugin API provides document editing, tool interfaces and local preferences.
Main code runs in QuickJS/WASM without DOM, window or direct Node.js access. UI runs in a separate DOM iframe. The actual global is figma; this identifier, editorType: ["figma"] and theme variables --figma-color-* are technical parts of NGIN’s current contract. Do not invent an ngin global. These names do not imply access to another product.
Runtime limits: each synchronous turn has a 30-second interrupt budget and the sandbox memory limit is 512 MiB. These are not a whole-plugin lifetime or download timeout. figma.apiVersion is 1.0.0, not the application version.
Build and run on the web
- Download the starter ZIP; keep its file structure.
- Open NGIN then
Application menu → Plugins → Manage Plugins… → Import ZIP…. - Import and Run
NGIN Starter, then pressCreate cardin its UI. - A selected orange 240×160 card is created. Use a disposable document.
- Re-import the ZIP after editing code.
Selecting only the manifest does not grant access to neighboring files: import a ZIP, folder or complete file set. Compile TypeScript and bundle imports into standalone JavaScript first; direct npm import/require in main code is not guaranteed.
manifest.json
code.js
ui.html
Manifest and actual permissions
{
"name": "NGIN Starter",
"id": "ngin.example.starter.v47",
"api": "1.0.0",
"editorType": [
"figma"
],
"main": "code.js",
"ui": "ui.html",
"documentAccess": "dynamic-page",
"networkAccess": {
"allowedDomains": [
"none"
]
}
}
| Field | Type | Actual behavior |
|---|---|---|
| name | string | Required, nonempty. |
| main | string | Required; built code path relative to manifest. |
| id | string | Unique ID; generated from name if omitted. Set explicitly to prevent storage collisions. |
| api | string | Defaults to 1.0.0; parser also accepts unknown strings. Acceptance is not compatibility validation. |
| editorType | string[] | Defaults to ["figma"]; must contain figma or dev. Runtime editorType remains figma. |
| ui | string / Record |
Optional; single HTML → html; map → uiFiles, first value → html. |
| menu | PluginMenuItem[] | Submenus, separators and commands; selected command becomes figma.command. |
| parameters | PluginParameter[] | key/name, optional, allowFreeform, description; parameterOnly defaults true when parameters exist. |
| permissions | string[] | currentuser is actually checked; other accepted strings do not create permissions. |
| documentAccess | string | Stored metadata; not a document security boundary or lazy-loading implementation. |
| networkAccess.allowedDomains | string[] | none=deny, *=all, omission=no manifest restriction. reasoning/devAllowedDomains are discarded by parser. |
| relaunchButtons | {command,name,multipleSelection?}[] | Parsed; test your required UI behavior separately. |
Non-object manifests and missing name/main throw. Widget packages are rejected. Unknown fields are generally dropped; permissive parsing is not support.
interface PluginMenuItem { name: string; command?: string; separator?: boolean; menu?: PluginMenuItem[] }
interface PluginParameter { name: string; key: string; description?: string; allowFreeform?: boolean; optional?: boolean }
Minimal main-code example
This file is exercised through the project runtime and an isolated browser session. RGB channels are 0–1. Synchronous operations may throw Error; validate UI input.
figma.showUI(__html__, { width: 300, height: 180, themeColors: true });
figma.ui.onmessage = (message) => {
if (!message || typeof message !== 'object') return;
if (message.type === 'create-card') {
const node = figma.createRectangle();
node.name = 'Plugin card';
node.resize(240, 160);
node.cornerRadius = 16;
node.fills = [{ type: 'SOLID', color: { r: 1, g: 0.44, b: 0.21 } }];
const center = figma.viewport.center;
node.x = center.x - 120;
node.y = center.y - 80;
figma.currentPage.selection = [node];
figma.viewport.scrollAndZoomIntoView([node]);
figma.notify('Card created');
}
if (message.type === 'close') figma.closePlugin();
};
UI, messages and lifecycle
<!doctype html>
<html lang="en"><meta charset="utf-8">
<style>
body { margin: 20px; font: 14px system-ui; color: #242424; background: #fff; }
button { padding: 10px 14px; margin: 6px 6px 0 0; border-radius: 8px; cursor: pointer; }
</style>
<h2>NGIN Starter</h2><p>Create an editable card on the canvas.</p>
<button id="create">Create card</button><button id="close">Close</button>
<script>
document.getElementById('create').onclick = () => parent.postMessage({ pluginMessage: { type: 'create-card' } }, '*');
document.getElementById('close').onclick = () => parent.postMessage({ pluginMessage: { type: 'close' } }, '*');
</script></html>
APIs: showUI(html: string, options?): void, ui.postMessage(message, options?): void, ui.onmessage = (message, {origin}) => …, ui.on/once/off("message", handler), ui.show/hide/close(): void, ui.resize(width,height): void, ui.reposition(x,y): void. Width is clamped to at least 70 and height to at least zero. ui.close() only closes the window; closePlugin(message?) ends the session.
Main → UI arrives as event.data.pluginMessage; UI → main uses parent.postMessage({pluginMessage: data}, "*"). Main currently receives origin "null", not an authenticated sender identity. Validate shape and values. Plain data and Uint8Array cross a JSON bridge; functions, cycles and DOM nodes are not reliable payloads.
Only one plugin runs at a time; starting another closes it. Top-level code runs before the run event. Parameters may delay run until answered. Edits are committed per turn into Undo; close clears timers and disposes the sandbox while keeping edits.
Reference data shapes
These are inspected NGIN data shapes, not a complete typings package or a guarantee of strict validation. Mixed properties can return figma.mixed (Symbol); compare using ===.
type NodeId = string;
type Vector = { x: number; y: number };
type RGB = { r: number; g: number; b: number };
type FontName = { family: string; style: string };
type SolidPaint = { type: "SOLID"; color: RGB; opacity?: number; visible?: boolean };
type VariableType = "COLOR" | "FLOAT" | "STRING" | "BOOLEAN";
type VariableAlias = { type: "VARIABLE_ALIAS"; id: string };
type Change = { type: "CREATE" | "DELETE" | "PROPERTY_CHANGE"; id: string; origin: "LOCAL"; properties?: string[] };
type DocumentChangeEvent = { documentChanges: Change[] };
type RunEvent = { command: string; parameters?: Record<string, unknown> };
Document, nodes and geometry
| API | Return / type | Contract and limits |
|---|---|---|
root / currentPage |
DocumentNode / PageNode | root read-only; currentPage writable. setCurrentPageAsync(page): Promise |
getNodeById(id) / getNodeByIdAsync(id) |
BaseNode | null / Promise |
Missing IDs return null; reference identity preserved. |
currentPage.selection |
SceneNode[] | Read/write page selection; narrow via node.type. |
createRectangle/Ellipse/Polygon/Star/Line/Vector/Text/Frame/Component/Section() |
typed SceneNode | Synchronous; inserts in current page; createPage(): PageNode. |
node.name / x / y / width / height / fills / cornerRadius |
string / number / Paint[] | Only on appropriate node types; resize(w,h): void, clone(): SceneNode, remove(): void. |
parent.appendChild(child) / insertChild(index,child) |
void | Containers only; invalid hierarchy/cycles can throw. |
findAll(predicate?) / findOne(predicate) |
SceneNode[] / SceneNode | null | On containers; predicate runs in sandbox. |
group(nodes,parent,index?) |
GroupNode | Nonempty list and valid parent. ungroup(group): SceneNode[]. |
union/subtract/intersect/exclude(nodes,parent,index?) |
BooleanOperationNode | Real geometry operations; flatten(nodes,parent?,index?): VectorNode. |
combineAsVariants(components,parent,index?) |
ComponentSetNode | Components only; empty/invalid lists error. |
createNodeFromSvg(svg) |
FrameNode | Unreadable SVG errors. |
node.getCSSAsync() |
Promise<Record |
Generated from current properties, not browser computed CSS. |
The downloadable file lists adapter members. Members without behavioral tests are not considered verified. This guide describes only inspected contracts.
Text, fonts and storage
async function addText() {
const font = {family: 'Inter', style: 'Regular'};
await figma.loadFontAsync(font);
const text = figma.createText();
text.fontName = font; text.characters = 'Hello, NGIN'; text.fontSize = 24;
figma.currentPage.selection = [text];
return text;
}
addText().catch(error => figma.notify(String(error)));
loadFontAsync(font: FontName): Promise<void> validates the FontName shape then resolves; it does not guarantee font existence, download or actual loading. A nonexistent font was accepted; verify glyph rendering separately. listAvailableFontsAsync(): Promise<Array<{fontName: FontName}>> lists known fonts. hasMissingFont is currently always false.
clientStorage.getAsync(key): Promise<unknown>, setAsync(key,value): Promise<null>, deleteAsync(key): Promise<null> and keysAsync(): Promise<string[]> are scoped by plugin ID. The sandbox bridge converts undefined to null: missing keys and set/delete results currently return null, not undefined. Validate stored preference data.
Storage uses IndexedDB; if unavailable, an in-memory fallback is lost on reload. clientStorageQuota is a fixed 5 MiB value, not an enforced code quota; browser limits also apply. Key namespacing uses an ID prefix, not a security boundary against malicious plugins. Do not store secrets here.
async function preferences() {
await figma.clientStorage.setAsync('gap', 24);
const gap = await figma.clientStorage.getAsync('gap');
const keys = await figma.clientStorage.keysAsync();
await figma.clientStorage.deleteAsync('gap');
return {gap, keys};
}
preferences().catch(error => figma.notify(String(error)));
Events and run parameters
| Event | Payload | Behavior |
|---|---|---|
| run | RunEvent | After main code and parameter entry; once is appropriate. |
| selectionchange | undefined | Microtask delivery with coalescing. |
| currentpagechange | undefined | After active-page changes. |
| documentchange | DocumentChangeEvent | Own plugin turns are generally filtered; not a complete or remote-change feed. |
| close | undefined | Before disposal; completion of async cleanup is not guaranteed. |
| drop | {node,x,y,absoluteX,absoluteY,items,files,dropMetadata} | Synchronous false prevents default file insertion; file.getBytesAsync/getTextAsync are available. |
| parameters: input | {key,query,parameters,result} | Register with figma.parameters.on("input", handler); result.setSuggestions/setError/setLoadingMessage. |
on(type,handler), once(type,handler) and off(type,handler) return undefined in the prelude; keep the same callback reference for off. Arbitrary strings can be registered but are not automatically emitted.
figma.once('run', ({command, parameters}) => {
figma.notify('NGIN: ' + (command || 'default'));
});
Styles, variables and additional APIs
| API / shape | Behavior and status |
|---|---|
createPaintStyle / createTextStyle / createEffectStyle() |
Local style; name, paints or text/effect properties; remove(). |
getLocalPaintStyles/TextStyles/EffectStyles[Async]() |
Sync returns array, Async returns Promise of array; getStyleById[Async] returns null when missing. |
variables.createVariableCollection(name) |
Collection with id/modes/defaultModeId; addMode/renameMode/removeMode; last mode cannot be removed. |
variables.createVariable(name,collection,type) |
Type COLOR/FLOAT/STRING/BOOLEAN; foreign collection or invalid type throws. |
variable.setValueForMode(modeId,value) |
Checks value type and mode existence; aliases via createVariableAlias(variable). |
variables.getLocalVariables[Async](type?) / getLocalVariableCollections[Async]() |
Local only; lookup via getVariableById[Async]/getVariableCollectionById[Async]; missing is null. |
node.exportAsync(settings?) |
PNG/JPG/SVG → Promise |
createImage(bytes: Uint8Array) / createImageAsync(url) |
Image or Promise |
viewport.center / zoom / bounds / scrollAndZoomIntoView(nodes) |
Writable Vector, writable number, read-only Rect; host void actions may become null through bridge. |
createPageDivider(name = "---") |
Divider PAGE; name only dashes/en/em dashes/asterisks/spaces; other text throws. |
createTextPath(pathNode, segment = 0, position = 0) |
TEXT_PATH; requires valid path and segment. |
createNodeFromJSXAsync(element) |
Design construction helper: Frame/AutoLayout/Rectangle/Ellipse/Line/Text/Image/SVG/Fragment; not a widget runtime. |
node.getPluginData / setPluginData / getSharedPluginData / setSharedPluginData |
String document metadata; not secret storage. Metadata/annotation members are in the inventory; test your required scenario separately. |
commitUndo() / triggerUndo() / saveVersionHistoryAsync(title,description) |
Flush turn/local Undo/Promise<{id:string}> local history; not a cloud service. |
Network and security boundaries
Main fetch(url: string, {method?, headers?, body?}): Promise<Response> is a subset: body string or Uint8Array; Response exposes status/ok/url/headers/text/json/arrayBuffer/clone. Do not assume streams, AbortSignal or all browser fetch options. HTTP error statuses do not themselves reject; check response.ok.
Without networkAccess no manifest domain restriction is applied; the offline starter uses ["none"]. Bare domains match a host; *.example.com matches subdomains but not the apex. An explicit scheme must match. Paths use startsWith (/v1 can also match /v10); port is not constrained by the matcher. Do not treat this as a strict path/port security boundary.
A constrained UI receives CSP including connect-src. CORS, browser sandbox, redirects and CSP are separate constraints; this is not a complete security audit or a guarantee about all redirects. Catch transport, JSON and policy failures. Never embed passwords, private tokens or secret configuration in packages or prompts.
Unsupported features and separated implementation issues
| Member / area | Actual status |
|---|---|
| createSlice / createVideoAsync / transformGroup / createGridStyle / PDF export | Throws or rejects; unavailable. |
| widget packages / editor-specific APIs | Widget packages rejected; other editor-specific methods throw. |
| teamLibrary / remote imports | No connected cloud library; empty lists; importComponent/Style may only resolve local IDs. |
| payments / codegen / devResources events | Payments and codegen/devResources listeners are placeholders/no-ops, not functioning services. |
| ui.getPosition / hasMissingFont / clientStorageQuota | Fixed zero/false/5MiB values, not actual position/font/quota guarantees. |
| getLocalGridStyles[Async] / moveLocalGridStyleAfter / moveLocalGridFolderAfter | Empty/no-op; node.layoutGrids is distinct from grid styles. |
| loadFontAsync / util.normalizeMarkdown / loadAllPagesAsync / loadBrushesAsync | Font only validates shape; normalizeMarkdown returns input unchanged; loadAllPages/Brushes are no-ops. |
| textreview enable / importShaderById / variables remote imports | Reject; listAvailableShaders/motion animation styles return empty lists. |
| notify(...).cancel / timeout / button | Current session cancel is a no-op; timeout/button are not honored by notification service. |
| undefined return across bridge | Runtime discrepancy: host undefined becomes null, including storage. Documented without changing API. |
These are current runtime limitations; no confirmed schedule for changing them has been announced.
Testing, building and troubleshooting
- Package standalone built code, manifest and UI in a ZIP; fix manifest-only errors by importing complete files.
- Use a disposable document; inspect dimensions, selection, parent, Undo and visual output.
- Test both UI message directions and origin behavior; never add secrets.
- Catch Promise rejections; compare not available errors against limitations.
- Test null/invalid storage and domain/CORS failures.
- Initial sandbox loading can require a download; wait for its UI.
Report an issue
If something goes wrong while building or running a plugin, send an issue report to Nourix. Include:
- What you were trying to do and the expected result.
- Steps to reproduce the issue and the complete error message.
- Your browser version and operating system.
- A minimal plugin code example or screenshot, with confidential information removed.
Send a report through Contact · Email support
Do not include passwords, tokens, API keys or private documents.