figdriver 0.0.0-stage → 0.4.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.
@@ -0,0 +1,481 @@
1
+ import { hexOf } from "../core/css";
2
+ import { fnv1a } from "../core/naming";
3
+ import type { Audit, AuditRules } from "../core/protocol";
4
+ import { round as round2 } from "../core/snapshot";
5
+ import { componentFullName, hasAncestor, localStyles, ownedBy, ownerOf, read, write } from "./owned";
6
+
7
+ // Unlike `instanceof Object`, this holds for an object from any realm.
8
+ const isObject = <T>(v: T): v is Extract<T, object> => Object(v) === v;
9
+
10
+ export function variableColors(
11
+ variables: Pick<Variable, "id" | "variableCollectionId" | "resolvedType" | "valuesByMode">[],
12
+ collections: ReadonlySet<string>,
13
+ ) {
14
+ const byId = new Map(variables.map((v) => [v.id, v]));
15
+ const tokens = new Set<string>();
16
+
17
+ for (const v of variables) {
18
+ if (v.resolvedType !== "COLOR" || !collections.has(v.variableCollectionId)) continue;
19
+ let value: VariableValue | undefined = Object.values(v.valuesByMode)[0];
20
+ const seen = new Set<string>([v.id]);
21
+
22
+ while (isObject(value) && "id" in value) {
23
+ if (seen.has(value.id)) {
24
+ value = undefined;
25
+ break;
26
+ }
27
+
28
+ seen.add(value.id);
29
+ value = Object.values(byId.get(value.id)?.valuesByMode ?? {})[0];
30
+ }
31
+
32
+ if (isObject(value) && "r" in value) tokens.add(hexOf(value));
33
+ }
34
+
35
+ return tokens;
36
+ }
37
+
38
+ const ARTWORK = new Set(["VECTOR", "BOOLEAN_OPERATION", "ELLIPSE", "RECTANGLE", "LINE", "POLYGON", "STAR", "GROUP"]);
39
+
40
+ export const insideInstance = (n: BaseNode) => hasAncestor(n, (p) => p.type === "INSTANCE", false);
41
+
42
+ const pathOf = (n: BaseNode) => {
43
+ const parts: string[] = [];
44
+
45
+ for (let p: BaseNode | null = n; p && p.type !== "PAGE"; p = p.parent) parts.unshift(p.name);
46
+
47
+ return parts.join(" › ");
48
+ };
49
+
50
+ type Laid = FrameNode | ComponentNode | InstanceNode;
51
+
52
+ const isLaid = (n: SceneNode): n is Laid => n.type === "FRAME" || n.type === "COMPONENT" || n.type === "INSTANCE";
53
+
54
+ /** Flow children of an auto layout stack that cover a neighbor by more than 2px along the stack. Wrapped lines do not overlap. */
55
+ function overlapping(f: Laid) {
56
+ if (f.layoutMode !== "HORIZONTAL" && f.layoutMode !== "VERTICAL") return [];
57
+ const flow = f.children.filter((c) => c.visible && !("layoutPositioning" in c && c.layoutPositioning === "ABSOLUTE"));
58
+
59
+ const [at, size, crossAt, crossSize] =
60
+ f.layoutMode === "HORIZONTAL" ? (["x", "width", "y", "height"] as const) : (["y", "height", "x", "width"] as const);
61
+
62
+ return flow.slice(1).flatMap((c, i) => {
63
+ const p = flow[i];
64
+ const along = Math.min(p[at] + p[size], c[at] + c[size]) - Math.max(p[at], c[at]);
65
+ const across = Math.min(p[crossAt] + p[crossSize], c[crossAt] + c[crossSize]) - Math.max(p[crossAt], c[crossAt]);
66
+
67
+ return along > 2 && across > 0 ? [c] : [];
68
+ });
69
+ }
70
+
71
+ export async function auditOf(roots: SceneNode[], rules: AuditRules = "run"): Promise<Audit> {
72
+ // Section backgrounds and the variant-set outline are page chrome, not design paints.
73
+ const nodes = roots
74
+ .flatMap((r) => [r, ...("findAll" in r ? r.findAll() : [])])
75
+ .filter((n) => !insideInstance(n) && n.type !== "SECTION" && n.type !== "COMPONENT_SET");
76
+
77
+ const owners = new Set(roots.map(ownerOf));
78
+
79
+ // A person's file names its tokens in any local collection; figdriver's output only in the collections it made.
80
+ const collections = new Set(
81
+ (await figma.variables.getLocalVariableCollectionsAsync())
82
+ .filter((c) => rules === "authored" || owners.has(ownerOf(c)))
83
+ .map((c) => c.id),
84
+ );
85
+
86
+ const tokens = variableColors(await figma.variables.getLocalVariablesAsync(), collections);
87
+
88
+ // A frame that only holds vector shapes is artwork, such as an icon or an SVG logo, and needs no auto layout. So are the frames an SVG
89
+ // import nests in it for clipping.
90
+ const isArtwork = (n: FrameNode | ComponentNode) =>
91
+ n.children.length > 0 &&
92
+ !n.findOne((d) => !ARTWORK.has(d.type) && !(d.type === "FRAME" && d.layoutMode === "NONE"));
93
+
94
+ const inArtwork = (n: BaseNode) =>
95
+ hasAncestor(n, (p) => (p.type === "FRAME" || p.type === "COMPONENT") && isArtwork(p));
96
+
97
+ const frames = nodes.filter(
98
+ (n): n is FrameNode | ComponentNode => (n.type === "FRAME" || n.type === "COMPONENT") && !inArtwork(n),
99
+ );
100
+
101
+ const texts = nodes.filter((n): n is TextNode => n.type === "TEXT");
102
+ const instances = nodes.filter((n): n is InstanceNode => n.type === "INSTANCE");
103
+ const mains = await Promise.all(instances.map((i) => i.getMainComponentAsync()));
104
+
105
+ const broken: SceneNode[] = [];
106
+
107
+ for (const n of rules === "authored" ? nodes : []) {
108
+ const destinations =
109
+ "reactions" in n
110
+ ? n.reactions.flatMap((r) =>
111
+ (r.actions ?? []).flatMap((a) => (a.type === "NODE" && a.destinationId ? [a.destinationId] : [])),
112
+ )
113
+ : [];
114
+
115
+ for (const id of destinations) {
116
+ const dest = await figma.getNodeByIdAsync(id);
117
+
118
+ if (!dest || dest.removed) {
119
+ broken.push(n);
120
+ break;
121
+ }
122
+ }
123
+ }
124
+
125
+ const raw: { node: SceneNode; hex: string; opacity: number }[] = [];
126
+
127
+ for (const n of nodes) {
128
+ const fills = "fills" in n && !("fillStyleId" in n && n.fillStyleId) ? n.fills : [];
129
+
130
+ for (const paints of [fills, "strokes" in n ? n.strokes : []] as const) {
131
+ if (paints === figma.mixed) continue;
132
+
133
+ for (const p of paints) {
134
+ if (p.type === "SOLID" && p.visible !== false && !p.boundVariables?.color)
135
+ raw.push({ node: n, hex: hexOf(p.color), opacity: p.opacity ?? 1 });
136
+ }
137
+ }
138
+ }
139
+
140
+ const offToken = raw.filter((r) => !tokens.has(r.hex));
141
+
142
+ return {
143
+ frames: frames.length,
144
+ texts: texts.length,
145
+ instances: instances.length,
146
+ problems: {
147
+ framesWithoutAutoLayout:
148
+ rules === "authored" ? [] : frames.flatMap((n) => (n.layoutMode === "NONE" ? [pathOf(n)] : [])),
149
+ textsWithoutStyle: texts.flatMap((t) =>
150
+ t.getStyledTextSegments(["textStyleId"]).some((s) => !s.textStyleId) ? [pathOf(t)] : [],
151
+ ),
152
+ // A library main is remote by design in a person's file; in figdriver's output every main is local.
153
+ detachedInstances: instances.flatMap((n, i) =>
154
+ !mains[i] || (rules === "run" && mains[i].remote) ? [pathOf(n)] : [],
155
+ ),
156
+ rawPaintsOnTokenColors: raw.flatMap((r) => (tokens.has(r.hex) && r.opacity === 1 ? [pathOf(r.node)] : [])),
157
+ negativeSpacing: nodes.flatMap((n) =>
158
+ isLaid(n) && n.layoutMode !== "NONE" && n.layoutMode !== "GRID" && n.itemSpacing < 0 ? [pathOf(n)] : [],
159
+ ),
160
+ overlappingSiblings: nodes.flatMap((n) => (isLaid(n) ? overlapping(n).map(pathOf) : [])),
161
+ brokenLinks: broken.map(pathOf),
162
+ },
163
+ rawPaints: {
164
+ translucentTokenColors: raw.filter((r) => tokens.has(r.hex) && r.opacity < 1).length,
165
+ offToken: offToken.length,
166
+ offTokenColors: [...new Set(offToken.map((r) => r.hex))],
167
+ },
168
+ };
169
+ }
170
+
171
+ export async function treeOf(roots: SceneNode[], owner?: string) {
172
+ const mine = owner ? ownedBy(owner) : () => true;
173
+ const collections = new Set((await figma.variables.getLocalVariableCollectionsAsync()).filter(mine).map((c) => c.id));
174
+ const variables = await figma.variables.getLocalVariablesAsync();
175
+ const varName = new Map(variables.map((v) => [v.id, v.name]));
176
+
177
+ const styles = await localStyles();
178
+ const styleName = new Map(styles.map((s) => [s.id, s.name]));
179
+
180
+ const round = <T>(v: T) =>
181
+ v === figma.mixed
182
+ ? "mixed"
183
+ : Number.isFinite(v)
184
+ ? // SAFETY: Number.isFinite is true only for a number.
185
+ round2(v as number)
186
+ : v;
187
+
188
+ const bare = (key: string) => key.split("#")[0];
189
+
190
+ const paint = (p: Paint) => ({
191
+ type: p.type,
192
+ opacity: round(p.opacity),
193
+ visible: p.visible,
194
+ ...(p.type === "SOLID" && {
195
+ color: hexOf(p.color),
196
+ variable: p.boundVariables?.color && varName.get(p.boundVariables.color.id),
197
+ }),
198
+ ...(p.type === "IMAGE" && {
199
+ image: p.imageHash,
200
+ scale: p.scaleMode,
201
+ transform: p.imageTransform?.map((row) => row.map(round)),
202
+ }),
203
+ ...(p.type === "VIDEO" && {
204
+ video: p.videoHash,
205
+ scale: p.scaleMode,
206
+ transform: p.videoTransform?.map((row) => row.map(round)),
207
+ }),
208
+ ...("gradientStops" in p && {
209
+ transform: p.gradientTransform.map((row) => row.map(round)),
210
+ stops: p.gradientStops.map((s) => [
211
+ round(s.position),
212
+ hexOf(s.color),
213
+ round(s.color.a),
214
+ s.boundVariables?.color && varName.get(s.boundVariables.color.id),
215
+ ]),
216
+ }),
217
+ });
218
+
219
+ const paints = (ps: readonly Paint[] | PluginAPI["mixed"]) => (ps === figma.mixed ? "mixed" : ps.map(paint));
220
+
221
+ const PLAIN = [
222
+ "topLeftRadius",
223
+ "topRightRadius",
224
+ "bottomLeftRadius",
225
+ "bottomRightRadius",
226
+ "opacity",
227
+ "rotation",
228
+ "visible",
229
+ "strokeWeight",
230
+ "strokeTopWeight",
231
+ "strokeRightWeight",
232
+ "strokeBottomWeight",
233
+ "strokeLeftWeight",
234
+ "strokeAlign",
235
+ "dashPattern",
236
+ "constraints",
237
+ "maxWidth",
238
+ "minHeight",
239
+ "clipsContent",
240
+ "layoutWrap",
241
+ "layoutPositioning",
242
+ "layoutSizingHorizontal",
243
+ "layoutSizingVertical",
244
+ "gridColumnSpan",
245
+ "gridRowSpan",
246
+ "gridChildHorizontalAlign",
247
+ "gridChildVerticalAlign",
248
+ "textAutoResize",
249
+ "textAlignHorizontal",
250
+ "maxLines",
251
+ "textTruncation",
252
+ ] as const;
253
+
254
+ type Plain = {
255
+ readonly [K in (typeof PLAIN)[number]]?:
256
+ | string
257
+ | number
258
+ | boolean
259
+ | symbol
260
+ | null
261
+ | readonly number[]
262
+ | Constraints;
263
+ };
264
+
265
+ const plainOf = (n: Plain) =>
266
+ Object.fromEntries(PLAIN.flatMap((key) => (key in n ? [[key, round(n[key])] as const] : [])));
267
+
268
+ const fieldsOf = async (n: SceneNode) => {
269
+ const main = n.type === "INSTANCE" ? await n.getMainComponentAsync() : null;
270
+
271
+ return {
272
+ type: n.type,
273
+ name: n.name,
274
+ x: round(n.x),
275
+ y: round(n.y),
276
+ w: round(n.width),
277
+ h: round(n.height),
278
+ ...plainOf(n),
279
+ ...("fills" in n && { fills: paints(n.fills) }),
280
+ ...("fillStyleId" in n &&
281
+ n.fillStyleId !== figma.mixed &&
282
+ n.fillStyleId !== "" && { fillStyle: styleName.get(n.fillStyleId) }),
283
+ ...("strokes" in n && { strokes: paints(n.strokes) }),
284
+ ...("effects" in n && {
285
+ effects: n.effectStyleId
286
+ ? styleName.get(n.effectStyleId)
287
+ : n.effects.map((e) => [e.type, "radius" in e ? round(e.radius) : undefined]),
288
+ }),
289
+ ...("layoutMode" in n && {
290
+ layout: [n.layoutMode, round(n.itemSpacing), n.primaryAxisAlignItems, n.counterAxisAlignItems],
291
+ pad: [n.paddingTop, n.paddingRight, n.paddingBottom, n.paddingLeft].map(round),
292
+ ...(n.layoutMode === "GRID" && {
293
+ grid: [n.gridColumnSizes, n.gridRowSizes, round(n.gridRowGap), round(n.gridColumnGap)],
294
+ }),
295
+ ...(n.layoutGrids.length > 0 && { layoutGrids: n.layoutGrids }),
296
+ }),
297
+ ...("boundVariables" in n &&
298
+ n.boundVariables && {
299
+ variables: Object.fromEntries(
300
+ Object.entries(n.boundVariables).flatMap(([key, alias]) =>
301
+ key === "fills" || key === "strokes"
302
+ ? []
303
+ : [
304
+ [
305
+ key,
306
+ Array.isArray(alias) || key === "componentProperties"
307
+ ? undefined
308
+ : // SAFETY: Figma binds a field to one alias or a list of them. componentProperties, the one map of bindings, is handled above.
309
+ varName.get((alias as VariableAlias).id),
310
+ ] as const,
311
+ ],
312
+ ),
313
+ ),
314
+ }),
315
+ ...(n.type === "TEXT" && {
316
+ characters: n.characters,
317
+ segments: n
318
+ .getStyledTextSegments(["textStyleId", "fills", "textDecoration"])
319
+ .map((s) => [s.start, s.end, styleName.get(s.textStyleId), paints(s.fills), s.textDecoration]),
320
+ }),
321
+ ...("componentPropertyReferences" in n &&
322
+ n.componentPropertyReferences && {
323
+ references: Object.fromEntries(
324
+ Object.entries(n.componentPropertyReferences).map(([key, ref]) => [
325
+ key,
326
+ ref == null ? undefined : bare(ref),
327
+ ]),
328
+ ),
329
+ }),
330
+ ...("reactions" in n &&
331
+ n.reactions.length > 0 && {
332
+ reactions: n.reactions.map((r) => [r.trigger?.type, r.actions?.map((a) => a.type)]),
333
+ }),
334
+ ...((n.type === "COMPONENT" || n.type === "COMPONENT_SET") && {
335
+ description: n.description,
336
+ ...(n.parent?.type !== "COMPONENT_SET" && {
337
+ properties: Object.fromEntries(
338
+ Object.entries(n.componentPropertyDefinitions).map(([key, d]) => [
339
+ bare(key),
340
+ [d.type, d.type === "INSTANCE_SWAP" ? "" : d.defaultValue],
341
+ ]),
342
+ ),
343
+ }),
344
+ }),
345
+ ...(n.type === "INSTANCE" && {
346
+ main: main && componentFullName(main),
347
+ exposed: n.isExposedInstance,
348
+ values: Object.fromEntries(
349
+ Object.entries(n.componentProperties)
350
+ .map(([key, p]) => [bare(key), p.type === "INSTANCE_SWAP" ? "swap" : p.value] as const)
351
+ .sort(([a], [b]) => (a < b ? -1 : 1)),
352
+ ),
353
+ }),
354
+ };
355
+ };
356
+
357
+ type Tree = Awaited<ReturnType<typeof fieldsOf>> & { children?: Tree[] };
358
+
359
+ const walk = async (n: SceneNode): Promise<Tree> => {
360
+ const fields = await fieldsOf(n);
361
+
362
+ if (!("children" in n)) return fields;
363
+ const children: Tree[] = [];
364
+
365
+ for (const c of n.children) children.push(await walk(c));
366
+
367
+ return { ...fields, children };
368
+ };
369
+
370
+ const value = (v: VariableValue) =>
371
+ !isObject(v) ? v : "id" in v ? `-> ${varName.get(v.id)}` : "r" in v ? ["a" in v ? round(v.a) : 1, hexOf(v)] : v;
372
+
373
+ const nodes = [];
374
+
375
+ for (const root of roots) nodes.push({ page: root.parent?.name, ...(await walk(root)) });
376
+
377
+ return {
378
+ variables: variables
379
+ .filter((v) => collections.has(v.variableCollectionId))
380
+ .map((v) => [v.name, v.resolvedType, v.scopes, Object.values(v.valuesByMode).map(value)] as const)
381
+ .sort(([a], [b]) => (a < b ? -1 : 1)),
382
+ textStyles: (await figma.getLocalTextStylesAsync())
383
+ .filter(mine)
384
+ .map((s) => [s.name, s.fontName, s.fontSize, s.lineHeight, s.letterSpacing, s.textCase]),
385
+ paintStyles: (await figma.getLocalPaintStylesAsync()).filter(mine).map((s) => [s.name, s.paints.map(paint)]),
386
+ effectStyles: (await figma.getLocalEffectStylesAsync()).filter(mine).map((s) => [s.name, s.effects]),
387
+ flows: figma.currentPage.flowStartingPoints.map((f) => f.name),
388
+ nodes,
389
+ };
390
+ }
391
+
392
+ function propertiesOf<T extends Variable | VariableCollection | BaseStyle>(x: T) {
393
+ const out: Partial<T> = {};
394
+
395
+ for (const key in x) if (key !== "consumers") out[key] = x[key];
396
+
397
+ return out;
398
+ }
399
+
400
+ // Figma's REST JSON of a root holds every node property but vector paths. A flow a person starts is their work, not an edit.
401
+ export async function fingerprintOf(roots: SceneNode[], owner: string, skip: ReadonlySet<string> = new Set()) {
402
+ const mine = (x: VariableCollection | BaseStyle) => ownedBy(owner)(x) && !skip.has(x.id);
403
+ const nodes = roots.flatMap((r) => [r, ...("findAll" in r ? r.findAll() : [])]);
404
+ const byId = new Map(nodes.map((n) => [n.id, n]));
405
+ const page = roots[0]?.parent;
406
+ const collections = (await figma.variables.getLocalVariableCollectionsAsync()).filter(mine);
407
+ const owned = new Set(collections.map((c) => c.id));
408
+ const styles = (await localStyles()).filter(mine);
409
+
410
+ return fnv1a(
411
+ JSON.stringify({
412
+ rest: await Promise.all(roots.map((r) => r.exportAsync({ format: "JSON_REST_V1" }))),
413
+ paths: nodes.flatMap((n) => (n.type === "VECTOR" ? [n.vectorNetwork] : [])),
414
+ collections: collections.map(propertiesOf),
415
+ variables: (await figma.variables.getLocalVariablesAsync())
416
+ .filter((v) => owned.has(v.variableCollectionId))
417
+ .map(propertiesOf),
418
+ styles: styles.map(propertiesOf),
419
+ flows:
420
+ page?.type === "PAGE"
421
+ ? page.flowStartingPoints.filter((f) => byId.has(f.nodeId) && read(byId.get(f.nodeId)!, "flow") === f.name)
422
+ : [],
423
+ }),
424
+ );
425
+ }
426
+
427
+ /** Each layer's own properties, hashed, by id: what tells which layers a person edited. Positions on the page are left out. */
428
+ export async function layerFingerprints(root: SceneNode) {
429
+ // Only the fields this reads; JSON.stringify still hashes every field the node has.
430
+ type RestNode = { id: string; children?: RestNode[]; absoluteBoundingBox?: object; absoluteRenderBounds?: object };
431
+
432
+ // SAFETY: Figma's REST JSON of a node is an object with a `document` node tree, each node with an id and maybe children.
433
+ const { document } = (await root.exportAsync({ format: "JSON_REST_V1" })) as { document: RestNode };
434
+
435
+ const out: Record<string, string> = {};
436
+
437
+ const visit = ({ children, absoluteBoundingBox: _box, absoluteRenderBounds: _bounds, ...own }: RestNode) => {
438
+ out[own.id] = fnv1a(JSON.stringify(own)).slice(0, 8);
439
+ children?.forEach(visit);
440
+ };
441
+
442
+ visit(document);
443
+
444
+ return out;
445
+ }
446
+
447
+ /** Stores each root's layer fingerprints. A file too large to hold them only loses the per-layer report of edits. */
448
+ export async function recordLayers(roots: SceneNode[]) {
449
+ for (const r of roots) {
450
+ try {
451
+ write(r, "layers", JSON.stringify(await layerFingerprints(r)));
452
+ } catch {
453
+ write(r, "layers", "");
454
+ }
455
+ }
456
+ }
457
+
458
+ /** The layers of `roots` that changed since `recordLayers`, as paths, with a count of the layers removed. */
459
+ export async function editedLayers(roots: SceneNode[]) {
460
+ const out: string[] = [];
461
+ let removed = 0;
462
+
463
+ for (const r of roots) {
464
+ const stored = read(r, "layers");
465
+
466
+ if (!stored) continue;
467
+ const before: Record<string, string> = JSON.parse(stored);
468
+ const now = await layerFingerprints(r);
469
+
470
+ for (const [id, hash] of Object.entries(now)) {
471
+ if (before[id] === hash) continue;
472
+ const n = await figma.getNodeByIdAsync(id);
473
+
474
+ if (n) out.push(pathOf(n));
475
+ }
476
+
477
+ removed += Object.keys(before).filter((id) => !(id in now)).length;
478
+ }
479
+
480
+ return removed ? [...out, `${removed} removed layer${removed > 1 ? "s" : ""}`] : out;
481
+ }
@@ -0,0 +1,97 @@
1
+ import type { TokenImportPlan, TokenImportSummary } from "../core/protocol";
2
+ import { messageOf } from "../core/snapshot";
3
+ import { aliasTarget, modeKey, rgbaOf, unboundAlias, upsertsOf } from "../core/tokens";
4
+
5
+ /** Each plan mode's id in the collection, adding the modes it lacks. The plan's first mode is always the default mode. */
6
+ function modesFor(collection: VariableCollection, plan: TokenImportPlan, warnings: string[]) {
7
+ const ids = new Map([[plan.modes[0], collection.defaultModeId]]);
8
+
9
+ for (const mode of plan.modes.slice(1)) {
10
+ const found = collection.modes.find((m) => modeKey(m.name) === modeKey(mode));
11
+
12
+ if (found) {
13
+ ids.set(mode, found.modeId);
14
+ continue;
15
+ }
16
+
17
+ try {
18
+ ids.set(mode, collection.addMode(mode));
19
+ } catch (e) {
20
+ warnings.push(
21
+ `The ${mode} values were left out: Figma could not add a "${mode}" mode to ${collection.name}: ${messageOf(e)} Figma's Starter plan allows one mode per collection.`,
22
+ );
23
+ }
24
+ }
25
+
26
+ return ids;
27
+ }
28
+
29
+ /**
30
+ * Finds or creates the plan's collection and upserts its variables in two passes, so an alias binds once its target exists. A mode the
31
+ * plan does not set takes the default mode's value.
32
+ */
33
+ export async function importTokens(plan: TokenImportPlan): Promise<TokenImportSummary> {
34
+ const warnings: string[] = [];
35
+ const local = await figma.variables.getLocalVariablesAsync();
36
+ const found = (await figma.variables.getLocalVariableCollectionsAsync()).find((c) => c.name === plan.collection);
37
+ const collection = found ?? figma.variables.createVariableCollection(plan.collection);
38
+
39
+ if (!found) collection.renameMode(collection.defaultModeId, plan.modes[0]);
40
+ const modeIds = modesFor(collection, plan, warnings);
41
+
42
+ const typed = local.map((v) => ({ v, name: v.name, type: v.resolvedType, web: v.codeSyntax.WEB }));
43
+ const own = typed.filter(({ v }) => v.variableCollectionId === collection.id);
44
+ const { upserts, warnings: skipped } = upsertsOf(plan, own);
45
+
46
+ warnings.push(...skipped);
47
+ const byName = new Map<string, (typeof typed)[number]>();
48
+
49
+ for (const { planned, match } of upserts) {
50
+ const v = match?.v ?? figma.variables.createVariable(planned.name, collection, planned.type);
51
+
52
+ if (planned.scopes) {
53
+ try {
54
+ // SAFETY: Figma checks each scope as it sets them, and a scope it does not know lands in the catch below.
55
+ v.scopes = planned.scopes as VariableScope[];
56
+ } catch (e) {
57
+ warnings.push(`${planned.name} keeps its scopes: ${messageOf(e)}`);
58
+ }
59
+ }
60
+
61
+ if (planned.codeSyntaxWeb) v.setVariableCodeSyntax("WEB", planned.codeSyntaxWeb);
62
+ byName.set(planned.name, { v, name: v.name, type: v.resolvedType, web: v.codeSyntax.WEB });
63
+ }
64
+
65
+ for (const aliases of [false, true]) {
66
+ for (const { planned } of upserts) {
67
+ const { v } = byName.get(planned.name)!;
68
+
69
+ for (const [mode, modeId] of modeIds) {
70
+ const value = planned.values[mode] ?? planned.values[plan.modes[0]];
71
+
72
+ if (value === undefined || value instanceof Object !== aliases) continue;
73
+
74
+ try {
75
+ if (value instanceof Object) {
76
+ const target = aliasTarget(value.alias, v.resolvedType, byName, typed);
77
+
78
+ if (target) v.setValueForMode(modeId, figma.variables.createVariableAlias(target.v));
79
+ else warnings.push(unboundAlias(planned.name, mode, value.alias));
80
+ } else v.setValueForMode(modeId, Number(value) === value ? value : rgbaOf(String(value)));
81
+ } catch (e) {
82
+ warnings.push(`${planned.name} keeps its ${mode} value: ${messageOf(e)}`);
83
+ }
84
+ }
85
+ }
86
+ }
87
+
88
+ const updated = upserts.filter((u) => u.match).length;
89
+
90
+ return {
91
+ collection: collection.name,
92
+ created: upserts.length - updated,
93
+ updated,
94
+ modes: collection.modes.map((m) => m.name),
95
+ warnings,
96
+ };
97
+ }