@nodii/dev 0.6.73 → 0.6.75

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.
@@ -0,0 +1,740 @@
1
+ // Render harness for the parserless Code Connect templates.
2
+ //
3
+ // `figma connect parse` bundles every `.figma.ts` into a self-contained JS
4
+ // program (the `template` field of its JSON output) that Figma runs against
5
+ // the selected instance. This module runs those same programs locally against
6
+ // a mock `figma` API built from the committed REST snapshot
7
+ // (docs/figma-ux-ds/figma/snapshots/figma-file.snapshot.json), so every
8
+ // snippet a template can emit is produced without Figma:
9
+ //
10
+ // - every VARIANT combination that exists in the component set (the real
11
+ // variant children, not a cartesian product that Figma could never select);
12
+ // - booleans at their defaults, all on, all off, and each one flipped alone;
13
+ // - TEXT at its default, plus one run with a hostile value (quote,
14
+ // backslash, apostrophe, newline) — the escaping contract of escape.ts;
15
+ // - INSTANCE_SWAP resolved to its default component and rendered through
16
+ // that component's own template when it has one, exactly as
17
+ // `executeTemplate()` does in Figma.
18
+ //
19
+ // Problems that are template bugs regardless of compilation (a property the
20
+ // Figma component does not have, an enum map missing one of the real variant
21
+ // values, an interpolated `undefined`/boolean that would print literally) are
22
+ // reported as render errors.
23
+ import { readFileSync } from "node:fs";
24
+ import { join } from "node:path";
25
+
26
+ const HOSTILE_TEXT = `Say "hi" \\ it's\nnext line`;
27
+
28
+ /**
29
+ * Interaction states Figma draws as variants and code draws with CSS
30
+ * pseudo-classes: a template maps them to nothing on purpose.
31
+ */
32
+ const DESIGN_ONLY_STATES = new Set([
33
+ "hover",
34
+ "focus",
35
+ "focused",
36
+ "focus-visible",
37
+ "pressed",
38
+ ]);
39
+
40
+ /**
41
+ * `fileSnapshot` replaces the DS file's Code Connect snapshot: the Figma 1:1
42
+ * check renders against its own pinned copy (docs/figma-ux-ds/figma/1to1/).
43
+ */
44
+ export function loadSnapshot(root, { fileSnapshot } = {}) {
45
+ const paths = [
46
+ fileSnapshot ??
47
+ join(
48
+ root,
49
+ "docs",
50
+ "figma-ux-ds",
51
+ "figma",
52
+ "snapshots",
53
+ "figma-file.snapshot.json"
54
+ ),
55
+ join(root, "code-connect", "snapshots", "hr-surfaces.snapshot.json"),
56
+ join(root, "code-connect", "snapshots", "dev-surfaces.snapshot.json"),
57
+ join(
58
+ root,
59
+ "code-connect",
60
+ "snapshots",
61
+ "notification-surfaces.snapshot.json"
62
+ ),
63
+ join(root, "code-connect", "snapshots", "kyc-surfaces.snapshot.json"),
64
+ join(
65
+ root,
66
+ "code-connect",
67
+ "snapshots",
68
+ "compliance-surfaces.snapshot.json"
69
+ ),
70
+ ];
71
+ const contexts = new Map();
72
+ for (const path of paths) {
73
+ try {
74
+ const snapshot = JSON.parse(readFileSync(path, "utf8"));
75
+ const byId = new Map(snapshot.nodes.map((node) => [node.nodeId, node]));
76
+ const variantsBySet = new Map();
77
+ for (const node of snapshot.nodes) {
78
+ if (node.type === "COMPONENT" && node.parentType === "COMPONENT_SET") {
79
+ const list = variantsBySet.get(node.parentId) ?? [];
80
+ list.push(node);
81
+ variantsBySet.set(node.parentId, list);
82
+ }
83
+ }
84
+ contexts.set(snapshot.fileKey, { snapshot, byId, variantsBySet });
85
+ } catch (error) {
86
+ if (error?.code !== "ENOENT") throw error;
87
+ }
88
+ }
89
+ return contexts;
90
+ }
91
+
92
+ const nodeIdFromUrl = (url) => {
93
+ const match = /node-id=([0-9]+)[-:]([0-9]+)/.exec(url);
94
+ return match ? `${match[1]}:${match[2]}` : null;
95
+ };
96
+
97
+ const stripSuffix = (key) => key.replace(/#[^#]*$/, "");
98
+
99
+ /** Parse a variant child name (`part=trigger, state=default`). */
100
+ const parseVariantName = (name) =>
101
+ Object.fromEntries(
102
+ name
103
+ .split(",")
104
+ .map((pair) => pair.split("="))
105
+ .filter((pair) => pair.length === 2)
106
+ .map(([key, value]) => [key.trim(), value.trim()])
107
+ );
108
+
109
+ class RenderError extends Error {}
110
+
111
+ function isSection(value) {
112
+ return (
113
+ value !== null &&
114
+ typeof value === "object" &&
115
+ typeof value.type === "string" &&
116
+ ["CODE", "INSTANCE", "SLOT", "ERROR"].includes(value.type)
117
+ );
118
+ }
119
+
120
+ function pushValue(sections, value, where) {
121
+ if (typeof value === "string" || typeof value === "number") {
122
+ sections.push({ type: "CODE", code: String(value) });
123
+ return;
124
+ }
125
+ if (value === undefined || value === null || typeof value === "boolean") {
126
+ throw new RenderError(
127
+ `interpolated ${String(value)} into figma.code${where} — Figma prints it literally`
128
+ );
129
+ }
130
+ if (Array.isArray(value)) {
131
+ for (const item of value) {
132
+ pushValue(sections, item, where);
133
+ }
134
+ return;
135
+ }
136
+ if (value.type === "SECTIONS" && Array.isArray(value.sections)) {
137
+ sections.push(...value.sections);
138
+ return;
139
+ }
140
+ if (isSection(value)) {
141
+ sections.push(value);
142
+ return;
143
+ }
144
+ throw new RenderError(
145
+ `interpolated an object that is not code (${JSON.stringify(value).slice(0, 80)})`
146
+ );
147
+ }
148
+
149
+ function makeCode(language) {
150
+ return (strings, ...values) => {
151
+ const sections = [];
152
+ strings.forEach((chunk, index) => {
153
+ sections.push({ type: "CODE", code: chunk });
154
+ if (index < values.length) {
155
+ pushValue(sections, values[index], "");
156
+ }
157
+ });
158
+ return { type: "SECTIONS", language, sections };
159
+ };
160
+ }
161
+
162
+ /**
163
+ * Point `figma.batch` at the entry a batch template stores on `scope`.
164
+ * Configurable, so rebinding a reused mock to a new scope does not throw.
165
+ */
166
+ export function bindBatch(figma, scope) {
167
+ Object.defineProperty(figma, "batch", {
168
+ configurable: true,
169
+ get: () => scope.__FIGMA_BATCH,
170
+ });
171
+ return figma;
172
+ }
173
+
174
+ /**
175
+ * Flatten sections to text, collecting nested imports along the way.
176
+ * `options.slot(propertyName)` replaces the empty fragment a SLOT renders as.
177
+ */
178
+ export function renderSections(sections, imports, options = {}) {
179
+ let out = "";
180
+ for (const section of sections) {
181
+ for (const nested of section.nestedImports ?? []) {
182
+ imports.add(nested);
183
+ }
184
+ if (section.type === "CODE") {
185
+ out += section.code;
186
+ } else if (section.type === "INSTANCE") {
187
+ // An instance with no template: Figma falls back to generated markup.
188
+ // A fragment stands in for it so the surrounding snippet still compiles
189
+ // on its own merits; the fallback itself is reported as a note.
190
+ out += section.resultSections
191
+ ? renderSections(section.resultSections, imports, options)
192
+ : "<></>";
193
+ } else if (section.type === "SLOT") {
194
+ // Slot content is whatever the designer drops in — any ReactNode.
195
+ out += options.slot ? options.slot(section.propertyName) : "<></>";
196
+ } else if (section.type === "ERROR") {
197
+ throw new RenderError(
198
+ `template produced an ERROR section: ${section.message}`
199
+ );
200
+ }
201
+ }
202
+ return out;
203
+ }
204
+
205
+ /**
206
+ * Build a renderer over the parsed Code Connect docs.
207
+ * `docs` is the array `figma connect parse` writes.
208
+ */
209
+ export function createRenderer(root, docs, options = {}) {
210
+ const contexts = loadSnapshot(root, options);
211
+ const docByNode = new Map();
212
+ for (const doc of docs) {
213
+ const nodeId = nodeIdFromUrl(doc.figmaNode);
214
+ const fileKey = [...contexts.keys()].find((key) =>
215
+ doc.figmaNode.includes(`/design/${key}/`)
216
+ );
217
+ if (nodeId && fileKey) {
218
+ docByNode.set(`${fileKey}:${nodeId}`, doc);
219
+ }
220
+ }
221
+ const compiled = new Map();
222
+
223
+ const templateFor = (doc) => {
224
+ let fn = compiled.get(doc);
225
+ if (!fn) {
226
+ // The parser emits either a bundled program ending in
227
+ // `export default <name>` or a single transpiled file ending in
228
+ // `export default { ... }`; both become a CommonJS assignment.
229
+ const body = doc.template.replace(
230
+ /^export default /m,
231
+ "module.exports.default = "
232
+ );
233
+ // Runs our own bundled templates — the same program Figma executes.
234
+ // A batch entry's program starts with
235
+ // `globalThis['__FIGMA_BATCH'] = <entry>`; the shadowing `globalThis`
236
+ // parameter keeps that per-doc instead of leaking into the process.
237
+ fn = new Function("require", "module", "globalThis", body);
238
+ compiled.set(doc, fn);
239
+ }
240
+ return fn;
241
+ };
242
+
243
+ /** The doc that renders an instance of `nodeId` (a variant maps to its set). */
244
+ const docForComponent = (context, nodeId) => {
245
+ const { snapshot, byId } = context;
246
+ const key = `${snapshot.fileKey}:${nodeId}`;
247
+ if (docByNode.has(key)) {
248
+ return { doc: docByNode.get(key), node: byId.get(nodeId) };
249
+ }
250
+ const node = byId.get(nodeId);
251
+ const parentKey = `${snapshot.fileKey}:${node?.parentId}`;
252
+ if (node?.parentType === "COMPONENT_SET" && docByNode.has(parentKey)) {
253
+ return { doc: docByNode.get(parentKey), node };
254
+ }
255
+ return null;
256
+ };
257
+
258
+ /** Property map for one case: { name -> { type, value } }. */
259
+ function propsFor(setNode, variantNode, overrides) {
260
+ const props = new Map();
261
+ for (const [key, def] of Object.entries(
262
+ setNode.propertyDefinitions ?? {}
263
+ )) {
264
+ props.set(stripSuffix(key), { type: def.type, value: def.defaultValue });
265
+ }
266
+ if (variantNode && variantNode !== setNode) {
267
+ for (const [key, value] of Object.entries(
268
+ parseVariantName(variantNode.name)
269
+ )) {
270
+ props.set(key, { type: "VARIANT", value });
271
+ }
272
+ }
273
+ for (const [key, value] of Object.entries(overrides ?? {})) {
274
+ const prop = props.get(key);
275
+ if (prop) {
276
+ props.set(key, { ...prop, value });
277
+ }
278
+ }
279
+ return props;
280
+ }
281
+
282
+ function makeInstance(context, setNode, props, depth, label, reads = null) {
283
+ const need = (name, type) => {
284
+ reads?.add(name);
285
+ const prop = props.get(name);
286
+ if (!prop) {
287
+ throw new RenderError(
288
+ `${label}: Figma component ${setNode.name} (${setNode.nodeId}) has no property "${name}"`
289
+ );
290
+ }
291
+ if (type && prop.type !== type) {
292
+ throw new RenderError(
293
+ `${label}: property "${name}" of ${setNode.name} is ${prop.type}, read as ${type}`
294
+ );
295
+ }
296
+ return prop;
297
+ };
298
+ const mapValue = (name, options, value) => {
299
+ const key = String(value);
300
+ if (!Object.hasOwn(options, key)) {
301
+ throw new RenderError(
302
+ `${label}: ${name}=${key} is a real value of ${setNode.name} but the template's map has no "${key}" key`
303
+ );
304
+ }
305
+ return options[key];
306
+ };
307
+ return {
308
+ type: "INSTANCE",
309
+ id: `${setNode.nodeId}-mock`,
310
+ symbolId: setNode.nodeId,
311
+ name: setNode.name,
312
+ children: [],
313
+ getString: (name) => String(need(name, "TEXT").value),
314
+ getBoolean: (name, options) => {
315
+ const value = Boolean(need(name, "BOOLEAN").value);
316
+ return options ? mapValue(name, options, value) : value;
317
+ },
318
+ getEnum: (name, options) =>
319
+ mapValue(name, options, need(name, "VARIANT").value),
320
+ getInstanceSwap: (name) => {
321
+ const target = String(need(name, "INSTANCE_SWAP").value);
322
+ return swapHandle(context, target, depth, label);
323
+ },
324
+ getSlot: (name) => {
325
+ need(name, "SLOT");
326
+ const slot = [{ type: "SLOT", propertyName: name }];
327
+ slot.connectedInstances = [];
328
+ return slot;
329
+ },
330
+ getPropertyValue: (name) => need(name).value,
331
+ hasCodeConnect: () => true,
332
+ codeConnectId: () => null,
333
+ };
334
+ }
335
+
336
+ function swapHandle(context, targetId, depth, label) {
337
+ const { byId } = context;
338
+ const found = docForComponent(context, targetId);
339
+ const node = byId.get(targetId);
340
+ return {
341
+ type: "INSTANCE",
342
+ id: `${targetId}-swap`,
343
+ symbolId: targetId,
344
+ name: node?.name ?? targetId,
345
+ children: [],
346
+ hasCodeConnect: () => Boolean(found),
347
+ codeConnectId: () => found?.doc.templateData?.id ?? null,
348
+ executeTemplate: () => {
349
+ if (!found) {
350
+ return {
351
+ example: [{ type: "INSTANCE", guid: targetId, symbolId: targetId }],
352
+ };
353
+ }
354
+ if (depth > 4) {
355
+ throw new RenderError(
356
+ `${label}: instance-swap recursion deeper than 4`
357
+ );
358
+ }
359
+ const setNode =
360
+ found.node.parentType === "COMPONENT_SET"
361
+ ? byId.get(found.node.parentId)
362
+ : found.node;
363
+ const result = runTemplate(
364
+ found.doc,
365
+ makeInstance(
366
+ context,
367
+ setNode,
368
+ propsFor(setNode, found.node, {}),
369
+ depth + 1,
370
+ `${label} > ${setNode.name}`
371
+ )
372
+ );
373
+ const example = result.example.sections.map((section, index) =>
374
+ index === 0
375
+ ? { ...section, nestedImports: result.imports ?? [] }
376
+ : section
377
+ );
378
+ return {
379
+ // Figma returns the nested template's sections directly. Keep the
380
+ // mock flat too so templates that inspect CODE sections exercise the
381
+ // same branches; nestedImports is harness-only compile metadata.
382
+ example,
383
+ metadata: result.metadata,
384
+ };
385
+ },
386
+ };
387
+ }
388
+
389
+ function runTemplate(doc, instance) {
390
+ const figma = {
391
+ selectedInstance: instance,
392
+ currentLayer: instance,
393
+ code: makeCode("tsx"),
394
+ tsx: makeCode("tsx"),
395
+ helpers: {},
396
+ };
397
+ const module = { exports: {} };
398
+ const require = (name) => {
399
+ if (name === "figma") {
400
+ return figma;
401
+ }
402
+ throw new RenderError(`template requires "${name}"`);
403
+ };
404
+ const scope = {};
405
+ bindBatch(figma, scope);
406
+ templateFor(doc)(require, module, scope);
407
+ const result = module.exports.default;
408
+ if (!result || result.example?.type !== "SECTIONS") {
409
+ throw new RenderError(
410
+ "template default export has no figma.code example"
411
+ );
412
+ }
413
+ return result;
414
+ }
415
+
416
+ /** Every case to render for a template's node. */
417
+ function casesFor(context, nodeId) {
418
+ const { byId, variantsBySet } = context;
419
+ const setNode = byId.get(nodeId);
420
+ if (!setNode) {
421
+ return [];
422
+ }
423
+ const defs = Object.entries(setNode.propertyDefinitions ?? {}).map(
424
+ ([key, def]) => [stripSuffix(key), def]
425
+ );
426
+ const booleans = defs.filter(([, def]) => def.type === "BOOLEAN");
427
+ const texts = defs.filter(([, def]) => def.type === "TEXT");
428
+ const variants =
429
+ setNode.type === "COMPONENT_SET"
430
+ ? (variantsBySet.get(nodeId) ?? [])
431
+ : [setNode];
432
+ const defaultVariant =
433
+ variants.find((variant) => {
434
+ const values = parseVariantName(variant.name);
435
+ return defs
436
+ .filter(([, def]) => def.type === "VARIANT")
437
+ .every(([key, def]) => values[key] === def.defaultValue);
438
+ }) ?? variants[0];
439
+ const allOf = (value) =>
440
+ Object.fromEntries(booleans.map(([key]) => [key, value]));
441
+ const cases = [];
442
+ for (const variant of variants) {
443
+ cases.push({ variant, overrides: {} });
444
+ if (booleans.length > 0) {
445
+ cases.push({ variant, overrides: allOf(true) });
446
+ cases.push({ variant, overrides: allOf(false) });
447
+ }
448
+ }
449
+ for (const [key, def] of booleans) {
450
+ cases.push({
451
+ variant: defaultVariant,
452
+ overrides: { [key]: !def.defaultValue },
453
+ });
454
+ }
455
+ if (texts.length > 0) {
456
+ cases.push({
457
+ variant: defaultVariant,
458
+ overrides: {
459
+ ...allOf(true),
460
+ ...Object.fromEntries(texts.map(([key]) => [key, HOSTILE_TEXT])),
461
+ },
462
+ });
463
+ }
464
+ return cases.map((entry) => ({
465
+ ...entry,
466
+ setNode,
467
+ label: [
468
+ entry.variant && entry.variant !== setNode
469
+ ? entry.variant.name
470
+ : "default",
471
+ ...Object.entries(entry.overrides).map(([k, v]) =>
472
+ v === HOSTILE_TEXT ? `${k}=<hostile>` : `${k}=${v}`
473
+ ),
474
+ ].join(", "),
475
+ }));
476
+ }
477
+
478
+ /**
479
+ * Render every case of one parsed doc.
480
+ * Returns { snippets: [{ code, imports, cases: [label], nestable }], errors: [string], notes }.
481
+ * `nestable` is true when any case that produced the snippet declared
482
+ * `metadata.nestable: true`.
483
+ */
484
+ function renderDoc(doc) {
485
+ const nodeId = nodeIdFromUrl(doc.figmaNode);
486
+ const context = [...contexts.entries()].find(([fileKey]) =>
487
+ doc.figmaNode.includes(`/design/${fileKey}/`)
488
+ )?.[1];
489
+ const cases = context ? casesFor(context, nodeId) : [];
490
+ const errors = [];
491
+ const notes = new Set();
492
+ const unique = new Map();
493
+ if (cases.length === 0) {
494
+ errors.push(`node ${nodeId} is not in the REST snapshot`);
495
+ }
496
+ for (const entry of cases) {
497
+ try {
498
+ const instance = makeInstance(
499
+ context,
500
+ entry.setNode,
501
+ propsFor(entry.setNode, entry.variant, entry.overrides),
502
+ 0,
503
+ entry.label
504
+ );
505
+ const result = runTemplate(doc, instance);
506
+ const imports = new Set(result.imports ?? []);
507
+ const code = renderSections(result.example.sections, imports);
508
+ if (code.includes("<></>")) {
509
+ notes.add(
510
+ "renders a placeholder for a slot or an unmapped instance swap"
511
+ );
512
+ }
513
+ const nestable = result.metadata?.nestable === true;
514
+ const key = `${[...imports].sort().join("\n")}\n---\n${code}`;
515
+ const existing = unique.get(key);
516
+ if (existing) {
517
+ existing.cases.push(entry.label);
518
+ existing.nestable ||= nestable;
519
+ } else {
520
+ unique.set(key, {
521
+ code,
522
+ imports: [...imports],
523
+ cases: [entry.label],
524
+ nestable,
525
+ });
526
+ }
527
+ } catch (error) {
528
+ if (error instanceof RenderError) {
529
+ errors.push(`[${entry.label}] ${error.message}`);
530
+ } else {
531
+ errors.push(`[${entry.label}] template threw: ${error.message}`);
532
+ }
533
+ }
534
+ }
535
+ return { snippets: [...unique.values()], errors, notes: [...notes] };
536
+ }
537
+
538
+ /**
539
+ * One snippet per real VARIANT child at its property defaults: what Dev Mode
540
+ * shows for an untouched instance of that variant, so what the Figma 1:1
541
+ * gate renders against that variant (infra/figma/figma-1to1-cc.mjs).
542
+ * `slot(propertyName)` is the code a SLOT renders as (default: `<></>`).
543
+ * Returns [{ nodeId, label, code, imports } | { nodeId, label, error }].
544
+ */
545
+ function renderVariants(doc, { slot } = {}) {
546
+ const nodeId = nodeIdFromUrl(doc.figmaNode);
547
+ const context = [...contexts.entries()].find(([fileKey]) =>
548
+ doc.figmaNode.includes(`/design/${fileKey}/`)
549
+ )?.[1];
550
+ const cases = context ? casesFor(context, nodeId) : [];
551
+ return cases
552
+ .filter((entry) => Object.keys(entry.overrides).length === 0)
553
+ .map((entry) => {
554
+ const variantId = (entry.variant ?? entry.setNode).nodeId;
555
+ try {
556
+ const result = runTemplate(
557
+ doc,
558
+ makeInstance(
559
+ context,
560
+ entry.setNode,
561
+ propsFor(entry.setNode, entry.variant, {}),
562
+ 0,
563
+ entry.label
564
+ )
565
+ );
566
+ const imports = new Set(result.imports ?? []);
567
+ const code = renderSections(result.example.sections, imports, {
568
+ slot,
569
+ });
570
+ return {
571
+ nodeId: variantId,
572
+ label: entry.label,
573
+ code,
574
+ imports: [...imports],
575
+ };
576
+ } catch (error) {
577
+ return {
578
+ nodeId: variantId,
579
+ label: entry.label,
580
+ error: error.message,
581
+ };
582
+ }
583
+ });
584
+ }
585
+
586
+ /**
587
+ * The snippet Dev Mode hands a developer for ONE placed instance: the
588
+ * template of `nodeId` (a variant or a component in `fileKey`), run with
589
+ * the instance's own property values (`values`: name → value, swaps as
590
+ * node ids). The frame-conformance check reads a Surface's composed
591
+ * instances this way. Returns { code, imports } | { error } | null (no
592
+ * template maps the component).
593
+ */
594
+ function renderInstance(fileKey, nodeId, values = {}, { slot } = {}) {
595
+ const context = contexts.get(fileKey);
596
+ const found = context ? docForComponent(context, nodeId) : null;
597
+ if (!found?.node) return null;
598
+ const setNode =
599
+ found.node.parentType === "COMPONENT_SET"
600
+ ? context.byId.get(found.node.parentId)
601
+ : found.node;
602
+ const label = `${setNode.name} instance`;
603
+ try {
604
+ const result = runTemplate(
605
+ found.doc,
606
+ makeInstance(
607
+ context,
608
+ setNode,
609
+ propsFor(setNode, found.node, values),
610
+ 0,
611
+ label
612
+ )
613
+ );
614
+ const imports = new Set(result.imports ?? []);
615
+ return {
616
+ template: found.doc,
617
+ code: renderSections(result.example.sections, imports, { slot }),
618
+ imports: [...imports],
619
+ };
620
+ } catch (error) {
621
+ return { template: found.doc, error: error.message };
622
+ }
623
+ }
624
+
625
+ /**
626
+ * Does the template USE every Figma property it reads? (The Code Connect
627
+ * fidelity gate, FRAME-CONFORMANCE-CHECK-1.) Each property the template
628
+ * reads is changed alone — every other VARIANT value, the BOOLEAN flipped, a
629
+ * different TEXT — from two bases: the defaults, and every boolean on (a
630
+ * text shown only behind a toggle). A property no change of which changes
631
+ * the snippet is DROPPED: Dev Mode would hand a developer the same code
632
+ * whatever the designer set. An INSTANCE_SWAP or SLOT cannot be probed
633
+ * without a target and is listed as such, never as used.
634
+ * Returns { read, dropped, unprobed } (property names) or null.
635
+ */
636
+ function fidelityOf(doc) {
637
+ const nodeId = nodeIdFromUrl(doc.figmaNode);
638
+ const context = [...contexts.entries()].find(([fileKey]) =>
639
+ doc.figmaNode.includes(`/design/${fileKey}/`)
640
+ )?.[1];
641
+ const setNode = context?.byId.get(nodeId);
642
+ if (!setNode) return null;
643
+ const variants =
644
+ setNode.type === "COMPONENT_SET"
645
+ ? (context.variantsBySet.get(nodeId) ?? [])
646
+ : [setNode];
647
+ const defs = Object.fromEntries(
648
+ Object.entries(setNode.propertyDefinitions ?? {}).map(([key, def]) => [
649
+ stripSuffix(key),
650
+ def,
651
+ ])
652
+ );
653
+ const reads = new Set();
654
+ const memo = new Map();
655
+ const render = (variant, overrides) => {
656
+ const key = `${variant.nodeId}\u0000${JSON.stringify(overrides)}`;
657
+ if (!memo.has(key)) memo.set(key, renderOnce(variant, overrides));
658
+ return memo.get(key);
659
+ };
660
+ const renderOnce = (variant, overrides) => {
661
+ try {
662
+ const result = runTemplate(
663
+ doc,
664
+ makeInstance(
665
+ context,
666
+ setNode,
667
+ propsFor(setNode, variant, overrides),
668
+ 0,
669
+ "fidelity",
670
+ reads
671
+ )
672
+ );
673
+ return renderSections(result.example.sections, new Set());
674
+ } catch (error) {
675
+ return `error: ${error.message}`;
676
+ }
677
+ };
678
+ const allOn = Object.fromEntries(
679
+ Object.entries(defs)
680
+ .filter(([, def]) => def.type === "BOOLEAN")
681
+ .map(([key]) => [key, true])
682
+ );
683
+ // Every real variant, with booleans at their defaults and all on: a
684
+ // text one part draws (a date picker's day number) is probed where it
685
+ // shows.
686
+ const bases = variants.flatMap((variant) =>
687
+ [{}, allOn].map((overrides) => ({
688
+ variant,
689
+ overrides,
690
+ code: render(variant, overrides),
691
+ }))
692
+ );
693
+ const options = (def) => {
694
+ if (def.type === "VARIANT") {
695
+ return (def.variantOptions ?? []).filter(
696
+ (value) => !DESIGN_ONLY_STATES.has(value)
697
+ );
698
+ }
699
+ if (def.type === "BOOLEAN") return [true, false];
700
+ if (def.type === "TEXT") {
701
+ return [`${def.defaultValue ?? ""} · fidelity probe`];
702
+ }
703
+ return [];
704
+ };
705
+ const read = [...reads];
706
+ const dropped = [];
707
+ const unprobed = [];
708
+ for (const key of read) {
709
+ const def = defs[key];
710
+ if (!def) continue;
711
+ const alternates = options(def);
712
+ // A VARIANT axis is one value per base, so it needs two to differ.
713
+ if (alternates.length < (def.type === "VARIANT" ? 2 : 1)) {
714
+ unprobed.push(key);
715
+ continue;
716
+ }
717
+ const used = bases.some(
718
+ (base) =>
719
+ alternates.some(
720
+ (value) =>
721
+ render(base.variant, { ...base.overrides, [key]: value }) !==
722
+ render(base.variant, { ...base.overrides, [key]: alternates[0] })
723
+ ) ||
724
+ (def.type !== "VARIANT" &&
725
+ render(base.variant, {
726
+ ...base.overrides,
727
+ [key]: alternates[0],
728
+ }) !== base.code)
729
+ );
730
+ if (!used) dropped.push(key);
731
+ }
732
+ return {
733
+ read: read.sort(),
734
+ dropped: dropped.sort(),
735
+ unprobed: unprobed.sort(),
736
+ };
737
+ }
738
+
739
+ return { renderDoc, renderVariants, renderInstance, fidelityOf };
740
+ }