@vizejs/vite-plugin-musea 0.782.0 → 0.783.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 (80) hide show
  1. package/README.md +10 -9
  2. package/client.d.ts +79 -2
  3. package/dist/a11y/index.d.mts +1 -1
  4. package/dist/a11y/index.mjs +2 -2
  5. package/dist/{report-identity-dHHBq0Ne.mjs → art-processing-BQ7OYXsq.mjs} +352 -985
  6. package/dist/art-processing-BQ7OYXsq.mjs.map +1 -0
  7. package/dist/autogen/index.mjs +1 -1
  8. package/dist/{autogen-D9K1av3V.mjs → autogen-DQVOrkzB.mjs} +8 -3
  9. package/dist/autogen-DQVOrkzB.mjs.map +1 -0
  10. package/dist/cli/index.d.mts +2 -2
  11. package/dist/cli/index.mjs +52 -7
  12. package/dist/cli/index.mjs.map +1 -1
  13. package/dist/gallery/assets/{MonacoEditor-TAa2JDXq.js → MonacoEditor-0o-tEf_d.js} +2 -2
  14. package/dist/gallery/assets/{cssMode-HbYMEqla.js → cssMode-CTeGZPsJ.js} +1 -1
  15. package/dist/gallery/assets/{editor.api-BnAmILmn.js → editor.api-By71ZNNJ.js} +1 -1
  16. package/dist/gallery/assets/{freemarker2-CUxx3K6C.js → freemarker2-PodIPOLZ.js} +1 -1
  17. package/dist/gallery/assets/{handlebars-D-tFxs03.js → handlebars-CxH85JIs.js} +1 -1
  18. package/dist/gallery/assets/{html-BvCZbWop.js → html-CLgd1G74.js} +1 -1
  19. package/dist/gallery/assets/{htmlMode-CtpLmhU0.js → htmlMode-CSxazmZ_.js} +1 -1
  20. package/dist/gallery/assets/{index-9Jbnkznu.js → index-CrdkHjj1.js} +28 -28
  21. package/dist/gallery/assets/index-DjzvBel3.css +1 -0
  22. package/dist/gallery/assets/{javascript-5Q8XUioJ.js → javascript-nMYU-ClU.js} +1 -1
  23. package/dist/gallery/assets/{jsonMode-meopLbOo.js → jsonMode-CR3wuGKP.js} +1 -1
  24. package/dist/gallery/assets/{liquid-XBHPlM5o.js → liquid-D0UrqjBJ.js} +1 -1
  25. package/dist/gallery/assets/{lspLanguageFeatures-uQPmNYRO.js → lspLanguageFeatures-Dd1uggns.js} +1 -1
  26. package/dist/gallery/assets/{mdx-DPlyNjoV.js → mdx-BL8lD8I3.js} +1 -1
  27. package/dist/gallery/assets/{python-BJGVh1ia.js → python-Ctx797mC.js} +1 -1
  28. package/dist/gallery/assets/{razor-tl_w-IGC.js → razor-Ba3xTj_L.js} +1 -1
  29. package/dist/gallery/assets/{register-B1Z_0Wj1.js → register-DS0poJDf.js} +2 -2
  30. package/dist/gallery/assets/{toggleHighContrast-CwaJX3-m.js → toggleHighContrast-Dd6XSMyb.js} +1 -1
  31. package/dist/gallery/assets/{tsMode-BTkaxugD.js → tsMode-BT2twH2C.js} +1 -1
  32. package/dist/gallery/assets/{typescript-BfDavZMU.js → typescript-C5pkGWfc.js} +1 -1
  33. package/dist/gallery/assets/{vs-yheCI45x.js → vs-BKqjpgpj.js} +3 -3
  34. package/dist/gallery/assets/{workers-CxTFpB1G.js → workers-Dw3ZZZ2Q.js} +1 -1
  35. package/dist/gallery/assets/{xml-BwtrP1DO.js → xml-DKxYmeMe.js} +1 -1
  36. package/dist/gallery/assets/{yaml-jwkm0mVv.js → yaml-BLz7QoYz.js} +1 -1
  37. package/dist/gallery/index.html +2 -2
  38. package/dist/{gallery-DNxzJA4V.mjs → gallery-CLjSInLi.mjs} +2 -2
  39. package/dist/{gallery-DNxzJA4V.mjs.map → gallery-CLjSInLi.mjs.map} +1 -1
  40. package/dist/{html-BW9Z7gL3.mjs → html-N6TFwUQB.mjs} +11 -4
  41. package/dist/html-N6TFwUQB.mjs.map +1 -0
  42. package/dist/{index-ELy0IbiZ.d.mts → index-DBZ6pHEP.d.mts} +3 -3
  43. package/dist/{index-ELy0IbiZ.d.mts.map → index-DBZ6pHEP.d.mts.map} +1 -1
  44. package/dist/{index-BemK8p6d.d.mts → index-s1-tayec.d.mts} +16 -3
  45. package/dist/{index-BemK8p6d.d.mts.map → index-s1-tayec.d.mts.map} +1 -1
  46. package/dist/index.d.mts +3 -3
  47. package/dist/index.mjs +6 -6
  48. package/dist/{module-BaxIBS_8.mjs → module-CUszeEyD.mjs} +2 -2
  49. package/dist/{module-BaxIBS_8.mjs.map → module-CUszeEyD.mjs.map} +1 -1
  50. package/dist/native-loader-T2dk9Xrf.mjs +304 -0
  51. package/dist/native-loader-T2dk9Xrf.mjs.map +1 -0
  52. package/dist/{plugin-D2KEfrj1.mjs → plugin-BhEarB-i.mjs} +301 -21
  53. package/dist/plugin-BhEarB-i.mjs.map +1 -0
  54. package/dist/{report-CHUEZNZA.mjs → report-BuvPnXYn.mjs} +2 -2
  55. package/dist/{report-CHUEZNZA.mjs.map → report-BuvPnXYn.mjs.map} +1 -1
  56. package/dist/{report-ZbXgDiN_.mjs → report-CNk-LzNl.mjs} +2 -2
  57. package/dist/{report-ZbXgDiN_.mjs.map → report-CNk-LzNl.mjs.map} +1 -1
  58. package/dist/report-identity-CvU6XOLJ.mjs +919 -0
  59. package/dist/report-identity-CvU6XOLJ.mjs.map +1 -0
  60. package/dist/{resolver-D8_4jxfT.mjs → resolver-DUipOWtm.mjs} +3 -254
  61. package/dist/resolver-DUipOWtm.mjs.map +1 -0
  62. package/dist/test-runner.d.mts +68 -0
  63. package/dist/test-runner.d.mts.map +1 -0
  64. package/dist/test-runner.mjs +160 -0
  65. package/dist/test-runner.mjs.map +1 -0
  66. package/dist/{vrt-CuAg5Eow.d.mts → vrt-DJwEoyjo.d.mts} +4 -3
  67. package/dist/vrt-DJwEoyjo.d.mts.map +1 -0
  68. package/dist/{vrt-B8j2yfiN.mjs → vrt-KEfbSnWX.mjs} +15 -5
  69. package/dist/vrt-KEfbSnWX.mjs.map +1 -0
  70. package/dist/vrt.d.mts +3 -3
  71. package/dist/vrt.mjs +4 -4
  72. package/package.json +8 -4
  73. package/dist/autogen-D9K1av3V.mjs.map +0 -1
  74. package/dist/gallery/assets/index-CT4hwaEG.css +0 -1
  75. package/dist/html-BW9Z7gL3.mjs.map +0 -1
  76. package/dist/plugin-D2KEfrj1.mjs.map +0 -1
  77. package/dist/report-identity-dHHBq0Ne.mjs.map +0 -1
  78. package/dist/resolver-D8_4jxfT.mjs.map +0 -1
  79. package/dist/vrt-B8j2yfiN.mjs.map +0 -1
  80. package/dist/vrt-CuAg5Eow.d.mts.map +0 -1
@@ -1,10 +1,7 @@
1
- import { a as resolveReferences, c as writeRawTokenFile, f as analyzeSfcFallback, i as readRawTokenFile, l as scanTokenUsage, n as deleteTokenAtPath, o as setTokenAtPath, p as loadNative, r as findDependentTokens, s as validateSemanticReference, t as buildTokenMap, u as parseTokens } from "./resolver-D8_4jxfT.mjs";
2
- import { r as resolveSnapshotIdentity } from "./snapshot-identity-Cm-t65Kl.mjs";
1
+ import { i as parseStaticJsonExpression, n as assertStaticExpression, r as loadNative } from "./native-loader-T2dk9Xrf.mjs";
3
2
  import path from "node:path";
4
3
  import fs from "node:fs";
5
- import crypto, { createHash, randomBytes, timingSafeEqual } from "node:crypto";
6
- import { lstat, readFile, readdir } from "node:fs/promises";
7
- import ts from "typescript";
4
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
8
5
  //#region src/http-error.ts
9
6
  var HttpError = class extends Error {
10
7
  status;
@@ -227,22 +224,6 @@ function getHeader(req, name) {
227
224
  return value;
228
225
  }
229
226
  //#endregion
230
- //#region src/component-source.ts
231
- function allowedSourceRoots(root, scanRoots = []) {
232
- return [...new Set([root, ...scanRoots].map((sourceRoot) => path.resolve(sourceRoot)))];
233
- }
234
- function resolveReadableArtPath(root, scanRoots, artPath) {
235
- return resolveTrustedSourcePath(root, scanRoots, artPath, "art path");
236
- }
237
- function resolveComponentSourcePath(art, artPath, sourceRoots) {
238
- 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;
239
- const [projectRoot, ...extraRoots] = sourceRoots;
240
- if (!componentPath) return null;
241
- const resolved = resolveTrustedSourcePath(projectRoot ?? ".", extraRoots, componentPath, "component path");
242
- assertComponentSourcePath(resolved, "component path");
243
- return resolved;
244
- }
245
- //#endregion
246
227
  //#region src/theme-config.ts
247
228
  /**
248
229
  * Build the theme config object from plugin options for runtime injection.
@@ -456,8 +437,18 @@ function escapeTemplateLiteral(str) {
456
437
  return str.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$");
457
438
  }
458
439
  function emitLegacyVariant(context) {
459
- const { variantComponentName, variantName, template, componentTagName, componentBindingName, scriptSetup, hasSetup, isolatedSetup, setupReturn, importDeclaresName } = context;
460
- const escapedTemplate = escapeTemplateLiteral(template);
440
+ const { variantComponentName, variantName, template, componentTagName, componentBindingName, scriptSetup, hasSetup, isolatedSetup, setupReturn, importDeclaresName, play, props, attrs } = context;
441
+ const playExpression = play ? assertStaticExpression(play, "play") : void 0;
442
+ const isolatedPlay = play ? ` const __museaVariantPlay = (${playExpression});\n if (typeof window !== "undefined") window.__museaPlay = __museaVariantPlay;\n` : "";
443
+ const sharedPlay = play ? ` const { ${scriptSetup?.returnNames.join(", ") ?? ""} } = __museaSharedSetup;\n const __museaVariantPlay = (${playExpression});\n if (typeof window !== "undefined") window.__museaPlay = __museaVariantPlay;\n` : "";
444
+ const hasBindings = Boolean(props || attrs);
445
+ const variantBindings = hasBindings ? ` const __museaVariantBindings = ${serializeScriptValue({
446
+ ...attrs,
447
+ ...props
448
+ })};\n` : "";
449
+ const isolatedReturn = hasBindings ? `Object.assign(${setupReturn}, { __museaVariantBindings })` : setupReturn;
450
+ const sharedReturn = hasBindings ? `{ ...__museaSharedSetup, __museaVariantBindings }` : "__museaSharedSetup";
451
+ const escapedTemplate = escapeTemplateLiteral(injectVariantBindings(template, componentTagName, hasBindings));
461
452
  const fullTemplate = `<div data-variant="${escapeTemplateLiteral(escapeHtml(variantName))}">${escapedTemplate}</div>`;
462
453
  const componentNames = /* @__PURE__ */ new Map();
463
454
  if (componentTagName) componentNames.set(componentTagName, componentBindingName);
@@ -470,7 +461,7 @@ export const ${variantComponentName} = __museaDefineComponent({
470
461
  name: '${variantComponentName}',
471
462
  ${components} setup() {
472
463
  ${scriptSetup.setupBody.join("\n")}
473
- return ${setupReturn};
464
+ ${variantBindings}${isolatedPlay} return ${isolatedReturn};
474
465
  },
475
466
  template: \`${fullTemplate}\`,
476
467
  });
@@ -479,10 +470,19 @@ ${scriptSetup.setupBody.join("\n")}
479
470
  export const ${variantComponentName} = __museaDefineComponent({
480
471
  name: '${variantComponentName}',
481
472
  ${components} setup() {
482
- return __museaSharedSetup;
473
+ ${variantBindings}${sharedPlay} return ${sharedReturn};
483
474
  },
484
475
  template: \`${fullTemplate}\`,
485
476
  });
477
+ `;
478
+ if (play || hasBindings) return `
479
+ export const ${variantComponentName} = {
480
+ name: '${variantComponentName}',
481
+ ${components} setup() {
482
+ ${variantBindings}${isolatedPlay} return ${hasBindings ? "{ __museaVariantBindings }" : "{}"};
483
+ },
484
+ template: \`${fullTemplate}\`,
485
+ };
486
486
  `;
487
487
  return `
488
488
  export const ${variantComponentName} = {
@@ -491,13 +491,34 @@ ${components} template: \`${fullTemplate}\`,
491
491
  };
492
492
  `;
493
493
  }
494
+ function injectVariantBindings(template, componentTagName, hasBindings) {
495
+ if (!componentTagName || !hasBindings) return template;
496
+ const escaped = componentTagName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
497
+ return template.replace(new RegExp(`<${escaped}(?=[\\s/>])`), `<${componentTagName} v-bind="__museaVariantBindings"`);
498
+ }
499
+ //#endregion
500
+ //#region src/component-source.ts
501
+ function allowedSourceRoots(root, scanRoots = []) {
502
+ return [...new Set([root, ...scanRoots].map((sourceRoot) => path.resolve(sourceRoot)))];
503
+ }
504
+ function resolveReadableArtPath(root, scanRoots, artPath) {
505
+ return resolveTrustedSourcePath(root, scanRoots, artPath, "art path");
506
+ }
507
+ function resolveComponentSourcePath(art, artPath, sourceRoots) {
508
+ 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;
509
+ const [projectRoot, ...extraRoots] = sourceRoots;
510
+ if (!componentPath) return null;
511
+ const resolved = resolveTrustedSourcePath(projectRoot ?? ".", extraRoots, componentPath, "component path");
512
+ assertComponentSourcePath(resolved, "component path");
513
+ return resolved;
514
+ }
494
515
  //#endregion
495
516
  //#region src/art-component.ts
496
517
  /**
497
518
  * Resolve which component an art file demonstrates, and under what tag.
498
519
  *
499
520
  * Shared by the art module and by the per-variant SFC compiler (#3857) so both
500
- * agree on the import path, the tag `<Self>` expands to, and the binding name.
521
+ * agree on the inferred target import and its template binding name.
501
522
  * The parsed `<script setup>` is passed in rather than parsed here, so this
502
523
  * module does not have to import back from `art-module.ts`.
503
524
  */
@@ -510,18 +531,20 @@ function componentNameFromSource(source) {
510
531
  }
511
532
  function resolveArtComponent(art, filePath, scriptSetup, options = {}) {
512
533
  let componentImportPath;
534
+ let componentSource;
513
535
  let componentTagName;
514
536
  let componentBindingName = "__MuseaComponent";
515
537
  const defineArtComponentName = scriptSetup?.defineArtComponentName;
516
538
  const defineArtComponentSource = scriptSetup?.defineArtComponentSource;
539
+ const componentImportStatement = scriptSetup?.defineArtComponentImport;
517
540
  if (art.isInline && art.componentPath) {
518
541
  componentImportPath = options.root ? resolveComponentSourcePath(art, filePath, allowedSourceRoots(options.root, options.scanRoots ?? [])) ?? void 0 : art.componentPath;
519
- componentTagName = "MuseaComponent";
542
+ componentTagName = componentNameFromSource(art.componentPath);
520
543
  componentBindingName = componentTagName;
521
- } else if (defineArtComponentSource || art.metadata.component) {
522
- const componentSource = defineArtComponentSource ?? art.metadata.component;
544
+ } else if (defineArtComponentName && defineArtComponentSource) {
545
+ componentSource = defineArtComponentSource;
523
546
  if (componentSource) {
524
- const sourceArt = componentSource === art.metadata.component ? art : {
547
+ const sourceArt = {
525
548
  ...art,
526
549
  metadata: {
527
550
  ...art.metadata,
@@ -530,19 +553,86 @@ function resolveArtComponent(art, filePath, scriptSetup, options = {}) {
530
553
  };
531
554
  componentImportPath = options.root ? resolveComponentSourcePath(sourceArt, filePath, allowedSourceRoots(options.root, options.scanRoots ?? [])) ?? void 0 : path.isAbsolute(componentSource) ? componentSource : path.resolve(path.dirname(filePath), componentSource);
532
555
  }
533
- componentTagName = defineArtComponentName ?? (art.metadata.component ? componentNameFromSource(art.metadata.component) : "MuseaComponent");
556
+ componentTagName = defineArtComponentName;
534
557
  componentBindingName = componentTagName;
558
+ } else {
559
+ const inferred = inferArtComponent(art, scriptSetup?.imports ?? []);
560
+ if (inferred) {
561
+ componentSource = inferred.source;
562
+ const sourceArt = {
563
+ ...art,
564
+ metadata: {
565
+ ...art.metadata,
566
+ component: inferred.source
567
+ }
568
+ };
569
+ componentImportPath = options.root ? resolveComponentSourcePath(sourceArt, filePath, allowedSourceRoots(options.root, options.scanRoots ?? [])) ?? void 0 : path.isAbsolute(inferred.source) ? inferred.source : path.resolve(path.dirname(filePath), inferred.source);
570
+ componentTagName = inferred.localName;
571
+ componentBindingName = inferred.localName;
572
+ return {
573
+ componentImportPath,
574
+ componentSource,
575
+ componentTagName,
576
+ componentBindingName,
577
+ componentImportStatement: inferred.statement
578
+ };
579
+ }
535
580
  }
536
581
  return {
537
582
  componentImportPath,
583
+ componentSource,
538
584
  componentTagName,
539
- componentBindingName
585
+ componentBindingName,
586
+ componentImportStatement
540
587
  };
541
588
  }
542
- /** Expand `<Self>` in a variant template to the resolved component tag. */
543
- function expandSelfTag(template, componentTagName) {
544
- if (!componentTagName) return template;
545
- return template.replace(/<Self(?=[\s/>])/g, `<${componentTagName}`).replace(/<\/Self\s*>/g, `</${componentTagName}>`);
589
+ /** Infer the demonstrated component from an imported tag shared by every variant. */
590
+ function inferArtComponent(art, imports) {
591
+ const imported = imports.flatMap(importedBindings);
592
+ if (imported.length === 0 || art.variants.length === 0) return void 0;
593
+ const tagsByVariant = art.variants.map((variant) => templateTags(variant.template));
594
+ const candidates = imported.filter(({ localName }) => tagsByVariant.every((tags) => tags.has(localName) || tags.has(toKebabComponentName(localName))));
595
+ if (candidates.length === 1) return candidates[0];
596
+ if (candidates.length > 1) throw ambiguousTargetError(candidates);
597
+ const used = imported.filter(({ localName }) => tagsByVariant.some((tags) => tags.has(localName) || tags.has(toKebabComponentName(localName))));
598
+ if (used.length > 1) throw ambiguousTargetError(used);
599
+ return used[0];
600
+ }
601
+ function ambiguousTargetError(candidates) {
602
+ const names = candidates.map(({ localName }) => localName).join(", ");
603
+ return /* @__PURE__ */ new Error(`Musea cannot infer one target component (${names}). Add defineArt(Target) to select it explicitly.`);
604
+ }
605
+ function importedBindings(statement) {
606
+ if (/^\s*import\s+type\b/u.test(statement)) return [];
607
+ const match = statement.replace(/\s+/gu, " ").trim().match(/^import\s+(.+?)\s+from\s+(["'])([^"']+)\2\s*;?$/u);
608
+ if (!match) return [];
609
+ const clause = match[1].trim();
610
+ const source = match[3];
611
+ const names = [];
612
+ const defaultName = clause.match(/^([A-Za-z_$][\w$]*)(?:\s*,|$)/u)?.[1];
613
+ if (defaultName) names.push(defaultName);
614
+ const namespaceName = clause.match(/\*\s+as\s+([A-Za-z_$][\w$]*)/u)?.[1];
615
+ if (namespaceName) names.push(namespaceName);
616
+ const named = clause.match(/\{([\s\S]*?)\}/u)?.[1];
617
+ if (named) for (const part of named.split(",")) {
618
+ const value = part.trim().replace(/^type\s+/u, "");
619
+ if (!value || part.trim().startsWith("type ")) continue;
620
+ const local = value.match(/(?:^|\s+as\s+)([A-Za-z_$][\w$]*)$/u)?.[1];
621
+ if (local) names.push(local);
622
+ }
623
+ return [...new Set(names)].map((localName) => ({
624
+ localName,
625
+ source,
626
+ statement
627
+ }));
628
+ }
629
+ function templateTags(template) {
630
+ const tags = /* @__PURE__ */ new Set();
631
+ for (const match of template.matchAll(/<([A-Za-z_$][\w$.-]*)(?=[\s/>])/gu)) if (match[1]) tags.add(match[1]);
632
+ return tags;
633
+ }
634
+ function toKebabComponentName(name) {
635
+ return name.replace(/([a-z0-9])([A-Z])/gu, "$1-$2").toLowerCase();
546
636
  }
547
637
  //#endregion
548
638
  //#region src/art-style.ts
@@ -709,7 +799,13 @@ function resolveRelativeSpecifier(specifier, artDir) {
709
799
  return path.resolve(artDir, specifier);
710
800
  }
711
801
  function rewriteRelativeImportStatement(statement, artDir) {
712
- 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}`);
802
+ return statement.replace(/\bfrom\s+(?:"([^"]+)"|'([^']+)')/g, (_match, doubleQuoted, singleQuoted) => {
803
+ const quote = doubleQuoted === void 0 ? "'" : "\"";
804
+ return `from ${quote}${resolveRelativeSpecifier(doubleQuoted ?? singleQuoted ?? "", artDir)}${quote}`;
805
+ }).replace(/^(\s*import\s+)(?:"([^"]+)"|'([^']+)')(\s*;?\s*)$/s, (_match, prefix, doubleQuoted, singleQuoted, suffix) => {
806
+ const quote = doubleQuoted === void 0 ? "'" : "\"";
807
+ return `${prefix}${quote}${resolveRelativeSpecifier(doubleQuoted ?? singleQuoted ?? "", artDir)}${quote}${suffix}`;
808
+ });
713
809
  }
714
810
  function countCharBalance(source, openChar, closeChar) {
715
811
  let balance = 0;
@@ -721,7 +817,7 @@ function isCompleteImportStatement(statement) {
721
817
  const trimmed = statement.trim();
722
818
  if (!trimmed.startsWith("import ")) return false;
723
819
  if (countCharBalance(statement, "{", "}") > 0) return false;
724
- return /^import\s+[\s\S]+?\s+from\s+['"][^'"]+['"]\s*;?$/s.test(trimmed) || /^import\s+['"][^'"]+['"]\s*;?$/s.test(trimmed);
820
+ return /^import\s+[\s\S]+?\s+from\s+(?:"[^"]+"|'[^']+')\s*;?$/s.test(trimmed) || /^import\s+(?:"[^"]+"|'[^']+')\s*;?$/s.test(trimmed);
725
821
  }
726
822
  function splitTopLevelCommaList(source) {
727
823
  const parts = [];
@@ -749,7 +845,7 @@ function splitTopLevelCommaList(source) {
749
845
  return parts;
750
846
  }
751
847
  function collectImportedNames(statement, returnNames) {
752
- const fromMatch = statement.replace(/\s+/g, " ").trim().replace(/;$/, "").match(/^import\s+(type\s+)?(.+?)\s+from\s+['"][^'"]+['"]$/);
848
+ const fromMatch = statement.replace(/\s+/g, " ").trim().replace(/;$/, "").match(/^import\s+(type\s+)?(.+?)\s+from\s+(?:"[^"]+"|'[^']+')$/);
753
849
  if (!fromMatch) return;
754
850
  if (fromMatch[1]) return;
755
851
  const specifierParts = splitTopLevelCommaList(fromMatch[2].trim());
@@ -848,11 +944,11 @@ function parseScriptSetupForArt(content) {
848
944
  const returnNames = /* @__PURE__ */ new Set();
849
945
  let currentImport = null;
850
946
  const defineArtComponent = extractDefineArtComponent(content);
851
- let defineArtBalance = 0;
947
+ let artMacroBalance = 0;
852
948
  for (const line of lines) {
853
949
  const trimmed = line.trim();
854
- if (defineArtBalance > 0) {
855
- defineArtBalance += countCharBalance(line, "(", ")");
950
+ if (artMacroBalance > 0) {
951
+ artMacroBalance += countCharBalance(line, "(", ")");
856
952
  continue;
857
953
  }
858
954
  if (currentImport) {
@@ -875,8 +971,8 @@ function parseScriptSetupForArt(content) {
875
971
  }
876
972
  continue;
877
973
  }
878
- if (isDefineArtLine(trimmed)) {
879
- defineArtBalance = Math.max(0, countCharBalance(line, "(", ")"));
974
+ if (isArtMacroLine(trimmed)) {
975
+ artMacroBalance = Math.max(0, countCharBalance(line, "(", ")"));
880
976
  continue;
881
977
  }
882
978
  setupBody.push(line);
@@ -887,52 +983,39 @@ function parseScriptSetupForArt(content) {
887
983
  collectImportedNames(statement, returnNames);
888
984
  }
889
985
  collectTopLevelReturnNames(setupBody, returnNames);
986
+ if (/\bdefinePlay\s*\(/.test(content)) {
987
+ setupBody.unshift("const definePlay = (play) => play;");
988
+ returnNames.delete("definePlay");
989
+ }
890
990
  returnNames.delete("type");
891
991
  if (defineArtComponent.name) returnNames.delete(defineArtComponent.name);
992
+ if (defineArtComponent.legacySource) throw new Error(`defineArt(${JSON.stringify(defineArtComponent.legacySource)}, …) is no longer supported. Import the component and call defineArt(Component, …) instead.`);
993
+ const componentImport = defineArtComponent.name ? imports.find((statement) => importDeclaresName(statement, defineArtComponent.name)) : void 0;
994
+ if (defineArtComponent.name && !componentImport) throw new Error(`defineArt(${defineArtComponent.name}, …) must receive a component imported in the same <script setup>.`);
995
+ const componentSource = componentImport?.replace(/\s+/g, " ").match(/\bfrom\s+(?:"([^"]+)"|'([^']+)')/);
892
996
  return {
893
997
  imports,
894
998
  setupBody,
895
999
  returnNames: [...returnNames],
896
1000
  defineArtComponentName: defineArtComponent.name,
897
- defineArtComponentSource: defineArtComponent.source
1001
+ defineArtComponentSource: componentSource?.[1] ?? componentSource?.[2],
1002
+ defineArtComponentImport: componentImport
898
1003
  };
899
1004
  }
900
1005
  function extractDefineArtComponent(content) {
901
1006
  const sourceMatch = content.match(/\bdefineArt\s*\(\s*(['"])([^'"]+)\1/);
902
- if (sourceMatch) return {
903
- name: componentNameFromSource(sourceMatch[2]),
904
- source: sourceMatch[2]
905
- };
1007
+ if (sourceMatch) return { legacySource: sourceMatch[2] };
906
1008
  return { name: content.match(/\bdefineArt\s*\(\s*([A-Za-z_$][\w$]*)/)?.[1] };
907
1009
  }
908
- function isDefineArtLine(trimmed) {
909
- return /\bdefineArt\s*\(/.test(trimmed);
1010
+ function isArtMacroLine(trimmed) {
1011
+ return /\b(?:defineArt|defineArtMeta)\s*\(/u.test(trimmed);
910
1012
  }
911
1013
  function generateArtModule(art, filePath, options = {}) {
912
- let componentImportPath;
913
- let componentTagName;
914
- let componentBindingName = "__MuseaComponent";
915
1014
  const scriptSetup = art.scriptSetupContent ? parseScriptSetupForArt(art.scriptSetupContent) : null;
916
- const defineArtComponentName = scriptSetup?.defineArtComponentName;
917
- const defineArtComponentSource = scriptSetup?.defineArtComponentSource;
918
- if (art.isInline && art.componentPath) {
919
- componentImportPath = options.root ? resolveComponentSourcePath(art, filePath, allowedSourceRoots(options.root, options.scanRoots ?? [])) ?? void 0 : art.componentPath;
920
- componentTagName = "MuseaComponent";
921
- } else if (defineArtComponentSource || art.metadata.component) {
922
- const componentSource = defineArtComponentSource ?? art.metadata.component;
923
- if (componentSource) {
924
- const sourceArt = componentSource === art.metadata.component ? art : {
925
- ...art,
926
- metadata: {
927
- ...art.metadata,
928
- component: componentSource
929
- }
930
- };
931
- componentImportPath = options.root ? resolveComponentSourcePath(sourceArt, filePath, allowedSourceRoots(options.root, options.scanRoots ?? [])) ?? void 0 : path.isAbsolute(componentSource) ? componentSource : path.resolve(path.dirname(filePath), componentSource);
932
- }
933
- componentTagName = defineArtComponentName ?? (art.metadata.component ? componentNameFromSource(art.metadata.component) : "MuseaComponent");
934
- componentBindingName = componentTagName;
935
- }
1015
+ const { componentImportPath, componentTagName, componentBindingName } = resolveArtComponent(art, filePath, scriptSetup, {
1016
+ root: options.root,
1017
+ scanRoots: options.scanRoots
1018
+ });
936
1019
  const hasSetupBody = scriptSetup?.setupBody.some((line) => line.trim().length > 0) ?? false;
937
1020
  const hasSetup = !!scriptSetup && (hasSetupBody || scriptSetup.returnNames.length > 0);
938
1021
  let code = `
@@ -972,7 +1055,7 @@ ${scriptSetup.setupBody.join("\n")}
972
1055
  const bindings = variantComponentNames(art.variants);
973
1056
  for (const variant of art.variants) {
974
1057
  const variantComponentName = bindings.get(variant.name);
975
- const template = expandSelfTag(variant.template, componentTagName);
1058
+ const template = variant.template;
976
1059
  if (options.vueVersion === 2) {
977
1060
  code += emitLegacyVariant({
978
1061
  variantComponentName,
@@ -984,7 +1067,10 @@ ${scriptSetup.setupBody.join("\n")}
984
1067
  hasSetup,
985
1068
  isolatedSetup,
986
1069
  setupReturn,
987
- importDeclaresName
1070
+ importDeclaresName,
1071
+ play: variant.play,
1072
+ props: variant.props,
1073
+ attrs: variant.attrs
988
1074
  });
989
1075
  continue;
990
1076
  }
@@ -1013,6 +1099,123 @@ function extractArtTagAttributes(source) {
1013
1099
  }
1014
1100
  return attributes;
1015
1101
  }
1102
+ function decodeAttributeValue(value) {
1103
+ return value.replaceAll("&quot;", "\"").replaceAll("&apos;", "'").replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
1104
+ }
1105
+ /** Read runtime-only variant attributes that older native bindings do not expose. */
1106
+ function extractVariantRuntimeOptions(source) {
1107
+ const variants = [];
1108
+ const tagPattern = /<variant\b((?:[^>"']|"[^"]*"|'[^']*')*)>/gi;
1109
+ const attrPattern = /([^\s=/>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
1110
+ for (const tag of source.matchAll(tagPattern)) {
1111
+ const attrs = {};
1112
+ for (const match of (tag[1] ?? "").matchAll(attrPattern)) {
1113
+ const name = match[1];
1114
+ if (!name || name === "/") continue;
1115
+ attrs[name] = match[2] ?? match[3] ?? match[4] ?? true;
1116
+ }
1117
+ const option = {};
1118
+ if (typeof attrs.name === "string") option.name = decodeAttributeValue(attrs.name);
1119
+ const play = attrs[":play"] ?? attrs.play;
1120
+ if (typeof play === "string") option.play = decodeAttributeValue(play).trim();
1121
+ const props = readVariantObject(attrs, "props");
1122
+ const variantAttrs = readVariantObject(attrs, "attrs");
1123
+ if (props) option.props = props;
1124
+ if (variantAttrs) option.attrs = variantAttrs;
1125
+ if (typeof attrs.args === "string") try {
1126
+ const parsed = JSON.parse(decodeAttributeValue(attrs.args));
1127
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) option.args = parsed;
1128
+ } catch {}
1129
+ if (typeof attrs[":args"] === "string") {
1130
+ const parsed = parseStaticJsonExpression(decodeAttributeValue(attrs[":args"]));
1131
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) option.args = parsed;
1132
+ }
1133
+ if (typeof attrs.viewport === "string") option.viewport = parseVariantViewport(decodeAttributeValue(attrs.viewport));
1134
+ variants.push(option);
1135
+ }
1136
+ return variants;
1137
+ }
1138
+ function readVariantObject(attrs, name) {
1139
+ const bound = attrs[`:${name}`];
1140
+ if (typeof bound === "string") {
1141
+ const parsed = parseStaticJsonExpression(decodeAttributeValue(bound));
1142
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
1143
+ throw new Error(`Musea variant :${name} must be a statically serializable object literal.`);
1144
+ }
1145
+ const literal = attrs[name];
1146
+ if (typeof literal !== "string") return void 0;
1147
+ try {
1148
+ const parsed = JSON.parse(decodeAttributeValue(literal));
1149
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
1150
+ throw new Error("not an object");
1151
+ } catch {
1152
+ throw new Error(`Musea variant ${name} must be a JSON object.`);
1153
+ }
1154
+ }
1155
+ const FALLTHROUGH_ATTRIBUTES = new Set([
1156
+ "class",
1157
+ "id",
1158
+ "role",
1159
+ "style",
1160
+ "tabindex"
1161
+ ]);
1162
+ /** Extract statically serializable inputs from one authored target instance. */
1163
+ function extractTargetInputs(template, componentName) {
1164
+ if (!componentName) return {};
1165
+ const escaped = [componentName, componentName.replace(/([a-z0-9])([A-Z])/gu, "$1-$2").toLowerCase()].map((name) => name.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")).join("|");
1166
+ const matches = [...template.matchAll(new RegExp(`<(?:${escaped})(?=\\s|/?>)((?:[^>"']|"[^"]*"|'[^']*')*)/?>`, "gu"))];
1167
+ if (matches.length !== 1) return {};
1168
+ const props = {};
1169
+ const attrs = {};
1170
+ const attributes = matches[0]?.[1] ?? "";
1171
+ for (const match of attributes.matchAll(/([^\s=/>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/gu)) {
1172
+ const rawName = match[1];
1173
+ if (!rawName || rawName === "/" || rawName.startsWith("@") || rawName.startsWith("#")) continue;
1174
+ if (/^v-(?:if|else|else-if|for|show|model|slot|on)(?::|$)/u.test(rawName)) continue;
1175
+ const isBound = rawName.startsWith(":") || rawName.startsWith("v-bind:");
1176
+ const name = rawName.replace(/^:/u, "").replace(/^v-bind:/u, "");
1177
+ if (!name || name === "key" || name === "ref" || name === "is" || name === "v-bind") continue;
1178
+ const rawValue = decodeAttributeValue(match[2] ?? match[3] ?? match[4] ?? "");
1179
+ let value = rawValue || true;
1180
+ if (isBound) {
1181
+ try {
1182
+ value = parseStaticJsonExpression(rawValue);
1183
+ } catch {
1184
+ continue;
1185
+ }
1186
+ if (value === void 0) continue;
1187
+ }
1188
+ const normalized = name.replace(/-([a-z])/gu, (_whole, letter) => letter.toUpperCase());
1189
+ const lower = name.toLowerCase();
1190
+ const isAttribute = lower.startsWith("aria-") || lower.startsWith("data-") || FALLTHROUGH_ATTRIBUTES.has(lower);
1191
+ (isAttribute ? attrs : props)[isAttribute ? name : normalized] = value;
1192
+ }
1193
+ return {
1194
+ ...Object.keys(props).length > 0 ? { props } : {},
1195
+ ...Object.keys(attrs).length > 0 ? { attrs } : {}
1196
+ };
1197
+ }
1198
+ function parseVariantViewport(value) {
1199
+ try {
1200
+ if (value.startsWith("{")) {
1201
+ const parsed = JSON.parse(value);
1202
+ if (typeof parsed.width === "number" && typeof parsed.height === "number") return {
1203
+ width: parsed.width,
1204
+ height: parsed.height,
1205
+ ...typeof parsed.deviceScaleFactor === "number" ? { deviceScaleFactor: parsed.deviceScaleFactor } : {}
1206
+ };
1207
+ }
1208
+ } catch {
1209
+ return;
1210
+ }
1211
+ const match = value.match(/^(\d+)x(\d+)(?:@(\d+(?:\.\d+)?))?$/);
1212
+ if (!match) return void 0;
1213
+ return {
1214
+ width: Number(match[1]),
1215
+ height: Number(match[2]),
1216
+ ...match[3] ? { deviceScaleFactor: Number(match[3]) } : {}
1217
+ };
1218
+ }
1016
1219
  function parseActionEvents(value) {
1017
1220
  if (typeof value !== "string") return void 0;
1018
1221
  const events = value.split(",").map((eventName) => eventName.trim().toLowerCase()).filter(Boolean);
@@ -1025,6 +1228,17 @@ function extractCustomArtMetadata(source) {
1025
1228
  if (captureMousemove === true || captureMousemove === "true") actionEvents.add("mousemove");
1026
1229
  return { actionEvents: actionEvents.size > 0 ? [...actionEvents] : void 0 };
1027
1230
  }
1231
+ function sourceWithOptionalArtTitle(source) {
1232
+ const match = source.match(/<art\b((?:[^>"']|"[^"]*"|'[^']*')*)>/iu);
1233
+ if (!match || /\btitle\s*=/iu.test(match[1] ?? "")) return source;
1234
+ return source.replace(/<art\b/iu, "<art title=\"\"");
1235
+ }
1236
+ function extractDefineArtMeta(source) {
1237
+ const match = source.match(/\bdefineArtMeta\s*\(\s*(\{[\s\S]*?\})\s*\)/u);
1238
+ if (!match?.[1]) return {};
1239
+ const value = parseStaticJsonExpression(match[1]);
1240
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
1241
+ }
1028
1242
  function extractStyleBlocks(source, filePath) {
1029
1243
  const styles = [];
1030
1244
  for (const match of source.matchAll(/<style\b((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/style>/gi)) {
@@ -1066,32 +1280,76 @@ async function processMuseaArtFile(filePath, ctx) {
1066
1280
  try {
1067
1281
  const source = await fs.promises.readFile(filePath, "utf-8");
1068
1282
  const binding = loadNative();
1069
- const parsed = binding.parseArt(source, { filename: filePath });
1283
+ const parsed = binding.parseArt(sourceWithOptionalArtTitle(source), { filename: filePath });
1070
1284
  reportArtStatusWarnings(binding, source, filePath);
1071
1285
  const customMetadata = extractCustomArtMetadata(source);
1286
+ const macroMetadata = extractDefineArtMeta(source);
1287
+ const variantOptions = extractVariantRuntimeOptions(source);
1072
1288
  if (!parsed.variants || parsed.variants.length === 0) return null;
1073
1289
  const isInline = !filePath.endsWith(".art.vue");
1074
1290
  const styles = isInline ? { blocks: [] } : extractStyleBlocks(source, filePath);
1075
- return {
1291
+ const scriptSetupContent = !isInline && parsed.hasScriptSetup ? extractScriptSetupContent(source) : void 0;
1292
+ const baseVariants = parsed.variants.map((variant) => ({
1293
+ name: variant.name,
1294
+ template: styles.scopeAttr ? stampScopeAttribute(variant.template, styles.scopeAttr) : variant.template,
1295
+ isDefault: variant.isDefault,
1296
+ skipVrt: variant.skipVrt
1297
+ }));
1298
+ const component = resolveArtComponent({
1076
1299
  path: filePath,
1077
1300
  metadata: {
1078
- title: parsed.metadata.title || (isInline ? path.basename(filePath, ".vue") : ""),
1079
- description: parsed.metadata.description,
1301
+ title: macroMetadata.title ?? parsed.metadata.title,
1302
+ description: macroMetadata.description ?? parsed.metadata.description,
1080
1303
  component: isInline ? void 0 : parsed.metadata.component,
1081
- category: parsed.metadata.category,
1082
- tags: parsed.metadata.tags,
1083
- status: parsed.metadata.status,
1084
- order: parsed.metadata.order,
1085
- actionEvents: customMetadata.actionEvents ?? parsed.metadata.actionEvents
1304
+ category: macroMetadata.category ?? parsed.metadata.category,
1305
+ tags: macroMetadata.tags ?? parsed.metadata.tags,
1306
+ status: macroMetadata.status ?? parsed.metadata.status,
1307
+ order: macroMetadata.order ?? parsed.metadata.order
1308
+ },
1309
+ variants: baseVariants,
1310
+ hasScriptSetup: !isInline && parsed.hasScriptSetup,
1311
+ scriptSetupContent,
1312
+ hasScript: parsed.hasScript,
1313
+ styleCount: parsed.styleCount,
1314
+ isInline,
1315
+ componentPath: isInline ? filePath : void 0
1316
+ }, filePath, scriptSetupContent ? parseScriptSetupForArt(scriptSetupContent) : null, { root: ctx.root });
1317
+ const inferredTitle = component.componentTagName ?? path.basename(filePath).replace(/\.art\.vue$/u, "");
1318
+ return {
1319
+ path: filePath,
1320
+ metadata: {
1321
+ title: macroMetadata.title || parsed.metadata.title || (isInline ? path.basename(filePath, ".vue") : inferredTitle),
1322
+ description: macroMetadata.description ?? parsed.metadata.description,
1323
+ component: isInline ? void 0 : parsed.metadata.component ?? component.componentSource,
1324
+ category: macroMetadata.category ?? parsed.metadata.category,
1325
+ tags: macroMetadata.tags ?? parsed.metadata.tags,
1326
+ status: macroMetadata.status ?? parsed.metadata.status,
1327
+ order: macroMetadata.order ?? parsed.metadata.order,
1328
+ actionEvents: customMetadata.actionEvents ?? macroMetadata.actionEvents ?? parsed.metadata.actionEvents
1086
1329
  },
1087
- variants: parsed.variants.map((v) => ({
1088
- name: v.name,
1089
- template: styles.scopeAttr ? stampScopeAttribute(v.template, styles.scopeAttr) : v.template,
1090
- isDefault: v.isDefault,
1091
- skipVrt: v.skipVrt
1092
- })),
1330
+ variants: parsed.variants.map((v, index) => {
1331
+ const runtime = variantOptions[index]?.name === v.name ? variantOptions[index] : void 0;
1332
+ const targetInputs = extractTargetInputs(v.template, component.componentTagName);
1333
+ const legacyArgs = runtime?.args ?? v.args;
1334
+ const viewport = v.viewport ?? runtime?.viewport ?? legacyArgs?.viewport;
1335
+ const legacyProps = legacyArgs ? Object.fromEntries(Object.entries(legacyArgs).filter(([name]) => name !== "viewport")) : void 0;
1336
+ const props = runtime?.props ?? v.props ?? targetInputs.props ?? legacyProps;
1337
+ const attrs = runtime?.attrs ?? v.attrs ?? targetInputs.attrs;
1338
+ const play = runtime?.play ?? v.play;
1339
+ return {
1340
+ name: v.name,
1341
+ template: styles.scopeAttr ? stampScopeAttribute(v.template, styles.scopeAttr) : v.template,
1342
+ isDefault: v.isDefault,
1343
+ skipVrt: v.skipVrt,
1344
+ ...play ? { play } : {},
1345
+ ...props && Object.keys(props).length > 0 ? { props } : {},
1346
+ ...attrs && Object.keys(attrs).length > 0 ? { attrs } : {},
1347
+ ...viewport ? { viewport } : {},
1348
+ ...legacyArgs && Object.keys(legacyArgs).length > 0 ? { args: legacyArgs } : {}
1349
+ };
1350
+ }),
1093
1351
  hasScriptSetup: isInline ? false : parsed.hasScriptSetup,
1094
- scriptSetupContent: !isInline && parsed.hasScriptSetup ? extractScriptSetupContent(source) : void 0,
1352
+ scriptSetupContent,
1095
1353
  scriptSetupIsolated: !isInline && parsed.hasScriptSetup ? extractScriptSetupIsolated(source) : true,
1096
1354
  hasScript: parsed.hasScript,
1097
1355
  styleCount: parsed.styleCount,
@@ -1109,897 +1367,6 @@ async function processMuseaArtFile(filePath, ctx) {
1109
1367
  }
1110
1368
  }
1111
1369
  //#endregion
1112
- //#region src/api-tokens.ts
1113
- function resolveTokensPath(ctx) {
1114
- const allowedRoots = [ctx.config.root, ...ctx.scanRoots];
1115
- if (ctx.projectRoot) allowedRoots.push(ctx.projectRoot);
1116
- return resolveInsideAny(allowedRoots, ctx.tokensPath, "tokensPath");
1117
- }
1118
- function sendTokenMutationError(e, sendError) {
1119
- if (e instanceof HttpError) {
1120
- sendError(e.message, e.status);
1121
- return;
1122
- }
1123
- if (e instanceof Error && /(token path|token editing)/i.test(e.message)) {
1124
- sendError(e.message, 400);
1125
- return;
1126
- }
1127
- sendError(e instanceof Error ? e.message : String(e));
1128
- }
1129
- /** GET /api/tokens/usage */
1130
- async function handleTokensUsage(ctx, sendJson) {
1131
- if (!ctx.tokensPath) {
1132
- sendJson({});
1133
- return;
1134
- }
1135
- try {
1136
- const categories = await parseTokens(resolveTokensPath(ctx));
1137
- resolveReferences(categories, buildTokenMap(categories));
1138
- const resolvedTokenMap = buildTokenMap(categories);
1139
- sendJson(scanTokenUsage(ctx.artFiles, resolvedTokenMap));
1140
- } catch (e) {
1141
- console.error("[musea] Failed to scan token usage:", e);
1142
- sendJson({});
1143
- }
1144
- }
1145
- /** GET /api/tokens */
1146
- async function handleTokensGet(ctx, sendJson) {
1147
- if (!ctx.tokensPath) {
1148
- sendJson({
1149
- categories: [],
1150
- tokenMap: {},
1151
- meta: {
1152
- filePath: "",
1153
- tokenCount: 0,
1154
- primitiveCount: 0,
1155
- semanticCount: 0
1156
- }
1157
- });
1158
- return;
1159
- }
1160
- try {
1161
- const absoluteTokensPath = resolveTokensPath(ctx);
1162
- const categories = await parseTokens(absoluteTokensPath);
1163
- resolveReferences(categories, buildTokenMap(categories));
1164
- const resolvedTokenMap = buildTokenMap(categories);
1165
- let primitiveCount = 0;
1166
- let semanticCount = 0;
1167
- for (const token of Object.values(resolvedTokenMap)) if (token.$tier === "semantic") semanticCount++;
1168
- else primitiveCount++;
1169
- sendJson({
1170
- categories,
1171
- tokenMap: resolvedTokenMap,
1172
- meta: {
1173
- filePath: absoluteTokensPath,
1174
- tokenCount: Object.keys(resolvedTokenMap).length,
1175
- primitiveCount,
1176
- semanticCount
1177
- }
1178
- });
1179
- } catch (e) {
1180
- console.error("[musea] Failed to load tokens:", e);
1181
- sendJson({
1182
- categories: [],
1183
- tokenMap: {},
1184
- error: String(e)
1185
- });
1186
- }
1187
- }
1188
- /** POST /api/tokens (create) */
1189
- async function handleTokensCreate(ctx, readBody, sendJson, sendError) {
1190
- if (!ctx.tokensPath) {
1191
- sendError("No tokens path configured", 400);
1192
- return;
1193
- }
1194
- const body = await readBody();
1195
- try {
1196
- const { path: dotPath, token } = parseJsonBody(body);
1197
- if (!dotPath || !token || token.value === void 0) {
1198
- sendError("Missing required fields: path, token.value", 400);
1199
- return;
1200
- }
1201
- const absoluteTokensPath = resolveTokensPath(ctx);
1202
- const rawData = await readRawTokenFile(absoluteTokensPath);
1203
- const currentMap = buildTokenMap(await parseTokens(absoluteTokensPath));
1204
- if (currentMap[dotPath]) {
1205
- sendError(`Token already exists at path "${dotPath}"`, 409);
1206
- return;
1207
- }
1208
- if (token.$reference) {
1209
- const validation = validateSemanticReference(currentMap, token.$reference, dotPath);
1210
- if (!validation.valid) {
1211
- sendError(validation.error, 400);
1212
- return;
1213
- }
1214
- token.value = `{${token.$reference}}`;
1215
- token.$tier = "semantic";
1216
- }
1217
- setTokenAtPath(rawData, dotPath, token);
1218
- await writeRawTokenFile(absoluteTokensPath, rawData);
1219
- const categories = await parseTokens(absoluteTokensPath);
1220
- resolveReferences(categories, buildTokenMap(categories));
1221
- sendJson({
1222
- categories,
1223
- tokenMap: buildTokenMap(categories)
1224
- }, 201);
1225
- } catch (e) {
1226
- sendTokenMutationError(e, sendError);
1227
- }
1228
- }
1229
- /** PUT /api/tokens (update) */
1230
- async function handleTokensUpdate(ctx, readBody, sendJson, sendError) {
1231
- if (!ctx.tokensPath) {
1232
- sendError("No tokens path configured", 400);
1233
- return;
1234
- }
1235
- const body = await readBody();
1236
- try {
1237
- const { path: dotPath, token } = parseJsonBody(body);
1238
- if (!dotPath || !token || token.value === void 0) {
1239
- sendError("Missing required fields: path, token.value", 400);
1240
- return;
1241
- }
1242
- const absoluteTokensPath = resolveTokensPath(ctx);
1243
- if (token.$reference) {
1244
- const validation = validateSemanticReference(buildTokenMap(await parseTokens(absoluteTokensPath)), token.$reference, dotPath);
1245
- if (!validation.valid) {
1246
- sendError(validation.error, 400);
1247
- return;
1248
- }
1249
- token.value = `{${token.$reference}}`;
1250
- token.$tier = "semantic";
1251
- }
1252
- const rawData = await readRawTokenFile(absoluteTokensPath);
1253
- setTokenAtPath(rawData, dotPath, token);
1254
- await writeRawTokenFile(absoluteTokensPath, rawData);
1255
- const categories = await parseTokens(absoluteTokensPath);
1256
- resolveReferences(categories, buildTokenMap(categories));
1257
- sendJson({
1258
- categories,
1259
- tokenMap: buildTokenMap(categories)
1260
- });
1261
- } catch (e) {
1262
- sendTokenMutationError(e, sendError);
1263
- }
1264
- }
1265
- /** DELETE /api/tokens */
1266
- async function handleTokensDelete(ctx, readBody, sendJson, sendError) {
1267
- if (!ctx.tokensPath) {
1268
- sendError("No tokens path configured", 400);
1269
- return;
1270
- }
1271
- const body = await readBody();
1272
- try {
1273
- const { path: dotPath } = parseJsonBody(body);
1274
- if (!dotPath) {
1275
- sendError("Missing required field: path", 400);
1276
- return;
1277
- }
1278
- const absoluteTokensPath = resolveTokensPath(ctx);
1279
- const dependents = findDependentTokens(buildTokenMap(await parseTokens(absoluteTokensPath)), dotPath);
1280
- const rawData = await readRawTokenFile(absoluteTokensPath);
1281
- if (!deleteTokenAtPath(rawData, dotPath)) {
1282
- sendError(`Token not found at path "${dotPath}"`, 404);
1283
- return;
1284
- }
1285
- await writeRawTokenFile(absoluteTokensPath, rawData);
1286
- const categories = await parseTokens(absoluteTokensPath);
1287
- resolveReferences(categories, buildTokenMap(categories));
1288
- sendJson({
1289
- categories,
1290
- tokenMap: buildTokenMap(categories),
1291
- dependentsWarning: dependents.length > 0 ? dependents : void 0
1292
- });
1293
- } catch (e) {
1294
- sendTokenMutationError(e, sendError);
1295
- }
1296
- }
1297
- //#endregion
1298
- //#region src/script-component-analysis.ts
1299
- /** Read a script component's runtime options without executing project code. */
1300
- function scriptKind(filename) {
1301
- if (filename.endsWith(".tsx")) return ts.ScriptKind.TSX;
1302
- if (filename.endsWith(".jsx")) return ts.ScriptKind.JSX;
1303
- if (filename.endsWith(".js")) return ts.ScriptKind.JS;
1304
- return ts.ScriptKind.TS;
1305
- }
1306
- function unwrap(expression) {
1307
- while (ts.isParenthesizedExpression(expression) || ts.isAsExpression(expression) || ts.isSatisfiesExpression(expression) || ts.isNonNullExpression(expression)) expression = expression.expression;
1308
- return expression;
1309
- }
1310
- function nameOf(name) {
1311
- if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) return name.text;
1312
- if (ts.isComputedPropertyName(name) && ts.isStringLiteral(name.expression)) return name.expression.text;
1313
- }
1314
- function variable(sourceFile, name) {
1315
- for (const statement of sourceFile.statements) {
1316
- if (!ts.isVariableStatement(statement)) continue;
1317
- for (const declaration of statement.declarationList.declarations) if (ts.isIdentifier(declaration.name) && declaration.name.text === name) return declaration.initializer;
1318
- }
1319
- }
1320
- function resolved(expression, sourceFile) {
1321
- expression = unwrap(expression);
1322
- if (ts.isIdentifier(expression)) {
1323
- const initializer = variable(sourceFile, expression.text);
1324
- if (initializer) return unwrap(initializer);
1325
- }
1326
- return expression;
1327
- }
1328
- function option(object, name, sourceFile) {
1329
- for (const property of object.properties) {
1330
- if (ts.isPropertyAssignment(property) && nameOf(property.name) === name) return resolved(property.initializer, sourceFile);
1331
- if (ts.isShorthandPropertyAssignment(property) && property.name.text === name) {
1332
- const initializer = variable(sourceFile, name);
1333
- if (initializer) return resolved(initializer, sourceFile);
1334
- }
1335
- }
1336
- }
1337
- function componentOptions(sourceFile) {
1338
- const assignment = sourceFile.statements.find((statement) => ts.isExportAssignment(statement));
1339
- if (!assignment || assignment.isExportEquals) return void 0;
1340
- let expression = resolved(assignment.expression, sourceFile);
1341
- if (ts.isCallExpression(expression)) {
1342
- const callee = expression.expression;
1343
- if (!(ts.isIdentifier(callee) && callee.text === "defineComponent" || ts.isPropertyAccessExpression(callee) && callee.name.text === "defineComponent") || !expression.arguments[0]) return void 0;
1344
- expression = resolved(expression.arguments[0], sourceFile);
1345
- }
1346
- return ts.isObjectLiteralExpression(expression) ? expression : void 0;
1347
- }
1348
- function literal(expression) {
1349
- expression = unwrap(expression);
1350
- if (ts.isStringLiteral(expression) || ts.isNoSubstitutionTemplateLiteral(expression)) return expression.text;
1351
- if (ts.isNumericLiteral(expression)) return Number(expression.text);
1352
- if (expression.kind === ts.SyntaxKind.TrueKeyword) return true;
1353
- if (expression.kind === ts.SyntaxKind.FalseKeyword) return false;
1354
- if (expression.kind === ts.SyntaxKind.NullKeyword) return null;
1355
- if (ts.isPrefixUnaryExpression(expression) && ts.isNumericLiteral(expression.operand)) {
1356
- const value = Number(expression.operand.text);
1357
- if (expression.operator === ts.SyntaxKind.MinusToken) return -value;
1358
- if (expression.operator === ts.SyntaxKind.PlusToken) return value;
1359
- }
1360
- }
1361
- function propType(expression) {
1362
- if (!expression) return "unknown";
1363
- expression = unwrap(expression);
1364
- if (ts.isArrayLiteralExpression(expression)) return expression.elements.map((element) => propType(element)).join(" | ") || "unknown";
1365
- switch (ts.isIdentifier(expression) ? expression.text : ts.isPropertyAccessExpression(expression) ? expression.name.text : void 0) {
1366
- case "String": return "string";
1367
- case "Number": return "number";
1368
- case "Boolean": return "boolean";
1369
- case "Array": return "unknown[]";
1370
- case "Object": return "Record<string, unknown>";
1371
- default: return "unknown";
1372
- }
1373
- }
1374
- function analyzeProps(expression, sourceFile) {
1375
- if (!expression) return [];
1376
- if (ts.isArrayLiteralExpression(expression)) return expression.elements.flatMap((element) => ts.isStringLiteral(element) ? [{
1377
- name: element.text,
1378
- type: "unknown",
1379
- required: false
1380
- }] : []);
1381
- if (!ts.isObjectLiteralExpression(expression)) return [];
1382
- const props = [];
1383
- for (const property of expression.properties) {
1384
- if (!ts.isPropertyAssignment(property)) continue;
1385
- const name = nameOf(property.name);
1386
- if (!name) continue;
1387
- const value = resolved(property.initializer, sourceFile);
1388
- if (ts.isObjectLiteralExpression(value)) {
1389
- const type = propType(option(value, "type", sourceFile));
1390
- const required = option(value, "required", sourceFile)?.kind === ts.SyntaxKind.TrueKeyword;
1391
- const defaultExpression = option(value, "default", sourceFile);
1392
- const defaultValue = defaultExpression ? literal(defaultExpression) : void 0;
1393
- props.push({
1394
- name,
1395
- type,
1396
- required,
1397
- ...defaultValue !== void 0 ? { default_value: defaultValue } : {}
1398
- });
1399
- } else props.push({
1400
- name,
1401
- type: propType(value),
1402
- required: false
1403
- });
1404
- }
1405
- return props;
1406
- }
1407
- function analyzeEmits(expression) {
1408
- if (!expression) return [];
1409
- if (ts.isArrayLiteralExpression(expression)) return expression.elements.flatMap((element) => ts.isStringLiteral(element) ? [element.text] : []);
1410
- if (ts.isObjectLiteralExpression(expression)) return expression.properties.flatMap((property) => (ts.isPropertyAssignment(property) || ts.isMethodDeclaration(property)) && nameOf(property.name) ? [nameOf(property.name)] : []);
1411
- return [];
1412
- }
1413
- function analyzeScriptComponent(source, filename) {
1414
- const sourceFile = ts.createSourceFile(filename, source, ts.ScriptTarget.Latest, true, scriptKind(filename));
1415
- const options = componentOptions(sourceFile);
1416
- if (!options) return {
1417
- props: [],
1418
- emits: []
1419
- };
1420
- return {
1421
- props: analyzeProps(option(options, "props", sourceFile), sourceFile),
1422
- emits: analyzeEmits(option(options, "emits", sourceFile))
1423
- };
1424
- }
1425
- //#endregion
1426
- //#region src/api-routes/handler-palette.ts
1427
- /**
1428
- * Palette handler for the Musea gallery API.
1429
- *
1430
- * Handles GET /api/arts/:path/palette endpoint.
1431
- */
1432
- /** GET /api/arts/:path/palette */
1433
- async function handleArtPalette(ctx, match, sendJson, sendError) {
1434
- const artPath = decodeUrlComponent(match[1], "art path");
1435
- const art = ctx.artFiles.get(artPath);
1436
- if (!art) {
1437
- sendError("Art not found", 404);
1438
- return;
1439
- }
1440
- try {
1441
- const readableArtPath = resolveReadableArtPath(ctx.config.root, ctx.scanRoots, artPath);
1442
- const source = await fs.promises.readFile(readableArtPath, "utf-8");
1443
- const binding = loadNative();
1444
- let palette;
1445
- if (binding.generateArtPalette) {
1446
- const generated = binding.generateArtPalette(source, { filename: readableArtPath });
1447
- palette = {
1448
- ...generated,
1449
- controls: generated.controls.map(({ defaultValue, ...control }) => ({
1450
- ...control,
1451
- ...defaultValue !== void 0 ? { default_value: defaultValue } : {}
1452
- }))
1453
- };
1454
- palette.json = JSON.stringify({
1455
- title: palette.title,
1456
- controls: palette.controls
1457
- }, null, 2);
1458
- } else palette = {
1459
- title: art.metadata.title,
1460
- controls: [],
1461
- groups: [],
1462
- json: "{}",
1463
- typescript: ""
1464
- };
1465
- palette.componentTagName = resolveArtComponent(art, artPath, art.scriptSetupContent ? parseScriptSetupForArt(art.scriptSetupContent) : null, {
1466
- root: ctx.config.root,
1467
- scanRoots: ctx.scanRoots
1468
- }).componentTagName;
1469
- const resolvedComponentPath = resolveComponentSourcePath(art, artPath, allowedSourceRoots(ctx.config.root, ctx.scanRoots));
1470
- if (!resolvedComponentPath) {
1471
- sendJson(palette);
1472
- return;
1473
- }
1474
- try {
1475
- const componentSource = await fs.promises.readFile(resolvedComponentPath, "utf-8");
1476
- const analysis = isVueSourcePath(resolvedComponentPath) ? binding.analyzeSfc ? binding.analyzeSfc(componentSource, { filename: resolvedComponentPath }) : analyzeSfcFallback(componentSource, { filename: resolvedComponentPath }) : analyzeScriptComponent(componentSource, resolvedComponentPath);
1477
- if (analysis.props.length > 0) mergeSfcPropsIntoPalette(palette, analysis.props);
1478
- if (isVueSourcePath(resolvedComponentPath) && analysis.props.some((prop) => prop.name === "__proto__")) palette.unsupportedProps = ["__proto__"];
1479
- } catch {}
1480
- sendJson(palette);
1481
- } catch (e) {
1482
- if (e instanceof HttpError) {
1483
- sendError(e.message, e.status);
1484
- return;
1485
- }
1486
- sendError(e instanceof Error ? e.message : String(e));
1487
- }
1488
- }
1489
- function mergeSfcPropsIntoPalette(palette, props) {
1490
- const controlsByName = /* @__PURE__ */ new Map();
1491
- for (const control of palette.controls) controlsByName.set(normalizePropName(control.name), control);
1492
- for (const prop of props) {
1493
- const control = controlsByName.get(normalizePropName(prop.name));
1494
- if (control) applyPropMetadata(control, prop);
1495
- else palette.controls.push(controlFromProp(prop));
1496
- }
1497
- palette.json = JSON.stringify({
1498
- title: palette.title,
1499
- controls: palette.controls
1500
- }, null, 2);
1501
- palette.typescript = generateTypescript(palette);
1502
- }
1503
- function applyPropMetadata(control, prop) {
1504
- const inferred = inferControl(prop.type);
1505
- control.name = prop.name;
1506
- control.required = prop.required;
1507
- if (control.default_value === void 0 && prop.default_value !== void 0) control.default_value = prop.default_value;
1508
- if (prop.unsupported_default) {
1509
- control.unsupported_default = true;
1510
- control.default_source = prop.default_source;
1511
- control.description = "The component retains its authored default; this expression is not evaluated for Controls.";
1512
- }
1513
- if (inferred.control !== "text" || control.control === "text") control.control = inferred.control;
1514
- if (inferred.options.length > 0) control.options = inferred.options;
1515
- }
1516
- function controlFromProp(prop) {
1517
- const inferred = inferControl(prop.type);
1518
- return {
1519
- name: prop.name,
1520
- control: inferred.control,
1521
- default_value: prop.default_value,
1522
- ...prop.unsupported_default ? {
1523
- unsupported_default: true,
1524
- default_source: prop.default_source,
1525
- description: "The component retains its authored default; this expression is not evaluated for Controls."
1526
- } : {},
1527
- required: prop.required,
1528
- options: inferred.options,
1529
- range: void 0,
1530
- group: void 0
1531
- };
1532
- }
1533
- function inferControl(type) {
1534
- const normalized = type.trim();
1535
- if (normalized.includes("=>") || normalized === "Function") return {
1536
- control: "function",
1537
- options: []
1538
- };
1539
- const options = literalOptions(normalized);
1540
- if (options.length > 0) return {
1541
- control: "select",
1542
- options
1543
- };
1544
- if (normalized === "boolean") return {
1545
- control: "boolean",
1546
- options: []
1547
- };
1548
- if (normalized === "number") return {
1549
- control: "number",
1550
- options: []
1551
- };
1552
- if (normalized.includes("[]") || normalized.startsWith("Array<")) return {
1553
- control: "array",
1554
- options: []
1555
- };
1556
- if (normalized.startsWith("{") || normalized.startsWith("Record<")) return {
1557
- control: "object",
1558
- options: []
1559
- };
1560
- return {
1561
- control: "text",
1562
- options: []
1563
- };
1564
- }
1565
- function literalOptions(type) {
1566
- if (!type.includes("|") || type.includes("=>")) return [];
1567
- return type.split("|").map((part) => part.trim()).map((part) => {
1568
- const stringMatch = part.match(/^["']([^"']+)["']$/);
1569
- if (stringMatch) return stringMatch[1];
1570
- if (part === "true") return true;
1571
- if (part === "false") return false;
1572
- const numberValue = Number(part);
1573
- return Number.isFinite(numberValue) ? numberValue : void 0;
1574
- }).filter((value) => value !== void 0).map((value) => ({
1575
- label: String(value),
1576
- value
1577
- }));
1578
- }
1579
- function normalizePropName(name) {
1580
- return name.replace(/[-_]/g, "").toLowerCase();
1581
- }
1582
- function generateTypescript(palette) {
1583
- const fields = palette.controls.map((control) => {
1584
- return ` ${/^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u.test(control.name) ? control.name : JSON.stringify(control.name)}${control.required ? "" : "?"}: ${controlTsType(control)};`;
1585
- }).join("\n");
1586
- return `export interface ${pascalCase(palette.title)}Props {\n${fields}\n}\n`;
1587
- }
1588
- function controlTsType(control) {
1589
- if (control.control === "boolean") return "boolean";
1590
- if (control.control === "number" || control.control === "range") return "number";
1591
- if (control.control === "function") return "(...args: unknown[]) => unknown";
1592
- if (control.control === "array") return "unknown[]";
1593
- if (control.control === "object") return "Record<string, unknown>";
1594
- if (control.control === "select" && control.options.length > 0) return control.options.map((option) => JSON.stringify(option.value)).join(" | ");
1595
- return "string";
1596
- }
1597
- function pascalCase(value) {
1598
- return value.split(/[^A-Za-z0-9]+/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
1599
- }
1600
- //#endregion
1601
- //#region src/api-routes/handlers.ts
1602
- /**
1603
- * Individual route handler functions for the Musea gallery API.
1604
- *
1605
- * Extracted from api-routes.ts to keep file sizes manageable.
1606
- * These handle GET /api/arts/:path/... sub-routes.
1607
- */
1608
- function sendCaughtError(sendError, error) {
1609
- if (error instanceof HttpError) {
1610
- sendError(error.message, error.status);
1611
- return;
1612
- }
1613
- sendError(error instanceof Error ? error.message : String(error));
1614
- }
1615
- /** GET /api/arts/:path/source */
1616
- async function handleArtSource(ctx, match, sendJson, sendError) {
1617
- const artPath = decodeUrlComponent(match[1], "art path");
1618
- if (!ctx.artFiles.get(artPath)) {
1619
- sendError("Art not found", 404);
1620
- return;
1621
- }
1622
- try {
1623
- const readableArtPath = resolveReadableArtPath(ctx.config.root, ctx.scanRoots, artPath);
1624
- sendJson({
1625
- source: await fs.promises.readFile(readableArtPath, "utf-8"),
1626
- path: artPath
1627
- });
1628
- } catch (e) {
1629
- sendCaughtError(sendError, e);
1630
- }
1631
- }
1632
- /** GET /api/arts/:path/analysis */
1633
- async function handleArtAnalysis(ctx, match, sendJson, sendError) {
1634
- const artPath = decodeUrlComponent(match[1], "art path");
1635
- const art = ctx.artFiles.get(artPath);
1636
- if (!art) {
1637
- sendError("Art not found", 404);
1638
- return;
1639
- }
1640
- try {
1641
- const resolvedComponentPath = resolveComponentSourcePath(art, artPath, allowedSourceRoots(ctx.config.root, ctx.scanRoots));
1642
- if (resolvedComponentPath) {
1643
- const source = await fs.promises.readFile(resolvedComponentPath, "utf-8");
1644
- if (isVueSourcePath(resolvedComponentPath)) {
1645
- const binding = loadNative();
1646
- sendJson(binding.analyzeSfc ? binding.analyzeSfc(source, { filename: resolvedComponentPath }) : analyzeSfcFallback(source, { filename: resolvedComponentPath }));
1647
- } else sendJson(analyzeScriptComponent(source, resolvedComponentPath));
1648
- } else sendJson({
1649
- props: [],
1650
- emits: []
1651
- });
1652
- } catch (e) {
1653
- sendCaughtError(sendError, e);
1654
- }
1655
- }
1656
- /** GET /api/arts/:path/docs */
1657
- async function handleArtDocs(ctx, match, sendJson, sendError) {
1658
- const artPath = decodeUrlComponent(match[1], "art path");
1659
- const art = ctx.artFiles.get(artPath);
1660
- if (!art) {
1661
- sendError("Art not found", 404);
1662
- return;
1663
- }
1664
- try {
1665
- const readableArtPath = resolveReadableArtPath(ctx.config.root, ctx.scanRoots, artPath);
1666
- const source = await fs.promises.readFile(readableArtPath, "utf-8");
1667
- const binding = loadNative();
1668
- if (binding.generateArtDoc) {
1669
- const doc = binding.generateArtDoc(source, { filename: readableArtPath });
1670
- let markdown = doc.markdown || "";
1671
- const componentName = art.metadata.title || "Component";
1672
- markdown = markdown.replace(/<Self(\s|>|\/)/g, `<${componentName}$1`).replace(/<\/Self>/g, `</${componentName}>`);
1673
- markdown = markdown.replace(/```(\w*)\n([\s\S]*?)```/g, (_match, lang, code) => {
1674
- const lines = code.split("\n");
1675
- let minIndent = Infinity;
1676
- for (const line of lines) if (line.trim()) {
1677
- const indent = line.match(/^(\s*)/)?.[1].length || 0;
1678
- minIndent = Math.min(minIndent, indent);
1679
- }
1680
- if (minIndent === Infinity) minIndent = 0;
1681
- let formatted;
1682
- if (minIndent > 0) formatted = lines.map((line) => line.slice(minIndent)).join("\n");
1683
- else {
1684
- let restIndent = Infinity;
1685
- for (let i = 1; i < lines.length; i++) if (lines[i].trim()) {
1686
- const indent = lines[i].match(/^(\s*)/)?.[1].length || 0;
1687
- restIndent = Math.min(restIndent, indent);
1688
- }
1689
- if (restIndent === Infinity || restIndent === 0) formatted = lines.join("\n");
1690
- else formatted = lines.map((line, i) => i === 0 ? line : line.slice(restIndent)).join("\n");
1691
- }
1692
- return "```" + lang + "\n" + formatted + "```";
1693
- });
1694
- sendJson({
1695
- ...doc,
1696
- markdown
1697
- });
1698
- } else sendJson({
1699
- markdown: "",
1700
- title: art.metadata.title,
1701
- variant_count: art.variants.length
1702
- });
1703
- } catch (e) {
1704
- sendCaughtError(sendError, e);
1705
- }
1706
- }
1707
- /** GET /api/arts/:path/variants/:name/a11y */
1708
- //#endregion
1709
- //#region src/art-order.ts
1710
- function sortedArts(arts) {
1711
- return [...arts].sort(compareArtFiles);
1712
- }
1713
- function compareArtFiles(a, b) {
1714
- const order = compareOrder(a.metadata.order, b.metadata.order);
1715
- if (order !== 0) return order;
1716
- const title = a.metadata.title.localeCompare(b.metadata.title, void 0, { numeric: true });
1717
- if (title !== 0) return title;
1718
- return a.path.localeCompare(b.path, void 0, { numeric: true });
1719
- }
1720
- function compareOrder(a, b) {
1721
- if (a === void 0 && b === void 0) return 0;
1722
- if (a === void 0) return 1;
1723
- if (b === void 0) return -1;
1724
- return a - b;
1725
- }
1726
- //#endregion
1727
- //#region src/static-data.ts
1728
- function staticPreviewId(artPath, variantName) {
1729
- return crypto.createHash("sha256").update(artPath).update("\0").update(variantName).digest("hex").slice(0, 20);
1730
- }
1731
- function joinUrlPath(basePath, ...segments) {
1732
- return `${basePath === "/" ? "" : basePath.replace(/\/+$/, "")}/${segments.map((segment) => segment.replace(/^\/+|\/+$/g, "")).filter(Boolean).join("/")}`;
1733
- }
1734
- async function createStaticGalleryPayload(ctx) {
1735
- const apiCtx = createApiContext(ctx);
1736
- const sourceArts = sortedArts(ctx.artFiles.values());
1737
- const arts = [];
1738
- const previews = Object.create(null);
1739
- const details = {};
1740
- const snapshotIdentities = Object.create(null);
1741
- const identityRoot = resolveStaticIdentityRoot(ctx.config.root, sourceArts.map((art) => art.path), ctx.projectRoot);
1742
- const publicPaths = /* @__PURE__ */ new Map();
1743
- for (const art of sourceArts) publicPaths.set(art.path, resolveStaticArtIdentity(art.path, identityRoot));
1744
- for (const sourceArt of sourceArts) {
1745
- const publicPath = publicPaths.get(sourceArt.path);
1746
- const art = publicArtInfo(sourceArt, publicPath, identityRoot);
1747
- arts.push(art);
1748
- snapshotIdentities[publicPath] = publicPath;
1749
- previews[publicPath] = Object.create(null);
1750
- for (const variant of art.variants) {
1751
- const id = staticPreviewId(publicPath, variant.name);
1752
- previews[publicPath][variant.name] = joinUrlPath(ctx.basePath, "preview", `${id}.html`);
1753
- }
1754
- details[publicPath] = {
1755
- source: withPublicSourcePath(await captureJson((sendJson, sendError) => {
1756
- return handleArtSource(apiCtx, artMatch(sourceArt.path), sendJson, sendError);
1757
- }, {
1758
- source: "",
1759
- path: sourceArt.path
1760
- }), publicPath),
1761
- palette: await captureJson((sendJson, sendError) => {
1762
- return handleArtPalette(apiCtx, artMatch(sourceArt.path), sendJson, sendError);
1763
- }, emptyPalette(art)),
1764
- analysis: await captureJson((sendJson, sendError) => {
1765
- return handleArtAnalysis(apiCtx, artMatch(sourceArt.path), sendJson, sendError);
1766
- }, {
1767
- props: [],
1768
- emits: []
1769
- }),
1770
- docs: await captureJson((sendJson, sendError) => {
1771
- return handleArtDocs(apiCtx, artMatch(sourceArt.path), sendJson, sendError);
1772
- }, emptyDocs(art))
1773
- };
1774
- }
1775
- const tokens = await captureJson((sendJson) => handleTokensGet(apiCtx, sendJson), emptyTokens());
1776
- const tokenUsage = await captureJson((sendJson) => handleTokensUsage(apiCtx, sendJson), {});
1777
- return {
1778
- arts,
1779
- snapshotIdentityVersion: 1,
1780
- snapshotIdentities,
1781
- previews,
1782
- details,
1783
- tokens: withPublicTokenPath(tokens, identityRoot),
1784
- tokenUsage: withPublicUsagePaths(tokenUsage, publicPaths)
1785
- };
1786
- }
1787
- function resolveStaticIdentityRoot(viteRoot, artPaths, projectRoot) {
1788
- if (projectRoot) return path.resolve(projectRoot);
1789
- let root = path.resolve(viteRoot);
1790
- for (const artPath of artPaths) {
1791
- const directory = path.dirname(path.resolve(artPath));
1792
- while (!isPathInside(root, directory)) {
1793
- const parent = path.dirname(root);
1794
- if (parent === root) throw new Error(`Art is outside the Vite root on another filesystem: ${artPath}. Configure projectRoot.`);
1795
- root = parent;
1796
- }
1797
- }
1798
- return root;
1799
- }
1800
- function resolveStaticArtIdentity(artPath, identityRoot) {
1801
- return resolveSnapshotIdentity(artPath, identityRoot);
1802
- }
1803
- function publicArtInfo(art, publicPath, identityRoot) {
1804
- return {
1805
- ...art,
1806
- path: publicPath,
1807
- ...art.componentPath ? { componentPath: publicSourceIdentity(art.componentPath, identityRoot) } : {}
1808
- };
1809
- }
1810
- function withPublicSourcePath(value, publicPath) {
1811
- if (!isRecord(value) || typeof value.path !== "string") return value;
1812
- return {
1813
- ...value,
1814
- path: publicPath
1815
- };
1816
- }
1817
- function withPublicTokenPath(value, identityRoot) {
1818
- if (!isRecord(value) || !isRecord(value.meta) || typeof value.meta.filePath !== "string") return value;
1819
- if (!path.isAbsolute(value.meta.filePath)) return value;
1820
- return {
1821
- ...value,
1822
- meta: {
1823
- ...value.meta,
1824
- filePath: publicSourceIdentity(value.meta.filePath, identityRoot)
1825
- }
1826
- };
1827
- }
1828
- function withPublicUsagePaths(value, publicPaths) {
1829
- if (!isRecord(value)) return value;
1830
- return Object.fromEntries(Object.entries(value).map(([token, entries]) => [token, Array.isArray(entries) ? entries.map((entry) => isRecord(entry) && typeof entry.artPath === "string" ? {
1831
- ...entry,
1832
- artPath: publicPaths.get(entry.artPath) ?? path.basename(entry.artPath)
1833
- } : entry) : entries]));
1834
- }
1835
- function publicSourceIdentity(sourcePath, identityRoot) {
1836
- const relative = path.relative(identityRoot, path.resolve(sourcePath));
1837
- if (relative === "" || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) return path.basename(sourcePath);
1838
- return relative.split(path.sep).join("/");
1839
- }
1840
- function isRecord(value) {
1841
- return value !== null && typeof value === "object" && !Array.isArray(value);
1842
- }
1843
- function isPathInside(root, candidate) {
1844
- const relative = path.relative(root, candidate);
1845
- return relative === "" || relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
1846
- }
1847
- function createApiContext(ctx) {
1848
- return {
1849
- config: ctx.config,
1850
- artFiles: ctx.artFiles,
1851
- scanRoots: ctx.scanRoots,
1852
- tokensPath: ctx.tokensPath,
1853
- projectRoot: ctx.projectRoot,
1854
- basePath: ctx.basePath,
1855
- resolvedPreviewCss: ctx.resolvedPreviewCss,
1856
- resolvedPreviewSetup: ctx.resolvedPreviewSetup,
1857
- devSessionToken: ctx.devSessionToken,
1858
- processArtFile: async (filePath) => {
1859
- await fs.promises.access(filePath);
1860
- },
1861
- getDevServerPort: () => 5173
1862
- };
1863
- }
1864
- async function captureJson(run, fallback) {
1865
- let captured = fallback;
1866
- const sendJson = (data) => {
1867
- captured = data;
1868
- };
1869
- const sendError = (message, status = 500) => {
1870
- captured = {
1871
- error: message,
1872
- status
1873
- };
1874
- };
1875
- await run(sendJson, sendError);
1876
- return captured;
1877
- }
1878
- function artMatch(artPath) {
1879
- return ["", encodeURIComponent(artPath)];
1880
- }
1881
- function emptyPalette(art) {
1882
- return {
1883
- title: art.metadata.title,
1884
- controls: [],
1885
- groups: [],
1886
- json: "{}",
1887
- typescript: ""
1888
- };
1889
- }
1890
- function emptyDocs(art) {
1891
- return {
1892
- markdown: "",
1893
- title: art.metadata.title,
1894
- variant_count: art.variants.length
1895
- };
1896
- }
1897
- function emptyTokens() {
1898
- return {
1899
- categories: [],
1900
- tokenMap: {},
1901
- meta: {
1902
- filePath: "",
1903
- tokenCount: 0,
1904
- primitiveCount: 0,
1905
- semanticCount: 0
1906
- }
1907
- };
1908
- }
1909
- //#endregion
1910
- //#region src/static-base.ts
1911
- const TEXT_GALLERY_ASSET_EXT = /\.(?:css|html|js|map|mjs)$/u;
1912
- function rewriteGalleryBase(source, basePath) {
1913
- return source.replaceAll("/__musea__/", `${basePath.replace(/\/?$/, "/")}`);
1914
- }
1915
- function rewriteGalleryTextAssetBase(source, relativePath, basePath) {
1916
- if (!TEXT_GALLERY_ASSET_EXT.test(relativePath)) return source;
1917
- return rewriteGalleryBase(Buffer.from(source).toString("utf-8"), basePath);
1918
- }
1919
- function rewriteDevGalleryAsset(source, relativePath, basePath) {
1920
- return basePath === "/__musea__" ? source : rewriteGalleryTextAssetBase(source, relativePath, basePath);
1921
- }
1922
- function publicBasePathFromViteBase(viteBase, basePath) {
1923
- return viteBase && viteBase !== "/" && viteBase !== "./" ? joinUrlPath(viteBase, basePath) : basePath;
1924
- }
1925
- //#endregion
1926
- //#region src/vrt/report-identity.ts
1927
- /** Reserve one qualified namespace and compare legacy names on case-insensitive filesystems. */
1928
- function legacyName(identity) {
1929
- const basename = path.posix.basename(identity, ".art.vue");
1930
- return /^[a-z0-9._-]{1,200}$/i.test(basename) && !/^art-[0-9a-f]{64}$/i.test(basename) ? `vrt-${basename}` : void 0;
1931
- }
1932
- /** The complete discovered Art set decides collisions, even for a single-Art request. */
1933
- function resolveArtReportTarget(artPath, artPaths, projectRoot, reportDir) {
1934
- const identities = Array.from(artPaths, (item) => resolveSnapshotIdentity(item, projectRoot));
1935
- const identity = resolveSnapshotIdentity(artPath, projectRoot);
1936
- if (!identities.includes(identity)) throw new Error(`Report Art not found: ${artPath}`);
1937
- const candidates = identities.map(legacyName);
1938
- const counts = /* @__PURE__ */ new Map();
1939
- for (const name of candidates) if (name) counts.set(name.toLowerCase(), (counts.get(name.toLowerCase()) ?? 0) + 1);
1940
- const names = identities.map((item, index) => {
1941
- const candidate = candidates[index];
1942
- const colliding = candidate && counts.get(candidate.toLowerCase()) > 1;
1943
- return candidate && !colliding ? candidate : `vrt-art-${createHash("sha256").update(JSON.stringify([1, item])).digest("hex")}`;
1944
- });
1945
- if (new Set(names.map((name) => name.toLowerCase())).size !== names.length) throw new Error("Ambiguous VRT report identities");
1946
- const base = names[identities.indexOf(identity)];
1947
- return {
1948
- identity,
1949
- jsonReportPath: path.join(reportDir, `${base}-report.json`),
1950
- htmlReportPath: path.join(reportDir, `${base}-report.html`)
1951
- };
1952
- }
1953
- async function existsRegularFile(file) {
1954
- try {
1955
- if (!(await lstat(file)).isFile()) throw new Error(`VRT report is not a regular file: ${file}`);
1956
- return true;
1957
- } catch (error) {
1958
- if (error.code === "ENOENT") return false;
1959
- throw error;
1960
- }
1961
- }
1962
- /** Fail before capture or writes; legacy adoption requires every recorded result to have this owner. */
1963
- async function assertArtReportOwnership(target, projectRoot) {
1964
- const refusal = `Ambiguous VRT report ownership: ${target.jsonReportPath}. Archive or move the existing reports before retrying.`;
1965
- const names = [path.basename(target.jsonReportPath), path.basename(target.htmlReportPath)];
1966
- let existingNames;
1967
- try {
1968
- existingNames = await readdir(path.dirname(target.jsonReportPath));
1969
- } catch (error) {
1970
- if (error.code === "ENOENT") return;
1971
- throw error;
1972
- }
1973
- if (existingNames.some((item) => names.some((name) => item !== name && item.toLowerCase() === name.toLowerCase()))) throw new Error(refusal);
1974
- const jsonExists = await existsRegularFile(target.jsonReportPath);
1975
- const htmlExists = await existsRegularFile(target.htmlReportPath);
1976
- if (!jsonExists && !htmlExists) return;
1977
- if (!jsonExists) throw new Error(refusal);
1978
- try {
1979
- const report = JSON.parse(await readFile(target.jsonReportPath, "utf8"));
1980
- if (!report || typeof report !== "object" || Array.isArray(report)) throw new Error(refusal);
1981
- if (Object.hasOwn(report, "reportOwner")) {
1982
- const owner = report.reportOwner;
1983
- if (!owner || typeof owner !== "object" || owner.version !== 1 || owner.artIdentity !== target.identity) throw new Error(refusal);
1984
- } else {
1985
- const results = report.results;
1986
- if (!Array.isArray(results) || !results.length || results.some((item) => !item || typeof item !== "object" || typeof item.artPath !== "string" || resolveSnapshotIdentity(item.artPath, projectRoot) !== target.identity)) throw new Error(refusal);
1987
- }
1988
- } catch {
1989
- throw new Error(refusal);
1990
- }
1991
- }
1992
- /** Keep ownership portable when a report directory moves to another machine. */
1993
- function attachArtReportOwner(json, target) {
1994
- return JSON.stringify({
1995
- ...JSON.parse(json),
1996
- reportOwner: {
1997
- version: 1,
1998
- artIdentity: target.identity
1999
- }
2000
- }, null, 2);
2001
- }
2002
- //#endregion
2003
- export { HttpError as $, expandSelfTag as A, DEFAULT_API_BODY_LIMIT_BYTES as B, processMuseaArtFile as C, loadArtStyle as D, rewriteRelativeImportStatement as E, matchGlob as F, validateDevApiRequest as G, createDevSessionToken as H, resolveScanRoots as I, decodeUrlComponent as J, assertArtVueSourcePath as K, scanArtFiles as L, variantComponentNames as M, escapeHtml as N, parseArtStyleRequest as O, generateStorybookFiles as P, resolveUrlPathInside as Q, shouldProcess as R, handleTokensUsage as S, parseScriptSetupForArt as T, parseJsonBody as U, collectRequestBody as V, serializeScriptValue as W, resolveInside as X, isTrustedSourcePath as Y, resolveTrustedSourcePath as Z, handleArtPalette as _, rewriteDevGalleryAsset as a, handleTokensGet as b, createStaticGalleryPayload as c, resolveStaticIdentityRoot as d, staticPreviewId as f, handleArtSource as g, handleArtDocs as h, publicBasePathFromViteBase as i, resolveArtComponent as j, transformPreprocessedArtStyle as k, joinUrlPath as l, handleArtAnalysis as m, attachArtReportOwner as n, rewriteGalleryBase as o, sortedArts as p, assertVueSourcePath as q, resolveArtReportTarget as r, rewriteGalleryTextAssetBase as s, assertArtReportOwnership as t, resolveStaticArtIdentity as u, handleTokensCreate as v, generateArtModule as w, handleTokensUpdate as x, handleTokensDelete as y, buildThemeConfig as z };
1370
+ export { decodeUrlComponent as A, collectRequestBody as C, validateDevApiRequest as D, serializeScriptValue as E, resolveTrustedSourcePath as F, resolveUrlPathInside as I, HttpError as L, isVueSourcePath as M, resolveInside as N, assertArtVueSourcePath as O, resolveInsideAny as P, DEFAULT_API_BODY_LIMIT_BYTES as S, parseJsonBody as T, matchGlob as _, parseScriptSetupForArt as a, shouldProcess as b, parseArtStyleRequest as c, allowedSourceRoots as d, resolveComponentSourcePath as f, generateStorybookFiles as g, escapeHtml as h, importDeclaresName as i, isTrustedSourcePath as j, assertVueSourcePath as k, transformPreprocessedArtStyle as l, variantComponentNames as m, sourceWithOptionalArtTitle as n, rewriteRelativeImportStatement as o, resolveReadableArtPath as p, generateArtModule as r, loadArtStyle as s, processMuseaArtFile as t, resolveArtComponent as u, resolveScanRoots as v, createDevSessionToken as w, buildThemeConfig as x, scanArtFiles as y };
2004
1371
 
2005
- //# sourceMappingURL=report-identity-dHHBq0Ne.mjs.map
1372
+ //# sourceMappingURL=art-processing-BQ7OYXsq.mjs.map