strata-react 0.1.5 → 0.1.9

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.
@@ -0,0 +1,605 @@
1
+ import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { extname, join, normalize, resolve, sep } from "node:path";
3
+ import pixelmatch from "pixelmatch";
4
+ import { PNG } from "pngjs";
5
+ import { createServer } from "node:http";
6
+ // src/visual/capture.ts
7
+ var freeze = `*, *::before, *::after { animation: none !important; transition: none !important; caret-color: transparent !important; }`;
8
+ /** Resolves a shot's path under the base URL, keeping the base's own path (`/app/` + `/review`). */
9
+ function resolveShotUrl(path, baseUrl) {
10
+ if (/^[a-z][a-z0-9+.-]*:/i.test(path)) return path;
11
+ return new URL(path.replace(/^\/+/, ""), baseUrl).href;
12
+ }
13
+ /** Converts a request the page made into a Fetch `Request` MSW can match. */
14
+ function toFetchRequest(request) {
15
+ const method = request.method();
16
+ const body = method === "GET" || method === "HEAD" ? void 0 : request.postDataBuffer() ?? void 0;
17
+ return new Request(request.url(), {
18
+ method,
19
+ headers: request.headers(),
20
+ body: body ? new Uint8Array(body) : void 0
21
+ });
22
+ }
23
+ async function answerWithHandlers(context, handlers, baseUrl, unhandled, problems) {
24
+ const msw = await import("msw").catch(() => {
25
+ throw new Error("route shots with handlers need msw: npm install -D msw");
26
+ });
27
+ const origin = new URL(baseUrl).origin;
28
+ await context.route("**/*", async (route) => {
29
+ const request = route.request();
30
+ const response = await msw.getResponse([...handlers], toFetchRequest(request), {
31
+ baseUrl: origin,
32
+ quiet: true
33
+ });
34
+ if (response && response.headers.get("x-msw-intention") !== "passthrough") {
35
+ const headers = {};
36
+ response.headers.forEach((value, key) => headers[key] = value);
37
+ await route.fulfill({
38
+ status: response.status,
39
+ headers,
40
+ body: Buffer.from(await response.arrayBuffer())
41
+ });
42
+ return;
43
+ }
44
+ if (!response && unhandled === "error" && [
45
+ "fetch",
46
+ "xhr",
47
+ "eventsource",
48
+ "websocket"
49
+ ].includes(request.resourceType())) {
50
+ const url = new URL(request.url());
51
+ problems.push(`no handler for ${request.method()} ${url.origin === origin ? "" : url.origin}${url.pathname}${url.search}`);
52
+ }
53
+ await route.continue();
54
+ });
55
+ }
56
+ /** Takes one shot and returns its PNG, or throws with what went wrong. Page and console errors are returned as problems. */
57
+ async function capture(browser, shot, options) {
58
+ const context = await browser.newContext({
59
+ viewport: shot.viewport,
60
+ deviceScaleFactor: 1,
61
+ reducedMotion: "reduce",
62
+ colorScheme: shot.theme,
63
+ timezoneId: options.timezone ?? "UTC",
64
+ locale: options.locale ?? "en-US",
65
+ serviceWorkers: options.blockServiceWorkers ? "block" : "allow"
66
+ });
67
+ const problems = [];
68
+ try {
69
+ if (options.time !== void 0) await context.clock.setFixedTime(options.time);
70
+ if (shot.darkClass) await context.addInitScript(({ cls, dark }) => {
71
+ const apply = () => document.documentElement?.classList.toggle(cls, dark);
72
+ apply();
73
+ document.addEventListener("DOMContentLoaded", apply);
74
+ }, {
75
+ cls: shot.darkClass,
76
+ dark: shot.theme === "dark"
77
+ });
78
+ if (shot.handlers?.length || options.onUnhandledRequest === "error") await answerWithHandlers(context, shot.handlers ?? [], options.baseUrl, options.onUnhandledRequest ?? "bypass", problems);
79
+ const page = await context.newPage();
80
+ page.on("pageerror", (e) => problems.push(e.message));
81
+ page.on("console", (m) => {
82
+ if (m.type() === "error" && !m.text().startsWith("Failed to load resource")) problems.push(m.text());
83
+ });
84
+ await page.goto(resolveShotUrl(shot.path, options.baseUrl), { waitUntil: "load" });
85
+ await page.addStyleTag({ content: freeze });
86
+ await page.waitForFunction((root) => (document.querySelector(root)?.childElementCount ?? 0) > 0, shot.root, { timeout: 15e3 }).catch(() => {
87
+ throw new Error(`${shot.root} stayed empty for 15s`);
88
+ });
89
+ if (shot.waitFor) await page.locator(shot.waitFor).first().waitFor({
90
+ state: "visible",
91
+ timeout: 15e3
92
+ });
93
+ await settle(page);
94
+ if (shot.setup) {
95
+ await shot.setup(page, shot);
96
+ await settle(page);
97
+ }
98
+ let png;
99
+ if (shot.clip === "page") png = await page.screenshot({
100
+ fullPage: true,
101
+ animations: "disabled"
102
+ });
103
+ else {
104
+ const clip = await page.evaluate(paintedBox, {
105
+ root: shot.root,
106
+ margin: 8
107
+ });
108
+ if (!clip) throw new Error("rendered nothing visible");
109
+ png = await page.screenshot({
110
+ fullPage: true,
111
+ clip,
112
+ animations: "disabled"
113
+ });
114
+ }
115
+ return {
116
+ png,
117
+ problems
118
+ };
119
+ } finally {
120
+ await context.close();
121
+ }
122
+ }
123
+ async function settle(page) {
124
+ await page.waitForLoadState("networkidle", { timeout: 3e3 }).catch(() => void 0);
125
+ await page.evaluate(() => document.fonts.ready.then(() => void 0));
126
+ await page.waitForTimeout(250);
127
+ }
128
+ function paintedBox({ root: selector, margin }) {
129
+ const root = document.querySelector(selector);
130
+ if (!root) return null;
131
+ const replaced = /* @__PURE__ */ new Set([
132
+ "IMG",
133
+ "INPUT",
134
+ "SELECT",
135
+ "TEXTAREA",
136
+ "CANVAS",
137
+ "VIDEO",
138
+ "svg",
139
+ "HR"
140
+ ]);
141
+ const transparent = (c) => c === "transparent" || /rgba\(.*,\s*0\)$/.test(c) || /\/\s*0\)$/.test(c);
142
+ const paints = (el) => {
143
+ const cs = getComputedStyle(el);
144
+ if (replaced.has(el.tagName)) return true;
145
+ if (!transparent(cs.backgroundColor) || cs.backgroundImage !== "none" || cs.boxShadow !== "none") return true;
146
+ return [
147
+ "Top",
148
+ "Right",
149
+ "Bottom",
150
+ "Left"
151
+ ].some((s) => parseFloat(cs[`border${s}Width`]) > 0 && cs[`border${s}Style`] !== "none");
152
+ };
153
+ const clipTo = (r, el) => {
154
+ let { left, top, right, bottom } = r;
155
+ for (let a = el.parentElement; a && a !== document.body; a = a.parentElement) {
156
+ const cs = getComputedStyle(a);
157
+ if (cs.overflowX !== "visible" || cs.overflowY !== "visible" || cs.clipPath !== "none" || cs.clip !== "auto") {
158
+ const b = a.getBoundingClientRect();
159
+ left = Math.max(left, b.left);
160
+ top = Math.max(top, b.top);
161
+ right = Math.min(right, b.right);
162
+ bottom = Math.min(bottom, b.bottom);
163
+ }
164
+ if (cs.position === "fixed") break;
165
+ }
166
+ return right - left > 1 && bottom - top > 1 ? {
167
+ left,
168
+ top,
169
+ right,
170
+ bottom
171
+ } : null;
172
+ };
173
+ const rects = [];
174
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT);
175
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {
176
+ if (n.nodeType === Node.TEXT_NODE) {
177
+ if (!n.textContent?.trim() || !n.parentElement) continue;
178
+ const range = document.createRange();
179
+ range.selectNodeContents(n);
180
+ for (const r of range.getClientRects()) {
181
+ const c = clipTo(r, n);
182
+ if (c) rects.push(c);
183
+ }
184
+ continue;
185
+ }
186
+ const el = n;
187
+ if (el.closest("svg") && el.tagName !== "svg") continue;
188
+ if (getComputedStyle(el).visibility === "hidden" || !paints(el)) continue;
189
+ const c = clipTo(el.getBoundingClientRect(), el);
190
+ if (c) rects.push(c);
191
+ }
192
+ if (!rects.length) return null;
193
+ const x0 = Math.max(0, Math.floor(Math.min(...rects.map((r) => r.left)) + scrollX - margin));
194
+ const y0 = Math.max(0, Math.floor(Math.min(...rects.map((r) => r.top)) + scrollY - margin));
195
+ const x1 = Math.min(document.documentElement.scrollWidth, Math.ceil(Math.max(...rects.map((r) => r.right)) + scrollX + margin));
196
+ const y1 = Math.min(document.documentElement.scrollHeight, Math.ceil(Math.max(...rects.map((r) => r.bottom)) + scrollY + margin));
197
+ return {
198
+ x: x0,
199
+ y: y0,
200
+ width: x1 - x0,
201
+ height: y1 - y0
202
+ };
203
+ }
204
+ // src/visual/compare.ts
205
+ /** Per-pixel colour distance pixelmatch treats as equal (0–1). Anti-aliased pixels are ignored. */
206
+ var THRESHOLD = .1;
207
+ /** Differing pixels tolerated before a screenshot counts as changed: sub-pixel text rasterisation
208
+ * noise between machines, never a real change (a 1px border on a button is far more). */
209
+ var MAX_DIFF_PIXELS = 20;
210
+ /** Decodes a PNG file's bytes. */
211
+ function decode(buffer) {
212
+ return PNG.sync.read(Buffer.from(buffer));
213
+ }
214
+ /** Encodes an RGBA image as PNG bytes. */
215
+ function encode({ width, height, data }) {
216
+ const png = new PNG({
217
+ width,
218
+ height
219
+ });
220
+ png.data = Buffer.from(data);
221
+ return PNG.sync.write(png);
222
+ }
223
+ /** Compares two decoded PNGs with pixelmatch. A size change is always a change. */
224
+ function compare(expected, actual, { threshold = THRESHOLD, maxDiffPixels = 20 } = {}) {
225
+ if (expected.width !== actual.width || expected.height !== actual.height) return {
226
+ same: false,
227
+ diffPixels: Number.POSITIVE_INFINITY,
228
+ reason: `size ${expected.width}×${expected.height} → ${actual.width}×${actual.height}`
229
+ };
230
+ const { width, height } = expected;
231
+ const diff = new PNG({
232
+ width,
233
+ height
234
+ });
235
+ const diffPixels = pixelmatch(expected.data, actual.data, diff.data, width, height, {
236
+ threshold,
237
+ includeAA: false
238
+ });
239
+ const same = diffPixels <= maxDiffPixels;
240
+ return {
241
+ same,
242
+ diffPixels,
243
+ reason: `${diffPixels} pixels differ (${(diffPixels / (width * height) * 100).toFixed(3)}%)`,
244
+ diff: same ? void 0 : PNG.sync.write(diff)
245
+ };
246
+ }
247
+ // src/visual/serve.ts
248
+ var types = {
249
+ ".html": "text/html",
250
+ ".js": "text/javascript",
251
+ ".mjs": "text/javascript",
252
+ ".css": "text/css",
253
+ ".json": "application/json",
254
+ ".map": "application/json",
255
+ ".webmanifest": "application/manifest+json",
256
+ ".svg": "image/svg+xml",
257
+ ".png": "image/png",
258
+ ".jpg": "image/jpeg",
259
+ ".jpeg": "image/jpeg",
260
+ ".webp": "image/webp",
261
+ ".avif": "image/avif",
262
+ ".gif": "image/gif",
263
+ ".ico": "image/x-icon",
264
+ ".woff2": "font/woff2",
265
+ ".woff": "font/woff",
266
+ ".ttf": "font/ttf",
267
+ ".txt": "text/plain",
268
+ ".wasm": "application/wasm"
269
+ };
270
+ /** Serves `dir` on 127.0.0.1 under `base`, with history fallback to `index.html` when `spa` is set. */
271
+ async function serveStatic(dir, { spa = false, base = "/" } = {}) {
272
+ const root = resolve(dir);
273
+ const prefix = `/${base.replace(/^\/+|\/+$/g, "")}/`.replace(/^\/\/$/, "/");
274
+ const server = createServer((req, res) => {
275
+ const pathname = decodeURIComponent(new URL(req.url ?? "/", "http://x").pathname);
276
+ if (!pathname.startsWith(prefix) && `${pathname}/` !== prefix) {
277
+ res.writeHead(404).end();
278
+ return;
279
+ }
280
+ const rel = normalize(pathname.slice(prefix.length)).replace(/^([/\\])+/, "");
281
+ let file = join(root, rel || "index.html");
282
+ if (file !== root && !file.startsWith(root + sep)) {
283
+ res.writeHead(404).end();
284
+ return;
285
+ }
286
+ if (existsSync(file) && statSync(file).isDirectory()) file = join(file, "index.html");
287
+ if (!existsSync(file)) {
288
+ const wantsHtml = (req.headers.accept ?? "").includes("text/html");
289
+ if (!spa || !wantsHtml || !existsSync(join(root, "index.html"))) {
290
+ res.writeHead(404).end();
291
+ return;
292
+ }
293
+ file = join(root, "index.html");
294
+ }
295
+ res.writeHead(200, {
296
+ "Content-Type": types[extname(file)] ?? "application/octet-stream",
297
+ "Service-Worker-Allowed": "/"
298
+ });
299
+ createReadStream(file).pipe(res);
300
+ });
301
+ await new Promise((r) => server.listen(0, "127.0.0.1", r));
302
+ const address = server.address();
303
+ return {
304
+ url: `http://127.0.0.1:${typeof address === "object" && address ? address.port : 0}${prefix}`,
305
+ close: () => new Promise((r) => server.close(() => r()))
306
+ };
307
+ }
308
+ // src/visual/types.ts
309
+ /**
310
+ * Named viewports. `wide` and `phone` are what the Storybook tags `visual-wide` and
311
+ * `visual-phone` select; `default` is a laptop-sized screen for routes. (Untagged stories render
312
+ * 1024 wide and 200 tall and grow with the component, see {@link storybookShots}.)
313
+ */
314
+ var viewports = {
315
+ default: {
316
+ width: 1024,
317
+ height: 768
318
+ },
319
+ wide: {
320
+ width: 1440,
321
+ height: 900
322
+ },
323
+ phone: {
324
+ width: 390,
325
+ height: 844
326
+ }
327
+ };
328
+ // src/visual/targets.ts
329
+ /** The light and dark themes, the default for every target. */
330
+ var defaultThemes = ["light", "dark"];
331
+ var storyViewport = {
332
+ width: 1024,
333
+ height: 200
334
+ };
335
+ /**
336
+ * Shots for every story in a built Storybook (its `index.json`), in each theme. Tags pick the
337
+ * viewport: `visual-phone` 390×844, `visual-wide` 1440×900, otherwise 1024 wide; `no-visual`
338
+ * skips the story. A story's own tag beats its file's, since Storybook merges both.
339
+ */
340
+ function storybookShots(target, themes = defaultThemes) {
341
+ const index = JSON.parse(readFileSync(join(target.dir, "index.json"), "utf8"));
342
+ const global = target.themeGlobal ?? "theme";
343
+ return Object.values(index.entries).filter((e) => e.type === "story" && !e.tags?.includes("no-visual")).flatMap((story) => {
344
+ const tag = ["visual-phone", "visual-wide"].find((t) => story.tags?.includes(t));
345
+ const viewport = tag === "visual-phone" ? viewports.phone : tag === "visual-wide" ? viewports.wide : storyViewport;
346
+ return themes.map((theme) => ({
347
+ name: `${story.id}--${theme}`,
348
+ path: `iframe.html?id=${story.id}&viewMode=story&globals=${global}:${theme}`,
349
+ theme,
350
+ viewport: { ...viewport },
351
+ root: "#storybook-root",
352
+ clip: "paint",
353
+ darkClass: false
354
+ }));
355
+ });
356
+ }
357
+ var slug = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
358
+ function viewportName(v) {
359
+ return typeof v === "string" ? v : `${v.width}x${v.height}`;
360
+ }
361
+ function viewportSize(v) {
362
+ if (typeof v !== "string") return {
363
+ width: v.width,
364
+ height: v.height
365
+ };
366
+ const size = viewports[v];
367
+ if (!size) throw new Error(`unknown viewport "${String(v)}": use ${Object.keys(viewports).join(", ")} or { width, height }`);
368
+ return { ...size };
369
+ }
370
+ function stateOf(value) {
371
+ return Array.isArray(value) ? { handlers: value } : value;
372
+ }
373
+ /**
374
+ * Shots for every route of an app in each state, viewport and theme, named
375
+ * `route--state--viewport--theme`. A state's handlers come before the target's base handlers, as
376
+ * `server.use(...)` would put them.
377
+ */
378
+ function routeShots(app, themes = defaultThemes) {
379
+ const shots = [];
380
+ for (const route of app.routes) {
381
+ if (!slug.test(route.name)) throw new Error(`route name "${route.name}" must be lower-case letters, digits and dashes`);
382
+ const states = Object.entries(route.states ?? { default: [] });
383
+ if (!states.length) throw new Error(`route "${route.name}" has an empty states object: leave it out for one default state`);
384
+ const chosen = route.viewports ?? app.viewports ?? ["wide"];
385
+ for (const [stateName, value] of states) {
386
+ if (!slug.test(stateName)) throw new Error(`state "${stateName}" of route "${route.name}" must be lower-case letters, digits and dashes`);
387
+ const state = stateOf(value);
388
+ const setups = [route.setup, state.setup].filter((s) => s !== void 0);
389
+ for (const v of chosen) for (const theme of themes) shots.push({
390
+ name: `${route.name}--${stateName}--${viewportName(v)}--${theme}`,
391
+ path: state.path ?? route.path,
392
+ theme,
393
+ viewport: viewportSize(v),
394
+ root: route.root ?? app.root ?? "#root",
395
+ clip: route.clip ?? app.clip ?? "page",
396
+ waitFor: state.waitFor ?? route.waitFor,
397
+ handlers: [...state.handlers ?? [], ...app.handlers ?? []],
398
+ darkClass: app.darkClass ?? "dark",
399
+ setup: setups.length ? async (page, shot) => {
400
+ for (const s of setups) await s(page, shot);
401
+ } : void 0
402
+ });
403
+ }
404
+ }
405
+ return shots;
406
+ }
407
+ // src/visual/run.ts
408
+ /** Returns the config unchanged; it exists so a config file is type-checked. */
409
+ function defineVisualConfig(config) {
410
+ return config;
411
+ }
412
+ var metaFile = ".strata-visual.json";
413
+ /** Screenshots every shot the config describes, compares with the baselines, and reports. */
414
+ async function runVisual(config, options = {}) {
415
+ const cwd = resolve(options.cwd ?? process.cwd());
416
+ const baselineDir = resolve(cwd, config.baselines ?? "tests/visual/baselines");
417
+ const outputDir = resolve(cwd, config.output ?? "tests/visual/output");
418
+ const themes = config.themes ?? defaultThemes;
419
+ const update = options.update ?? false;
420
+ const ci = options.ci ?? Boolean(process.env.CI);
421
+ const log = options.log ?? (() => void 0);
422
+ const concurrency = config.concurrency ?? 4;
423
+ if (!Number.isInteger(concurrency) || concurrency < 1) throw new Error(`concurrency must be a whole number of pages, 1 or more (got ${String(config.concurrency)})`);
424
+ const report = {
425
+ total: 0,
426
+ same: 0,
427
+ changed: [],
428
+ added: [],
429
+ obsolete: [],
430
+ errors: [],
431
+ warnings: pinWarnings(cwd),
432
+ updated: update,
433
+ failed: false
434
+ };
435
+ const batches = [];
436
+ try {
437
+ if (config.storybook !== void 0) {
438
+ const target = typeof config.storybook === "string" ? { dir: config.storybook } : config.storybook;
439
+ const dir = resolve(cwd, target.dir ?? "storybook-static");
440
+ if (!existsSync(join(dir, "index.json"))) throw new Error(`${join(dir, "index.json")} not found: build Storybook first (storybook build)`);
441
+ const batch = {
442
+ shots: storybookShots({
443
+ ...target,
444
+ dir
445
+ }, themes),
446
+ baseUrl: "",
447
+ blockServiceWorkers: false
448
+ };
449
+ batches.push(batch);
450
+ batch.server = await serveStatic(dir);
451
+ batch.baseUrl = batch.server.url;
452
+ }
453
+ if (config.app !== void 0) {
454
+ const app = config.app;
455
+ if (!app.dir === !app.url) throw new Error("app needs exactly one of dir (a build to serve) or url (a running server)");
456
+ const batch = {
457
+ shots: routeShots(app, themes),
458
+ baseUrl: "",
459
+ blockServiceWorkers: true,
460
+ onUnhandledRequest: app.onUnhandledRequest ?? "error"
461
+ };
462
+ batches.push(batch);
463
+ if (app.dir) {
464
+ const dir = resolve(cwd, app.dir);
465
+ if (!existsSync(join(dir, "index.html"))) throw new Error(`${join(dir, "index.html")} not found: build the app first`);
466
+ batch.server = await serveStatic(dir, {
467
+ spa: true,
468
+ base: app.base
469
+ });
470
+ batch.baseUrl = batch.server.url;
471
+ } else batch.baseUrl = new URL(`${(app.base ?? "/").replace(/^\/*/, "/").replace(/\/*$/, "/")}`, app.url).href;
472
+ }
473
+ if (!batches.length) throw new Error("nothing to screenshot: the config needs storybook or app");
474
+ const all = batches.flatMap((b) => b.shots);
475
+ const names = /* @__PURE__ */ new Set();
476
+ for (const s of all) {
477
+ if (names.has(s.name)) throw new Error(`two shots are named ${s.name}: give routes and states distinct names`);
478
+ names.add(s.name);
479
+ }
480
+ for (const b of batches) b.shots = b.shots.filter((s) => !options.filter || s.name.includes(options.filter));
481
+ report.total = batches.reduce((n, b) => n + b.shots.length, 0);
482
+ mkdirSync(baselineDir, { recursive: true });
483
+ rmSync(outputDir, {
484
+ recursive: true,
485
+ force: true
486
+ });
487
+ mkdirSync(outputDir, { recursive: true });
488
+ const { chromium } = await import("playwright").catch(() => {
489
+ throw new Error("strata-visual needs Playwright: npm install -D -E playwright, then npx playwright install chromium");
490
+ });
491
+ const browser = await chromium.launch({ args: [
492
+ "--font-render-hinting=none",
493
+ "--disable-lcd-text",
494
+ "--force-color-profile=srgb"
495
+ ] });
496
+ const meta = {
497
+ chromium: browser.version(),
498
+ platform: `${process.platform}-${process.arch}`
499
+ };
500
+ try {
501
+ for (const batch of batches) await runBatch(browser, batch, {
502
+ config,
503
+ baselineDir,
504
+ outputDir,
505
+ update,
506
+ report,
507
+ log
508
+ });
509
+ } finally {
510
+ await browser.close();
511
+ }
512
+ const pngs = readdirSync(baselineDir).filter((f) => f.endsWith(".png"));
513
+ report.obsolete = options.filter ? [] : pngs.filter((f) => !names.has(f.slice(0, -4)));
514
+ if (update) {
515
+ for (const f of report.obsolete) rmSync(join(baselineDir, f));
516
+ if (!options.filter) writeFileSync(join(baselineDir, metaFile), `${JSON.stringify(meta, null, 2)}\n`);
517
+ } else if (report.changed.length) {
518
+ const written = readMeta(baselineDir);
519
+ if (written && (written.chromium !== meta.chromium || written.platform !== meta.platform)) report.warnings.push(`the baselines were written by Chromium ${written.chromium} on ${written.platform}; this run used Chromium ${meta.chromium} on ${meta.platform}, so some differences may be the browser, not the app`);
520
+ }
521
+ } finally {
522
+ for (const b of batches) await b.server?.close();
523
+ }
524
+ report.failed = Boolean(report.errors.length || report.changed.length || ci && !update && report.added.length);
525
+ return report;
526
+ }
527
+ async function runBatch(browser, batch, ctx) {
528
+ const { baselineDir, outputDir, update, report } = ctx;
529
+ const shoot = async (shot) => {
530
+ const file = `${shot.name}.png`;
531
+ try {
532
+ const { png, problems } = await capture(browser, shot, {
533
+ baseUrl: batch.baseUrl,
534
+ time: ctx.config.time,
535
+ timezone: ctx.config.timezone,
536
+ locale: ctx.config.locale,
537
+ blockServiceWorkers: batch.blockServiceWorkers,
538
+ onUnhandledRequest: batch.onUnhandledRequest
539
+ });
540
+ if (problems.length) report.errors.push(`${file}: ${problems.join(" | ")}`);
541
+ const baselinePath = join(baselineDir, file);
542
+ if (update || !existsSync(baselinePath)) {
543
+ if (!update) report.added.push(file);
544
+ writeFileSync(baselinePath, png);
545
+ if (!update) writeFileSync(join(outputDir, file), png);
546
+ return;
547
+ }
548
+ const expected = readFileSync(baselinePath);
549
+ const result = compare(decode(expected), decode(png));
550
+ if (result.same) {
551
+ report.same++;
552
+ return;
553
+ }
554
+ report.changed.push(`${file}: ${result.reason}`);
555
+ writeFileSync(join(outputDir, `${shot.name}.actual.png`), png);
556
+ writeFileSync(join(outputDir, `${shot.name}.expected.png`), expected);
557
+ if (result.diff) writeFileSync(join(outputDir, `${shot.name}.diff.png`), result.diff);
558
+ } catch (e) {
559
+ report.errors.push(`${file}: ${(e instanceof Error ? e.message : String(e)).split("\n")[0]}`);
560
+ } finally {
561
+ ctx.log(file);
562
+ }
563
+ };
564
+ const queue = [...batch.shots];
565
+ await Promise.all(Array.from({ length: ctx.config.concurrency ?? 4 }, async () => {
566
+ for (let shot = queue.shift(); shot; shot = queue.shift()) await shoot(shot);
567
+ }));
568
+ }
569
+ function readMeta(dir) {
570
+ try {
571
+ return JSON.parse(readFileSync(join(dir, metaFile), "utf8"));
572
+ } catch {
573
+ return;
574
+ }
575
+ }
576
+ /** A warning when the app's package.json lets Playwright float, since each version brings its own Chromium. */
577
+ function pinWarnings(cwd) {
578
+ let pkg;
579
+ try {
580
+ pkg = JSON.parse(readFileSync(join(cwd, "package.json"), "utf8"));
581
+ } catch {
582
+ return [];
583
+ }
584
+ const deps = {
585
+ ...pkg.dependencies,
586
+ ...pkg.devDependencies
587
+ };
588
+ return ["playwright", "@playwright/test"].filter((name) => deps[name] !== void 0 && !/^\d+\.\d+\.\d+$/.test(deps[name])).map((name) => `${name} is "${deps[name]}" in package.json: pin an exact version (npm install -D -E ${name}) so CI and the machine that wrote the baselines render with the same Chromium`);
589
+ }
590
+ /** The report as the lines the command prints. */
591
+ function formatReport(report) {
592
+ const lines = [
593
+ report.updated ? `Wrote ${report.total} baselines${report.obsolete.length ? `, removed ${report.obsolete.length} obsolete` : ""}.` : `${report.same} of ${report.total} screenshots match their baselines.`,
594
+ ...report.changed.map((l) => `changed ${l}`),
595
+ ...report.added.map((l) => `new ${l} (baseline written; commit it)`),
596
+ ...report.obsolete.map((l) => `obsolete ${l}${report.updated ? " (removed)" : " (run with --update to remove)"}`),
597
+ ...report.errors.map((l) => `error ${l}`),
598
+ ...report.warnings.map((l) => `warning ${l}`)
599
+ ];
600
+ if (report.failed) lines.push("", "Diffs are in the output folder (tests/visual/output by default). Look at them; if the change is intended, run with --update and commit the baselines.");
601
+ return lines.join("\n");
602
+ }
603
+ export { toFetchRequest as _, defaultThemes as a, viewports as c, THRESHOLD as d, compare as f, resolveShotUrl as g, capture as h, runVisual as i, serveStatic as l, encode as m, formatReport as n, routeShots as o, decode as p, pinWarnings as r, storybookShots as s, defineVisualConfig as t, MAX_DIFF_PIXELS as u };
604
+
605
+ //# sourceMappingURL=run-CLQi924v.js.map