@vizejs/vite-plugin-musea 0.730.0 → 0.732.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 (51) hide show
  1. package/dist/a11y/index.d.mts +1 -1
  2. package/dist/a11y/index.mjs +200 -1
  3. package/dist/a11y/index.mjs.map +1 -0
  4. package/dist/apply-DIAnotZa.mjs +8 -0
  5. package/dist/apply-DIAnotZa.mjs.map +1 -0
  6. package/dist/autogen/index.mjs +1 -1
  7. package/dist/{autogen-B-N0cJbZ.mjs → autogen-D9K1av3V.mjs} +2 -2
  8. package/dist/{autogen-B-N0cJbZ.mjs.map → autogen-D9K1av3V.mjs.map} +1 -1
  9. package/dist/browser-launch-DCUbOf0d.mjs +29 -0
  10. package/dist/browser-launch-DCUbOf0d.mjs.map +1 -0
  11. package/dist/cli/index.mjs +9 -7
  12. package/dist/cli/index.mjs.map +1 -1
  13. package/dist/{gallery-DLl3pMOF.mjs → gallery-DNxzJA4V.mjs} +2 -2
  14. package/dist/{gallery-DLl3pMOF.mjs.map → gallery-DNxzJA4V.mjs.map} +1 -1
  15. package/dist/{browser-launch-L43ulIaZ.mjs → html-BW9Z7gL3.mjs} +5 -26
  16. package/dist/html-BW9Z7gL3.mjs.map +1 -0
  17. package/dist/{index-Dh4IXacU.d.mts → index-ELy0IbiZ.d.mts} +2 -2
  18. package/dist/{index-Dh4IXacU.d.mts.map → index-ELy0IbiZ.d.mts.map} +1 -1
  19. package/dist/index.d.mts +67 -3
  20. package/dist/index.d.mts.map +1 -1
  21. package/dist/index.mjs +505 -2232
  22. package/dist/index.mjs.map +1 -1
  23. package/dist/{template-D12HYJCn.mjs → module-BaxIBS_8.mjs} +39 -39
  24. package/dist/module-BaxIBS_8.mjs.map +1 -0
  25. package/dist/plugin-D2KEfrj1.mjs +2285 -0
  26. package/dist/plugin-D2KEfrj1.mjs.map +1 -0
  27. package/dist/{a11y-CR7bHK1d.mjs → report-CHUEZNZA.mjs} +3 -199
  28. package/dist/report-CHUEZNZA.mjs.map +1 -0
  29. package/dist/report-ZbXgDiN_.mjs +300 -0
  30. package/dist/report-ZbXgDiN_.mjs.map +1 -0
  31. package/dist/{options-DLFcpXwQ.mjs → report-identity-dHHBq0Ne.mjs} +502 -956
  32. package/dist/report-identity-dHHBq0Ne.mjs.map +1 -0
  33. package/dist/resolver-D8_4jxfT.mjs +812 -0
  34. package/dist/resolver-D8_4jxfT.mjs.map +1 -0
  35. package/dist/snapshot-identity-Cm-t65Kl.mjs +63 -0
  36. package/dist/snapshot-identity-Cm-t65Kl.mjs.map +1 -0
  37. package/dist/{vrt-CUz4NxKK.mjs → vrt-B8j2yfiN.mjs} +8 -363
  38. package/dist/vrt-B8j2yfiN.mjs.map +1 -0
  39. package/dist/{vrt-JoCQcFDG.d.mts → vrt-CuAg5Eow.d.mts} +2 -3
  40. package/dist/vrt-CuAg5Eow.d.mts.map +1 -0
  41. package/dist/vrt.d.mts +1 -1
  42. package/dist/vrt.mjs +3 -2
  43. package/package.json +5 -5
  44. package/dist/a11y-CR7bHK1d.mjs.map +0 -1
  45. package/dist/browser-launch-L43ulIaZ.mjs.map +0 -1
  46. package/dist/options-DLFcpXwQ.mjs.map +0 -1
  47. package/dist/template-D12HYJCn.mjs.map +0 -1
  48. package/dist/utils-BQi1club.mjs +0 -654
  49. package/dist/utils-BQi1club.mjs.map +0 -1
  50. package/dist/vrt-CUz4NxKK.mjs.map +0 -1
  51. package/dist/vrt-JoCQcFDG.d.mts.map +0 -1
@@ -0,0 +1,812 @@
1
+ import { createRequire } from "node:module";
2
+ import path from "node:path";
3
+ import fs from "node:fs";
4
+ //#region src/plugin/options.ts
5
+ const MUSEA_OPTIONS_KEY = "__vizeMuseaOptions";
6
+ function attachMuseaOptions(plugin, options) {
7
+ Object.defineProperty(plugin, MUSEA_OPTIONS_KEY, {
8
+ configurable: false,
9
+ enumerable: false,
10
+ value: options,
11
+ writable: false
12
+ });
13
+ return plugin;
14
+ }
15
+ function readMuseaOptions(plugin) {
16
+ if (!plugin || typeof plugin !== "object") return void 0;
17
+ return plugin[MUSEA_OPTIONS_KEY];
18
+ }
19
+ //#endregion
20
+ //#region src/with-defaults.ts
21
+ /**
22
+ * Parsing helpers for extracting prop defaults from a Vue SFC `<script setup>`
23
+ * block. Defaults are read only from `withDefaults(defineProps(...), { ... })`
24
+ * so unrelated local identifiers are never treated as prop defaults.
25
+ */
26
+ function extractWithDefaults(scriptContent) {
27
+ const defaults = /* @__PURE__ */ new Map();
28
+ let searchIndex = 0;
29
+ while (searchIndex < scriptContent.length) {
30
+ const calleeIndex = scriptContent.indexOf("withDefaults", searchIndex);
31
+ if (calleeIndex === -1) break;
32
+ searchIndex = calleeIndex + 12;
33
+ if (!isIdentifierBoundary(scriptContent[calleeIndex - 1])) continue;
34
+ if (!isIdentifierBoundary(scriptContent[searchIndex])) continue;
35
+ const parenIndex = skipWhitespace(scriptContent, searchIndex);
36
+ if (scriptContent[parenIndex] !== "(") continue;
37
+ const endParen = findMatching(scriptContent, parenIndex, "(", ")");
38
+ if (endParen === -1) continue;
39
+ const defaultsArg = splitTopLevel(scriptContent.slice(parenIndex + 1, endParen))[1]?.trim();
40
+ if (!defaultsArg?.startsWith("{")) continue;
41
+ const objectStart = scriptContent.indexOf(defaultsArg, parenIndex + 1);
42
+ const objectEnd = findMatching(scriptContent, objectStart, "{", "}");
43
+ if (objectEnd === -1) continue;
44
+ for (const [name, value] of objectProperties(scriptContent.slice(objectStart + 1, objectEnd))) defaults.set(name, value);
45
+ }
46
+ return defaults;
47
+ }
48
+ function objectProperties(objectBody) {
49
+ const properties = [];
50
+ for (const item of splitTopLevel(objectBody)) {
51
+ const colonIndex = topLevelColon(item);
52
+ if (colonIndex === -1) continue;
53
+ const rawKey = item.slice(0, colonIndex).trim();
54
+ const key = rawKey.match(/^[$A-Z_a-z][$\w]*$/)?.[0] ?? rawKey.match(/^["']([^"']+)["']$/)?.[1];
55
+ if (!key) continue;
56
+ const value = item.slice(colonIndex + 1).trim();
57
+ if (value) properties.push([key, value]);
58
+ }
59
+ return properties;
60
+ }
61
+ function splitTopLevel(source) {
62
+ const parts = [];
63
+ let start = 0;
64
+ let round = 0;
65
+ let curly = 0;
66
+ let square = 0;
67
+ let quote = null;
68
+ let escaped = false;
69
+ for (let index = 0; index < source.length; index++) {
70
+ const char = source[index];
71
+ if (quote) {
72
+ if (escaped) escaped = false;
73
+ else if (char === "\\") escaped = true;
74
+ else if (char === quote) quote = null;
75
+ continue;
76
+ }
77
+ if (char === "\"" || char === "'" || char === "`") {
78
+ quote = char;
79
+ continue;
80
+ }
81
+ if (char === "(") round++;
82
+ else if (char === ")") round--;
83
+ else if (char === "{") curly++;
84
+ else if (char === "}") curly--;
85
+ else if (char === "[") square++;
86
+ else if (char === "]") square--;
87
+ else if (char === "," && round === 0 && curly === 0 && square === 0) {
88
+ parts.push(source.slice(start, index).trim());
89
+ start = index + 1;
90
+ }
91
+ }
92
+ const tail = source.slice(start).trim();
93
+ if (tail) parts.push(tail);
94
+ return parts;
95
+ }
96
+ function topLevelColon(source) {
97
+ let round = 0;
98
+ let curly = 0;
99
+ let square = 0;
100
+ let quote = null;
101
+ let escaped = false;
102
+ for (let index = 0; index < source.length; index++) {
103
+ const char = source[index];
104
+ if (quote) {
105
+ if (escaped) escaped = false;
106
+ else if (char === "\\") escaped = true;
107
+ else if (char === quote) quote = null;
108
+ continue;
109
+ }
110
+ if (char === "\"" || char === "'" || char === "`") {
111
+ quote = char;
112
+ continue;
113
+ }
114
+ if (char === "(") round++;
115
+ else if (char === ")") round--;
116
+ else if (char === "{") curly++;
117
+ else if (char === "}") curly--;
118
+ else if (char === "[") square++;
119
+ else if (char === "]") square--;
120
+ else if (char === ":" && round === 0 && curly === 0 && square === 0) return index;
121
+ }
122
+ return -1;
123
+ }
124
+ function findMatching(source, start, open, close) {
125
+ let depth = 0;
126
+ let quote = null;
127
+ let escaped = false;
128
+ for (let index = start; index < source.length; index++) {
129
+ const char = source[index];
130
+ if (quote) {
131
+ if (escaped) escaped = false;
132
+ else if (char === "\\") escaped = true;
133
+ else if (char === quote) quote = null;
134
+ continue;
135
+ }
136
+ if (char === "\"" || char === "'" || char === "`") {
137
+ quote = char;
138
+ continue;
139
+ }
140
+ if (char === open) depth++;
141
+ if (char === close) {
142
+ depth--;
143
+ if (depth === 0) return index;
144
+ }
145
+ }
146
+ return -1;
147
+ }
148
+ function skipWhitespace(source, index) {
149
+ while (index < source.length && /\s/.test(source[index])) index++;
150
+ return index;
151
+ }
152
+ function isIdentifierBoundary(char) {
153
+ return char === void 0 || !/[$\w]/.test(char);
154
+ }
155
+ //#endregion
156
+ //#region src/native-loader.ts
157
+ /**
158
+ * Native binding loader for @vizejs/native.
159
+ *
160
+ * Provides lazy-loading of the native Rust-based parser and a JS fallback
161
+ * for SFC analysis when the native `analyzeSfc` function is unavailable.
162
+ */
163
+ let native = null;
164
+ let typescript = null;
165
+ function loadTypeScript() {
166
+ if (typescript) return typescript;
167
+ typescript = createRequire(import.meta.url)("typescript");
168
+ return typescript;
169
+ }
170
+ function loadNative() {
171
+ if (native) return native;
172
+ const require = createRequire(import.meta.url);
173
+ try {
174
+ native = require("@vizejs/native");
175
+ return native;
176
+ } catch (e) {
177
+ throw new Error(`Failed to load @vizejs/native. Make sure it's installed and built:\n${String(e)}`);
178
+ }
179
+ }
180
+ /**
181
+ * JS-based fallback for SFC analysis when native `analyzeSfc` is not available.
182
+ * Reads direct type-literal props and preserves the existing emits/defaults contract.
183
+ */
184
+ function analyzeSfcFallback(source, _options) {
185
+ try {
186
+ const props = [];
187
+ const emits = [];
188
+ const scriptSetupMatch = source.match(/<script\s+[^>]*setup[^>]*>([\s\S]*?)<\/script>/);
189
+ if (!scriptSetupMatch) {
190
+ if (!source.match(/<script[^>]*>([\s\S]*?)<\/script>/)) return {
191
+ props: [],
192
+ emits: []
193
+ };
194
+ }
195
+ const scriptContent = scriptSetupMatch?.[1] || "";
196
+ const withDefaults = extractWithDefaults(scriptContent);
197
+ for (const { name, type, optional } of directTypeLiteralProps(scriptContent)) {
198
+ const defaultValue = withDefaults.get(name);
199
+ props.push({
200
+ name,
201
+ type,
202
+ required: !optional,
203
+ ...defaultValue !== void 0 ? fallbackDefault(defaultValue) : {}
204
+ });
205
+ }
206
+ const emitsMatch = scriptContent.match(/defineEmits\s*<\s*\{([\s\S]*?)\}>/);
207
+ if (emitsMatch) {
208
+ const emitsBody = emitsMatch[1];
209
+ const emitRegex = /(\w+)\s*:/g;
210
+ let match;
211
+ while ((match = emitRegex.exec(emitsBody)) !== null) emits.push(match[1]);
212
+ }
213
+ return {
214
+ props,
215
+ emits
216
+ };
217
+ } catch {
218
+ return {
219
+ props: [],
220
+ emits: []
221
+ };
222
+ }
223
+ }
224
+ function directTypeLiteralProps(scriptContent) {
225
+ const ts = loadTypeScript();
226
+ const source = ts.createSourceFile("props.ts", scriptContent, ts.ScriptTarget.Latest, true);
227
+ const findLiteral = (node) => {
228
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === "defineProps") {
229
+ const argument = node.typeArguments?.[0];
230
+ if (argument && ts.isTypeLiteralNode(argument)) return argument;
231
+ }
232
+ return ts.forEachChild(node, findLiteral);
233
+ };
234
+ return findLiteral(source)?.members.flatMap((member) => {
235
+ if (!ts.isPropertySignature(member) || !member.type) return [];
236
+ let name = member.name;
237
+ if (ts.isComputedPropertyName(name)) {
238
+ if (!ts.isStringLiteral(name.expression)) return [];
239
+ name = name.expression;
240
+ }
241
+ if (!ts.isIdentifier(name) && !ts.isStringLiteral(name) && !ts.isNumericLiteral(name)) return [];
242
+ return [{
243
+ name: name.text,
244
+ type: member.type.getText(source),
245
+ optional: !!member.questionToken
246
+ }];
247
+ }) ?? [];
248
+ }
249
+ /** Preserve the JSON contract when an older native binary requires the typed fallback. */
250
+ function fallbackDefault(source) {
251
+ const ts = loadTypeScript();
252
+ const statement = ts.createSourceFile("default.ts", `const value = (${source});`, ts.ScriptTarget.Latest, true).statements[0];
253
+ let value = statement && ts.isVariableStatement(statement) ? statement.declarationList.declarations[0]?.initializer : void 0;
254
+ while (value && (ts.isParenthesizedExpression(value) || ts.isAsExpression(value) || ts.isSatisfiesExpression(value))) value = value.expression;
255
+ if (value && (ts.isStringLiteral(value) || ts.isNoSubstitutionTemplateLiteral(value))) return { default_value: value.text };
256
+ if (value && ts.isNumericLiteral(value) && Number.isFinite(Number(value.text))) return { default_value: Number(value.text) };
257
+ if (value?.kind === ts.SyntaxKind.TrueKeyword) return { default_value: true };
258
+ if (value?.kind === ts.SyntaxKind.FalseKeyword) return { default_value: false };
259
+ if (value?.kind === ts.SyntaxKind.NullKeyword) return { default_value: null };
260
+ if (value && ts.isPrefixUnaryExpression(value) && ts.isNumericLiteral(value.operand)) {
261
+ const number = Number(value.operand.text);
262
+ if (value.operator === ts.SyntaxKind.MinusToken) return { default_value: -number };
263
+ if (value.operator === ts.SyntaxKind.PlusToken) return { default_value: number };
264
+ }
265
+ return {
266
+ default_source: source,
267
+ unsupported_default: true
268
+ };
269
+ }
270
+ //#endregion
271
+ //#region src/tokens/native.ts
272
+ function tokenNative() {
273
+ const native = loadNative();
274
+ return {
275
+ parseDesignTokensFromPath(path) {
276
+ return normalizeCategories(parseJsonResult(native.parseDesignTokensFromPath(path)));
277
+ },
278
+ buildDesignTokenMap(categories) {
279
+ return nullRecord(parseJsonResult(native.buildDesignTokenMap(JSON.stringify(categories))));
280
+ },
281
+ resolveDesignTokenReferences(categories) {
282
+ const resolved = parseJsonResult(native.resolveDesignTokenReferences(JSON.stringify(categories)));
283
+ return {
284
+ ...resolved,
285
+ categories: normalizeCategories(resolved.categories),
286
+ tokenMap: nullRecord(resolved.tokenMap)
287
+ };
288
+ },
289
+ flattenDesignTokenCategories(categories) {
290
+ return parseJsonResult(native.flattenDesignTokenCategories(JSON.stringify(categories)));
291
+ },
292
+ generateDesignTokensMarkdown(categories, generatedAt) {
293
+ return native.generateDesignTokensMarkdown(JSON.stringify(categories), generatedAt);
294
+ },
295
+ validateDesignTokenReference(tokenMap, reference, selfPath) {
296
+ return parseJsonResult(native.validateDesignTokenReference(JSON.stringify(tokenMap), reference, selfPath));
297
+ },
298
+ findDependentDesignTokens(tokenMap, targetPath) {
299
+ return native.findDependentDesignTokens(JSON.stringify(tokenMap), targetPath);
300
+ }
301
+ };
302
+ }
303
+ function parseJsonResult(value) {
304
+ if (typeof value === "string") return JSON.parse(value);
305
+ return value;
306
+ }
307
+ function normalizeCategories(categories) {
308
+ for (const category of categories) {
309
+ category.tokens = nullRecord(Object.fromEntries(sortTokenEntries(category.tokens)));
310
+ if (category.subcategories) normalizeCategories(category.subcategories);
311
+ }
312
+ return categories;
313
+ }
314
+ function sortTokenEntries(tokens) {
315
+ return Object.entries(tokens).sort((a, b) => {
316
+ const order = compareTokenOrder(a[1], b[1]);
317
+ if (order !== 0) return order;
318
+ return a[0].localeCompare(b[0], void 0, { numeric: true });
319
+ });
320
+ }
321
+ function compareTokenOrder(a, b) {
322
+ const aOrder = tokenOrder(a);
323
+ const bOrder = tokenOrder(b);
324
+ if (aOrder === void 0 && bOrder === void 0) return 0;
325
+ if (aOrder === void 0) return 1;
326
+ if (bOrder === void 0) return -1;
327
+ return aOrder - bOrder;
328
+ }
329
+ function tokenOrder(token) {
330
+ const order = token.attributes?.order;
331
+ if (typeof order === "number" && Number.isFinite(order)) return order;
332
+ if (typeof order === "string") {
333
+ const parsed = Number(order);
334
+ if (Number.isFinite(parsed)) return parsed;
335
+ }
336
+ }
337
+ function nullRecord(record) {
338
+ return Object.assign(Object.create(null), record);
339
+ }
340
+ //#endregion
341
+ //#region src/tokens/tailwind.ts
342
+ const TAILWIND_TOKEN_EXTENSIONS = new Set([
343
+ ".css",
344
+ ".pcss",
345
+ ".postcss"
346
+ ]);
347
+ const VARIABLE_DECLARATION_RE = /(--[A-Za-z0-9_-]+)\s*:\s*([^;{}]+);/g;
348
+ const CSS_COMMENT_RE = /\/\*[\s\S]*?\*\//g;
349
+ const NAMESPACE_MAPPINGS = [
350
+ {
351
+ prefix: "inset-shadow",
352
+ category: "shadow",
353
+ pathPrefix: ["inset"],
354
+ type: "shadow"
355
+ },
356
+ {
357
+ prefix: "drop-shadow",
358
+ category: "shadow",
359
+ pathPrefix: ["drop"],
360
+ type: "shadow"
361
+ },
362
+ {
363
+ prefix: "font-weight",
364
+ category: "typography",
365
+ pathPrefix: ["fontWeight"],
366
+ type: "fontWeight"
367
+ },
368
+ {
369
+ prefix: "color",
370
+ category: "color",
371
+ type: "color"
372
+ },
373
+ {
374
+ prefix: "spacing",
375
+ category: "spacing",
376
+ type: "dimension"
377
+ },
378
+ {
379
+ prefix: "font",
380
+ category: "typography",
381
+ pathPrefix: ["font"],
382
+ type: "fontFamily"
383
+ },
384
+ {
385
+ prefix: "text",
386
+ category: "typography",
387
+ pathPrefix: ["fontSize"],
388
+ type: "dimension"
389
+ },
390
+ {
391
+ prefix: "leading",
392
+ category: "typography",
393
+ pathPrefix: ["lineHeight"],
394
+ type: "number"
395
+ },
396
+ {
397
+ prefix: "tracking",
398
+ category: "typography",
399
+ pathPrefix: ["letterSpacing"],
400
+ type: "dimension"
401
+ },
402
+ {
403
+ prefix: "radius",
404
+ category: "radius",
405
+ type: "dimension"
406
+ },
407
+ {
408
+ prefix: "shadow",
409
+ category: "shadow",
410
+ type: "shadow"
411
+ },
412
+ {
413
+ prefix: "breakpoint",
414
+ category: "breakpoint",
415
+ type: "dimension"
416
+ },
417
+ {
418
+ prefix: "container",
419
+ category: "container",
420
+ type: "dimension"
421
+ },
422
+ {
423
+ prefix: "ease",
424
+ category: "easing",
425
+ type: "cubicBezier"
426
+ },
427
+ {
428
+ prefix: "animate",
429
+ category: "animation",
430
+ type: "transition"
431
+ },
432
+ {
433
+ prefix: "blur",
434
+ category: "blur",
435
+ type: "dimension"
436
+ },
437
+ {
438
+ prefix: "perspective",
439
+ category: "perspective",
440
+ type: "dimension"
441
+ },
442
+ {
443
+ prefix: "aspect",
444
+ category: "aspectRatio",
445
+ type: "number"
446
+ }
447
+ ];
448
+ async function isTailwindTokenPath(tokensPath) {
449
+ const stat = await fs.promises.stat(tokensPath).catch(() => null);
450
+ if (!stat) return false;
451
+ if (stat.isFile()) return TAILWIND_TOKEN_EXTENSIONS.has(path.extname(tokensPath));
452
+ if (!stat.isDirectory()) return false;
453
+ return (await fs.promises.readdir(tokensPath, { withFileTypes: true })).some((entry) => entry.isFile() && TAILWIND_TOKEN_EXTENSIONS.has(path.extname(entry.name)));
454
+ }
455
+ async function parseTailwindTokens(tokensPath) {
456
+ const files = await collectTailwindTokenFiles(tokensPath);
457
+ const candidates = [];
458
+ for (const file of files) {
459
+ const css = await fs.promises.readFile(file, "utf-8");
460
+ candidates.push(...extractTailwindTokenCandidates(css));
461
+ }
462
+ return normalizeCategories(buildCategories(candidates));
463
+ }
464
+ async function collectTailwindTokenFiles(tokensPath) {
465
+ if ((await fs.promises.stat(tokensPath)).isFile()) return [tokensPath];
466
+ return (await fs.promises.readdir(tokensPath, { withFileTypes: true })).filter((entry) => entry.isFile() && TAILWIND_TOKEN_EXTENSIONS.has(path.extname(entry.name))).map((entry) => path.join(tokensPath, entry.name)).sort();
467
+ }
468
+ function extractTailwindTokenCandidates(css) {
469
+ const source = css.replace(CSS_COMMENT_RE, "");
470
+ const candidates = [];
471
+ let match;
472
+ VARIABLE_DECLARATION_RE.lastIndex = 0;
473
+ while ((match = VARIABLE_DECLARATION_RE.exec(source)) !== null) {
474
+ const variable = match[1];
475
+ const value = match[2].trim();
476
+ const mapped = mapTokenVariable(variable, value);
477
+ if (!mapped || !value) continue;
478
+ candidates.push({
479
+ variable,
480
+ value,
481
+ ...mapped
482
+ });
483
+ }
484
+ return candidates;
485
+ }
486
+ function mapTokenVariable(variable, value) {
487
+ const tailwind = mapTailwindVariable(variable);
488
+ if (tailwind) return {
489
+ ...tailwind,
490
+ description: `Tailwind theme variable ${variable}`
491
+ };
492
+ const segments = variable.replace(/^--/, "").split("-").filter(Boolean);
493
+ const category = segments[0];
494
+ if (!category) return null;
495
+ const rest = segments.slice(1).join("-");
496
+ return {
497
+ category,
498
+ path: rest ? [rest] : ["DEFAULT"],
499
+ type: inferCustomPropertyType(value),
500
+ description: `Custom property ${variable}`
501
+ };
502
+ }
503
+ function mapTailwindVariable(variable) {
504
+ const name = variable.replace(/^--/, "");
505
+ const mapping = NAMESPACE_MAPPINGS.find((candidate) => name === candidate.prefix || name.startsWith(`${candidate.prefix}-`));
506
+ if (!mapping) return null;
507
+ const rest = name === mapping.prefix ? "DEFAULT" : name.slice(mapping.prefix.length + 1);
508
+ const pathParts = [...mapping.pathPrefix ?? [], ...tailwindNameToPath(rest)];
509
+ if (pathParts.length === 0) return null;
510
+ return {
511
+ category: mapping.category,
512
+ path: pathParts,
513
+ type: mapping.type
514
+ };
515
+ }
516
+ function inferCustomPropertyType(value) {
517
+ const trimmed = value.trim();
518
+ if (/^(?:#|rgba?\(|hsla?\(|oklch\(|oklab\(|color-mix\(|color\()/i.test(trimmed)) return "color";
519
+ if (/^-?(?:\d+\.\d+|\d+)(?:px|rem|em|vh|vw|vmin|vmax|%)$/i.test(trimmed)) return "dimension";
520
+ if (/^-?(?:\d+\.\d+|\d+)$/.test(trimmed)) return "number";
521
+ return "other";
522
+ }
523
+ function tailwindNameToPath(name) {
524
+ if (!name || name === "DEFAULT") return ["DEFAULT"];
525
+ const parts = name.split("-").filter(Boolean);
526
+ if (parts.length <= 1) return parts;
527
+ const last = parts[parts.length - 1];
528
+ if (/^\d+$/.test(last)) return [...parts.slice(0, -1), last];
529
+ return [parts.join("-")];
530
+ }
531
+ function buildCategories(candidates) {
532
+ const variableToPath = /* @__PURE__ */ new Map();
533
+ for (const candidate of candidates) variableToPath.set(candidate.variable, [candidate.category, ...candidate.path].join("."));
534
+ const categoryMap = /* @__PURE__ */ new Map();
535
+ for (const candidate of candidates) {
536
+ const category = categoryMap.get(candidate.category) ?? {
537
+ name: candidate.category,
538
+ tokens: nullRecord({})
539
+ };
540
+ categoryMap.set(candidate.category, category);
541
+ const valueReference = parseTailwindVariableReference(candidate.value);
542
+ const referencedPath = valueReference ? variableToPath.get(valueReference) : void 0;
543
+ const token = {
544
+ value: referencedPath ? `{${referencedPath}}` : candidate.value,
545
+ type: candidate.type,
546
+ description: candidate.description,
547
+ attributes: { tailwindVariable: candidate.variable },
548
+ $tier: referencedPath ? "semantic" : "primitive",
549
+ ...referencedPath ? { $reference: referencedPath } : {}
550
+ };
551
+ setCategoryToken(category, candidate.path, token);
552
+ }
553
+ return [...categoryMap.values()];
554
+ }
555
+ function parseTailwindVariableReference(value) {
556
+ return value.match(/^var\(\s*(--[A-Za-z0-9_-]+)\s*(?:,[^)]+)?\)$/)?.[1];
557
+ }
558
+ function setCategoryToken(category, pathParts, token) {
559
+ if (pathParts.length === 1) {
560
+ category.tokens[pathParts[0]] = token;
561
+ return;
562
+ }
563
+ let current = category;
564
+ for (const part of pathParts.slice(0, -1)) {
565
+ current.subcategories ??= [];
566
+ let next = current.subcategories.find((subcategory) => subcategory.name === part);
567
+ if (!next) {
568
+ next = {
569
+ name: part,
570
+ tokens: nullRecord({})
571
+ };
572
+ current.subcategories.push(next);
573
+ }
574
+ current = next;
575
+ }
576
+ current.tokens[pathParts[pathParts.length - 1]] = token;
577
+ }
578
+ //#endregion
579
+ //#region src/tokens/parser.ts
580
+ /**
581
+ * Token parsing utilities for Style Dictionary integration.
582
+ *
583
+ * Thin native binding for design token files (JSON) and directories.
584
+ */
585
+ /**
586
+ * Parse Style Dictionary tokens file/directory or Tailwind CSS theme variables.
587
+ */
588
+ async function parseTokens(tokensPath) {
589
+ if (await isTailwindTokenPath(tokensPath)) return parseTailwindTokens(tokensPath);
590
+ return normalizeCategories(tokenNative().parseDesignTokensFromPath(tokensPath));
591
+ }
592
+ //#endregion
593
+ //#region src/tokens/usage.ts
594
+ /**
595
+ * Token usage scanning and value normalization.
596
+ *
597
+ * Scans art file `<style>` blocks for CSS property values that match
598
+ * design token values, and provides value normalization utilities.
599
+ */
600
+ /**
601
+ * Normalize a token value for comparison.
602
+ * - Lowercase, trim
603
+ * - Leading-zero: `.5rem` -> `0.5rem`
604
+ * - Short hex: `#fff` -> `#ffffff`
605
+ */
606
+ function normalizeTokenValue(value) {
607
+ let v = String(value).trim().toLowerCase();
608
+ const shortHex = v.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])?$/);
609
+ if (shortHex) {
610
+ const [, r, g, b, a] = shortHex;
611
+ v = a ? `#${r}${r}${g}${g}${b}${b}${a}${a}` : `#${r}${r}${g}${g}${b}${b}`;
612
+ }
613
+ v = v.replace(/(?<![0-9])\.(\d)/g, "0.$1");
614
+ return v;
615
+ }
616
+ const STYLE_BLOCK_RE = /<style[^>]*>([\s\S]*?)<\/style>/g;
617
+ const CSS_PROPERTY_RE = /^\s*([\w-]+)\s*:\s*(.+?)\s*;?\s*$/;
618
+ /**
619
+ * Scan art file sources for token value matches in `<style>` blocks.
620
+ */
621
+ function scanTokenUsage(artFiles, tokenMap) {
622
+ const valueLookup = /* @__PURE__ */ new Map();
623
+ for (const [tokenPath, token] of Object.entries(tokenMap)) {
624
+ const normalized = normalizeTokenValue(token.$resolvedValue ?? token.value);
625
+ if (!normalized) continue;
626
+ const existing = valueLookup.get(normalized);
627
+ if (existing) existing.push(tokenPath);
628
+ else valueLookup.set(normalized, [tokenPath]);
629
+ const tailwindVariable = token.attributes?.tailwindVariable;
630
+ if (typeof tailwindVariable === "string") {
631
+ const normalizedVariable = normalizeTokenValue(`var(${tailwindVariable})`);
632
+ const variableMatches = valueLookup.get(normalizedVariable);
633
+ if (variableMatches) variableMatches.push(tokenPath);
634
+ else valueLookup.set(normalizedVariable, [tokenPath]);
635
+ }
636
+ }
637
+ const usageMap = {};
638
+ for (const [artPath, artInfo] of artFiles) {
639
+ let source;
640
+ try {
641
+ source = fs.readFileSync(artPath, "utf-8");
642
+ } catch {
643
+ continue;
644
+ }
645
+ const allLines = source.split("\n");
646
+ const styleRegions = [];
647
+ let match;
648
+ STYLE_BLOCK_RE.lastIndex = 0;
649
+ while ((match = STYLE_BLOCK_RE.exec(source)) !== null) {
650
+ const beforeMatch = source.slice(0, match.index);
651
+ const startTag = source.slice(match.index, match.index + match[0].indexOf(match[1]));
652
+ const startLine = beforeMatch.split("\n").length + startTag.split("\n").length - 1;
653
+ styleRegions.push({
654
+ startLine,
655
+ content: match[1]
656
+ });
657
+ }
658
+ for (const region of styleRegions) {
659
+ const lines = region.content.split("\n");
660
+ for (let i = 0; i < lines.length; i++) {
661
+ const line = lines[i];
662
+ const propMatch = line.match(CSS_PROPERTY_RE);
663
+ if (!propMatch) continue;
664
+ const property = propMatch[1];
665
+ const valueParts = propMatch[2].split(/\s+/);
666
+ for (const part of valueParts) {
667
+ const normalizedPart = normalizeTokenValue(part);
668
+ const matchingTokens = valueLookup.get(normalizedPart);
669
+ if (!matchingTokens) continue;
670
+ const lineNumber = region.startLine + i;
671
+ const lineContent = allLines[lineNumber - 1]?.trim() ?? line.trim();
672
+ for (const tokenPath of matchingTokens) {
673
+ if (!usageMap[tokenPath]) usageMap[tokenPath] = [];
674
+ let entry = usageMap[tokenPath].find((e) => e.artPath === artPath);
675
+ if (!entry) {
676
+ entry = {
677
+ artPath,
678
+ artTitle: artInfo.metadata.title,
679
+ artCategory: artInfo.metadata.category,
680
+ matches: []
681
+ };
682
+ usageMap[tokenPath].push(entry);
683
+ }
684
+ if (!entry.matches.some((m) => m.line === lineNumber && m.property === property)) entry.matches.push({
685
+ line: lineNumber,
686
+ lineContent,
687
+ property
688
+ });
689
+ }
690
+ }
691
+ }
692
+ }
693
+ }
694
+ return usageMap;
695
+ }
696
+ //#endregion
697
+ //#region src/tokens/resolver.ts
698
+ /**
699
+ * Token resolution, CRUD operations, and validation.
700
+ *
701
+ * Handles building flat token maps from categories, resolving reference chains,
702
+ * reading/writing raw token files, and validating semantic references.
703
+ */
704
+ const JSON_TOKEN_EXTENSIONS = new Set([".json", ".tokens.json"]);
705
+ const UNSAFE_TOKEN_PATH_SEGMENTS = new Set([
706
+ "__proto__",
707
+ "prototype",
708
+ "constructor"
709
+ ]);
710
+ function parseTokenPath(dotPath) {
711
+ const parts = dotPath.split(".");
712
+ if (parts.length === 0 || parts.some((part) => part.trim() === "")) throw new Error(`Invalid token path "${dotPath}"`);
713
+ const unsafeSegment = parts.find((part) => UNSAFE_TOKEN_PATH_SEGMENTS.has(part));
714
+ if (unsafeSegment) throw new Error(`Token path segment "${unsafeSegment}" is not allowed`);
715
+ return parts;
716
+ }
717
+ /**
718
+ * Flatten nested categories into a flat map keyed by dot-path.
719
+ */
720
+ function buildTokenMap(categories) {
721
+ return nullRecord(tokenNative().buildDesignTokenMap(categories));
722
+ }
723
+ /**
724
+ * Resolve references in categories, setting $tier, $reference, and $resolvedValue.
725
+ */
726
+ function resolveReferences(categories, _tokenMap) {
727
+ const resolved = tokenNative().resolveDesignTokenReferences(categories);
728
+ categories.splice(0, categories.length, ...normalizeCategories(resolved.categories));
729
+ }
730
+ /**
731
+ * Read raw JSON token file.
732
+ */
733
+ async function readRawTokenFile(tokensPath) {
734
+ if (!isJsonTokenPath(tokensPath)) throw new Error("Token editing is only supported for JSON token files");
735
+ const content = await fs.promises.readFile(tokensPath, "utf-8");
736
+ return JSON.parse(content);
737
+ }
738
+ /**
739
+ * Write raw JSON token file atomically (write tmp, rename).
740
+ */
741
+ async function writeRawTokenFile(tokensPath, data) {
742
+ if (!isJsonTokenPath(tokensPath)) throw new Error("Token editing is only supported for JSON token files");
743
+ const tmpPath = tokensPath + ".tmp";
744
+ await fs.promises.writeFile(tmpPath, JSON.stringify(data, null, 2) + "\n", "utf-8");
745
+ await fs.promises.rename(tmpPath, tokensPath);
746
+ }
747
+ function isJsonTokenPath(tokensPath) {
748
+ return JSON_TOKEN_EXTENSIONS.has(path.extname(tokensPath)) || tokensPath.endsWith(".tokens.json");
749
+ }
750
+ /**
751
+ * Set a token at a dot-separated path in the raw JSON structure.
752
+ */
753
+ function setTokenAtPath(data, dotPath, token) {
754
+ const parts = parseTokenPath(dotPath);
755
+ let current = data;
756
+ for (let i = 0; i < parts.length - 1; i++) {
757
+ const key = parts[i];
758
+ if (typeof current[key] !== "object" || current[key] === null) current[key] = {};
759
+ current = current[key];
760
+ }
761
+ const leafKey = parts[parts.length - 1];
762
+ const raw = { value: token.value };
763
+ if (token.type) raw.type = token.type;
764
+ if (token.description) raw.description = token.description;
765
+ if (token.$tier) raw.$tier = token.$tier;
766
+ if (token.$reference) raw.$reference = token.$reference;
767
+ if (token.attributes) raw.attributes = token.attributes;
768
+ current[leafKey] = raw;
769
+ }
770
+ /**
771
+ * Delete a token at a dot-separated path, cleaning empty parents.
772
+ */
773
+ function deleteTokenAtPath(data, dotPath) {
774
+ const parts = parseTokenPath(dotPath);
775
+ const parents = [];
776
+ let current = data;
777
+ for (let i = 0; i < parts.length - 1; i++) {
778
+ const key = parts[i];
779
+ if (typeof current[key] !== "object" || current[key] === null) return false;
780
+ parents.push({
781
+ obj: current,
782
+ key
783
+ });
784
+ current = current[key];
785
+ }
786
+ const leafKey = parts[parts.length - 1];
787
+ if (!(leafKey in current)) return false;
788
+ delete current[leafKey];
789
+ for (let i = parents.length - 1; i >= 0; i--) {
790
+ const { obj, key } = parents[i];
791
+ const child = obj[key];
792
+ if (Object.keys(child).length === 0) delete obj[key];
793
+ else break;
794
+ }
795
+ return true;
796
+ }
797
+ /**
798
+ * Validate that a semantic reference points to an existing token and has no cycles.
799
+ */
800
+ function validateSemanticReference(tokenMap, reference, selfPath) {
801
+ return tokenNative().validateDesignTokenReference(tokenMap, reference, selfPath);
802
+ }
803
+ /**
804
+ * Find all tokens that reference the given path.
805
+ */
806
+ function findDependentTokens(tokenMap, targetPath) {
807
+ return tokenNative().findDependentDesignTokens(tokenMap, targetPath);
808
+ }
809
+ //#endregion
810
+ export { resolveReferences as a, writeRawTokenFile as c, tokenNative as d, analyzeSfcFallback as f, readMuseaOptions as h, readRawTokenFile as i, scanTokenUsage as l, attachMuseaOptions as m, deleteTokenAtPath as n, setTokenAtPath as o, loadNative as p, findDependentTokens as r, validateSemanticReference as s, buildTokenMap as t, parseTokens as u };
811
+
812
+ //# sourceMappingURL=resolver-D8_4jxfT.mjs.map