figme-mcp 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +447 -0
  3. package/dist/cache.d.ts +29 -0
  4. package/dist/cache.js +68 -0
  5. package/dist/fig/bytebuffer.d.ts +31 -0
  6. package/dist/fig/bytebuffer.js +98 -0
  7. package/dist/fig/container.d.ts +32 -0
  8. package/dist/fig/container.js +80 -0
  9. package/dist/fig/imagemeta.d.ts +17 -0
  10. package/dist/fig/imagemeta.js +96 -0
  11. package/dist/fig/invariants.d.ts +10 -0
  12. package/dist/fig/invariants.js +63 -0
  13. package/dist/fig/kiwi.d.ts +38 -0
  14. package/dist/fig/kiwi.js +144 -0
  15. package/dist/fig/parse.d.ts +37 -0
  16. package/dist/fig/parse.js +91 -0
  17. package/dist/fig/zip.d.ts +23 -0
  18. package/dist/fig/zip.js +95 -0
  19. package/dist/mcp/create.d.ts +12 -0
  20. package/dist/mcp/create.js +48 -0
  21. package/dist/mcp/respond.d.ts +76 -0
  22. package/dist/mcp/respond.js +124 -0
  23. package/dist/mcp/server.d.ts +3 -0
  24. package/dist/mcp/server.js +22 -0
  25. package/dist/mcp/tools/blob.d.ts +7 -0
  26. package/dist/mcp/tools/blob.js +55 -0
  27. package/dist/mcp/tools/components.d.ts +7 -0
  28. package/dist/mcp/tools/components.js +54 -0
  29. package/dist/mcp/tools/context.d.ts +24 -0
  30. package/dist/mcp/tools/context.js +48 -0
  31. package/dist/mcp/tools/find.d.ts +7 -0
  32. package/dist/mcp/tools/find.js +97 -0
  33. package/dist/mcp/tools/image.d.ts +6 -0
  34. package/dist/mcp/tools/image.js +100 -0
  35. package/dist/mcp/tools/instance.d.ts +7 -0
  36. package/dist/mcp/tools/instance.js +44 -0
  37. package/dist/mcp/tools/node.d.ts +7 -0
  38. package/dist/mcp/tools/node.js +49 -0
  39. package/dist/mcp/tools/overview.d.ts +7 -0
  40. package/dist/mcp/tools/overview.js +45 -0
  41. package/dist/mcp/tools/render.d.ts +6 -0
  42. package/dist/mcp/tools/render.js +128 -0
  43. package/dist/mcp/tools/style.d.ts +7 -0
  44. package/dist/mcp/tools/style.js +38 -0
  45. package/dist/mcp/tools/text.d.ts +7 -0
  46. package/dist/mcp/tools/text.js +89 -0
  47. package/dist/mcp/tools/tree.d.ts +7 -0
  48. package/dist/mcp/tools/tree.js +100 -0
  49. package/dist/mcp/tools/variables.d.ts +7 -0
  50. package/dist/mcp/tools/variables.js +71 -0
  51. package/dist/model/access.d.ts +28 -0
  52. package/dist/model/access.js +106 -0
  53. package/dist/model/components.d.ts +72 -0
  54. package/dist/model/components.js +157 -0
  55. package/dist/model/index.d.ts +73 -0
  56. package/dist/model/index.js +192 -0
  57. package/dist/model/instance.d.ts +87 -0
  58. package/dist/model/instance.js +208 -0
  59. package/dist/model/summarize.d.ts +83 -0
  60. package/dist/model/summarize.js +541 -0
  61. package/dist/model/text.d.ts +29 -0
  62. package/dist/model/text.js +61 -0
  63. package/dist/model/tree.d.ts +47 -0
  64. package/dist/model/tree.js +89 -0
  65. package/dist/model/variables.d.ts +50 -0
  66. package/dist/model/variables.js +141 -0
  67. package/dist/render/bounds.d.ts +64 -0
  68. package/dist/render/bounds.js +173 -0
  69. package/dist/render/color.d.ts +20 -0
  70. package/dist/render/color.js +41 -0
  71. package/dist/render/effects.d.ts +34 -0
  72. package/dist/render/effects.js +196 -0
  73. package/dist/render/export.d.ts +51 -0
  74. package/dist/render/export.js +573 -0
  75. package/dist/render/index.d.ts +42 -0
  76. package/dist/render/index.js +94 -0
  77. package/dist/render/instance.d.ts +12 -0
  78. package/dist/render/instance.js +72 -0
  79. package/dist/render/matrix.d.ts +46 -0
  80. package/dist/render/matrix.js +94 -0
  81. package/dist/render/node.d.ts +41 -0
  82. package/dist/render/node.js +95 -0
  83. package/dist/render/paint.d.ts +27 -0
  84. package/dist/render/paint.js +301 -0
  85. package/dist/render/path.d.ts +42 -0
  86. package/dist/render/path.js +156 -0
  87. package/dist/render/raster.d.ts +31 -0
  88. package/dist/render/raster.js +69 -0
  89. package/dist/render/report.d.ts +72 -0
  90. package/dist/render/report.js +106 -0
  91. package/dist/render/style.d.ts +31 -0
  92. package/dist/render/style.js +67 -0
  93. package/dist/render/svg.d.ts +60 -0
  94. package/dist/render/svg.js +150 -0
  95. package/dist/render/text.d.ts +50 -0
  96. package/dist/render/text.js +90 -0
  97. package/package.json +47 -0
@@ -0,0 +1,573 @@
1
+ import { overrideIdentity } from '../model/tree.js';
2
+ import { bool, bytes, num, obj, objArr, str } from '../model/access.js';
3
+ import { BoundsCache, effectMargins } from './bounds.js';
4
+ import { applyProps, descend, instanceShapeNode, mergeNode, resolveInstance, } from './instance.js';
5
+ import { applyStyles, runPaints } from './style.js';
6
+ import { expandBox, fromFigma, isIdentity, transformBox, unionBox } from './matrix.js';
7
+ import { classify, clipsChildren, hasFillGeometry, isBooleanOperation, isInstance, isMask, isVisible, nodeOpacity, nodeSize, nodeType, strokeAlign, } from './node.js';
8
+ import { decodeCommands, ellipseCommands, roundedRectCommands, toPathData } from './path.js';
9
+ import { paintAttrs } from './paint.js';
10
+ import { alphaToWhiteFilter, blendStyle, effectsFilter } from './effects.js';
11
+ import { ReportBuilder, feat } from './report.js';
12
+ import { buildText, hasCharactersWithoutOutlines } from './text.js';
13
+ import { SvgWriter, fmt, toAttr } from './svg.js';
14
+ export const DEFAULT_MAX_NODES = 20_000;
15
+ export const HARD_MAX_NODES = 60_000;
16
+ /**
17
+ * `maxNodes` counts nodes in the TREE, which is the number a caller can see with fig_tree. The
18
+ * traversal visits many more, because every INSTANCE expands into the symbol it points at
19
+ * (F17) — page `0:1` is 14 912 tree nodes but walks several times that. So the runtime guard is
20
+ * a separate, larger budget derived from `maxNodes`.
21
+ */
22
+ export const VISIT_FACTOR = 12;
23
+ export const HARD_MAX_VISITS = 400_000;
24
+ /** A render whose SVG exceeds this is refused rather than handed to the rasterizer. */
25
+ export const MAX_SVG_BYTES = 64 * 1024 * 1024;
26
+ /** Instances nested deeper than this are almost certainly a cycle in a damaged file. */
27
+ const MAX_INSTANCE_DEPTH = 24;
28
+ /** Node types whose shape can be rebuilt from size and corner radii when geometry is absent. */
29
+ const RECTANGULAR = new Set([
30
+ 'RECTANGLE',
31
+ 'ROUNDED_RECTANGLE',
32
+ 'FRAME',
33
+ 'SYMBOL',
34
+ 'INSTANCE',
35
+ 'SECTION',
36
+ 'GROUP',
37
+ ]);
38
+ /** Per-corner radii in SVG order: top-left, top-right, bottom-right, bottom-left. */
39
+ function cornerRadii(node) {
40
+ const uniform = num(node, 'cornerRadius') ?? 0;
41
+ if (bool(node, 'rectangleCornerRadiiIndependent') !== true) {
42
+ return [uniform, uniform, uniform, uniform];
43
+ }
44
+ return [
45
+ num(node, 'rectangleTopLeftCornerRadius') ?? uniform,
46
+ num(node, 'rectangleTopRightCornerRadius') ?? uniform,
47
+ num(node, 'rectangleBottomRightCornerRadius') ?? uniform,
48
+ num(node, 'rectangleBottomLeftCornerRadius') ?? uniform,
49
+ ];
50
+ }
51
+ /** A stop that must abort the whole render rather than being isolated to one node. */
52
+ export class RenderBudgetError extends Error {
53
+ }
54
+ class Exporter {
55
+ entry;
56
+ root;
57
+ out = new SvgWriter();
58
+ report = new ReportBuilder();
59
+ bounds;
60
+ maxVisits;
61
+ collectBoxes;
62
+ background;
63
+ boxes = [];
64
+ /** OUTLINE masks re-render their content with every paint forced to opaque white (§4.10). */
65
+ whiteout = false;
66
+ /** Override records of the innermost enclosing INSTANCE, keyed by identity path (F17). */
67
+ frame;
68
+ /** Component-property assignments of the innermost enclosing INSTANCE (F18). */
69
+ props = new Map();
70
+ /** Effective TEXT nodes whose glyphs belong to the symbol's words, not the assigned ones. */
71
+ staleOutlines = new WeakSet();
72
+ /** Symbols currently being expanded, so a self-referential component cannot loop. */
73
+ activeSymbols = new Set();
74
+ /** Distinguishes ids for the same symbol node drawn under different instances. */
75
+ defScope = '';
76
+ constructor(entry, root, opts) {
77
+ this.entry = entry;
78
+ this.root = root;
79
+ // Bounds must see nodes as this instance does — a nested instance's box may be resized by
80
+ // the enclosing one (F20) — so they are computed on the effective node, memoised per scope.
81
+ this.bounds = new BoundsCache(entry, (t) => this.effective(t), () => this.defScope);
82
+ const maxNodes = Math.min(opts.maxNodes ?? DEFAULT_MAX_NODES, HARD_MAX_NODES);
83
+ this.maxVisits = Math.min(maxNodes * VISIT_FACTOR, HARD_MAX_VISITS);
84
+ this.collectBoxes = opts.collectBoxes === true;
85
+ this.background = opts.background;
86
+ }
87
+ blob(index) {
88
+ if (index === undefined)
89
+ return undefined;
90
+ return bytes(this.entry.fig.blobs[index], 'bytes');
91
+ }
92
+ images = new Map();
93
+ get env() {
94
+ return {
95
+ report: this.report,
96
+ out: this.out,
97
+ entry: this.entry,
98
+ images: this.images,
99
+ whiteout: this.whiteout,
100
+ };
101
+ }
102
+ static box(node) {
103
+ const size = nodeSize(node);
104
+ return { x: 0, y: 0, w: size.w, h: size.h };
105
+ }
106
+ /**
107
+ * The node as this instance sees it: the tree node merged with the active overrides and with
108
+ * the enclosing instance's property assignments applied (F17, F18), then with every colour or
109
+ * effect style it references resolved to that style's live value (F19).
110
+ */
111
+ effective(t) {
112
+ let node = t.node;
113
+ if (this.frame) {
114
+ const record = this.frame.get(overrideIdentity(t));
115
+ node = mergeNode(node, record);
116
+ const applied = applyProps(node, this.props, record?.['derivedTextData'] !== undefined);
117
+ if (applied.node !== node) {
118
+ this.report.seen('instance-property');
119
+ node = applied.node;
120
+ if (applied.staleOutlines)
121
+ this.staleOutlines.add(node);
122
+ }
123
+ }
124
+ return applyStyles(this.entry.index, node);
125
+ }
126
+ /** Def keys must not collide between two instances of the same symbol with different fills. */
127
+ defKey(kind, t) {
128
+ return `${kind}:${this.defScope}${t.key}`;
129
+ }
130
+ run() {
131
+ const measured = this.bounds.renderBounds(this.root);
132
+ // A zero-area subtree (everything hidden, or a degenerate node) still needs a legal viewBox.
133
+ const bounds = {
134
+ x: measured?.x ?? 0,
135
+ y: measured?.y ?? 0,
136
+ w: Math.max(measured?.w ?? 0, 1),
137
+ h: Math.max(measured?.h ?? 0, 1),
138
+ };
139
+ this.emitNode(this.root, true);
140
+ const svg = this.out.finish(bounds, {
141
+ width: bounds.w,
142
+ height: bounds.h,
143
+ background: this.background,
144
+ });
145
+ return { svg, bounds, report: this.report, boxes: this.boxes };
146
+ }
147
+ emitNode(t, isRoot) {
148
+ this.report.nodesVisited += 1;
149
+ if (this.report.nodesVisited > this.maxVisits) {
150
+ throw new RenderBudgetError(`this render walked more than ${this.maxVisits} nodes — every instance expands into the ` +
151
+ `component it points at, so a page costs far more than its layer count; ` +
152
+ `render a smaller node or raise maxNodes`);
153
+ }
154
+ const node = this.effective(t);
155
+ if (!isVisible(node))
156
+ return;
157
+ const opacity = nodeOpacity(node);
158
+ if (opacity <= 0)
159
+ return;
160
+ const type = nodeType(node);
161
+ const cls = classify(node, isRoot);
162
+ if (cls === 'skip') {
163
+ this.report.unsupported(feat.nodeType(type), t.key);
164
+ return;
165
+ }
166
+ this.report.seen(feat.nodeType(type));
167
+ this.report.nodesDrawn += 1;
168
+ const attrs = {};
169
+ if (!isRoot) {
170
+ // The root is drawn in its own local space; the viewBox carries its position (Pitfall 4).
171
+ const m = fromFigma(obj(node, 'transform'));
172
+ if (!isIdentity(m))
173
+ attrs['transform'] = toAttr(m);
174
+ }
175
+ // A mask's coverage is its geometry, not its appearance: no opacity, blend or effects.
176
+ if (!this.whiteout) {
177
+ if (opacity < 1)
178
+ attrs['opacity'] = opacity;
179
+ attrs['style'] = blendStyle(node, cls === 'container', this.report, t.key);
180
+ attrs['filter'] = this.effectsFor(t, node);
181
+ }
182
+ // Ground rule 6: one node that throws must not abort the whole render. The writer is
183
+ // unwound to the depth it had before this group, so the document stays well-formed.
184
+ const depth = this.out.depth;
185
+ this.out.open('g', attrs);
186
+ try {
187
+ if (isInstance(node)) {
188
+ this.emitInstance(t, node);
189
+ }
190
+ else {
191
+ this.emitOwnContent(t, node, cls, t.children);
192
+ }
193
+ }
194
+ catch (err) {
195
+ if (err instanceof RenderBudgetError)
196
+ throw err; // a budget stop must abort everything
197
+ this.report.unsupported('node-failed', t.key);
198
+ }
199
+ finally {
200
+ this.out.unwindTo(depth);
201
+ }
202
+ if (this.collectBoxes) {
203
+ const box = this.bounds.boundsIn(t, this.root);
204
+ if (box)
205
+ this.boxes.push({ guid: t.key, type, name: str(node, 'name'), box });
206
+ }
207
+ }
208
+ /** Draw order inside a node (F12): own fills, then children, then own strokes. */
209
+ emitOwnContent(t, node, cls, children) {
210
+ if (cls === 'text') {
211
+ this.emitText(t, node);
212
+ }
213
+ else {
214
+ this.emitPaths(t, node, 'fillGeometry', objArr(node, 'fillPaints'));
215
+ }
216
+ if (cls === 'container' && !isBooleanOperation(node)) {
217
+ const clipId = clipsChildren(node) ? this.fillShapeClip(t, node) : undefined;
218
+ if (clipId)
219
+ this.out.open('g', { 'clip-path': `url(#${clipId})` });
220
+ this.emitChildren(children);
221
+ if (clipId)
222
+ this.out.close('g');
223
+ }
224
+ if (cls !== 'text')
225
+ this.emitStrokes(t, node);
226
+ }
227
+ /** The node's `<filter>`, sized from its own content plus the effective node's effects. */
228
+ effectsFor(t, node) {
229
+ if (objArr(node, 'effects').length === 0)
230
+ return undefined;
231
+ const content = this.bounds.contentBounds(t) ?? Exporter.box(node);
232
+ const m = effectMargins(node);
233
+ const region = expandBox(content, m.left, m.top, m.right, m.bottom);
234
+ const id = effectsFilter(node, region, this.out, this.report, t.key, this.defKey('filter', t));
235
+ return id ? `url(#${id})` : undefined;
236
+ }
237
+ /**
238
+ * F11 — a child with `mask: true` masks the siblings ABOVE it (later indices) within the same
239
+ * parent, up to the next sibling that is itself a mask, or the end of the list. The mask layer
240
+ * is never painted as content.
241
+ *
242
+ * Whether a second mask really ends the first one's run could not be measured on the sample;
243
+ * fixture `cf-mask-two-in-one-parent` decides it. This is the only line to change.
244
+ */
245
+ emitChildren(children) {
246
+ let i = 0;
247
+ while (i < children.length) {
248
+ const child = children[i];
249
+ const childNode = this.effective(child);
250
+ if (!isMask(childNode)) {
251
+ this.emitNode(child, false);
252
+ i += 1;
253
+ continue;
254
+ }
255
+ if (!isVisible(childNode)) {
256
+ // A hidden mask masks nothing in Figma, so its run is drawn unmasked.
257
+ this.report.approximated('mask-hidden', child.key);
258
+ i += 1;
259
+ continue;
260
+ }
261
+ let j = i + 1;
262
+ while (j < children.length && !isMask(this.effective(children[j])))
263
+ j += 1;
264
+ const masked = children.slice(i + 1, j);
265
+ if (masked.length > 0) {
266
+ const maskId = this.defineMask(child, childNode, masked);
267
+ this.out.open('g', { mask: `url(#${maskId})` });
268
+ for (const m of masked)
269
+ this.emitNode(m, false);
270
+ this.out.close('g');
271
+ }
272
+ i = j;
273
+ }
274
+ }
275
+ /**
276
+ * §4.10 — every Figma mask type becomes a luminance `<mask>`, which avoids depending on the
277
+ * `mask-type` property. resvg computes mask luminance in sRGB and ignores
278
+ * `color-interpolation` (Appendix E, R7/R8); the attribute is emitted anyway so browsers agree.
279
+ */
280
+ defineMask(maskT, maskNode, masked) {
281
+ const maskType = str(maskNode, 'maskType') ?? 'ALPHA';
282
+ this.report.seen(feat.mask(maskType));
283
+ return this.out.def(this.defKey('mask', maskT), (id) => {
284
+ // Never an unbounded region: the rasterizer allocates it (Pitfall 5).
285
+ let region;
286
+ for (const node of [maskT, ...masked]) {
287
+ const box = this.bounds.renderBounds(node);
288
+ if (!box)
289
+ continue;
290
+ region = unionBox(region, transformBox(fromFigma(obj(this.effective(node), 'transform')), box));
291
+ }
292
+ const r = region ?? { x: 0, y: 0, w: 1, h: 1 };
293
+ const content = this.out.capture(() => {
294
+ if (maskType === 'OUTLINE') {
295
+ // Coverage is where the geometry is, whatever colour it was painted.
296
+ const saved = this.whiteout;
297
+ this.whiteout = true;
298
+ try {
299
+ this.emitNode(maskT, false);
300
+ }
301
+ finally {
302
+ this.whiteout = saved;
303
+ }
304
+ }
305
+ else {
306
+ this.emitNode(maskT, false);
307
+ }
308
+ });
309
+ const body = maskType === 'ALPHA'
310
+ ? `<g filter="url(#${alphaToWhiteFilter(this.out)})">${content}</g>`
311
+ : content;
312
+ return (`<mask id="${id}" maskUnits="userSpaceOnUse" x="${fmt(r.x)}" y="${fmt(r.y)}" ` +
313
+ `width="${fmt(r.w)}" height="${fmt(r.h)}" color-interpolation="sRGB">${body}</mask>`);
314
+ });
315
+ }
316
+ /**
317
+ * F17 — an INSTANCE has no children of its own; its content is the SYMBOL it points at, with
318
+ * this instance's overrides and Figma's per-instance derived geometry applied.
319
+ */
320
+ emitInstance(t, node) {
321
+ if (node['overriddenSymbolID'] !== undefined)
322
+ this.report.seen('instance-swap');
323
+ const resolved = resolveInstance(this.entry.index, node, descend(this.frame ?? new Map(), overrideIdentity(t)), this.props);
324
+ if (!resolved) {
325
+ // No symbol in this file (a library component that was never published locally).
326
+ this.report.unsupported('instance-unresolved', t.key);
327
+ this.emitOwnContent(t, node, 'container', []);
328
+ return;
329
+ }
330
+ if (this.activeSymbols.has(resolved.symbol.key) || this.activeSymbols.size >= MAX_INSTANCE_DEPTH) {
331
+ this.report.unsupported('instance-recursive', t.key);
332
+ return;
333
+ }
334
+ const savedFrame = this.frame;
335
+ const savedProps = this.props;
336
+ const savedScope = this.defScope;
337
+ this.frame = resolved.records;
338
+ this.props = resolved.props;
339
+ this.defScope = `${this.defScope}${t.key}~`;
340
+ this.activeSymbols.add(resolved.symbol.key);
341
+ try {
342
+ // The instance's own box: the symbol root with its override applied, overlaid by whatever
343
+ // the instance itself (as seen in its context) already carries resolved.
344
+ const shape = applyStyles(this.entry.index, instanceShapeNode(node, resolved.symbol, resolved.records));
345
+ this.emitOwnContent(t, shape, 'container', resolved.symbol.children);
346
+ }
347
+ finally {
348
+ this.activeSymbols.delete(resolved.symbol.key);
349
+ this.frame = savedFrame;
350
+ this.props = savedProps;
351
+ this.defScope = savedScope;
352
+ }
353
+ }
354
+ /** One `<path>` per (geometry, visible paint) pair. */
355
+ emitPaths(t, node, field, paints) {
356
+ const geometry = objArr(node, field);
357
+ if (geometry.length === 0) {
358
+ this.emitSynthesised(t, node, field, paints);
359
+ return;
360
+ }
361
+ const box = Exporter.box(node);
362
+ const paintField = field === 'fillGeometry' ? 'fillPaints' : 'strokePaints';
363
+ for (const path of geometry) {
364
+ const raw = this.blob(num(path, 'commandsBlob'));
365
+ if (!raw || raw.length === 0)
366
+ continue;
367
+ let d;
368
+ try {
369
+ const cmds = decodeCommands(raw);
370
+ if (cmds.length === 0)
371
+ continue;
372
+ d = toPathData(cmds);
373
+ }
374
+ catch {
375
+ this.report.unsupported('geometry:corrupt', t.key);
376
+ continue;
377
+ }
378
+ // SVG's default fill-rule is nonzero, so it is only written when the winding is ODD.
379
+ const rule = str(path, 'windingRule') === 'ODD' ? 'evenodd' : undefined;
380
+ const styled = runPaints(this.entry.index, node, num(path, 'styleID'), paintField);
381
+ for (const paint of styled ?? paints) {
382
+ const attrs = paintAttrs(paint, box, this.env, t.key);
383
+ if (!attrs)
384
+ continue;
385
+ this.out.element('path', { d, 'fill-rule': rule, ...attrs });
386
+ }
387
+ }
388
+ }
389
+ /**
390
+ * §4.14 — this file's own nodes always carry derived geometry, but files written by other
391
+ * tools may not. A rectangle or ellipse can be rebuilt from `size` and its corner radii;
392
+ * anything else is reported rather than guessed at.
393
+ */
394
+ emitSynthesised(t, node, field, paints) {
395
+ const visible = paints.filter((p) => bool(p, 'visible') !== false);
396
+ if (visible.length === 0)
397
+ return;
398
+ if (field === 'strokeGeometry') {
399
+ this.report.unsupported('stroke-without-geometry', t.key);
400
+ return;
401
+ }
402
+ const type = nodeType(node);
403
+ const size = nodeSize(node);
404
+ if (size.w <= 0 || size.h <= 0)
405
+ return;
406
+ let cmds;
407
+ if (type === 'ELLIPSE') {
408
+ cmds = ellipseCommands(size.w, size.h);
409
+ }
410
+ else if (RECTANGULAR.has(type)) {
411
+ cmds = roundedRectCommands(size.w, size.h, cornerRadii(node));
412
+ }
413
+ else {
414
+ this.report.unsupported('vector-without-geometry', t.key);
415
+ return;
416
+ }
417
+ if (cmds.length === 0)
418
+ return;
419
+ this.report.approximated('geometry:synthesised', t.key);
420
+ const d = toPathData(cmds);
421
+ const box = Exporter.box(node);
422
+ for (const paint of visible) {
423
+ const attrs = paintAttrs(paint, box, this.env, t.key);
424
+ if (attrs)
425
+ this.out.element('path', { d, ...attrs });
426
+ }
427
+ }
428
+ /**
429
+ * Strokes, with the alignment clip Figma applies at render time (F16).
430
+ *
431
+ * `strokeGeometry` for an INSIDE or OUTSIDE stroke is a band of DOUBLE the weight straddling
432
+ * the shape edge; Figma keeps the half that falls inside (INSIDE) or outside (OUTSIDE) the
433
+ * fill shape. Drawing it unclipped paints a double-width border that bleeds past the node —
434
+ * on this sample that would be wrong on 9 055 nodes. CENTER geometry is already final.
435
+ */
436
+ emitStrokes(t, node) {
437
+ if (objArr(node, 'strokeGeometry').length === 0)
438
+ return;
439
+ const align = strokeAlign(node);
440
+ this.report.seen(feat.strokeAlign(align));
441
+ const dashes = node['dashPattern'];
442
+ if (Array.isArray(dashes) && dashes.length)
443
+ this.report.seen('stroke-dashed');
444
+ let wrapped = false;
445
+ if (align === 'INSIDE' && hasFillGeometry(node)) {
446
+ this.out.open('g', { 'clip-path': `url(#${this.fillShapeClip(t, node)})` });
447
+ wrapped = true;
448
+ }
449
+ else if (align === 'OUTSIDE' && hasFillGeometry(node)) {
450
+ this.out.open('g', { mask: `url(#${this.outsideStrokeMask(t, node)})` });
451
+ wrapped = true;
452
+ }
453
+ else if (align === 'OFFSET') {
454
+ // Not present in the sample; drawn as CENTER until a fixture pins the offset down.
455
+ this.report.approximated(feat.strokeAlign(align), t.key);
456
+ }
457
+ this.emitPaths(t, node, 'strokeGeometry', objArr(node, 'strokePaints'));
458
+ if (wrapped)
459
+ this.out.close('g');
460
+ }
461
+ /** The node's fill shape as a `<clipPath>`; shared by frame clipping and INSIDE strokes. */
462
+ fillShapeClip(t, node) {
463
+ return this.out.def(this.defKey('clip', t), (id) => {
464
+ const parts = this.shapePaths(node, 'clip');
465
+ if (parts.length === 0) {
466
+ // No geometry, or geometry dropped as stale (F20): the box with its corner radii.
467
+ const size = nodeSize(node);
468
+ const cmds = roundedRectCommands(size.w, size.h, cornerRadii(node));
469
+ parts.push(cmds.length
470
+ ? `<path d="${toPathData(cmds)}"/>`
471
+ : `<rect x="0" y="0" width="${fmt(size.w)}" height="${fmt(size.h)}"/>`);
472
+ }
473
+ return `<clipPath id="${id}" clipPathUnits="userSpaceOnUse">${parts.join('')}</clipPath>`;
474
+ });
475
+ }
476
+ /**
477
+ * The complement of the fill shape, as a luminance mask: white over the node's content box,
478
+ * black over the shape. A mask rather than an even-odd clip path, because combining an
479
+ * arbitrary winding rule with an enclosing rectangle is not reliably the complement.
480
+ */
481
+ outsideStrokeMask(t, node) {
482
+ return this.out.def(this.defKey('outside', t), (id) => {
483
+ const region = this.bounds.contentBounds(t) ?? Exporter.box(node);
484
+ const parts = [
485
+ `<rect x="${fmt(region.x)}" y="${fmt(region.y)}" width="${fmt(region.w)}" ` +
486
+ `height="${fmt(region.h)}" fill="#ffffff"/>`,
487
+ ...this.shapePaths(node, 'black'),
488
+ ];
489
+ return (`<mask id="${id}" maskUnits="userSpaceOnUse" x="${fmt(region.x)}" y="${fmt(region.y)}" ` +
490
+ `width="${fmt(region.w)}" height="${fmt(region.h)}">${parts.join('')}</mask>`);
491
+ });
492
+ }
493
+ /**
494
+ * The fill geometry as `<path>` markup. `clip` emits `clip-rule`, which is what a `<clipPath>`
495
+ * child honours — resvg silently ignores `fill-rule` there (Appendix E, R11).
496
+ */
497
+ shapePaths(node, mode) {
498
+ const parts = [];
499
+ for (const path of objArr(node, 'fillGeometry')) {
500
+ const raw = this.blob(num(path, 'commandsBlob'));
501
+ if (!raw || raw.length === 0)
502
+ continue;
503
+ try {
504
+ const cmds = decodeCommands(raw);
505
+ if (cmds.length === 0)
506
+ continue;
507
+ const odd = str(path, 'windingRule') === 'ODD';
508
+ const d = toPathData(cmds);
509
+ parts.push(mode === 'clip'
510
+ ? `<path d="${d}"${odd ? ' clip-rule="evenodd"' : ''}/>`
511
+ : `<path d="${d}" fill="#000000"${odd ? ' fill-rule="evenodd"' : ''}/>`);
512
+ }
513
+ catch {
514
+ // reported by emitPaths for the same node
515
+ }
516
+ }
517
+ return parts;
518
+ }
519
+ /**
520
+ * §4.8 — glyph outlines and decoration rects. Glyph coordinates are baked into node-local
521
+ * pixels here, so gradient and image fills on text go through the ordinary paint path.
522
+ */
523
+ emitText(t, node) {
524
+ if (this.staleOutlines.has(node)) {
525
+ // A text property gave this node new words, but no record supplied outlines for them;
526
+ // the symbol's glyphs would spell the wrong thing (F18).
527
+ this.report.unsupported('text-property-without-outlines', t.key);
528
+ return;
529
+ }
530
+ const draw = buildText(node, (i) => this.blob(i), this.report, t.key);
531
+ if (!draw) {
532
+ if (hasCharactersWithoutOutlines(node)) {
533
+ this.report.unsupported('text-without-outlines', t.key);
534
+ }
535
+ return;
536
+ }
537
+ const box = Exporter.box(node);
538
+ const own = objArr(node, 'fillPaints');
539
+ const paintsFor = (styleID) => runPaints(this.entry.index, node, styleID, 'fillPaints') ?? own;
540
+ for (const run of draw.glyphs) {
541
+ for (const paint of paintsFor(run.styleID)) {
542
+ const attrs = paintAttrs(paint, box, this.env, t.key);
543
+ if (attrs)
544
+ this.out.element('path', { d: run.d, ...attrs });
545
+ }
546
+ }
547
+ if (draw.decorations.length)
548
+ this.report.seen('text-decoration');
549
+ for (const decoration of draw.decorations) {
550
+ for (const paint of paintsFor(decoration.styleID)) {
551
+ const attrs = paintAttrs(paint, box, this.env, t.key);
552
+ if (!attrs)
553
+ continue;
554
+ for (const rect of decoration.rects) {
555
+ this.out.element('rect', {
556
+ x: rect.x,
557
+ y: rect.y,
558
+ width: rect.w,
559
+ height: rect.h,
560
+ ...attrs,
561
+ });
562
+ }
563
+ }
564
+ }
565
+ // Text strokes are not outlined into strokeGeometry (0 such nodes in the sample).
566
+ if (objArr(node, 'strokePaints').length > 0 && objArr(node, 'strokeGeometry').length === 0) {
567
+ this.report.unsupported('text-stroke', t.key);
568
+ }
569
+ }
570
+ }
571
+ export function exportSubtree(entry, root, opts = {}) {
572
+ return new Exporter(entry, root, opts).run();
573
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * `renderNode` — the entry point used by the tool, the CLI and the visual tester.
3
+ *
4
+ * Resolves a guid, exports the subtree to SVG (§4), decides the effective scale (§4.13) and,
5
+ * when a rasterizer is installed, produces PNG bytes. Nothing here touches the network and
6
+ * nothing is ever written back into the .fig.
7
+ */
8
+ import type { CacheEntry } from '../cache.js';
9
+ import { type NodeBox } from './export.js';
10
+ import type { Box } from './matrix.js';
11
+ import type { RenderReport } from './report.js';
12
+ export declare const DEFAULT_SCALE = 2;
13
+ export declare const DEFAULT_MAX_SIZE = 1568;
14
+ export declare const HARD_MAX_SIZE = 4096;
15
+ export interface RenderOptions {
16
+ readonly scale?: number;
17
+ readonly maxSize?: number;
18
+ readonly background?: 'transparent' | 'page';
19
+ readonly maxNodes?: number;
20
+ /** 'svg' skips rasterization entirely. Default 'png', which falls back to SVG when absent. */
21
+ readonly format?: 'png' | 'svg';
22
+ /** Record every drawn node's box in root-local units (used by the tester's attribution). */
23
+ readonly collectBoxes?: boolean;
24
+ }
25
+ export interface RenderResult {
26
+ readonly svg: string;
27
+ readonly png?: Uint8Array;
28
+ /** Output pixel size: `round(bounds × effective scale)`. */
29
+ readonly width: number;
30
+ readonly height: number;
31
+ readonly bounds: Box;
32
+ readonly report: RenderReport;
33
+ readonly boxes?: NodeBox[];
34
+ /** True when PNG was requested but no rasterizer is installed. */
35
+ readonly rasterizerMissing: boolean;
36
+ }
37
+ export declare function renderNode(entry: CacheEntry, guid: string, opts?: RenderOptions): Promise<RenderResult>;
38
+ export { rasterizer, rasterize } from './raster.js';
39
+ export type { NodeBox } from './export.js';
40
+ export type { RenderReport } from './report.js';
41
+ export type { Box } from './matrix.js';
42
+ //# sourceMappingURL=index.d.ts.map