@vizejs/vite-plugin-musea 0.441.0 → 0.443.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/a11y/index.d.mts +1 -1
  2. package/dist/a11y/index.mjs +1 -1
  3. package/dist/{a11y-BbFK942j.mjs → a11y-DuFu75hl.mjs} +7 -6
  4. package/dist/a11y-DuFu75hl.mjs.map +1 -0
  5. package/dist/cli/index.d.mts +7 -1
  6. package/dist/cli/index.d.mts.map +1 -1
  7. package/dist/cli/index.mjs +111 -10
  8. package/dist/cli/index.mjs.map +1 -1
  9. package/dist/gallery/assets/MonacoEditor-CmjDtbrI.js +2 -0
  10. package/dist/gallery/assets/MonacoEditor-DxzpSKbC.css +1 -0
  11. package/dist/gallery/assets/{cssMode-D6nK_kDe.js → cssMode-B16oWKdO.js} +1 -1
  12. package/dist/gallery/assets/{editor.api-Bs4-VZ3V.js → editor.api-CfYscGcC.js} +1 -1
  13. package/dist/gallery/assets/{freemarker2-rDjl8685.js → freemarker2-Bsla50n3.js} +1 -1
  14. package/dist/gallery/assets/{handlebars-OkqFmHQQ.js → handlebars-CS_Y5cXs.js} +1 -1
  15. package/dist/gallery/assets/{html-Bq6Ai15v.js → html-DagAGhpS.js} +1 -1
  16. package/dist/gallery/assets/{htmlMode-H8XqFg_c.js → htmlMode-CiuL2Y-P.js} +1 -1
  17. package/dist/gallery/assets/index-BaRljRmN.css +1 -0
  18. package/dist/gallery/assets/{index-V774j4nI.js → index-Bma1gCA8.js} +6 -6
  19. package/dist/gallery/assets/{javascript-DY3JGgzg.js → javascript-BQYQMq9R.js} +1 -1
  20. package/dist/gallery/assets/{jsonMode-CYaDarn3.js → jsonMode-C5lyVqru.js} +1 -1
  21. package/dist/gallery/assets/{liquid-DSwk2doy.js → liquid-qbEuwx0o.js} +1 -1
  22. package/dist/gallery/assets/{lspLanguageFeatures-CThGg67f.js → lspLanguageFeatures-Dqts9s1L.js} +1 -1
  23. package/dist/gallery/assets/{mdx-B9XzBagU.js → mdx-DN6uw21R.js} +1 -1
  24. package/dist/gallery/assets/{python-sRU_mC7d.js → python-Cbp5CGeG.js} +1 -1
  25. package/dist/gallery/assets/{razor-CUHkZDIN.js → razor-BXu36P7p.js} +1 -1
  26. package/dist/gallery/assets/{register-BRx-S1So.js → register-vvpXemvQ.js} +2 -2
  27. package/dist/gallery/assets/{toggleHighContrast-tYUHUcTT.js → toggleHighContrast-9EQLxoB9.js} +1 -1
  28. package/dist/gallery/assets/{tsMode-C0mNxmwK.js → tsMode-DakVvyMV.js} +1 -1
  29. package/dist/gallery/assets/{typescript-Ba_YUPxA.js → typescript-DEY4mnQU.js} +1 -1
  30. package/dist/gallery/assets/{vs-omjQMPuv.js → vs-Cd8KAJDG.js} +3 -3
  31. package/dist/gallery/assets/{workers-BOTkt7rp.js → workers-GvANOwSC.js} +1 -1
  32. package/dist/gallery/assets/{xml-CGK9gfdX.js → xml-cZMAcMEr.js} +1 -1
  33. package/dist/gallery/assets/{yaml-CA-jHXc3.js → yaml-CReFeuuC.js} +1 -1
  34. package/dist/gallery/index.html +2 -2
  35. package/dist/{gallery-CLe_4-XW.mjs → gallery-LgVvVp28.mjs} +2 -2
  36. package/dist/{gallery-CLe_4-XW.mjs.map → gallery-LgVvVp28.mjs.map} +1 -1
  37. package/dist/{index-GkKsNzkf.d.mts → index-BU4-FGUC.d.mts} +3 -4
  38. package/dist/index-BU4-FGUC.d.mts.map +1 -0
  39. package/dist/{index-CtvsGVFJ.d.mts → index-ZFHsOEPD.d.mts} +6 -1
  40. package/dist/{index-CtvsGVFJ.d.mts.map → index-ZFHsOEPD.d.mts.map} +1 -1
  41. package/dist/index.d.mts +3 -3
  42. package/dist/index.mjs +153 -1592
  43. package/dist/index.mjs.map +1 -1
  44. package/dist/options-DnKPMMPV.mjs +2159 -0
  45. package/dist/options-DnKPMMPV.mjs.map +1 -0
  46. package/dist/{template-BgBSA10_.mjs → template-CpNUvZPp.mjs} +5 -3
  47. package/dist/template-CpNUvZPp.mjs.map +1 -0
  48. package/dist/{utils-DeMLVlNS.mjs → utils-BloA9YP9.mjs} +35 -29
  49. package/dist/utils-BloA9YP9.mjs.map +1 -0
  50. package/dist/utils-ChmPv0qc.mjs +55 -0
  51. package/dist/utils-ChmPv0qc.mjs.map +1 -0
  52. package/dist/{vrt-DNNAFYv1.d.mts → vrt-DtcnqPhF.d.mts} +22 -3
  53. package/dist/vrt-DtcnqPhF.d.mts.map +1 -0
  54. package/dist/{vrt-VuGK9wTX.mjs → vrt-PuxpRuHa.mjs} +392 -97
  55. package/dist/vrt-PuxpRuHa.mjs.map +1 -0
  56. package/dist/vrt.d.mts +1 -1
  57. package/dist/vrt.mjs +1 -1
  58. package/package.json +4 -4
  59. package/dist/a11y-BbFK942j.mjs.map +0 -1
  60. package/dist/gallery/assets/MonacoEditor-B2gyQ5TW.js +0 -2
  61. package/dist/gallery/assets/MonacoEditor-Db3Q217Z.css +0 -1
  62. package/dist/gallery/assets/index-DTMv-5r0.css +0 -1
  63. package/dist/index-GkKsNzkf.d.mts.map +0 -1
  64. package/dist/options-Bjo4e_75.mjs +0 -582
  65. package/dist/options-Bjo4e_75.mjs.map +0 -1
  66. package/dist/template-BgBSA10_.mjs.map +0 -1
  67. package/dist/utils-DeMLVlNS.mjs.map +0 -1
  68. package/dist/vrt-DNNAFYv1.d.mts.map +0 -1
  69. package/dist/vrt-VuGK9wTX.mjs.map +0 -1
@@ -1,6 +1,68 @@
1
+ import { a as waitForMountedPreview, i as observePreviewReady, n as buildVariantUrl, r as computeSummary, t as buildSnapshotName } from "./utils-ChmPv0qc.mjs";
1
2
  import fs from "node:fs";
2
3
  import path from "node:path";
4
+ import crypto from "node:crypto";
5
+ import fs$1 from "node:fs/promises";
3
6
  import { PNG } from "pngjs";
7
+ //#region src/vrt/snapshot-identity.ts
8
+ /** Validate a portable project-relative identity without changing its meaning. */
9
+ function normalizeSnapshotIdentity(relative) {
10
+ if (typeof relative !== "string" || !relative || relative.includes("\\") || relative.includes("\0") || path.posix.isAbsolute(relative) || path.win32.isAbsolute(relative) || /^[a-z]:/i.test(relative) || relative.split("/").some((part) => !part || part === "." || part === "..")) throw new Error(`Invalid project-relative snapshot identity: ${JSON.stringify(relative)}`);
11
+ return relative;
12
+ }
13
+ /** A hosted manifest supplies identities explicitly; it cannot fall back to local paths. */
14
+ function resolveSnapshotIdentity(artPath, projectRoot = process.cwd(), identities) {
15
+ if (identities !== void 0) {
16
+ if (!Object.hasOwn(identities, artPath)) throw new Error(`Snapshot identity missing for Art: ${artPath}`);
17
+ return normalizeSnapshotIdentity(identities[artPath]);
18
+ }
19
+ const root = path.resolve(projectRoot);
20
+ const absolute = path.resolve(root, artPath);
21
+ const relative = path.relative(root, absolute).split(path.sep).join("/");
22
+ try {
23
+ return normalizeSnapshotIdentity(relative);
24
+ } catch {
25
+ throw new Error(`Art is outside its snapshot projectRoot: ${artPath}. Configure projectRoot.`);
26
+ }
27
+ }
28
+ /** The viewport dimensions and scale remain part of identity even when it has a name. */
29
+ function buildCaptureIdentity(job, projectRoot = process.cwd(), identities) {
30
+ const { width, height, deviceScaleFactor = 1, name = "" } = job.viewport;
31
+ if (typeof job.variantName !== "string" || typeof name !== "string" || !Number.isSafeInteger(width) || width <= 0 || !Number.isSafeInteger(height) || height <= 0 || !Number.isFinite(deviceScaleFactor) || deviceScaleFactor <= 0) throw new Error("Invalid snapshot capture identity: variant or viewport");
32
+ return JSON.stringify([
33
+ 1,
34
+ resolveSnapshotIdentity(job.art.path, projectRoot, identities),
35
+ job.variantName,
36
+ name || "",
37
+ width,
38
+ height,
39
+ deviceScaleFactor
40
+ ]);
41
+ }
42
+ /** Reject corrupt ownership records, including noncanonical or unsupported tuples. */
43
+ function validateCaptureIdentity(value) {
44
+ if (typeof value !== "string") throw new Error("Invalid snapshot ownership identity");
45
+ let tuple;
46
+ try {
47
+ tuple = JSON.parse(value);
48
+ } catch {
49
+ throw new Error("Invalid snapshot ownership identity JSON");
50
+ }
51
+ if (!Array.isArray(tuple) || tuple.length !== 7 || tuple[0] !== 1) throw new Error("Invalid snapshot ownership identity version or tuple");
52
+ const [_, relative, variantName, name, width, height, deviceScaleFactor] = tuple;
53
+ normalizeSnapshotIdentity(relative);
54
+ if (buildCaptureIdentity({
55
+ art: { path: relative },
56
+ variantName,
57
+ viewport: {
58
+ name,
59
+ width,
60
+ height,
61
+ deviceScaleFactor
62
+ }
63
+ }, process.cwd(), { [relative]: relative }) !== value) throw new Error("Noncanonical snapshot ownership identity");
64
+ }
65
+ //#endregion
4
66
  //#region src/vrt/comparison.ts
5
67
  /**
6
68
  * Pixel comparison utilities for VRT.
@@ -92,54 +154,12 @@ function isAntiAliased(img1, img2, x, y, width, height) {
92
154
  return zeroes > 0 && (positives > 0 || negatives > 0) && positives + negatives < 4;
93
155
  }
94
156
  /**
95
- * Simple glob matching for pattern-based filtering.
96
- */
97
- function matchGlob(filepath, pattern) {
98
- const regex = pattern.replace(/\./g, "\\.").replace(/\*\*/g, ".*").replace(/\*(?!\*)/g, "[^/]*");
99
- return new RegExp(`^${regex}$`).test(filepath);
100
- }
101
- /**
102
157
  * Escape HTML special characters.
103
158
  */
104
159
  function escapeHtml(str) {
105
160
  return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#x27;");
106
161
  }
107
162
  //#endregion
108
- //#region src/vrt/utils.ts
109
- /**
110
- * Build URL for variant preview.
111
- */
112
- function buildVariantUrl(baseUrl, artPath, variantName) {
113
- return `${baseUrl}/__musea__/preview?art=${encodeURIComponent(artPath)}&variant=${encodeURIComponent(variantName)}`;
114
- }
115
- /**
116
- * Build a filesystem-safe snapshot file name for a VRT capture.
117
- */
118
- function buildSnapshotName(artPath, variantName, viewport) {
119
- const artBaseName = path.basename(artPath, ".art.vue");
120
- const viewportName = viewport.name || `${viewport.width}x${viewport.height}`;
121
- return `${encodeSnapshotNamePart(artBaseName)}--${encodeSnapshotNamePart(variantName)}--${encodeSnapshotNamePart(viewportName)}.png`;
122
- }
123
- function encodeSnapshotNamePart(value) {
124
- const encoded = encodeURIComponent(value);
125
- return encoded.length === 0 ? "unnamed" : encoded;
126
- }
127
- /**
128
- * Compute VRT summary statistics from a list of results.
129
- */
130
- function computeSummary(results, startTime) {
131
- const errors = results.filter((r) => r.error).length;
132
- return {
133
- total: results.length,
134
- passed: results.filter((r) => r.passed && !r.isNew).length,
135
- failed: results.filter((r) => !r.passed && !r.error).length,
136
- new: results.filter((r) => r.isNew).length,
137
- skipped: 0,
138
- errors,
139
- duration: Date.now() - startTime
140
- };
141
- }
142
- //#endregion
143
163
  //#region src/vrt/runner-comparison.ts
144
164
  /**
145
165
  * Capture screenshot and compare with baseline.
@@ -153,7 +173,7 @@ async function captureAndCompare(runner, art, variantName, viewport, baseUrl) {
153
173
  const capture = runner.getCapture();
154
174
  const comparison = runner.getComparison();
155
175
  const snapshotDir = options.snapshotDir;
156
- const snapshotName = buildSnapshotName(art.path, variantName, viewport);
176
+ const snapshotName = await runner.getSnapshotName(art, variantName, viewport);
157
177
  const snapshotPath = path.join(snapshotDir, snapshotName);
158
178
  const currentPath = path.join(snapshotDir, "current", snapshotName);
159
179
  const diffPath = path.join(snapshotDir, "diff", snapshotName);
@@ -172,9 +192,11 @@ async function captureAndCompare(runner, art, variantName, viewport, baseUrl) {
172
192
  reducedMotion: capture.reducedMotion
173
193
  });
174
194
  page = await context.newPage();
175
- const variantUrl = buildVariantUrl(baseUrl, art.path, variantName);
195
+ const variantUrl = runner.getPreviewUrl(baseUrl, art.path, variantName);
176
196
  const waitUntil = capture.waitForNetwork ? "networkidle" : "load";
197
+ if (capture.waitForPreviewReady) await observePreviewReady(page);
177
198
  await page.goto(variantUrl, { waitUntil });
199
+ if (capture.waitForPreviewReady) await waitForMountedPreview(page);
178
200
  await page.waitForSelector(capture.waitSelector, { timeout: 1e4 });
179
201
  await page.waitForTimeout(capture.settleTime);
180
202
  if (capture.hideElements.length > 0) for (const selector of capture.hideElements) await page.evaluate((sel) => {
@@ -318,6 +340,253 @@ async function compareImages(baselinePath, currentPath, diffPath, comparison) {
318
340
  };
319
341
  }
320
342
  //#endregion
343
+ //#region src/vrt/jobs.ts
344
+ function normalizeVrtWorkerCount(workers) {
345
+ if (workers === void 0 || !Number.isFinite(workers)) return 1;
346
+ return Math.max(1, Math.floor(workers));
347
+ }
348
+ function createVrtJobs(artFiles, defaultViewports) {
349
+ const jobs = [];
350
+ for (const art of artFiles) for (const variant of art.variants) {
351
+ if (variant.skipVrt) continue;
352
+ const viewports = variant.args?.viewport ? [variant.args.viewport] : defaultViewports;
353
+ for (const viewport of viewports) jobs.push({
354
+ art,
355
+ variantName: variant.name,
356
+ viewport
357
+ });
358
+ }
359
+ return jobs;
360
+ }
361
+ async function runJobsWithWorkers(jobs, workerCount, runJob) {
362
+ const results = Array.from({ length: jobs.length }, () => null);
363
+ let nextJobIndex = 0;
364
+ async function runWorker() {
365
+ while (true) {
366
+ const jobIndex = nextJobIndex++;
367
+ const job = jobs[jobIndex];
368
+ if (!job) return;
369
+ results[jobIndex] = await runJob(job);
370
+ }
371
+ }
372
+ const activeWorkers = Math.min(normalizeVrtWorkerCount(workerCount), jobs.length);
373
+ await Promise.all(Array.from({ length: activeWorkers }, () => runWorker()));
374
+ return results.filter((result) => result !== null);
375
+ }
376
+ //#endregion
377
+ //#region src/vrt/snapshot-index.ts
378
+ const SNAPSHOT_INDEX_FILE = "identities.json";
379
+ const SNAPSHOT_LOCK_FILE = "identities.lock";
380
+ /** Reserve one owner per PNG before parallel captures can touch the filesystem. */
381
+ var SnapshotIndex = class SnapshotIndex {
382
+ directory;
383
+ options;
384
+ owners = Object.create(null);
385
+ token = crypto.randomUUID();
386
+ lock;
387
+ closed = false;
388
+ closing = false;
389
+ pending = Promise.resolve();
390
+ constructor(directory, options) {
391
+ this.directory = directory;
392
+ this.options = options;
393
+ }
394
+ static async open(directory, options = {}) {
395
+ validateIdentityMap(options.snapshotIdentities);
396
+ const index = new SnapshotIndex(path.resolve(directory), {
397
+ ...options,
398
+ projectRoot: path.resolve(options.projectRoot ?? process.cwd()),
399
+ snapshotIdentities: options.snapshotIdentities === void 0 ? void 0 : { ...options.snapshotIdentities }
400
+ });
401
+ await fs$1.mkdir(index.directory, { recursive: true });
402
+ try {
403
+ index.lock = await fs$1.open(path.join(index.directory, SNAPSHOT_LOCK_FILE), "wx");
404
+ } catch (error) {
405
+ if (hasCode(error, "EEXIST")) throw new Error(`Snapshot directory is locked: ${index.directory}. Another VRT run may be active.`);
406
+ throw error;
407
+ }
408
+ try {
409
+ await index.lock.writeFile(index.token);
410
+ const file = path.join(index.directory, SNAPSHOT_INDEX_FILE);
411
+ try {
412
+ index.owners = validateIndex(JSON.parse(await fs$1.readFile(file, "utf8")));
413
+ } catch (error) {
414
+ if (!hasCode(error, "ENOENT")) throw new Error(`Invalid snapshot ownership index: ${file}`, { cause: error });
415
+ }
416
+ return index;
417
+ } catch (error) {
418
+ await index.close();
419
+ throw error;
420
+ }
421
+ }
422
+ plan(jobs) {
423
+ if (this.closed || this.closing) return Promise.reject(/* @__PURE__ */ new Error("Snapshot ownership index is closed"));
424
+ const result = this.pending.then(() => this.planBatch(jobs));
425
+ this.pending = result.catch(() => {});
426
+ return result;
427
+ }
428
+ async planBatch(jobs) {
429
+ const planned = this.prepare(jobs);
430
+ const alreadyOwned = new Map(Object.entries(this.owners).map(([name, id]) => [id, name]));
431
+ if (planned.every(({ identity }) => alreadyOwned.has(identity))) {
432
+ const result = new Map(planned.map(({ identity }) => [identity, alreadyOwned.get(identity)]));
433
+ await this.validateFiles(result.values());
434
+ return result;
435
+ }
436
+ const files = await fs$1.readdir(this.directory);
437
+ const existing = /* @__PURE__ */ new Map();
438
+ for (const name of files) {
439
+ const key = foldName(name);
440
+ existing.set(key, [...existing.get(key) ?? [], name]);
441
+ }
442
+ const owners = { ...this.owners };
443
+ const byIdentity = new Map(Object.entries(owners).map(([name, id]) => [id, name]));
444
+ const byName = new Map(Object.entries(owners).map(([name, id]) => [foldName(name), id]));
445
+ const groups = /* @__PURE__ */ new Map();
446
+ for (const job of planned) if (job.legacyName) {
447
+ const key = foldName(job.legacyName);
448
+ groups.set(key, (groups.get(key) ?? 0) + 1);
449
+ }
450
+ const result = /* @__PURE__ */ new Map();
451
+ for (const { identity, legacyName } of planned) {
452
+ const owned = byIdentity.get(identity);
453
+ if (owned) {
454
+ result.set(identity, owned);
455
+ continue;
456
+ }
457
+ const legacyKey = legacyName ? foldName(legacyName) : "";
458
+ const ambiguous = (groups.get(legacyKey) ?? 0) > 1 || (existing.get(legacyKey)?.length ?? 0) > 1;
459
+ if (legacyName && ambiguous && existing.has(legacyKey) && !byName.has(legacyKey) && this.options.adoptLegacySnapshots) throw new Error(`Cannot adopt ambiguous legacy snapshot: ${legacyName}`);
460
+ let name = legacyName && !ambiguous && !byName.has(legacyKey) ? legacyName : hashedName(identity);
461
+ const key = foldName(name);
462
+ if (byName.has(key)) throw new Error(`Snapshot filename ownership collision: ${name}`);
463
+ if (existing.has(key) && !this.options.adoptLegacySnapshots) throw new Error(`Unowned snapshot ${name}. Explicit adoptLegacySnapshots is required.`);
464
+ if (existing.has(key)) {
465
+ const matches = existing.get(key);
466
+ if (matches.length !== 1) throw new Error(`Cannot adopt ambiguous legacy snapshot: ${name}`);
467
+ if (!isSafeName(matches[0])) throw new Error(`Invalid snapshot filename: ${matches[0]}`);
468
+ name = matches[0];
469
+ }
470
+ owners[name] = identity;
471
+ byName.set(key, identity);
472
+ byIdentity.set(identity, name);
473
+ result.set(identity, name);
474
+ }
475
+ await this.validateFiles(result.values());
476
+ await this.persist(owners);
477
+ this.owners = owners;
478
+ return result;
479
+ }
480
+ async close() {
481
+ if (this.closed || this.closing) return;
482
+ this.closing = true;
483
+ await this.pending;
484
+ this.closed = true;
485
+ const lock = this.lock;
486
+ if (!lock) return;
487
+ const file = path.join(this.directory, SNAPSHOT_LOCK_FILE);
488
+ try {
489
+ if (await fs$1.readFile(file, "utf8") === this.token) await fs$1.unlink(file);
490
+ } catch (error) {
491
+ if (!hasCode(error, "ENOENT")) throw error;
492
+ } finally {
493
+ await lock.close();
494
+ this.lock = void 0;
495
+ }
496
+ }
497
+ prepare(jobs) {
498
+ const identities = /* @__PURE__ */ new Set();
499
+ return jobs.map((job) => {
500
+ const identity = buildCaptureIdentity(job, this.options.projectRoot, this.options.snapshotIdentities);
501
+ if (identities.has(identity)) throw new Error(`Duplicate snapshot capture identity: ${identity}`);
502
+ identities.add(identity);
503
+ let legacyName = null;
504
+ try {
505
+ const relative = JSON.parse(identity)[1];
506
+ const candidate = buildSnapshotName(relative, job.variantName, job.viewport);
507
+ if (isSafeName(candidate)) legacyName = candidate;
508
+ } catch {}
509
+ return {
510
+ identity,
511
+ legacyName
512
+ };
513
+ }).sort((a, b) => a.identity < b.identity ? -1 : a.identity > b.identity ? 1 : 0);
514
+ }
515
+ async persist(owners) {
516
+ const file = path.join(this.directory, SNAPSHOT_INDEX_FILE);
517
+ const temporary = `${file}.${this.token}.tmp`;
518
+ const ordered = Object.fromEntries(Object.entries(owners).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
519
+ try {
520
+ await fs$1.writeFile(temporary, `${JSON.stringify({
521
+ version: 1,
522
+ owners: ordered
523
+ }, null, 2)}\n`, { flag: "wx" });
524
+ await fs$1.rename(temporary, file);
525
+ } finally {
526
+ await fs$1.rm(temporary, { force: true });
527
+ }
528
+ }
529
+ async validateFiles(names) {
530
+ for (const name of names) try {
531
+ if (!(await fs$1.lstat(path.join(this.directory, name))).isFile()) throw new Error(`Snapshot must be a regular PNG file: ${name}`);
532
+ } catch (error) {
533
+ if (!hasCode(error, "ENOENT")) throw error;
534
+ }
535
+ }
536
+ };
537
+ function validateIdentityMap(identities) {
538
+ if (identities === void 0) return;
539
+ if (!isRecord(identities)) throw new Error("Invalid snapshot identity map");
540
+ const seen = /* @__PURE__ */ new Set();
541
+ for (const identity of Object.values(identities)) {
542
+ normalizeSnapshotIdentity(identity);
543
+ if (seen.has(identity)) throw new Error(`Duplicate Art snapshot identity: ${identity}`);
544
+ seen.add(identity);
545
+ }
546
+ }
547
+ function validateIndex(data) {
548
+ if (!isRecord(data) || data.version !== 1 || !isRecord(data.owners)) throw new Error("Snapshot ownership index must have version 1 and owners");
549
+ const owners = Object.create(null);
550
+ const names = /* @__PURE__ */ new Set();
551
+ const identities = /* @__PURE__ */ new Set();
552
+ for (const [name, identity] of Object.entries(data.owners)) {
553
+ if (!isSafeName(name)) throw new Error(`Invalid snapshot filename: ${name}`);
554
+ validateCaptureIdentity(identity);
555
+ if (names.has(foldName(name)) || identities.has(identity)) throw new Error(`Duplicate snapshot ownership: ${name}`);
556
+ if (/^snapshot-[0-9a-f]{64}\.png$/i.test(name) && foldName(name) !== hashedName(identity)) throw new Error(`Snapshot filename does not match its identity: ${name}`);
557
+ names.add(foldName(name));
558
+ identities.add(identity);
559
+ owners[name] = identity;
560
+ }
561
+ return owners;
562
+ }
563
+ function hashedName(identity) {
564
+ return `snapshot-${crypto.createHash("sha256").update(identity).digest("hex")}.png`;
565
+ }
566
+ function foldName(name) {
567
+ return name.toLowerCase();
568
+ }
569
+ function isSafeName(name) {
570
+ return name.endsWith(".png") && Buffer.byteLength(name) <= 255 && !/[\\/<>:"|?*]/.test(name) && !Array.from(name).some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) > 126) && name !== ".png";
571
+ }
572
+ function isRecord(value) {
573
+ return value !== null && typeof value === "object" && !Array.isArray(value);
574
+ }
575
+ function hasCode(error, code) {
576
+ return isRecord(error) && error.code === code;
577
+ }
578
+ //#endregion
579
+ //#region src/vrt/snapshot-pattern.ts
580
+ /** Approval treats literal path/name characters literally and supports * and **. */
581
+ function matchesSnapshotPattern(name, pattern) {
582
+ if (name.includes(pattern)) return true;
583
+ const source = pattern.split("**").map((part) => part.split("*").map(escapeRegex).join("[^/]*")).join(".*");
584
+ return new RegExp(`^${source}$`).test(name);
585
+ }
586
+ function escapeRegex(value) {
587
+ return value.replace(/[|\\{}()[\]^$+?.]/g, "\\$&");
588
+ }
589
+ //#endregion
321
590
  //#region src/vrt/runner.ts
322
591
  /**
323
592
  * VRT runner using Playwright.
@@ -329,8 +598,18 @@ var MuseaVrtRunner = class {
329
598
  ci;
330
599
  browser = null;
331
600
  startTime = 0;
601
+ snapshotIndex;
602
+ snapshotIndexOpening;
603
+ identityOptions;
604
+ previewUrls;
332
605
  constructor(options = {}) {
606
+ this.identityOptions = {
607
+ ...options,
608
+ projectRoot: path.resolve(options.projectRoot ?? process.cwd()),
609
+ snapshotIdentities: options.snapshotIdentities ? { ...options.snapshotIdentities } : void 0
610
+ };
333
611
  this.options = {
612
+ previewBasePath: options.previewBasePath ?? "/__musea__",
334
613
  snapshotDir: options.snapshotDir ?? ".vize/snapshots",
335
614
  threshold: options.threshold ?? .1,
336
615
  viewports: options.viewports ?? [{
@@ -350,6 +629,7 @@ var MuseaVrtRunner = class {
350
629
  caret: options.capture?.caret ?? "hide",
351
630
  fullPage: options.capture?.fullPage ?? false,
352
631
  waitForNetwork: options.capture?.waitForNetwork ?? true,
632
+ waitForPreviewReady: options.capture?.waitForPreviewReady ?? false,
353
633
  settleTime: options.capture?.settleTime ?? 100,
354
634
  waitSelector: options.capture?.waitSelector ?? ".musea-variant",
355
635
  hideElements: options.capture?.hideElements ?? [],
@@ -357,6 +637,17 @@ var MuseaVrtRunner = class {
357
637
  };
358
638
  this.comparison = options.comparison ?? {};
359
639
  this.ci = options.ci ?? {};
640
+ this.previewUrls = options.previewUrls;
641
+ }
642
+ /** Resolve the same actual preview for screenshots and accessibility audits. */
643
+ getPreviewUrl(baseUrl, artPath, variantName) {
644
+ if (this.previewUrls !== void 0) {
645
+ const variants = Object.hasOwn(this.previewUrls, artPath) ? this.previewUrls[artPath] : void 0;
646
+ const url = variants && Object.hasOwn(variants, variantName) ? variants[variantName] : void 0;
647
+ if (!url) throw new Error(`Hosted preview not found: ${artPath}/${variantName}`);
648
+ return url;
649
+ }
650
+ return buildVariantUrl(baseUrl, artPath, variantName, this.options.previewBasePath);
360
651
  }
361
652
  /** @internal */
362
653
  getBrowser() {
@@ -382,10 +673,29 @@ var MuseaVrtRunner = class {
382
673
  this.browser = await chromium.launch({ headless: true });
383
674
  this.startTime = Date.now();
384
675
  }
676
+ /** @internal Resolve and reserve a baseline before navigation or PNG writes. */
677
+ async getSnapshotName(art, variantName, viewport) {
678
+ return (await (await this.getSnapshotIndex()).plan([{
679
+ art,
680
+ variantName,
681
+ viewport
682
+ }])).values().next().value;
683
+ }
684
+ async getSnapshotIndex() {
685
+ if (this.snapshotIndex) return this.snapshotIndex;
686
+ const opening = this.snapshotIndexOpening ??= SnapshotIndex.open(this.options.snapshotDir, this.identityOptions);
687
+ try {
688
+ return this.snapshotIndex = await opening;
689
+ } finally {
690
+ if (this.snapshotIndexOpening === opening) this.snapshotIndexOpening = void 0;
691
+ }
692
+ }
385
693
  /**
386
694
  * Close browser and cleanup.
387
695
  */
388
696
  async close() {
697
+ await (this.snapshotIndex ?? await this.snapshotIndexOpening?.catch(() => void 0))?.close();
698
+ this.snapshotIndex = void 0;
389
699
  if (this.browser) {
390
700
  await this.browser.close();
391
701
  this.browser = null;
@@ -409,7 +719,9 @@ var MuseaVrtRunner = class {
409
719
  async runAllTests(artFiles, baseUrl) {
410
720
  if (!this.browser) throw new Error("VRT runner not initialized. Call init() first.");
411
721
  const retries = this.ci.retries ?? 0;
412
- return runJobsWithWorkers(createVrtJobs(artFiles, this.options.viewports), this.options.workers, async (job) => {
722
+ const jobs = createVrtJobs(artFiles, this.options.viewports);
723
+ await (await this.getSnapshotIndex()).plan(jobs);
724
+ return runJobsWithWorkers(jobs, this.options.workers, async (job) => {
413
725
  let result = null;
414
726
  let attempts = 0;
415
727
  while (attempts <= retries) {
@@ -461,6 +773,10 @@ var MuseaVrtRunner = class {
461
773
  const snapshotDir = this.options.snapshotDir;
462
774
  const currentDir = path.join(snapshotDir, "current");
463
775
  for (const result of results) {
776
+ if (result.error) continue;
777
+ const art = { path: result.artPath };
778
+ const name = await this.getSnapshotName(art, result.variantName, result.viewport);
779
+ if (path.resolve(result.snapshotPath) !== path.resolve(snapshotDir, name)) throw new Error("Baseline path does not match its snapshot owner");
464
780
  const currentPath = result.currentPath ?? path.join(currentDir, path.basename(result.snapshotPath));
465
781
  if (await fileExists(currentPath)) {
466
782
  await fs.promises.mkdir(path.dirname(result.snapshotPath), { recursive: true });
@@ -475,31 +791,35 @@ var MuseaVrtRunner = class {
475
791
  * Approve specific failed results (update their baselines).
476
792
  */
477
793
  async approveResults(results, pattern) {
478
- const toApprove = pattern ? results.filter((r) => {
479
- const name = `${path.basename(r.artPath, ".art.vue")}/${r.variantName}`;
480
- return name.includes(pattern) || matchGlob(name, pattern);
481
- }) : results.filter((r) => !r.passed && !r.error);
794
+ const candidates = results.filter((result) => !result.passed && !result.error);
795
+ const toApprove = pattern ? candidates.filter((result) => {
796
+ const identity = resolveSnapshotIdentity(result.artPath, this.identityOptions.projectRoot, this.identityOptions.snapshotIdentities);
797
+ const relativeName = `${identity.replace(/\.art\.vue$/, "")}/${result.variantName}`;
798
+ const legacyName = `${path.posix.basename(identity, ".art.vue")}/${result.variantName}`;
799
+ return matchesSnapshotPattern(relativeName, pattern) || matchesSnapshotPattern(legacyName, pattern);
800
+ }) : candidates;
801
+ if (pattern) {
802
+ const legacyMatches = results.filter((result) => {
803
+ const identity = resolveSnapshotIdentity(result.artPath, this.identityOptions.projectRoot, this.identityOptions.snapshotIdentities);
804
+ return matchesSnapshotPattern(`${path.posix.basename(identity, ".art.vue")}/${result.variantName}`, pattern);
805
+ });
806
+ if (new Set(legacyMatches.map((result) => result.artPath)).size > 1) throw new Error(`Ambiguous approval pattern ${pattern}; use a project-relative Art path: ${legacyMatches.map((result) => resolveSnapshotIdentity(result.artPath, this.identityOptions.projectRoot, this.identityOptions.snapshotIdentities)).join(", ")}`);
807
+ }
482
808
  return this.updateBaselines(toApprove);
483
809
  }
484
810
  /**
485
811
  * Clean orphaned snapshots (no corresponding art/variant).
486
812
  */
487
813
  async cleanOrphans(artFiles) {
488
- const snapshotDir = this.options.snapshotDir;
814
+ const names = await (await this.getSnapshotIndex()).plan(createVrtJobs(artFiles, this.options.viewports));
815
+ const validNames = new Set(names.values());
816
+ const files = await fs.promises.readdir(this.options.snapshotDir);
489
817
  let cleaned = 0;
490
- try {
491
- const files = await fs.promises.readdir(snapshotDir);
492
- const validNames = /* @__PURE__ */ new Set();
493
- for (const art of artFiles) for (const variant of art.variants) {
494
- if (variant.skipVrt) continue;
495
- for (const viewport of this.options.viewports) validNames.add(buildSnapshotName(art.path, variant.name, viewport));
496
- }
497
- for (const file of files) if (file.endsWith(".png") && !validNames.has(file)) {
498
- await fs.promises.unlink(path.join(snapshotDir, file));
499
- cleaned++;
500
- console.log(`[vrt] Cleaned: ${file}`);
501
- }
502
- } catch {}
818
+ for (const file of files) if (file.endsWith(".png") && !validNames.has(file)) {
819
+ await fs.promises.unlink(path.join(this.options.snapshotDir, file));
820
+ cleaned++;
821
+ console.log(`[vrt] Cleaned: ${file}`);
822
+ }
503
823
  return cleaned;
504
824
  }
505
825
  /**
@@ -509,38 +829,6 @@ var MuseaVrtRunner = class {
509
829
  return computeSummary(results, this.startTime);
510
830
  }
511
831
  };
512
- function normalizeVrtWorkerCount(workers) {
513
- if (workers === void 0 || !Number.isFinite(workers)) return 1;
514
- return Math.max(1, Math.floor(workers));
515
- }
516
- function createVrtJobs(artFiles, defaultViewports) {
517
- const jobs = [];
518
- for (const art of artFiles) for (const variant of art.variants) {
519
- if (variant.skipVrt) continue;
520
- const viewports = variant.args?.viewport ? [variant.args.viewport] : defaultViewports;
521
- for (const viewport of viewports) jobs.push({
522
- art,
523
- variantName: variant.name,
524
- viewport
525
- });
526
- }
527
- return jobs;
528
- }
529
- async function runJobsWithWorkers(jobs, workerCount, runJob) {
530
- const results = Array.from({ length: jobs.length }, () => null);
531
- let nextJobIndex = 0;
532
- async function runWorker() {
533
- while (true) {
534
- const jobIndex = nextJobIndex++;
535
- const job = jobs[jobIndex];
536
- if (!job) return;
537
- results[jobIndex] = await runJob(job);
538
- }
539
- }
540
- const activeWorkers = Math.min(normalizeVrtWorkerCount(workerCount), jobs.length);
541
- await Promise.all(Array.from({ length: activeWorkers }, () => runWorker()));
542
- return results.filter((result) => result !== null);
543
- }
544
832
  //#endregion
545
833
  //#region src/vrt/report.ts
546
834
  /**
@@ -799,6 +1087,13 @@ function generateVrtJsonReport(results, summary) {
799
1087
  summary,
800
1088
  results: results.map((r) => ({
801
1089
  art: path.basename(r.artPath, ".art.vue"),
1090
+ artPath: r.artPath,
1091
+ variantName: r.variantName,
1092
+ snapshotPath: r.snapshotPath,
1093
+ currentPath: r.currentPath,
1094
+ diffPath: r.diffPath,
1095
+ diffPixels: r.diffPixels,
1096
+ totalPixels: r.totalPixels,
802
1097
  variant: r.variantName,
803
1098
  viewport: r.viewport.name || `${r.viewport.width}x${r.viewport.height}`,
804
1099
  status: r.error ? "error" : r.isNew ? "new" : r.passed ? "passed" : "failed",
@@ -811,6 +1106,6 @@ function generateVrtJsonReport(results, summary) {
811
1106
  //#region src/vrt.ts
812
1107
  var vrt_default = MuseaVrtRunner;
813
1108
  //#endregion
814
- export { normalizeVrtWorkerCount as a, MuseaVrtRunner as i, generateVrtJsonReport as n, generateVrtReport as r, vrt_default as t };
1109
+ export { normalizeVrtWorkerCount as a, MuseaVrtRunner as i, generateVrtJsonReport as n, normalizeSnapshotIdentity as o, generateVrtReport as r, resolveSnapshotIdentity as s, vrt_default as t };
815
1110
 
816
- //# sourceMappingURL=vrt-VuGK9wTX.mjs.map
1111
+ //# sourceMappingURL=vrt-PuxpRuHa.mjs.map