@vizejs/vite-plugin-musea 0.441.0 → 0.443.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 (69) hide show
  1. package/dist/a11y/index.d.mts +1 -1
  2. package/dist/a11y/index.mjs +1 -1
  3. package/dist/{a11y-BbFK942j.mjs → a11y-DuFu75hl.mjs} +7 -6
  4. package/dist/a11y-DuFu75hl.mjs.map +1 -0
  5. package/dist/cli/index.d.mts +7 -1
  6. package/dist/cli/index.d.mts.map +1 -1
  7. package/dist/cli/index.mjs +111 -10
  8. package/dist/cli/index.mjs.map +1 -1
  9. package/dist/gallery/assets/MonacoEditor-CmjDtbrI.js +2 -0
  10. package/dist/gallery/assets/MonacoEditor-DxzpSKbC.css +1 -0
  11. package/dist/gallery/assets/{cssMode-D6nK_kDe.js → cssMode-B16oWKdO.js} +1 -1
  12. package/dist/gallery/assets/{editor.api-Bs4-VZ3V.js → editor.api-CfYscGcC.js} +1 -1
  13. package/dist/gallery/assets/{freemarker2-rDjl8685.js → freemarker2-Bsla50n3.js} +1 -1
  14. package/dist/gallery/assets/{handlebars-OkqFmHQQ.js → handlebars-CS_Y5cXs.js} +1 -1
  15. package/dist/gallery/assets/{html-Bq6Ai15v.js → html-DagAGhpS.js} +1 -1
  16. package/dist/gallery/assets/{htmlMode-H8XqFg_c.js → htmlMode-CiuL2Y-P.js} +1 -1
  17. package/dist/gallery/assets/index-BaRljRmN.css +1 -0
  18. package/dist/gallery/assets/{index-V774j4nI.js → index-Bma1gCA8.js} +6 -6
  19. package/dist/gallery/assets/{javascript-DY3JGgzg.js → javascript-BQYQMq9R.js} +1 -1
  20. package/dist/gallery/assets/{jsonMode-CYaDarn3.js → jsonMode-C5lyVqru.js} +1 -1
  21. package/dist/gallery/assets/{liquid-DSwk2doy.js → liquid-qbEuwx0o.js} +1 -1
  22. package/dist/gallery/assets/{lspLanguageFeatures-CThGg67f.js → lspLanguageFeatures-Dqts9s1L.js} +1 -1
  23. package/dist/gallery/assets/{mdx-B9XzBagU.js → mdx-DN6uw21R.js} +1 -1
  24. package/dist/gallery/assets/{python-sRU_mC7d.js → python-Cbp5CGeG.js} +1 -1
  25. package/dist/gallery/assets/{razor-CUHkZDIN.js → razor-BXu36P7p.js} +1 -1
  26. package/dist/gallery/assets/{register-BRx-S1So.js → register-vvpXemvQ.js} +2 -2
  27. package/dist/gallery/assets/{toggleHighContrast-tYUHUcTT.js → toggleHighContrast-9EQLxoB9.js} +1 -1
  28. package/dist/gallery/assets/{tsMode-C0mNxmwK.js → tsMode-DakVvyMV.js} +1 -1
  29. package/dist/gallery/assets/{typescript-Ba_YUPxA.js → typescript-DEY4mnQU.js} +1 -1
  30. package/dist/gallery/assets/{vs-omjQMPuv.js → vs-Cd8KAJDG.js} +3 -3
  31. package/dist/gallery/assets/{workers-BOTkt7rp.js → workers-GvANOwSC.js} +1 -1
  32. package/dist/gallery/assets/{xml-CGK9gfdX.js → xml-cZMAcMEr.js} +1 -1
  33. package/dist/gallery/assets/{yaml-CA-jHXc3.js → yaml-CReFeuuC.js} +1 -1
  34. package/dist/gallery/index.html +2 -2
  35. package/dist/{gallery-CLe_4-XW.mjs → gallery-LgVvVp28.mjs} +2 -2
  36. package/dist/{gallery-CLe_4-XW.mjs.map → gallery-LgVvVp28.mjs.map} +1 -1
  37. package/dist/{index-GkKsNzkf.d.mts → index-BU4-FGUC.d.mts} +3 -4
  38. package/dist/index-BU4-FGUC.d.mts.map +1 -0
  39. package/dist/{index-CtvsGVFJ.d.mts → index-ZFHsOEPD.d.mts} +6 -1
  40. package/dist/{index-CtvsGVFJ.d.mts.map → index-ZFHsOEPD.d.mts.map} +1 -1
  41. package/dist/index.d.mts +3 -3
  42. package/dist/index.mjs +153 -1592
  43. package/dist/index.mjs.map +1 -1
  44. package/dist/options-DnKPMMPV.mjs +2159 -0
  45. package/dist/options-DnKPMMPV.mjs.map +1 -0
  46. package/dist/{template-BgBSA10_.mjs → template-CpNUvZPp.mjs} +5 -3
  47. package/dist/template-CpNUvZPp.mjs.map +1 -0
  48. package/dist/{utils-DeMLVlNS.mjs → utils-BloA9YP9.mjs} +35 -29
  49. package/dist/utils-BloA9YP9.mjs.map +1 -0
  50. package/dist/utils-ChmPv0qc.mjs +55 -0
  51. package/dist/utils-ChmPv0qc.mjs.map +1 -0
  52. package/dist/{vrt-DNNAFYv1.d.mts → vrt-DtcnqPhF.d.mts} +22 -3
  53. package/dist/vrt-DtcnqPhF.d.mts.map +1 -0
  54. package/dist/{vrt-VuGK9wTX.mjs → vrt-PuxpRuHa.mjs} +392 -97
  55. package/dist/vrt-PuxpRuHa.mjs.map +1 -0
  56. package/dist/vrt.d.mts +1 -1
  57. package/dist/vrt.mjs +1 -1
  58. package/package.json +4 -4
  59. package/dist/a11y-BbFK942j.mjs.map +0 -1
  60. package/dist/gallery/assets/MonacoEditor-B2gyQ5TW.js +0 -2
  61. package/dist/gallery/assets/MonacoEditor-Db3Q217Z.css +0 -1
  62. package/dist/gallery/assets/index-DTMv-5r0.css +0 -1
  63. package/dist/index-GkKsNzkf.d.mts.map +0 -1
  64. package/dist/options-Bjo4e_75.mjs +0 -582
  65. package/dist/options-Bjo4e_75.mjs.map +0 -1
  66. package/dist/template-BgBSA10_.mjs.map +0 -1
  67. package/dist/utils-DeMLVlNS.mjs.map +0 -1
  68. package/dist/vrt-DNNAFYv1.d.mts.map +0 -1
  69. package/dist/vrt-VuGK9wTX.mjs.map +0 -1
@@ -0,0 +1,2159 @@
1
+ import { E as loadNative, S as resolveTrustedSourcePath, T as analyzeSfcFallback, f as parseJsonBody, g as assertComponentSourcePath, s as toPascalCase, t as escapeHtml, v as decodeUrlComponent, w as HttpError, x as resolveInsideAny, y as isVueSourcePath } from "./utils-BloA9YP9.mjs";
2
+ import { s as resolveSnapshotIdentity } from "./vrt-PuxpRuHa.mjs";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import ts from "typescript";
6
+ import crypto, { createHash } from "node:crypto";
7
+ //#region src/component-source.ts
8
+ function allowedSourceRoots(root, scanRoots = []) {
9
+ return [...new Set([root, ...scanRoots].map((sourceRoot) => path.resolve(sourceRoot)))];
10
+ }
11
+ function resolveReadableArtPath(root, scanRoots, artPath) {
12
+ return resolveTrustedSourcePath(root, scanRoots, artPath, "art path");
13
+ }
14
+ function resolveComponentSourcePath(art, artPath, sourceRoots) {
15
+ const componentPath = art.isInline && art.componentPath ? art.componentPath : art.metadata.component ? path.isAbsolute(art.metadata.component) ? art.metadata.component : path.resolve(path.dirname(artPath), art.metadata.component) : null;
16
+ const [projectRoot, ...extraRoots] = sourceRoots;
17
+ if (!componentPath) return null;
18
+ const resolved = resolveTrustedSourcePath(projectRoot ?? ".", extraRoots, componentPath, "component path");
19
+ assertComponentSourcePath(resolved, "component path");
20
+ return resolved;
21
+ }
22
+ //#endregion
23
+ //#region src/variant-bindings.ts
24
+ /** Preserve ordinary bindings and disambiguate every normalized collision. */
25
+ function variantComponentNames(variants) {
26
+ const names = /* @__PURE__ */ new Map();
27
+ const counts = /* @__PURE__ */ new Map();
28
+ for (const { name } of variants) {
29
+ if (names.has(name)) throw new Error(`Duplicate Musea variant name: ${JSON.stringify(name)}`);
30
+ const binding = toPascalCase(name);
31
+ names.set(name, binding);
32
+ counts.set(binding, (counts.get(binding) ?? 0) + 1);
33
+ }
34
+ for (const [name, binding] of names) if (counts.get(binding) > 1) {
35
+ const hash = createHash("sha256").update(JSON.stringify(name)).digest("hex");
36
+ names.set(name, `__MuseaVariant_${hash}`);
37
+ }
38
+ return names;
39
+ }
40
+ //#endregion
41
+ //#region src/art-module-vue2.ts
42
+ /**
43
+ * Legacy Vue 2 variant emission.
44
+ *
45
+ * Vue 2 has no `openBlock`/`createElementBlock` runtime, so the compiled Vue 3
46
+ * render functions the SFC pipeline produces cannot load there. Vue 2 galleries
47
+ * keep the runtime-compiled `template:` string they always had — the TypeScript
48
+ * fix in #3857 applies to Vue 3, which is what `.art.vue` with
49
+ * `<script setup lang="ts">` targets.
50
+ */
51
+ function escapeTemplateLiteral(str) {
52
+ return str.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$");
53
+ }
54
+ function emitLegacyVariant(context) {
55
+ const { variantComponentName, variantName, template, componentTagName, componentBindingName, scriptSetup, hasSetup, isolatedSetup, setupReturn, importDeclaresName } = context;
56
+ const escapedTemplate = escapeTemplateLiteral(template);
57
+ const fullTemplate = `<div data-variant="${escapeTemplateLiteral(escapeHtml(variantName))}">${escapedTemplate}</div>`;
58
+ const componentNames = /* @__PURE__ */ new Map();
59
+ if (componentTagName) componentNames.set(componentTagName, componentBindingName);
60
+ if (scriptSetup) {
61
+ for (const name of scriptSetup.returnNames) if (/^[A-Z]/.test(name) && scriptSetup.imports.some((imp) => importDeclaresName(imp, name))) componentNames.set(name, name);
62
+ }
63
+ const components = componentNames.size > 0 ? ` components: { ${[...componentNames].map(([name, value]) => `${JSON.stringify(name)}: ${value}`).join(", ")} },\n` : "";
64
+ if (scriptSetup && hasSetup && isolatedSetup) return `
65
+ export const ${variantComponentName} = __museaDefineComponent({
66
+ name: '${variantComponentName}',
67
+ ${components} setup() {
68
+ ${scriptSetup.setupBody.join("\n")}
69
+ return ${setupReturn};
70
+ },
71
+ template: \`${fullTemplate}\`,
72
+ });
73
+ `;
74
+ if (scriptSetup && hasSetup) return `
75
+ export const ${variantComponentName} = __museaDefineComponent({
76
+ name: '${variantComponentName}',
77
+ ${components} setup() {
78
+ return __museaSharedSetup;
79
+ },
80
+ template: \`${fullTemplate}\`,
81
+ });
82
+ `;
83
+ return `
84
+ export const ${variantComponentName} = {
85
+ name: '${variantComponentName}',
86
+ ${components} template: \`${fullTemplate}\`,
87
+ };
88
+ `;
89
+ }
90
+ //#endregion
91
+ //#region src/art-component.ts
92
+ /**
93
+ * Resolve which component an art file demonstrates, and under what tag.
94
+ *
95
+ * Shared by the art module and by the per-variant SFC compiler (#3857) so both
96
+ * agree on the import path, the tag `<Self>` expands to, and the binding name.
97
+ * The parsed `<script setup>` is passed in rather than parsed here, so this
98
+ * module does not have to import back from `art-module.ts`.
99
+ */
100
+ function componentNameFromSource(source) {
101
+ const withoutQuery = source.split(/[?#]/, 1)[0] || source;
102
+ const filename = path.basename(withoutQuery);
103
+ const extension = path.extname(filename);
104
+ const name = toPascalCase(extension ? filename.slice(0, -extension.length) : filename);
105
+ return name === "Variant" ? "MuseaComponent" : name;
106
+ }
107
+ function resolveArtComponent(art, filePath, scriptSetup, options = {}) {
108
+ let componentImportPath;
109
+ let componentTagName;
110
+ let componentBindingName = "__MuseaComponent";
111
+ const defineArtComponentName = scriptSetup?.defineArtComponentName;
112
+ const defineArtComponentSource = scriptSetup?.defineArtComponentSource;
113
+ if (art.isInline && art.componentPath) {
114
+ componentImportPath = options.root ? resolveComponentSourcePath(art, filePath, allowedSourceRoots(options.root, options.scanRoots ?? [])) ?? void 0 : art.componentPath;
115
+ componentTagName = "MuseaComponent";
116
+ componentBindingName = componentTagName;
117
+ } else if (defineArtComponentSource || art.metadata.component) {
118
+ const componentSource = defineArtComponentSource ?? art.metadata.component;
119
+ if (componentSource) {
120
+ const sourceArt = componentSource === art.metadata.component ? art : {
121
+ ...art,
122
+ metadata: {
123
+ ...art.metadata,
124
+ component: componentSource
125
+ }
126
+ };
127
+ componentImportPath = options.root ? resolveComponentSourcePath(sourceArt, filePath, allowedSourceRoots(options.root, options.scanRoots ?? [])) ?? void 0 : path.isAbsolute(componentSource) ? componentSource : path.resolve(path.dirname(filePath), componentSource);
128
+ }
129
+ componentTagName = defineArtComponentName ?? (art.metadata.component ? componentNameFromSource(art.metadata.component) : "MuseaComponent");
130
+ componentBindingName = componentTagName;
131
+ }
132
+ return {
133
+ componentImportPath,
134
+ componentTagName,
135
+ componentBindingName
136
+ };
137
+ }
138
+ /** Expand `<Self>` in a variant template to the resolved component tag. */
139
+ function expandSelfTag(template, componentTagName) {
140
+ if (!componentTagName) return template;
141
+ return template.replace(/<Self(?=[\s/>])/g, `<${componentTagName}`).replace(/<\/Self\s*>/g, `</${componentTagName}>`);
142
+ }
143
+ //#endregion
144
+ //#region src/art-module.ts
145
+ /**
146
+ * Art module generation for Musea.
147
+ *
148
+ * Generates the virtual ES modules that represent parsed `.art.vue` files,
149
+ * including variant component definitions and script setup handling.
150
+ */
151
+ /**
152
+ * Extract the content of the first <script setup> block from a Vue SFC source.
153
+ */
154
+ function extractScriptSetupContent(source) {
155
+ return source.match(/<script\s+[^>]*setup[^>]*>([\s\S]*?)<\/script>/)?.[1]?.trim();
156
+ }
157
+ function extractScriptSetupIsolated(source) {
158
+ const match = source.match(/<script\s+([^>]*)\bsetup\b([^>]*)>/);
159
+ if (!match) return true;
160
+ const isolate = `${match[1] ?? ""} ${match[2] ?? ""}`.match(/\bisolate\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/);
161
+ return (isolate?.[1] ?? isolate?.[2] ?? isolate?.[3]) !== "false";
162
+ }
163
+ function resolveRelativeSpecifier(specifier, artDir) {
164
+ if (!specifier.startsWith(".")) return specifier;
165
+ return path.resolve(artDir, specifier);
166
+ }
167
+ function rewriteRelativeImportStatement(statement, artDir) {
168
+ return statement.replace(/\bfrom\s+(['"])([^'"]+)\1/g, (_match, quote, specifier) => `from ${quote}${resolveRelativeSpecifier(specifier, artDir)}${quote}`).replace(/^(\s*import\s+)(['"])([^'"]+)\2(\s*;?\s*)$/s, (_match, prefix, quote, specifier, suffix) => `${prefix}${quote}${resolveRelativeSpecifier(specifier, artDir)}${quote}${suffix}`);
169
+ }
170
+ function countCharBalance(source, openChar, closeChar) {
171
+ let balance = 0;
172
+ for (const char of source) if (char === openChar) balance++;
173
+ else if (char === closeChar) balance--;
174
+ return balance;
175
+ }
176
+ function isCompleteImportStatement(statement) {
177
+ const trimmed = statement.trim();
178
+ if (!trimmed.startsWith("import ")) return false;
179
+ if (countCharBalance(statement, "{", "}") > 0) return false;
180
+ return /^import\s+[\s\S]+?\s+from\s+['"][^'"]+['"]\s*;?$/s.test(trimmed) || /^import\s+['"][^'"]+['"]\s*;?$/s.test(trimmed);
181
+ }
182
+ function splitTopLevelCommaList(source) {
183
+ const parts = [];
184
+ let current = "";
185
+ let braceDepth = 0;
186
+ let bracketDepth = 0;
187
+ let parenDepth = 0;
188
+ for (const char of source) {
189
+ if (char === "," && braceDepth === 0 && bracketDepth === 0 && parenDepth === 0) {
190
+ const trimmed = current.trim();
191
+ if (trimmed) parts.push(trimmed);
192
+ current = "";
193
+ continue;
194
+ }
195
+ current += char;
196
+ if (char === "{") braceDepth++;
197
+ else if (char === "}") braceDepth--;
198
+ else if (char === "[") bracketDepth++;
199
+ else if (char === "]") bracketDepth--;
200
+ else if (char === "(") parenDepth++;
201
+ else if (char === ")") parenDepth--;
202
+ }
203
+ const trimmed = current.trim();
204
+ if (trimmed) parts.push(trimmed);
205
+ return parts;
206
+ }
207
+ function collectImportedNames(statement, returnNames) {
208
+ const fromMatch = statement.replace(/\s+/g, " ").trim().replace(/;$/, "").match(/^import\s+(type\s+)?(.+?)\s+from\s+['"][^'"]+['"]$/);
209
+ if (!fromMatch) return;
210
+ if (fromMatch[1]) return;
211
+ const specifierParts = splitTopLevelCommaList(fromMatch[2].trim());
212
+ const defaultOrNamespace = specifierParts[0]?.trim() ?? "";
213
+ const trailing = specifierParts.slice(1).join(", ").trim();
214
+ if (defaultOrNamespace && !defaultOrNamespace.startsWith("{")) {
215
+ const namespaceMatch = defaultOrNamespace.match(/^\*\s+as\s+([A-Za-z_$][\w$]*)$/);
216
+ if (namespaceMatch) returnNames.add(namespaceMatch[1]);
217
+ else if (!defaultOrNamespace.startsWith("type ")) returnNames.add(defaultOrNamespace);
218
+ }
219
+ const namedBlock = defaultOrNamespace.startsWith("{") ? defaultOrNamespace : trailing.startsWith("{") ? trailing : "";
220
+ if (!namedBlock) return;
221
+ const namedContent = namedBlock.slice(1, -1);
222
+ for (const part of splitTopLevelCommaList(namedContent)) {
223
+ const trimmed = part.trim();
224
+ if (!trimmed || trimmed.startsWith("type ")) continue;
225
+ const alias = trimmed.split(/\s+as\s+/).pop()?.trim();
226
+ if (alias) returnNames.add(alias);
227
+ }
228
+ }
229
+ function importDeclaresName(statement, name) {
230
+ const names = /* @__PURE__ */ new Set();
231
+ collectImportedNames(statement, names);
232
+ return names.has(name);
233
+ }
234
+ function collectObjectDestructuredNames(statement, returnNames) {
235
+ const match = statement.match(/^(?:export\s+)?(?:const|let|var)\s+\{([\s\S]*?)\}\s*=/);
236
+ if (!match) return;
237
+ for (const part of splitTopLevelCommaList(match[1])) {
238
+ let name = part.trim();
239
+ if (!name) continue;
240
+ if (name.startsWith("...")) name = name.slice(3).trim();
241
+ else if (name.includes(":")) name = name.split(":").pop().trim();
242
+ else if (name.includes("=")) name = name.split("=")[0].trim();
243
+ if (name.includes("=")) name = name.split("=")[0].trim();
244
+ if (/^[A-Za-z_$][\w$]*$/.test(name)) returnNames.add(name);
245
+ }
246
+ }
247
+ function collectArrayDestructuredNames(statement, returnNames) {
248
+ const match = statement.match(/^(?:export\s+)?(?:const|let|var)\s+\[([\s\S]*?)\]\s*=/);
249
+ if (!match) return;
250
+ for (const part of splitTopLevelCommaList(match[1])) {
251
+ let name = part.trim();
252
+ if (!name) continue;
253
+ if (name.startsWith("...")) name = name.slice(3).trim();
254
+ if (name.includes("=")) name = name.split("=")[0].trim();
255
+ if (/^[A-Za-z_$][\w$]*$/.test(name)) returnNames.add(name);
256
+ }
257
+ }
258
+ function collectTopLevelReturnNames(setupBody, returnNames) {
259
+ let braceDepth = 0;
260
+ for (let i = 0; i < setupBody.length; i++) {
261
+ const line = setupBody[i];
262
+ const trimmed = line.trim();
263
+ if (braceDepth === 0) {
264
+ if (/^(?:export\s+)?(?:const|let|var)\s+\{/.test(trimmed)) {
265
+ const statementLines = [line];
266
+ let balance = countCharBalance(line, "{", "}") + countCharBalance(line, "[", "]") + countCharBalance(line, "(", ")");
267
+ while (balance > 0 && i + 1 < setupBody.length) {
268
+ i++;
269
+ statementLines.push(setupBody[i]);
270
+ balance += countCharBalance(setupBody[i], "{", "}") + countCharBalance(setupBody[i], "[", "]") + countCharBalance(setupBody[i], "(", ")");
271
+ }
272
+ collectObjectDestructuredNames(statementLines.join("\n"), returnNames);
273
+ continue;
274
+ }
275
+ if (/^(?:export\s+)?(?:const|let|var)\s+\[/.test(trimmed)) {
276
+ const statementLines = [line];
277
+ let balance = countCharBalance(line, "{", "}") + countCharBalance(line, "[", "]") + countCharBalance(line, "(", ")");
278
+ while (balance > 0 && i + 1 < setupBody.length) {
279
+ i++;
280
+ statementLines.push(setupBody[i]);
281
+ balance += countCharBalance(setupBody[i], "{", "}") + countCharBalance(setupBody[i], "[", "]") + countCharBalance(setupBody[i], "(", ")");
282
+ }
283
+ collectArrayDestructuredNames(statementLines.join("\n"), returnNames);
284
+ continue;
285
+ }
286
+ const constMatch = trimmed.match(/^(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)/);
287
+ if (constMatch) returnNames.add(constMatch[1]);
288
+ const functionMatch = trimmed.match(/^(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(/);
289
+ if (functionMatch) returnNames.add(functionMatch[1]);
290
+ const classMatch = trimmed.match(/^(?:export\s+)?class\s+([A-Za-z_$][\w$]*)\b/);
291
+ if (classMatch) returnNames.add(classMatch[1]);
292
+ }
293
+ braceDepth += countCharBalance(line, "{", "}");
294
+ }
295
+ }
296
+ /**
297
+ * Parse script setup content into imports and setup body.
298
+ * Returns the import lines, setup body lines, and all identifiers to expose.
299
+ */
300
+ function parseScriptSetupForArt(content) {
301
+ const lines = content.split("\n");
302
+ const imports = [];
303
+ const setupBody = [];
304
+ const returnNames = /* @__PURE__ */ new Set();
305
+ let currentImport = null;
306
+ const defineArtComponent = extractDefineArtComponent(content);
307
+ let defineArtBalance = 0;
308
+ for (const line of lines) {
309
+ const trimmed = line.trim();
310
+ if (defineArtBalance > 0) {
311
+ defineArtBalance += countCharBalance(line, "(", ")");
312
+ continue;
313
+ }
314
+ if (currentImport) {
315
+ currentImport.push(line);
316
+ const statement = currentImport.join("\n");
317
+ if (isCompleteImportStatement(statement)) {
318
+ imports.push(statement);
319
+ collectImportedNames(statement, returnNames);
320
+ currentImport = null;
321
+ }
322
+ continue;
323
+ }
324
+ if (trimmed.startsWith("import ")) {
325
+ currentImport = [line];
326
+ const statement = currentImport.join("\n");
327
+ if (isCompleteImportStatement(statement)) {
328
+ imports.push(statement);
329
+ collectImportedNames(statement, returnNames);
330
+ currentImport = null;
331
+ }
332
+ continue;
333
+ }
334
+ if (isDefineArtLine(trimmed)) {
335
+ defineArtBalance = Math.max(0, countCharBalance(line, "(", ")"));
336
+ continue;
337
+ }
338
+ setupBody.push(line);
339
+ }
340
+ if (currentImport) {
341
+ const statement = currentImport.join("\n");
342
+ imports.push(statement);
343
+ collectImportedNames(statement, returnNames);
344
+ }
345
+ collectTopLevelReturnNames(setupBody, returnNames);
346
+ returnNames.delete("type");
347
+ if (defineArtComponent.name) returnNames.delete(defineArtComponent.name);
348
+ return {
349
+ imports,
350
+ setupBody,
351
+ returnNames: [...returnNames],
352
+ defineArtComponentName: defineArtComponent.name,
353
+ defineArtComponentSource: defineArtComponent.source
354
+ };
355
+ }
356
+ function extractDefineArtComponent(content) {
357
+ const sourceMatch = content.match(/\bdefineArt\s*\(\s*(['"])([^'"]+)\1/);
358
+ if (sourceMatch) return {
359
+ name: componentNameFromSource(sourceMatch[2]),
360
+ source: sourceMatch[2]
361
+ };
362
+ return { name: content.match(/\bdefineArt\s*\(\s*([A-Za-z_$][\w$]*)/)?.[1] };
363
+ }
364
+ function isDefineArtLine(trimmed) {
365
+ return /\bdefineArt\s*\(/.test(trimmed);
366
+ }
367
+ function generateArtModule(art, filePath, options = {}) {
368
+ let componentImportPath;
369
+ let componentTagName;
370
+ let componentBindingName = "__MuseaComponent";
371
+ const scriptSetup = art.scriptSetupContent ? parseScriptSetupForArt(art.scriptSetupContent) : null;
372
+ const defineArtComponentName = scriptSetup?.defineArtComponentName;
373
+ const defineArtComponentSource = scriptSetup?.defineArtComponentSource;
374
+ if (art.isInline && art.componentPath) {
375
+ componentImportPath = options.root ? resolveComponentSourcePath(art, filePath, allowedSourceRoots(options.root, options.scanRoots ?? [])) ?? void 0 : art.componentPath;
376
+ componentTagName = "MuseaComponent";
377
+ } else if (defineArtComponentSource || art.metadata.component) {
378
+ const componentSource = defineArtComponentSource ?? art.metadata.component;
379
+ if (componentSource) {
380
+ const sourceArt = componentSource === art.metadata.component ? art : {
381
+ ...art,
382
+ metadata: {
383
+ ...art.metadata,
384
+ component: componentSource
385
+ }
386
+ };
387
+ componentImportPath = options.root ? resolveComponentSourcePath(sourceArt, filePath, allowedSourceRoots(options.root, options.scanRoots ?? [])) ?? void 0 : path.isAbsolute(componentSource) ? componentSource : path.resolve(path.dirname(filePath), componentSource);
388
+ }
389
+ componentTagName = defineArtComponentName ?? (art.metadata.component ? componentNameFromSource(art.metadata.component) : "MuseaComponent");
390
+ componentBindingName = componentTagName;
391
+ }
392
+ const hasSetupBody = scriptSetup?.setupBody.some((line) => line.trim().length > 0) ?? false;
393
+ const hasSetup = !!scriptSetup && (hasSetupBody || scriptSetup.returnNames.length > 0);
394
+ let code = `
395
+ // Auto-generated module for: ${path.basename(filePath)}
396
+ `;
397
+ if (options.vueVersion === 2 && hasSetup) code += `import { defineComponent as __museaDefineComponent } from 'vue';\n`;
398
+ if (scriptSetup) {
399
+ const artDir = path.dirname(filePath);
400
+ for (const imp of scriptSetup.imports) {
401
+ const resolved = rewriteRelativeImportStatement(imp, artDir);
402
+ code += `${resolved}\n`;
403
+ }
404
+ }
405
+ if (componentImportPath && componentTagName) {
406
+ if (!scriptSetup?.imports.some((imp) => importDeclaresName(imp, componentBindingName))) code += `import ${componentBindingName} from ${JSON.stringify(componentImportPath)};\n`;
407
+ code += `export const __component__ = ${componentBindingName};\n`;
408
+ }
409
+ code += `
410
+ export const metadata = ${JSON.stringify(art.metadata)};
411
+ export const variants = ${JSON.stringify(art.variants)};
412
+ export const __styles__ = ${JSON.stringify(art.styleBlocks ?? [])};
413
+ `;
414
+ const setupReturn = `{ ${scriptSetup?.returnNames.join(", ") ?? ""} }`;
415
+ const isolatedSetup = art.scriptSetupIsolated !== false;
416
+ if (scriptSetup && hasSetup && !isolatedSetup) code += `
417
+ const __museaSharedSetup = (() => {
418
+ ${scriptSetup.setupBody.join("\n")}
419
+ return ${setupReturn};
420
+ })();
421
+ `;
422
+ const bindings = variantComponentNames(art.variants);
423
+ for (const variant of art.variants) {
424
+ const variantComponentName = bindings.get(variant.name);
425
+ const template = expandSelfTag(variant.template, componentTagName);
426
+ if (options.vueVersion === 2) {
427
+ code += emitLegacyVariant({
428
+ variantComponentName,
429
+ variantName: variant.name,
430
+ template,
431
+ componentTagName,
432
+ componentBindingName,
433
+ scriptSetup,
434
+ hasSetup,
435
+ isolatedSetup,
436
+ setupReturn,
437
+ importDeclaresName
438
+ });
439
+ continue;
440
+ }
441
+ const variantModuleId = `virtual:musea-variant:${filePath}:${encodeURIComponent(variant.name)}`;
442
+ code += `
443
+ import ${variantComponentName} from ${JSON.stringify(variantModuleId)};
444
+ export { ${variantComponentName} };
445
+ `;
446
+ }
447
+ const defaultVariant = art.variants.find((v) => v.isDefault) || art.variants[0];
448
+ if (defaultVariant) code += `
449
+ export default ${bindings.get(defaultVariant.name)};
450
+ `;
451
+ return code;
452
+ }
453
+ //#endregion
454
+ //#region src/art-order.ts
455
+ function sortedArts(arts) {
456
+ return [...arts].sort(compareArtFiles);
457
+ }
458
+ function compareArtFiles(a, b) {
459
+ const order = compareOrder(a.metadata.order, b.metadata.order);
460
+ if (order !== 0) return order;
461
+ const title = a.metadata.title.localeCompare(b.metadata.title, void 0, { numeric: true });
462
+ if (title !== 0) return title;
463
+ return a.path.localeCompare(b.path, void 0, { numeric: true });
464
+ }
465
+ function compareOrder(a, b) {
466
+ if (a === void 0 && b === void 0) return 0;
467
+ if (a === void 0) return 1;
468
+ if (b === void 0) return -1;
469
+ return a - b;
470
+ }
471
+ //#endregion
472
+ //#region src/tokens/native.ts
473
+ function tokenNative() {
474
+ const native = loadNative();
475
+ return {
476
+ parseDesignTokensFromPath(path) {
477
+ return normalizeCategories(parseJsonResult(native.parseDesignTokensFromPath(path)));
478
+ },
479
+ buildDesignTokenMap(categories) {
480
+ return nullRecord(parseJsonResult(native.buildDesignTokenMap(JSON.stringify(categories))));
481
+ },
482
+ resolveDesignTokenReferences(categories) {
483
+ const resolved = parseJsonResult(native.resolveDesignTokenReferences(JSON.stringify(categories)));
484
+ return {
485
+ ...resolved,
486
+ categories: normalizeCategories(resolved.categories),
487
+ tokenMap: nullRecord(resolved.tokenMap)
488
+ };
489
+ },
490
+ flattenDesignTokenCategories(categories) {
491
+ return parseJsonResult(native.flattenDesignTokenCategories(JSON.stringify(categories)));
492
+ },
493
+ generateDesignTokensMarkdown(categories, generatedAt) {
494
+ return native.generateDesignTokensMarkdown(JSON.stringify(categories), generatedAt);
495
+ },
496
+ validateDesignTokenReference(tokenMap, reference, selfPath) {
497
+ return parseJsonResult(native.validateDesignTokenReference(JSON.stringify(tokenMap), reference, selfPath));
498
+ },
499
+ findDependentDesignTokens(tokenMap, targetPath) {
500
+ return native.findDependentDesignTokens(JSON.stringify(tokenMap), targetPath);
501
+ }
502
+ };
503
+ }
504
+ function parseJsonResult(value) {
505
+ if (typeof value === "string") return JSON.parse(value);
506
+ return value;
507
+ }
508
+ function normalizeCategories(categories) {
509
+ for (const category of categories) {
510
+ category.tokens = nullRecord(Object.fromEntries(sortTokenEntries(category.tokens)));
511
+ if (category.subcategories) normalizeCategories(category.subcategories);
512
+ }
513
+ return categories;
514
+ }
515
+ function sortTokenEntries(tokens) {
516
+ return Object.entries(tokens).sort((a, b) => {
517
+ const order = compareTokenOrder(a[1], b[1]);
518
+ if (order !== 0) return order;
519
+ return a[0].localeCompare(b[0], void 0, { numeric: true });
520
+ });
521
+ }
522
+ function compareTokenOrder(a, b) {
523
+ const aOrder = tokenOrder(a);
524
+ const bOrder = tokenOrder(b);
525
+ if (aOrder === void 0 && bOrder === void 0) return 0;
526
+ if (aOrder === void 0) return 1;
527
+ if (bOrder === void 0) return -1;
528
+ return aOrder - bOrder;
529
+ }
530
+ function tokenOrder(token) {
531
+ const order = token.attributes?.order;
532
+ if (typeof order === "number" && Number.isFinite(order)) return order;
533
+ if (typeof order === "string") {
534
+ const parsed = Number(order);
535
+ if (Number.isFinite(parsed)) return parsed;
536
+ }
537
+ }
538
+ function nullRecord(record) {
539
+ return Object.assign(Object.create(null), record);
540
+ }
541
+ //#endregion
542
+ //#region src/tokens/tailwind.ts
543
+ const TAILWIND_TOKEN_EXTENSIONS = new Set([
544
+ ".css",
545
+ ".pcss",
546
+ ".postcss"
547
+ ]);
548
+ const VARIABLE_DECLARATION_RE = /(--[A-Za-z0-9_-]+)\s*:\s*([^;{}]+);/g;
549
+ const CSS_COMMENT_RE = /\/\*[\s\S]*?\*\//g;
550
+ const NAMESPACE_MAPPINGS = [
551
+ {
552
+ prefix: "inset-shadow",
553
+ category: "shadow",
554
+ pathPrefix: ["inset"],
555
+ type: "shadow"
556
+ },
557
+ {
558
+ prefix: "drop-shadow",
559
+ category: "shadow",
560
+ pathPrefix: ["drop"],
561
+ type: "shadow"
562
+ },
563
+ {
564
+ prefix: "font-weight",
565
+ category: "typography",
566
+ pathPrefix: ["fontWeight"],
567
+ type: "fontWeight"
568
+ },
569
+ {
570
+ prefix: "color",
571
+ category: "color",
572
+ type: "color"
573
+ },
574
+ {
575
+ prefix: "spacing",
576
+ category: "spacing",
577
+ type: "dimension"
578
+ },
579
+ {
580
+ prefix: "font",
581
+ category: "typography",
582
+ pathPrefix: ["font"],
583
+ type: "fontFamily"
584
+ },
585
+ {
586
+ prefix: "text",
587
+ category: "typography",
588
+ pathPrefix: ["fontSize"],
589
+ type: "dimension"
590
+ },
591
+ {
592
+ prefix: "leading",
593
+ category: "typography",
594
+ pathPrefix: ["lineHeight"],
595
+ type: "number"
596
+ },
597
+ {
598
+ prefix: "tracking",
599
+ category: "typography",
600
+ pathPrefix: ["letterSpacing"],
601
+ type: "dimension"
602
+ },
603
+ {
604
+ prefix: "radius",
605
+ category: "radius",
606
+ type: "dimension"
607
+ },
608
+ {
609
+ prefix: "shadow",
610
+ category: "shadow",
611
+ type: "shadow"
612
+ },
613
+ {
614
+ prefix: "breakpoint",
615
+ category: "breakpoint",
616
+ type: "dimension"
617
+ },
618
+ {
619
+ prefix: "container",
620
+ category: "container",
621
+ type: "dimension"
622
+ },
623
+ {
624
+ prefix: "ease",
625
+ category: "easing",
626
+ type: "cubicBezier"
627
+ },
628
+ {
629
+ prefix: "animate",
630
+ category: "animation",
631
+ type: "transition"
632
+ },
633
+ {
634
+ prefix: "blur",
635
+ category: "blur",
636
+ type: "dimension"
637
+ },
638
+ {
639
+ prefix: "perspective",
640
+ category: "perspective",
641
+ type: "dimension"
642
+ },
643
+ {
644
+ prefix: "aspect",
645
+ category: "aspectRatio",
646
+ type: "number"
647
+ }
648
+ ];
649
+ async function isTailwindTokenPath(tokensPath) {
650
+ const stat = await fs.promises.stat(tokensPath).catch(() => null);
651
+ if (!stat) return false;
652
+ if (stat.isFile()) return TAILWIND_TOKEN_EXTENSIONS.has(path.extname(tokensPath));
653
+ if (!stat.isDirectory()) return false;
654
+ return (await fs.promises.readdir(tokensPath, { withFileTypes: true })).some((entry) => entry.isFile() && TAILWIND_TOKEN_EXTENSIONS.has(path.extname(entry.name)));
655
+ }
656
+ async function parseTailwindTokens(tokensPath) {
657
+ const files = await collectTailwindTokenFiles(tokensPath);
658
+ const candidates = [];
659
+ for (const file of files) {
660
+ const css = await fs.promises.readFile(file, "utf-8");
661
+ candidates.push(...extractTailwindTokenCandidates(css));
662
+ }
663
+ return normalizeCategories(buildCategories(candidates));
664
+ }
665
+ async function collectTailwindTokenFiles(tokensPath) {
666
+ if ((await fs.promises.stat(tokensPath)).isFile()) return [tokensPath];
667
+ 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();
668
+ }
669
+ function extractTailwindTokenCandidates(css) {
670
+ const source = css.replace(CSS_COMMENT_RE, "");
671
+ const candidates = [];
672
+ let match;
673
+ VARIABLE_DECLARATION_RE.lastIndex = 0;
674
+ while ((match = VARIABLE_DECLARATION_RE.exec(source)) !== null) {
675
+ const variable = match[1];
676
+ const value = match[2].trim();
677
+ const mapped = mapTokenVariable(variable, value);
678
+ if (!mapped || !value) continue;
679
+ candidates.push({
680
+ variable,
681
+ value,
682
+ ...mapped
683
+ });
684
+ }
685
+ return candidates;
686
+ }
687
+ function mapTokenVariable(variable, value) {
688
+ const tailwind = mapTailwindVariable(variable);
689
+ if (tailwind) return {
690
+ ...tailwind,
691
+ description: `Tailwind theme variable ${variable}`
692
+ };
693
+ const segments = variable.replace(/^--/, "").split("-").filter(Boolean);
694
+ const category = segments[0];
695
+ if (!category) return null;
696
+ const rest = segments.slice(1).join("-");
697
+ return {
698
+ category,
699
+ path: rest ? [rest] : ["DEFAULT"],
700
+ type: inferCustomPropertyType(value),
701
+ description: `Custom property ${variable}`
702
+ };
703
+ }
704
+ function mapTailwindVariable(variable) {
705
+ const name = variable.replace(/^--/, "");
706
+ const mapping = NAMESPACE_MAPPINGS.find((candidate) => name === candidate.prefix || name.startsWith(`${candidate.prefix}-`));
707
+ if (!mapping) return null;
708
+ const rest = name === mapping.prefix ? "DEFAULT" : name.slice(mapping.prefix.length + 1);
709
+ const pathParts = [...mapping.pathPrefix ?? [], ...tailwindNameToPath(rest)];
710
+ if (pathParts.length === 0) return null;
711
+ return {
712
+ category: mapping.category,
713
+ path: pathParts,
714
+ type: mapping.type
715
+ };
716
+ }
717
+ function inferCustomPropertyType(value) {
718
+ const trimmed = value.trim();
719
+ if (/^(?:#|rgba?\(|hsla?\(|oklch\(|oklab\(|color-mix\(|color\()/i.test(trimmed)) return "color";
720
+ if (/^-?(?:\d+\.\d+|\d+)(?:px|rem|em|vh|vw|vmin|vmax|%)$/i.test(trimmed)) return "dimension";
721
+ if (/^-?(?:\d+\.\d+|\d+)$/.test(trimmed)) return "number";
722
+ return "other";
723
+ }
724
+ function tailwindNameToPath(name) {
725
+ if (!name || name === "DEFAULT") return ["DEFAULT"];
726
+ const parts = name.split("-").filter(Boolean);
727
+ if (parts.length <= 1) return parts;
728
+ const last = parts[parts.length - 1];
729
+ if (/^\d+$/.test(last)) return [...parts.slice(0, -1), last];
730
+ return [parts.join("-")];
731
+ }
732
+ function buildCategories(candidates) {
733
+ const variableToPath = /* @__PURE__ */ new Map();
734
+ for (const candidate of candidates) variableToPath.set(candidate.variable, [candidate.category, ...candidate.path].join("."));
735
+ const categoryMap = /* @__PURE__ */ new Map();
736
+ for (const candidate of candidates) {
737
+ const category = categoryMap.get(candidate.category) ?? {
738
+ name: candidate.category,
739
+ tokens: nullRecord({})
740
+ };
741
+ categoryMap.set(candidate.category, category);
742
+ const valueReference = parseTailwindVariableReference(candidate.value);
743
+ const referencedPath = valueReference ? variableToPath.get(valueReference) : void 0;
744
+ const token = {
745
+ value: referencedPath ? `{${referencedPath}}` : candidate.value,
746
+ type: candidate.type,
747
+ description: candidate.description,
748
+ attributes: { tailwindVariable: candidate.variable },
749
+ $tier: referencedPath ? "semantic" : "primitive",
750
+ ...referencedPath ? { $reference: referencedPath } : {}
751
+ };
752
+ setCategoryToken(category, candidate.path, token);
753
+ }
754
+ return [...categoryMap.values()];
755
+ }
756
+ function parseTailwindVariableReference(value) {
757
+ return value.match(/^var\(\s*(--[A-Za-z0-9_-]+)\s*(?:,[^)]+)?\)$/)?.[1];
758
+ }
759
+ function setCategoryToken(category, pathParts, token) {
760
+ if (pathParts.length === 1) {
761
+ category.tokens[pathParts[0]] = token;
762
+ return;
763
+ }
764
+ let current = category;
765
+ for (const part of pathParts.slice(0, -1)) {
766
+ current.subcategories ??= [];
767
+ let next = current.subcategories.find((subcategory) => subcategory.name === part);
768
+ if (!next) {
769
+ next = {
770
+ name: part,
771
+ tokens: nullRecord({})
772
+ };
773
+ current.subcategories.push(next);
774
+ }
775
+ current = next;
776
+ }
777
+ current.tokens[pathParts[pathParts.length - 1]] = token;
778
+ }
779
+ //#endregion
780
+ //#region src/tokens/parser.ts
781
+ /**
782
+ * Token parsing utilities for Style Dictionary integration.
783
+ *
784
+ * Thin native binding for design token files (JSON) and directories.
785
+ */
786
+ /**
787
+ * Parse Style Dictionary tokens file/directory or Tailwind CSS theme variables.
788
+ */
789
+ async function parseTokens(tokensPath) {
790
+ if (await isTailwindTokenPath(tokensPath)) return parseTailwindTokens(tokensPath);
791
+ return normalizeCategories(tokenNative().parseDesignTokensFromPath(tokensPath));
792
+ }
793
+ //#endregion
794
+ //#region src/tokens/usage.ts
795
+ /**
796
+ * Token usage scanning and value normalization.
797
+ *
798
+ * Scans art file `<style>` blocks for CSS property values that match
799
+ * design token values, and provides value normalization utilities.
800
+ */
801
+ /**
802
+ * Normalize a token value for comparison.
803
+ * - Lowercase, trim
804
+ * - Leading-zero: `.5rem` -> `0.5rem`
805
+ * - Short hex: `#fff` -> `#ffffff`
806
+ */
807
+ function normalizeTokenValue(value) {
808
+ let v = String(value).trim().toLowerCase();
809
+ const shortHex = v.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])?$/);
810
+ if (shortHex) {
811
+ const [, r, g, b, a] = shortHex;
812
+ v = a ? `#${r}${r}${g}${g}${b}${b}${a}${a}` : `#${r}${r}${g}${g}${b}${b}`;
813
+ }
814
+ v = v.replace(/(?<![0-9])\.(\d)/g, "0.$1");
815
+ return v;
816
+ }
817
+ const STYLE_BLOCK_RE = /<style[^>]*>([\s\S]*?)<\/style>/g;
818
+ const CSS_PROPERTY_RE = /^\s*([\w-]+)\s*:\s*(.+?)\s*;?\s*$/;
819
+ /**
820
+ * Scan art file sources for token value matches in `<style>` blocks.
821
+ */
822
+ function scanTokenUsage(artFiles, tokenMap) {
823
+ const valueLookup = /* @__PURE__ */ new Map();
824
+ for (const [tokenPath, token] of Object.entries(tokenMap)) {
825
+ const normalized = normalizeTokenValue(token.$resolvedValue ?? token.value);
826
+ if (!normalized) continue;
827
+ const existing = valueLookup.get(normalized);
828
+ if (existing) existing.push(tokenPath);
829
+ else valueLookup.set(normalized, [tokenPath]);
830
+ const tailwindVariable = token.attributes?.tailwindVariable;
831
+ if (typeof tailwindVariable === "string") {
832
+ const normalizedVariable = normalizeTokenValue(`var(${tailwindVariable})`);
833
+ const variableMatches = valueLookup.get(normalizedVariable);
834
+ if (variableMatches) variableMatches.push(tokenPath);
835
+ else valueLookup.set(normalizedVariable, [tokenPath]);
836
+ }
837
+ }
838
+ const usageMap = {};
839
+ for (const [artPath, artInfo] of artFiles) {
840
+ let source;
841
+ try {
842
+ source = fs.readFileSync(artPath, "utf-8");
843
+ } catch {
844
+ continue;
845
+ }
846
+ const allLines = source.split("\n");
847
+ const styleRegions = [];
848
+ let match;
849
+ STYLE_BLOCK_RE.lastIndex = 0;
850
+ while ((match = STYLE_BLOCK_RE.exec(source)) !== null) {
851
+ const beforeMatch = source.slice(0, match.index);
852
+ const startTag = source.slice(match.index, match.index + match[0].indexOf(match[1]));
853
+ const startLine = beforeMatch.split("\n").length + startTag.split("\n").length - 1;
854
+ styleRegions.push({
855
+ startLine,
856
+ content: match[1]
857
+ });
858
+ }
859
+ for (const region of styleRegions) {
860
+ const lines = region.content.split("\n");
861
+ for (let i = 0; i < lines.length; i++) {
862
+ const line = lines[i];
863
+ const propMatch = line.match(CSS_PROPERTY_RE);
864
+ if (!propMatch) continue;
865
+ const property = propMatch[1];
866
+ const valueParts = propMatch[2].split(/\s+/);
867
+ for (const part of valueParts) {
868
+ const normalizedPart = normalizeTokenValue(part);
869
+ const matchingTokens = valueLookup.get(normalizedPart);
870
+ if (!matchingTokens) continue;
871
+ const lineNumber = region.startLine + i;
872
+ const lineContent = allLines[lineNumber - 1]?.trim() ?? line.trim();
873
+ for (const tokenPath of matchingTokens) {
874
+ if (!usageMap[tokenPath]) usageMap[tokenPath] = [];
875
+ let entry = usageMap[tokenPath].find((e) => e.artPath === artPath);
876
+ if (!entry) {
877
+ entry = {
878
+ artPath,
879
+ artTitle: artInfo.metadata.title,
880
+ artCategory: artInfo.metadata.category,
881
+ matches: []
882
+ };
883
+ usageMap[tokenPath].push(entry);
884
+ }
885
+ if (!entry.matches.some((m) => m.line === lineNumber && m.property === property)) entry.matches.push({
886
+ line: lineNumber,
887
+ lineContent,
888
+ property
889
+ });
890
+ }
891
+ }
892
+ }
893
+ }
894
+ }
895
+ return usageMap;
896
+ }
897
+ //#endregion
898
+ //#region src/tokens/resolver.ts
899
+ /**
900
+ * Token resolution, CRUD operations, and validation.
901
+ *
902
+ * Handles building flat token maps from categories, resolving reference chains,
903
+ * reading/writing raw token files, and validating semantic references.
904
+ */
905
+ const JSON_TOKEN_EXTENSIONS = new Set([".json", ".tokens.json"]);
906
+ const UNSAFE_TOKEN_PATH_SEGMENTS = new Set([
907
+ "__proto__",
908
+ "prototype",
909
+ "constructor"
910
+ ]);
911
+ function parseTokenPath(dotPath) {
912
+ const parts = dotPath.split(".");
913
+ if (parts.length === 0 || parts.some((part) => part.trim() === "")) throw new Error(`Invalid token path "${dotPath}"`);
914
+ const unsafeSegment = parts.find((part) => UNSAFE_TOKEN_PATH_SEGMENTS.has(part));
915
+ if (unsafeSegment) throw new Error(`Token path segment "${unsafeSegment}" is not allowed`);
916
+ return parts;
917
+ }
918
+ /**
919
+ * Flatten nested categories into a flat map keyed by dot-path.
920
+ */
921
+ function buildTokenMap(categories) {
922
+ return nullRecord(tokenNative().buildDesignTokenMap(categories));
923
+ }
924
+ /**
925
+ * Resolve references in categories, setting $tier, $reference, and $resolvedValue.
926
+ */
927
+ function resolveReferences(categories, _tokenMap) {
928
+ const resolved = tokenNative().resolveDesignTokenReferences(categories);
929
+ categories.splice(0, categories.length, ...normalizeCategories(resolved.categories));
930
+ }
931
+ /**
932
+ * Read raw JSON token file.
933
+ */
934
+ async function readRawTokenFile(tokensPath) {
935
+ if (!isJsonTokenPath(tokensPath)) throw new Error("Token editing is only supported for JSON token files");
936
+ const content = await fs.promises.readFile(tokensPath, "utf-8");
937
+ return JSON.parse(content);
938
+ }
939
+ /**
940
+ * Write raw JSON token file atomically (write tmp, rename).
941
+ */
942
+ async function writeRawTokenFile(tokensPath, data) {
943
+ if (!isJsonTokenPath(tokensPath)) throw new Error("Token editing is only supported for JSON token files");
944
+ const tmpPath = tokensPath + ".tmp";
945
+ await fs.promises.writeFile(tmpPath, JSON.stringify(data, null, 2) + "\n", "utf-8");
946
+ await fs.promises.rename(tmpPath, tokensPath);
947
+ }
948
+ function isJsonTokenPath(tokensPath) {
949
+ return JSON_TOKEN_EXTENSIONS.has(path.extname(tokensPath)) || tokensPath.endsWith(".tokens.json");
950
+ }
951
+ /**
952
+ * Set a token at a dot-separated path in the raw JSON structure.
953
+ */
954
+ function setTokenAtPath(data, dotPath, token) {
955
+ const parts = parseTokenPath(dotPath);
956
+ let current = data;
957
+ for (let i = 0; i < parts.length - 1; i++) {
958
+ const key = parts[i];
959
+ if (typeof current[key] !== "object" || current[key] === null) current[key] = {};
960
+ current = current[key];
961
+ }
962
+ const leafKey = parts[parts.length - 1];
963
+ const raw = { value: token.value };
964
+ if (token.type) raw.type = token.type;
965
+ if (token.description) raw.description = token.description;
966
+ if (token.$tier) raw.$tier = token.$tier;
967
+ if (token.$reference) raw.$reference = token.$reference;
968
+ if (token.attributes) raw.attributes = token.attributes;
969
+ current[leafKey] = raw;
970
+ }
971
+ /**
972
+ * Delete a token at a dot-separated path, cleaning empty parents.
973
+ */
974
+ function deleteTokenAtPath(data, dotPath) {
975
+ const parts = parseTokenPath(dotPath);
976
+ const parents = [];
977
+ let current = data;
978
+ for (let i = 0; i < parts.length - 1; i++) {
979
+ const key = parts[i];
980
+ if (typeof current[key] !== "object" || current[key] === null) return false;
981
+ parents.push({
982
+ obj: current,
983
+ key
984
+ });
985
+ current = current[key];
986
+ }
987
+ const leafKey = parts[parts.length - 1];
988
+ if (!(leafKey in current)) return false;
989
+ delete current[leafKey];
990
+ for (let i = parents.length - 1; i >= 0; i--) {
991
+ const { obj, key } = parents[i];
992
+ const child = obj[key];
993
+ if (Object.keys(child).length === 0) delete obj[key];
994
+ else break;
995
+ }
996
+ return true;
997
+ }
998
+ /**
999
+ * Validate that a semantic reference points to an existing token and has no cycles.
1000
+ */
1001
+ function validateSemanticReference(tokenMap, reference, selfPath) {
1002
+ return tokenNative().validateDesignTokenReference(tokenMap, reference, selfPath);
1003
+ }
1004
+ /**
1005
+ * Find all tokens that reference the given path.
1006
+ */
1007
+ function findDependentTokens(tokenMap, targetPath) {
1008
+ return tokenNative().findDependentDesignTokens(tokenMap, targetPath);
1009
+ }
1010
+ //#endregion
1011
+ //#region src/tokens/generator.ts
1012
+ /**
1013
+ * Token documentation generators for Style Dictionary integration.
1014
+ *
1015
+ * Generates HTML, Markdown, and JSON documentation from parsed token categories,
1016
+ * and provides the main processStyleDictionary orchestrator function.
1017
+ */
1018
+ const SAFE_CSS_COLOR_PATTERN = /^(?:#[0-9a-fA-F]{3,8}|(?:rgb|hsl)a?\(\s*[-+.\d,%\s/]+\)|(?:oklch|oklab|lab|lch)\(\s*[-+.\d,%\s/]+\))$/;
1019
+ const DANGEROUS_PROTOCOL_PATTERN = /\b(javascript|vbscript):/gi;
1020
+ function escapeTokenText(value) {
1021
+ return escapeHtml(value).replace(DANGEROUS_PROTOCOL_PATTERN, "$1&#58;");
1022
+ }
1023
+ function safeCssColor(value, type) {
1024
+ if (typeof value !== "string") return null;
1025
+ const trimmed = value.trim();
1026
+ return (type === "color" || trimmed.startsWith("#") || trimmed.startsWith("rgb") || trimmed.startsWith("hsl")) && SAFE_CSS_COLOR_PATTERN.test(trimmed) ? trimmed : null;
1027
+ }
1028
+ /**
1029
+ * Generate HTML documentation for tokens.
1030
+ */
1031
+ function generateTokensHtml(categories) {
1032
+ const renderToken = (name, token) => {
1033
+ const color = safeCssColor(token.value, token.type);
1034
+ return `
1035
+ <div class="token">
1036
+ <div class="token-preview">
1037
+ ${color ? `<div class="color-swatch" style="background: ${color}"></div>` : ""}
1038
+ </div>
1039
+ <div class="token-info">
1040
+ <div class="token-name">${escapeTokenText(name)}</div>
1041
+ <div class="token-value">${escapeTokenText(String(token.value))}</div>
1042
+ ${token.description ? `<div class="token-description">${escapeTokenText(token.description)}</div>` : ""}
1043
+ </div>
1044
+ </div>
1045
+ `;
1046
+ };
1047
+ const renderCategory = (category, level = 2) => {
1048
+ const heading = `h${Math.min(level, 6)}`;
1049
+ let html = `<${heading}>${escapeTokenText(category.name)}</${heading}>`;
1050
+ html += "<div class=\"tokens-grid\">";
1051
+ for (const [name, token] of Object.entries(category.tokens)) html += renderToken(name, token);
1052
+ html += "</div>";
1053
+ if (category.subcategories) for (const sub of category.subcategories) html += renderCategory(sub, level + 1);
1054
+ return html;
1055
+ };
1056
+ return `<!DOCTYPE html>
1057
+ <html lang="en">
1058
+ <head>
1059
+ <meta charset="UTF-8">
1060
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1061
+ <title>Design Tokens - Musea</title>
1062
+ <style>
1063
+ :root {
1064
+ --musea-bg: #0d0d0d;
1065
+ --musea-bg-secondary: #1a1815;
1066
+ --musea-text: #e6e9f0;
1067
+ --musea-text-muted: #7b8494;
1068
+ --musea-accent: #a34828;
1069
+ --musea-border: #3a3530;
1070
+ }
1071
+ * { box-sizing: border-box; margin: 0; padding: 0; }
1072
+ body {
1073
+ font-family: 'Inter', -apple-system, sans-serif;
1074
+ background: var(--musea-bg);
1075
+ color: var(--musea-text);
1076
+ line-height: 1.6;
1077
+ padding: 2rem;
1078
+ }
1079
+ h1 { margin-bottom: 2rem; color: var(--musea-accent); }
1080
+ h2 { margin: 2rem 0 1rem; padding-bottom: 0.5rem; border-bottom: 1px solid var(--musea-border); }
1081
+ h3, h4, h5, h6 { margin: 1.5rem 0 0.75rem; }
1082
+ .tokens-grid {
1083
+ display: grid;
1084
+ grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
1085
+ gap: 1rem;
1086
+ margin-bottom: 1.5rem;
1087
+ }
1088
+ .token {
1089
+ background: var(--musea-bg-secondary);
1090
+ border: 1px solid var(--musea-border);
1091
+ border-radius: 8px;
1092
+ padding: 1rem;
1093
+ display: flex;
1094
+ gap: 1rem;
1095
+ align-items: center;
1096
+ }
1097
+ .token-preview {
1098
+ flex-shrink: 0;
1099
+ width: 48px;
1100
+ height: 48px;
1101
+ display: flex;
1102
+ align-items: center;
1103
+ justify-content: center;
1104
+ }
1105
+ .color-swatch {
1106
+ width: 48px;
1107
+ height: 48px;
1108
+ border-radius: 8px;
1109
+ border: 1px solid var(--musea-border);
1110
+ }
1111
+ .token-info {
1112
+ flex: 1;
1113
+ min-width: 0;
1114
+ }
1115
+ .token-name {
1116
+ font-weight: 600;
1117
+ font-family: 'JetBrains Mono', monospace;
1118
+ font-size: 0.875rem;
1119
+ }
1120
+ .token-value {
1121
+ color: var(--musea-text-muted);
1122
+ font-family: 'JetBrains Mono', monospace;
1123
+ font-size: 0.75rem;
1124
+ word-break: break-all;
1125
+ }
1126
+ .token-description {
1127
+ color: var(--musea-text-muted);
1128
+ font-size: 0.75rem;
1129
+ margin-top: 0.25rem;
1130
+ }
1131
+ </style>
1132
+ </head>
1133
+ <body>
1134
+ <h1>Design Tokens</h1>
1135
+ ${categories.map((cat) => renderCategory(cat)).join("")}
1136
+ </body>
1137
+ </html>`;
1138
+ }
1139
+ /**
1140
+ * Generate Markdown documentation for tokens.
1141
+ */
1142
+ function generateTokensMarkdown(categories) {
1143
+ return tokenNative().generateDesignTokensMarkdown(categories, (/* @__PURE__ */ new Date()).toISOString());
1144
+ }
1145
+ /**
1146
+ * Style Dictionary plugin for Musea.
1147
+ * Parses tokens and generates documentation in the specified format.
1148
+ */
1149
+ async function processStyleDictionary(config) {
1150
+ const categories = await parseTokens(config.tokensPath);
1151
+ const outputDir = config.outputDir ?? ".vize/tokens";
1152
+ const outputFormat = config.outputFormat ?? "html";
1153
+ await fs.promises.mkdir(outputDir, { recursive: true });
1154
+ let content;
1155
+ let filename;
1156
+ switch (outputFormat) {
1157
+ case "html":
1158
+ content = generateTokensHtml(categories);
1159
+ filename = "tokens.html";
1160
+ break;
1161
+ case "markdown":
1162
+ content = generateTokensMarkdown(categories);
1163
+ filename = "tokens.md";
1164
+ break;
1165
+ default:
1166
+ content = JSON.stringify({ categories }, null, 2);
1167
+ filename = "tokens.json";
1168
+ }
1169
+ const outputPath = path.join(outputDir, filename);
1170
+ await fs.promises.writeFile(outputPath, content, "utf-8");
1171
+ console.log(`[musea] Generated token documentation: ${outputPath}`);
1172
+ return {
1173
+ categories,
1174
+ metadata: {
1175
+ name: path.basename(config.tokensPath),
1176
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString()
1177
+ }
1178
+ };
1179
+ }
1180
+ //#endregion
1181
+ //#region src/tokens/preview.ts
1182
+ function resolveTokenPreview(input) {
1183
+ const reference = resolveReference(input.token, input.tokenMap);
1184
+ const value = input.token.$resolvedValue ?? reference?.value ?? input.token.value;
1185
+ const candidates = buildCandidates(input.tokenPath, input.token, reference);
1186
+ const kind = resolveCustomKind(candidates, reference?.path, input.config?.rules) ?? inferPreviewKind(candidates, value);
1187
+ return {
1188
+ kind: new Set(input.config?.disabledKinds ?? []).has(kind) ? "generic" : kind,
1189
+ value,
1190
+ tokenPath: input.tokenPath,
1191
+ reference
1192
+ };
1193
+ }
1194
+ function resolveReference(token, tokenMap) {
1195
+ if (!token.$reference) return void 0;
1196
+ const referencedToken = tokenMap?.[token.$reference];
1197
+ return {
1198
+ path: token.$reference,
1199
+ token: referencedToken,
1200
+ value: referencedToken ? referencedToken.$resolvedValue ?? referencedToken.value : void 0
1201
+ };
1202
+ }
1203
+ function buildCandidates(tokenPath, token, reference) {
1204
+ const candidates = [{
1205
+ tokenPath,
1206
+ name: pathName(tokenPath),
1207
+ token
1208
+ }];
1209
+ if (reference?.token) candidates.push({
1210
+ tokenPath: reference.path,
1211
+ name: pathName(reference.path),
1212
+ token: reference.token
1213
+ });
1214
+ return candidates;
1215
+ }
1216
+ function resolveCustomKind(candidates, referencePath, rules) {
1217
+ for (const rule of rules ?? []) if (matchesRule(rule, candidates, referencePath)) return rule.kind;
1218
+ }
1219
+ function matchesRule(rule, candidates, referencePath) {
1220
+ const checks = [];
1221
+ if (rule.type !== void 0) checks.push(candidates.some((candidate) => typeMatches(candidate, rule.type)));
1222
+ if (rule.pathIncludes !== void 0) checks.push(candidates.some((candidate) => includesAny(candidate.tokenPath, rule.pathIncludes)));
1223
+ if (rule.nameIncludes !== void 0) checks.push(candidates.some((candidate) => includesAny(candidate.name, rule.nameIncludes)));
1224
+ if (rule.referencePathIncludes !== void 0) checks.push(referencePath !== void 0 && includesAny(referencePath, rule.referencePathIncludes));
1225
+ return checks.length > 0 && checks.every(Boolean);
1226
+ }
1227
+ function inferPreviewKind(candidates, value) {
1228
+ if (hasType(candidates, ["color"]) || isColorValue(value)) return "color";
1229
+ if (hasType(candidates, ["shadow", "box-shadow"]) || hasSignal(candidates, ["shadow", "box-shadow"])) return "shadow";
1230
+ if (hasType(candidates, [
1231
+ "z-index",
1232
+ "zindex",
1233
+ "zIndex"
1234
+ ]) || hasSignal(candidates, [
1235
+ "z-index",
1236
+ "zindex",
1237
+ "stacking-order"
1238
+ ])) return "zIndex";
1239
+ if (hasType(candidates, ["opacity"]) || hasSignal(candidates, ["opacity", "alpha"])) return "opacity";
1240
+ if (hasType(candidates, [
1241
+ "border-radius",
1242
+ "borderradius",
1243
+ "radius"
1244
+ ]) || hasSignal(candidates, [
1245
+ "border-radius",
1246
+ "borderradius",
1247
+ "radius",
1248
+ "round",
1249
+ "rounded"
1250
+ ])) return "radius";
1251
+ if (hasType(candidates, ["letterspacing", "letter-spacing"]) || hasSignal(candidates, [
1252
+ "letter-spacing",
1253
+ "letterspacing",
1254
+ "tracking"
1255
+ ])) return "letterSpacing";
1256
+ if (hasType(candidates, ["spacing", "space"]) || hasSignal(candidates, [
1257
+ "spacing",
1258
+ "spasing",
1259
+ "space",
1260
+ "gap",
1261
+ "padding",
1262
+ "margin",
1263
+ "inset"
1264
+ ])) return "spacing";
1265
+ if (hasSignal(candidates, [
1266
+ "font-size",
1267
+ "fontsize",
1268
+ "text-size"
1269
+ ])) return "fontSize";
1270
+ if (hasType(candidates, ["fontweight", "font-weight"]) || hasSignal(candidates, [
1271
+ "font-weight",
1272
+ "fontweight",
1273
+ "weight"
1274
+ ])) return "fontWeight";
1275
+ if (hasType(candidates, ["lineheight", "line-height"]) || hasSignal(candidates, ["line-height", "lineheight"])) return "lineHeight";
1276
+ return "generic";
1277
+ }
1278
+ function hasType(candidates, terms) {
1279
+ return candidates.some((candidate) => typeMatches(candidate, terms));
1280
+ }
1281
+ function hasSignal(candidates, terms) {
1282
+ return candidates.some((candidate) => includesAny(candidate.tokenPath, terms) || includesAny(candidate.name, terms) || candidate.token.type !== void 0 && includesAny(candidate.token.type, terms));
1283
+ }
1284
+ function typeMatches(candidate, expected) {
1285
+ if (!candidate.token.type) return false;
1286
+ return toArray(expected).some((term) => normalize(candidate.token.type) === normalize(term));
1287
+ }
1288
+ function includesAny(value, expected) {
1289
+ const normalizedValue = normalize(value);
1290
+ const compactValue = compact(normalizedValue);
1291
+ return toArray(expected).some((term) => {
1292
+ const normalizedTerm = normalize(term);
1293
+ return normalizedValue.includes(normalizedTerm) || compactValue.includes(compact(normalizedTerm));
1294
+ });
1295
+ }
1296
+ function isColorValue(value) {
1297
+ if (typeof value !== "string") return false;
1298
+ return /^(#|rgb\(|rgba\(|hsl\(|hsla\(|oklch\(|oklab\(|lab\(|lch\(|color\()/i.test(value.trim());
1299
+ }
1300
+ function pathName(tokenPath) {
1301
+ return tokenPath.split(".").at(-1) ?? tokenPath;
1302
+ }
1303
+ function normalize(value) {
1304
+ return value.trim().toLowerCase().replace(/[_\s]+/g, "-");
1305
+ }
1306
+ function compact(value) {
1307
+ return value.replace(/[-.]/g, "");
1308
+ }
1309
+ function toArray(value) {
1310
+ return Array.isArray(value) ? value : [value];
1311
+ }
1312
+ //#endregion
1313
+ //#region src/api-tokens.ts
1314
+ function resolveTokensPath(ctx) {
1315
+ const allowedRoots = [ctx.config.root, ...ctx.scanRoots];
1316
+ if (ctx.projectRoot) allowedRoots.push(ctx.projectRoot);
1317
+ return resolveInsideAny(allowedRoots, ctx.tokensPath, "tokensPath");
1318
+ }
1319
+ function sendTokenMutationError(e, sendError) {
1320
+ if (e instanceof HttpError) {
1321
+ sendError(e.message, e.status);
1322
+ return;
1323
+ }
1324
+ if (e instanceof Error && /(token path|token editing)/i.test(e.message)) {
1325
+ sendError(e.message, 400);
1326
+ return;
1327
+ }
1328
+ sendError(e instanceof Error ? e.message : String(e));
1329
+ }
1330
+ /** GET /api/tokens/usage */
1331
+ async function handleTokensUsage(ctx, sendJson) {
1332
+ if (!ctx.tokensPath) {
1333
+ sendJson({});
1334
+ return;
1335
+ }
1336
+ try {
1337
+ const categories = await parseTokens(resolveTokensPath(ctx));
1338
+ resolveReferences(categories, buildTokenMap(categories));
1339
+ const resolvedTokenMap = buildTokenMap(categories);
1340
+ sendJson(scanTokenUsage(ctx.artFiles, resolvedTokenMap));
1341
+ } catch (e) {
1342
+ console.error("[musea] Failed to scan token usage:", e);
1343
+ sendJson({});
1344
+ }
1345
+ }
1346
+ /** GET /api/tokens */
1347
+ async function handleTokensGet(ctx, sendJson) {
1348
+ if (!ctx.tokensPath) {
1349
+ sendJson({
1350
+ categories: [],
1351
+ tokenMap: {},
1352
+ meta: {
1353
+ filePath: "",
1354
+ tokenCount: 0,
1355
+ primitiveCount: 0,
1356
+ semanticCount: 0
1357
+ }
1358
+ });
1359
+ return;
1360
+ }
1361
+ try {
1362
+ const absoluteTokensPath = resolveTokensPath(ctx);
1363
+ const categories = await parseTokens(absoluteTokensPath);
1364
+ resolveReferences(categories, buildTokenMap(categories));
1365
+ const resolvedTokenMap = buildTokenMap(categories);
1366
+ let primitiveCount = 0;
1367
+ let semanticCount = 0;
1368
+ for (const token of Object.values(resolvedTokenMap)) if (token.$tier === "semantic") semanticCount++;
1369
+ else primitiveCount++;
1370
+ sendJson({
1371
+ categories,
1372
+ tokenMap: resolvedTokenMap,
1373
+ meta: {
1374
+ filePath: absoluteTokensPath,
1375
+ tokenCount: Object.keys(resolvedTokenMap).length,
1376
+ primitiveCount,
1377
+ semanticCount
1378
+ }
1379
+ });
1380
+ } catch (e) {
1381
+ console.error("[musea] Failed to load tokens:", e);
1382
+ sendJson({
1383
+ categories: [],
1384
+ tokenMap: {},
1385
+ error: String(e)
1386
+ });
1387
+ }
1388
+ }
1389
+ /** POST /api/tokens (create) */
1390
+ async function handleTokensCreate(ctx, readBody, sendJson, sendError) {
1391
+ if (!ctx.tokensPath) {
1392
+ sendError("No tokens path configured", 400);
1393
+ return;
1394
+ }
1395
+ const body = await readBody();
1396
+ try {
1397
+ const { path: dotPath, token } = parseJsonBody(body);
1398
+ if (!dotPath || !token || token.value === void 0) {
1399
+ sendError("Missing required fields: path, token.value", 400);
1400
+ return;
1401
+ }
1402
+ const absoluteTokensPath = resolveTokensPath(ctx);
1403
+ const rawData = await readRawTokenFile(absoluteTokensPath);
1404
+ const currentMap = buildTokenMap(await parseTokens(absoluteTokensPath));
1405
+ if (currentMap[dotPath]) {
1406
+ sendError(`Token already exists at path "${dotPath}"`, 409);
1407
+ return;
1408
+ }
1409
+ if (token.$reference) {
1410
+ const validation = validateSemanticReference(currentMap, token.$reference, dotPath);
1411
+ if (!validation.valid) {
1412
+ sendError(validation.error, 400);
1413
+ return;
1414
+ }
1415
+ token.value = `{${token.$reference}}`;
1416
+ token.$tier = "semantic";
1417
+ }
1418
+ setTokenAtPath(rawData, dotPath, token);
1419
+ await writeRawTokenFile(absoluteTokensPath, rawData);
1420
+ const categories = await parseTokens(absoluteTokensPath);
1421
+ resolveReferences(categories, buildTokenMap(categories));
1422
+ sendJson({
1423
+ categories,
1424
+ tokenMap: buildTokenMap(categories)
1425
+ }, 201);
1426
+ } catch (e) {
1427
+ sendTokenMutationError(e, sendError);
1428
+ }
1429
+ }
1430
+ /** PUT /api/tokens (update) */
1431
+ async function handleTokensUpdate(ctx, readBody, sendJson, sendError) {
1432
+ if (!ctx.tokensPath) {
1433
+ sendError("No tokens path configured", 400);
1434
+ return;
1435
+ }
1436
+ const body = await readBody();
1437
+ try {
1438
+ const { path: dotPath, token } = parseJsonBody(body);
1439
+ if (!dotPath || !token || token.value === void 0) {
1440
+ sendError("Missing required fields: path, token.value", 400);
1441
+ return;
1442
+ }
1443
+ const absoluteTokensPath = resolveTokensPath(ctx);
1444
+ if (token.$reference) {
1445
+ const validation = validateSemanticReference(buildTokenMap(await parseTokens(absoluteTokensPath)), token.$reference, dotPath);
1446
+ if (!validation.valid) {
1447
+ sendError(validation.error, 400);
1448
+ return;
1449
+ }
1450
+ token.value = `{${token.$reference}}`;
1451
+ token.$tier = "semantic";
1452
+ }
1453
+ const rawData = await readRawTokenFile(absoluteTokensPath);
1454
+ setTokenAtPath(rawData, dotPath, token);
1455
+ await writeRawTokenFile(absoluteTokensPath, rawData);
1456
+ const categories = await parseTokens(absoluteTokensPath);
1457
+ resolveReferences(categories, buildTokenMap(categories));
1458
+ sendJson({
1459
+ categories,
1460
+ tokenMap: buildTokenMap(categories)
1461
+ });
1462
+ } catch (e) {
1463
+ sendTokenMutationError(e, sendError);
1464
+ }
1465
+ }
1466
+ /** DELETE /api/tokens */
1467
+ async function handleTokensDelete(ctx, readBody, sendJson, sendError) {
1468
+ if (!ctx.tokensPath) {
1469
+ sendError("No tokens path configured", 400);
1470
+ return;
1471
+ }
1472
+ const body = await readBody();
1473
+ try {
1474
+ const { path: dotPath } = parseJsonBody(body);
1475
+ if (!dotPath) {
1476
+ sendError("Missing required field: path", 400);
1477
+ return;
1478
+ }
1479
+ const absoluteTokensPath = resolveTokensPath(ctx);
1480
+ const dependents = findDependentTokens(buildTokenMap(await parseTokens(absoluteTokensPath)), dotPath);
1481
+ const rawData = await readRawTokenFile(absoluteTokensPath);
1482
+ if (!deleteTokenAtPath(rawData, dotPath)) {
1483
+ sendError(`Token not found at path "${dotPath}"`, 404);
1484
+ return;
1485
+ }
1486
+ await writeRawTokenFile(absoluteTokensPath, rawData);
1487
+ const categories = await parseTokens(absoluteTokensPath);
1488
+ resolveReferences(categories, buildTokenMap(categories));
1489
+ sendJson({
1490
+ categories,
1491
+ tokenMap: buildTokenMap(categories),
1492
+ dependentsWarning: dependents.length > 0 ? dependents : void 0
1493
+ });
1494
+ } catch (e) {
1495
+ sendTokenMutationError(e, sendError);
1496
+ }
1497
+ }
1498
+ //#endregion
1499
+ //#region src/script-component-analysis.ts
1500
+ /** Read a script component's runtime options without executing project code. */
1501
+ function scriptKind(filename) {
1502
+ if (filename.endsWith(".tsx")) return ts.ScriptKind.TSX;
1503
+ if (filename.endsWith(".jsx")) return ts.ScriptKind.JSX;
1504
+ if (filename.endsWith(".js")) return ts.ScriptKind.JS;
1505
+ return ts.ScriptKind.TS;
1506
+ }
1507
+ function unwrap(expression) {
1508
+ while (ts.isParenthesizedExpression(expression) || ts.isAsExpression(expression) || ts.isSatisfiesExpression(expression) || ts.isNonNullExpression(expression)) expression = expression.expression;
1509
+ return expression;
1510
+ }
1511
+ function nameOf(name) {
1512
+ if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) return name.text;
1513
+ if (ts.isComputedPropertyName(name) && ts.isStringLiteral(name.expression)) return name.expression.text;
1514
+ }
1515
+ function variable(sourceFile, name) {
1516
+ for (const statement of sourceFile.statements) {
1517
+ if (!ts.isVariableStatement(statement)) continue;
1518
+ for (const declaration of statement.declarationList.declarations) if (ts.isIdentifier(declaration.name) && declaration.name.text === name) return declaration.initializer;
1519
+ }
1520
+ }
1521
+ function resolved(expression, sourceFile) {
1522
+ expression = unwrap(expression);
1523
+ if (ts.isIdentifier(expression)) {
1524
+ const initializer = variable(sourceFile, expression.text);
1525
+ if (initializer) return unwrap(initializer);
1526
+ }
1527
+ return expression;
1528
+ }
1529
+ function option(object, name, sourceFile) {
1530
+ for (const property of object.properties) {
1531
+ if (ts.isPropertyAssignment(property) && nameOf(property.name) === name) return resolved(property.initializer, sourceFile);
1532
+ if (ts.isShorthandPropertyAssignment(property) && property.name.text === name) {
1533
+ const initializer = variable(sourceFile, name);
1534
+ if (initializer) return resolved(initializer, sourceFile);
1535
+ }
1536
+ }
1537
+ }
1538
+ function componentOptions(sourceFile) {
1539
+ const assignment = sourceFile.statements.find((statement) => ts.isExportAssignment(statement));
1540
+ if (!assignment || assignment.isExportEquals) return void 0;
1541
+ let expression = resolved(assignment.expression, sourceFile);
1542
+ if (ts.isCallExpression(expression)) {
1543
+ const callee = expression.expression;
1544
+ if (!(ts.isIdentifier(callee) && callee.text === "defineComponent" || ts.isPropertyAccessExpression(callee) && callee.name.text === "defineComponent") || !expression.arguments[0]) return void 0;
1545
+ expression = resolved(expression.arguments[0], sourceFile);
1546
+ }
1547
+ return ts.isObjectLiteralExpression(expression) ? expression : void 0;
1548
+ }
1549
+ function literal(expression) {
1550
+ expression = unwrap(expression);
1551
+ if (ts.isStringLiteral(expression) || ts.isNoSubstitutionTemplateLiteral(expression)) return expression.text;
1552
+ if (ts.isNumericLiteral(expression)) return Number(expression.text);
1553
+ if (expression.kind === ts.SyntaxKind.TrueKeyword) return true;
1554
+ if (expression.kind === ts.SyntaxKind.FalseKeyword) return false;
1555
+ if (expression.kind === ts.SyntaxKind.NullKeyword) return null;
1556
+ if (ts.isPrefixUnaryExpression(expression) && ts.isNumericLiteral(expression.operand)) {
1557
+ const value = Number(expression.operand.text);
1558
+ if (expression.operator === ts.SyntaxKind.MinusToken) return -value;
1559
+ if (expression.operator === ts.SyntaxKind.PlusToken) return value;
1560
+ }
1561
+ }
1562
+ function propType(expression) {
1563
+ if (!expression) return "unknown";
1564
+ expression = unwrap(expression);
1565
+ if (ts.isArrayLiteralExpression(expression)) return expression.elements.map((element) => propType(element)).join(" | ") || "unknown";
1566
+ switch (ts.isIdentifier(expression) ? expression.text : ts.isPropertyAccessExpression(expression) ? expression.name.text : void 0) {
1567
+ case "String": return "string";
1568
+ case "Number": return "number";
1569
+ case "Boolean": return "boolean";
1570
+ case "Array": return "unknown[]";
1571
+ case "Object": return "Record<string, unknown>";
1572
+ default: return "unknown";
1573
+ }
1574
+ }
1575
+ function analyzeProps(expression, sourceFile) {
1576
+ if (!expression) return [];
1577
+ if (ts.isArrayLiteralExpression(expression)) return expression.elements.flatMap((element) => ts.isStringLiteral(element) ? [{
1578
+ name: element.text,
1579
+ type: "unknown",
1580
+ required: false
1581
+ }] : []);
1582
+ if (!ts.isObjectLiteralExpression(expression)) return [];
1583
+ const props = [];
1584
+ for (const property of expression.properties) {
1585
+ if (!ts.isPropertyAssignment(property)) continue;
1586
+ const name = nameOf(property.name);
1587
+ if (!name) continue;
1588
+ const value = resolved(property.initializer, sourceFile);
1589
+ if (ts.isObjectLiteralExpression(value)) {
1590
+ const type = propType(option(value, "type", sourceFile));
1591
+ const required = option(value, "required", sourceFile)?.kind === ts.SyntaxKind.TrueKeyword;
1592
+ const defaultExpression = option(value, "default", sourceFile);
1593
+ const defaultValue = defaultExpression ? literal(defaultExpression) : void 0;
1594
+ props.push({
1595
+ name,
1596
+ type,
1597
+ required,
1598
+ ...defaultValue !== void 0 ? { default_value: defaultValue } : {}
1599
+ });
1600
+ } else props.push({
1601
+ name,
1602
+ type: propType(value),
1603
+ required: false
1604
+ });
1605
+ }
1606
+ return props;
1607
+ }
1608
+ function analyzeEmits(expression) {
1609
+ if (!expression) return [];
1610
+ if (ts.isArrayLiteralExpression(expression)) return expression.elements.flatMap((element) => ts.isStringLiteral(element) ? [element.text] : []);
1611
+ if (ts.isObjectLiteralExpression(expression)) return expression.properties.flatMap((property) => (ts.isPropertyAssignment(property) || ts.isMethodDeclaration(property)) && nameOf(property.name) ? [nameOf(property.name)] : []);
1612
+ return [];
1613
+ }
1614
+ function analyzeScriptComponent(source, filename) {
1615
+ const sourceFile = ts.createSourceFile(filename, source, ts.ScriptTarget.Latest, true, scriptKind(filename));
1616
+ const options = componentOptions(sourceFile);
1617
+ if (!options) return {
1618
+ props: [],
1619
+ emits: []
1620
+ };
1621
+ return {
1622
+ props: analyzeProps(option(options, "props", sourceFile), sourceFile),
1623
+ emits: analyzeEmits(option(options, "emits", sourceFile))
1624
+ };
1625
+ }
1626
+ //#endregion
1627
+ //#region src/api-routes/handler-palette.ts
1628
+ /**
1629
+ * Palette handler for the Musea gallery API.
1630
+ *
1631
+ * Handles GET /api/arts/:path/palette endpoint.
1632
+ */
1633
+ /** GET /api/arts/:path/palette */
1634
+ async function handleArtPalette(ctx, match, sendJson, sendError) {
1635
+ const artPath = decodeUrlComponent(match[1], "art path");
1636
+ const art = ctx.artFiles.get(artPath);
1637
+ if (!art) {
1638
+ sendError("Art not found", 404);
1639
+ return;
1640
+ }
1641
+ try {
1642
+ const readableArtPath = resolveReadableArtPath(ctx.config.root, ctx.scanRoots, artPath);
1643
+ const source = await fs.promises.readFile(readableArtPath, "utf-8");
1644
+ const binding = loadNative();
1645
+ let palette;
1646
+ if (binding.generateArtPalette) palette = binding.generateArtPalette(source, { filename: readableArtPath });
1647
+ else palette = {
1648
+ title: art.metadata.title,
1649
+ controls: [],
1650
+ groups: [],
1651
+ json: "{}",
1652
+ typescript: ""
1653
+ };
1654
+ palette.componentTagName = resolveArtComponent(art, artPath, art.scriptSetupContent ? parseScriptSetupForArt(art.scriptSetupContent) : null, {
1655
+ root: ctx.config.root,
1656
+ scanRoots: ctx.scanRoots
1657
+ }).componentTagName;
1658
+ const resolvedComponentPath = resolveComponentSourcePath(art, artPath, allowedSourceRoots(ctx.config.root, ctx.scanRoots));
1659
+ if (!resolvedComponentPath) {
1660
+ sendJson(palette);
1661
+ return;
1662
+ }
1663
+ try {
1664
+ const componentSource = await fs.promises.readFile(resolvedComponentPath, "utf-8");
1665
+ const analysis = isVueSourcePath(resolvedComponentPath) ? binding.analyzeSfc ? binding.analyzeSfc(componentSource, { filename: resolvedComponentPath }) : analyzeSfcFallback(componentSource, { filename: resolvedComponentPath }) : analyzeScriptComponent(componentSource, resolvedComponentPath);
1666
+ if (analysis.props.length > 0) mergeSfcPropsIntoPalette(palette, analysis.props);
1667
+ } catch {}
1668
+ sendJson(palette);
1669
+ } catch (e) {
1670
+ if (e instanceof HttpError) {
1671
+ sendError(e.message, e.status);
1672
+ return;
1673
+ }
1674
+ sendError(e instanceof Error ? e.message : String(e));
1675
+ }
1676
+ }
1677
+ function mergeSfcPropsIntoPalette(palette, props) {
1678
+ const controlsByName = /* @__PURE__ */ new Map();
1679
+ for (const control of palette.controls) controlsByName.set(normalizePropName(control.name), control);
1680
+ for (const prop of props) {
1681
+ const control = controlsByName.get(normalizePropName(prop.name));
1682
+ if (control) applyPropMetadata(control, prop);
1683
+ else palette.controls.push(controlFromProp(prop));
1684
+ }
1685
+ palette.json = JSON.stringify({
1686
+ title: palette.title,
1687
+ controls: palette.controls
1688
+ }, null, 2);
1689
+ palette.typescript = generateTypescript(palette);
1690
+ }
1691
+ function applyPropMetadata(control, prop) {
1692
+ const inferred = inferControl(prop.type);
1693
+ control.name = prop.name;
1694
+ control.required = prop.required;
1695
+ if (control.default_value === void 0 && prop.default_value !== void 0) control.default_value = parseDefault(prop.default_value);
1696
+ if (inferred.control !== "text" || control.control === "text") control.control = inferred.control;
1697
+ if (inferred.options.length > 0) control.options = inferred.options;
1698
+ }
1699
+ function controlFromProp(prop) {
1700
+ const inferred = inferControl(prop.type);
1701
+ return {
1702
+ name: prop.name,
1703
+ control: inferred.control,
1704
+ default_value: prop.default_value === void 0 ? void 0 : parseDefault(prop.default_value),
1705
+ description: void 0,
1706
+ required: prop.required,
1707
+ options: inferred.options,
1708
+ range: void 0,
1709
+ group: void 0
1710
+ };
1711
+ }
1712
+ function inferControl(type) {
1713
+ const normalized = type.trim();
1714
+ const options = literalOptions(normalized);
1715
+ if (options.length > 0) return {
1716
+ control: "select",
1717
+ options
1718
+ };
1719
+ if (normalized === "boolean") return {
1720
+ control: "boolean",
1721
+ options: []
1722
+ };
1723
+ if (normalized === "number") return {
1724
+ control: "number",
1725
+ options: []
1726
+ };
1727
+ if (normalized.includes("[]") || normalized.startsWith("Array<")) return {
1728
+ control: "array",
1729
+ options: []
1730
+ };
1731
+ if (normalized.startsWith("{") || normalized.startsWith("Record<")) return {
1732
+ control: "object",
1733
+ options: []
1734
+ };
1735
+ return {
1736
+ control: "text",
1737
+ options: []
1738
+ };
1739
+ }
1740
+ function literalOptions(type) {
1741
+ if (!type.includes("|") || type.includes("=>")) return [];
1742
+ return type.split("|").map((part) => part.trim()).map((part) => {
1743
+ const stringMatch = part.match(/^["']([^"']+)["']$/);
1744
+ if (stringMatch) return stringMatch[1];
1745
+ if (part === "true") return true;
1746
+ if (part === "false") return false;
1747
+ const numberValue = Number(part);
1748
+ return Number.isFinite(numberValue) ? numberValue : void 0;
1749
+ }).filter((value) => value !== void 0).map((value) => ({
1750
+ label: String(value),
1751
+ value
1752
+ }));
1753
+ }
1754
+ function parseDefault(value) {
1755
+ if (typeof value !== "string") return value;
1756
+ if (value === "true") return true;
1757
+ if (value === "false") return false;
1758
+ if (/^-?\d+(?:\.\d+)?$/.test(value)) return Number(value);
1759
+ return value.replace(/^["']|["']$/g, "");
1760
+ }
1761
+ function normalizePropName(name) {
1762
+ return name.replace(/[-_]/g, "").toLowerCase();
1763
+ }
1764
+ function generateTypescript(palette) {
1765
+ const fields = palette.controls.map((control) => {
1766
+ return ` ${/^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u.test(control.name) ? control.name : JSON.stringify(control.name)}${control.required ? "" : "?"}: ${controlTsType(control)};`;
1767
+ }).join("\n");
1768
+ return `export interface ${pascalCase(palette.title)}Props {\n${fields}\n}\n`;
1769
+ }
1770
+ function controlTsType(control) {
1771
+ if (control.control === "boolean") return "boolean";
1772
+ if (control.control === "number" || control.control === "range") return "number";
1773
+ if (control.control === "array") return "unknown[]";
1774
+ if (control.control === "object") return "Record<string, unknown>";
1775
+ if (control.control === "select" && control.options.length > 0) return control.options.map((option) => JSON.stringify(option.value)).join(" | ");
1776
+ return "string";
1777
+ }
1778
+ function pascalCase(value) {
1779
+ return value.split(/[^A-Za-z0-9]+/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
1780
+ }
1781
+ //#endregion
1782
+ //#region src/api-routes/handlers.ts
1783
+ /**
1784
+ * Individual route handler functions for the Musea gallery API.
1785
+ *
1786
+ * Extracted from api-routes.ts to keep file sizes manageable.
1787
+ * These handle GET /api/arts/:path/... sub-routes.
1788
+ */
1789
+ function sendCaughtError(sendError, error) {
1790
+ if (error instanceof HttpError) {
1791
+ sendError(error.message, error.status);
1792
+ return;
1793
+ }
1794
+ sendError(error instanceof Error ? error.message : String(error));
1795
+ }
1796
+ /** GET /api/arts/:path/source */
1797
+ async function handleArtSource(ctx, match, sendJson, sendError) {
1798
+ const artPath = decodeUrlComponent(match[1], "art path");
1799
+ if (!ctx.artFiles.get(artPath)) {
1800
+ sendError("Art not found", 404);
1801
+ return;
1802
+ }
1803
+ try {
1804
+ const readableArtPath = resolveReadableArtPath(ctx.config.root, ctx.scanRoots, artPath);
1805
+ sendJson({
1806
+ source: await fs.promises.readFile(readableArtPath, "utf-8"),
1807
+ path: artPath
1808
+ });
1809
+ } catch (e) {
1810
+ sendCaughtError(sendError, e);
1811
+ }
1812
+ }
1813
+ /** GET /api/arts/:path/analysis */
1814
+ async function handleArtAnalysis(ctx, match, sendJson, sendError) {
1815
+ const artPath = decodeUrlComponent(match[1], "art path");
1816
+ const art = ctx.artFiles.get(artPath);
1817
+ if (!art) {
1818
+ sendError("Art not found", 404);
1819
+ return;
1820
+ }
1821
+ try {
1822
+ const resolvedComponentPath = resolveComponentSourcePath(art, artPath, allowedSourceRoots(ctx.config.root, ctx.scanRoots));
1823
+ if (resolvedComponentPath) {
1824
+ const source = await fs.promises.readFile(resolvedComponentPath, "utf-8");
1825
+ if (isVueSourcePath(resolvedComponentPath)) {
1826
+ const binding = loadNative();
1827
+ sendJson(binding.analyzeSfc ? binding.analyzeSfc(source, { filename: resolvedComponentPath }) : analyzeSfcFallback(source, { filename: resolvedComponentPath }));
1828
+ } else sendJson(analyzeScriptComponent(source, resolvedComponentPath));
1829
+ } else sendJson({
1830
+ props: [],
1831
+ emits: []
1832
+ });
1833
+ } catch (e) {
1834
+ sendCaughtError(sendError, e);
1835
+ }
1836
+ }
1837
+ /** GET /api/arts/:path/docs */
1838
+ async function handleArtDocs(ctx, match, sendJson, sendError) {
1839
+ const artPath = decodeUrlComponent(match[1], "art path");
1840
+ const art = ctx.artFiles.get(artPath);
1841
+ if (!art) {
1842
+ sendError("Art not found", 404);
1843
+ return;
1844
+ }
1845
+ try {
1846
+ const readableArtPath = resolveReadableArtPath(ctx.config.root, ctx.scanRoots, artPath);
1847
+ const source = await fs.promises.readFile(readableArtPath, "utf-8");
1848
+ const binding = loadNative();
1849
+ if (binding.generateArtDoc) {
1850
+ const doc = binding.generateArtDoc(source, { filename: readableArtPath });
1851
+ let markdown = doc.markdown || "";
1852
+ const componentName = art.metadata.title || "Component";
1853
+ markdown = markdown.replace(/<Self(\s|>|\/)/g, `<${componentName}$1`).replace(/<\/Self>/g, `</${componentName}>`);
1854
+ markdown = markdown.replace(/```(\w*)\n([\s\S]*?)```/g, (_match, lang, code) => {
1855
+ const lines = code.split("\n");
1856
+ let minIndent = Infinity;
1857
+ for (const line of lines) if (line.trim()) {
1858
+ const indent = line.match(/^(\s*)/)?.[1].length || 0;
1859
+ minIndent = Math.min(minIndent, indent);
1860
+ }
1861
+ if (minIndent === Infinity) minIndent = 0;
1862
+ let formatted;
1863
+ if (minIndent > 0) formatted = lines.map((line) => line.slice(minIndent)).join("\n");
1864
+ else {
1865
+ let restIndent = Infinity;
1866
+ for (let i = 1; i < lines.length; i++) if (lines[i].trim()) {
1867
+ const indent = lines[i].match(/^(\s*)/)?.[1].length || 0;
1868
+ restIndent = Math.min(restIndent, indent);
1869
+ }
1870
+ if (restIndent === Infinity || restIndent === 0) formatted = lines.join("\n");
1871
+ else formatted = lines.map((line, i) => i === 0 ? line : line.slice(restIndent)).join("\n");
1872
+ }
1873
+ return "```" + lang + "\n" + formatted + "```";
1874
+ });
1875
+ sendJson({
1876
+ ...doc,
1877
+ markdown
1878
+ });
1879
+ } else sendJson({
1880
+ markdown: "",
1881
+ title: art.metadata.title,
1882
+ variant_count: art.variants.length
1883
+ });
1884
+ } catch (e) {
1885
+ sendCaughtError(sendError, e);
1886
+ }
1887
+ }
1888
+ /** GET /api/arts/:path/variants/:name/a11y */
1889
+ //#endregion
1890
+ //#region src/static-data.ts
1891
+ function staticPreviewId(artPath, variantName) {
1892
+ return crypto.createHash("sha256").update(artPath).update("\0").update(variantName).digest("hex").slice(0, 20);
1893
+ }
1894
+ function joinUrlPath(basePath, ...segments) {
1895
+ return `${basePath === "/" ? "" : basePath.replace(/\/+$/, "")}/${segments.map((segment) => segment.replace(/^\/+|\/+$/g, "")).filter(Boolean).join("/")}`;
1896
+ }
1897
+ async function createStaticGalleryPayload(ctx) {
1898
+ const apiCtx = createApiContext(ctx);
1899
+ const arts = sortedArts(ctx.artFiles.values());
1900
+ const previews = Object.create(null);
1901
+ const details = {};
1902
+ const snapshotIdentities = Object.create(null);
1903
+ for (const art of arts) {
1904
+ snapshotIdentities[art.path] = resolveSnapshotIdentity(art.path, ctx.projectRoot ?? ctx.config.root);
1905
+ previews[art.path] = Object.create(null);
1906
+ for (const variant of art.variants) {
1907
+ const id = staticPreviewId(art.path, variant.name);
1908
+ previews[art.path][variant.name] = joinUrlPath(ctx.basePath, "preview", `${id}.html`);
1909
+ }
1910
+ details[art.path] = {
1911
+ source: await captureJson((sendJson, sendError) => {
1912
+ return handleArtSource(apiCtx, artMatch(art.path), sendJson, sendError);
1913
+ }, {
1914
+ source: "",
1915
+ path: art.path
1916
+ }),
1917
+ palette: await captureJson((sendJson, sendError) => {
1918
+ return handleArtPalette(apiCtx, artMatch(art.path), sendJson, sendError);
1919
+ }, emptyPalette(art)),
1920
+ analysis: await captureJson((sendJson, sendError) => {
1921
+ return handleArtAnalysis(apiCtx, artMatch(art.path), sendJson, sendError);
1922
+ }, {
1923
+ props: [],
1924
+ emits: []
1925
+ }),
1926
+ docs: await captureJson((sendJson, sendError) => {
1927
+ return handleArtDocs(apiCtx, artMatch(art.path), sendJson, sendError);
1928
+ }, emptyDocs(art))
1929
+ };
1930
+ }
1931
+ return {
1932
+ arts,
1933
+ snapshotIdentityVersion: 1,
1934
+ snapshotIdentities,
1935
+ previews,
1936
+ details,
1937
+ tokens: await captureJson((sendJson) => handleTokensGet(apiCtx, sendJson), emptyTokens()),
1938
+ tokenUsage: await captureJson((sendJson) => handleTokensUsage(apiCtx, sendJson), {})
1939
+ };
1940
+ }
1941
+ function createApiContext(ctx) {
1942
+ return {
1943
+ config: ctx.config,
1944
+ artFiles: ctx.artFiles,
1945
+ scanRoots: ctx.scanRoots,
1946
+ tokensPath: ctx.tokensPath,
1947
+ projectRoot: ctx.projectRoot,
1948
+ basePath: ctx.basePath,
1949
+ resolvedPreviewCss: ctx.resolvedPreviewCss,
1950
+ resolvedPreviewSetup: ctx.resolvedPreviewSetup,
1951
+ devSessionToken: ctx.devSessionToken,
1952
+ processArtFile: async (filePath) => {
1953
+ await fs.promises.access(filePath);
1954
+ },
1955
+ getDevServerPort: () => 5173
1956
+ };
1957
+ }
1958
+ async function captureJson(run, fallback) {
1959
+ let captured = fallback;
1960
+ const sendJson = (data) => {
1961
+ captured = data;
1962
+ };
1963
+ const sendError = (message, status = 500) => {
1964
+ captured = {
1965
+ error: message,
1966
+ status
1967
+ };
1968
+ };
1969
+ await run(sendJson, sendError);
1970
+ return captured;
1971
+ }
1972
+ function artMatch(artPath) {
1973
+ return ["", encodeURIComponent(artPath)];
1974
+ }
1975
+ function emptyPalette(art) {
1976
+ return {
1977
+ title: art.metadata.title,
1978
+ controls: [],
1979
+ groups: [],
1980
+ json: "{}",
1981
+ typescript: ""
1982
+ };
1983
+ }
1984
+ function emptyDocs(art) {
1985
+ return {
1986
+ markdown: "",
1987
+ title: art.metadata.title,
1988
+ variant_count: art.variants.length
1989
+ };
1990
+ }
1991
+ function emptyTokens() {
1992
+ return {
1993
+ categories: [],
1994
+ tokenMap: {},
1995
+ meta: {
1996
+ filePath: "",
1997
+ tokenCount: 0,
1998
+ primitiveCount: 0,
1999
+ semanticCount: 0
2000
+ }
2001
+ };
2002
+ }
2003
+ //#endregion
2004
+ //#region src/static-base.ts
2005
+ const TEXT_GALLERY_ASSET_EXT = /\.(?:css|html|js|map|mjs)$/u;
2006
+ function rewriteGalleryBase(source, basePath) {
2007
+ return source.replaceAll("/__musea__/", `${basePath.replace(/\/?$/, "/")}`);
2008
+ }
2009
+ function rewriteGalleryTextAssetBase(source, relativePath, basePath) {
2010
+ if (!TEXT_GALLERY_ASSET_EXT.test(relativePath)) return source;
2011
+ return rewriteGalleryBase(Buffer.from(source).toString("utf-8"), basePath);
2012
+ }
2013
+ function publicBasePathFromViteBase(viteBase, basePath) {
2014
+ return viteBase && viteBase !== "/" && viteBase !== "./" ? joinUrlPath(viteBase, basePath) : basePath;
2015
+ }
2016
+ //#endregion
2017
+ //#region src/art-style.ts
2018
+ function artScopeAttribute(filePath) {
2019
+ return `data-v-${createHash("sha256").update(filePath).digest("hex").slice(0, 8)}`;
2020
+ }
2021
+ function stampScopeAttribute(template, scopeAttr) {
2022
+ return template.replace(/<([A-Za-z][\w:.-]*)([^<>]*?)>/g, (match, tag, rest) => {
2023
+ if (rest.includes(scopeAttr)) return match;
2024
+ const selfClosing = /\/\s*$/.test(rest);
2025
+ const attrs = selfClosing ? rest.replace(/\/\s*$/, "").trimEnd() : rest.trimEnd();
2026
+ return `<${tag}${`${attrs.length > 0 && !attrs.startsWith(" ") && !attrs.startsWith("\n") ? " " : ""}${attrs}`.trimEnd()} ${scopeAttr}${selfClosing ? " /" : ""}>`;
2027
+ });
2028
+ }
2029
+ //#endregion
2030
+ //#region src/plugin/art-processing.ts
2031
+ function extractArtTagAttributes(source) {
2032
+ const artTagMatch = source.match(/<art\b([\s\S]*?)>/i);
2033
+ if (!artTagMatch) return {};
2034
+ const attributes = {};
2035
+ for (const match of artTagMatch[1].matchAll(/([^\s=/>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'))?/g)) {
2036
+ const name = match[1];
2037
+ if (!name || name === "/") continue;
2038
+ attributes[name] = match[2] ?? match[3] ?? true;
2039
+ }
2040
+ return attributes;
2041
+ }
2042
+ function parseActionEvents(value) {
2043
+ if (typeof value !== "string") return void 0;
2044
+ const events = value.split(",").map((eventName) => eventName.trim().toLowerCase()).filter(Boolean);
2045
+ return events.length > 0 ? [...new Set(events)] : void 0;
2046
+ }
2047
+ function extractCustomArtMetadata(source) {
2048
+ const attrs = extractArtTagAttributes(source);
2049
+ const actionEvents = new Set(parseActionEvents(attrs["action-events"]) ?? []);
2050
+ const captureMousemove = attrs["capture-mousemove"];
2051
+ if (captureMousemove === true || captureMousemove === "true") actionEvents.add("mousemove");
2052
+ return { actionEvents: actionEvents.size > 0 ? [...actionEvents] : void 0 };
2053
+ }
2054
+ function extractStyleBlocks(source, filePath) {
2055
+ const styles = [];
2056
+ for (const match of source.matchAll(/<style\b([^>]*)>([\s\S]*?)<\/style>/gi)) {
2057
+ const attrs = match[1] ?? "";
2058
+ const content = match[2]?.trim();
2059
+ const lang = attrs.match(/\blang\s*=\s*["']([^"']+)["']/i)?.[1]?.toLowerCase();
2060
+ if (!content) continue;
2061
+ if (lang && lang !== "css") {
2062
+ console.warn(`[musea] ${filePath}: <style lang="${lang}"> is not processed. Art styles are plain CSS.`);
2063
+ continue;
2064
+ }
2065
+ styles.push({
2066
+ content,
2067
+ scoped: /\bscoped\b/i.test(attrs)
2068
+ });
2069
+ }
2070
+ if (!styles.some((style) => style.scoped)) return { blocks: styles.map((style) => style.content) };
2071
+ const scopeAttr = artScopeAttribute(filePath);
2072
+ const scope = loadNative().scopeViteCssForPipeline;
2073
+ return {
2074
+ scopeAttr,
2075
+ blocks: styles.map((style) => style.scoped && scope ? scope(style.content, scopeAttr) : style.content)
2076
+ };
2077
+ }
2078
+ function formatArtProcessingError(root, filePath, error) {
2079
+ const detail = error instanceof Error ? error.message || error.name : error == null ? "unknown error" : stringifyUnknown(error);
2080
+ return `[musea] Failed to process ${path.relative(root, filePath) || filePath}: ${detail}`;
2081
+ }
2082
+ function stringifyUnknown(value) {
2083
+ if (typeof value === "string") return value;
2084
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return value.toString();
2085
+ try {
2086
+ return JSON.stringify(value) ?? "unknown error";
2087
+ } catch {
2088
+ return "unknown error";
2089
+ }
2090
+ }
2091
+ function reportArtStatusWarnings(binding, source, filename, warn = console.warn) {
2092
+ const warnings = binding.parseArtStatusWarnings?.(source, { filename });
2093
+ if (warnings == null) return;
2094
+ for (const warning of warnings) warn(`[musea] ${warning}`);
2095
+ }
2096
+ async function processMuseaArtFile(filePath, ctx) {
2097
+ try {
2098
+ const source = await fs.promises.readFile(filePath, "utf-8");
2099
+ const binding = loadNative();
2100
+ const parsed = binding.parseArt(source, { filename: filePath });
2101
+ reportArtStatusWarnings(binding, source, filePath);
2102
+ const customMetadata = extractCustomArtMetadata(source);
2103
+ if (!parsed.variants || parsed.variants.length === 0) return null;
2104
+ const isInline = !filePath.endsWith(".art.vue");
2105
+ const styles = isInline ? { blocks: [] } : extractStyleBlocks(source, filePath);
2106
+ return {
2107
+ path: filePath,
2108
+ metadata: {
2109
+ title: parsed.metadata.title || (isInline ? path.basename(filePath, ".vue") : ""),
2110
+ description: parsed.metadata.description,
2111
+ component: isInline ? void 0 : parsed.metadata.component,
2112
+ category: parsed.metadata.category,
2113
+ tags: parsed.metadata.tags,
2114
+ status: parsed.metadata.status,
2115
+ order: parsed.metadata.order,
2116
+ actionEvents: customMetadata.actionEvents ?? parsed.metadata.actionEvents
2117
+ },
2118
+ variants: parsed.variants.map((v) => ({
2119
+ name: v.name,
2120
+ template: styles.scopeAttr ? stampScopeAttribute(v.template, styles.scopeAttr) : v.template,
2121
+ isDefault: v.isDefault,
2122
+ skipVrt: v.skipVrt
2123
+ })),
2124
+ hasScriptSetup: isInline ? false : parsed.hasScriptSetup,
2125
+ scriptSetupContent: !isInline && parsed.hasScriptSetup ? extractScriptSetupContent(source) : void 0,
2126
+ scriptSetupIsolated: !isInline && parsed.hasScriptSetup ? extractScriptSetupIsolated(source) : true,
2127
+ hasScript: parsed.hasScript,
2128
+ styleCount: parsed.styleCount,
2129
+ styleBlocks: styles.blocks,
2130
+ isInline,
2131
+ componentPath: isInline ? filePath : void 0
2132
+ };
2133
+ } catch (error) {
2134
+ const message = formatArtProcessingError(ctx.root, filePath, error);
2135
+ if (ctx.command === "build") throw new Error(message);
2136
+ (ctx.onError ?? console.error)(message);
2137
+ return null;
2138
+ }
2139
+ }
2140
+ //#endregion
2141
+ //#region src/plugin/options.ts
2142
+ const MUSEA_OPTIONS_KEY = "__vizeMuseaOptions";
2143
+ function attachMuseaOptions(plugin, options) {
2144
+ Object.defineProperty(plugin, MUSEA_OPTIONS_KEY, {
2145
+ configurable: false,
2146
+ enumerable: false,
2147
+ value: options,
2148
+ writable: false
2149
+ });
2150
+ return plugin;
2151
+ }
2152
+ function readMuseaOptions(plugin) {
2153
+ if (!plugin || typeof plugin !== "object") return void 0;
2154
+ return plugin[MUSEA_OPTIONS_KEY];
2155
+ }
2156
+ //#endregion
2157
+ export { rewriteRelativeImportStatement as A, buildTokenMap as C, sortedArts as D, parseTokens as E, resolveArtComponent as M, variantComponentNames as N, generateArtModule as O, processStyleDictionary as S, scanTokenUsage as T, handleTokensUpdate as _, rewriteGalleryBase as a, generateTokensHtml as b, joinUrlPath as c, handleArtDocs as d, handleArtSource as f, handleTokensGet as g, handleTokensDelete as h, publicBasePathFromViteBase as i, expandSelfTag as j, parseScriptSetupForArt as k, staticPreviewId as l, handleTokensCreate as m, readMuseaOptions as n, rewriteGalleryTextAssetBase as o, handleArtPalette as p, processMuseaArtFile as r, createStaticGalleryPayload as s, attachMuseaOptions as t, handleArtAnalysis as u, handleTokensUsage as v, resolveReferences as w, generateTokensMarkdown as x, resolveTokenPreview as y };
2158
+
2159
+ //# sourceMappingURL=options-DnKPMMPV.mjs.map