@vizejs/vite-plugin-musea 0.730.0 → 0.732.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/a11y/index.d.mts +1 -1
  2. package/dist/a11y/index.mjs +200 -1
  3. package/dist/a11y/index.mjs.map +1 -0
  4. package/dist/apply-DIAnotZa.mjs +8 -0
  5. package/dist/apply-DIAnotZa.mjs.map +1 -0
  6. package/dist/autogen/index.mjs +1 -1
  7. package/dist/{autogen-B-N0cJbZ.mjs → autogen-D9K1av3V.mjs} +2 -2
  8. package/dist/{autogen-B-N0cJbZ.mjs.map → autogen-D9K1av3V.mjs.map} +1 -1
  9. package/dist/browser-launch-DCUbOf0d.mjs +29 -0
  10. package/dist/browser-launch-DCUbOf0d.mjs.map +1 -0
  11. package/dist/cli/index.mjs +9 -7
  12. package/dist/cli/index.mjs.map +1 -1
  13. package/dist/{gallery-DLl3pMOF.mjs → gallery-DNxzJA4V.mjs} +2 -2
  14. package/dist/{gallery-DLl3pMOF.mjs.map → gallery-DNxzJA4V.mjs.map} +1 -1
  15. package/dist/{browser-launch-L43ulIaZ.mjs → html-BW9Z7gL3.mjs} +5 -26
  16. package/dist/html-BW9Z7gL3.mjs.map +1 -0
  17. package/dist/{index-Dh4IXacU.d.mts → index-ELy0IbiZ.d.mts} +2 -2
  18. package/dist/{index-Dh4IXacU.d.mts.map → index-ELy0IbiZ.d.mts.map} +1 -1
  19. package/dist/index.d.mts +67 -3
  20. package/dist/index.d.mts.map +1 -1
  21. package/dist/index.mjs +505 -2232
  22. package/dist/index.mjs.map +1 -1
  23. package/dist/{template-D12HYJCn.mjs → module-BaxIBS_8.mjs} +39 -39
  24. package/dist/module-BaxIBS_8.mjs.map +1 -0
  25. package/dist/plugin-D2KEfrj1.mjs +2285 -0
  26. package/dist/plugin-D2KEfrj1.mjs.map +1 -0
  27. package/dist/{a11y-CR7bHK1d.mjs → report-CHUEZNZA.mjs} +3 -199
  28. package/dist/report-CHUEZNZA.mjs.map +1 -0
  29. package/dist/report-ZbXgDiN_.mjs +300 -0
  30. package/dist/report-ZbXgDiN_.mjs.map +1 -0
  31. package/dist/{options-DLFcpXwQ.mjs → report-identity-dHHBq0Ne.mjs} +502 -956
  32. package/dist/report-identity-dHHBq0Ne.mjs.map +1 -0
  33. package/dist/resolver-D8_4jxfT.mjs +812 -0
  34. package/dist/resolver-D8_4jxfT.mjs.map +1 -0
  35. package/dist/snapshot-identity-Cm-t65Kl.mjs +63 -0
  36. package/dist/snapshot-identity-Cm-t65Kl.mjs.map +1 -0
  37. package/dist/{vrt-CUz4NxKK.mjs → vrt-B8j2yfiN.mjs} +8 -363
  38. package/dist/vrt-B8j2yfiN.mjs.map +1 -0
  39. package/dist/{vrt-JoCQcFDG.d.mts → vrt-CuAg5Eow.d.mts} +2 -3
  40. package/dist/vrt-CuAg5Eow.d.mts.map +1 -0
  41. package/dist/vrt.d.mts +1 -1
  42. package/dist/vrt.mjs +3 -2
  43. package/package.json +5 -5
  44. package/dist/a11y-CR7bHK1d.mjs.map +0 -1
  45. package/dist/browser-launch-L43ulIaZ.mjs.map +0 -1
  46. package/dist/options-DLFcpXwQ.mjs.map +0 -1
  47. package/dist/template-D12HYJCn.mjs.map +0 -1
  48. package/dist/utils-BQi1club.mjs +0 -654
  49. package/dist/utils-BQi1club.mjs.map +0 -1
  50. package/dist/vrt-CUz4NxKK.mjs.map +0 -1
  51. package/dist/vrt-JoCQcFDG.d.mts.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,2291 +1,564 @@
1
- import { C as resolveTrustedSourcePath, D as loadNative, T as HttpError, _ as assertVueSourcePath, a as scanArtFiles, c as buildThemeConfig, d as createDevSessionToken, f as parseJsonBody, h as assertArtVueSourcePath, i as resolveScanRoots, m as validateDevApiRequest, n as generateStorybookFiles, o as shouldProcess, p as serializeScriptValue, r as matchGlob, t as escapeHtml, u as collectRequestBody, v as decodeUrlComponent, w as resolveUrlPathInside, x as resolveInside, y as isTrustedSourcePath } from "./utils-BQi1club.mjs";
2
- import { A as buildTokenMap, B as expandSelfTag, C as handleTokensGet, D as generateTokensHtml, E as resolveTokenPreview, F as parseScriptSetupForArt, H as variantComponentNames, I as rewriteRelativeImportStatement, L as loadArtStyle, M as scanTokenUsage, N as parseTokens, O as generateTokensMarkdown, P as generateArtModule, R as parseArtStyleRequest, S as handleTokensDelete, T as handleTokensUsage, V as resolveArtComponent, _ as handleArtAnalysis, a as attachArtReportOwner, b as handleArtPalette, c as rewriteDevGalleryAsset, d as createStaticGalleryPayload, f as joinUrlPath, g as sortedArts, h as staticPreviewId, i as assertArtReportOwnership, j as resolveReferences, k as processStyleDictionary, l as rewriteGalleryBase, m as resolveStaticIdentityRoot, o as resolveArtReportTarget, p as resolveStaticArtIdentity, r as processMuseaArtFile, s as publicBasePathFromViteBase, t as attachMuseaOptions, u as rewriteGalleryTextAssetBase, v as handleArtDocs, w as handleTokensUpdate, x as handleTokensCreate, y as handleArtSource, z as transformPreprocessedArtStyle } from "./options-DLFcpXwQ.mjs";
3
- import { a as generateGalleryGlobalsScript, i as generateDevGlobalsScript, n as generateGalleryScript, r as generateGalleryModule, t as generateGalleryBody } from "./template-D12HYJCn.mjs";
4
- import { a as UnsupportedDiffStyleError, i as MuseaVrtRunner, n as generateVrtJsonReport, r as generateVrtReport } from "./vrt-CUz4NxKK.mjs";
5
- import { t as MuseaA11yRunner } from "./a11y-CR7bHK1d.mjs";
6
- import { n as writeArtFile, t as generateArtFile } from "./autogen-B-N0cJbZ.mjs";
7
- import { createRequire } from "node:module";
8
- import fs, { existsSync } from "node:fs";
1
+ import { t as shouldApplyMuseaPlugin } from "./apply-DIAnotZa.mjs";
2
+ import { a as resolveReferences, d as tokenNative, l as scanTokenUsage, m as attachMuseaOptions, t as buildTokenMap, u as parseTokens } from "./resolver-D8_4jxfT.mjs";
3
+ import { i as resolveDiffStyle, n as generateVrtReport, r as UnsupportedDiffStyleError, t as generateVrtJsonReport } from "./report-ZbXgDiN_.mjs";
4
+ import { o as buildVariantUrl, r as normalizeVrtWorkerCount, s as computeSummary, t as escapeHtml } from "./html-BW9Z7gL3.mjs";
5
+ import { n as generateA11yHtmlReport, r as generateA11yJsonReport, t as computeA11ySummary } from "./report-CHUEZNZA.mjs";
6
+ import { n as writeArtFile, t as generateArtFile } from "./autogen-D9K1av3V.mjs";
9
7
  import path from "node:path";
10
- import { fileURLToPath } from "node:url";
11
- import { VIZE_CONFIG_FILE_ENV, loadConfig, resolveViteConfigExport } from "@vizejs/vite-plugin";
12
- import { getResolvedVizeConfigRegistration } from "@vizejs/vite-plugin/internal/config-bridge";
13
- import * as vite from "vite";
14
- import { normalizePath } from "vite";
15
- //#region src/toolbar.ts
16
- function normalizeToolbar(toolbar = []) {
17
- const ids = /* @__PURE__ */ new Set();
18
- return toolbar.map((control) => {
19
- const fail = (reason) => {
20
- throw new Error(`[musea] Invalid toolbar control ${JSON.stringify(control.id)}: ${reason}`);
21
- };
22
- if (!/^[a-zA-Z][\w-]*$/.test(control.id) || ids.has(control.id)) fail("ids must be unique and start with a letter");
23
- ids.add(control.id);
24
- if (!control.title?.trim()) fail("title is required");
25
- if (control.type !== "select" && control.type !== "toggle") fail("unknown control type");
26
- if (!Array.isArray(control.options) || control.options.length === 0) fail("options are required");
27
- if (control.type === "toggle" && control.options.length !== 2) fail("toggles need two options");
28
- const values = /* @__PURE__ */ new Set();
29
- const options = control.options.map((option) => {
30
- const item = typeof option === "string" ? {
31
- value: option,
32
- label: option
33
- } : option;
34
- if (!item || ![
35
- "string",
36
- "boolean",
37
- "number"
38
- ].includes(typeof item.value) || typeof item.value === "number" && !Number.isFinite(item.value) || typeof item.label !== "string" || !item.label.trim() || item.icon !== void 0 && typeof item.icon !== "string") fail("options require a finite primitive value and a label");
39
- if (values.has(item.value)) fail("option values must be unique");
40
- values.add(item.value);
41
- return {
42
- value: item.value,
43
- label: item.label,
44
- ...item.icon ? { icon: item.icon } : {}
45
- };
46
- });
47
- if (!values.has(control.default)) fail("default must match an option value");
48
- return {
49
- id: control.id,
50
- title: control.title,
51
- type: control.type,
52
- options,
53
- default: control.default
54
- };
55
- });
56
- }
57
- //#endregion
58
- //#region src/preview/globals.ts
59
- /** Generated only for configured controls; the default preview stays unchanged. */
60
- function generatePreviewGlobals(toolbar) {
61
- if (toolbar.length === 0) return "";
62
- return `
63
- const __museaToolbar = ${JSON.stringify(toolbar)};
64
- function __museaResolveGlobals(input) {
65
- const record = input && typeof input === 'object' ? input : {};
66
- return Object.fromEntries(__museaToolbar.map((control) => {
67
- const value = Object.hasOwn(record, control.id) ? record[control.id] : undefined;
68
- return [control.id, control.options.some((option) => option.value === value) ? value : control.default];
69
- }));
70
- }
71
- let __museaInitialGlobals;
72
- try {
73
- __museaInitialGlobals = JSON.parse(new URL(window.location.href).searchParams.get('museaGlobals'));
74
- } catch {}
75
- const __museaGlobals = __museaCreateGlobalsRef(__museaResolveGlobals(__museaInitialGlobals));
76
- function __museaUpdateGlobals(event) {
77
- if (event.origin !== window.location.origin || event.source !== window.parent) return;
78
- if (event.data?.type !== 'musea:set-globals') return;
79
- const next = __museaResolveGlobals(event.data.payload);
80
- if (__museaToolbar.some((control) => next[control.id] !== __museaGlobals.value[control.id])) {
81
- __museaGlobals.value = next;
82
- }
83
- }
84
- window.addEventListener('message', __museaUpdateGlobals);
85
- window.addEventListener('pagehide', (event) => {
86
- if (!event.persisted) window.removeEventListener('message', __museaUpdateGlobals);
87
- });
88
- `;
89
- }
90
- //#endregion
91
- //#region src/preview/addons.ts
92
- /**
93
- * Addon initialization code for Musea preview iframes.
94
- *
95
- * Contains DOM event capture, measure overlay, and message handler logic
96
- * injected into preview modules.
97
- *
98
- * Extracted from preview.ts to keep file sizes manageable.
99
- */
8
+ import fs from "node:fs";
9
+ //#region src/plugin/lazy.ts
100
10
  /**
101
- * Addon initialization code injected into preview iframe modules.
102
- * Shared between generatePreviewModule and generatePreviewModuleWithProps.
11
+ * Keep config-only Vite+ commands on a dependency-free entry path. The real
12
+ * plugin graph is loaded only after Vite invokes a Musea hook.
103
13
  */
104
- const MUSEA_ADDONS_INIT_CODE = `
105
- function __museaInitAddons(container, variantName, extraCaptureEvents = []) {
106
- const parentOrigin = window.location.origin;
107
- // === DOM event capture ===
108
- // Note: wheel and hover-style events are excluded by default because they are too noisy.
109
- const BASE_CAPTURE_EVENTS = ['click','dblclick','input','change','submit','focus','blur','keydown','keyup','mousedown','mouseup','contextmenu','pointerdown','pointerup'];
110
- const CAPTURE_EVENTS = [...new Set([
111
- ...BASE_CAPTURE_EVENTS,
112
- ...((Array.isArray(extraCaptureEvents) ? extraCaptureEvents : [])
113
- .filter((eventName) => typeof eventName === 'string')
114
- .map((eventName) => eventName.trim())
115
- .filter(Boolean))
116
- ])];
117
- for (const evt of CAPTURE_EVENTS) {
118
- container.addEventListener(evt, (e) => {
119
- // Extract raw event properties
120
- const rawEvent = {
121
- type: e.type,
122
- bubbles: e.bubbles,
123
- cancelable: e.cancelable,
124
- composed: e.composed,
125
- defaultPrevented: e.defaultPrevented,
126
- eventPhase: e.eventPhase,
127
- isTrusted: e.isTrusted,
128
- timeStamp: e.timeStamp,
129
- };
130
- // Mouse/Pointer event properties
131
- if ('clientX' in e) {
132
- rawEvent.clientX = e.clientX;
133
- rawEvent.clientY = e.clientY;
134
- rawEvent.screenX = e.screenX;
135
- rawEvent.screenY = e.screenY;
136
- rawEvent.pageX = e.pageX;
137
- rawEvent.pageY = e.pageY;
138
- rawEvent.offsetX = e.offsetX;
139
- rawEvent.offsetY = e.offsetY;
140
- rawEvent.button = e.button;
141
- rawEvent.buttons = e.buttons;
142
- rawEvent.altKey = e.altKey;
143
- rawEvent.ctrlKey = e.ctrlKey;
144
- rawEvent.metaKey = e.metaKey;
145
- rawEvent.shiftKey = e.shiftKey;
146
- }
147
- // Keyboard event properties
148
- if ('key' in e) {
149
- rawEvent.key = e.key;
150
- rawEvent.code = e.code;
151
- rawEvent.repeat = e.repeat;
152
- rawEvent.altKey = e.altKey;
153
- rawEvent.ctrlKey = e.ctrlKey;
154
- rawEvent.metaKey = e.metaKey;
155
- rawEvent.shiftKey = e.shiftKey;
156
- }
157
- // Input event properties
158
- if ('inputType' in e) {
159
- rawEvent.inputType = e.inputType;
160
- rawEvent.data = e.data;
161
- }
162
- // Wheel event properties
163
- if ('deltaX' in e) {
164
- rawEvent.deltaX = e.deltaX;
165
- rawEvent.deltaY = e.deltaY;
166
- rawEvent.deltaZ = e.deltaZ;
167
- rawEvent.deltaMode = e.deltaMode;
168
- }
169
- const payload = {
170
- name: e.type,
171
- target: e.target?.tagName,
172
- timestamp: Date.now(),
173
- source: 'dom',
174
- rawEvent,
175
- variantName
176
- };
177
- if (e.target && 'value' in e.target) {
178
- payload.value = e.target.value;
179
- }
180
- window.parent.postMessage({ type: 'musea:event', payload }, parentOrigin);
181
- }, true);
182
- }
183
-
184
- // === Message handler for parent commands ===
185
- let measureActive = false;
186
- let measureOverlay = null;
187
- let measureLabel = null;
188
-
189
- function toggleStyleById(id, enabled, css) {
190
- let el = document.getElementById(id);
191
- if (enabled) {
192
- if (!el) {
193
- el = document.createElement('style');
194
- el.id = id;
195
- el.textContent = css;
196
- document.head.appendChild(el);
197
- }
198
- } else {
199
- if (el) el.remove();
200
- }
201
- }
202
-
203
- function createMeasureOverlay() {
204
- if (measureOverlay) return;
205
- measureOverlay = document.createElement('div');
206
- measureOverlay.id = 'musea-measure-overlay';
207
- measureOverlay.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:99999;';
208
- document.body.appendChild(measureOverlay);
209
-
210
- measureLabel = document.createElement('div');
211
- measureLabel.className = 'musea-measure-label';
212
- measureLabel.style.cssText = 'position:fixed;background:#333;color:#fff;font-size:11px;padding:2px 6px;border-radius:3px;pointer-events:none;z-index:100000;display:none;';
213
- document.body.appendChild(measureLabel);
214
- }
215
-
216
- function removeMeasureOverlay() {
217
- if (measureOverlay) { measureOverlay.remove(); measureOverlay = null; }
218
- if (measureLabel) { measureLabel.remove(); measureLabel = null; }
219
- }
220
-
221
- function onMeasureMouseMove(e) {
222
- if (!measureActive || !measureOverlay) return;
223
- const el = document.elementFromPoint(e.clientX, e.clientY);
224
- if (!el || el === measureOverlay || el === measureLabel) return;
225
-
226
- const rect = el.getBoundingClientRect();
227
- const cs = getComputedStyle(el);
228
- const mt = parseFloat(cs.marginTop) || 0;
229
- const mr = parseFloat(cs.marginRight) || 0;
230
- const mb = parseFloat(cs.marginBottom) || 0;
231
- const ml = parseFloat(cs.marginLeft) || 0;
232
- const bt = parseFloat(cs.borderTopWidth) || 0;
233
- const br = parseFloat(cs.borderRightWidth) || 0;
234
- const bb = parseFloat(cs.borderBottomWidth) || 0;
235
- const blw = parseFloat(cs.borderLeftWidth) || 0;
236
- const pt = parseFloat(cs.paddingTop) || 0;
237
- const pr = parseFloat(cs.paddingRight) || 0;
238
- const pb = parseFloat(cs.paddingBottom) || 0;
239
- const pl = parseFloat(cs.paddingLeft) || 0;
240
-
241
- const cw = rect.width - blw - br - pl - pr;
242
- const ch = rect.height - bt - bb - pt - pb;
243
-
244
- measureOverlay.innerHTML = ''
245
- // Margin
246
- + '<div style="position:fixed;background:rgba(255,165,0,0.3);'
247
- + 'left:' + (rect.left - ml) + 'px;top:' + (rect.top - mt) + 'px;'
248
- + 'width:' + (rect.width + ml + mr) + 'px;height:' + mt + 'px;"></div>'
249
- + '<div style="position:fixed;background:rgba(255,165,0,0.3);'
250
- + 'left:' + (rect.left - ml) + 'px;top:' + (rect.bottom) + 'px;'
251
- + 'width:' + (rect.width + ml + mr) + 'px;height:' + mb + 'px;"></div>'
252
- + '<div style="position:fixed;background:rgba(255,165,0,0.3);'
253
- + 'left:' + (rect.left - ml) + 'px;top:' + rect.top + 'px;'
254
- + 'width:' + ml + 'px;height:' + rect.height + 'px;"></div>'
255
- + '<div style="position:fixed;background:rgba(255,165,0,0.3);'
256
- + 'left:' + rect.right + 'px;top:' + rect.top + 'px;'
257
- + 'width:' + mr + 'px;height:' + rect.height + 'px;"></div>'
258
- // Border
259
- + '<div style="position:fixed;background:rgba(255,255,0,0.3);'
260
- + 'left:' + rect.left + 'px;top:' + rect.top + 'px;'
261
- + 'width:' + rect.width + 'px;height:' + bt + 'px;"></div>'
262
- + '<div style="position:fixed;background:rgba(255,255,0,0.3);'
263
- + 'left:' + rect.left + 'px;top:' + (rect.bottom - bb) + 'px;'
264
- + 'width:' + rect.width + 'px;height:' + bb + 'px;"></div>'
265
- + '<div style="position:fixed;background:rgba(255,255,0,0.3);'
266
- + 'left:' + rect.left + 'px;top:' + (rect.top + bt) + 'px;'
267
- + 'width:' + blw + 'px;height:' + (rect.height - bt - bb) + 'px;"></div>'
268
- + '<div style="position:fixed;background:rgba(255,255,0,0.3);'
269
- + 'left:' + (rect.right - br) + 'px;top:' + (rect.top + bt) + 'px;'
270
- + 'width:' + br + 'px;height:' + (rect.height - bt - bb) + 'px;"></div>'
271
- // Padding
272
- + '<div style="position:fixed;background:rgba(144,238,144,0.3);'
273
- + 'left:' + (rect.left + blw) + 'px;top:' + (rect.top + bt) + 'px;'
274
- + 'width:' + (rect.width - blw - br) + 'px;height:' + pt + 'px;"></div>'
275
- + '<div style="position:fixed;background:rgba(144,238,144,0.3);'
276
- + 'left:' + (rect.left + blw) + 'px;top:' + (rect.bottom - bb - pb) + 'px;'
277
- + 'width:' + (rect.width - blw - br) + 'px;height:' + pb + 'px;"></div>'
278
- + '<div style="position:fixed;background:rgba(144,238,144,0.3);'
279
- + 'left:' + (rect.left + blw) + 'px;top:' + (rect.top + bt + pt) + 'px;'
280
- + 'width:' + pl + 'px;height:' + (rect.height - bt - bb - pt - pb) + 'px;"></div>'
281
- + '<div style="position:fixed;background:rgba(144,238,144,0.3);'
282
- + 'left:' + (rect.right - br - pr) + 'px;top:' + (rect.top + bt + pt) + 'px;'
283
- + 'width:' + pr + 'px;height:' + (rect.height - bt - bb - pt - pb) + 'px;"></div>'
284
- // Content
285
- + '<div style="position:fixed;background:rgba(100,149,237,0.3);'
286
- + 'left:' + (rect.left + blw + pl) + 'px;top:' + (rect.top + bt + pt) + 'px;'
287
- + 'width:' + cw + 'px;height:' + ch + 'px;"></div>';
288
-
289
- // Label
290
- measureLabel.textContent = Math.round(rect.width) + ' x ' + Math.round(rect.height);
291
- measureLabel.style.display = 'block';
292
- measureLabel.style.left = (rect.right + 8) + 'px';
293
- measureLabel.style.top = rect.top + 'px';
294
- }
295
-
296
- window.addEventListener('message', (e) => {
297
- if (e.origin !== window.location.origin) return;
298
- if (!e.data?.type?.startsWith('musea:')) return;
299
- const { type, payload } = e.data;
300
- switch (type) {
301
- case 'musea:set-background': {
302
- if (payload.pattern === 'checkerboard') {
303
- document.body.style.background = '';
304
- document.body.classList.add('musea-bg-checkerboard');
305
- } else {
306
- document.body.classList.remove('musea-bg-checkerboard');
307
- document.body.style.background = payload.color || '';
308
- }
309
- break;
310
- }
311
- case 'musea:toggle-outline': {
312
- toggleStyleById('musea-outline', payload.enabled,
313
- '* { outline: 1px solid rgba(255, 0, 0, 0.3) !important; }');
314
- break;
315
- }
316
- case 'musea:toggle-measure': {
317
- measureActive = payload.enabled;
318
- if (measureActive) {
319
- createMeasureOverlay();
320
- document.addEventListener('mousemove', onMeasureMouseMove);
321
- } else {
322
- document.removeEventListener('mousemove', onMeasureMouseMove);
323
- removeMeasureOverlay();
324
- }
325
- break;
326
- }
327
- case 'musea:set-props': {
328
- // Store props for remount - handled by preview module
329
- if (window.__museaSetProps) {
330
- window.__museaSetProps(payload.props || {});
331
- }
332
- break;
333
- }
334
- case 'musea:set-slots': {
335
- // Store slots for remount - handled by preview module
336
- if (window.__museaSetSlots) {
337
- window.__museaSetSlots(payload.slots || {});
338
- }
339
- break;
340
- }
341
- case 'musea:run-a11y': {
342
- // Run axe-core a11y test
343
- const requestId = typeof payload?.requestId === 'string' ? payload.requestId : undefined;
344
- (async () => {
345
- try {
346
- // Dynamically load axe-core from local vendor route if not already loaded
347
- if (!window.axe) {
348
- const script = document.createElement('script');
349
- const _basePath = window.__MUSEA_BASE_PATH__
350
- || location.pathname.replace(/\\/preview(?:\\/[^/]+\\.html)?$/, '');
351
- script.src = _basePath + '/vendor/axe-core.min.js';
352
- await new Promise((resolve, reject) => {
353
- script.onload = resolve;
354
- script.onerror = reject;
355
- document.head.appendChild(script);
356
- });
357
- // A load event is not proof the vendor script exists. axe-core is
358
- // an optional peer, so a static export can ship without it, and a
359
- // static host is free to answer the missing asset with an SPA
360
- // fallback: 200 plus HTML. The script tag then "loads" fine and
361
- // window.axe is still undefined, which surfaced downstream as an
362
- // opaque "cannot read properties of undefined" instead of the real
363
- // cause.
364
- if (!window.axe) {
365
- throw new Error(
366
- 'axe-core did not load from ' + script.src +
367
- ' - install axe-core so the gallery can ship it, and check that the path is served as JavaScript rather than an SPA fallback'
368
- );
369
- }
370
- }
371
- // Run axe-core on the .musea-variant container only (not the full document)
372
- const context = document.querySelector('.musea-variant') || document;
373
- const results = await window.axe.run(context, {
374
- // Run all rules without restrictions for comprehensive testing
375
- resultTypes: ['violations', 'incomplete', 'passes']
376
- });
377
- window.parent.postMessage({
378
- type: 'musea:a11y-result',
379
- payload: {
380
- requestId,
381
- violations: results.violations.map(v => ({
382
- id: v.id,
383
- impact: v.impact,
384
- description: v.description,
385
- helpUrl: v.helpUrl,
386
- nodes: v.nodes.map(n => ({
387
- html: n.html,
388
- target: n.target,
389
- failureSummary: n.failureSummary
390
- }))
391
- })),
392
- passes: results.passes.length,
393
- incomplete: results.incomplete.length
394
- }
395
- }, parentOrigin);
396
- } catch (err) {
397
- window.parent.postMessage({
398
- type: 'musea:a11y-result',
399
- payload: {
400
- requestId,
401
- error: err instanceof Error ? err.message : String(err),
402
- violations: [],
403
- passes: 0,
404
- incomplete: 0
405
- }
406
- }, parentOrigin);
407
- }
408
- })();
409
- break;
410
- }
411
- }
412
- });
413
-
414
- // Notify parent that iframe is ready
415
- window.parent.postMessage({ type: 'musea:ready', payload: {} }, parentOrigin);
416
- }
417
- `;
418
- //#endregion
419
- //#region src/preview/html.ts
420
- function generatePreviewHtml(art, variant, _basePath, viteBase) {
421
- const previewModuleUrl = `${_basePath}/preview-module?art=${encodeURIComponent(art.path)}&variant=${encodeURIComponent(variant.name)}`;
422
- const base = (viteBase || "/").replace(/\/$/, "");
423
- return `<!DOCTYPE html>
424
- <html lang="en">
425
- <head>
426
- <meta charset="UTF-8">
427
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
428
- <title>${escapeHtml(art.metadata.title)} - ${escapeHtml(variant.name)}</title>
429
- <script type="module" src="${base}/@vite/client"><\/script>
430
- <style>
431
- @layer musea-preview {
432
- *,
433
- *::before,
434
- *::after {
435
- box-sizing: border-box;
436
- }
437
- :root {
438
- --musea-preview-padding: clamp(1rem, 2vw, 1.5rem);
439
- }
440
- html, body {
441
- width: 100%;
442
- min-height: 100%;
443
- margin: 0;
444
- }
445
- body {
446
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
447
- background: #ffffff;
448
- padding: var(--musea-preview-padding);
449
- }
450
- .musea-variant {
451
- width: 100%;
452
- min-height: calc(100vh - (var(--musea-preview-padding) * 2));
453
- }
454
- .musea-error {
455
- color: #dc2626;
456
- background: #fef2f2;
457
- border: 1px solid #fecaca;
458
- border-radius: 8px;
459
- padding: 1rem;
460
- font-size: 0.875rem;
461
- max-width: 400px;
462
- }
463
- .musea-error-title {
464
- font-weight: 600;
465
- margin-bottom: 0.5rem;
466
- }
467
- .musea-error pre {
468
- font-family: monospace;
469
- font-size: 0.75rem;
470
- white-space: pre-wrap;
471
- word-break: break-all;
472
- margin-top: 0.5rem;
473
- padding: 0.5rem;
474
- background: #fff;
475
- border-radius: 4px;
476
- }
477
- .musea-loading {
478
- display: flex;
479
- align-items: center;
480
- gap: 0.75rem;
481
- color: #6b7280;
482
- font-size: 0.875rem;
483
- }
484
- .musea-spinner {
485
- width: 20px;
486
- height: 20px;
487
- border: 2px solid #e5e7eb;
488
- border-top-color: #3b82f6;
489
- border-radius: 50%;
490
- animation: musea-preview-spin 0.8s linear infinite;
491
- }
492
- }
493
- @keyframes musea-preview-spin { to { transform: rotate(360deg); } }
494
-
495
- /* Musea Addons: Checkerboard background for transparent mode */
496
- .musea-bg-checkerboard {
497
- background-image:
498
- linear-gradient(45deg, #ccc 25%, transparent 25%),
499
- linear-gradient(-45deg, #ccc 25%, transparent 25%),
500
- linear-gradient(45deg, transparent 75%, #ccc 75%),
501
- linear-gradient(-45deg, transparent 75%, #ccc 75%) !important;
502
- background-size: 20px 20px !important;
503
- background-position: 0 0, 0 10px, 10px -10px, -10px 0 !important;
504
- }
505
-
506
- /* Musea Addons: Measure label */
507
- .musea-measure-label {
508
- position: fixed;
509
- background: #333;
510
- color: #fff;
511
- font-size: 11px;
512
- padding: 2px 6px;
513
- border-radius: 3px;
514
- pointer-events: none;
515
- z-index: 100000;
516
- }
517
- </style>
518
- </head>
519
- <body>
520
- <div id="app" class="musea-variant" data-art="${escapeHtml(art.path)}" data-variant="${escapeHtml(variant.name)}">
521
- <div class="musea-loading">
522
- <div class="musea-spinner"></div>
523
- Loading component...
524
- </div>
525
- </div>
526
- <script type="module" src="${previewModuleUrl}"><\/script>
527
- </body>
528
- </html>`;
529
- }
530
- //#endregion
531
- //#region src/preview/index.ts
532
- function generatePreviewModule(art, variantComponentName, variantName, cssImports = [], previewSetup = null, vueVersion = 3, toolbar = []) {
533
- const artModuleId = `virtual:musea-art:${art.path}`;
534
- const artModuleIdLiteral = JSON.stringify(artModuleId);
535
- const variantNameLiteral = JSON.stringify(variantName);
536
- const variantComponentNameLiteral = JSON.stringify(variantComponentName);
537
- const cssImportStatements = cssImports.map((cssPath) => `import ${JSON.stringify(cssPath)};`).join("\n");
538
- const setupImport = previewSetup ? `import __museaPreviewSetup from ${JSON.stringify(previewSetup)};` : "";
539
- const globals = toolbar.length > 0;
540
- const setupCall = previewSetup ? `await __museaPreviewSetup(app${globals ? ", { globals: __museaGlobals }" : ""});` : "";
541
- const actionEvents = JSON.stringify(art.metadata.actionEvents ?? []);
542
- const legacyVue = isLegacyVueVersion(vueVersion);
543
- const vueImport = legacyVue ? `import Vue, { reactive, shallowRef${globals ? ", ref as __museaCreateGlobalsRef" : ""} } from 'vue';` : `import { createApp, reactive, shallowRef, h${globals ? ", ref as __museaCreateGlobalsRef" : ""} } from 'vue';`;
544
- const destroyCurrentApp = legacyVue ? "currentApp.$destroy();" : "currentApp.unmount();";
545
- const mountInitialApp = legacyVue ? "const app = new Vue({ render: (h) => h(VariantComponent) });" : "const app = createApp(VariantComponent);";
546
- const mountCurrentApp = legacyVue ? "mountVue2App(app);" : "app.mount(container);\n currentApp = app;";
547
- const mountHelper = legacyVue ? vue2MountHelperSnippet() : "";
548
- const remountApp = legacyVue ? vue2RemountAppSnippet() : vue3RemountAppSnippet();
549
- return `
550
- ${cssImportStatements}
551
- ${setupImport}
552
- ${vueImport}
553
- import * as artModule from ${artModuleIdLiteral};
554
-
555
- const container = document.getElementById('app');
556
-
557
- ${MUSEA_ADDONS_INIT_CODE}${generatePreviewGlobals(toolbar)}
558
-
559
- let currentApp = null;
560
- // Replace raw JSON snapshots so every literal prop name stays an own key.
561
- const propsOverride = shallowRef({});
562
- const slotsOverride = reactive({ default: '' });
563
-
564
- function renderError(title, error) {
565
- container.textContent = '';
566
- const root = document.createElement('div');
567
- root.className = 'musea-error';
568
-
569
- const titleEl = document.createElement('div');
570
- titleEl.className = 'musea-error-title';
571
- titleEl.textContent = title;
572
- root.appendChild(titleEl);
573
-
574
- const messageEl = document.createElement('div');
575
- messageEl.textContent = error instanceof Error ? error.message : String(error);
576
- root.appendChild(messageEl);
577
-
578
- const stack = error instanceof Error ? error.stack : '';
579
- if (stack) {
580
- const stackEl = document.createElement('pre');
581
- stackEl.textContent = stack;
582
- root.appendChild(stackEl);
583
- }
584
-
585
- container.appendChild(root);
586
- }
587
-
588
- ${mountHelper}
589
-
590
- window.__museaSetProps = (props) => {
591
- propsOverride.value = { ...props };
592
- };
593
-
594
- window.__museaSetSlots = (slots) => {
595
- for (const key of Object.keys(slotsOverride)) {
596
- delete slotsOverride[key];
597
- }
598
- Object.assign(slotsOverride, slots);
599
- };
600
-
601
- async function mount() {
602
- try {
603
- // Get the specific variant component
604
- const VariantComponent = artModule[${variantComponentNameLiteral}];
605
- const RawComponent = artModule.__component__;
606
-
607
- if (!VariantComponent) {
608
- throw new Error('Variant component ' + ${variantComponentNameLiteral} + ' not found in art module');
609
- }
610
-
611
- // Create and mount the app
612
- ${mountInitialApp}
613
- ${setupCall}
614
- container.innerHTML = '';
615
- container.className = 'musea-variant';
616
- ${mountCurrentApp}
617
-
618
- console.log('[musea-preview] Mounted variant:', ${variantNameLiteral});
619
- __museaInitAddons(container, ${variantNameLiteral}, ${actionEvents});
620
-
621
- // Override set-props to remount with raw component + props
622
- const TargetComponent = RawComponent || VariantComponent;
623
- window.__museaSetProps = (props) => {
624
- propsOverride.value = { ...props };
625
- remountWithProps(TargetComponent);
626
- };
627
- window.__museaSetSlots = (slots) => {
628
- for (const key of Object.keys(slotsOverride)) {
629
- delete slotsOverride[key];
630
- }
631
- Object.assign(slotsOverride, slots);
632
- remountWithProps(TargetComponent);
633
- };
634
- } catch (error) {
635
- console.error('[musea-preview] Failed to mount:', error);
636
- renderError('Failed to render component', error);
637
- }
638
- }
639
-
640
- async function remountWithProps(Component) {
641
- if (currentApp) {
642
- ${destroyCurrentApp}
643
- }
644
- ${remountApp}
645
- ${setupCall}
646
- container.innerHTML = '';
647
- ${mountCurrentApp}
648
- }
649
-
650
- mount();
651
- `;
652
- }
653
- function isLegacyVueVersion(version) {
654
- return version === .11 || version === 1 || version === 2 || version === "2.7" || version === "legacy";
655
- }
656
- function vue2MountHelperSnippet() {
657
- return `function mountVue2App(app) {
658
- container.innerHTML = '';
659
- const mountPoint = document.createElement('div');
660
- container.appendChild(mountPoint);
661
- app.$mount(mountPoint);
662
- currentApp = app;
663
- }`;
664
- }
665
- function vue2RemountAppSnippet() {
666
- return `const app = new Vue({
667
- render(h) {
668
- const slotFns = {};
669
- const children = [];
670
- for (const [name, content] of Object.entries(slotsOverride)) {
671
- if (!content) continue;
672
- const slot = () => [h('span', String(content))];
673
- slotFns[name] = slot;
674
- if (name === 'default') children.push(...slot());
675
- }
676
- return h(Component, { props: { ...propsOverride.value }, scopedSlots: slotFns }, children);
677
- }
678
- });`;
679
- }
680
- function vue3RemountAppSnippet() {
681
- return `const app = createApp({
682
- setup() {
683
- return () => {
684
- const slotFns = {};
685
- for (const [name, content] of Object.entries(slotsOverride)) {
686
- if (content) slotFns[name] = () => h('span', String(content));
687
- }
688
- return h(Component, { ...propsOverride.value }, slotFns);
689
- };
690
- }
691
- });`;
692
- }
693
- function generatePreviewModuleWithProps(art, variantComponentName, variantName, propsOverride, cssImports = [], previewSetup = null, vueVersion = 3, toolbar = []) {
694
- const artModuleId = `virtual:musea-art:${art.path}`;
695
- const artModuleIdLiteral = JSON.stringify(artModuleId);
696
- const variantNameLiteral = JSON.stringify(variantName);
697
- const variantComponentNameLiteral = JSON.stringify(variantComponentName);
698
- const propsJson = JSON.stringify(propsOverride);
699
- const cssImportStatements = cssImports.map((cssPath) => `import ${JSON.stringify(cssPath)};`).join("\n");
700
- const setupImport = previewSetup ? `import __museaPreviewSetup from ${JSON.stringify(previewSetup)};` : "";
701
- const globals = toolbar.length > 0;
702
- const setupCall = previewSetup ? `await __museaPreviewSetup(app${globals ? ", { globals: __museaGlobals }" : ""});` : "";
703
- const actionEvents = JSON.stringify(art.metadata.actionEvents ?? []);
704
- const legacyVue = isLegacyVueVersion(vueVersion);
705
- const vueImport = legacyVue ? `import Vue${globals ? ", { ref as __museaCreateGlobalsRef }" : ""} from 'vue';` : `import { createApp, h${globals ? ", ref as __museaCreateGlobalsRef" : ""} } from 'vue';`;
706
- const wrappedComponent = legacyVue ? `const WrappedComponent = {
707
- render(h) {
708
- return h(VariantComponent, { props: propsOverride });
709
- }
710
- };` : `const WrappedComponent = {
711
- render() {
712
- return h(VariantComponent, propsOverride);
713
- }
714
- };`;
715
- const appCreate = legacyVue ? "const app = new Vue(WrappedComponent);" : "const app = createApp(WrappedComponent);";
716
- const appMount = legacyVue ? "const mountPoint = document.createElement('div');\n container.appendChild(mountPoint);\n app.$mount(mountPoint);" : "app.mount(container);";
717
- return `
718
- ${cssImportStatements}
719
- ${setupImport}
720
- ${vueImport}
721
- import * as artModule from ${artModuleIdLiteral};
722
-
723
- const container = document.getElementById('app');
724
- const propsOverride = JSON.parse(${JSON.stringify(propsJson)});
725
-
726
- ${MUSEA_ADDONS_INIT_CODE}${generatePreviewGlobals(toolbar)}
727
-
728
- function renderError(title, error) {
729
- container.textContent = '';
730
- const root = document.createElement('div');
731
- root.className = 'musea-error';
732
-
733
- const titleEl = document.createElement('div');
734
- titleEl.className = 'musea-error-title';
735
- titleEl.textContent = title;
736
- root.appendChild(titleEl);
737
-
738
- const messageEl = document.createElement('div');
739
- messageEl.textContent = error instanceof Error ? error.message : String(error);
740
- root.appendChild(messageEl);
741
-
742
- container.appendChild(root);
743
- }
744
-
745
- async function mount() {
746
- try {
747
- const VariantComponent = artModule[${variantComponentNameLiteral}];
748
- if (!VariantComponent) {
749
- throw new Error('Variant component ' + ${variantComponentNameLiteral} + ' not found');
750
- }
751
-
752
- ${wrappedComponent}
753
-
754
- ${appCreate}
755
- ${setupCall}
756
- container.innerHTML = '';
757
- container.className = 'musea-variant';
758
- ${appMount}
759
- console.log('[musea-preview] Mounted variant with props override:', ${variantNameLiteral});
760
- __museaInitAddons(container, ${variantNameLiteral}, ${actionEvents});
761
- } catch (error) {
762
- console.error('[musea-preview] Failed to mount:', error);
763
- renderError('Failed to render', error);
764
- }
765
- }
766
-
767
- mount();
768
- `;
769
- }
770
- //#endregion
771
- //#region src/preview-module-id.ts
772
- /** Keep the final colon delimiter unambiguous while retaining ordinary module IDs. */
773
- function previewModuleId(artPath, variantName) {
774
- return `virtual:musea-preview:${artPath}:${variantName.replaceAll("%", "%25").replaceAll(":", "%3A")}`;
775
- }
776
- //#endregion
777
- //#region src/middleware-response.ts
778
- /** Both transformed and fallback previews keep the same response contract. */
779
- function sendPreviewModule(response, code) {
780
- response.setHeader("Content-Type", "application/javascript");
781
- response.setHeader("Cache-Control", "no-cache");
782
- response.end(code);
783
- }
784
- function sendPreviewError(response, error) {
785
- response.statusCode = 500;
786
- response.end(error instanceof Error ? error.message : String(error));
787
- }
788
- /** Art fallbacks retain their existing headers and bound generation failures. */
789
- function sendArtModuleFallback(response, generate) {
790
- try {
791
- const code = generate();
792
- response.setHeader("Content-Type", "application/javascript");
793
- response.end(code);
794
- } catch (error) {
795
- sendPreviewError(response, error);
796
- }
797
- }
798
- //#endregion
799
- //#region src/server-middleware.ts
800
- const moduleDir$2 = path.dirname(fileURLToPath(import.meta.url));
801
- const galleryAssetMimeTypes = {
802
- ".js": "application/javascript",
803
- ".css": "text/css",
804
- ".svg": "image/svg+xml",
805
- ".png": "image/png",
806
- ".ico": "image/x-icon",
807
- ".woff2": "font/woff2",
808
- ".woff": "font/woff"
809
- };
810
- function resolveGalleryDistDir$1() {
811
- return path.resolve(moduleDir$2, "gallery");
812
- }
813
- function resolveGallerySourceDir() {
814
- return path.resolve(moduleDir$2, "../gallery");
815
- }
816
- function toViteFsPath(filePath) {
817
- return encodeURI(`/@fs${filePath.split(path.sep).join("/")}`);
818
- }
819
- function ignorePackedGalleryAssetTransforms(html, basePath) {
820
- const assetPrefix = `${basePath.replace(/\/+$/, "")}/assets/`;
821
- return html.replace(/<script\b[^>]*>/giu, (tag) => {
822
- const type = /\btype\s*=\s*(["'])module\1/iu.exec(tag);
823
- const src = /\bsrc\s*=\s*(["'])([^"']+)\1/iu.exec(tag);
824
- if (!type || !src || !src[2].startsWith(assetPrefix) || /\bvite-ignore\b/iu.test(tag)) return tag;
825
- return tag.replace(/^<script\b/iu, "<script vite-ignore");
826
- });
827
- }
828
- async function tryLoadSourceGalleryHtml(devServer, url, basePath, devSessionToken, themeConfig, tokenPreviewConfig, toolbar) {
829
- const gallerySourceDir = resolveGallerySourceDir();
830
- const indexHtmlPath = path.join(gallerySourceDir, "index.html");
831
- try {
832
- await fs.promises.access(indexHtmlPath);
833
- } catch {
834
- return null;
835
- }
836
- const sourceEntryPath = toViteFsPath(path.join(gallerySourceDir, "main.ts"));
837
- let html = await fs.promises.readFile(indexHtmlPath, "utf-8");
838
- html = html.replace("src=\"./main.ts\"", `src="${sourceEntryPath}"`);
839
- html = html.replace("</head>", `<script>${generateDevGlobalsScript(basePath, devSessionToken, themeConfig, tokenPreviewConfig, toolbar)}<\/script></head>`);
840
- return devServer.transformIndexHtml(url, html);
841
- }
842
- async function generateFallbackGalleryHtml(basePath, devSessionToken, themeConfig, tokenPreviewConfig, toolbar) {
843
- const { generateGalleryHtml } = await import("./gallery-DLl3pMOF.mjs");
844
- return generateGalleryHtml(basePath, devSessionToken, themeConfig, tokenPreviewConfig, toolbar);
845
- }
846
- async function serveGalleryAsset(galleryDistDir, requestUrl, res, basePath = "/__musea__") {
847
- try {
848
- const filePath = resolveUrlPathInside(galleryDistDir, requestUrl, "asset path");
849
- if (!(await fs.promises.stat(filePath)).isFile()) return false;
850
- const content = await fs.promises.readFile(filePath);
851
- const ext = path.extname(filePath);
852
- res.setHeader("Content-Type", galleryAssetMimeTypes[ext] || "application/octet-stream");
853
- res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
854
- res.end(rewriteDevGalleryAsset(content, filePath, basePath));
855
- return true;
856
- } catch (error) {
857
- if (error instanceof HttpError) {
858
- res.statusCode = error.status;
859
- res.end(error.message);
860
- return true;
861
- }
862
- return false;
863
- }
864
- }
865
- function registerMiddleware(devServer, ctx) {
866
- const { basePath, devSessionToken, themeConfig, tokenPreviewConfig, toolbar, artFiles } = ctx;
867
- devServer.middlewares.use(basePath, async (req, res, next) => {
868
- const url = req.url || "/";
869
- if (url === "/" || url === "/index.html" || url.startsWith("/tokens") || url.startsWith("/component/") || url.startsWith("/tests")) {
870
- const galleryDistDir = resolveGalleryDistDir$1();
871
- const indexHtmlPath = path.join(galleryDistDir, "index.html");
872
- try {
873
- await fs.promises.access(indexHtmlPath);
874
- let html = rewriteGalleryBase(await fs.promises.readFile(indexHtmlPath, "utf-8"), basePath);
875
- html = html.replace("</head>", `<script>${generateDevGlobalsScript(basePath, devSessionToken, themeConfig, tokenPreviewConfig, toolbar)}<\/script></head>`);
876
- res.setHeader("Content-Type", "text/html");
877
- res.end(await devServer.transformIndexHtml(url, ignorePackedGalleryAssetTransforms(html, basePath)));
878
- return;
879
- } catch {
880
- const sourceHtml = await tryLoadSourceGalleryHtml(devServer, url, basePath, devSessionToken, themeConfig, tokenPreviewConfig, toolbar);
881
- if (sourceHtml) {
882
- res.setHeader("Content-Type", "text/html");
883
- res.end(sourceHtml);
884
- return;
885
- }
886
- const html = await generateFallbackGalleryHtml(basePath, devSessionToken, themeConfig, tokenPreviewConfig, toolbar);
887
- res.setHeader("Content-Type", "text/html");
888
- res.end(html);
889
- return;
890
- }
891
- }
892
- if (url.startsWith("/assets/")) {
893
- if (await serveGalleryAsset(resolveGalleryDistDir$1(), url, res, basePath)) return;
894
- }
895
- next();
896
- });
897
- devServer.middlewares.use(`${basePath}/vendor/axe-core.min.js`, async (_req, res, _next) => {
898
- try {
899
- const axeCorePath = createRequire(import.meta.url).resolve("axe-core/axe.min.js");
900
- const content = await fs.promises.readFile(axeCorePath, "utf-8");
901
- res.setHeader("Content-Type", "application/javascript");
902
- res.setHeader("Cache-Control", "public, max-age=86400");
903
- res.end(content);
904
- } catch {
905
- res.statusCode = 404;
906
- res.end("axe-core not installed");
907
- }
908
- });
909
- devServer.middlewares.use(`${basePath}/preview-module`, async (req, res, _next) => {
910
- const url = new URL(req.url || "", `http://localhost`);
911
- const artPath = url.searchParams.get("art");
912
- const variantName = url.searchParams.get("variant");
913
- if (!artPath || !variantName) {
914
- res.statusCode = 400;
915
- res.end("Missing art or variant parameter");
916
- return;
917
- }
918
- const art = artFiles.get(artPath);
919
- if (!art) {
920
- res.statusCode = 404;
921
- res.end("Art not found");
922
- return;
923
- }
924
- const variant = art.variants.find((v) => v.name === variantName);
925
- if (!variant) {
926
- res.statusCode = 404;
927
- res.end("Variant not found");
928
- return;
929
- }
930
- let variantComponentName;
931
- try {
932
- variantComponentName = variantComponentNames(art.variants).get(variant.name);
933
- } catch (error) {
934
- sendPreviewError(res, error);
935
- return;
936
- }
937
- const moduleCode = generatePreviewModule(art, variantComponentName, variant.name, ctx.resolvedPreviewCss, ctx.resolvedPreviewSetup, 3, ctx.toolbar);
14
+ function musea(options = {}) {
15
+ let runtimePlugins;
16
+ let loading;
17
+ const load = async () => {
18
+ if (runtimePlugins) return runtimePlugins;
19
+ const pending = loading ??= import("./plugin-D2KEfrj1.mjs").then(({ musea: createRuntimePlugins }) => createRuntimePlugins(options));
938
20
  try {
939
- const result = await devServer.transformRequest(previewModuleId(artPath, variantName));
940
- if (result) {
941
- sendPreviewModule(res, result.code);
942
- return;
943
- }
944
- } catch {}
945
- sendPreviewModule(res, moduleCode);
946
- });
947
- devServer.middlewares.use(`${basePath}/preview`, async (req, res, _next) => {
948
- const url = new URL(req.url || "", `http://localhost`);
949
- const artPath = url.searchParams.get("art");
950
- const variantName = url.searchParams.get("variant");
951
- if (!artPath || !variantName) {
952
- res.statusCode = 400;
953
- res.end("Missing art or variant parameter");
954
- return;
21
+ return runtimePlugins = await pending;
22
+ } finally {
23
+ if (!runtimePlugins) loading = void 0;
955
24
  }
956
- const art = artFiles.get(artPath);
957
- if (!art) {
958
- res.statusCode = 404;
959
- res.end("Art not found");
960
- return;
961
- }
962
- const variant = art.variants.find((v) => v.name === variantName);
963
- if (!variant) {
964
- res.statusCode = 404;
965
- res.end("Variant not found");
966
- return;
967
- }
968
- const config = devServer.config;
969
- const html = generatePreviewHtml(art, variant, basePath, config.base);
970
- res.setHeader("Content-Type", "text/html");
971
- res.end(html);
972
- });
973
- devServer.middlewares.use(`${basePath}/art`, async (req, res, next) => {
974
- const url = new URL(req.url || "", "http://localhost");
975
- let artPath;
976
- try {
977
- artPath = decodeUrlComponent(url.pathname.slice(1), "art path");
978
- } catch (error) {
979
- if (error instanceof HttpError) {
980
- res.statusCode = error.status;
981
- res.end(error.message);
982
- return;
25
+ };
26
+ const callHook = async (pluginIndex, hookName, context, args) => {
27
+ const plugin = (await load())[pluginIndex];
28
+ const hook = plugin && Reflect.get(plugin, hookName);
29
+ const handler = typeof hook === "function" ? hook : hook && typeof hook === "object" ? Reflect.get(hook, "handler") : void 0;
30
+ if (typeof handler !== "function") return void 0;
31
+ return Reflect.apply(handler, context, args);
32
+ };
33
+ return [attachMuseaOptions({
34
+ name: "vite-plugin-musea",
35
+ enforce: "pre",
36
+ api: { vizePrecompileInputOwner: Object.freeze({
37
+ version: 1,
38
+ forConfig(config) {
39
+ const api = runtimePlugins?.[0]?.api;
40
+ const owner = api && Reflect.get(api, "vizePrecompileInputOwner");
41
+ const forConfig = owner && Reflect.get(owner, "forConfig");
42
+ return typeof forConfig === "function" ? Reflect.apply(forConfig, owner, [config]) : void 0;
983
43
  }
984
- throw error;
985
- }
986
- if (!artPath) {
987
- next();
988
- return;
989
- }
990
- const art = artFiles.get(artPath);
991
- if (!art) {
992
- res.statusCode = 404;
993
- res.end("Art not found: " + artPath);
994
- return;
995
- }
996
- try {
997
- const virtualId = `virtual:musea-art:${artPath}`;
998
- const result = await devServer.transformRequest(virtualId);
999
- if (result) sendPreviewModule(res, result.code);
1000
- else sendArtModuleFallback(res, () => generateArtModule(art, artPath, {
1001
- root: devServer.config.root,
1002
- scanRoots: ctx.scanRoots
1003
- }));
1004
- } catch (err) {
1005
- console.error("[musea] Failed to transform art module:", err);
1006
- sendArtModuleFallback(res, () => generateArtModule(art, artPath, {
1007
- root: devServer.config.root,
1008
- scanRoots: ctx.scanRoots
1009
- }));
1010
- }
1011
- });
1012
- }
1013
- //#endregion
1014
- //#region src/api-routes/post-handlers.ts
1015
- /** POST /api/preview-with-props */
1016
- function handlePreviewWithProps(ctx, body, res, sendJson, sendError) {
1017
- try {
1018
- const { artPath: reqArtPath, variantName, props: propsOverride } = parseJsonBody(body);
1019
- const art = ctx.artFiles.get(reqArtPath);
1020
- if (!art) {
1021
- sendError("Art not found", 404);
1022
- return;
1023
- }
1024
- const variant = art.variants.find((v) => v.name === variantName);
1025
- if (!variant) {
1026
- sendError("Variant not found", 404);
1027
- return;
1028
- }
1029
- const moduleCode = generatePreviewModuleWithProps(art, variantComponentNames(art.variants).get(variant.name), variant.name, propsOverride, ctx.resolvedPreviewCss, ctx.resolvedPreviewSetup, 3, ctx.toolbar);
1030
- res.setHeader("Content-Type", "application/javascript");
1031
- res.end(moduleCode);
1032
- } catch (e) {
1033
- if (e instanceof HttpError) {
1034
- sendError(e.message, e.status);
1035
- return;
1036
- }
1037
- sendError(e instanceof Error ? e.message : String(e));
1038
- }
1039
- }
1040
- /** POST /api/generate */
1041
- async function handleGenerate(ctx, body, sendJson, sendError) {
1042
- try {
1043
- const { componentPath: reqComponentPath, options: autogenOptions } = parseJsonBody(body);
1044
- if (typeof reqComponentPath !== "string") {
1045
- sendError("Missing required field: componentPath", 400);
1046
- return;
1047
- }
1048
- if (!reqComponentPath.toLowerCase().endsWith(".vue")) {
1049
- sendError("componentPath must be a .vue file", 400);
1050
- return;
1051
- }
1052
- const componentPath = resolveInside(ctx.config.root, reqComponentPath, "componentPath");
1053
- assertVueSourcePath(componentPath, "componentPath");
1054
- const { generateArtFile: genArt } = await import("./autogen/index.mjs");
1055
- const result = await genArt(componentPath, autogenOptions);
1056
- sendJson({
1057
- generated: true,
1058
- componentName: result.componentName,
1059
- variants: result.variants,
1060
- artFileContent: result.artFileContent
1061
- });
1062
- } catch (e) {
1063
- if (e instanceof HttpError) {
1064
- sendError(e.message, e.status);
1065
- return;
44
+ }) },
45
+ apply(_config, environment) {
46
+ return shouldApplyMuseaPlugin(environment);
47
+ },
48
+ config(config, environment) {
49
+ return callHook(0, "config", this, [config, environment]);
50
+ },
51
+ options(input) {
52
+ return callHook(0, "options", this, [input]);
53
+ },
54
+ configResolved(config) {
55
+ return callHook(0, "configResolved", this, [config]);
56
+ },
57
+ configureServer(server) {
58
+ return callHook(0, "configureServer", this, [server]);
59
+ },
60
+ buildStart(input) {
61
+ return callHook(0, "buildStart", this, [input]);
62
+ },
63
+ resolveId(source, importer, resolveOptions) {
64
+ return callHook(0, "resolveId", this, [
65
+ source,
66
+ importer,
67
+ resolveOptions
68
+ ]);
69
+ },
70
+ load(id) {
71
+ return callHook(0, "load", this, [id]);
72
+ },
73
+ generateBundle(outputOptions, bundle, isWrite) {
74
+ return callHook(0, "generateBundle", this, [
75
+ outputOptions,
76
+ bundle,
77
+ isWrite
78
+ ]);
79
+ },
80
+ transform(code, id, transformOptions) {
81
+ return callHook(0, "transform", this, [
82
+ code,
83
+ id,
84
+ transformOptions
85
+ ]);
86
+ },
87
+ handleHotUpdate(context) {
88
+ return callHook(0, "handleHotUpdate", this, [context]);
1066
89
  }
1067
- sendError(e instanceof Error ? e.message : String(e));
1068
- }
1069
- }
1070
- /** POST /api/run-vrt */
1071
- async function handleRunVrt(ctx, body, sendJson, sendError) {
1072
- try {
1073
- const { artPath, updateSnapshots } = parseJsonBody(body);
1074
- if (artPath !== void 0 && typeof artPath !== "string") throw new HttpError("artPath must be a string", 400);
1075
- if (artPath !== void 0 && !ctx.artFiles.has(artPath)) throw new HttpError("Art not found", 404);
1076
- const { MuseaVrtRunner, generateVrtJsonReport, generateVrtReport } = await import("./vrt.mjs");
1077
- const { a11y: _a11y, ...configured } = ctx.vrt ?? {};
1078
- const snapshotDir = path.resolve(ctx.config.root, configured.snapshotDir ?? ".vize/snapshots");
1079
- const reportDir = path.resolve(ctx.config.root, ".vize/reports");
1080
- const projectRoot = ctx.projectRoot ?? ctx.config.root;
1081
- const reportTarget = artPath === void 0 ? void 0 : resolveArtReportTarget(artPath, ctx.artFiles.keys(), projectRoot, reportDir);
1082
- if (reportTarget) await assertArtReportOwnership(reportTarget, projectRoot);
1083
- const runner = new MuseaVrtRunner({
1084
- ...configured,
1085
- capture: {
1086
- ...configured.capture,
1087
- waitForPreviewReady: true
1088
- },
1089
- snapshotDir,
1090
- projectRoot,
1091
- previewBasePath: publicBasePathFromViteBase(ctx.config.base, ctx.basePath)
1092
- });
1093
- const baseUrl = `http://localhost:${ctx.getDevServerPort()}`;
1094
- let artsToTest = Array.from(ctx.artFiles.values());
1095
- if (artPath) artsToTest = artsToTest.filter((a) => a.path === artPath);
1096
- const { results, summary } = await (async () => {
1097
- await runner.start();
1098
- try {
1099
- const results = await runner.runTests(artsToTest, baseUrl, { updateSnapshots });
1100
- return {
1101
- results,
1102
- summary: runner.getSummary(results)
1103
- };
1104
- } finally {
1105
- await runner.stop();
1106
- }
1107
- })();
1108
- const jsonReportPath = reportTarget?.jsonReportPath ?? path.join(reportDir, "vrt-report.json");
1109
- const htmlReportPath = reportTarget?.htmlReportPath ?? path.join(reportDir, "vrt-report.html");
1110
- const jsonReport = generateVrtJsonReport(results, summary);
1111
- await fs.promises.mkdir(reportDir, { recursive: true });
1112
- await fs.promises.writeFile(jsonReportPath, reportTarget ? attachArtReportOwner(jsonReport, reportTarget) : jsonReport, "utf-8");
1113
- await fs.promises.writeFile(htmlReportPath, generateVrtReport(results, summary), "utf-8");
1114
- sendJson({
1115
- success: true,
1116
- summary,
1117
- results: results.map((r) => ({
1118
- artPath: r.artPath,
1119
- variantName: r.variantName,
1120
- viewport: r.viewport.name,
1121
- passed: r.passed,
1122
- isNew: r.isNew,
1123
- diffPercentage: r.diffPercentage,
1124
- snapshotPath: r.snapshotPath,
1125
- currentPath: r.currentPath,
1126
- diffPath: r.diffPath,
1127
- diffStyle: r.diffStyle,
1128
- error: r.error
1129
- })),
1130
- artifacts: {
1131
- reportDir,
1132
- htmlReportPath,
1133
- jsonReportPath,
1134
- snapshotDir,
1135
- currentDir: path.join(snapshotDir, "current"),
1136
- diffDir: path.join(snapshotDir, "diff")
1137
- }
1138
- });
1139
- } catch (e) {
1140
- if (e instanceof HttpError) {
1141
- sendError(e.message, e.status);
1142
- return;
90
+ }, options), {
91
+ name: "vite-plugin-musea:style-post-transform",
92
+ transform(code, id, transformOptions) {
93
+ return callHook(1, "transform", this, [
94
+ code,
95
+ id,
96
+ transformOptions
97
+ ]);
1143
98
  }
1144
- sendError(e instanceof Error ? e.message : String(e));
1145
- }
99
+ }];
1146
100
  }
1147
101
  //#endregion
1148
- //#region src/api-routes/index.ts
102
+ //#region src/root-vrt.ts
1149
103
  /**
1150
- * Create the API middleware handler for the Musea gallery.
1151
- *
1152
- * Returns a Connect-compatible middleware function that handles all
1153
- * `/api/...` sub-routes under the configured basePath.
104
+ * Backward-compatible root export whose implementation is loaded on first VRT
105
+ * operation. New code can continue to import the dedicated `./vrt` subpath.
1154
106
  */
1155
- function createApiMiddleware(ctx) {
1156
- return async (req, res, next) => {
1157
- const sendJson = (data, status = 200) => {
1158
- res.statusCode = status;
1159
- res.setHeader("Content-Type", "application/json");
1160
- res.end(JSON.stringify(data));
107
+ var MuseaVrtRunner = class {
108
+ sourceOptions;
109
+ options;
110
+ capture;
111
+ comparison;
112
+ runtime;
113
+ loading;
114
+ constructor(options = {}) {
115
+ resolveDiffStyle(options.comparison?.diffStyle);
116
+ if (options.capture?.beforeCapture !== void 0 && typeof options.capture.beforeCapture !== "function") throw new TypeError("Musea capture.beforeCapture must be a function.");
117
+ this.sourceOptions = options;
118
+ this.options = {
119
+ previewBasePath: options.previewBasePath ?? "/__musea__",
120
+ snapshotDir: options.snapshotDir ?? ".vize/snapshots",
121
+ threshold: options.threshold ?? .1,
122
+ viewports: options.viewports ?? [{
123
+ width: 1280,
124
+ height: 720,
125
+ name: "desktop"
126
+ }, {
127
+ width: 375,
128
+ height: 667,
129
+ name: "mobile"
130
+ }],
131
+ workers: normalizeVrtWorkerCount(options.workers),
132
+ launchOptions: options.launchOptions ?? {}
1161
133
  };
1162
- const sendError = (message, status = 500) => {
1163
- sendJson({ error: message }, status);
134
+ this.capture = {
135
+ beforeCapture: options.capture?.beforeCapture,
136
+ animations: options.capture?.animations ?? "disabled",
137
+ reducedMotion: options.capture?.reducedMotion ?? "no-preference",
138
+ caret: options.capture?.caret ?? "hide",
139
+ fullPage: options.capture?.fullPage ?? false,
140
+ waitForNetwork: options.capture?.waitForNetwork ?? true,
141
+ waitForPreviewReady: options.capture?.waitForPreviewReady ?? false,
142
+ settleTime: options.capture?.settleTime ?? 100,
143
+ waitSelector: options.capture?.waitSelector ?? ".musea-variant",
144
+ hideElements: options.capture?.hideElements ?? [],
145
+ maskElements: options.capture?.maskElements ?? [],
146
+ maskColor: options.capture?.maskColor ?? "#ff00ff"
1164
147
  };
1165
- const readBody = () => collectRequestBody(req, ctx.apiBodyLimit ?? 1048576);
1166
- const url = req.url || "/";
148
+ this.comparison = options.comparison ?? {};
149
+ }
150
+ async loadRuntime() {
151
+ if (this.runtime) return this.runtime;
152
+ const pending = this.loading ??= import("./vrt.mjs").then(({ MuseaVrtRunner: Runtime }) => new Runtime(this.sourceOptions));
1167
153
  try {
1168
- const requestError = validateDevApiRequest(req, ctx.devSessionToken);
1169
- if (requestError) {
1170
- sendError(requestError.message, requestError.status);
1171
- return;
1172
- }
1173
- if (url === "/arts" && req.method === "GET") {
1174
- sendJson(sortedArts(ctx.artFiles.values()));
1175
- return;
1176
- }
1177
- if (url === "/tokens/usage" && req.method === "GET") {
1178
- await handleTokensUsage(ctx, sendJson);
1179
- return;
1180
- }
1181
- if (url === "/tokens" && req.method === "GET") {
1182
- await handleTokensGet(ctx, sendJson);
1183
- return;
1184
- }
1185
- if (url === "/tokens" && req.method === "POST") {
1186
- await handleTokensCreate(ctx, readBody, sendJson, sendError);
1187
- return;
1188
- }
1189
- if (url === "/tokens" && req.method === "PUT") {
1190
- await handleTokensUpdate(ctx, readBody, sendJson, sendError);
1191
- return;
1192
- }
1193
- if (url === "/tokens" && req.method === "DELETE") {
1194
- await handleTokensDelete(ctx, readBody, sendJson, sendError);
1195
- return;
1196
- }
1197
- if (url?.startsWith("/arts/") && req.method === "PUT") {
1198
- const sourceMatch = url.slice(6).match(/^(.+)\/source$/);
1199
- if (sourceMatch) {
1200
- const artPath = decodeUrlComponent(sourceMatch[1], "art path");
1201
- if (!ctx.artFiles.get(artPath)) {
1202
- sendError("Art not found", 404);
1203
- return;
1204
- }
1205
- const safeArtPath = resolveInside(ctx.config.root, artPath, "art path");
1206
- assertArtVueSourcePath(safeArtPath);
1207
- const { source } = parseJsonBody(await readBody());
1208
- if (typeof source !== "string") {
1209
- sendError("Missing required field: source", 400);
1210
- return;
1211
- }
1212
- await fs.promises.writeFile(safeArtPath, source, "utf-8");
1213
- await ctx.processArtFile(safeArtPath);
1214
- sendJson({ success: true });
1215
- return;
1216
- }
1217
- next();
1218
- return;
1219
- }
1220
- if (url?.startsWith("/arts/") && req.method === "GET") {
1221
- const rest = url.slice(6);
1222
- const sourceMatch = rest.match(/^(.+)\/source$/);
1223
- const paletteMatch = rest.match(/^(.+)\/palette$/);
1224
- const analysisMatch = rest.match(/^(.+)\/analysis$/);
1225
- const docsMatch = rest.match(/^(.+)\/docs$/);
1226
- if (sourceMatch) {
1227
- await handleArtSource(ctx, sourceMatch, sendJson, sendError);
1228
- return;
1229
- }
1230
- if (paletteMatch) {
1231
- await handleArtPalette(ctx, paletteMatch, sendJson, sendError);
1232
- return;
1233
- }
1234
- if (analysisMatch) {
1235
- await handleArtAnalysis(ctx, analysisMatch, sendJson, sendError);
1236
- return;
1237
- }
1238
- if (docsMatch) {
1239
- await handleArtDocs(ctx, docsMatch, sendJson, sendError);
1240
- return;
1241
- }
1242
- const artPath = decodeUrlComponent(rest, "art path");
1243
- const art = ctx.artFiles.get(artPath);
1244
- if (art) sendJson(art);
1245
- else sendError("Art not found", 404);
1246
- return;
1247
- }
1248
- if (req.method === "POST") {
1249
- const body = await readBody();
1250
- if (url === "/preview-with-props") {
1251
- handlePreviewWithProps(ctx, body, res, sendJson, sendError);
1252
- return;
1253
- }
1254
- if (url === "/generate") {
1255
- await handleGenerate(ctx, body, sendJson, sendError);
1256
- return;
1257
- }
1258
- if (url === "/run-vrt") {
1259
- await handleRunVrt(ctx, body, sendJson, sendError);
1260
- return;
1261
- }
1262
- }
1263
- next();
1264
- } catch (e) {
1265
- if (e instanceof HttpError) {
1266
- sendError(e.message, e.status);
1267
- return;
1268
- }
1269
- sendError(e instanceof Error ? e.message : String(e));
154
+ return this.runtime = await pending;
155
+ } finally {
156
+ if (!this.runtime) this.loading = void 0;
1270
157
  }
1271
- };
1272
- }
1273
- //#endregion
1274
- //#region src/manifest.ts
1275
- /**
1276
- * Generate the virtual manifest module code containing all art file metadata.
1277
- */
1278
- function generateManifestModule(artFiles) {
1279
- const arts = sortedArts(artFiles.values());
1280
- return `export const arts = ${JSON.stringify(arts, null, 2)};`;
1281
- }
1282
- //#endregion
1283
- //#region src/art-variant-sfc.ts
1284
- /**
1285
- * Compile an `<art>` variant through the SFC pipeline.
1286
- *
1287
- * Variants used to be emitted as `template:` strings for Vue's runtime
1288
- * compiler, which never sees the SFC pipeline. Any template expression relying
1289
- * on SFC-time compilation therefore failed at render time — most importantly
1290
- * TypeScript, even though `.art.vue` files are authored with
1291
- * `<script setup lang="ts">` (#3857).
1292
- *
1293
- * Compiling the raw template with the template compiler is not enough: it
1294
- * leaves TypeScript in place *and* its identifier prefixer gives up on TS
1295
- * syntax, so `items[0]!.isValid` stays unprefixed and throws at runtime. Only
1296
- * the SFC pipeline handles both, which is what the issue asks for — the variant
1297
- * is compiled the same way the enclosing SFC is:
1298
- *
1299
- * :disabled="items[0]!.isValid" -> disabled: $setup.items[0].isValid
1300
- * @u="(f: File | null) => …" -> onU: (f) => $setup.file = f
1301
- *
1302
- * The generated module render function receives setup state through Vue's
1303
- * proxy-unwrapped `$setup` argument, so refs intentionally do not retain an
1304
- * explicit `.value` access in this output mode.
1305
- */
1306
- /**
1307
- * Rebase the art file's `<script setup>` for a virtual module.
1308
- *
1309
- * A variant compiles into a virtual module, and a relative specifier cannot be
1310
- * resolved from one — the art module rebases its own imports for exactly this
1311
- * reason, and the variant needs the same treatment or every relative import in
1312
- * an art file fails to resolve.
1313
- */
1314
- function rebaseScriptSetup(scriptSetup, artDir) {
1315
- if (!scriptSetup.trim()) return "";
1316
- const parsed = parseScriptSetupForArt(scriptSetup);
1317
- return [...parsed.imports.map((statement) => rewriteRelativeImportStatement(statement, artDir)), ...parsed.setupBody].join("\n").trim();
1318
- }
1319
- /**
1320
- * Build the synthetic SFC source for one variant.
1321
- *
1322
- * The art file's own `<script setup>` becomes the variant's setup block, so
1323
- * bindings resolve exactly as they do in the authored file, and `lang="ts"` is
1324
- * carried over so the pipeline strips TypeScript from template expressions.
1325
- */
1326
- function buildVariantSfcSource(art, variantTemplate, variantName, options = {}) {
1327
- if (options.sharedBindings && options.sharedBindings.names.length > 0) {
1328
- const { moduleId, names } = options.sharedBindings;
1329
- const escapedShared = variantName.replace(/"/g, "&quot;");
1330
- return `<script setup lang="ts">\n` + (options.componentImportPath && options.componentBindingName && !names.includes(options.componentBindingName) ? `import ${options.componentBindingName} from ${JSON.stringify(options.componentImportPath)}\n` : "") + `import { ${names.join(", ")} } from ${JSON.stringify(moduleId)}\n<\/script>\n<template><div data-variant="${escapedShared}">${variantTemplate}</div></template>\n`;
1331
158
  }
1332
- const scriptSetup = rebaseScriptSetup(options.scriptSetup ?? art.scriptSetupContent ?? "", path.dirname(options.artFilePath ?? art.path));
1333
- return `${`<script setup lang="ts">\n${`${options.componentImportPath && options.componentBindingName ? `import ${options.componentBindingName} from ${JSON.stringify(options.componentImportPath)}\n` : ""}${scriptSetup.trim()}`.trim()}\n<\/script>\n`}<template><div data-variant="${variantName.replace(/"/g, "&quot;")}">${variantTemplate}</div></template>\n`;
1334
- }
1335
- /**
1336
- * Compile a variant to a self-contained ES module exporting the component.
1337
- *
1338
- * Each variant compiles to its own module because `compileSfc` emits a complete
1339
- * module with its own `export default` and imports; concatenating several into
1340
- * one art module would redeclare bindings and collide on the default export.
1341
- */
1342
- function compileVariantSfc(art, variantTemplate, variantName, filename, options = {}) {
1343
- const component = resolveArtComponent(art, filename, options.parsedScriptSetup ?? null, {
1344
- root: options.root,
1345
- scanRoots: options.scanRoots
1346
- });
1347
- const source = buildVariantSfcSource(art, expandSelfTag(variantTemplate, component.componentTagName), variantName, {
1348
- scriptSetup: options.scriptSetup,
1349
- componentImportPath: component.componentImportPath,
1350
- componentBindingName: component.componentBindingName,
1351
- artFilePath: filename,
1352
- sharedBindings: options.sharedBindings
1353
- });
1354
- const result = loadNative().compileSfc(source, { filename });
1355
- return {
1356
- code: result.code ?? "",
1357
- errors: (result.errors ?? []).map((error) => typeof error === "string" ? error : error.message ?? JSON.stringify(error))
1358
- };
1359
- }
159
+ getPreviewUrl(baseUrl, artPath, variantName) {
160
+ if (this.sourceOptions.previewUrls !== void 0) {
161
+ const variants = Object.hasOwn(this.sourceOptions.previewUrls, artPath) ? this.sourceOptions.previewUrls[artPath] : void 0;
162
+ const url = variants && Object.hasOwn(variants, variantName) ? variants[variantName] : void 0;
163
+ if (!url) throw new Error(`Hosted preview not found: ${artPath}/${variantName}`);
164
+ return url;
165
+ }
166
+ return buildVariantUrl(baseUrl, artPath, variantName, this.options.previewBasePath);
167
+ }
168
+ getBrowser() {
169
+ return this.runtime?.getBrowser() ?? null;
170
+ }
171
+ getOptions() {
172
+ return this.options;
173
+ }
174
+ getCapture() {
175
+ return this.capture;
176
+ }
177
+ getComparison() {
178
+ return this.comparison;
179
+ }
180
+ getHostedNavigation() {
181
+ return this.sourceOptions.hostedNavigation;
182
+ }
183
+ async init(trust) {
184
+ return (await this.loadRuntime()).init(trust);
185
+ }
186
+ async getSnapshotName(art, variantName, viewport) {
187
+ return (await this.loadRuntime()).getSnapshotName(art, variantName, viewport);
188
+ }
189
+ async close() {
190
+ return this.runtime?.close();
191
+ }
192
+ async start() {
193
+ return this.init();
194
+ }
195
+ async stop() {
196
+ return this.close();
197
+ }
198
+ async runAllTests(artFiles, baseUrl) {
199
+ return (await this.loadRuntime()).runAllTests(artFiles, baseUrl);
200
+ }
201
+ async runTests(artFiles, baseUrl, options) {
202
+ return (await this.loadRuntime()).runTests(artFiles, baseUrl, options);
203
+ }
204
+ async captureAndCompare(art, variantName, viewport, baseUrl) {
205
+ return (await this.loadRuntime()).captureAndCompare(art, variantName, viewport, baseUrl);
206
+ }
207
+ async createPage(viewport) {
208
+ return (await this.loadRuntime()).createPage(viewport);
209
+ }
210
+ async updateBaselines(results) {
211
+ return (await this.loadRuntime()).updateBaselines(results);
212
+ }
213
+ async approveResults(results, pattern) {
214
+ return (await this.loadRuntime()).approveResults(results, pattern);
215
+ }
216
+ async cleanOrphans(artFiles) {
217
+ return (await this.loadRuntime()).cleanOrphans(artFiles);
218
+ }
219
+ getSummary(results) {
220
+ return this.runtime?.getSummary(results) ?? computeSummary(results, 0);
221
+ }
222
+ };
1360
223
  //#endregion
1361
- //#region src/art-shared-setup.ts
224
+ //#region src/tokens/generator.ts
1362
225
  /**
1363
- * One shared `<script setup>` instance for an art file's variants.
1364
- *
1365
- * `scriptSetupIsolated: false` opts an art file out of per-variant isolation:
1366
- * every variant sees the same setup instance, so state written in one variant is
1367
- * visible in the next. Compiling each variant as its own SFC (#3857) would give
1368
- * each one its own setup and silently drop that, so the shared case hoists the
1369
- * setup into this module and the variants import its bindings instead of
1370
- * declaring them.
226
+ * Token documentation generators for Style Dictionary integration.
1371
227
  *
1372
- * A dedicated module rather than the art module itself, because the art module
1373
- * imports the variants — routing the shared state through it would make that a
1374
- * cycle.
228
+ * Generates HTML, Markdown, and JSON documentation from parsed token categories,
229
+ * and provides the main processStyleDictionary orchestrator function.
1375
230
  */
1376
- /**
1377
- * The binding names a variant SFC should import from the shared module.
1378
- *
1379
- * `<script setup>` resolves template identifiers from its own bindings, and an
1380
- * import is a binding, so importing each name by hand is what makes the shared
1381
- * state reachable from the variant's template.
1382
- */
1383
- function sharedBindingNames(parsed) {
1384
- return [...new Set(parsed.returnNames)].filter((name) => /^[A-Za-z_$][\w$]*$/.test(name));
1385
- }
1386
- function generateSharedSetupModule(art, filePath) {
1387
- const parsed = parseSharedScriptSetup(art);
1388
- if (!parsed) return "export {};\n";
1389
- const artDir = path.dirname(filePath);
1390
- const imports = parsed.imports.map((statement) => rewriteRelativeImportStatement(statement, artDir)).join("\n");
1391
- const names = sharedBindingNames(parsed);
1392
- return [
1393
- imports,
1394
- parsed.setupBody.join("\n"),
1395
- names.length > 0 ? `export { ${names.join(", ")} };` : "export {};",
1396
- ""
1397
- ].join("\n");
231
+ const SAFE_CSS_COLOR_PATTERN = /^(?:#[0-9a-fA-F]{3,8}|(?:rgb|hsl)a?\(\s*[-+.\d,%\s/]+\)|(?:oklch|oklab|lab|lch)\(\s*[-+.\d,%\s/]+\))$/;
232
+ const DANGEROUS_PROTOCOL_PATTERN = /\b(javascript|vbscript):/gi;
233
+ function escapeTokenText(value) {
234
+ return escapeHtml(value).replace(DANGEROUS_PROTOCOL_PATTERN, "$1&#58;");
1398
235
  }
1399
- function parseSharedScriptSetup(art) {
1400
- if (!art.scriptSetupContent) return null;
1401
- return parseScriptSetupForArt(art.scriptSetupContent);
236
+ function safeCssColor(value, type) {
237
+ if (typeof value !== "string") return null;
238
+ const trimmed = value.trim();
239
+ return (type === "color" || trimmed.startsWith("#") || trimmed.startsWith("rgb") || trimmed.startsWith("hsl")) && SAFE_CSS_COLOR_PATTERN.test(trimmed) ? trimmed : null;
1402
240
  }
1403
- //#endregion
1404
- //#region src/plugin/inline-art-query.ts
1405
- /** Consume only the custom block already registered as this instance's inline Art. */
1406
- function loadInlineArtCustomBlock(state, id) {
1407
- if (!state.inlineArt) return null;
1408
- const queryStart = id.indexOf("?");
1409
- if (queryStart === -1) return null;
1410
- const requestPath = id.slice(0, queryStart);
1411
- const file = requestPath.startsWith("/@fs/") ? requestPath.slice(4) : requestPath;
1412
- if (!file.endsWith(".vue") || file.endsWith(".art.vue")) return null;
1413
- const query = new URLSearchParams(id.slice(queryStart + 1));
1414
- if (query.getAll("vue").length !== 1 || query.get("vue") !== "" || query.getAll("type").length !== 1 || query.get("type") !== "art" || query.getAll("index").length !== 1) return null;
1415
- const indexText = query.get("index");
1416
- if (!/^(?:0|[1-9]\d*)$/.test(indexText)) return null;
1417
- const index = Number(indexText);
1418
- if (!Number.isSafeInteger(index)) return null;
1419
- const art = state.artFiles.get(file);
1420
- if (!art?.isInline || art.path !== file || art.componentPath !== file || art.inlineArtBlockIndex !== index || !isTrustedSourcePath(state.getConfigRoot(), state.getScanRoots(), file)) return null;
1421
- return "export default {};\n";
1422
- }
1423
- //#endregion
1424
- //#region src/plugin/virtual.ts
1425
241
  /**
1426
- * Virtual module handling for the Musea Vite plugin.
1427
- *
1428
- * Contains `resolveId`, `load`, and `handleHotUpdate` hooks that
1429
- * manage virtual modules for gallery, manifest, preview, and art files.
1430
- */
1431
- const VIRTUAL_MUSEA_PREFIX = "\0musea:";
1432
- const VIRTUAL_GALLERY = "\0musea-gallery";
1433
- const VIRTUAL_MANIFEST = "\0musea-manifest";
1434
- /**
1435
- * Recover a variant name from a virtual module id.
1436
- *
1437
- * `generateArtModule` percent-encodes it, so a hand-written import with an
1438
- * invalid escape still falls back to the raw text instead of throwing a
1439
- * `URIError` out of `load`.
242
+ * Generate HTML documentation for tokens.
1440
243
  */
1441
- function decodeVariantName(encoded) {
1442
- try {
1443
- return decodeURIComponent(encoded);
1444
- } catch {
1445
- return encoded;
1446
- }
1447
- }
1448
- function createResolveId(state) {
1449
- return function resolveId(id) {
1450
- const root = state.getConfigRoot();
1451
- const styleRequest = parseArtStyleRequest(id);
1452
- if (styleRequest && state.artFiles.has(styleRequest.filePath)) return id.startsWith("\0") ? id : `\0${id}`;
1453
- if (id === "\0musea-gallery") return VIRTUAL_GALLERY;
1454
- if (id === "\0musea-manifest") return VIRTUAL_MANIFEST;
1455
- if (id.startsWith("virtual:musea-preview:")) return "\0musea-preview:" + id.slice(22);
1456
- if (id.startsWith("virtual:musea-variant:")) return "\0musea-variant:" + id.slice(22) + "?musea-virtual";
1457
- if (id.startsWith("virtual:musea-shared:")) return "\0musea-shared:" + id.slice(21) + "?musea-virtual";
1458
- if (id.startsWith("virtual:musea-art:")) {
1459
- const artPath = id.slice(18);
1460
- if (state.artFiles.has(artPath)) return "\0musea-art:" + artPath + "?musea-virtual";
1461
- }
1462
- if (id.endsWith(".art.vue")) {
1463
- const resolved = path.resolve(root, id);
1464
- if (state.artFiles.has(resolved)) return VIRTUAL_MUSEA_PREFIX + resolved + "?musea-virtual";
1465
- }
1466
- if (state.inlineArt && id.endsWith(".vue") && !id.endsWith(".art.vue")) {
1467
- const resolved = path.resolve(root, id);
1468
- if (state.artFiles.has(resolved)) return VIRTUAL_MUSEA_PREFIX + resolved + "?musea-virtual";
1469
- }
1470
- return null;
244
+ function generateTokensHtml(categories) {
245
+ const renderToken = (name, token) => {
246
+ const color = safeCssColor(token.value, token.type);
247
+ return `
248
+ <div class="token">
249
+ <div class="token-preview">
250
+ ${color ? `<div class="color-swatch" style="background: ${color}"></div>` : ""}
251
+ </div>
252
+ <div class="token-info">
253
+ <div class="token-name">${escapeTokenText(name)}</div>
254
+ <div class="token-value">${escapeTokenText(String(token.value))}</div>
255
+ ${token.description ? `<div class="token-description">${escapeTokenText(token.description)}</div>` : ""}
256
+ </div>
257
+ </div>
258
+ `;
1471
259
  };
1472
- }
1473
- function createLoad(state) {
1474
- return function load(id) {
1475
- const inlineArtBlock = loadInlineArtCustomBlock(state, id);
1476
- if (inlineArtBlock !== null) return inlineArtBlock;
1477
- const styleRequest = parseArtStyleRequest(id);
1478
- if (styleRequest) return loadArtStyle(state.artFiles.get(styleRequest.filePath), styleRequest);
1479
- if (id === "\0musea-gallery") return generateGalleryModule(state.basePath);
1480
- if (id === "\0musea-manifest") return generateManifestModule(state.artFiles);
1481
- if (id.startsWith("\0musea-preview:")) {
1482
- const rest = id.slice(15);
1483
- const lastColonIndex = rest.lastIndexOf(":");
1484
- if (lastColonIndex !== -1) {
1485
- const artPath = rest.slice(0, lastColonIndex);
1486
- const variantName = decodeVariantName(rest.slice(lastColonIndex + 1));
1487
- const art = state.artFiles.get(artPath);
1488
- if (art) {
1489
- const variantComponentName = variantComponentNames(art.variants).get(variantName);
1490
- if (!variantComponentName) return null;
1491
- return generatePreviewModule(art, variantComponentName, variantName, state.resolvedPreviewCss, state.resolvedPreviewSetup, state.getVueVersion(), state.toolbar);
1492
- }
1493
- }
1494
- }
1495
- if (id.startsWith("\0musea-shared:")) {
1496
- const artPath = id.slice(14).replace(/\?musea-virtual$/, "");
1497
- const art = state.artFiles.get(artPath);
1498
- if (art) return generateSharedSetupModule(art, artPath);
1499
- }
1500
- if (id.startsWith("\0musea-variant:")) {
1501
- const rest = id.slice(15).replace(/\?musea-virtual$/, "");
1502
- const lastColonIndex = rest.lastIndexOf(":");
1503
- if (lastColonIndex !== -1) {
1504
- const artPath = rest.slice(0, lastColonIndex);
1505
- const variantName = decodeVariantName(rest.slice(lastColonIndex + 1));
1506
- const art = state.artFiles.get(artPath);
1507
- const variant = art?.variants.find((candidate) => candidate.name === variantName);
1508
- if (art && variant) {
1509
- const parsedScriptSetup = art.scriptSetupContent ? parseScriptSetupForArt(art.scriptSetupContent) : null;
1510
- const shared = art.scriptSetupIsolated === false && parsedScriptSetup ? {
1511
- moduleId: `virtual:musea-shared:${artPath}`,
1512
- names: sharedBindingNames(parsedScriptSetup)
1513
- } : void 0;
1514
- const compiled = compileVariantSfc(art, variant.template, variant.name, artPath, {
1515
- scriptSetup: art.scriptSetupContent,
1516
- parsedScriptSetup,
1517
- root: state.getConfigRoot(),
1518
- scanRoots: state.getScanRoots(),
1519
- sharedBindings: shared
1520
- });
1521
- if (compiled.errors.length > 0) throw new Error(`Failed to compile <art> variant "${variantName}" in ${artPath}:\n${compiled.errors.join("\n")}`);
1522
- if (!compiled.code) throw new Error(`The compiler produced no code for <art> variant "${variantName}" in ${artPath}.`);
1523
- return compiled.code;
1524
- }
1525
- }
1526
- }
1527
- if (id.startsWith("\0musea-art:")) {
1528
- const artPath = id.slice(11).replace(/\?musea-virtual$/, "");
1529
- const art = state.artFiles.get(artPath);
1530
- if (art) return generateArtModule(art, artPath, {
1531
- root: state.getConfigRoot(),
1532
- scanRoots: state.getScanRoots(),
1533
- vueVersion: state.getVueVersion()
1534
- });
1535
- }
1536
- if (id.startsWith("\0musea:")) {
1537
- const realPath = id.slice(7).replace(/\?musea-virtual$/, "");
1538
- const art = state.artFiles.get(realPath);
1539
- if (art) return generateArtModule(art, realPath, {
1540
- root: state.getConfigRoot(),
1541
- scanRoots: state.getScanRoots(),
1542
- vueVersion: state.getVueVersion()
1543
- });
1544
- }
1545
- return null;
260
+ const renderCategory = (category, level = 2) => {
261
+ const heading = `h${Math.min(level, 6)}`;
262
+ let html = `<${heading}>${escapeTokenText(category.name)}</${heading}>`;
263
+ html += "<div class=\"tokens-grid\">";
264
+ for (const [name, token] of Object.entries(category.tokens)) html += renderToken(name, token);
265
+ html += "</div>";
266
+ if (category.subcategories) for (const sub of category.subcategories) html += renderCategory(sub, level + 1);
267
+ return html;
1546
268
  };
1547
- }
1548
- function createHandleHotUpdate(state) {
1549
- return async function handleHotUpdate(ctx) {
1550
- const { file } = ctx;
1551
- if (file.endsWith(".art.vue") && state.artFiles.has(file)) {
1552
- await state.processArtFile(file);
1553
- return artHotUpdateModules(state, file, ctx.modules);
1554
- }
1555
- if (state.inlineArt && file.endsWith(".vue") && !file.endsWith(".art.vue") && state.artFiles.has(file)) {
1556
- await state.processArtFile(file);
1557
- return artHotUpdateModules(state, file, ctx.modules);
1558
- }
1559
- };
1560
- }
1561
- function artHotUpdateModules(state, file, sourceModules) {
1562
- const modules = new Set(sourceModules);
1563
- const graph = state.getServer()?.moduleGraph;
1564
- if (!graph) return [...modules];
1565
- const exactIds = new Set([
1566
- `${VIRTUAL_MUSEA_PREFIX}${file}?musea-virtual`,
1567
- `\0musea-art:${file}?musea-virtual`,
1568
- `\0musea-shared:${file}?musea-virtual`
1569
- ]);
1570
- const derivedPrefixes = [
1571
- `\0musea-variant:${file}:`,
1572
- `\0musea-preview:${file}:`,
1573
- `\0${file}.__musea_style_`
1574
- ];
1575
- for (const [id, module] of graph.idToModuleMap) if (exactIds.has(id) || derivedPrefixes.some((prefix) => id.startsWith(prefix))) modules.add(module);
1576
- return [...modules];
1577
- }
1578
- //#endregion
1579
- //#region src/plugin/apply.ts
1580
- function shouldApplyMuseaPlugin(env) {
1581
- return (env.command === "serve" || env.command === "build") && env.mode !== "test";
1582
- }
1583
- //#endregion
1584
- //#region src/plugin/watch.ts
1585
- function createMuseaWatchTargets(files) {
1586
- return [...new Set(files)];
1587
- }
1588
- function watchMuseaArtFiles(watcher, files) {
1589
- const targets = createMuseaWatchTargets(files);
1590
- if (targets.length === 0) return;
1591
- watcher.add(targets);
1592
- }
1593
- //#endregion
1594
- //#region src/plugin/vue-alias.ts
1595
- const require = createRequire(import.meta.url);
1596
- function createVueRuntimeCompilerAlias(options = {}) {
1597
- return {
1598
- find: /^vue$/,
1599
- replacement: resolveVueRuntimeCompiler(options)
1600
- };
1601
- }
1602
- function resolveVueRuntimeCompiler(options) {
1603
- if (options.runtimeCompiler) return normalizeRuntimeCompilerOverride(options.runtimeCompiler, options.root);
1604
- const root = options.root ?? process.cwd();
1605
- const projectRequire = createRequire(path.join(root, "package.json"));
1606
- try {
1607
- return projectRequire.resolve("vue/dist/vue.esm-bundler.js");
1608
- } catch {}
1609
- try {
1610
- return require.resolve("vue/dist/vue.esm-bundler.js");
1611
- } catch {
1612
- return "vue/dist/vue.esm-bundler.js";
1613
- }
1614
- }
1615
- function normalizeRuntimeCompilerOverride(value, root) {
1616
- if (path.isAbsolute(value) || !value.startsWith(".")) return value;
1617
- return path.resolve(root ?? process.cwd(), value);
1618
- }
1619
- //#endregion
1620
- //#region src/plugin/storybook-inputs.ts
1621
- function isStorybookTsxInput(filePath) {
1622
- return /\.(?:stories|story)\.tsx$/i.test(filePath);
1623
- }
1624
- async function scanStorybookTsxInputs(root, include, exclude) {
1625
- const files = /* @__PURE__ */ new Set();
1626
- const visitedDirs = /* @__PURE__ */ new Set();
1627
- async function scan(dir) {
1628
- const resolvedDir = path.resolve(dir);
1629
- if (visitedDirs.has(resolvedDir)) return;
1630
- visitedDirs.add(resolvedDir);
1631
- let entries;
1632
- try {
1633
- entries = await fs.promises.readdir(resolvedDir, { withFileTypes: true });
1634
- } catch {
1635
- return;
1636
- }
1637
- for (const entry of entries) {
1638
- const fullPath = path.join(resolvedDir, entry.name);
1639
- if (isExcluded(fullPath, entry.name, exclude, root)) continue;
1640
- if (entry.isDirectory()) await scan(fullPath);
1641
- else if (entry.isFile() && isStorybookTsxInput(entry.name) && shouldProcess(fullPath, include, exclude, root)) files.add(fullPath);
1642
- }
1643
- }
1644
- for (const scanRoot of resolveScanRoots(root, include)) await scan(scanRoot);
1645
- return [...files].sort();
1646
- }
1647
- async function assertNoUnsupportedStorybookTsxInputs(root, include, exclude) {
1648
- const files = await scanStorybookTsxInputs(root, include, exclude);
1649
- if (files.length > 0) throw new Error(formatUnsupportedStorybookTsxInputError(root, files));
1650
- }
1651
- function formatUnsupportedStorybookTsxInputError(root, files) {
1652
- return [
1653
- "[musea] Storybook TSX files matched by include are not supported as Musea art inputs yet.",
1654
- "Remove *.stories.tsx from musea.include or migrate those stories to .art.vue files.",
1655
- "Matched files:",
1656
- `${files.slice(0, 5).map((file) => ` - ${relativePath(root, file)}`).join("\n")}${files.length > 5 ? `\n ... and ${files.length - 5} more` : ""}`
1657
- ].join("\n");
1658
- }
1659
- function isExcluded(filePath, name, exclude, root) {
1660
- return exclude.some((pattern) => matchesPathPattern(filePath, pattern, root) || matchGlob(name, pattern));
1661
- }
1662
- function matchesPathPattern(filePath, pattern, root) {
1663
- return matchGlob(path.isAbsolute(pattern) ? path.resolve(filePath) : path.relative(root, filePath), pattern);
1664
- }
1665
- function relativePath(root, filePath) {
1666
- return path.relative(root, filePath).split(path.sep).join("/");
1667
- }
1668
- //#endregion
1669
- //#region src/static-gallery-shell.ts
1670
- const moduleDir$1 = path.dirname(fileURLToPath(import.meta.url));
1671
- function joinFileName(...parts) {
1672
- return parts.filter(Boolean).join("/");
1673
- }
1674
- async function emitGalleryShell(emitFile, staticRoot, ctx, payload, galleryDistDir = resolveGalleryDistDir()) {
1675
- if (!galleryDistDir) {
1676
- const html = injectStaticGlobals(generateStaticFallbackGalleryHtml(ctx.basePath), ctx, payload);
1677
- emitFile({
1678
- type: "asset",
1679
- fileName: joinFileName(staticRoot, "index.html"),
1680
- source: html
1681
- });
1682
- return;
1683
- }
1684
- for (const filePath of await collectFiles(galleryDistDir)) {
1685
- const relative = path.relative(galleryDistDir, filePath).split(path.sep).join("/");
1686
- const target = joinFileName(staticRoot, relative);
1687
- const content = await fs.promises.readFile(filePath);
1688
- if (relative === "index.html") emitFile({
1689
- type: "asset",
1690
- fileName: target,
1691
- source: injectStaticGlobals(rewriteGalleryBase(content.toString("utf-8"), ctx.basePath), ctx, payload)
1692
- });
1693
- else emitFile({
1694
- type: "asset",
1695
- fileName: target,
1696
- source: rewriteGalleryTextAssetBase(content, relative, ctx.basePath)
1697
- });
1698
- }
1699
- }
1700
- function injectStaticGlobals(html, ctx, payload) {
1701
- const script = `<script>${generateGalleryGlobalsScript({
1702
- basePath: ctx.basePath,
1703
- staticPreviews: payload.previews,
1704
- themeConfig: ctx.themeConfig,
1705
- tokenPreviewConfig: ctx.tokenPreviewConfig,
1706
- toolbar: ctx.toolbar
1707
- })}<\/script>`;
1708
- return html.includes("</head>") ? html.replace("</head>", `${script}</head>`) : `${script}${html}`;
1709
- }
1710
- function generateStaticFallbackGalleryHtml(basePath) {
1711
269
  return `<!DOCTYPE html>
1712
270
  <html lang="en">
1713
271
  <head>
1714
272
  <meta charset="UTF-8">
1715
273
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
1716
- <title>Musea - Component Gallery</title>
1717
- <style>html,body{min-height:100%;margin:0}body{font-family:system-ui,sans-serif}</style>
274
+ <title>Design Tokens - Musea</title>
275
+ <style>
276
+ :root {
277
+ --musea-bg: #0d0d0d;
278
+ --musea-bg-secondary: #1a1815;
279
+ --musea-text: #e6e9f0;
280
+ --musea-text-muted: #7b8494;
281
+ --musea-accent: #a34828;
282
+ --musea-border: #3a3530;
283
+ }
284
+ * { box-sizing: border-box; margin: 0; padding: 0; }
285
+ body {
286
+ font-family: 'Inter', -apple-system, sans-serif;
287
+ background: var(--musea-bg);
288
+ color: var(--musea-text);
289
+ line-height: 1.6;
290
+ padding: 2rem;
291
+ }
292
+ h1 { margin-bottom: 2rem; color: var(--musea-accent); }
293
+ h2 { margin: 2rem 0 1rem; padding-bottom: 0.5rem; border-bottom: 1px solid var(--musea-border); }
294
+ h3, h4, h5, h6 { margin: 1.5rem 0 0.75rem; }
295
+ .tokens-grid {
296
+ display: grid;
297
+ grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
298
+ gap: 1rem;
299
+ margin-bottom: 1.5rem;
300
+ }
301
+ .token {
302
+ background: var(--musea-bg-secondary);
303
+ border: 1px solid var(--musea-border);
304
+ border-radius: 8px;
305
+ padding: 1rem;
306
+ display: flex;
307
+ gap: 1rem;
308
+ align-items: center;
309
+ }
310
+ .token-preview {
311
+ flex-shrink: 0;
312
+ width: 48px;
313
+ height: 48px;
314
+ display: flex;
315
+ align-items: center;
316
+ justify-content: center;
317
+ }
318
+ .color-swatch {
319
+ width: 48px;
320
+ height: 48px;
321
+ border-radius: 8px;
322
+ border: 1px solid var(--musea-border);
323
+ }
324
+ .token-info {
325
+ flex: 1;
326
+ min-width: 0;
327
+ }
328
+ .token-name {
329
+ font-weight: 600;
330
+ font-family: 'JetBrains Mono', monospace;
331
+ font-size: 0.875rem;
332
+ }
333
+ .token-value {
334
+ color: var(--musea-text-muted);
335
+ font-family: 'JetBrains Mono', monospace;
336
+ font-size: 0.75rem;
337
+ word-break: break-all;
338
+ }
339
+ .token-description {
340
+ color: var(--musea-text-muted);
341
+ font-size: 0.75rem;
342
+ margin-top: 0.25rem;
343
+ }
344
+ </style>
1718
345
  </head>
1719
- <body>${generateGalleryBody(basePath)}
1720
-
1721
- <script type="module">${generateGalleryScript(basePath)}
1722
- <\/script>
346
+ <body>
347
+ <h1>Design Tokens</h1>
348
+ ${categories.map((cat) => renderCategory(cat)).join("")}
1723
349
  </body>
1724
350
  </html>`;
1725
351
  }
1726
- function resolveGalleryDistDir() {
1727
- return [path.join(moduleDir$1, "gallery"), path.resolve(moduleDir$1, "../dist/gallery")].find((candidate) => fs.existsSync(path.join(candidate, "index.html"))) ?? null;
352
+ /**
353
+ * Generate Markdown documentation for tokens.
354
+ */
355
+ function generateTokensMarkdown(categories) {
356
+ return tokenNative().generateDesignTokensMarkdown(categories, (/* @__PURE__ */ new Date()).toISOString());
1728
357
  }
1729
- async function collectFiles(dir) {
1730
- const entries = await fs.promises.readdir(dir, { withFileTypes: true });
1731
- const files = [];
1732
- for (const entry of entries) {
1733
- const filePath = path.join(dir, entry.name);
1734
- if (entry.isDirectory()) files.push(...await collectFiles(filePath));
1735
- else files.push(filePath);
358
+ /**
359
+ * Style Dictionary plugin for Musea.
360
+ * Parses tokens and generates documentation in the specified format.
361
+ */
362
+ async function processStyleDictionary(config) {
363
+ const categories = await parseTokens(config.tokensPath);
364
+ const outputDir = config.outputDir ?? ".vize/tokens";
365
+ const outputFormat = config.outputFormat ?? "html";
366
+ await fs.promises.mkdir(outputDir, { recursive: true });
367
+ let content;
368
+ let filename;
369
+ switch (outputFormat) {
370
+ case "html":
371
+ content = generateTokensHtml(categories);
372
+ filename = "tokens.html";
373
+ break;
374
+ case "markdown":
375
+ content = generateTokensMarkdown(categories);
376
+ filename = "tokens.md";
377
+ break;
378
+ default:
379
+ content = JSON.stringify({ categories }, null, 2);
380
+ filename = "tokens.json";
1736
381
  }
1737
- return files;
382
+ const outputPath = path.join(outputDir, filename);
383
+ await fs.promises.writeFile(outputPath, content, "utf-8");
384
+ console.log(`[musea] Generated token documentation: ${outputPath}`);
385
+ return {
386
+ categories,
387
+ metadata: {
388
+ name: path.basename(config.tokensPath),
389
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString()
390
+ }
391
+ };
1738
392
  }
1739
393
  //#endregion
1740
- //#region src/static-export.ts
1741
- const MUSEA_STATIC_BUILD_ENV = "VIZE_MUSEA_STATIC_BUILD";
1742
- const VIRTUAL_STATIC_RUNTIME = "virtual:musea-static-runtime";
1743
- const RESOLVED_STATIC_RUNTIME = "\0musea-static-runtime";
1744
- const STATIC_RUNTIME_INPUT_NAME = "musea-static-runtime";
1745
- const STATIC_USER_INPUT_NAME = "musea-static-entry";
1746
- function isMuseaStaticBuild() {
1747
- return process.env[MUSEA_STATIC_BUILD_ENV] === "1";
1748
- }
1749
- function shouldEnableMuseaStaticBuild(command) {
1750
- return isMuseaStaticBuild() || command === "build";
1751
- }
1752
- function shouldEmitMuseaStaticGallery(command, storybookCompat) {
1753
- if (isMuseaStaticBuild()) return true;
1754
- return shouldEnableMuseaStaticBuild(command) && !storybookCompat;
1755
- }
1756
- function museaStaticBuildInput(input) {
1757
- const entries = {};
1758
- if (typeof input === "string") entries[STATIC_USER_INPUT_NAME] = input;
1759
- else if (Array.isArray(input)) input.forEach((value, index) => {
1760
- entries[`${STATIC_USER_INPUT_NAME}-${index + 1}`] = value;
1761
- });
1762
- else if (input) Object.assign(entries, input);
1763
- entries[STATIC_RUNTIME_INPUT_NAME] = VIRTUAL_STATIC_RUNTIME;
1764
- return entries;
1765
- }
1766
- function applyMuseaStaticBuildInput(options) {
1767
- if (!isMuseaStaticBuild()) return null;
1768
- options.input = museaStaticBuildInput(options.input);
1769
- return null;
1770
- }
1771
- function museaStaticBuildConfig(input) {
1772
- return { build: { rollupOptions: { input: museaStaticBuildInput(input) } } };
1773
- }
1774
- function resolveStaticRuntimeId(id) {
1775
- return id === "virtual:musea-static-runtime" ? RESOLVED_STATIC_RUNTIME : null;
1776
- }
1777
- function loadStaticRuntimeModule(id, artFiles, identityRoot) {
1778
- if (id !== RESOLVED_STATIC_RUNTIME) return null;
1779
- return `
1780
- const loaders = { ${Array.from(artFiles.values()).flatMap((art) => art.variants.map((variant) => {
1781
- const key = staticPreviewId(identityRoot ? resolveStaticArtIdentity(art.path, identityRoot) : art.path, variant.name);
1782
- const moduleId = previewModuleId(art.path, variant.name);
1783
- return `${JSON.stringify(key)}: () => import(${JSON.stringify(moduleId)})`;
1784
- })).join(",\n")} };
1785
-
1786
- export async function loadMuseaPreview(id) {
1787
- const load = loaders[id];
1788
- if (!load) throw new Error("Musea preview not found: " + id);
1789
- await load();
1790
- }
1791
-
1792
- if (typeof window !== "undefined") {
1793
- window.__MUSEA_LOAD_PREVIEW__ = loadMuseaPreview;
1794
- }
1795
- `;
394
+ //#region src/tokens/preview.ts
395
+ function resolveTokenPreview(input) {
396
+ const reference = resolveReference(input.token, input.tokenMap);
397
+ const value = input.token.$resolvedValue ?? reference?.value ?? input.token.value;
398
+ const candidates = buildCandidates(input.tokenPath, input.token, reference);
399
+ const kind = resolveCustomKind(candidates, reference?.path, input.config?.rules) ?? inferPreviewKind(candidates, value);
400
+ return {
401
+ kind: new Set(input.config?.disabledKinds ?? []).has(kind) ? "generic" : kind,
402
+ value,
403
+ tokenPath: input.tokenPath,
404
+ reference
405
+ };
1796
406
  }
1797
- async function emitStaticGallery(emitFile, bundle, ctx) {
1798
- const runtimeFileName = findRuntimeFileName(bundle);
1799
- if (!runtimeFileName) throw new Error("musea static build could not find its generated runtime entry");
1800
- const staticRoot = staticRootFromBasePath(ctx.basePath);
1801
- const publicBasePath = publicBasePathFromViteBase(ctx.config.base, ctx.basePath);
1802
- const publicCtx = {
1803
- ...ctx,
1804
- basePath: publicBasePath
407
+ function resolveReference(token, tokenMap) {
408
+ if (!token.$reference) return void 0;
409
+ const referencedToken = tokenMap?.[token.$reference];
410
+ return {
411
+ path: token.$reference,
412
+ token: referencedToken,
413
+ value: referencedToken ? referencedToken.$resolvedValue ?? referencedToken.value : void 0
1805
414
  };
1806
- const publicPayload = await createStaticGalleryPayload(publicCtx);
1807
- await emitGalleryShell(emitFile, staticRoot, publicCtx, publicPayload);
1808
- emitFile({
1809
- type: "asset",
1810
- fileName: joinFileName(staticRoot, "api", "static.json"),
1811
- source: JSON.stringify(publicPayload, null, 2)
415
+ }
416
+ function buildCandidates(tokenPath, token, reference) {
417
+ const candidates = [{
418
+ tokenPath,
419
+ name: pathName(tokenPath),
420
+ token
421
+ }];
422
+ if (reference?.token) candidates.push({
423
+ tokenPath: reference.path,
424
+ name: pathName(reference.path),
425
+ token: reference.token
1812
426
  });
1813
- emitFile({
1814
- type: "asset",
1815
- fileName: joinFileName(staticRoot, "api", "arts"),
1816
- source: JSON.stringify(publicPayload.arts, null, 2)
427
+ return candidates;
428
+ }
429
+ function resolveCustomKind(candidates, referencePath, rules) {
430
+ for (const rule of rules ?? []) if (matchesRule(rule, candidates, referencePath)) return rule.kind;
431
+ }
432
+ function matchesRule(rule, candidates, referencePath) {
433
+ const checks = [];
434
+ if (rule.type !== void 0) checks.push(candidates.some((candidate) => typeMatches(candidate, rule.type)));
435
+ if (rule.pathIncludes !== void 0) checks.push(candidates.some((candidate) => includesAny(candidate.tokenPath, rule.pathIncludes)));
436
+ if (rule.nameIncludes !== void 0) checks.push(candidates.some((candidate) => includesAny(candidate.name, rule.nameIncludes)));
437
+ if (rule.referencePathIncludes !== void 0) checks.push(referencePath !== void 0 && includesAny(referencePath, rule.referencePathIncludes));
438
+ return checks.length > 0 && checks.every(Boolean);
439
+ }
440
+ function inferPreviewKind(candidates, value) {
441
+ if (hasType(candidates, ["color"]) || isColorValue(value)) return "color";
442
+ if (hasType(candidates, ["shadow", "box-shadow"]) || hasSignal(candidates, ["shadow", "box-shadow"])) return "shadow";
443
+ if (hasType(candidates, [
444
+ "z-index",
445
+ "zindex",
446
+ "zIndex"
447
+ ]) || hasSignal(candidates, [
448
+ "z-index",
449
+ "zindex",
450
+ "stacking-order"
451
+ ])) return "zIndex";
452
+ if (hasType(candidates, ["opacity"]) || hasSignal(candidates, ["opacity", "alpha"])) return "opacity";
453
+ if (hasType(candidates, [
454
+ "border-radius",
455
+ "borderradius",
456
+ "radius"
457
+ ]) || hasSignal(candidates, [
458
+ "border-radius",
459
+ "borderradius",
460
+ "radius",
461
+ "round",
462
+ "rounded"
463
+ ])) return "radius";
464
+ if (hasType(candidates, ["letterspacing", "letter-spacing"]) || hasSignal(candidates, [
465
+ "letter-spacing",
466
+ "letterspacing",
467
+ "tracking"
468
+ ])) return "letterSpacing";
469
+ if (hasType(candidates, ["spacing", "space"]) || hasSignal(candidates, [
470
+ "spacing",
471
+ "spasing",
472
+ "space",
473
+ "gap",
474
+ "padding",
475
+ "margin",
476
+ "inset"
477
+ ])) return "spacing";
478
+ if (hasSignal(candidates, [
479
+ "font-size",
480
+ "fontsize",
481
+ "text-size"
482
+ ])) return "fontSize";
483
+ if (hasType(candidates, ["fontweight", "font-weight"]) || hasSignal(candidates, [
484
+ "font-weight",
485
+ "fontweight",
486
+ "weight"
487
+ ])) return "fontWeight";
488
+ if (hasType(candidates, ["lineheight", "line-height"]) || hasSignal(candidates, ["line-height", "lineheight"])) return "lineHeight";
489
+ return "generic";
490
+ }
491
+ function hasType(candidates, terms) {
492
+ return candidates.some((candidate) => typeMatches(candidate, terms));
493
+ }
494
+ function hasSignal(candidates, terms) {
495
+ return candidates.some((candidate) => includesAny(candidate.tokenPath, terms) || includesAny(candidate.name, terms) || candidate.token.type !== void 0 && includesAny(candidate.token.type, terms));
496
+ }
497
+ function typeMatches(candidate, expected) {
498
+ if (!candidate.token.type) return false;
499
+ return toArray(expected).some((term) => normalize(candidate.token.type) === normalize(term));
500
+ }
501
+ function includesAny(value, expected) {
502
+ const normalizedValue = normalize(value);
503
+ const compactValue = compact(normalizedValue);
504
+ return toArray(expected).some((term) => {
505
+ const normalizedTerm = normalize(term);
506
+ return normalizedValue.includes(normalizedTerm) || compactValue.includes(compact(normalizedTerm));
1817
507
  });
1818
- await emitAxeVendor(emitFile, staticRoot);
1819
- emitPreviewHtml(emitFile, staticRoot, runtimeFileName, publicBasePath, new Map(publicPayload.arts.map((art) => [art.path, art])));
1820
- emitRootRedirect(emitFile, staticRoot, publicBasePath);
1821
508
  }
1822
- function findRuntimeFileName(bundle) {
1823
- for (const item of Object.values(bundle)) if (item.type === "chunk" && item.name === "musea-static-runtime") return item.fileName;
1824
- return null;
509
+ function isColorValue(value) {
510
+ if (typeof value !== "string") return false;
511
+ return /^(#|rgb\(|rgba\(|hsl\(|hsla\(|oklch\(|oklab\(|lab\(|lch\(|color\()/i.test(value.trim());
1825
512
  }
1826
- function emitPreviewHtml(emitFile, staticRoot, runtimeFileName, basePath, artFiles) {
1827
- const previewDir = joinFileName(staticRoot, "preview");
1828
- const runtimeUrl = relativeUrl(previewDir, runtimeFileName);
1829
- for (const art of artFiles.values()) for (const variant of art.variants) {
1830
- const id = staticPreviewId(art.path, variant.name);
1831
- const html = generateStaticPreviewHtml(art, variant.name, id, basePath, runtimeUrl);
1832
- emitFile({
1833
- type: "asset",
1834
- fileName: joinFileName(previewDir, `${id}.html`),
1835
- source: html
1836
- });
1837
- }
513
+ function pathName(tokenPath) {
514
+ return tokenPath.split(".").at(-1) ?? tokenPath;
1838
515
  }
1839
- function generateStaticPreviewHtml(art, variantName, previewId, basePath, runtimeUrl) {
1840
- return `<!DOCTYPE html>
1841
- <html lang="en">
1842
- <head>
1843
- <meta charset="UTF-8">
1844
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
1845
- <title>${escapeHtml(art.metadata.title)} - ${escapeHtml(variantName)}</title>
1846
- <script>window.__MUSEA_BASE_PATH__=${serializeScriptValue(basePath)};<\/script>
1847
- <style>html,body{width:100%;height:100%;margin:0}body{font-family:system-ui,sans-serif;background:#fff;padding:1rem;overflow:auto;box-sizing:border-box}.musea-variant{min-height:calc(100vh - 2rem)}.musea-error{color:#dc2626;background:#fef2f2;border:1px solid #fecaca;border-radius:8px;padding:1rem;font-size:.875rem}.musea-loading{color:#6b7280;font-size:.875rem}.musea-bg-checkerboard{background-image:linear-gradient(45deg,#ccc 25%,transparent 25%),linear-gradient(-45deg,#ccc 25%,transparent 25%),linear-gradient(45deg,transparent 75%,#ccc 75%),linear-gradient(-45deg,transparent 75%,#ccc 75%)!important;background-size:20px 20px!important;background-position:0 0,0 10px,10px -10px,-10px 0!important}</style>
1848
- </head>
1849
- <body>
1850
- <div id="app" class="musea-variant" data-art="${escapeHtml(art.path)}" data-variant="${escapeHtml(variantName)}">
1851
- <div class="musea-loading">Loading component...</div>
1852
- </div>
1853
- <script type="module">
1854
- import ${JSON.stringify(runtimeUrl)};
1855
- Promise.resolve().then(() => {
1856
- const loadMuseaPreview = window.__MUSEA_LOAD_PREVIEW__;
1857
- if (typeof loadMuseaPreview !== "function") {
1858
- throw new Error("Musea preview runtime failed to load");
1859
- }
1860
- return loadMuseaPreview(${JSON.stringify(previewId)});
1861
- }).catch((error) => {
1862
- const el = document.getElementById("app");
1863
- if (el) el.textContent = error instanceof Error ? error.message : String(error);
1864
- });
1865
- <\/script>
1866
- </body>
1867
- </html>`;
1868
- }
1869
- function emitRootRedirect(emitFile, staticRoot, basePath) {
1870
- if (!staticRoot) return;
1871
- const target = joinUrlPath(basePath, "");
1872
- emitFile({
1873
- type: "asset",
1874
- fileName: "index.html",
1875
- source: `<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="0; url=${target}"><script>location.replace(${JSON.stringify(target)}+location.search+location.hash)<\/script>`
1876
- });
516
+ function normalize(value) {
517
+ return value.trim().toLowerCase().replace(/[_\s]+/g, "-");
1877
518
  }
1878
- async function emitAxeVendor(emitFile, staticRoot) {
1879
- try {
1880
- const axePath = createRequire(import.meta.url).resolve("axe-core/axe.min.js");
1881
- const source = await fs.promises.readFile(axePath);
1882
- emitFile({
1883
- type: "asset",
1884
- fileName: joinFileName(staticRoot, "vendor/axe-core.min.js"),
1885
- source
1886
- });
1887
- } catch {
1888
- console.warn("[musea] axe-core is not installed, so the exported gallery cannot run accessibility checks.\n Install it to enable the A11y panel in the static build: vp install -D axe-core");
1889
- }
1890
- }
1891
- function staticRootFromBasePath(basePath) {
1892
- return basePath.replace(/^\/+|\/+$/g, "");
519
+ function compact(value) {
520
+ return value.replace(/[-.]/g, "");
1893
521
  }
1894
- function relativeUrl(fromDir, toFile) {
1895
- const relative = path.posix.relative(fromDir || ".", toFile);
1896
- return relative.startsWith(".") ? relative : `./${relative}`;
522
+ function toArray(value) {
523
+ return Array.isArray(value) ? value : [value];
1897
524
  }
1898
525
  //#endregion
1899
- //#region src/plugin/config.ts
1900
- async function resolveMuseaSharedConfig(resolvedConfig, loadConfigFile = loadConfig, projectViteConfig = resolveViteConfigExport) {
1901
- let registration = getResolvedVizeConfigRegistration(resolvedConfig);
1902
- if (!registration.registered) {
1903
- await Promise.resolve();
1904
- registration = getResolvedVizeConfigRegistration(resolvedConfig);
526
+ //#region src/root-a11y.ts
527
+ /** Backward-compatible root export that loads browser audit code on demand. */
528
+ var MuseaA11yRunner = class {
529
+ options;
530
+ launchOptions;
531
+ runtime;
532
+ loading;
533
+ constructor(options = {}, launchOptions = {}) {
534
+ this.options = options;
535
+ this.launchOptions = launchOptions;
1905
536
  }
1906
- if (registration.registered) return await registration.config;
1907
- const configFile = process.env[VIZE_CONFIG_FILE_ENV];
1908
- try {
1909
- const env = {
1910
- mode: resolvedConfig.mode,
1911
- command: resolvedConfig.command === "build" ? "build" : "serve",
1912
- isSsrBuild: !!resolvedConfig.build?.ssr
1913
- };
1914
- return await loadConfigFile(resolvedConfig.root, {
1915
- configFile,
1916
- viteConfig: false,
1917
- env
1918
- }) ?? await projectViteConfig(resolvedConfig, env);
1919
- } catch (error) {
1920
- throw new Error(`[musea] Failed to load Vize config from ${configFile ?? resolvedConfig.root}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
537
+ async loadRuntime() {
538
+ if (this.runtime) return this.runtime;
539
+ const pending = this.loading ??= import("./a11y/index.mjs").then(({ MuseaA11yRunner: Runtime }) => new Runtime(this.options, this.launchOptions));
540
+ try {
541
+ return this.runtime = await pending;
542
+ } finally {
543
+ if (!this.runtime) this.loading = void 0;
544
+ }
1921
545
  }
1922
- }
1923
- //#endregion
1924
- //#region src/plugin/virtual-transform.ts
1925
- const VIRTUAL_ART_PREFIX = "\0musea-art:";
1926
- const VIRTUAL_INLINE_ART_PREFIX = "\0musea:";
1927
- /**
1928
- * Give Vite's TypeScript transformer a filename beside the authored art file.
1929
- * OXC uses this filename to select a tsconfig, so a synthetic filename under
1930
- * the Vite root can accidentally select an unrelated ancestor config.
1931
- */
1932
- function museaVirtualTransformId(id) {
1933
- const prefix = id.startsWith(VIRTUAL_ART_PREFIX) ? VIRTUAL_ART_PREFIX : id.startsWith(VIRTUAL_INLINE_ART_PREFIX) ? VIRTUAL_INLINE_ART_PREFIX : null;
1934
- if (!prefix) return null;
1935
- return `${id.slice(prefix.length).replace(/\?musea-virtual$/, "")}.ts`;
1936
- }
1937
- function createMuseaVirtualTransformer(viteApi) {
1938
- return async (code, id, sourcemap) => {
1939
- if (typeof viteApi.transformWithOxc === "function") return viteApi.transformWithOxc(code, id, {
1940
- lang: "ts",
1941
- sourcemap,
1942
- target: "esnext"
1943
- });
1944
- if (typeof viteApi.transformWithEsbuild === "function") return viteApi.transformWithEsbuild(code, id, {
1945
- loader: "ts",
1946
- format: "esm",
1947
- sourcemap,
1948
- target: "esnext"
1949
- });
1950
- throw new Error("Installed Vite does not expose transformWithOxc or transformWithEsbuild");
1951
- };
1952
- }
1953
- const transformMuseaVirtualModule = createMuseaVirtualTransformer(vite);
1954
- //#endregion
1955
- //#region src/plugin/preview-css.ts
1956
- /**
1957
- * Resolve a `previewCss` entry.
1958
- *
1959
- * Relative and project-root files stay filesystem paths. Bare specifiers
1960
- * (`normalize.css`, `@fontsource/inter/index.css`) are left for Vite.
1961
- */
1962
- function resolvePreviewCssPath(root, cssPath) {
1963
- if (path.isAbsolute(cssPath)) return cssPath;
1964
- const rooted = path.resolve(root, cssPath);
1965
- if (cssPath.startsWith(".") || fs.existsSync(rooted)) return rooted;
1966
- return cssPath;
1967
- }
1968
- //#endregion
1969
- //#region src/plugin/static-preview.ts
1970
- function resolveStaticPreviewVueVersion(configured, plugins) {
1971
- if (configured !== void 0) return configured;
1972
- if (hasLegacyVueSfcCompilerPlugin(plugins)) return 2;
1973
- return 3;
1974
- }
1975
- function hasLegacyVueSfcCompilerPlugin(plugins) {
1976
- return plugins.some((plugin) => {
1977
- const name = plugin.name ?? "";
1978
- return name === "vite:vue2" || name.includes("plugin-vue2") || name.includes("vue2");
1979
- });
1980
- }
1981
- //#endregion
1982
- //#region src/gallery-dependencies.ts
1983
- const moduleDir = path.dirname(fileURLToPath(import.meta.url));
1984
- const globPath = (entry) => normalizePath(entry).replace(/([*?{}[\]()!])/g, "\\$1");
1985
- async function registerSourceGalleryDependencies(config) {
1986
- const client = config.environments.client;
1987
- const optimizer = client.optimizeDeps;
1988
- const gallery = path.join(moduleDir, "../gallery/index.html");
1989
- if (config.command !== "serve" || optimizer.disabled === true || optimizer.disabled === "dev" || optimizer.noDiscovery || existsSync(path.join(moduleDir, "gallery/index.html")) || !existsSync(gallery)) return;
1990
- let entries = optimizer.entries;
1991
- if (!entries) {
1992
- const input = client.build.rollupOptions.input;
1993
- if (input) {
1994
- const inputs = typeof input === "string" ? [input] : Array.isArray(input) ? input : Object.values(input);
1995
- const resolve = config.createResolver();
1996
- entries = await Promise.all(inputs.map(async (entry) => {
1997
- const resolved = await resolve(entry, path.join(process.cwd(), "*"));
1998
- if (!resolved) throw new Error(`Failed to resolve gallery dependency scan input: ${entry}`);
1999
- return globPath(resolved);
2000
- }));
2001
- } else entries = [
2002
- "**/*.html",
2003
- "!**/__tests__/**",
2004
- "!**/coverage/**"
2005
- ];
546
+ async runAudits(artFiles, baseUrl, vrtRunner) {
547
+ return (await this.loadRuntime()).runAudits(artFiles, baseUrl, vrtRunner);
2006
548
  }
2007
- optimizer.entries = [...new Set([...typeof entries === "string" ? [entries] : entries, globPath(gallery)])];
2008
- }
2009
- //#endregion
2010
- //#region src/plugin/gallery-url.ts
2011
- function resolveMuseaGalleryUrls(resolvedUrls, fallback, basePath) {
2012
- const origins = [...resolvedUrls?.local ?? [], ...resolvedUrls?.network ?? []];
2013
- if (origins.length === 0) {
2014
- const host = ["::", "0.0.0.0"].includes(fallback.address) ? "localhost" : fallback.address === "::1" ? "[::1]" : fallback.address;
2015
- origins.push(`${fallback.protocol}://${host}:${fallback.port}/`);
549
+ async auditPage(page, artPath, variantName) {
550
+ return (await this.loadRuntime()).auditPage(page, artPath, variantName);
2016
551
  }
2017
- return [...new Set(origins)].map((origin) => {
2018
- const url = new URL(origin);
2019
- url.pathname = basePath;
2020
- url.search = "";
2021
- url.hash = "";
2022
- return url.href;
2023
- });
2024
- }
2025
- //#endregion
2026
- //#region src/plugin/raw-input-owner.ts
2027
- /** Only the active Musea instance may delegate raw Art to its virtual SFC route. */
2028
- function createRawArtInputOwner(config) {
2029
- const root = config.root;
2030
- const include = [...config.include];
2031
- const exclude = [...config.exclude];
2032
- const scanRoots = [...config.scanRoots];
2033
- return Object.freeze({ ownsInput(file, source) {
2034
- if (!file.endsWith(".art.vue") || !shouldProcess(file, include, exclude, root) || !isTrustedSourcePath(root, scanRoots, file)) return false;
2035
- const native = loadNative();
2036
- if (!native.parseSfc(source, { filename: file }).customBlocks.some((block) => block.type === "art")) return false;
2037
- return native.parseArt(source, { filename: file }).variants.length > 0;
2038
- } });
2039
- }
2040
- //#endregion
2041
- //#region src/plugin/index.ts
2042
- function musea(options = {}) {
2043
- let include = options.include ?? ["**/*.art.vue"];
2044
- let exclude = options.exclude ?? ["node_modules/**", "dist/**"];
2045
- let basePath = options.basePath ?? "/__musea__";
2046
- let storybookCompat = options.storybookCompat ?? false;
2047
- const storybookOutDir = options.storybookOutDir ?? ".storybook/stories";
2048
- let inlineArt = options.inlineArt ?? false;
2049
- const tokensPath = options.tokensPath;
2050
- let tokenPreviewConfig = options.tokenPreviews;
2051
- const projectRootOption = options.projectRoot;
2052
- const themeConfig = buildThemeConfig(options.theme);
2053
- const previewCss = options.previewCss ?? [];
2054
- const previewSetup = options.previewSetup;
2055
- const toolbar = normalizeToolbar(options.toolbar);
2056
- let vueVersion = options.vueVersion;
2057
- const devSessionToken = createDevSessionToken();
2058
- let config;
2059
- const rawInputOwners = /* @__PURE__ */ new WeakMap();
2060
- let server = null;
2061
- const artFiles = /* @__PURE__ */ new Map();
2062
- let resolvedPreviewCss = [];
2063
- let resolvedPreviewSetup = null;
2064
- let scanRoots = [];
2065
- let staticBuildEnabled = isMuseaStaticBuild();
2066
- const virtualState = {
2067
- basePath,
2068
- get inlineArt() {
2069
- return inlineArt;
2070
- },
2071
- artFiles,
2072
- resolvedPreviewCss,
2073
- resolvedPreviewSetup,
2074
- toolbar,
2075
- getConfigRoot: () => config.root,
2076
- getScanRoots: () => scanRoots,
2077
- getVueVersion: () => vueVersion,
2078
- getServer: () => server,
2079
- processArtFile
2080
- };
2081
- const virtualResolveId = createResolveId(virtualState);
2082
- const virtualLoad = createLoad(virtualState);
2083
- const handleHotUpdate = createHandleHotUpdate(virtualState);
2084
- const mainPlugin = {
2085
- name: "vite-plugin-musea",
2086
- api: { vizePrecompileInputOwner: Object.freeze({
2087
- version: 1,
2088
- forConfig: (resolved) => rawInputOwners.get(resolved)
2089
- }) },
2090
- enforce: "pre",
2091
- apply(_config, env) {
2092
- return shouldApplyMuseaPlugin(env);
2093
- },
2094
- config(userConfig, env) {
2095
- staticBuildEnabled = shouldEmitMuseaStaticGallery(env.command, storybookCompat);
2096
- const staticBuildConfig = staticBuildEnabled ? museaStaticBuildConfig(userConfig.build?.rollupOptions?.input) : {};
2097
- return {
2098
- resolve: { alias: [createVueRuntimeCompilerAlias({
2099
- root: userConfig.root ? path.resolve(userConfig.root) : process.cwd(),
2100
- runtimeCompiler: options.vueRuntimeCompiler
2101
- })] },
2102
- ...staticBuildConfig
2103
- };
2104
- },
2105
- options: applyMuseaStaticBuildInput,
2106
- async configResolved(resolvedConfig) {
2107
- config = resolvedConfig;
2108
- await registerSourceGalleryDependencies(resolvedConfig);
2109
- const vizeConfig = await resolveMuseaSharedConfig(resolvedConfig);
2110
- if (vizeConfig?.musea) {
2111
- const mc = vizeConfig.musea;
2112
- if (!options.include && mc.include) include = mc.include;
2113
- if (!options.exclude && mc.exclude) exclude = mc.exclude;
2114
- if (!options.basePath && mc.basePath) basePath = mc.basePath;
2115
- if (options.storybookCompat === void 0 && mc.storybookCompat !== void 0) storybookCompat = mc.storybookCompat;
2116
- if (options.inlineArt === void 0 && mc.inlineArt !== void 0) inlineArt = mc.inlineArt;
2117
- if (options.tokenPreviews === void 0 && mc.tokenPreviews !== void 0) tokenPreviewConfig = mc.tokenPreviews;
2118
- }
2119
- if (basePath !== "/") basePath = basePath.replace(/\/+$/, "");
2120
- vueVersion = resolveStaticPreviewVueVersion(vueVersion, resolvedConfig.plugins);
2121
- if (toolbar.length > 0 && vueVersion !== 3 && vueVersion !== "2.7") throw new Error("[musea] Global toolbar controls require Vue 3 or Vue 2.7");
2122
- staticBuildEnabled = shouldEmitMuseaStaticGallery(resolvedConfig.command, storybookCompat);
2123
- virtualState.basePath = basePath;
2124
- resolvedPreviewCss = previewCss.map((cssPath) => resolvePreviewCssPath(resolvedConfig.root, cssPath));
2125
- if (previewSetup) resolvedPreviewSetup = path.isAbsolute(previewSetup) ? previewSetup : path.resolve(resolvedConfig.root, previewSetup);
2126
- virtualState.resolvedPreviewCss = resolvedPreviewCss;
2127
- virtualState.resolvedPreviewSetup = resolvedPreviewSetup;
2128
- scanRoots = resolveScanRoots(resolvedConfig.root, include);
2129
- rawInputOwners.set(resolvedConfig, createRawArtInputOwner({
2130
- root: resolvedConfig.root,
2131
- include,
2132
- exclude,
2133
- scanRoots
2134
- }));
2135
- },
2136
- configureServer(devServer) {
2137
- server = devServer;
2138
- devServer.watcher.unwatch(path.resolve(config.root, ".vize/reports"));
2139
- registerMiddleware(devServer, {
2140
- basePath,
2141
- devSessionToken,
2142
- themeConfig,
2143
- tokenPreviewConfig,
2144
- artFiles,
2145
- scanRoots,
2146
- resolvedPreviewCss,
2147
- resolvedPreviewSetup,
2148
- toolbar
2149
- });
2150
- devServer.middlewares.use(`${basePath}/api`, createApiMiddleware({
2151
- config,
2152
- artFiles,
2153
- scanRoots,
2154
- tokensPath,
2155
- projectRoot: resolveProjectRoot(projectRootOption, config.root),
2156
- basePath,
2157
- resolvedPreviewCss,
2158
- resolvedPreviewSetup,
2159
- toolbar,
2160
- vrt: options.vrt,
2161
- devSessionToken,
2162
- processArtFile,
2163
- getDevServerPort: () => devServer.config.server.port || 5173
2164
- }));
2165
- devServer.watcher.on("change", async (file) => {
2166
- if (file.endsWith(".art.vue") && shouldProcess(file, include, exclude, config.root)) {
2167
- await processArtFile(file);
2168
- console.log(`[musea] Reloaded: ${path.relative(config.root, file)}`);
2169
- }
2170
- if (inlineArt && file.endsWith(".vue") && !file.endsWith(".art.vue")) {
2171
- const hadArt = artFiles.has(file);
2172
- if ((await fs.promises.readFile(file, "utf-8")).includes("<art")) {
2173
- await processArtFile(file);
2174
- console.log(`[musea] Reloaded inline art: ${path.relative(config.root, file)}`);
2175
- } else if (hadArt) {
2176
- artFiles.delete(file);
2177
- console.log(`[musea] Removed inline art: ${path.relative(config.root, file)}`);
2178
- }
2179
- }
2180
- });
2181
- devServer.watcher.on("add", async (file) => {
2182
- if (file.endsWith(".art.vue") && shouldProcess(file, include, exclude, config.root)) {
2183
- await processArtFile(file);
2184
- console.log(`[musea] Added: ${path.relative(config.root, file)}`);
2185
- }
2186
- if (inlineArt && file.endsWith(".vue") && !file.endsWith(".art.vue")) {
2187
- if ((await fs.promises.readFile(file, "utf-8")).includes("<art")) {
2188
- await processArtFile(file);
2189
- console.log(`[musea] Added inline art: ${path.relative(config.root, file)}`);
2190
- }
2191
- }
2192
- });
2193
- devServer.watcher.on("unlink", (file) => {
2194
- if (artFiles.has(file)) {
2195
- artFiles.delete(file);
2196
- console.log(`[musea] Removed: ${path.relative(config.root, file)}`);
2197
- }
2198
- });
2199
- return () => {
2200
- devServer.httpServer?.once("listening", () => {
2201
- const address = devServer.httpServer?.address();
2202
- if (address && typeof address === "object") {
2203
- const protocol = devServer.config.server.https ? "https" : "http";
2204
- console.log();
2205
- for (const url of resolveMuseaGalleryUrls(devServer.resolvedUrls, {
2206
- protocol,
2207
- address: address.address,
2208
- port: address.port
2209
- }, basePath)) console.log(` \x1b[36m➜\x1b[0m \x1b[1mMusea Gallery:\x1b[0m \x1b[36m${url}\x1b[0m`);
2210
- }
2211
- });
2212
- };
2213
- },
2214
- async buildStart() {
2215
- console.log(`[musea] config.root: ${config.root}, include: ${JSON.stringify(include)}`);
2216
- if (storybookCompat && staticBuildEnabled) await assertNoUnsupportedStorybookTsxInputs(config.root, include, exclude);
2217
- const files = await scanArtFiles(config.root, include, exclude, inlineArt);
2218
- console.log(`[musea] Found ${files.length} art files`);
2219
- if (server) watchMuseaArtFiles(server.watcher, files);
2220
- for (const file of files) await processArtFile(file);
2221
- if (storybookCompat) await generateStorybookFiles(artFiles, config.root, storybookOutDir);
2222
- },
2223
- resolveId(id) {
2224
- return resolveStaticRuntimeId(id) ?? virtualResolveId(id);
2225
- },
2226
- load(id) {
2227
- return loadStaticRuntimeModule(id, artFiles, staticBuildEnabled ? resolveStaticIdentityRoot(config.root, artFiles.keys(), resolveProjectRoot(projectRootOption, config.root)) : void 0) ?? virtualLoad(id);
2228
- },
2229
- async generateBundle(_options, bundle) {
2230
- if (!staticBuildEnabled) return;
2231
- await emitStaticGallery((asset) => void this.emitFile(asset), bundle, {
2232
- config,
2233
- artFiles,
2234
- scanRoots,
2235
- tokensPath,
2236
- projectRoot: resolveProjectRoot(projectRootOption, config.root),
2237
- basePath,
2238
- resolvedPreviewCss,
2239
- resolvedPreviewSetup,
2240
- toolbar,
2241
- devSessionToken,
2242
- themeConfig,
2243
- tokenPreviewConfig
2244
- });
2245
- },
2246
- async transform(code, id) {
2247
- const inlineArtBlock = loadInlineArtCustomBlock(virtualState, id);
2248
- if (inlineArtBlock !== null) return {
2249
- code: inlineArtBlock,
2250
- map: null
2251
- };
2252
- if (!id.includes("?musea-virtual")) return null;
2253
- if (!id.includes("musea-art:") && !id.includes("\0musea:")) return null;
2254
- const loaderId = museaVirtualTransformId(id);
2255
- if (!loaderId) return null;
2256
- return transformMuseaVirtualModule(code, loaderId, config.command === "serve");
2257
- },
2258
- handleHotUpdate
2259
- };
2260
- async function processArtFile(filePath) {
2261
- try {
2262
- resolveTrustedSourcePath(config.root, scanRoots, filePath, "art path");
2263
- } catch {
2264
- return;
2265
- }
2266
- const info = await processMuseaArtFile(filePath, {
2267
- root: config.root,
2268
- command: config.command
2269
- });
2270
- if (info) artFiles.set(filePath, info);
2271
- else if (artFiles.get(filePath)?.isInline) artFiles.delete(filePath);
552
+ getSummary(results) {
553
+ return computeA11ySummary(results);
2272
554
  }
2273
- return [attachMuseaOptions(mainPlugin, options), {
2274
- name: "vite-plugin-musea:style-post-transform",
2275
- transform(code, id) {
2276
- const transformed = transformPreprocessedArtStyle(code, id);
2277
- return transformed === null ? null : {
2278
- code: transformed,
2279
- map: null
2280
- };
2281
- }
2282
- }];
2283
- }
2284
- function resolveProjectRoot(projectRoot, viteRoot) {
2285
- if (!projectRoot) return void 0;
2286
- const absolute = path.isAbsolute(projectRoot) ? projectRoot : path.resolve(viteRoot, projectRoot);
2287
- return absolute === path.resolve(viteRoot) ? void 0 : absolute;
2288
- }
555
+ generateHtmlReport(results) {
556
+ return generateA11yHtmlReport(results, this.getSummary(results));
557
+ }
558
+ generateJsonReport(results) {
559
+ return generateA11yJsonReport(results);
560
+ }
561
+ };
2289
562
  //#endregion
2290
563
  //#region src/index.ts
2291
564
  var src_default = musea;