@krizaka/page-audit 0.3.1 → 0.5.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.
package/README.md CHANGED
@@ -24,7 +24,8 @@ before anything is measured (yomizaka#354). `prepare(page, route)` signs in or s
24
24
  Opt-in through `checks` (nothing changes for a repo that does not ask): `status` (HTTP 4xx/5xx or no response), `emptyMain`, `frame`
25
25
  (the signed-in frame, `[data-app-frame-slot]`, forces a scroll), `minAction` (a button-styled action under N px), `boxes` (a landmark
26
26
  wider than its box), `landmarks` (`"public"` one footer naming Krizaka and a nav, `"app"`, `"auth"`), `pictures`, `emptyControls`,
27
- `hardColors`. Console noise the app tolerates: `ignoreConsole: [/…/]` (`[]` counts every error); `attempts` retries a route.
27
+ `hardColors`, `maps` (an empty map, akinaza#488: a GL / Leaflet / `[data-kz-map]` box under 120 px on a side, a GL map with no canvas,
28
+ a Leaflet map with no loaded tile; `maps: { required: true }` also fails a page that should draw one but has none). Console noise the app tolerates: `ignoreConsole: [/…/]` (`[]` counts every error); `attempts` retries a route.
28
29
 
29
30
  ```js
30
31
  const routes = await routesFromSitemap(base, { first: ["/", "/docs"], limit: 14 }); // a crawl as the route source (null: nothing answers)
@@ -39,3 +40,26 @@ await auditRoutes({
39
40
 
40
41
  `a11y` runs axe through `@krizaka/a11y-audit` (an optional peer) and ratchets with the repo's own baseline file; `--a11y-update` and
41
42
  `--a11y-init` work as there. The CLI takes `--sitemap`, `--status`, `--empty-main`, `--min-action`, `--a11y app:baseline.json`.
43
+
44
+ ## Visual regression of the journeys (0.4)
45
+
46
+ `@krizaka/page-audit/visual` (krizaka/.github#375) compares screenshots of an app's main journeys against Linux baselines, with `@playwright/test`
47
+ as the runner. It freezes what moves (clock, motion, caret, View Transition, locale, time zone, fonts) and leaves the app its routes, its persona and its masks.
48
+
49
+ ```js
50
+ import { test, expect } from "@playwright/test";
51
+ import { defineJourneyTests } from "@krizaka/page-audit/visual";
52
+ defineJourneyTests({
53
+ test, expect,
54
+ signIn: async (page) => { /* the seeded persona signs in through the form */ },
55
+ journeys: [
56
+ { name: "landing", path: "/fr" },
57
+ { name: "home", path: "/fr/app", session: true, mask: ["[data-live]"] },
58
+ { name: "home", path: "/fr/app", session: true, firstPaint: true, viewports: ["phone"] }, // the HTML the server sent
59
+ { name: "home", path: "/fr/app", session: true, firstPaint: { hold: ["**/api/me"] } }, // hydrated, account query pending
60
+ ],
61
+ });
62
+ ```
63
+
64
+ Baselines are taken in the official Playwright container by the shared workflows of krizaka/.github (`visual-regression.yml` to compare,
65
+ `update-visual-baselines.yml` to commit them on a branch); never on a Mac.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@krizaka/page-audit",
3
- "version": "0.3.1",
3
+ "version": "0.5.0",
4
4
  "description": "The page audit of every Krizaka app, in one place: HTTP status, empty main, horizontal overflow, a card out of its panel, sections covering each other, a column cut off, top chrome overlaps, unnamed buttons, empty headings. Runs in a real browser (Playwright) over a route list, viewports and themes, with View Transitions neutralised and a self-test on its own fixtures.",
5
5
  "keywords": [
6
6
  "krizaka",
@@ -34,7 +34,11 @@
34
34
  "import": "./src/settle.mjs"
35
35
  },
36
36
  "./fixtures": "./src/fixtures.mjs",
37
- "./package.json": "./package.json"
37
+ "./package.json": "./package.json",
38
+ "./visual": {
39
+ "types": "./src/visual.d.ts",
40
+ "import": "./src/visual.mjs"
41
+ }
38
42
  },
39
43
  "files": [
40
44
  "src",
package/src/fixtures.mjs CHANGED
@@ -48,3 +48,12 @@ export const CHROME_BAD = `<!doctype html><html><body><main><p>Hello</p></main><
48
48
  export const TOKEN_IN_STRETCHED_ROW = page(`<table style="width:600px"><tbody><tr><td>orazaka-media-pack</td><td>${"A long description. ".repeat(30)}</td></tr></tbody></table>`);
49
49
  /** An identifier in a narrow cell that breaks every few characters. */
50
50
  export const TOKEN_WRAPPED = page(`<table style="width:100px;table-layout:fixed"><tbody><tr><td style="word-break:break-all;font-size:20px">abcdefghijklmnopqrstuvwxyz0123456789</td></tr></tbody></table>`);
51
+
52
+ /** A map that laid out at 0 px: `absolute inset-0` in a frame with no height of its own (akinaza#488). */
53
+ export const MAP_COLLAPSED = page(`<section><div style="position:relative"><div class="maplibregl-map" style="position:absolute;inset:0"><canvas width="0" height="0"></canvas></div></div></section>`);
54
+ /** A map box with a size and a canvas, and a Leaflet one with a loaded tile. */
55
+ export const MAP_FINE = page(`<section><div class="maplibregl-map" style="height:300px;width:600px"><canvas style="width:600px;height:300px" width="600" height="300"></canvas></div><div class="leaflet-container" style="height:300px;width:600px"><img class="leaflet-tile-loaded" alt="" width="256" height="256"></div></section>`);
56
+ /** A GL map box of a good size where nothing was drawn (no canvas). */
57
+ export const MAP_NO_CANVAS = page(`<section><div class="maplibregl-map" style="height:300px;width:600px"></div></section>`);
58
+ /** A map that is not drawn (display none: a closed tab, a small screen): nothing to measure. */
59
+ export const MAP_HIDDEN = page(`<section><div class="maplibregl-map" style="display:none"></div></section>`);
package/src/index.d.ts CHANGED
@@ -9,6 +9,8 @@ export interface ProblemChecks {
9
9
  /** HTTP status of the load (`null`: no response); a 4xx/5xx is a problem. */
10
10
  status?: number | null;
11
11
  emptyMain?: boolean; frame?: boolean; minAction?: number; boxes?: boolean; landmarks?: Chrome; pictures?: boolean; emptyControls?: boolean; hardColors?: boolean;
12
+ /** Empty maps (a GL / Leaflet / `[data-kz-map]` box under 120 px, no canvas, no loaded tile); `{ min, required }` to tune, `required` fails a page with no map. */
13
+ maps?: boolean | { min?: number; required?: boolean };
12
14
  }
13
15
  export function problemsOf(where: string, result: Record<string, unknown>, checks?: ProblemChecks): string[];
14
16
  export function auditOptions<T extends object>(options?: T): T & { reducedMotion: "reduce" };
@@ -261,6 +261,21 @@ function hardColorsOf() {
261
261
  return [...document.querySelectorAll("[style]")].filter((e) => /#[0-9a-f]{3,8}\b|rgba?\(/i.test(e.getAttribute("style") || "") && !/var\(/.test(e.getAttribute("style") || "")).length;
262
262
  }
263
263
 
264
+ /**
265
+ * The live maps of the page (maplibre / mapbox GL, Leaflet, or anything marked `[data-kz-map]`): a map is a box with a size and something drawn in it.
266
+ * One that lays out at 0 px (an `absolute inset-0` map in a frame with no height of its own) overflows nothing, so no other probe sees it.
267
+ * GL maps are told by their canvas; Leaflet by its loaded tiles. A map with no client rect (`display: none`, a closed tab) is not drawn, so not measured.
268
+ */
269
+ function mapsOf() {
270
+ return [...document.querySelectorAll(".maplibregl-map, .mapboxgl-map, .leaflet-container, [data-kz-map]")]
271
+ .filter((el) => el.getClientRects().length > 0 && !el.closest(ARIA_HIDDEN) && !folded(el) && !el.parentElement?.closest(".maplibregl-map, .mapboxgl-map, .leaflet-container, [data-kz-map]"))
272
+ .map((el) => {
273
+ const box = el.getBoundingClientRect();
274
+ const canvas = el.querySelector("canvas")?.getBoundingClientRect();
275
+ return { name: nameOf(el), width: Math.round(box.width), height: Math.round(box.height), canvas: !!canvas && canvas.width > 0 && canvas.height > 0, leaflet: el.classList.contains("leaflet-container"), tiles: el.querySelectorAll(".leaflet-tile-loaded").length };
276
+ });
277
+ }
278
+
264
279
  function measurePage() {
265
280
  const doc = document.documentElement;
266
281
  const panels = [...document.querySelectorAll("[data-panel], main section, main [role=region]")].filter((el) => !el.closest(ARIA_HIDDEN) && !folded(el));
@@ -290,11 +305,12 @@ function measurePage() {
290
305
  brokenPictures: brokenPicturesOf(),
291
306
  emptyControls: emptyControlsOf(),
292
307
  hardColors: hardColorsOf(),
308
+ maps: mapsOf(),
293
309
  segmentError: !!document.querySelector('[data-testid="segment-error"]'),
294
310
  };
295
311
  }
296
312
 
297
- const PROBES = [tooTall, wrappedOf, className, nameOf, scrolls, meets, apart, clipped, wideOf, named, unnamedOf, headerActionOf, folded, keptBetween, notDrawn, runsOut, spillOf, overlapsOf, cutBy, cutColumnsOf, topBoxOf, isTopBar, chromeOverlapsOf, clipsOf, emptyHeadingsOf, unlabelledFilesOf, emptyMainOf, actionsOf, frameOf, boxesOf, landmarksOf, brokenPicturesOf, emptyControlsOf, hardColorsOf, measurePage];
313
+ const PROBES = [tooTall, wrappedOf, className, nameOf, scrolls, meets, apart, clipped, wideOf, named, unnamedOf, headerActionOf, folded, keptBetween, notDrawn, runsOut, spillOf, overlapsOf, cutBy, cutColumnsOf, topBoxOf, isTopBar, chromeOverlapsOf, clipsOf, emptyHeadingsOf, unlabelledFilesOf, emptyMainOf, actionsOf, frameOf, boxesOf, landmarksOf, brokenPicturesOf, emptyControlsOf, hardColorsOf, mapsOf, measurePage];
298
314
 
299
315
  /** The expression Playwright runs in the page (`page.evaluate(auditPage)`): the probes, serialised together, then the measure. */
300
316
  export const auditPage = `(() => {\nconst ARIA_HIDDEN = ${JSON.stringify(ARIA_HIDDEN)};\n${PROBES.map((f) => `const ${f.name} = ${f.toString()};`).join("\n")}\nreturn measurePage();\n})()`;
@@ -311,7 +327,7 @@ function accessibilityProblems(where, result, fileLabels) {
311
327
  return problems;
312
328
  }
313
329
 
314
- export function problemsOf(where, result, { errors = [], h1 = false, headerAction = false, fileLabels = false, status, emptyMain = false, frame = false, minAction, boxes = false, landmarks, pictures = false, emptyControls = false, hardColors = false } = {}) {
330
+ export function problemsOf(where, result, { errors = [], h1 = false, headerAction = false, fileLabels = false, status, emptyMain = false, frame = false, minAction, boxes = false, landmarks, pictures = false, emptyControls = false, hardColors = false, maps = false } = {}) {
315
331
  return [
316
332
  ...statusProblems(where, status),
317
333
  ...(emptyMain && result.emptyMain ? [`${where}: empty <main>`] : []),
@@ -322,6 +338,7 @@ export function problemsOf(where, result, { errors = [], h1 = false, headerActio
322
338
  ...(pictures && result.brokenPictures?.length ? [`${where}: broken picture ${result.brokenPictures.join(", ")}`] : []),
323
339
  ...(emptyControls ? (result.emptyControls ?? []).map((c) => `${where}: ${c}`) : []),
324
340
  ...(hardColors && result.hardColors ? [`${where}: ${result.hardColors} element(s) with a hard-coded colour in an inline style`] : []),
341
+ ...(maps ? mapProblems(where, result.maps ?? [], maps) : []),
325
342
  ...errorsOf(where, errors),
326
343
  ...layoutProblems(where, result),
327
344
  ...(h1 ? namingProblems(where, result) : []),
@@ -331,6 +348,24 @@ export function problemsOf(where, result, { errors = [], h1 = false, headerActio
331
348
  ];
332
349
  }
333
350
 
351
+ /** The smallest side (px) of a map worth the name. */
352
+ export const MIN_MAP_SIDE = 120;
353
+
354
+ /**
355
+ * An empty map (akinaza#488): a box under `min` px on a side, a GL map with no canvas, a Leaflet map with no loaded tile.
356
+ * `maps` is `true` (the default minimum) or `{ min, required }`; with `required`, a page that was expected to draw a map and has none is a problem too.
357
+ */
358
+ function mapProblems(where, found, option) {
359
+ const { min = MIN_MAP_SIDE, required = false } = option === true ? {} : option;
360
+ if (!found.length) return required ? [`${where}: no map on the page`] : [];
361
+ const out = [];
362
+ for (const m of found) {
363
+ if (m.width < min || m.height < min) out.push(`${where}: the map ${m.name} is ${m.width}x${m.height} px (empty)`);
364
+ else if (m.leaflet ? m.tiles === 0 : !m.canvas) out.push(`${where}: the map ${m.name} ${m.leaflet ? "has no loaded tile" : "has no canvas"}`);
365
+ }
366
+ return out;
367
+ }
368
+
334
369
  function errorsOf(where, errors) {
335
370
  return errors.length ? [`${where}: console error — ${errors[0]}`] : [];
336
371
  }
package/src/self-test.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  // The audit proven on its own fixtures, in a real browser: each broken fixture must be reported, the fine ones must not.
2
2
  // A guard that stopped seeing is itself a red build.
3
- import { BOX_TOO_WIDE, BROKEN_PARTS, CARD_OVER_NEXT, CHROME_BAD, CHROME_FINE, COLUMN_CUT, EMPTY_MAIN, FINE, FOLDED_SECTION, FRAME_FITS, FRAME_FORCES_SCROLL, HIDDEN_CONTENT, SECTIONS_OVERLAP, SMALL_ACTION, TOKEN_IN_STRETCHED_ROW, TOKEN_WRAPPED } from "./fixtures.mjs";
3
+ import { BOX_TOO_WIDE, BROKEN_PARTS, CARD_OVER_NEXT, CHROME_BAD, CHROME_FINE, COLUMN_CUT, EMPTY_MAIN, FINE, FOLDED_SECTION, FRAME_FITS, FRAME_FORCES_SCROLL, HIDDEN_CONTENT, MAP_COLLAPSED, MAP_FINE, MAP_HIDDEN, MAP_NO_CANVAS, SECTIONS_OVERLAP, SMALL_ACTION, TOKEN_IN_STRETCHED_ROW, TOKEN_WRAPPED } from "./fixtures.mjs";
4
4
  import { auditPage, problemsOf } from "./page-audit.mjs";
5
5
  import { auditContext } from "./settle.mjs";
6
6
 
@@ -17,6 +17,9 @@ const EXPECT = [
17
17
  ["a broken picture", BROKEN_PARTS, /broken picture/, { pictures: true }],
18
18
  ["a tile that draws nothing", BROKEN_PARTS, /empty tile/, { emptyControls: true }],
19
19
  ["a hard-coded inline colour", BROKEN_PARTS, /hard-coded colour/, { hardColors: true }],
20
+ ["a map that laid out at 0 px", MAP_COLLAPSED, /the map .* is \d+x0 px \(empty\)/, { maps: true }],
21
+ ["a map with no canvas", MAP_NO_CANVAS, /has no canvas/, { maps: true }],
22
+ ["no map where one is required", FINE, /no map on the page/, { maps: { required: true } }],
20
23
  ["two page footers and no nav", CHROME_BAD, /2 page footers/, { landmarks: "public" }],
21
24
  ["no nav landmark", CHROME_BAD, /no <nav> landmark/, { landmarks: "app" }],
22
25
  ];
@@ -27,10 +30,12 @@ const FINES = [
27
30
  ["a short token in a row a taller neighbour stretches", TOKEN_IN_STRETCHED_ROW],
28
31
  ];
29
32
  /** Fixtures that must stay clean even with every opt-in check on. */
30
- const ALL = { emptyMain: true, frame: true, minAction: 36, boxes: true, pictures: true, emptyControls: true, hardColors: true, landmarks: "public" };
33
+ const ALL = { emptyMain: true, frame: true, minAction: 36, boxes: true, pictures: true, emptyControls: true, hardColors: true, landmarks: "public", maps: true };
31
34
  const FINES_STRICT = [
32
35
  ["a frame that fits its screen", FRAME_FITS, { frame: true, emptyMain: false }],
33
36
  ["the family chrome", CHROME_FINE, ALL],
37
+ ["maps with a size and something drawn", MAP_FINE, { maps: true }],
38
+ ["a map that is not drawn (display none)", MAP_HIDDEN, { maps: true }],
34
39
  ];
35
40
 
36
41
  async function problemsOn(page, html, checks) {
@@ -0,0 +1,26 @@
1
+ import type { Browser,Page } from "playwright-core";
2
+
3
+ export interface Size { width: number; height: number }
4
+ export const VIEWPORTS: Readonly<{ desktop: Size; phone: Size }>;
5
+ export const VISUAL_THEMES: readonly ["light", "dark"];
6
+ export const FROZEN_TIME: string;
7
+ export const VISUAL_LOCALE: string;
8
+ export const VISUAL_TIME_ZONE: string;
9
+ export const FREEZE_CSS: string;
10
+ export interface Journey {
11
+ name: string; path: string | ((page: Page, o: { origin: string }) => Promise<string>); session?: boolean; mask?: string[]; viewports?: string[];
12
+ ready?: string | ((page: Page) => Promise<unknown>);
13
+ firstPaint?: true | { hold: string[] };
14
+ }
15
+ export interface Cell { viewport: string; size: Size; theme: string; snapshot: string }
16
+ export function visualMatrix(journey: Journey, options?: { viewports?: Record<string, Size>; themes?: readonly string[] }): Cell[];
17
+ export function visualContextOptions(o: { size: Size; theme: string; javaScript?: boolean; storageState?: unknown }): Record<string, unknown>;
18
+ export function initVisualPage(o: { theme: string; themeKey: string }): void;
19
+ export function prepareVisualPage(page: Page, o?: { theme?: string; themeKey?: string; now?: string }): Promise<void>;
20
+ export function settleForShot(page: Page, o?: { javaScript?: boolean }): Promise<void>;
21
+ export function shotOptions(o?: { mask?: string[]; page?: Page }): Record<string, unknown>;
22
+ export function defineJourneyTests(o: {
23
+ test: unknown; expect: unknown; journeys: Journey[]; signIn: (page: Page, o: { base?: string }) => Promise<void>;
24
+ base?: string; viewports?: Record<string, Size>; themes?: readonly string[]; themeKey?: string; now?: string;
25
+ }): void;
26
+ export type { Browser };
package/src/visual.mjs ADDED
@@ -0,0 +1,143 @@
1
+ // Visual regression of the main journeys, one source for every app (krizaka/.github#375).
2
+ //
3
+ // What it fixes so that two runs of the same build give the same pixels: a frozen clock, reduced motion, no caret, no
4
+ // View Transition, the fonts loaded, a fixed locale and time zone, the app's theme key set before the page runs, and the
5
+ // live values masked. What it leaves to the app: its routes, how its persona signs in, what is live on its pages.
6
+ // The baselines are Linux ones, taken in the official Playwright container (the `visual-regression` workflow of
7
+ // krizaka/.github); the helper never compares against a baseline taken on a Mac.
8
+ //
9
+ // import { test, expect } from "@playwright/test";
10
+ // import { defineJourneyTests } from "@krizaka/page-audit/visual";
11
+ // defineJourneyTests({ test, expect, journeys: [{ name: "landing", path: "/fr" }, …], signIn });
12
+
13
+ import { settled, withoutViewTransitions } from "./settle.mjs";
14
+
15
+ /** The two sizes of every journey: a laptop and a phone. */
16
+ export const VIEWPORTS = Object.freeze({
17
+ desktop: { width: 1280, height: 800 },
18
+ phone: { width: 390, height: 844 },
19
+ });
20
+ export const VISUAL_THEMES = Object.freeze(["light", "dark"]);
21
+ /** The clock of every capture (a Thursday, in winter: no daylight-saving edge). */
22
+ export const FROZEN_TIME = "2026-01-15T15:00:00.000Z";
23
+ export const VISUAL_LOCALE = "fr-CA";
24
+ export const VISUAL_TIME_ZONE = "America/Toronto";
25
+
26
+ /** The viewport × theme cells of a journey, with the snapshot name of each (`<journey>-<viewport>-<theme>.png`). */
27
+ export function visualMatrix(journey, { viewports = VIEWPORTS, themes = VISUAL_THEMES } = {}) {
28
+ const only = journey.viewports ?? Object.keys(viewports);
29
+ const cells = [];
30
+ for (const viewport of only) {
31
+ if (!viewports[viewport]) throw new Error(`unknown viewport « ${viewport} » in journey « ${journey.name} »`);
32
+ for (const theme of themes) {
33
+ const suffix = journey.firstPaint ? "-first-paint" : "";
34
+ cells.push({ viewport, size: viewports[viewport], theme, snapshot: `${journey.name}${suffix}-${viewport}-${theme}.png` });
35
+ }
36
+ }
37
+ return cells;
38
+ }
39
+
40
+ /** The options of a browser context for a capture. `javaScript: false` shows the page as the server sent it. */
41
+ export function visualContextOptions({ size, theme, javaScript = true, storageState }) {
42
+ return {
43
+ viewport: size,
44
+ colorScheme: theme,
45
+ reducedMotion: "reduce",
46
+ locale: VISUAL_LOCALE,
47
+ timezoneId: VISUAL_TIME_ZONE,
48
+ deviceScaleFactor: 1,
49
+ javaScriptEnabled: javaScript,
50
+ serviceWorkers: "block",
51
+ ...(storageState ? { storageState } : {}),
52
+ };
53
+ }
54
+
55
+ /** The style every capture carries: nothing moves, nothing blinks. */
56
+ export const FREEZE_CSS = "*,*::before,*::after{animation:none!important;transition:none!important;caret-color:transparent!important;scroll-behavior:auto!important}";
57
+
58
+ /** Runs before the page's own scripts: the theme the app reads, no View Transition. */
59
+ export const initVisualPage = ({ theme, themeKey }) => {
60
+ try {
61
+ localStorage.setItem(themeKey, theme);
62
+ } catch {
63
+ /* storage can be blocked: the colour scheme of the context still applies */
64
+ }
65
+ };
66
+
67
+ /** Prepares a page: fixed time, the theme key, no View Transition. Call before the first `goto`. */
68
+ export async function prepareVisualPage(page, { theme, themeKey = "kz-theme", now = FROZEN_TIME } = {}) {
69
+ // Date is fixed, timers still run: the app finishes loading.
70
+ await page.context().clock.setFixedTime(new Date(now));
71
+ await page.addInitScript(initVisualPage, { theme, themeKey });
72
+ await page.addInitScript(withoutViewTransitions);
73
+ }
74
+
75
+ /** Waits until what is on screen is final: the faces, the images, the transitions. */
76
+ export async function settleForShot(page, { javaScript = true } = {}) {
77
+ await page.addStyleTag({ content: FREEZE_CSS });
78
+ if (!javaScript) return;
79
+ await page.evaluate(() => document.fonts.ready);
80
+ await settled(page);
81
+ await page.evaluate(() =>
82
+ Promise.all([...document.images].filter((img) => !img.complete).map((img) => img.decode().catch(() => undefined))),
83
+ );
84
+ }
85
+
86
+ /** The options of `toHaveScreenshot`: a small tolerance for anti-aliasing, never for a missing element. */
87
+ export function shotOptions({ mask = [], page } = {}) {
88
+ return {
89
+ animations: "disabled",
90
+ caret: "hide",
91
+ scale: "css",
92
+ maxDiffPixelRatio: 0.002,
93
+ ...(page && mask.length ? { mask: mask.map((selector) => page.locator(selector)) } : {}),
94
+ };
95
+ }
96
+
97
+ /**
98
+ * Registers one test per journey × viewport × theme.
99
+ *
100
+ * journey: { name, path (a string, or `(page, { origin }) => Promise<string>` that finds it, e.g. the first document), session?: boolean, mask?: string[] (selectors of live values), ready?: selector | (page) => Promise,
101
+ * viewports?: string[], firstPaint?: true | { hold: string[] } }
102
+ * firstPaint: the page before it is alive. `true` turns JavaScript off (the HTML the server sent); `{ hold }` keeps JavaScript
103
+ * but never answers the listed URL patterns (the account query, say), so the account mark is captured while its query is pending.
104
+ * now: the instant of the browser clock (default FROZEN_TIME); an app whose seed stamps rows with the day of the run passes that moment.
105
+ * signIn(page, { base }): signs the persona in; its cookies are kept and reused by every signed-in capture of the worker.
106
+ */
107
+ export function defineJourneyTests({ test, expect, journeys, signIn, base, viewports = VIEWPORTS, themes = VISUAL_THEMES, themeKey = "kz-theme", now = FROZEN_TIME }) {
108
+ let session;
109
+ const sessionState = (browser) => {
110
+ session ??= (async () => {
111
+ const context = await browser.newContext(visualContextOptions({ size: viewports.desktop ?? Object.values(viewports)[0], theme: "light" }));
112
+ const page = await context.newPage();
113
+ await signIn(page, { base });
114
+ const state = await context.storageState();
115
+ await context.close();
116
+ return state;
117
+ })();
118
+ return session;
119
+ };
120
+ for (const journey of journeys) {
121
+ for (const cell of visualMatrix(journey, { viewports, themes })) {
122
+ test(`${journey.name} · ${cell.viewport} · ${cell.theme}${journey.firstPaint ? " · first paint" : ""}`, async ({ browser, baseURL }) => {
123
+ const origin = base ?? baseURL;
124
+ const javaScript = !(journey.firstPaint === true);
125
+ const storageState = journey.session ? await sessionState(browser) : undefined;
126
+ const context = await browser.newContext(visualContextOptions({ size: cell.size, theme: cell.theme, javaScript, storageState }));
127
+ try {
128
+ const page = await context.newPage();
129
+ await prepareVisualPage(page, { theme: cell.theme, themeKey, now });
130
+ for (const pattern of journey.firstPaint?.hold ?? []) await page.route(pattern, () => undefined);
131
+ const path = typeof journey.path === "function" ? await journey.path(page, { origin }) : journey.path;
132
+ await page.goto(new URL(path, origin).toString(), { waitUntil: journey.firstPaint ? "domcontentloaded" : "load" });
133
+ if (typeof journey.ready === "string") await page.locator(journey.ready).first().waitFor();
134
+ else if (journey.ready) await journey.ready(page);
135
+ await settleForShot(page, { javaScript });
136
+ await expect(page).toHaveScreenshot(cell.snapshot, shotOptions({ mask: journey.mask, page }));
137
+ } finally {
138
+ await context.close();
139
+ }
140
+ });
141
+ }
142
+ }
143
+ }