@pixerate/editor 0.26.1 → 0.28.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 (90) hide show
  1. package/README.md +32 -3
  2. package/dist/agent/index.cjs +56 -6
  3. package/dist/agent/index.cjs.map +1 -1
  4. package/dist/agent/index.d.cts +6 -4
  5. package/dist/agent/index.d.ts +6 -4
  6. package/dist/agent/index.js +51 -1
  7. package/dist/agent/index.js.map +1 -1
  8. package/dist/animation/index.cjs +62 -0
  9. package/dist/animation/index.cjs.map +1 -0
  10. package/dist/animation/index.d.cts +296 -0
  11. package/dist/animation/index.d.ts +296 -0
  12. package/dist/animation/index.js +62 -0
  13. package/dist/animation/index.js.map +1 -0
  14. package/dist/{builtins-Chj6zv_O.d.ts → builtins-haN82vjT.d.ts} +33 -3
  15. package/dist/{builtins-CdPcLwwF.d.cts → builtins-nMXh9sT3.d.cts} +33 -3
  16. package/dist/canvas/index.cjs +535 -737
  17. package/dist/canvas/index.cjs.map +1 -1
  18. package/dist/canvas/index.d.cts +74 -291
  19. package/dist/canvas/index.d.ts +74 -291
  20. package/dist/canvas/index.js +417 -619
  21. package/dist/canvas/index.js.map +1 -1
  22. package/dist/{chunk-X7HXL2SB.js → chunk-3RPOW4CS.js} +342 -16
  23. package/dist/chunk-3RPOW4CS.js.map +1 -0
  24. package/dist/{chunk-UBCFIABU.js → chunk-5H2OPMXZ.js} +183 -6
  25. package/dist/chunk-5H2OPMXZ.js.map +1 -0
  26. package/dist/chunk-A6PHCAGX.cjs +87 -0
  27. package/dist/chunk-A6PHCAGX.cjs.map +1 -0
  28. package/dist/{chunk-HRMEDT2L.js → chunk-D6AVOTSD.js} +6 -85
  29. package/dist/chunk-D6AVOTSD.js.map +1 -0
  30. package/dist/chunk-HXDMZQTD.cjs +497 -0
  31. package/dist/chunk-HXDMZQTD.cjs.map +1 -0
  32. package/dist/chunk-IB3ZHQAX.js +497 -0
  33. package/dist/chunk-IB3ZHQAX.js.map +1 -0
  34. package/dist/{chunk-4BVP64JJ.cjs → chunk-K2UYKJ6M.cjs} +24 -103
  35. package/dist/chunk-K2UYKJ6M.cjs.map +1 -0
  36. package/dist/{chunk-HDYMLS3X.cjs → chunk-MC2LQN5S.cjs} +196 -19
  37. package/dist/chunk-MC2LQN5S.cjs.map +1 -0
  38. package/dist/{chunk-XQFHLT53.js → chunk-MXZJ4PKN.js} +24 -10
  39. package/dist/chunk-MXZJ4PKN.js.map +1 -0
  40. package/dist/{chunk-LN2POBHT.cjs → chunk-OYEFRO3D.cjs} +28 -14
  41. package/dist/chunk-OYEFRO3D.cjs.map +1 -0
  42. package/dist/chunk-PWJARCI4.js +637 -0
  43. package/dist/chunk-PWJARCI4.js.map +1 -0
  44. package/dist/chunk-TGD52FEZ.js +87 -0
  45. package/dist/chunk-TGD52FEZ.js.map +1 -0
  46. package/dist/chunk-TTYCN6ZH.cjs +637 -0
  47. package/dist/chunk-TTYCN6ZH.cjs.map +1 -0
  48. package/dist/{chunk-NQF32I6Z.cjs → chunk-U7VGDSNY.cjs} +463 -137
  49. package/dist/chunk-U7VGDSNY.cjs.map +1 -0
  50. package/dist/commands/index.cjs +30 -410
  51. package/dist/commands/index.cjs.map +1 -1
  52. package/dist/commands/index.d.cts +1 -1
  53. package/dist/commands/index.d.ts +1 -1
  54. package/dist/commands/index.js +17 -397
  55. package/dist/commands/index.js.map +1 -1
  56. package/dist/{controller-CxXGOEmy.d.ts → controller-w6eRTjF8.d.cts} +67 -2
  57. package/dist/{controller-CxXGOEmy.d.cts → controller-w6eRTjF8.d.ts} +67 -2
  58. package/dist/extensions/index.cjs +25 -7
  59. package/dist/extensions/index.cjs.map +1 -1
  60. package/dist/extensions/index.d.cts +1 -1
  61. package/dist/extensions/index.d.ts +1 -1
  62. package/dist/extensions/index.js +32 -14
  63. package/dist/generation/index.cjs +3 -3
  64. package/dist/generation/index.cjs.map +1 -1
  65. package/dist/generation/index.js +3 -3
  66. package/dist/{index-jcJwmBYt.d.cts → index-C6gaQRH0.d.cts} +53 -4
  67. package/dist/{index-B273Zllk.d.ts → index-DXAv_R08.d.ts} +53 -4
  68. package/dist/index.cjs +57 -19
  69. package/dist/index.cjs.map +1 -1
  70. package/dist/index.d.cts +7 -5
  71. package/dist/index.d.ts +7 -5
  72. package/dist/index.js +132 -94
  73. package/dist/index.js.map +1 -1
  74. package/dist/spreadsheet/index.cjs +23 -3
  75. package/dist/spreadsheet/index.cjs.map +1 -1
  76. package/dist/spreadsheet/index.d.cts +76 -3
  77. package/dist/spreadsheet/index.d.ts +76 -3
  78. package/dist/spreadsheet/index.js +28 -8
  79. package/dist/tokens/index.cjs +4 -2
  80. package/dist/tokens/index.cjs.map +1 -1
  81. package/dist/tokens/index.js +6 -4
  82. package/package.json +6 -1
  83. package/dist/chunk-4BVP64JJ.cjs.map +0 -1
  84. package/dist/chunk-HDYMLS3X.cjs.map +0 -1
  85. package/dist/chunk-HRMEDT2L.js.map +0 -1
  86. package/dist/chunk-LN2POBHT.cjs.map +0 -1
  87. package/dist/chunk-NQF32I6Z.cjs.map +0 -1
  88. package/dist/chunk-UBCFIABU.js.map +0 -1
  89. package/dist/chunk-X7HXL2SB.js.map +0 -1
  90. package/dist/chunk-XQFHLT53.js.map +0 -1
@@ -1,4 +1,9 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;// src/tokens/types.ts
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;
2
+
3
+
4
+ var _chunkA6PHCAGXcjs = require('./chunk-A6PHCAGX.cjs');
5
+
6
+ // src/tokens/types.ts
2
7
  var TOKEN_TYPES = ["color", "number", "string", "boolean"];
3
8
  var TokenError = class extends Error {
4
9
 
@@ -13,87 +18,6 @@ function isTokenAlias(value) {
13
18
  }
14
19
  var EMPTY_TOKEN_STATE = Object.freeze({ collections: Object.freeze([]), variables: Object.freeze([]) });
15
20
 
16
- // src/tokens/color.ts
17
- var HEX = /^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
18
- var RGB = /^rgba?\(([^()]*)\)$/i;
19
- var clamp01 = (v) => Math.min(1, Math.max(0, v));
20
- var byte = (v) => Math.round(clamp01(v) * 255);
21
- var hex2 = (n) => n.toString(16).padStart(2, "0");
22
- function rgbaToHex(r, g, b, a = 1) {
23
- const head = `#${hex2(byte(r))}${hex2(byte(g))}${hex2(byte(b))}`;
24
- const alpha = byte(a);
25
- return alpha === 255 ? head : head + hex2(alpha);
26
- }
27
- function hexToRgba(hex) {
28
- const normal = normalizeTokenColor(hex);
29
- if (normal === null) return null;
30
- const n = (i) => parseInt(normal.slice(i, i + 2), 16) / 255;
31
- return { r: n(1), g: n(3), b: n(5), a: normal.length === 9 ? n(7) : 1 };
32
- }
33
- function channel(part, scale) {
34
- const pct = part.endsWith("%");
35
- const n = Number(pct ? part.slice(0, -1) : part);
36
- if (!Number.isFinite(n)) return null;
37
- return pct ? n / 100 : n / scale;
38
- }
39
- function normalizeTokenColor(input) {
40
- if (typeof input === "string") {
41
- const text = input.trim();
42
- if (text.length > 200) return null;
43
- const lower = text.toLowerCase();
44
- if (lower === "transparent") return "#00000000";
45
- if (lower === "black") return "#000000";
46
- if (lower === "white") return "#ffffff";
47
- const hex = HEX.exec(text);
48
- if (hex) {
49
- let digits = hex[1].toLowerCase();
50
- if (digits.length <= 4) digits = [...digits].map((c) => c + c).join("");
51
- if (digits.length === 8 && digits.endsWith("ff")) digits = digits.slice(0, 6);
52
- return `#${digits}`;
53
- }
54
- const rgb = RGB.exec(text);
55
- if (rgb) {
56
- const [colour, alphaPart] = rgb[1].split("/");
57
- const parts = colour.split(/[\s,]+/).filter(Boolean);
58
- let alpha = _optionalChain([alphaPart, 'optionalAccess', _ => _.trim, 'call', _2 => _2()]);
59
- if (parts.length === 4 && alpha === void 0) alpha = parts.pop();
60
- if (parts.length !== 3) return null;
61
- const channels = parts.map((p) => channel(p, 255));
62
- const a = alpha === void 0 || alpha === "" ? 1 : channel(alpha, 1);
63
- if (channels.some((c) => c === null) || a === null) return null;
64
- return rgbaToHex(channels[0], channels[1], channels[2], a);
65
- }
66
- return null;
67
- }
68
- if (typeof input === "object" && input !== null) {
69
- const obj = input;
70
- if (Array.isArray(obj.components)) {
71
- const space = obj.colorSpace;
72
- if (space === void 0 || space === "srgb") {
73
- const [r2, g2, b2] = obj.components;
74
- const a2 = obj.alpha === void 0 ? 1 : obj.alpha;
75
- if ([r2, g2, b2, a2].every((v) => typeof v === "number" && Number.isFinite(v))) {
76
- return rgbaToHex(r2, g2, b2, a2);
77
- }
78
- }
79
- if (typeof obj.hex === "string") {
80
- const base = normalizeTokenColor(obj.hex);
81
- if (base === null) return null;
82
- const a2 = typeof obj.alpha === "number" ? obj.alpha : 1;
83
- const c = hexToRgba(base);
84
- return rgbaToHex(c.r, c.g, c.b, a2);
85
- }
86
- return null;
87
- }
88
- const { r, g, b } = obj;
89
- const a = obj.a === void 0 ? 1 : obj.a;
90
- if ([r, g, b, a].every((v) => typeof v === "number" && Number.isFinite(v))) {
91
- return rgbaToHex(r, g, b, a);
92
- }
93
- }
94
- return null;
95
- }
96
-
97
21
  // src/tokens/model.ts
98
22
  var indexes = /* @__PURE__ */ new WeakMap();
99
23
  function indexOf(state) {
@@ -129,7 +53,7 @@ function findTokenMode(collection, key) {
129
53
  return _nullishCoalesce(collection.modes.find((m) => m.id === key), () => ( collection.modes.find((m) => m.name === key)));
130
54
  }
131
55
  function getCurrentMode(collection, modes) {
132
- const chosen = _optionalChain([modes, 'optionalAccess', _3 => _3[collection.id]]);
56
+ const chosen = _optionalChain([modes, 'optionalAccess', _ => _[collection.id]]);
133
57
  return chosen !== void 0 && collection.modes.find((m) => m.id === chosen) || collection.modes[0];
134
58
  }
135
59
  function defaultTokenValue(type) {
@@ -147,7 +71,7 @@ function defaultTokenValue(type) {
147
71
  function coerceTokenLiteral(type, value) {
148
72
  switch (type) {
149
73
  case "color":
150
- return normalizeTokenColor(value);
74
+ return _chunkA6PHCAGXcjs.normalizeTokenColor.call(void 0, value);
151
75
  case "number": {
152
76
  if (typeof value === "number") return Number.isFinite(value) ? value : null;
153
77
  if (typeof value === "string" && value.trim() !== "") {
@@ -170,7 +94,7 @@ function literalTokenType(value) {
170
94
  }
171
95
  function formatTokenValue(state, value) {
172
96
  if (value === void 0) return "";
173
- if (isTokenAlias(value)) return `\u2192 ${_nullishCoalesce(_optionalChain([getTokenVariable, 'call', _4 => _4(state, value.alias), 'optionalAccess', _5 => _5.name]), () => ( value.alias))}`;
97
+ if (isTokenAlias(value)) return `\u2192 ${_nullishCoalesce(_optionalChain([getTokenVariable, 'call', _2 => _2(state, value.alias), 'optionalAccess', _3 => _3.name]), () => ( value.alias))}`;
174
98
  return String(value);
175
99
  }
176
100
  function label(state, id) {
@@ -214,10 +138,10 @@ function resolveToken(state, id, modes) {
214
138
  type = variable.type;
215
139
  const collection = getTokenCollection(state, variable.collectionId);
216
140
  const mode = collection ? getCurrentMode(collection, modes) : void 0;
217
- let modeId = _optionalChain([mode, 'optionalAccess', _6 => _6.id]);
141
+ let modeId = _optionalChain([mode, 'optionalAccess', _4 => _4.id]);
218
142
  let value = modeId !== void 0 ? variable.valuesByMode[modeId] : void 0;
219
143
  if (value === void 0) {
220
- const fallback = _optionalChain([collection, 'optionalAccess', _7 => _7.modes, 'access', _8 => _8[0], 'optionalAccess', _9 => _9.id]);
144
+ const fallback = _optionalChain([collection, 'optionalAccess', _5 => _5.modes, 'access', _6 => _6[0], 'optionalAccess', _7 => _7.id]);
221
145
  if (fallback !== void 0 && variable.valuesByMode[fallback] !== void 0) {
222
146
  modeId = fallback;
223
147
  value = variable.valuesByMode[fallback];
@@ -565,7 +489,7 @@ function parseTokenState(input) {
565
489
  const ids = /* @__PURE__ */ new Set();
566
490
  for (const c of Array.isArray(obj.collections) ? obj.collections : []) {
567
491
  const item = c;
568
- const modes = Array.isArray(_optionalChain([item, 'optionalAccess', _10 => _10.modes])) ? item.modes.filter(
492
+ const modes = Array.isArray(_optionalChain([item, 'optionalAccess', _8 => _8.modes])) ? item.modes.filter(
569
493
  (m) => typeof m === "object" && m !== null && typeof m.id === "string" && typeof m.name === "string"
570
494
  ) : [];
571
495
  if (!item || typeof item.id !== "string" || typeof item.name !== "string" || modes.length === 0 || ids.has(item.id)) {
@@ -582,7 +506,7 @@ function parseTokenState(input) {
582
506
  const item = v;
583
507
  const collection = item && typeof item.collectionId === "string" ? byId.get(item.collectionId) : void 0;
584
508
  if (!item || typeof item.id !== "string" || typeof item.name !== "string" || !collection || !["color", "number", "string", "boolean"].includes(item.type) || varIds.has(item.id)) {
585
- issues.push({ message: "Dropped an invalid variable", variableId: typeof _optionalChain([item, 'optionalAccess', _11 => _11.id]) === "string" ? item.id : void 0 });
509
+ issues.push({ message: "Dropped an invalid variable", variableId: typeof _optionalChain([item, 'optionalAccess', _9 => _9.id]) === "string" ? item.id : void 0 });
586
510
  continue;
587
511
  }
588
512
  varIds.add(item.id);
@@ -954,7 +878,7 @@ function path(name) {
954
878
  }
955
879
  function reference(state, variable) {
956
880
  const collection = getTokenCollection(state, variable.collectionId);
957
- return `{${[_nullishCoalesce(_optionalChain([collection, 'optionalAccess', _12 => _12.name]), () => ( variable.collectionId)), ...path(variable.name)].join(".")}}`;
881
+ return `{${[_nullishCoalesce(_optionalChain([collection, 'optionalAccess', _10 => _10.name]), () => ( variable.collectionId)), ...path(variable.name)].join(".")}}`;
958
882
  }
959
883
  function w3cType(variable) {
960
884
  if (variable.type === "number") {
@@ -965,7 +889,7 @@ function w3cType(variable) {
965
889
  }
966
890
  function w3cLiteral(variable, value, colorFormat) {
967
891
  if (variable.type === "color" && colorFormat === "object") {
968
- const c = hexToRgba(String(value));
892
+ const c = _chunkA6PHCAGXcjs.hexToRgba.call(void 0, String(value));
969
893
  if (c) {
970
894
  const round = (n) => Math.round(n * 1e4) / 1e4;
971
895
  return { colorSpace: "srgb", components: [round(c.r), round(c.g), round(c.b)], alpha: round(c.a), hex: String(value).slice(0, 7) };
@@ -995,7 +919,7 @@ function exportW3CTokens(state, options = {}) {
995
919
  [W3C_TOKENS_EXTENSION]: { id: collection.id, modes: collection.modes.map((m) => ({ id: m.id, name: m.name })) }
996
920
  };
997
921
  }
998
- const chosen = _optionalChain([options, 'access', _13 => _13.modes, 'optionalAccess', _14 => _14[collection.id]]);
922
+ const chosen = _optionalChain([options, 'access', _11 => _11.modes, 'optionalAccess', _12 => _12[collection.id]]);
999
923
  const mode = chosen !== void 0 && collection.modes.find((m) => m.id === chosen) || collection.modes[0];
1000
924
  for (const variable of state.variables) {
1001
925
  if (variable.collectionId !== collection.id) continue;
@@ -1088,7 +1012,7 @@ function inferType(value) {
1088
1012
  if (typeof value === "number") return "number";
1089
1013
  if (typeof value === "string") {
1090
1014
  const text = value.trim();
1091
- if ((text.startsWith("#") || /^rgba?\(/i.test(text)) && normalizeTokenColor(text)) return "color";
1015
+ if ((text.startsWith("#") || /^rgba?\(/i.test(text)) && _chunkA6PHCAGXcjs.normalizeTokenColor.call(void 0, text)) return "color";
1092
1016
  if (MEASURE.test(text) && /[a-z%]$/i.test(text)) return "dimension";
1093
1017
  return "string";
1094
1018
  }
@@ -1163,7 +1087,7 @@ function importW3CTokens(state, input, options = {}) {
1163
1087
  const warn = (message) => {
1164
1088
  if (report.warnings.length < 500) report.warnings.push(message);
1165
1089
  };
1166
- const marked = Object.entries(doc).filter(([key, value]) => !key.startsWith("$") && isObject(value) && !("$value" in value) && Array.isArray(_optionalChain([extensionOf, 'call', _15 => _15(value), 'optionalAccess', _16 => _16.modes])));
1090
+ const marked = Object.entries(doc).filter(([key, value]) => !key.startsWith("$") && isObject(value) && !("$value" in value) && Array.isArray(_optionalChain([extensionOf, 'call', _13 => _13(value), 'optionalAccess', _14 => _14.modes])));
1167
1091
  const plainName = _nullishCoalesce(options.collection, () => ( "Tokens"));
1168
1092
  const sources = [];
1169
1093
  if (marked.length > 0) {
@@ -1271,7 +1195,7 @@ function importW3CTokens(state, input, options = {}) {
1271
1195
  }
1272
1196
  if (!variable) {
1273
1197
  try {
1274
- const result = createTokenVariable(next, { collectionId, name, type }, idFrom(_optionalChain([token, 'access', _17 => _17.ext, 'optionalAccess', _18 => _18.id]), "variable"));
1198
+ const result = createTokenVariable(next, { collectionId, name, type }, idFrom(_optionalChain([token, 'access', _15 => _15.ext, 'optionalAccess', _16 => _16.id]), "variable"));
1275
1199
  next = result.state;
1276
1200
  variable = result.variable;
1277
1201
  report.variablesAdded += 1;
@@ -1282,7 +1206,7 @@ function importW3CTokens(state, input, options = {}) {
1282
1206
  } else report.variablesUpdated += 1;
1283
1207
  variableFor.set(token, variable.id);
1284
1208
  const values = [];
1285
- const extModes = _optionalChain([token, 'access', _19 => _19.ext, 'optionalAccess', _20 => _20.modes]);
1209
+ const extModes = _optionalChain([token, 'access', _17 => _17.ext, 'optionalAccess', _18 => _18.modes]);
1286
1210
  if (isObject(extModes)) {
1287
1211
  for (const [modeName, value] of Object.entries(extModes)) {
1288
1212
  const modeId = ensureMode(collectionId, modeName);
@@ -1309,10 +1233,10 @@ function importW3CTokens(state, input, options = {}) {
1309
1233
  }
1310
1234
  const update = {};
1311
1235
  if (typeof token.description === "string") update.description = token.description;
1312
- const extUnit = _optionalChain([token, 'access', _21 => _21.ext, 'optionalAccess', _22 => _22.unit]);
1236
+ const extUnit = _optionalChain([token, 'access', _19 => _19.ext, 'optionalAccess', _20 => _20.unit]);
1313
1237
  if (typeof extUnit === "string") unit = extUnit;
1314
1238
  if (unit && unit !== variable.unit) update.unit = unit;
1315
- if (Array.isArray(_optionalChain([token, 'access', _23 => _23.ext, 'optionalAccess', _24 => _24.scopes]))) update.scopes = token.ext.scopes.filter((s) => typeof s === "string");
1239
+ if (Array.isArray(_optionalChain([token, 'access', _21 => _21.ext, 'optionalAccess', _22 => _22.scopes]))) update.scopes = token.ext.scopes.filter((s) => typeof s === "string");
1316
1240
  if (Object.keys(update).length > 0) {
1317
1241
  try {
1318
1242
  next = updateTokenVariable(next, variable.id, update);
@@ -1399,8 +1323,5 @@ function importW3CTokens(state, input, options = {}) {
1399
1323
 
1400
1324
 
1401
1325
 
1402
-
1403
-
1404
-
1405
- exports.TOKEN_TYPES = TOKEN_TYPES; exports.TokenError = TokenError; exports.isTokenAlias = isTokenAlias; exports.EMPTY_TOKEN_STATE = EMPTY_TOKEN_STATE; exports.rgbaToHex = rgbaToHex; exports.hexToRgba = hexToRgba; exports.normalizeTokenColor = normalizeTokenColor; exports.getTokenCollection = getTokenCollection; exports.getTokenVariable = getTokenVariable; exports.findTokenCollection = findTokenCollection; exports.findTokenVariable = findTokenVariable; exports.getCollectionVariables = getCollectionVariables; exports.getDefaultMode = getDefaultMode; exports.findTokenMode = findTokenMode; exports.getCurrentMode = getCurrentMode; exports.defaultTokenValue = defaultTokenValue; exports.coerceTokenLiteral = coerceTokenLiteral; exports.literalTokenType = literalTokenType; exports.formatTokenValue = formatTokenValue; exports.resolveToken = resolveToken; exports.resolveTokenValue = resolveTokenValue; exports.resolveTokenInMode = resolveTokenInMode; exports.checkTokenAlias = checkTokenAlias; exports.TOKEN_SCOPES_BY_TYPE = TOKEN_SCOPES_BY_TYPE; exports.isTokenScopeKnown = isTokenScopeKnown; exports.normalizeTokenScopes = normalizeTokenScopes; exports.isTokenInScope = isTokenInScope; exports.normalizeTokenName = normalizeTokenName; exports.defaultTokenId = defaultTokenId; exports.createTokenCollection = createTokenCollection; exports.renameTokenCollection = renameTokenCollection; exports.deleteTokenVariables = deleteTokenVariables; exports.deleteTokenCollection = deleteTokenCollection; exports.addTokenMode = addTokenMode; exports.renameTokenMode = renameTokenMode; exports.removeTokenMode = removeTokenMode; exports.moveTokenMode = moveTokenMode; exports.prepareTokenValue = prepareTokenValue; exports.createTokenVariable = createTokenVariable; exports.setTokenValue = setTokenValue; exports.renameTokenVariable = renameTokenVariable; exports.updateTokenVariable = updateTokenVariable; exports.parseTokenState = parseTokenState; exports.TokenStore = TokenStore; exports.createTokenStore = createTokenStore; exports.tokenSlug = tokenSlug; exports.getTokenCssName = getTokenCssName; exports.cssString = cssString; exports.formatTokenCssValue = formatTokenCssValue; exports.exportTokensCss = exportTokensCss; exports.getTokenCssVariables = getTokenCssVariables; exports.W3C_TOKENS_EXTENSION = W3C_TOKENS_EXTENSION; exports.exportW3CTokens = exportW3CTokens; exports.exportW3CTokensJson = exportW3CTokensJson; exports.importW3CTokens = importW3CTokens;
1406
- //# sourceMappingURL=chunk-4BVP64JJ.cjs.map
1326
+ exports.TOKEN_TYPES = TOKEN_TYPES; exports.TokenError = TokenError; exports.isTokenAlias = isTokenAlias; exports.EMPTY_TOKEN_STATE = EMPTY_TOKEN_STATE; exports.getTokenCollection = getTokenCollection; exports.getTokenVariable = getTokenVariable; exports.findTokenCollection = findTokenCollection; exports.findTokenVariable = findTokenVariable; exports.getCollectionVariables = getCollectionVariables; exports.getDefaultMode = getDefaultMode; exports.findTokenMode = findTokenMode; exports.getCurrentMode = getCurrentMode; exports.defaultTokenValue = defaultTokenValue; exports.coerceTokenLiteral = coerceTokenLiteral; exports.literalTokenType = literalTokenType; exports.formatTokenValue = formatTokenValue; exports.resolveToken = resolveToken; exports.resolveTokenValue = resolveTokenValue; exports.resolveTokenInMode = resolveTokenInMode; exports.checkTokenAlias = checkTokenAlias; exports.TOKEN_SCOPES_BY_TYPE = TOKEN_SCOPES_BY_TYPE; exports.isTokenScopeKnown = isTokenScopeKnown; exports.normalizeTokenScopes = normalizeTokenScopes; exports.isTokenInScope = isTokenInScope; exports.normalizeTokenName = normalizeTokenName; exports.defaultTokenId = defaultTokenId; exports.createTokenCollection = createTokenCollection; exports.renameTokenCollection = renameTokenCollection; exports.deleteTokenVariables = deleteTokenVariables; exports.deleteTokenCollection = deleteTokenCollection; exports.addTokenMode = addTokenMode; exports.renameTokenMode = renameTokenMode; exports.removeTokenMode = removeTokenMode; exports.moveTokenMode = moveTokenMode; exports.prepareTokenValue = prepareTokenValue; exports.createTokenVariable = createTokenVariable; exports.setTokenValue = setTokenValue; exports.renameTokenVariable = renameTokenVariable; exports.updateTokenVariable = updateTokenVariable; exports.parseTokenState = parseTokenState; exports.TokenStore = TokenStore; exports.createTokenStore = createTokenStore; exports.tokenSlug = tokenSlug; exports.getTokenCssName = getTokenCssName; exports.cssString = cssString; exports.formatTokenCssValue = formatTokenCssValue; exports.exportTokensCss = exportTokensCss; exports.getTokenCssVariables = getTokenCssVariables; exports.W3C_TOKENS_EXTENSION = W3C_TOKENS_EXTENSION; exports.exportW3CTokens = exportW3CTokens; exports.exportW3CTokensJson = exportW3CTokensJson; exports.importW3CTokens = importW3CTokens;
1327
+ //# sourceMappingURL=chunk-K2UYKJ6M.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/editor/editor/packages/core/dist/chunk-K2UYKJ6M.cjs","../src/tokens/types.ts","../src/tokens/model.ts","../src/tokens/store.ts","../src/tokens/css.ts","../src/tokens/w3c.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B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MAAA;AAC4B,QAAA;AAC7C,QAAA;AACD,MAAA;AAC8C,MAAA;AAChC,MAAA;AAC+D,QAAA;AAC5E,QAAA;AACD,MAAA;AACiC,MAAA;AAC4B,MAAA;AAC9D,IAAA;AAC4E,IAAA;AACN,IAAA;AAC3C,IAAA;AACa,IAAA;AACU,IAAA;AAC6E,IAAA;AAC3F,IAAA;AAC/B,MAAA;AACiD,QAAA;AACrC,MAAA;AACiC,QAAA;AACjD,MAAA;AACD,IAAA;AACD,EAAA;AAGwD,EAAA;AACC,IAAA;AAC1B,IAAA;AACc,IAAA;AAC7B,IAAA;AAEa,MAAA;AACmD,MAAA;AAEK,MAAA;AAErD,MAAA;AAC/B,IAAA;AACe,IAAA;AAC0E,MAAA;AACxF,MAAA;AACD,IAAA;AACkD,IAAA;AACG,IAAA;AAC1C,IAAA;AAC2B,MAAA;AACrC,MAAA;AACD,IAAA;AACmE,IAAA;AACpE,EAAA;AAE6B,EAAA;AAC9B;AL2tBsG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/editor/editor/packages/core/dist/chunk-K2UYKJ6M.cjs","sourcesContent":[null,"// Portions ported from figcraft/crates/doc/src/styles.rs (MIT OR Apache-2.0, © ArtCraft Team and contributors). See THIRD_PARTY_NOTICES.md.\n\n/**\n * Design tokens (Figma-style \"variables\"): collections hold modes (e.g. Light / Dark) and\n * typed variables with one value per mode. A value is a literal or an alias to another\n * variable of the same type, possibly in another collection.\n *\n * The state is plain, immutable, JSON-serialisable data. Every operation returns a new state.\n */\n\n/** A variable's type. */\nexport type TokenType = 'color' | 'number' | 'string' | 'boolean';\n\nexport const TOKEN_TYPES: readonly TokenType[] = ['color', 'number', 'string', 'boolean'];\n\n/** A resolved value: colours are normalised hex strings (`#rrggbb` or `#rrggbbaa`). */\nexport type TokenLiteral = string | number | boolean;\n\n/** A reference to another variable (by id). */\nexport interface TokenAlias {\n\talias: string;\n}\n\n/** What a variable holds in one mode. */\nexport type TokenValue = TokenLiteral | TokenAlias;\n\nexport interface TokenMode {\n\tid: string;\n\tname: string;\n}\n\nexport interface TokenCollection {\n\tid: string;\n\tname: string;\n\t/** At least one mode. The first one is the default mode. */\n\tmodes: readonly TokenMode[];\n}\n\n/**\n * Which properties pickers offer a variable for (figcraft / Figma scope ids). Scopes only\n * filter pickers: binding out of scope still works.\n */\nexport type TokenScope =\n\t| 'ALL_SCOPES'\n\t| 'ALL_FILLS'\n\t| 'FRAME_FILL'\n\t| 'SHAPE_FILL'\n\t| 'TEXT_FILL'\n\t| 'STROKE_COLOR'\n\t| 'EFFECT_COLOR'\n\t| 'CORNER_RADIUS'\n\t| 'WIDTH_HEIGHT'\n\t| 'GAP'\n\t| 'OPACITY'\n\t| 'STROKE_FLOAT'\n\t| 'EFFECT_FLOAT'\n\t| 'FONT_WEIGHT'\n\t| 'FONT_SIZE'\n\t| 'LINE_HEIGHT'\n\t| 'LETTER_SPACING'\n\t| 'PARAGRAPH_SPACING'\n\t| 'PARAGRAPH_INDENT'\n\t| 'TEXT_CONTENT'\n\t| 'FONT_FAMILY'\n\t| 'FONT_STYLE';\n\nexport interface TokenVariable {\n\tid: string;\n\t/** Unique within its collection. `/` separates groups (`color/bg`). */\n\tname: string;\n\tcollectionId: string;\n\ttype: TokenType;\n\t/** Value per mode id of the collection. */\n\tvaluesByMode: Readonly<Record<string, TokenValue>>;\n\tdescription?: string;\n\t/** Pickers offer the variable for these scopes; `undefined` = every supported property. */\n\tscopes?: readonly TokenScope[];\n\t/** Unit for number variables in CSS / W3C export (`px`, `rem`, `ms`, …). */\n\tunit?: string;\n}\n\nexport interface TokenState {\n\tcollections: readonly TokenCollection[];\n\tvariables: readonly TokenVariable[];\n}\n\n/**\n * Chosen mode per collection: `{ [collectionId]: modeId }`. Collections not listed (or with an\n * unknown mode) use their default (first) mode.\n */\nexport type TokenModeContext = Readonly<Record<string, string>>;\n\nexport type TokenErrorCode =\n\t| 'not-found'\n\t| 'invalid-name'\n\t| 'duplicate-name'\n\t| 'name-conflict'\n\t| 'invalid-type'\n\t| 'invalid-value'\n\t| 'type-mismatch'\n\t| 'alias-missing'\n\t| 'alias-cycle'\n\t| 'last-mode'\n\t| 'unknown-scope'\n\t| 'invalid-input';\n\n/** Thrown by token operations that are refused; `code` says why. */\nexport class TokenError extends Error {\n\treadonly code: TokenErrorCode;\n\tconstructor(code: TokenErrorCode, message: string) {\n\t\tsuper(message);\n\t\tthis.name = 'TokenError';\n\t\tthis.code = code;\n\t}\n}\n\nexport function isTokenAlias(value: unknown): value is TokenAlias {\n\treturn typeof value === 'object' && value !== null && typeof (value as TokenAlias).alias === 'string';\n}\n\nexport const EMPTY_TOKEN_STATE: TokenState = Object.freeze({ collections: Object.freeze([]), variables: Object.freeze([]) }) as TokenState;\n","// Portions ported from figcraft/crates/doc/src/styles.rs and figcraft/crates/engine/src/cmd/variables.rs (MIT OR Apache-2.0, © ArtCraft Team and contributors). See THIRD_PARTY_NOTICES.md.\nimport { normalizeTokenColor } from './color.js';\nimport {\n\tTokenError,\n\tisTokenAlias,\n\ttype TokenCollection,\n\ttype TokenLiteral,\n\ttype TokenMode,\n\ttype TokenModeContext,\n\ttype TokenScope,\n\ttype TokenState,\n\ttype TokenType,\n\ttype TokenValue,\n\ttype TokenVariable\n} from './types.js';\n\n// ---------------------------------------------------------------------------------------------\n// Lookups\n\ninterface TokenIndex {\n\tcollections: Map<string, TokenCollection>;\n\tvariables: Map<string, TokenVariable>;\n}\n\nconst indexes = new WeakMap<TokenState, TokenIndex>();\n\nfunction indexOf(state: TokenState): TokenIndex {\n\tlet index = indexes.get(state);\n\tif (!index) {\n\t\tindex = {\n\t\t\tcollections: new Map(state.collections.map((c) => [c.id, c])),\n\t\t\tvariables: new Map(state.variables.map((v) => [v.id, v]))\n\t\t};\n\t\tindexes.set(state, index);\n\t}\n\treturn index;\n}\n\nexport function getTokenCollection(state: TokenState, id: string): TokenCollection | undefined {\n\treturn indexOf(state).collections.get(id);\n}\n\nexport function getTokenVariable(state: TokenState, id: string): TokenVariable | undefined {\n\treturn indexOf(state).variables.get(id);\n}\n\n/** The collection with this name. */\nexport function findTokenCollection(state: TokenState, name: string): TokenCollection | undefined {\n\treturn state.collections.find((c) => c.name === name);\n}\n\n/** The variable named `name` (in `collectionId` when given, else the first match). */\nexport function findTokenVariable(state: TokenState, name: string, collectionId?: string): TokenVariable | undefined {\n\treturn state.variables.find((v) => v.name === name && (collectionId === undefined || v.collectionId === collectionId));\n}\n\n/** The variables of a collection, in order. */\nexport function getCollectionVariables(state: TokenState, collectionId: string): TokenVariable[] {\n\treturn state.variables.filter((v) => v.collectionId === collectionId);\n}\n\n/** The collection's default (first) mode. */\nexport function getDefaultMode(collection: TokenCollection): TokenMode {\n\treturn collection.modes[0];\n}\n\n/** The mode with id `key`, else the one named `key`. */\nexport function findTokenMode(collection: TokenCollection, key: string): TokenMode | undefined {\n\treturn collection.modes.find((m) => m.id === key) ?? collection.modes.find((m) => m.name === key);\n}\n\n/** The mode `collection` is in under `modes` (its chosen mode if valid, else the default). */\nexport function getCurrentMode(collection: TokenCollection, modes: TokenModeContext | undefined): TokenMode {\n\tconst chosen = modes?.[collection.id];\n\treturn (chosen !== undefined && collection.modes.find((m) => m.id === chosen)) || collection.modes[0];\n}\n\n// ---------------------------------------------------------------------------------------------\n// Values\n\n/** A new variable's value per type: black, 0, empty, true (figcraft's pinned defaults). */\nexport function defaultTokenValue(type: TokenType): TokenLiteral {\n\tswitch (type) {\n\t\tcase 'color':\n\t\t\treturn '#000000';\n\t\tcase 'number':\n\t\t\treturn 0;\n\t\tcase 'string':\n\t\t\treturn '';\n\t\tcase 'boolean':\n\t\t\treturn true;\n\t}\n}\n\n/** The literal as `type`, or `null` when it does not fit (colours are normalised). */\nexport function coerceTokenLiteral(type: TokenType, value: unknown): TokenLiteral | null {\n\tswitch (type) {\n\t\tcase 'color':\n\t\t\treturn normalizeTokenColor(value);\n\t\tcase 'number': {\n\t\t\tif (typeof value === 'number') return Number.isFinite(value) ? value : null;\n\t\t\tif (typeof value === 'string' && value.trim() !== '') {\n\t\t\t\tconst n = Number(value);\n\t\t\t\treturn Number.isFinite(n) ? n : null;\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t\tcase 'string':\n\t\t\treturn typeof value === 'string' ? value : null;\n\t\tcase 'boolean':\n\t\t\tif (typeof value === 'boolean') return value;\n\t\t\tif (value === 'true') return true;\n\t\t\tif (value === 'false') return false;\n\t\t\treturn null;\n\t}\n}\n\n/** The type of a literal value (strings that are colours count as strings). */\nexport function literalTokenType(value: TokenLiteral): TokenType {\n\treturn typeof value === 'number' ? 'number' : typeof value === 'boolean' ? 'boolean' : 'string';\n}\n\n/** A short text for a value: hex, number, string, boolean, or `→ name` for an alias. */\nexport function formatTokenValue(state: TokenState, value: TokenValue | undefined): string {\n\tif (value === undefined) return '';\n\tif (isTokenAlias(value)) return `→ ${getTokenVariable(state, value.alias)?.name ?? value.alias}`;\n\treturn String(value);\n}\n\n// ---------------------------------------------------------------------------------------------\n// Resolution\n\nexport type TokenResolutionErrorCode = 'missing' | 'cycle' | 'no-value' | 'type-mismatch';\n\nexport type TokenResolution =\n\t| {\n\t\t\tok: true;\n\t\t\tvalue: TokenLiteral;\n\t\t\ttype: TokenType;\n\t\t\t/** The variable whose literal was used (the end of the alias chain). */\n\t\t\tvariable: TokenVariable;\n\t\t\t/** Mode of `variable`'s collection that supplied the value. */\n\t\t\tmodeId: string;\n\t\t\t/** Variable ids visited, starting with the requested one. */\n\t\t\tchain: string[];\n\t }\n\t| {\n\t\t\tok: false;\n\t\t\tcode: TokenResolutionErrorCode;\n\t\t\tmessage: string;\n\t\t\tchain: string[];\n\t };\n\n/** The name of a variable for messages. */\nfunction label(state: TokenState, id: string): string {\n\tconst v = getTokenVariable(state, id);\n\treturn v ? `\\`${v.name}\\`` : `\\`${id}\\``;\n}\n\n/**\n * Resolves variable `id` under `modes` (collection id → mode id; the default mode otherwise),\n * following aliases. Each variable along the chain is read in its own collection's mode.\n * Cycles, missing variables and type changes along the chain are reported, never thrown.\n */\nexport function resolveToken(state: TokenState, id: string, modes?: TokenModeContext): TokenResolution {\n\tconst chain: string[] = [];\n\tconst seen = new Set<string>();\n\tlet current = id;\n\tlet type: TokenType | undefined;\n\tfor (;;) {\n\t\tif (seen.has(current)) {\n\t\t\tchain.push(current);\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tcode: 'cycle',\n\t\t\t\tmessage: `Alias cycle: ${chain.map((c) => label(state, c)).join(' → ')}`,\n\t\t\t\tchain\n\t\t\t};\n\t\t}\n\t\tseen.add(current);\n\t\tchain.push(current);\n\t\tconst variable = getTokenVariable(state, current);\n\t\tif (!variable) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tcode: 'missing',\n\t\t\t\tmessage:\n\t\t\t\t\tchain.length === 1\n\t\t\t\t\t\t? `No variable ${label(state, current)}`\n\t\t\t\t\t\t: `${label(state, chain[chain.length - 2])} aliases a missing variable ${label(state, current)}`,\n\t\t\t\tchain\n\t\t\t};\n\t\t}\n\t\tif (type !== undefined && variable.type !== type) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tcode: 'type-mismatch',\n\t\t\t\tmessage: `${label(state, chain[chain.length - 2])} (${type}) aliases ${label(state, current)} (${variable.type})`,\n\t\t\t\tchain\n\t\t\t};\n\t\t}\n\t\ttype = variable.type;\n\t\tconst collection = getTokenCollection(state, variable.collectionId);\n\t\tconst mode = collection ? getCurrentMode(collection, modes) : undefined;\n\t\tlet modeId = mode?.id;\n\t\tlet value = modeId !== undefined ? variable.valuesByMode[modeId] : undefined;\n\t\tif (value === undefined) {\n\t\t\t// figcraft: a missing per-mode value falls back to the default mode, then any value.\n\t\t\tconst fallback = collection?.modes[0]?.id;\n\t\t\tif (fallback !== undefined && variable.valuesByMode[fallback] !== undefined) {\n\t\t\t\tmodeId = fallback;\n\t\t\t\tvalue = variable.valuesByMode[fallback];\n\t\t\t} else {\n\t\t\t\tconst first = Object.keys(variable.valuesByMode)[0];\n\t\t\t\tif (first !== undefined) {\n\t\t\t\t\tmodeId = first;\n\t\t\t\t\tvalue = variable.valuesByMode[first];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (value === undefined || modeId === undefined) {\n\t\t\treturn { ok: false, code: 'no-value', message: `${label(state, current)} has no value`, chain };\n\t\t}\n\t\tif (isTokenAlias(value)) {\n\t\t\tcurrent = value.alias;\n\t\t\tcontinue;\n\t\t}\n\t\treturn { ok: true, value, type: variable.type, variable, modeId, chain };\n\t}\n}\n\n/** The resolved literal, or `undefined` when it does not resolve. */\nexport function resolveTokenValue(state: TokenState, id: string, modes?: TokenModeContext): TokenLiteral | undefined {\n\tconst result = resolveToken(state, id, modes);\n\treturn result.ok ? result.value : undefined;\n}\n\n/** The value of `variableId` in mode `modeId` of its own collection (other collections in their default mode). */\nexport function resolveTokenInMode(state: TokenState, variableId: string, modeId: string): TokenLiteral | undefined {\n\tconst variable = getTokenVariable(state, variableId);\n\tif (!variable) return undefined;\n\treturn resolveTokenValue(state, variableId, { [variable.collectionId]: modeId });\n}\n\n/**\n * Why `variable` cannot alias `targetId`, or `null` when it can: the target must exist, have\n * the same type, and not lead back to `variable` through any alias in any mode.\n */\nexport function checkTokenAlias(state: TokenState, variable: Pick<TokenVariable, 'id' | 'type' | 'name'>, targetId: string): TokenError | null {\n\tconst target = getTokenVariable(state, targetId);\n\tif (!target) return new TokenError('alias-missing', `No variable \\`${targetId}\\` to alias`);\n\tif (target.type !== variable.type) {\n\t\treturn new TokenError('type-mismatch', `Can't alias a ${variable.type} variable to a ${target.type} one (\\`${target.name}\\`)`);\n\t}\n\t// Depth-first search over alias edges in every mode, remembering the path for the message.\n\tconst parent = new Map<string, string | null>([[target.id, null]]);\n\tconst stack = [target.id];\n\twhile (stack.length > 0) {\n\t\tconst current = stack.pop()!;\n\t\tif (current === variable.id) {\n\t\t\tconst path: string[] = [];\n\t\t\tfor (let at: string | null | undefined = current; at != null; at = parent.get(at)) path.push(at);\n\t\t\tconst names = [variable.id, ...path.reverse()].map((id) => (id === variable.id ? `\\`${variable.name}\\`` : label(state, id)));\n\t\t\treturn new TokenError('alias-cycle', `The alias would create a cycle: ${names.join(' → ')}`);\n\t\t}\n\t\tconst v = getTokenVariable(state, current);\n\t\tif (!v) continue;\n\t\tfor (const value of Object.values(v.valuesByMode)) {\n\t\t\tif (isTokenAlias(value) && !parent.has(value.alias)) {\n\t\t\t\tparent.set(value.alias, current);\n\t\t\t\tstack.push(value.alias);\n\t\t\t}\n\t\t}\n\t}\n\treturn null;\n}\n\n// ---------------------------------------------------------------------------------------------\n// Scopes\n\nexport const TOKEN_SCOPES_BY_TYPE: Readonly<Record<TokenType, readonly TokenScope[]>> = {\n\tnumber: [\n\t\t'CORNER_RADIUS',\n\t\t'WIDTH_HEIGHT',\n\t\t'GAP',\n\t\t'OPACITY',\n\t\t'STROKE_FLOAT',\n\t\t'EFFECT_FLOAT',\n\t\t'FONT_WEIGHT',\n\t\t'FONT_SIZE',\n\t\t'LINE_HEIGHT',\n\t\t'LETTER_SPACING',\n\t\t'PARAGRAPH_SPACING',\n\t\t'PARAGRAPH_INDENT',\n\t\t'TEXT_CONTENT'\n\t],\n\tcolor: ['FRAME_FILL', 'SHAPE_FILL', 'TEXT_FILL', 'STROKE_COLOR', 'EFFECT_COLOR'],\n\tstring: ['TEXT_CONTENT', 'FONT_FAMILY', 'FONT_STYLE'],\n\tboolean: []\n};\n\n/** Whether `scope` is a scope a variable of `type` can be limited to. */\nexport function isTokenScopeKnown(type: TokenType, scope: string): scope is TokenScope {\n\treturn scope === 'ALL_SCOPES' || (scope === 'ALL_FILLS' && type === 'color') || (TOKEN_SCOPES_BY_TYPE[type] as readonly string[]).includes(scope);\n}\n\n/**\n * Canonical scope list: known ids only, no repeats, `undefined` (no limit) when every\n * supported property is named. Unknown ids throw `unknown-scope`.\n */\nexport function normalizeTokenScopes(type: TokenType, scopes: readonly string[] | null | undefined): TokenScope[] | undefined {\n\tif (scopes == null) return undefined;\n\tconst list: TokenScope[] = [];\n\tfor (const scope of scopes) {\n\t\tif (!isTokenScopeKnown(type, scope)) throw new TokenError('unknown-scope', `Unknown ${type} scope \\`${scope}\\``);\n\t\tif (!list.includes(scope)) list.push(scope);\n\t}\n\tconst allowed = TOKEN_SCOPES_BY_TYPE[type];\n\tconst all = list.includes('ALL_SCOPES') || (allowed.length > 0 && allowed.every((s) => list.includes(s)));\n\treturn all ? undefined : list;\n}\n\n/** Whether pickers offer `variable` for a property of `scope` (no scope: any). */\nexport function isTokenInScope(variable: Pick<TokenVariable, 'scopes'>, scope: TokenScope | undefined): boolean {\n\tif (!variable.scopes || scope === undefined) return true;\n\treturn variable.scopes.some((s) => s === scope || s === 'ALL_SCOPES' || (s === 'ALL_FILLS' && scope.endsWith('_FILL')));\n}\n\n// ---------------------------------------------------------------------------------------------\n// Names\n\nconst BAD_NAME_CHARS = /[{}.]/;\n\n/** Trims each `/`-separated group; throws `invalid-name` when empty or not exportable. */\nexport function normalizeTokenName(name: unknown, what = 'Variable'): string {\n\tif (typeof name !== 'string') throw new TokenError('invalid-name', `${what} name must be a string`);\n\tconst segments = name.split('/').map((s) => s.trim());\n\tif (name.length > 500 || segments.some((s) => s === '')) {\n\t\tthrow new TokenError('invalid-name', `${what} name \\`${name}\\` has an empty group`);\n\t}\n\tfor (const segment of segments) {\n\t\tif (BAD_NAME_CHARS.test(segment) || segment.startsWith('$')) {\n\t\t\tthrow new TokenError('invalid-name', `${what} name \\`${name}\\` can't contain \\`{\\`, \\`}\\` or \\`.\\`, or start a group with \\`$\\``);\n\t\t}\n\t}\n\treturn segments.join('/');\n}\n\nfunction normalizeModeName(name: unknown): string {\n\tif (typeof name !== 'string' || name.trim() === '') throw new TokenError('invalid-name', 'Mode name can\\'t be empty');\n\treturn name.trim().slice(0, 200);\n}\n\nfunction checkVariableName(state: TokenState, collectionId: string, name: string, exceptId?: string): void {\n\tfor (const other of state.variables) {\n\t\tif (other.collectionId !== collectionId || other.id === exceptId) continue;\n\t\tif (other.name === name) throw new TokenError('duplicate-name', `A variable named \\`${name}\\` already exists in this collection`);\n\t\t// A token can't also be a group (W3C design tokens): `color` and `color/bg` clash.\n\t\tif (other.name.startsWith(name + '/') || name.startsWith(other.name + '/')) {\n\t\t\tthrow new TokenError('name-conflict', `\\`${name}\\` clashes with \\`${other.name}\\`: a name can't be both a variable and a group`);\n\t\t}\n\t}\n}\n\n// ---------------------------------------------------------------------------------------------\n// Operations (pure: each returns a new state, or throws a TokenError)\n\nexport type TokenIdFactory = (kind: 'collection' | 'mode' | 'variable') => string;\n\nlet fallbackCounter = 0;\n/** Default id factory: `crypto.randomUUID`, with a counter fallback. */\nexport const defaultTokenId: TokenIdFactory = (kind) => {\n\tif (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') return `${kind}-${crypto.randomUUID()}`;\n\tfallbackCounter += 1;\n\treturn `${kind}-${Date.now().toString(36)}-${fallbackCounter}`;\n};\n\nfunction requireCollection(state: TokenState, id: string): TokenCollection {\n\tconst c = getTokenCollection(state, id);\n\tif (!c) throw new TokenError('not-found', `No collection \\`${id}\\``);\n\treturn c;\n}\n\nfunction requireVariable(state: TokenState, id: string): TokenVariable {\n\tconst v = getTokenVariable(state, id);\n\tif (!v) throw new TokenError('not-found', `No variable \\`${id}\\``);\n\treturn v;\n}\n\nfunction requireMode(collection: TokenCollection, key: string): TokenMode {\n\tconst m = findTokenMode(collection, key);\n\tif (!m) throw new TokenError('not-found', `No mode \\`${key}\\` in \\`${collection.name}\\``);\n\treturn m;\n}\n\nfunction replaceCollection(state: TokenState, next: TokenCollection): TokenState {\n\treturn { ...state, collections: state.collections.map((c) => (c.id === next.id ? next : c)) };\n}\n\nfunction replaceVariable(state: TokenState, next: TokenVariable): TokenState {\n\treturn { ...state, variables: state.variables.map((v) => (v.id === next.id ? next : v)) };\n}\n\nexport interface CreateTokenCollectionInput {\n\tname: string;\n\t/** Mode names (default `['Default']`). */\n\tmodes?: readonly string[];\n}\n\nexport function createTokenCollection(\n\tstate: TokenState,\n\tinput: CreateTokenCollectionInput,\n\tcreateId: TokenIdFactory = defaultTokenId\n): { state: TokenState; collection: TokenCollection } {\n\tconst name = normalizeTokenName(input.name, 'Collection');\n\tif (state.collections.some((c) => c.name === name)) {\n\t\tthrow new TokenError('duplicate-name', `A collection named \\`${name}\\` already exists`);\n\t}\n\tconst modeNames = input.modes && input.modes.length > 0 ? input.modes.map(normalizeModeName) : ['Default'];\n\tconst collection: TokenCollection = {\n\t\tid: createId('collection'),\n\t\tname,\n\t\tmodes: modeNames.map((n) => ({ id: createId('mode'), name: n }))\n\t};\n\treturn { state: { ...state, collections: [...state.collections, collection] }, collection };\n}\n\nexport function renameTokenCollection(state: TokenState, id: string, name: string): TokenState {\n\tconst collection = requireCollection(state, id);\n\tconst next = normalizeTokenName(name, 'Collection');\n\tif (state.collections.some((c) => c.id !== id && c.name === next)) {\n\t\tthrow new TokenError('duplicate-name', `A collection named \\`${next}\\` already exists`);\n\t}\n\treturn replaceCollection(state, { ...collection, name: next });\n}\n\n/**\n * Deletes variables `ids`. Variables aliasing one of them take its values (per mode: the deleted\n * variable resolved in that mode when it is in the same collection, else in its default mode).\n */\nexport function deleteTokenVariables(state: TokenState, ids: Iterable<string>): { state: TokenState; deleted: string[] } {\n\tconst gone = new Set<string>();\n\tfor (const id of ids) if (getTokenVariable(state, id)) gone.add(id);\n\tif (gone.size === 0) return { state, deleted: [] };\n\tconst variables: TokenVariable[] = [];\n\tfor (const v of state.variables) {\n\t\tif (gone.has(v.id)) continue;\n\t\tlet values: Record<string, TokenValue> | null = null;\n\t\tfor (const [modeId, value] of Object.entries(v.valuesByMode)) {\n\t\t\tif (!isTokenAlias(value) || !gone.has(value.alias)) continue;\n\t\t\tconst target = getTokenVariable(state, value.alias)!;\n\t\t\tconst resolved = resolveTokenValue(state, target.id, { [target.collectionId]: modeId, [v.collectionId]: modeId });\n\t\t\tvalues ??= { ...v.valuesByMode };\n\t\t\tvalues[modeId] = resolved ?? defaultTokenValue(v.type);\n\t\t}\n\t\tvariables.push(values ? { ...v, valuesByMode: values } : v);\n\t}\n\treturn { state: { ...state, variables }, deleted: [...gone] };\n}\n\n/** Deletes a collection and its variables (aliases into it are detached to their values). */\nexport function deleteTokenCollection(state: TokenState, id: string): { state: TokenState; deleted: string[] } {\n\trequireCollection(state, id);\n\tconst result = deleteTokenVariables(\n\t\tstate,\n\t\tstate.variables.filter((v) => v.collectionId === id).map((v) => v.id)\n\t);\n\treturn { state: { ...result.state, collections: result.state.collections.filter((c) => c.id !== id) }, deleted: result.deleted };\n}\n\n/**\n * Adds a mode. Variables start with the values of mode `from` (default: the default mode).\n */\nexport function addTokenMode(\n\tstate: TokenState,\n\tcollectionId: string,\n\tname: string,\n\toptions: { from?: string } = {},\n\tcreateId: TokenIdFactory = defaultTokenId\n): { state: TokenState; mode: TokenMode } {\n\tconst collection = requireCollection(state, collectionId);\n\tconst modeName = normalizeModeName(name);\n\tif (collection.modes.some((m) => m.name === modeName)) {\n\t\tthrow new TokenError('duplicate-name', `\\`${collection.name}\\` already has a mode named \\`${modeName}\\``);\n\t}\n\tconst source = options.from !== undefined ? requireMode(collection, options.from) : collection.modes[0];\n\tconst mode: TokenMode = { id: createId('mode'), name: modeName };\n\tlet next = replaceCollection(state, { ...collection, modes: [...collection.modes, mode] });\n\tnext = {\n\t\t...next,\n\t\tvariables: next.variables.map((v) => {\n\t\t\tif (v.collectionId !== collectionId) return v;\n\t\t\tconst value = v.valuesByMode[source.id] ?? defaultTokenValue(v.type);\n\t\t\treturn { ...v, valuesByMode: { ...v.valuesByMode, [mode.id]: value } };\n\t\t})\n\t};\n\treturn { state: next, mode };\n}\n\nexport function renameTokenMode(state: TokenState, collectionId: string, modeId: string, name: string): TokenState {\n\tconst collection = requireCollection(state, collectionId);\n\tconst mode = requireMode(collection, modeId);\n\tconst modeName = normalizeModeName(name);\n\tif (collection.modes.some((m) => m.id !== mode.id && m.name === modeName)) {\n\t\tthrow new TokenError('duplicate-name', `\\`${collection.name}\\` already has a mode named \\`${modeName}\\``);\n\t}\n\treturn replaceCollection(state, { ...collection, modes: collection.modes.map((m) => (m.id === mode.id ? { ...m, name: modeName } : m)) });\n}\n\n/** Removes a mode and its values; a collection keeps at least one mode. */\nexport function removeTokenMode(state: TokenState, collectionId: string, modeId: string): TokenState {\n\tconst collection = requireCollection(state, collectionId);\n\tconst mode = requireMode(collection, modeId);\n\tif (collection.modes.length < 2) throw new TokenError('last-mode', 'A collection keeps at least one mode');\n\tconst next = replaceCollection(state, { ...collection, modes: collection.modes.filter((m) => m.id !== mode.id) });\n\treturn {\n\t\t...next,\n\t\tvariables: next.variables.map((v) => {\n\t\t\tif (v.collectionId !== collectionId || !(mode.id in v.valuesByMode)) return v;\n\t\t\tconst values = { ...v.valuesByMode };\n\t\t\tdelete values[mode.id];\n\t\t\treturn { ...v, valuesByMode: values };\n\t\t})\n\t};\n}\n\n/** Moves a mode to index `to` (clamped). Index 0 makes it the default mode. */\nexport function moveTokenMode(state: TokenState, collectionId: string, modeId: string, to: number): TokenState {\n\tconst collection = requireCollection(state, collectionId);\n\tconst mode = requireMode(collection, modeId);\n\tconst modes = collection.modes.filter((m) => m.id !== mode.id);\n\tconst at = Math.min(Math.max(Number.isFinite(to) ? Math.trunc(to) : 0, 0), modes.length);\n\tmodes.splice(at, 0, mode);\n\treturn replaceCollection(state, { ...collection, modes });\n}\n\nexport interface CreateTokenVariableInput {\n\tcollectionId: string;\n\tname: string;\n\ttype: TokenType;\n\t/** Value for every mode (literal or `{ alias }`). Default: the type's default. */\n\tvalue?: unknown;\n\t/** Values by mode id or name (win over `value`). */\n\tvalues?: Readonly<Record<string, unknown>>;\n\tdescription?: string;\n\tscopes?: readonly string[];\n\tunit?: string;\n}\n\n/** A value for `variable`: a normalised literal or a checked alias. Throws when refused. */\nexport function prepareTokenValue(state: TokenState, variable: Pick<TokenVariable, 'id' | 'type' | 'name'>, value: unknown): TokenValue {\n\tif (isTokenAlias(value)) {\n\t\tconst error = checkTokenAlias(state, variable, value.alias);\n\t\tif (error) throw error;\n\t\treturn { alias: value.alias };\n\t}\n\tconst literal = coerceTokenLiteral(variable.type, value);\n\tif (literal === null) {\n\t\tthrow new TokenError('invalid-value', `\\`${String(value)}\\` is not a ${variable.type} value for \\`${variable.name}\\``);\n\t}\n\treturn literal;\n}\n\nfunction normalizeUnit(unit: unknown): string | undefined {\n\tif (unit === undefined || unit === null || unit === '') return undefined;\n\tif (typeof unit !== 'string' || !/^[a-z%]{1,8}$/i.test(unit)) throw new TokenError('invalid-value', `Unknown unit \\`${String(unit)}\\``);\n\treturn unit.toLowerCase();\n}\n\nexport function createTokenVariable(\n\tstate: TokenState,\n\tinput: CreateTokenVariableInput,\n\tcreateId: TokenIdFactory = defaultTokenId\n): { state: TokenState; variable: TokenVariable } {\n\tconst collection = requireCollection(state, input.collectionId);\n\tif (!(['color', 'number', 'string', 'boolean'] as unknown[]).includes(input.type)) {\n\t\tthrow new TokenError('invalid-type', `Unknown variable type \\`${String(input.type)}\\``);\n\t}\n\tconst name = normalizeTokenName(input.name);\n\tcheckVariableName(state, collection.id, name);\n\tconst id = createId('variable');\n\tconst stub = { id, type: input.type, name };\n\tconst base = input.value === undefined ? defaultTokenValue(input.type) : prepareTokenValue(state, stub, input.value);\n\tconst valuesByMode: Record<string, TokenValue> = {};\n\tfor (const mode of collection.modes) valuesByMode[mode.id] = base;\n\tif (input.values) {\n\t\tfor (const [key, raw] of Object.entries(input.values)) {\n\t\t\tconst mode = requireMode(collection, key);\n\t\t\tvaluesByMode[mode.id] = prepareTokenValue(state, stub, raw);\n\t\t}\n\t}\n\tconst variable: TokenVariable = {\n\t\tid,\n\t\tname,\n\t\tcollectionId: collection.id,\n\t\ttype: input.type,\n\t\tvaluesByMode,\n\t\t...(input.description ? { description: String(input.description) } : {}),\n\t\t...(input.scopes !== undefined ? { scopes: normalizeTokenScopes(input.type, input.scopes) } : {}),\n\t};\n\tif (variable.scopes === undefined) delete variable.scopes;\n\tconst unit = normalizeUnit(input.unit);\n\tif (unit) variable.unit = unit;\n\treturn { state: { ...state, variables: [...state.variables, variable] }, variable };\n}\n\n/**\n * Sets a variable's value in one mode (id or name; default: the default mode) to a literal or\n * `{ alias: variableId }`. Aliases must keep the type and not create a cycle.\n */\nexport function setTokenValue(state: TokenState, variableId: string, value: unknown, modeId?: string): TokenState {\n\tconst variable = requireVariable(state, variableId);\n\tconst collection = requireCollection(state, variable.collectionId);\n\tconst mode = modeId === undefined ? collection.modes[0] : requireMode(collection, modeId);\n\tconst prepared = prepareTokenValue(state, variable, value);\n\tconst current = variable.valuesByMode[mode.id];\n\tif (current === prepared || (isTokenAlias(current) && isTokenAlias(prepared) && current.alias === prepared.alias)) return state;\n\treturn replaceVariable(state, { ...variable, valuesByMode: { ...variable.valuesByMode, [mode.id]: prepared } });\n}\n\nexport function renameTokenVariable(state: TokenState, variableId: string, name: string): TokenState {\n\tconst variable = requireVariable(state, variableId);\n\tconst next = normalizeTokenName(name);\n\tif (next === variable.name) return state;\n\tcheckVariableName(state, variable.collectionId, next, variable.id);\n\treturn replaceVariable(state, { ...variable, name: next });\n}\n\nexport interface UpdateTokenVariableInput {\n\tdescription?: string;\n\t/** `null` clears the limit (every property). */\n\tscopes?: readonly string[] | null;\n\t/** `null` clears the unit. */\n\tunit?: string | null;\n}\n\nexport function updateTokenVariable(state: TokenState, variableId: string, input: UpdateTokenVariableInput): TokenState {\n\tconst variable = requireVariable(state, variableId);\n\tconst next: TokenVariable = { ...variable };\n\tif (input.description !== undefined) {\n\t\tif (input.description) next.description = String(input.description);\n\t\telse delete next.description;\n\t}\n\tif (input.scopes !== undefined) {\n\t\tconst scopes = normalizeTokenScopes(variable.type, input.scopes);\n\t\tif (scopes) next.scopes = scopes;\n\t\telse delete next.scopes;\n\t}\n\tif (input.unit !== undefined) {\n\t\tconst unit = normalizeUnit(input.unit);\n\t\tif (unit) next.unit = unit;\n\t\telse delete next.unit;\n\t}\n\treturn replaceVariable(state, next);\n}\n\n// ---------------------------------------------------------------------------------------------\n// Validation of untrusted state\n\nexport interface TokenStateIssue {\n\tmessage: string;\n\tcollectionId?: string;\n\tvariableId?: string;\n}\n\n/**\n * Reads untrusted data (e.g. a saved `TokenState`) and keeps what is valid: junk collections,\n * modes and variables are dropped, bad values replaced by the type's default and alias cycles\n * broken, each with an issue.\n */\nexport function parseTokenState(input: unknown): { state: TokenState; issues: TokenStateIssue[] } {\n\tconst issues: TokenStateIssue[] = [];\n\tlet raw = input;\n\tif (typeof raw === 'string') {\n\t\ttry {\n\t\t\traw = JSON.parse(raw);\n\t\t} catch {\n\t\t\treturn { state: { collections: [], variables: [] }, issues: [{ message: 'Not JSON' }] };\n\t\t}\n\t}\n\tconst obj = (typeof raw === 'object' && raw !== null ? raw : {}) as Record<string, unknown>;\n\tconst collections: TokenCollection[] = [];\n\tconst ids = new Set<string>();\n\tfor (const c of Array.isArray(obj.collections) ? obj.collections : []) {\n\t\tconst item = c as Partial<TokenCollection> | null;\n\t\tconst modes = Array.isArray(item?.modes)\n\t\t\t? (item!.modes as unknown[]).filter(\n\t\t\t\t\t(m): m is TokenMode => typeof m === 'object' && m !== null && typeof (m as TokenMode).id === 'string' && typeof (m as TokenMode).name === 'string'\n\t\t\t\t)\n\t\t\t: [];\n\t\tif (!item || typeof item.id !== 'string' || typeof item.name !== 'string' || modes.length === 0 || ids.has(item.id)) {\n\t\t\tissues.push({ message: 'Dropped an invalid collection' });\n\t\t\tcontinue;\n\t\t}\n\t\tids.add(item.id);\n\t\tcollections.push({ id: item.id, name: item.name, modes: modes.map((m) => ({ id: m.id, name: m.name })) });\n\t}\n\tconst byId = new Map(collections.map((c) => [c.id, c]));\n\tconst variables: TokenVariable[] = [];\n\tconst varIds = new Set<string>();\n\tfor (const v of Array.isArray(obj.variables) ? obj.variables : []) {\n\t\tconst item = v as Partial<TokenVariable> | null;\n\t\tconst collection = item && typeof item.collectionId === 'string' ? byId.get(item.collectionId) : undefined;\n\t\tif (\n\t\t\t!item ||\n\t\t\ttypeof item.id !== 'string' ||\n\t\t\ttypeof item.name !== 'string' ||\n\t\t\t!collection ||\n\t\t\t!(['color', 'number', 'string', 'boolean'] as unknown[]).includes(item.type) ||\n\t\t\tvarIds.has(item.id)\n\t\t) {\n\t\t\tissues.push({ message: 'Dropped an invalid variable', variableId: typeof item?.id === 'string' ? item.id : undefined });\n\t\t\tcontinue;\n\t\t}\n\t\tvarIds.add(item.id);\n\t\tconst type = item.type as TokenType;\n\t\tconst values: Record<string, TokenValue> = {};\n\t\tconst rawValues = (typeof item.valuesByMode === 'object' && item.valuesByMode !== null ? item.valuesByMode : {}) as Record<string, unknown>;\n\t\tfor (const mode of collection.modes) {\n\t\t\tconst value = rawValues[mode.id];\n\t\t\tif (isTokenAlias(value)) values[mode.id] = { alias: value.alias };\n\t\t\telse {\n\t\t\t\tconst literal = coerceTokenLiteral(type, value);\n\t\t\t\tif (literal === null) issues.push({ message: `\\`${item.name}\\` had no valid value in \\`${mode.name}\\``, variableId: item.id });\n\t\t\t\tvalues[mode.id] = literal ?? defaultTokenValue(type);\n\t\t\t}\n\t\t}\n\t\tconst variable: TokenVariable = { id: item.id, name: item.name, collectionId: collection.id, type, valuesByMode: values };\n\t\tif (typeof item.description === 'string' && item.description) variable.description = item.description;\n\t\tif (Array.isArray(item.scopes)) {\n\t\t\ttry {\n\t\t\t\tconst scopes = normalizeTokenScopes(type, item.scopes as string[]);\n\t\t\t\tif (scopes) variable.scopes = scopes;\n\t\t\t} catch {\n\t\t\t\tissues.push({ message: `Dropped unknown scopes of \\`${item.name}\\``, variableId: item.id });\n\t\t\t}\n\t\t}\n\t\tif (typeof item.unit === 'string' && /^[a-z%]{1,8}$/i.test(item.unit)) variable.unit = item.unit.toLowerCase();\n\t\tvariables.push(variable);\n\t}\n\tlet state: TokenState = { collections, variables };\n\t// Aliases: drop missing / mistyped targets and break cycles.\n\tconst fixed = state.variables.map((variable) => {\n\t\tlet values: Record<string, TokenValue> | null = null;\n\t\tfor (const [modeId, value] of Object.entries(variable.valuesByMode)) {\n\t\t\tif (!isTokenAlias(value)) continue;\n\t\t\tconst target = state.variables.find((t) => t.id === value.alias);\n\t\t\tif (!target || target.type !== variable.type) {\n\t\t\t\tvalues ??= { ...variable.valuesByMode };\n\t\t\t\tvalues[modeId] = defaultTokenValue(variable.type);\n\t\t\t\tissues.push({ message: `\\`${variable.name}\\` aliased a missing or mistyped variable`, variableId: variable.id });\n\t\t\t}\n\t\t}\n\t\treturn values ? { ...variable, valuesByMode: values } : variable;\n\t});\n\tstate = { collections, variables: fixed };\n\t// Cycle breaking: rebuild alias by alias, keeping only those that do not close a loop.\n\tconst literalOnly = fixed.map((variable) => {\n\t\tconst values: Record<string, TokenValue> = {};\n\t\tfor (const [modeId, value] of Object.entries(variable.valuesByMode)) values[modeId] = isTokenAlias(value) ? defaultTokenValue(variable.type) : value;\n\t\treturn { ...variable, valuesByMode: values };\n\t});\n\tlet rebuilt: TokenState = { collections, variables: literalOnly };\n\tfor (const variable of fixed) {\n\t\tfor (const [modeId, value] of Object.entries(variable.valuesByMode)) {\n\t\t\tif (!isTokenAlias(value)) continue;\n\t\t\tconst error = checkTokenAlias(rebuilt, variable, value.alias);\n\t\t\tif (error) {\n\t\t\t\tissues.push({ message: `\\`${variable.name}\\`: ${error.message}`, variableId: variable.id });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst current = getTokenVariable(rebuilt, variable.id)!;\n\t\t\trebuilt = replaceVariable(rebuilt, { ...current, valuesByMode: { ...current.valuesByMode, [modeId]: { alias: value.alias } } });\n\t\t}\n\t}\n\treturn { state: rebuilt, issues };\n}\n","import {\n\taddTokenMode,\n\tcreateTokenCollection,\n\tcreateTokenVariable,\n\tdefaultTokenId,\n\tdeleteTokenCollection,\n\tdeleteTokenVariables,\n\tmoveTokenMode,\n\tparseTokenState,\n\tremoveTokenMode,\n\trenameTokenCollection,\n\trenameTokenMode,\n\trenameTokenVariable,\n\tresolveToken,\n\tresolveTokenValue,\n\tsetTokenValue,\n\tupdateTokenVariable,\n\ttype CreateTokenCollectionInput,\n\ttype CreateTokenVariableInput,\n\ttype TokenIdFactory,\n\ttype TokenResolution,\n\ttype UpdateTokenVariableInput\n} from './model.js';\nimport type { TokenCollection, TokenLiteral, TokenMode, TokenModeContext, TokenState, TokenVariable } from './types.js';\nimport { EMPTY_TOKEN_STATE } from './types.js';\n\n/** Why the state changed. */\nexport type TokenChangeSource = 'edit' | 'undo' | 'redo' | 'replace';\n\nexport interface TokenChangeEvent {\n\tsource: TokenChangeSource;\n\t/** Operation name (`setValue`, `deleteVariables`, a `transact` label, …). */\n\treason: string;\n\tstate: TokenState;\n\tprevious: TokenState;\n\t/**\n\t * Variables this edit deleted (also via `deleteCollection`). Detach canvas bindings to them\n\t * with `detachTokenBindings(nodes, event.previous, event.deletedVariableIds)`.\n\t */\n\tdeletedVariableIds: readonly string[];\n}\n\nexport type TokenChangeListener = (event: TokenChangeEvent) => void;\n\nexport interface TokenStoreOptions {\n\tinitialState?: TokenState;\n\tcreateId?: TokenIdFactory;\n\t/** Undo steps kept (default 100). */\n\thistoryLimit?: number;\n}\n\ninterface Pending {\n\treason: string;\n\tprevious: TokenState;\n\tdeleted: string[];\n}\n\n/**\n * Undoable design-token store. Every edit is one undo step (group several with `transact`)\n * and notifies subscribers once. `getState()` returns an immutable snapshot whose reference\n * only changes on edits, so it works with `useSyncExternalStore` and Svelte stores.\n * Refused edits throw a `TokenError` and change nothing.\n */\nexport class TokenStore {\n\tprivate state: TokenState;\n\tprivate undoStack: { state: TokenState; reason: string }[] = [];\n\tprivate redoStack: { state: TokenState; reason: string }[] = [];\n\tprivate listeners = new Set<TokenChangeListener>();\n\tprivate pending: Pending | null = null;\n\tprivate depth = 0;\n\tprivate readonly createId: TokenIdFactory;\n\tprivate readonly historyLimit: number;\n\n\tconstructor(options: TokenStoreOptions = {}) {\n\t\tthis.state = options.initialState ?? EMPTY_TOKEN_STATE;\n\t\tthis.createId = options.createId ?? defaultTokenId;\n\t\tthis.historyLimit = Math.max(0, options.historyLimit ?? 100);\n\t}\n\n\tgetState = (): TokenState => this.state;\n\n\tsubscribe = (listener: TokenChangeListener): (() => void) => {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t};\n\n\tget collections(): readonly TokenCollection[] {\n\t\treturn this.state.collections;\n\t}\n\n\tget variables(): readonly TokenVariable[] {\n\t\treturn this.state.variables;\n\t}\n\n\tcanUndo(): boolean {\n\t\treturn this.undoStack.length > 0;\n\t}\n\n\tcanRedo(): boolean {\n\t\treturn this.redoStack.length > 0;\n\t}\n\n\t/** Resolves a variable under `modes` (see `resolveToken`). */\n\tresolve(id: string, modes?: TokenModeContext): TokenResolution {\n\t\treturn resolveToken(this.state, id, modes);\n\t}\n\n\tresolveValue(id: string, modes?: TokenModeContext): TokenLiteral | undefined {\n\t\treturn resolveTokenValue(this.state, id, modes);\n\t}\n\n\t/**\n\t * Runs `fn` as one undo step with one change event. If `fn` throws, every change it made is\n\t * rolled back and the error rethrown.\n\t */\n\ttransact<T>(reason: string, fn: (store: this) => T): T {\n\t\tconst outer = this.depth === 0;\n\t\tif (outer) this.pending = { reason, previous: this.state, deleted: [] };\n\t\tthis.depth += 1;\n\t\ttry {\n\t\t\tconst result = fn(this);\n\t\t\tthis.depth -= 1;\n\t\t\tif (outer) this.flush();\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tthis.depth -= 1;\n\t\t\tif (outer) {\n\t\t\t\tthis.state = this.pending!.previous;\n\t\t\t\tthis.pending = null;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate apply(reason: string, next: TokenState, deleted: readonly string[] = []): void {\n\t\tif (next === this.state) return;\n\t\tif (this.depth > 0) {\n\t\t\tthis.state = next;\n\t\t\tthis.pending!.deleted.push(...deleted);\n\t\t\treturn;\n\t\t}\n\t\tthis.pending = { reason, previous: this.state, deleted: [...deleted] };\n\t\tthis.state = next;\n\t\tthis.flush();\n\t}\n\n\tprivate flush(): void {\n\t\tconst pending = this.pending!;\n\t\tthis.pending = null;\n\t\tif (pending.previous === this.state) return;\n\t\tthis.undoStack.push({ state: pending.previous, reason: pending.reason });\n\t\tif (this.undoStack.length > this.historyLimit) this.undoStack.splice(0, this.undoStack.length - this.historyLimit);\n\t\tthis.redoStack = [];\n\t\tthis.emit({ source: 'edit', reason: pending.reason, state: this.state, previous: pending.previous, deletedVariableIds: pending.deleted });\n\t}\n\n\tprivate emit(event: TokenChangeEvent): void {\n\t\tfor (const listener of [...this.listeners]) listener(event);\n\t}\n\n\tundo(): boolean {\n\t\tconst entry = this.undoStack.pop();\n\t\tif (!entry) return false;\n\t\tconst previous = this.state;\n\t\tthis.redoStack.push({ state: previous, reason: entry.reason });\n\t\tthis.state = entry.state;\n\t\tthis.emit({ source: 'undo', reason: entry.reason, state: this.state, previous, deletedVariableIds: [] });\n\t\treturn true;\n\t}\n\n\tredo(): boolean {\n\t\tconst entry = this.redoStack.pop();\n\t\tif (!entry) return false;\n\t\tconst previous = this.state;\n\t\tthis.undoStack.push({ state: previous, reason: entry.reason });\n\t\tthis.state = entry.state;\n\t\tthis.emit({ source: 'redo', reason: entry.reason, state: this.state, previous, deletedVariableIds: [] });\n\t\treturn true;\n\t}\n\n\t/**\n\t * Replaces the whole state (e.g. after loading a file). Untrusted data should go through\n\t * `parseTokenState` first. With `record: true` it is an undo step; otherwise history is cleared.\n\t */\n\treplaceState(state: TokenState, options: { record?: boolean; reason?: string } = {}): void {\n\t\tif (options.record) {\n\t\t\tthis.apply(options.reason ?? 'replace', state);\n\t\t\treturn;\n\t\t}\n\t\tconst previous = this.state;\n\t\tthis.state = state;\n\t\tthis.undoStack = [];\n\t\tthis.redoStack = [];\n\t\tthis.emit({ source: 'replace', reason: options.reason ?? 'replace', state, previous, deletedVariableIds: [] });\n\t}\n\n\t/** Loads untrusted JSON (or an object) as the new state; returns the issues found. */\n\tload(input: unknown): ReturnType<typeof parseTokenState>['issues'] {\n\t\tconst { state, issues } = parseTokenState(input);\n\t\tthis.replaceState(state, { reason: 'load' });\n\t\treturn issues;\n\t}\n\n\t/** The state as JSON. */\n\ttoJSON(): TokenState {\n\t\treturn this.state;\n\t}\n\n\t// --- Collections and modes -----------------------------------------------------------------\n\n\tcreateCollection(name: string, modes?: readonly string[]): TokenCollection {\n\t\tconst input: CreateTokenCollectionInput = { name, modes };\n\t\tconst result = createTokenCollection(this.state, input, this.createId);\n\t\tthis.apply('createCollection', result.state);\n\t\treturn result.collection;\n\t}\n\n\trenameCollection(id: string, name: string): void {\n\t\tthis.apply('renameCollection', renameTokenCollection(this.state, id, name));\n\t}\n\n\tdeleteCollection(id: string): string[] {\n\t\tconst result = deleteTokenCollection(this.state, id);\n\t\tthis.apply('deleteCollection', result.state, result.deleted);\n\t\treturn result.deleted;\n\t}\n\n\taddMode(collectionId: string, name: string, options: { from?: string } = {}): TokenMode {\n\t\tconst result = addTokenMode(this.state, collectionId, name, options, this.createId);\n\t\tthis.apply('addMode', result.state);\n\t\treturn result.mode;\n\t}\n\n\trenameMode(collectionId: string, modeId: string, name: string): void {\n\t\tthis.apply('renameMode', renameTokenMode(this.state, collectionId, modeId, name));\n\t}\n\n\tremoveMode(collectionId: string, modeId: string): void {\n\t\tthis.apply('removeMode', removeTokenMode(this.state, collectionId, modeId));\n\t}\n\n\tmoveMode(collectionId: string, modeId: string, to: number): void {\n\t\tthis.apply('moveMode', moveTokenMode(this.state, collectionId, modeId, to));\n\t}\n\n\t/** Makes a mode the default by moving it first. */\n\tsetDefaultMode(collectionId: string, modeId: string): void {\n\t\tthis.apply('setDefaultMode', moveTokenMode(this.state, collectionId, modeId, 0));\n\t}\n\n\t// --- Variables -----------------------------------------------------------------------------\n\n\tcreateVariable(input: CreateTokenVariableInput): TokenVariable {\n\t\tconst result = createTokenVariable(this.state, input, this.createId);\n\t\tthis.apply('createVariable', result.state);\n\t\treturn result.variable;\n\t}\n\n\t/** Sets a literal or `{ alias }` in one mode (id or name; default: the default mode). */\n\tsetValue(variableId: string, value: unknown, modeId?: string): void {\n\t\tthis.apply('setValue', setTokenValue(this.state, variableId, value, modeId));\n\t}\n\n\trenameVariable(variableId: string, name: string): void {\n\t\tthis.apply('renameVariable', renameTokenVariable(this.state, variableId, name));\n\t}\n\n\tupdateVariable(variableId: string, input: UpdateTokenVariableInput): void {\n\t\tthis.apply('updateVariable', updateTokenVariable(this.state, variableId, input));\n\t}\n\n\t/** Deletes variables; aliases to them take their values. Returns the ids deleted. */\n\tdeleteVariables(ids: string | Iterable<string>): string[] {\n\t\tconst result = deleteTokenVariables(this.state, typeof ids === 'string' ? [ids] : ids);\n\t\tthis.apply('deleteVariables', result.state, result.deleted);\n\t\treturn result.deleted;\n\t}\n\n\t/** Applies a pure state transform (e.g. `importW3CTokens`) as one undo step. */\n\tupdate(reason: string, fn: (state: TokenState) => TokenState): void {\n\t\tthis.apply(reason, fn(this.state));\n\t}\n}\n\nexport function createTokenStore(options: TokenStoreOptions = {}): TokenStore {\n\treturn new TokenStore(options);\n}\n","// Portions ported from figcraft/crates/engine/src/variables_io_tests.rs (MIT OR Apache-2.0, © ArtCraft Team and contributors). See THIRD_PARTY_NOTICES.md.\nimport { getCurrentMode, getTokenCollection, getTokenVariable, resolveToken } from './model.js';\nimport { isTokenAlias, type TokenCollection, type TokenLiteral, type TokenMode, type TokenModeContext, type TokenState, type TokenVariable } from './types.js';\n\nexport interface TokenCssOptions {\n\t/** Collections to export (ids; default all). */\n\tcollections?: readonly string[];\n\t/** Prefix after `--` (e.g. `ds-` → `--ds-color-bg`). */\n\tprefix?: string;\n\t/** Also prefix each variable with its collection name (avoids clashes between collections). */\n\tcollectionPrefix?: boolean;\n\t/** Root selector (default `:root`). */\n\tselector?: string;\n\t/** Attribute that selects a mode (default `data-mode`), or one per collection. */\n\tattribute?: string | ((collection: TokenCollection) => string);\n\t/** Attribute value for a mode (default: the mode name as a lowercase slug, e.g. `dark`). */\n\tmodeValue?: (mode: TokenMode, collection: TokenCollection) => string;\n\t/**\n\t * Also emit `[data-mode=\"…\"]` rules that match any element (not just the root), so a subtree\n\t * can switch mode. Default `false`.\n\t */\n\tnested?: boolean;\n\t/** Formats numbers (default: the number with the variable's `unit`, if any). */\n\tformatNumber?: (value: number, variable: TokenVariable) => string;\n}\n\n/** Lowercase slug of a name: groups and spaces become `-` (`Color/Bg Muted` → `color-bg-muted`). */\nexport function tokenSlug(name: string): string {\n\tlet out = '';\n\tlet dash = false;\n\tfor (const ch of name.toLowerCase()) {\n\t\tif ((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch === '_') {\n\t\t\tif (dash && out) out += '-';\n\t\t\tout += ch;\n\t\t\tdash = false;\n\t\t} else dash = true;\n\t}\n\treturn out || 'token';\n}\n\n/** The CSS custom property for a variable (e.g. `--color-bg`). */\nexport function getTokenCssName(state: TokenState, variable: TokenVariable, options: Pick<TokenCssOptions, 'prefix' | 'collectionPrefix'> = {}): string {\n\tconst collection = getTokenCollection(state, variable.collectionId);\n\tconst head = options.collectionPrefix && collection ? `${tokenSlug(collection.name)}-` : '';\n\tconst prefix = options.prefix ? `${tokenSlug(options.prefix)}-` : '';\n\treturn `--${prefix}${head}${tokenSlug(variable.name)}`;\n}\n\n/** A CSS string literal with `\"`, `\\`, newlines and `<` escaped. */\nexport function cssString(value: string): string {\n\tlet out = '\"';\n\tfor (const ch of value) {\n\t\tif (ch === '\"' || ch === '\\\\') out += '\\\\' + ch;\n\t\telse if (ch === '\\n') out += '\\\\a ';\n\t\telse if (ch === '\\r') out += '\\\\d ';\n\t\telse if (ch === '<') out += '\\\\3c ';\n\t\telse out += ch;\n\t}\n\treturn out + '\"';\n}\n\n/** A literal as CSS. */\nexport function formatTokenCssValue(value: TokenLiteral, variable: TokenVariable, options: Pick<TokenCssOptions, 'formatNumber'> = {}): string {\n\tswitch (variable.type) {\n\t\tcase 'color':\n\t\t\treturn String(value);\n\t\tcase 'number':\n\t\t\treturn options.formatNumber ? options.formatNumber(value as number, variable) : `${value}${variable.unit ?? ''}`;\n\t\tcase 'string':\n\t\t\treturn cssString(String(value));\n\t\tcase 'boolean':\n\t\t\treturn value ? 'true' : 'false';\n\t}\n}\n\nconst defaultModeValue = (mode: TokenMode) => tokenSlug(mode.name);\n\nfunction attributeFor(options: TokenCssOptions, collection: TokenCollection): string {\n\tconst attr = typeof options.attribute === 'function' ? options.attribute(collection) : options.attribute ?? 'data-mode';\n\treturn tokenSlug(attr);\n}\n\n/**\n * Flat CSS custom properties per mode: each collection's default mode on `:root`, its other\n * modes on `:root[data-mode=\"dark\"]`. Aliases to exported variables become `var(--target)`, so\n * switching the attribute re-themes everything; aliases to other variables are resolved.\n */\nexport function exportTokensCss(state: TokenState, options: TokenCssOptions = {}): string {\n\tconst selector = options.selector ?? ':root';\n\tconst wanted = options.collections ? new Set(options.collections) : null;\n\tconst collections = state.collections.filter((c) => !wanted || wanted.has(c.id));\n\tconst exported = new Set(state.variables.filter((v) => collections.some((c) => c.id === v.collectionId)).map((v) => v.id));\n\tconst modeValue = options.modeValue ?? defaultModeValue;\n\n\tconst declaration = (variable: TokenVariable, collection: TokenCollection, mode: TokenMode): string | null => {\n\t\tconst value = variable.valuesByMode[mode.id];\n\t\tif (isTokenAlias(value) && exported.has(value.alias)) {\n\t\t\tconst target = getTokenVariable(state, value.alias)!;\n\t\t\treturn ` ${getTokenCssName(state, variable, options)}: var(${getTokenCssName(state, target, options)});`;\n\t\t}\n\t\tconst resolved = resolveToken(state, variable.id, { [collection.id]: mode.id });\n\t\tif (!resolved.ok) return null;\n\t\treturn ` ${getTokenCssName(state, variable, options)}: ${formatTokenCssValue(resolved.value, variable, options)};`;\n\t};\n\n\tconst blocks: string[] = [];\n\tconst rootLines: string[] = [];\n\tfor (const collection of collections) {\n\t\tconst vars = state.variables.filter((v) => v.collectionId === collection.id);\n\t\tfor (const v of vars) {\n\t\t\tconst line = declaration(v, collection, collection.modes[0]);\n\t\t\tif (line) rootLines.push(line);\n\t\t}\n\t}\n\tconst rootSelectors = [selector];\n\tif (options.nested) {\n\t\tfor (const collection of collections) {\n\t\t\trootSelectors.push(`[${attributeFor(options, collection)}=\"${tokenSlug(modeValue(collection.modes[0], collection))}\"]`);\n\t\t}\n\t}\n\tblocks.push(`${[...new Set(rootSelectors)].join(', ')} {\\n${rootLines.join('\\n')}${rootLines.length ? '\\n' : ''}}`);\n\tfor (const collection of collections) {\n\t\tconst vars = state.variables.filter((v) => v.collectionId === collection.id);\n\t\tconst attr = attributeFor(options, collection);\n\t\tfor (const mode of collection.modes.slice(1)) {\n\t\t\tconst lines = vars.map((v) => declaration(v, collection, mode)).filter((l): l is string => l !== null);\n\t\t\tconst value = tokenSlug(modeValue(mode, collection));\n\t\t\tconst selectors = [`${selector}[${attr}=\"${value}\"]`];\n\t\t\tif (options.nested) selectors.push(`[${attr}=\"${value}\"]`);\n\t\t\tblocks.push(`${selectors.join(', ')} {\\n${lines.join('\\n')}${lines.length ? '\\n' : ''}}`);\n\t\t}\n\t}\n\treturn blocks.join('\\n\\n') + '\\n';\n}\n\n/**\n * Resolved CSS custom properties for one mode context, e.g. for an element's inline style:\n * `{ '--color-bg': '#ffffff', … }`. Aliases are resolved (no `var()`).\n */\nexport function getTokenCssVariables(\n\tstate: TokenState,\n\tmodes?: TokenModeContext,\n\toptions: Omit<TokenCssOptions, 'selector' | 'attribute' | 'modeValue' | 'nested'> = {}\n): Record<string, string> {\n\tconst wanted = options.collections ? new Set(options.collections) : null;\n\tconst out: Record<string, string> = {};\n\tfor (const variable of state.variables) {\n\t\tif (wanted && !wanted.has(variable.collectionId)) continue;\n\t\tconst collection = getTokenCollection(state, variable.collectionId);\n\t\tif (!collection) continue;\n\t\tconst resolved = resolveToken(state, variable.id, { ...modes, [collection.id]: getCurrentMode(collection, modes).id });\n\t\tif (resolved.ok) out[getTokenCssName(state, variable, options)] = formatTokenCssValue(resolved.value, variable, options);\n\t}\n\treturn out;\n}\n","// Portions ported from figcraft/crates/engine/src/variables_io_tests.rs (MIT OR Apache-2.0, © ArtCraft Team and contributors). See THIRD_PARTY_NOTICES.md.\nimport { hexToRgba, normalizeTokenColor } from './color.js';\nimport {\n\taddTokenMode,\n\tcheckTokenAlias,\n\tcoerceTokenLiteral,\n\tcreateTokenCollection,\n\tcreateTokenVariable,\n\tdefaultTokenId,\n\tfindTokenCollection,\n\tfindTokenMode,\n\tfindTokenVariable,\n\tgetTokenCollection,\n\tgetTokenVariable,\n\tnormalizeTokenName,\n\tsetTokenValue,\n\tupdateTokenVariable,\n\ttype TokenIdFactory\n} from './model.js';\nimport {\n\tTokenError,\n\tisTokenAlias,\n\ttype TokenCollection,\n\ttype TokenLiteral,\n\ttype TokenModeContext,\n\ttype TokenState,\n\ttype TokenType,\n\ttype TokenValue,\n\ttype TokenVariable\n} from './types.js';\n\n/**\n * W3C Design Tokens (DTCG) JSON. Each collection is a top-level group named after it; variable\n * names' `/` groups become nested groups; aliases are `{Collection.group.token}` references.\n * `$value` holds the default mode (or the modes passed in). Modes, ids and scopes ride along in\n * `$extensions[\"com.pixerate.tokens\"]`, so an export round-trips; tools that ignore extensions\n * still read the default mode. Strings and booleans use `$type: \"string\"` / `\"boolean\"`\n * (outside the spec, as Tokens Studio and Style Dictionary do).\n */\nexport const W3C_TOKENS_EXTENSION = 'com.pixerate.tokens';\n\nexport interface W3CTokensExportOptions {\n\t/** Collections to export (ids; default all). */\n\tcollections?: readonly string[];\n\t/** Modes that supply `$value` (default: each collection's default mode). */\n\tmodes?: TokenModeContext;\n\t/** Include `$extensions` with ids, every mode's value and scopes (default `true`). */\n\textensions?: boolean;\n\t/** Colours as `#hex` strings (default) or W3C colour objects. */\n\tcolorFormat?: 'hex' | 'object';\n}\n\ntype Json = null | boolean | number | string | Json[] | { [key: string]: Json };\n\nfunction path(name: string): string[] {\n\treturn name.split('/');\n}\n\nfunction reference(state: TokenState, variable: TokenVariable): string {\n\tconst collection = getTokenCollection(state, variable.collectionId);\n\treturn `{${[collection?.name ?? variable.collectionId, ...path(variable.name)].join('.')}}`;\n}\n\nfunction w3cType(variable: TokenVariable): string {\n\tif (variable.type === 'number') {\n\t\tif (variable.unit === 'ms' || variable.unit === 's') return 'duration';\n\t\tif (variable.unit) return 'dimension';\n\t}\n\treturn variable.type;\n}\n\nfunction w3cLiteral(variable: TokenVariable, value: TokenLiteral, colorFormat: 'hex' | 'object'): Json {\n\tif (variable.type === 'color' && colorFormat === 'object') {\n\t\tconst c = hexToRgba(String(value));\n\t\tif (c) {\n\t\t\tconst round = (n: number) => Math.round(n * 10000) / 10000;\n\t\t\treturn { colorSpace: 'srgb', components: [round(c.r), round(c.g), round(c.b)], alpha: round(c.a), hex: String(value).slice(0, 7) };\n\t\t}\n\t}\n\tif (variable.type === 'number' && variable.unit) return { value: value as number, unit: variable.unit };\n\treturn value;\n}\n\nfunction w3cValue(state: TokenState, variable: TokenVariable, value: TokenValue | undefined, colorFormat: 'hex' | 'object'): Json {\n\tif (value === undefined) return null;\n\tif (isTokenAlias(value)) {\n\t\tconst target = getTokenVariable(state, value.alias);\n\t\treturn target ? reference(state, target) : null;\n\t}\n\treturn w3cLiteral(variable, value, colorFormat);\n}\n\n/** The tokens as a W3C Design Tokens object (see {@link W3C_TOKENS_EXTENSION}). */\nexport function exportW3CTokens(state: TokenState, options: W3CTokensExportOptions = {}): Record<string, Json> {\n\tconst withExtensions = options.extensions !== false;\n\tconst colorFormat = options.colorFormat ?? 'hex';\n\tconst wanted = options.collections ? new Set(options.collections) : null;\n\tconst root: Record<string, Json> = {};\n\tfor (const collection of state.collections) {\n\t\tif (wanted && !wanted.has(collection.id)) continue;\n\t\tconst group: Record<string, Json> = {};\n\t\tif (withExtensions) {\n\t\t\tgroup.$extensions = {\n\t\t\t\t[W3C_TOKENS_EXTENSION]: { id: collection.id, modes: collection.modes.map((m) => ({ id: m.id, name: m.name })) }\n\t\t\t};\n\t\t}\n\t\tconst chosen = options.modes?.[collection.id];\n\t\tconst mode = (chosen !== undefined && collection.modes.find((m) => m.id === chosen)) || collection.modes[0];\n\t\tfor (const variable of state.variables) {\n\t\t\tif (variable.collectionId !== collection.id) continue;\n\t\t\tconst token: Record<string, Json> = {\n\t\t\t\t$type: w3cType(variable),\n\t\t\t\t$value: w3cValue(state, variable, variable.valuesByMode[mode.id], colorFormat)\n\t\t\t};\n\t\t\tif (variable.description) token.$description = variable.description;\n\t\t\tif (withExtensions) {\n\t\t\t\tconst modes: Record<string, Json> = {};\n\t\t\t\tfor (const m of collection.modes) modes[m.name] = w3cValue(state, variable, variable.valuesByMode[m.id], colorFormat);\n\t\t\t\tconst ext: Record<string, Json> = { id: variable.id, modes };\n\t\t\t\tif (variable.scopes) ext.scopes = [...variable.scopes];\n\t\t\t\tif (variable.unit) ext.unit = variable.unit;\n\t\t\t\ttoken.$extensions = { [W3C_TOKENS_EXTENSION]: ext };\n\t\t\t}\n\t\t\tlet at = group;\n\t\t\tconst segments = path(variable.name);\n\t\t\tfor (const segment of segments.slice(0, -1)) {\n\t\t\t\tconst next = at[segment];\n\t\t\t\tif (typeof next !== 'object' || next === null || Array.isArray(next) || '$value' in next) at[segment] = {};\n\t\t\t\tat = at[segment] as Record<string, Json>;\n\t\t\t}\n\t\t\tat[segments[segments.length - 1]] = token;\n\t\t}\n\t\troot[collection.name] = group;\n\t}\n\treturn root;\n}\n\n/** {@link exportW3CTokens} as indented JSON text. */\nexport function exportW3CTokensJson(state: TokenState, options: W3CTokensExportOptions = {}): string {\n\treturn JSON.stringify(exportW3CTokens(state, options), null, 2);\n}\n\n// ---------------------------------------------------------------------------------------------\n// Import\n\nexport interface W3CTokensImportOptions {\n\t/**\n\t * Collection for tokens outside a marked collection group (a plain W3C file). Default\n\t * `\"Tokens\"`; an existing collection with that name is updated.\n\t */\n\tcollection?: string;\n\t/** Mode that plain `$value`s go to (name; created when missing). Default: the default mode. */\n\tmode?: string;\n\tcreateId?: TokenIdFactory;\n}\n\nexport interface W3CTokensImportReport {\n\tcollectionsAdded: number;\n\tmodesAdded: number;\n\tvariablesAdded: number;\n\t/** Existing variables (matched by collection and name) that were updated in place. */\n\tvariablesUpdated: number;\n\t/** Entries skipped or values not taken, with the reason. */\n\twarnings: string[];\n}\n\ninterface RawToken {\n\tcollection: string;\n\tpath: string[];\n\ttype: string | undefined;\n\tvalue: unknown;\n\tdescription: unknown;\n\text: Record<string, unknown> | undefined;\n}\n\nconst MAX_DEPTH = 32;\nconst REF = /^\\{([^{}]+)\\}$/;\nconst MEASURE = /^(-?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?)\\s*([a-z%]*)$/i;\nconst FONT_WEIGHTS: Record<string, number> = {\n\tthin: 100,\n\thairline: 100,\n\t'extra-light': 200,\n\t'ultra-light': 200,\n\tlight: 300,\n\tnormal: 400,\n\tregular: 400,\n\tbook: 400,\n\tmedium: 500,\n\t'semi-bold': 600,\n\t'demi-bold': 600,\n\tbold: 700,\n\t'extra-bold': 800,\n\t'ultra-bold': 800,\n\tblack: 900,\n\theavy: 900,\n\t'extra-black': 950,\n\t'ultra-black': 950\n};\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);\n\nfunction extensionOf(node: Record<string, unknown>): Record<string, unknown> | undefined {\n\tconst ext = node.$extensions;\n\tif (!isObject(ext)) return undefined;\n\tconst ours = ext[W3C_TOKENS_EXTENSION];\n\treturn isObject(ours) ? ours : undefined;\n}\n\nfunction aliasRef(value: unknown): string | null {\n\tif (typeof value !== 'string' || value.length > 1000) return null;\n\tconst match = REF.exec(value.trim());\n\treturn match ? match[1].trim() : null;\n}\n\n/** W3C type → our type, or `null` for types we don't take (composites). */\nfunction mapType(type: string): TokenType | null {\n\tswitch (type) {\n\t\tcase 'color':\n\t\t\treturn 'color';\n\t\tcase 'number':\n\t\tcase 'dimension':\n\t\tcase 'duration':\n\t\tcase 'fontWeight':\n\t\t\treturn 'number';\n\t\tcase 'string':\n\t\tcase 'text':\n\t\tcase 'fontFamily':\n\t\tcase 'fontStyle':\n\t\t\treturn 'string';\n\t\tcase 'boolean':\n\t\t\treturn 'boolean';\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\nfunction inferType(value: unknown): string | undefined {\n\tif (typeof value === 'boolean') return 'boolean';\n\tif (typeof value === 'number') return 'number';\n\tif (typeof value === 'string') {\n\t\tconst text = value.trim();\n\t\tif ((text.startsWith('#') || /^rgba?\\(/i.test(text)) && normalizeTokenColor(text)) return 'color';\n\t\tif (MEASURE.test(text) && /[a-z%]$/i.test(text)) return 'dimension';\n\t\treturn 'string';\n\t}\n\tif (isObject(value) && Array.isArray(value.components)) return 'color';\n\tif (isObject(value) && typeof value.value === 'number' && typeof value.unit === 'string') return 'dimension';\n\treturn undefined;\n}\n\n/** A literal and (for numbers) unit from a W3C value of `w3cType`, or `null`. */\nfunction readLiteral(w3cType: string, type: TokenType, value: unknown): { value: TokenLiteral; unit?: string } | null {\n\tif (type === 'number') {\n\t\tif (w3cType === 'fontWeight' && typeof value === 'string') {\n\t\t\tconst weight = FONT_WEIGHTS[value.trim().toLowerCase()];\n\t\t\treturn weight === undefined ? null : { value: weight };\n\t\t}\n\t\tif (isObject(value) && typeof value.value === 'number' && Number.isFinite(value.value)) {\n\t\t\tconst unit = typeof value.unit === 'string' && /^[a-z%]{1,8}$/i.test(value.unit) ? value.unit.toLowerCase() : undefined;\n\t\t\treturn { value: value.value, unit };\n\t\t}\n\t\tif (typeof value === 'string' && value.length <= 100) {\n\t\t\tconst match = MEASURE.exec(value.trim());\n\t\t\tif (!match) return null;\n\t\t\tconst n = Number(match[1]);\n\t\t\tif (!Number.isFinite(n)) return null;\n\t\t\tconst unit = match[2] ? match[2].toLowerCase() : undefined;\n\t\t\treturn { value: n, unit: unit && unit.length <= 8 ? unit : undefined };\n\t\t}\n\t\tconst n = coerceTokenLiteral('number', value);\n\t\treturn n === null ? null : { value: n };\n\t}\n\tif (type === 'string' && w3cType === 'fontFamily' && Array.isArray(value)) {\n\t\treturn value.every((v) => typeof v === 'string') ? { value: value.join(', ') } : null;\n\t}\n\tconst literal = coerceTokenLiteral(type, value);\n\treturn literal === null ? null : { value: literal };\n}\n\nfunction collectTokens(\n\tgroup: Record<string, unknown>,\n\tcollection: string,\n\tprefix: string[],\n\tinheritedType: string | undefined,\n\tout: RawToken[],\n\twarnings: string[],\n\tdepth: number\n): void {\n\tif (depth > MAX_DEPTH) {\n\t\twarnings.push(`\\`${prefix.join('.')}\\` is nested too deeply; skipped`);\n\t\treturn;\n\t}\n\tconst groupType = typeof group.$type === 'string' ? group.$type : inheritedType;\n\tfor (const [key, child] of Object.entries(group)) {\n\t\tif (key.startsWith('$')) continue;\n\t\tconst at = [...prefix, key];\n\t\tif (!isObject(child)) {\n\t\t\twarnings.push(`\\`${at.join('.')}\\` is not a token or group; skipped`);\n\t\t\tcontinue;\n\t\t}\n\t\tif ('$value' in child) {\n\t\t\tout.push({\n\t\t\t\tcollection,\n\t\t\t\tpath: at,\n\t\t\t\ttype: typeof child.$type === 'string' ? child.$type : groupType,\n\t\t\t\tvalue: child.$value,\n\t\t\t\tdescription: child.$description,\n\t\t\t\text: extensionOf(child)\n\t\t\t});\n\t\t} else collectTokens(child, collection, at, groupType, out, warnings, depth + 1);\n\t}\n}\n\n/**\n * Merges a W3C Design Tokens document (object or JSON text) into `state`. Collections, modes\n * and variables are matched by name and updated in place (ids, and so canvas bindings, are\n * kept); new ones take the ids in the file's extensions when free. Junk entries, type clashes,\n * unresolved references and alias cycles are skipped with a warning. Throws `invalid-input`\n * only when the input is not a JSON object.\n */\nexport function importW3CTokens(\n\tstate: TokenState,\n\tinput: unknown,\n\toptions: W3CTokensImportOptions = {}\n): { state: TokenState; report: W3CTokensImportReport } {\n\tlet doc = input;\n\tif (typeof doc === 'string') {\n\t\ttry {\n\t\t\tdoc = JSON.parse(doc);\n\t\t} catch {\n\t\t\tthrow new TokenError('invalid-input', 'Not JSON');\n\t\t}\n\t}\n\tif (!isObject(doc)) throw new TokenError('invalid-input', 'Expected a design tokens object');\n\tconst createId = options.createId ?? defaultTokenId;\n\tconst report: W3CTokensImportReport = { collectionsAdded: 0, modesAdded: 0, variablesAdded: 0, variablesUpdated: 0, warnings: [] };\n\tconst warn = (message: string) => {\n\t\tif (report.warnings.length < 500) report.warnings.push(message);\n\t};\n\n\t// Which top-level groups are collections.\n\tconst marked = Object.entries(doc).filter(([key, value]) => !key.startsWith('$') && isObject(value) && !('$value' in value) && Array.isArray(extensionOf(value)?.modes));\n\tconst plainName = options.collection ?? 'Tokens';\n\tconst sources: { name: string; group: Record<string, unknown>; modes?: unknown[]; id?: unknown; plain: boolean }[] = [];\n\tif (marked.length > 0) {\n\t\tfor (const [key, value] of marked) {\n\t\t\tconst ext = extensionOf(value as Record<string, unknown>)!;\n\t\t\tsources.push({ name: key, group: value as Record<string, unknown>, modes: ext.modes as unknown[], id: ext.id, plain: false });\n\t\t}\n\t\tconst rest: Record<string, unknown> = {};\n\t\tfor (const [key, value] of Object.entries(doc)) if (!marked.some(([k]) => k === key)) rest[key] = value;\n\t\tif (Object.keys(rest).some((k) => !k.startsWith('$'))) sources.push({ name: plainName, group: rest, plain: true });\n\t} else sources.push({ name: plainName, group: doc, plain: true });\n\n\tconst usedIds = new Set<string>([...state.collections.map((c) => c.id), ...state.variables.map((v) => v.id)]);\n\tfor (const c of state.collections) for (const m of c.modes) usedIds.add(m.id);\n\tconst idFrom = (candidate: unknown, kind: 'collection' | 'mode' | 'variable'): TokenIdFactory => (k) => {\n\t\tif (k === kind && typeof candidate === 'string' && candidate.length > 0 && candidate.length <= 200 && !usedIds.has(candidate)) {\n\t\t\tusedIds.add(candidate);\n\t\t\treturn candidate;\n\t\t}\n\t\tconst id = createId(k);\n\t\tusedIds.add(id);\n\t\treturn id;\n\t};\n\n\tlet next = state;\n\tconst tokens: RawToken[] = [];\n\tconst collectionIds = new Map<string, string>();\n\tconst plainMode = new Map<string, string>();\n\n\tconst ensureMode = (collectionId: string, name: string, id?: unknown): string | null => {\n\t\tconst collection = getTokenCollection(next, collectionId)!;\n\t\tconst existing = findTokenMode(collection, name);\n\t\tif (existing) return existing.id;\n\t\ttry {\n\t\t\tconst result = addTokenMode(next, collectionId, name, {}, idFrom(id, 'mode'));\n\t\t\tnext = result.state;\n\t\t\treport.modesAdded += 1;\n\t\t\treturn result.mode.id;\n\t\t} catch (error) {\n\t\t\twarn(`Mode \\`${name}\\`: ${(error as Error).message}`);\n\t\t\treturn null;\n\t\t}\n\t};\n\n\tfor (const source of sources) {\n\t\tlet collection: TokenCollection | undefined = findTokenCollection(next, source.name);\n\t\tif (!collection) {\n\t\t\tconst declared = (source.modes ?? []).filter(isObject);\n\t\t\tconst names = declared.map((m) => m.name).filter((n): n is string => typeof n === 'string' && n.trim() !== '');\n\t\t\tif (source.plain && options.mode) names.splice(0, names.length, options.mode);\n\t\t\ttry {\n\t\t\t\tconst ids = [source.id, ...declared.map((m) => m.id)];\n\t\t\t\tlet i = 0;\n\t\t\t\tconst factory: TokenIdFactory = (kind) => idFrom(kind === 'collection' ? ids[0] : ids[++i], kind)(kind);\n\t\t\t\tconst result = createTokenCollection(next, { name: source.name, modes: names.length ? names : undefined }, factory);\n\t\t\t\tnext = result.state;\n\t\t\t\tcollection = result.collection;\n\t\t\t\treport.collectionsAdded += 1;\n\t\t\t} catch (error) {\n\t\t\t\twarn(`Collection \\`${source.name}\\`: ${(error as Error).message}`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t} else {\n\t\t\tfor (const m of (source.modes ?? []).filter(isObject)) {\n\t\t\t\tif (typeof m.name === 'string' && m.name.trim()) ensureMode(collection.id, m.name, m.id);\n\t\t\t}\n\t\t}\n\t\tcollectionIds.set(source.name, collection.id);\n\t\tconst modeId = options.mode && source.plain ? ensureMode(collection.id, options.mode) : getTokenCollection(next, collection.id)!.modes[0].id;\n\t\tif (modeId) plainMode.set(source.name, modeId);\n\t\tcollectTokens(source.group, source.name, [], undefined, tokens, report.warnings, 0);\n\t}\n\n\t// Paths for references: `Collection.a.b` and (within a collection) `a.b`.\n\tconst byFullPath = new Map<string, RawToken>();\n\tfor (const token of tokens) byFullPath.set([token.collection, ...token.path].join('.'), token);\n\tconst findRaw = (ref: string, from: RawToken): RawToken | undefined =>\n\t\tbyFullPath.get(ref) ?? byFullPath.get(`${from.collection}.${ref}`);\n\n\t// Types of untyped aliases follow their targets.\n\tconst typeOf = (token: RawToken): string | undefined => {\n\t\tlet current: RawToken | undefined = token;\n\t\tfor (let i = 0; i < MAX_DEPTH && current; i++) {\n\t\t\tif (current.type) return current.type;\n\t\t\tconst ref = aliasRef(current.value);\n\t\t\tif (ref === null) return inferType(current.value);\n\t\t\tcurrent = findRaw(ref, current);\n\t\t}\n\t\treturn undefined;\n\t};\n\n\tconst pending: { variable: TokenVariable; modeId: string; ref: string; token: RawToken }[] = [];\n\tconst variableFor = new Map<RawToken, string>();\n\tfor (const token of tokens) {\n\t\tconst label = [token.collection, ...token.path].join('.');\n\t\tconst collectionId = collectionIds.get(token.collection);\n\t\tif (!collectionId) continue;\n\t\tconst w3cType = typeOf(token);\n\t\tconst type = w3cType ? mapType(w3cType) : null;\n\t\tif (!w3cType || !type) {\n\t\t\twarn(`\\`${label}\\` has an unsupported type \\`${w3cType ?? 'unknown'}\\`; skipped`);\n\t\t\tcontinue;\n\t\t}\n\t\tlet name: string;\n\t\ttry {\n\t\t\tname = normalizeTokenName(token.path.join('/'));\n\t\t} catch (error) {\n\t\t\twarn(`\\`${label}\\`: ${(error as Error).message}`);\n\t\t\tcontinue;\n\t\t}\n\t\tlet variable = findTokenVariable(next, name, collectionId);\n\t\tif (variable && variable.type !== type) {\n\t\t\twarn(`\\`${name}\\` is a ${variable.type} variable; the ${type} token \\`${label}\\` was skipped`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!variable) {\n\t\t\ttry {\n\t\t\t\tconst result = createTokenVariable(next, { collectionId, name, type }, idFrom(token.ext?.id, 'variable'));\n\t\t\t\tnext = result.state;\n\t\t\t\tvariable = result.variable;\n\t\t\t\treport.variablesAdded += 1;\n\t\t\t} catch (error) {\n\t\t\t\twarn(`\\`${label}\\`: ${(error as Error).message}`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t} else report.variablesUpdated += 1;\n\t\tvariableFor.set(token, variable.id);\n\n\t\t// Values: per mode from our extension, else `$value` into the plain mode.\n\t\tconst values: [string, unknown][] = [];\n\t\tconst extModes = token.ext?.modes;\n\t\tif (isObject(extModes)) {\n\t\t\tfor (const [modeName, value] of Object.entries(extModes)) {\n\t\t\t\tconst modeId = ensureMode(collectionId, modeName);\n\t\t\t\tif (modeId) values.push([modeId, value]);\n\t\t\t}\n\t\t} else {\n\t\t\tconst modeId = plainMode.get(token.collection);\n\t\t\tif (modeId) values.push([modeId, token.value]);\n\t\t}\n\t\tlet unit: string | undefined;\n\t\tfor (const [modeId, raw] of values) {\n\t\t\tconst ref = aliasRef(raw);\n\t\t\tif (ref !== null) {\n\t\t\t\tpending.push({ variable, modeId, ref, token });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst literal = readLiteral(w3cType, type, raw);\n\t\t\tif (!literal) {\n\t\t\t\twarn(`\\`${label}\\` has an invalid ${w3cType} value; kept the previous value`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (literal.unit) unit = literal.unit;\n\t\t\tnext = setTokenValue(next, variable.id, literal.value, modeId);\n\t\t}\n\t\tconst update: { description?: string; scopes?: string[]; unit?: string } = {};\n\t\tif (typeof token.description === 'string') update.description = token.description;\n\t\tconst extUnit = token.ext?.unit;\n\t\tif (typeof extUnit === 'string') unit = extUnit;\n\t\tif (unit && unit !== variable.unit) update.unit = unit;\n\t\tif (Array.isArray(token.ext?.scopes)) update.scopes = (token.ext!.scopes as unknown[]).filter((s): s is string => typeof s === 'string');\n\t\tif (Object.keys(update).length > 0) {\n\t\t\ttry {\n\t\t\t\tnext = updateTokenVariable(next, variable.id, update);\n\t\t\t} catch (error) {\n\t\t\t\twarn(`\\`${label}\\`: ${(error as Error).message}`);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Aliases, once every variable exists.\n\tfor (const { variable, modeId, ref, token } of pending) {\n\t\tconst label = [token.collection, ...token.path].join('.');\n\t\tconst raw = findRaw(ref, token);\n\t\tlet targetId = raw ? variableFor.get(raw) : undefined;\n\t\tif (!targetId) {\n\t\t\t// A variable already in the state: `Collection.a.b` or `a.b` in this collection.\n\t\t\tconst dot = ref.indexOf('.');\n\t\t\tconst inCollection = dot > 0 ? findTokenCollection(next, ref.slice(0, dot)) : undefined;\n\t\t\tconst found =\n\t\t\t\t(inCollection && findTokenVariable(next, ref.slice(dot + 1).split('.').join('/'), inCollection.id)) ||\n\t\t\t\tfindTokenVariable(next, ref.split('.').join('/'), variable.collectionId);\n\t\t\ttargetId = found ? found.id : undefined;\n\t\t}\n\t\tif (!targetId) {\n\t\t\twarn(`\\`${label}\\` refers to \\`{${ref}}\\`, which doesn't exist; kept the previous value`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst current = getTokenVariable(next, variable.id)!;\n\t\tconst error = checkTokenAlias(next, current, targetId);\n\t\tif (error) {\n\t\t\twarn(`\\`${label}\\`: ${error.message}`);\n\t\t\tcontinue;\n\t\t}\n\t\tnext = setTokenValue(next, variable.id, { alias: targetId }, modeId);\n\t}\n\n\treturn { state: next, report };\n}\n"]}