openfig-mcp 0.1.0 → 0.1.1

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.
package/src/html.mjs CHANGED
@@ -1,110 +1,110 @@
1
- // Spec tree -> HTML + deduplicated CSS classes.
2
- import { slug } from './util.mjs';
3
- import { AUTO_NAME } from './convert.mjs';
4
-
5
- const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
6
- const decl = o => Object.entries(o || {}).filter(([k, v]) => v !== undefined && v !== null && !k.startsWith('/*')).map(([k, v]) => `${k}: ${v}`);
7
- const inline = o => decl(o).join('; ');
8
-
9
- /**
10
- * @returns {{ html: string, css: string, classCount: number }}
11
- */
12
- export function toHtml(spec, { states = [], maxDepth = Infinity, collapsedNote = true } = {}) {
13
- const classes = new Map(); // css text -> class
14
- const used = new Set();
15
- const comments = new Map();
16
- function classFor(spec) {
17
- const body = decl(spec.style).join('; ');
18
- if (!body) return null;
19
- if (classes.has(body)) return classes.get(body);
20
- const base = (spec.component && !AUTO_NAME.test(spec.component.name) ? spec.component.name : !AUTO_NAME.test(spec.name) && spec.type !== 'TEXT' ? spec.name : spec.type === 'TEXT' ? 'text' : spec.type.toLowerCase()).slice(0, 32);
21
- let name = slug(base) || 'el', i = 2;
22
- if (/^\d/.test(name)) name = 'n-' + name;
23
- while (used.has(name)) name = `${slug(base) || 'el'}-${i++}`;
24
- used.add(name); classes.set(body, name);
25
- const notes = Object.entries(spec.style || {}).filter(([k]) => k.startsWith('/*')).map(([k, v]) => `${k.slice(3, -3).trim()}: ${v}`);
26
- if (notes.length) comments.set(name, notes.join('; '));
27
- return name;
28
- }
29
- function attrs(s, cls) {
30
- const a = [];
31
- const c = [cls, s.textStyle?.className].filter(Boolean).join(' ');
32
- if (c) a.push(`class="${c}"`);
33
- a.push(`data-id="${s.id}"`);
34
- a.push(`data-name="${esc(s.name)}"`);
35
- if (s.component) {
36
- a.push(`data-component="${esc(s.component.name)}"`);
37
- if (s.component.variant) a.push(`data-variant="${esc(Object.entries(s.component.variant).map(([k, v]) => `${k}=${v}`).join(', '))}"`);
38
- }
39
- if (s.interactions) {
40
- // compact hints, e.g. data-on-click="NAVIGATE Dashboard (1:23)"; the full list is in spec.json / DESIGN.md
41
- const byTrigger = new Map();
42
- for (const i of s.interactions) {
43
- if (i.action === 'SWAP_STATE' && (i.trigger === 'ON_HOVER' || i.trigger === 'ON_PRESS')) continue; // expressed as CSS
44
- const k = `data-on-${(i.trigger === 'ON_KEY_DOWN' ? 'key' : i.trigger === 'AFTER_TIMEOUT' ? 'timeout' : i.trigger.replace(/^ON_/, '')).toLowerCase().replace(/_/g, '-')}`;
45
- const v = `${i.action}${i.target ? ` ${i.target.name} (${i.target.id})` : i.url ? ` ${i.url}` : i.variable ? ` ${i.variable}=${i.value}` : ''}${i.keys ? ` [${i.keys.join('+')}]` : ''}`;
46
- byTrigger.set(k, byTrigger.has(k) ? `${byTrigger.get(k)}; ${v}` : v);
47
- }
48
- for (const [k, v] of byTrigger) a.push(`${k}="${esc(v)}"`);
49
- }
50
- if (s.scroll) a.push(`data-scroll="${s.scroll}"`);
51
- const st = inline(s.box);
52
- if (st) a.push(`style="${esc(st)}"`);
53
- return a.join(' ');
54
- }
55
- function render(s, depth, indent) {
56
- const pad = ' '.repeat(indent);
57
- const cls = classFor(s);
58
- const at = attrs(s, cls);
59
- if (s.asset) return `${pad}<img src="${s.asset}" alt="${esc(s.component?.name || s.name)}" ${at}>`;
60
- if (s.image) return `${pad}<img src="${s.image.src}" alt="${esc(s.image.alt || s.name)}" ${at.replace(/style="/, `style="object-fit: ${s.image.fit}; `)}>`;
61
- if (s.type === 'TEXT') {
62
- const content = s.runs ? s.runs.map(r => r.css && Object.keys(r.css).length ? `<span style="${esc(inline(r.css))}">${esc(r.text)}</span>` : esc(r.text)).join('') : esc(s.text);
63
- const tag = s.href ? 'a' : 'p';
64
- const href = s.href ? ` href="${esc(s.href)}"` : '';
65
- const inner = s.style?.display === 'flex' ? `<span>${content}</span>` : content;
66
- return `${pad}<${tag}${href} ${at}>${inner}</${tag}>`;
67
- }
68
- const isButton = s.component && /button|btn|cta/i.test(s.component.name) && !(s.children || []).some(c => c.component && /button|btn/i.test(c.component.name));
69
- const tag = isButton ? 'button' : 'div';
70
- if (!s.children?.length) return `${pad}<${tag} ${at}></${tag}>`;
71
- if (depth >= maxDepth) {
72
- const count = countNodes(s) - 1;
73
- return `${pad}<${tag} ${at}>${collapsedNote ? `<!-- ${count} nested nodes omitted: call get_frame with frame="${s.id}" -->` : ''}</${tag}>`;
74
- }
75
- return `${pad}<${tag} ${at}>\n${s.children.map(c => render(c, depth + 1, indent + 1)).join('\n')}\n${pad}</${tag}>`;
76
- }
77
- const html = render(spec, 0, 0);
78
- const css = [];
79
- css.push(`/* Reset so semantic tags don't add styles (zero specificity) */\n:where(button) { font: inherit; color: inherit; background: none; border: 0; padding: 0; text-align: inherit; cursor: pointer; }\n:where(p) { margin: 0; }\n:where(*) { box-sizing: border-box; }`);
80
- for (const [body, name] of classes) css.push(`.${name} { ${body}; }${comments.has(name) ? ` /* ${comments.get(name)} */` : ''}`);
81
- const stateCss = statesToCss(states);
82
- if (stateCss) css.push('\n/* ---- Interactive states (from Figma variant interactions) ---- */\n' + stateCss);
83
- return { html, css: css.join('\n'), classCount: classes.size };
84
- }
85
-
86
- export function countNodes(s) { return 1 + (s.children || []).reduce((a, c) => a + countNodes(c), 0); }
87
-
88
- function attrSel(v) { return Object.entries(v || {}).map(([k, x]) => `${k}=${x}`).join(', '); }
89
- /** Escape a value for use inside a double-quoted CSS attribute selector. */
90
- const cssStr = v => String(v).replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\a ');
91
-
92
- export function statesToCss(states) {
93
- const out = [];
94
- for (const s of states) {
95
- if (!s.pseudo?.length) continue;
96
- const base = `[data-component="${cssStr(s.component)}"][data-variant="${cssStr(attrSel(s.from))}"]`;
97
- const label = `${s.component}: ${attrSel(s.from)} → ${attrSel(s.to)} (${s.source === 'variant-naming' ? 'from variant naming' : `Figma ${s.triggerText || s.trigger}`})`;
98
- out.push(`/* ${label.replace(/\*\//g, '* /')} */`);
99
- if (s.durationMs && s.transition && s.transition !== 'INSTANT_TRANSITION') out.push(`${base}, ${base} * { transition: all ${s.durationMs}ms ${s.easing || 'ease'}; } /* Figma: ${s.transition} */`);
100
- const sels = suffix => s.pseudo.map(p => `${base}${p}${suffix}`).join(', ');
101
- for (const [path, changes] of Object.entries(s.changes)) {
102
- const decls = decl(changes).join('; ');
103
- const suffix = path === '(root)' ? '' : ' ' + path.split(' > ').map(p => `[data-name="${cssStr(p.replace(/\[\d+\]$/, ''))}"]`).join(' ');
104
- if (decls) out.push(`${sels(suffix)} { ${decls}; }`);
105
- }
106
- if (s.shows) out.push(`/* shows: ${s.shows.join(', ').replace(/\*\//g, '* /')} (only exists in the target variant: render it conditionally) */`);
107
- for (const h of s.hides || []) out.push(`${sels(' ' + h.split(' > ').map(p => `[data-name="${cssStr(p.replace(/\[\d+\]$/, ''))}"]`).join(' '))} { display: none; } /* hidden in target state */`);
108
- }
109
- return out.join('\n');
110
- }
1
+ // Spec tree -> HTML + deduplicated CSS classes.
2
+ import { slug } from './util.mjs';
3
+ import { AUTO_NAME } from './convert.mjs';
4
+
5
+ const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
6
+ const decl = o => Object.entries(o || {}).filter(([k, v]) => v !== undefined && v !== null && !k.startsWith('/*')).map(([k, v]) => `${k}: ${v}`);
7
+ const inline = o => decl(o).join('; ');
8
+
9
+ /**
10
+ * @returns {{ html: string, css: string, classCount: number }}
11
+ */
12
+ export function toHtml(spec, { states = [], maxDepth = Infinity, collapsedNote = true } = {}) {
13
+ const classes = new Map(); // css text -> class
14
+ const used = new Set();
15
+ const comments = new Map();
16
+ function classFor(spec) {
17
+ const body = decl(spec.style).join('; ');
18
+ if (!body) return null;
19
+ if (classes.has(body)) return classes.get(body);
20
+ const base = (spec.component && !AUTO_NAME.test(spec.component.name) ? spec.component.name : !AUTO_NAME.test(spec.name) && spec.type !== 'TEXT' ? spec.name : spec.type === 'TEXT' ? 'text' : spec.type.toLowerCase()).slice(0, 32);
21
+ let name = slug(base) || 'el', i = 2;
22
+ if (/^\d/.test(name)) name = 'n-' + name;
23
+ while (used.has(name)) name = `${slug(base) || 'el'}-${i++}`;
24
+ used.add(name); classes.set(body, name);
25
+ const notes = Object.entries(spec.style || {}).filter(([k]) => k.startsWith('/*')).map(([k, v]) => `${k.slice(3, -3).trim()}: ${v}`);
26
+ if (notes.length) comments.set(name, notes.join('; '));
27
+ return name;
28
+ }
29
+ function attrs(s, cls) {
30
+ const a = [];
31
+ const c = [cls, s.textStyle?.className].filter(Boolean).join(' ');
32
+ if (c) a.push(`class="${c}"`);
33
+ a.push(`data-id="${s.id}"`);
34
+ a.push(`data-name="${esc(s.name)}"`);
35
+ if (s.component) {
36
+ a.push(`data-component="${esc(s.component.name)}"`);
37
+ if (s.component.variant) a.push(`data-variant="${esc(Object.entries(s.component.variant).map(([k, v]) => `${k}=${v}`).join(', '))}"`);
38
+ }
39
+ if (s.interactions) {
40
+ // compact hints, e.g. data-on-click="NAVIGATE Dashboard (1:23)"; the full list is in spec.json / DESIGN.md
41
+ const byTrigger = new Map();
42
+ for (const i of s.interactions) {
43
+ if (i.action === 'SWAP_STATE' && (i.trigger === 'ON_HOVER' || i.trigger === 'ON_PRESS')) continue; // expressed as CSS
44
+ const k = `data-on-${(i.trigger === 'ON_KEY_DOWN' ? 'key' : i.trigger === 'AFTER_TIMEOUT' ? 'timeout' : i.trigger.replace(/^ON_/, '')).toLowerCase().replace(/_/g, '-')}`;
45
+ const v = `${i.action}${i.target ? ` ${i.target.name} (${i.target.id})` : i.url ? ` ${i.url}` : i.variable ? ` ${i.variable}=${i.value}` : ''}${i.keys ? ` [${i.keys.join('+')}]` : ''}`;
46
+ byTrigger.set(k, byTrigger.has(k) ? `${byTrigger.get(k)}; ${v}` : v);
47
+ }
48
+ for (const [k, v] of byTrigger) a.push(`${k}="${esc(v)}"`);
49
+ }
50
+ if (s.scroll) a.push(`data-scroll="${s.scroll}"`);
51
+ const st = inline(s.box);
52
+ if (st) a.push(`style="${esc(st)}"`);
53
+ return a.join(' ');
54
+ }
55
+ function render(s, depth, indent) {
56
+ const pad = ' '.repeat(indent);
57
+ const cls = classFor(s);
58
+ const at = attrs(s, cls);
59
+ if (s.asset) return `${pad}<img src="${s.asset}" alt="${esc(s.component?.name || s.name)}" ${at}>`;
60
+ if (s.image) return `${pad}<img src="${s.image.src}" alt="${esc(s.image.alt || s.name)}" ${at.replace(/style="/, `style="object-fit: ${s.image.fit}; `)}>`;
61
+ if (s.type === 'TEXT') {
62
+ const content = s.runs ? s.runs.map(r => r.css && Object.keys(r.css).length ? `<span style="${esc(inline(r.css))}">${esc(r.text)}</span>` : esc(r.text)).join('') : esc(s.text);
63
+ const tag = s.href ? 'a' : 'p';
64
+ const href = s.href ? ` href="${esc(s.href)}"` : '';
65
+ const inner = s.style?.display === 'flex' ? `<span>${content}</span>` : content;
66
+ return `${pad}<${tag}${href} ${at}>${inner}</${tag}>`;
67
+ }
68
+ const isButton = s.component && /button|btn|cta/i.test(s.component.name) && !(s.children || []).some(c => c.component && /button|btn/i.test(c.component.name));
69
+ const tag = isButton ? 'button' : 'div';
70
+ if (!s.children?.length) return `${pad}<${tag} ${at}></${tag}>`;
71
+ if (depth >= maxDepth) {
72
+ const count = countNodes(s) - 1;
73
+ return `${pad}<${tag} ${at}>${collapsedNote ? `<!-- ${count} nested nodes omitted: call get_frame with frame="${s.id}" -->` : ''}</${tag}>`;
74
+ }
75
+ return `${pad}<${tag} ${at}>\n${s.children.map(c => render(c, depth + 1, indent + 1)).join('\n')}\n${pad}</${tag}>`;
76
+ }
77
+ const html = render(spec, 0, 0);
78
+ const css = [];
79
+ css.push(`/* Reset so semantic tags don't add styles (zero specificity) */\n:where(button) { font: inherit; color: inherit; background: none; border: 0; padding: 0; text-align: inherit; cursor: pointer; }\n:where(p) { margin: 0; }\n:where(*) { box-sizing: border-box; }`);
80
+ for (const [body, name] of classes) css.push(`.${name} { ${body}; }${comments.has(name) ? ` /* ${comments.get(name)} */` : ''}`);
81
+ const stateCss = statesToCss(states);
82
+ if (stateCss) css.push('\n/* ---- Interactive states (from Figma variant interactions) ---- */\n' + stateCss);
83
+ return { html, css: css.join('\n'), classCount: classes.size };
84
+ }
85
+
86
+ export function countNodes(s) { return 1 + (s.children || []).reduce((a, c) => a + countNodes(c), 0); }
87
+
88
+ function attrSel(v) { return Object.entries(v || {}).map(([k, x]) => `${k}=${x}`).join(', '); }
89
+ /** Escape a value for use inside a double-quoted CSS attribute selector. */
90
+ const cssStr = v => String(v).replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\a ');
91
+
92
+ export function statesToCss(states) {
93
+ const out = [];
94
+ for (const s of states) {
95
+ if (!s.pseudo?.length) continue;
96
+ const base = `[data-component="${cssStr(s.component)}"][data-variant="${cssStr(attrSel(s.from))}"]`;
97
+ const label = `${s.component}: ${attrSel(s.from)} → ${attrSel(s.to)} (${s.source === 'variant-naming' ? 'from variant naming' : `Figma ${s.triggerText || s.trigger}`})`;
98
+ out.push(`/* ${label.replace(/\*\//g, '* /')} */`);
99
+ if (s.durationMs && s.transition && s.transition !== 'INSTANT_TRANSITION') out.push(`${base}, ${base} * { transition: all ${s.durationMs}ms ${s.easing || 'ease'}; } /* Figma: ${s.transition} */`);
100
+ const sels = suffix => s.pseudo.map(p => `${base}${p}${suffix}`).join(', ');
101
+ for (const [path, changes] of Object.entries(s.changes)) {
102
+ const decls = decl(changes).join('; ');
103
+ const suffix = path === '(root)' ? '' : ' ' + path.split(' > ').map(p => `[data-name="${cssStr(p.replace(/\[\d+\]$/, ''))}"]`).join(' ');
104
+ if (decls) out.push(`${sels(suffix)} { ${decls}; }`);
105
+ }
106
+ if (s.shows) out.push(`/* shows: ${s.shows.join(', ').replace(/\*\//g, '* /')} (only exists in the target variant: render it conditionally) */`);
107
+ for (const h of s.hides || []) out.push(`${sels(' ' + h.split(' > ').map(p => `[data-name="${cssStr(p.replace(/\[\d+\]$/, ''))}"]`).join(' '))} { display: none; } /* hidden in target state */`);
108
+ }
109
+ return out.join('\n');
110
+ }
package/src/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
- export { FigFile, summarize } from './api.mjs';
2
- export { loadFig, FigDoc } from './doc.mjs';
3
- export { Converter, variantStates, animationLoops } from './convert.mjs';
4
- export { toHtml, statesToCss } from './html.mjs';
5
- export { TokenRegistry } from './tokens.mjs';
6
- export { nodeToSvg, svgToPng } from './render.mjs';
7
- export { fontReport, fontWarning } from './fonts.mjs';
8
- export { createServer } from './server.mjs';
1
+ export { FigFile, summarize } from './api.mjs';
2
+ export { loadFig, FigDoc } from './doc.mjs';
3
+ export { Converter, variantStates, animationLoops } from './convert.mjs';
4
+ export { toHtml, statesToCss } from './html.mjs';
5
+ export { TokenRegistry } from './tokens.mjs';
6
+ export { nodeToSvg, svgToPng } from './render.mjs';
7
+ export { fontReport, fontWarning } from './fonts.mjs';
8
+ export { createServer } from './server.mjs';
package/src/render.mjs CHANGED
@@ -1,85 +1,85 @@
1
- // Rendering nodes to SVG / PNG: openfig's SVG builder (vendored, see src/vendor) + resvg-wasm.
2
- import { createRequire } from 'module';
3
- import { dirname, join } from 'path';
4
- import { readFileSync } from 'fs';
5
- import { initWasm, Resvg } from '@resvg/resvg-wasm';
6
- import { idOf } from './util.mjs';
7
- import { frameToSvg } from './vendor/svg-builder.mjs';
8
- import { previewFonts, fallbackFamily } from './fonts.mjs';
9
-
10
- const require = createRequire(import.meta.url);
11
-
12
- let wasmReady = null;
13
- function ensureWasm() {
14
- if (!wasmReady) {
15
- const dir = dirname(require.resolve('@resvg/resvg-wasm'));
16
- wasmReady = initWasm(readFileSync(join(dir, 'index_bg.wasm'))).catch(e => { if (!/already/i.test(e.message)) throw e; });
17
- }
18
- return wasmReady;
19
- }
20
-
21
- let baseFonts = null;
22
- /** Fallback font for previews: a common UI font already installed on the system. */
23
- async function base() {
24
- if (!baseFonts) baseFonts = previewFonts([]).buffers; // system fallback font (no downloads)
25
- return baseFonts;
26
- }
27
-
28
- /**
29
- * Render any node (frame, instance, vector, …) to a standalone SVG string.
30
- * Instances are materialized first (overrides, component props, hidden layers resolved).
31
- * @param {object} [opts.raw] the raw node when `node` is an override-applied copy
32
- * @param {object} [opts.ctx] override context of the node (when it lives inside an instance)
33
- */
34
- // openfig draws a dashed magenta debug box for nodes it can't paint (e.g. a STAR without fills);
35
- // those boxes are not part of the design (and can crash resvg), so strip them.
36
- const PLACEHOLDER = /<g transform="[^"]*"><rect [^>]*stroke="#ff00ff"[^>]*\/><!-- [A-Z_?]* --><\/g>/g;
37
- export async function nodeToSvg(doc, node, opts = {}) { return (await nodeToSvgRaw(doc, node, opts)).replace(PLACEHOLDER, ''); }
38
-
39
- async function nodeToSvgRaw(doc, node, { raw, ctx, conv } = {}) {
40
- const { Converter } = await import('./convert.mjs');
41
- const c = conv || new Converter(doc);
42
- const { root, cleanup } = c.materialize(raw || node, ctx);
43
- try {
44
- const hasKids = doc.deck.getChildren(idOf(root)).length > 0;
45
- if (['FRAME', 'SYMBOL', 'SECTION'].includes(root.type) && hasKids) {
46
- return frameToSvg(doc.deck, { ...root, transform: undefined });
47
- }
48
- // frameToSvg renders a node's *children*, so wrap leaf nodes in a synthetic frame.
49
- const wid = { sessionID: 999999991, localID: ++Converter.seq };
50
- const key = `${wid.sessionID}:${wid.localID}`;
51
- const wrapper = { guid: wid, type: 'FRAME', name: '__wrapper', size: root.size, fillPaints: [], frameMaskDisabled: true };
52
- doc.deck.childrenMap.set(key, [{ ...root, transform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }, parentIndex: { guid: wid, position: '!' } }]);
53
- try {
54
- return frameToSvg(doc.deck, wrapper).replace(/<rect x="0" y="0" width="[\d.]+" height="[\d.]+" fill="white"\/>/, '');
55
- } finally { doc.deck.childrenMap.delete(key); }
56
- } finally { cleanup(); }
57
- }
58
-
59
- /** SVG string -> PNG bytes. */
60
- export async function svgToPng(svg, { scale = 1, maxDim, fonts = [], background } = {}) {
61
- await ensureWasm();
62
- fonts = [...(await base()), ...fonts];
63
- const m = svg.match(/<svg[^>]*width="([\d.]+)"[^>]*height="([\d.]+)"/);
64
- const w = m ? +m[1] : 1000, h = m ? +m[2] : 1000;
65
- let s = scale;
66
- if (maxDim && Math.max(w, h) * s > maxDim) s = maxDim / Math.max(w, h);
67
- const attempts = [svg, svg.replace(/ filter="url\([^)]*\)"/g, ''), svg.replace(/ filter="url\([^)]*\)"/g, '').replace(/ mask="url\([^)]*\)"/g, '')];
68
- let lastErr;
69
- for (const attempt of attempts) {
70
- try { return render(attempt, s, fonts, background); } catch (e) { lastErr = e; }
71
- }
72
- throw lastErr;
73
- }
74
-
75
- function render(svg, s, fonts, background) {
76
- const resvg = new Resvg(svg, {
77
- background,
78
- fitTo: s !== 1 ? { mode: 'zoom', value: s } : { mode: 'original' },
79
- font: { fontBuffers: fonts.map(b => new Uint8Array(b)), loadSystemFonts: false, defaultFontFamily: fallbackFamily() || 'Arial', sansSerifFamily: fallbackFamily() || 'Arial' },
80
- });
81
- const img = resvg.render();
82
- const png = img.asPng();
83
- img.free(); resvg.free();
84
- return Buffer.from(png);
85
- }
1
+ // Rendering nodes to SVG / PNG: openfig's SVG builder (vendored, see src/vendor) + resvg-wasm.
2
+ import { createRequire } from 'module';
3
+ import { dirname, join } from 'path';
4
+ import { readFileSync } from 'fs';
5
+ import { initWasm, Resvg } from '@resvg/resvg-wasm';
6
+ import { idOf } from './util.mjs';
7
+ import { frameToSvg } from './vendor/svg-builder.mjs';
8
+ import { previewFonts, fallbackFamily } from './fonts.mjs';
9
+
10
+ const require = createRequire(import.meta.url);
11
+
12
+ let wasmReady = null;
13
+ function ensureWasm() {
14
+ if (!wasmReady) {
15
+ const dir = dirname(require.resolve('@resvg/resvg-wasm'));
16
+ wasmReady = initWasm(readFileSync(join(dir, 'index_bg.wasm'))).catch(e => { if (!/already/i.test(e.message)) throw e; });
17
+ }
18
+ return wasmReady;
19
+ }
20
+
21
+ let baseFonts = null;
22
+ /** Fallback font for previews: a common UI font already installed on the system. */
23
+ async function base() {
24
+ if (!baseFonts) baseFonts = previewFonts([]).buffers; // system fallback font (no downloads)
25
+ return baseFonts;
26
+ }
27
+
28
+ /**
29
+ * Render any node (frame, instance, vector, …) to a standalone SVG string.
30
+ * Instances are materialized first (overrides, component props, hidden layers resolved).
31
+ * @param {object} [opts.raw] the raw node when `node` is an override-applied copy
32
+ * @param {object} [opts.ctx] override context of the node (when it lives inside an instance)
33
+ */
34
+ // openfig draws a dashed magenta debug box for nodes it can't paint (e.g. a STAR without fills);
35
+ // those boxes are not part of the design (and can crash resvg), so strip them.
36
+ const PLACEHOLDER = /<g transform="[^"]*"><rect [^>]*stroke="#ff00ff"[^>]*\/><!-- [A-Z_?]* --><\/g>/g;
37
+ export async function nodeToSvg(doc, node, opts = {}) { return (await nodeToSvgRaw(doc, node, opts)).replace(PLACEHOLDER, ''); }
38
+
39
+ async function nodeToSvgRaw(doc, node, { raw, ctx, conv } = {}) {
40
+ const { Converter } = await import('./convert.mjs');
41
+ const c = conv || new Converter(doc);
42
+ const { root, cleanup } = c.materialize(raw || node, ctx);
43
+ try {
44
+ const hasKids = doc.deck.getChildren(idOf(root)).length > 0;
45
+ if (['FRAME', 'SYMBOL', 'SECTION'].includes(root.type) && hasKids) {
46
+ return frameToSvg(doc.deck, { ...root, transform: undefined });
47
+ }
48
+ // frameToSvg renders a node's *children*, so wrap leaf nodes in a synthetic frame.
49
+ const wid = { sessionID: 999999991, localID: ++Converter.seq };
50
+ const key = `${wid.sessionID}:${wid.localID}`;
51
+ const wrapper = { guid: wid, type: 'FRAME', name: '__wrapper', size: root.size, fillPaints: [], frameMaskDisabled: true };
52
+ doc.deck.childrenMap.set(key, [{ ...root, transform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }, parentIndex: { guid: wid, position: '!' } }]);
53
+ try {
54
+ return frameToSvg(doc.deck, wrapper).replace(/<rect x="0" y="0" width="[\d.]+" height="[\d.]+" fill="white"\/>/, '');
55
+ } finally { doc.deck.childrenMap.delete(key); }
56
+ } finally { cleanup(); }
57
+ }
58
+
59
+ /** SVG string -> PNG bytes. */
60
+ export async function svgToPng(svg, { scale = 1, maxDim, fonts = [], background } = {}) {
61
+ await ensureWasm();
62
+ fonts = [...(await base()), ...fonts];
63
+ const m = svg.match(/<svg[^>]*width="([\d.]+)"[^>]*height="([\d.]+)"/);
64
+ const w = m ? +m[1] : 1000, h = m ? +m[2] : 1000;
65
+ let s = scale;
66
+ if (maxDim && Math.max(w, h) * s > maxDim) s = maxDim / Math.max(w, h);
67
+ const attempts = [svg, svg.replace(/ filter="url\([^)]*\)"/g, ''), svg.replace(/ filter="url\([^)]*\)"/g, '').replace(/ mask="url\([^)]*\)"/g, '')];
68
+ let lastErr;
69
+ for (const attempt of attempts) {
70
+ try { return render(attempt, s, fonts, background); } catch (e) { lastErr = e; }
71
+ }
72
+ throw lastErr;
73
+ }
74
+
75
+ function render(svg, s, fonts, background) {
76
+ const resvg = new Resvg(svg, {
77
+ background,
78
+ fitTo: s !== 1 ? { mode: 'zoom', value: s } : { mode: 'original' },
79
+ font: { fontBuffers: fonts.map(b => new Uint8Array(b)), loadSystemFonts: false, defaultFontFamily: fallbackFamily() || 'Arial', sansSerifFamily: fallbackFamily() || 'Arial' },
80
+ });
81
+ const img = resvg.render();
82
+ const png = img.asPng();
83
+ img.free(); resvg.free();
84
+ return Buffer.from(png);
85
+ }