strata-react 1.0.15 → 1.0.20

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,165 @@
1
+ import * as React from "react";
2
+ import { jsx } from "react/jsx-runtime";
3
+ import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";
4
+ // src/lib/errors.ts
5
+ /** Thrown by `fetchJson` on a non-2xx response; carries the status, the response body and the server's reason for `describeHttpError` and `describeActionError`. */
6
+ var HttpError = class extends Error {
7
+ status;
8
+ statusText;
9
+ url;
10
+ body;
11
+ /** The server's sentence for why it refused, from the body (`detail`, `message`, `error`), if it gave one. */
12
+ reason;
13
+ /** Messages for individual fields from the body (FastAPI's 422 `detail: [{loc, msg}]`), keyed by field name. Empty when there are none. */
14
+ fieldErrors;
15
+ constructor(status, statusText, url, body, found = readErrorBody(body)) {
16
+ super(`${status} ${statusText} from ${url}`);
17
+ this.status = status;
18
+ this.statusText = statusText;
19
+ this.url = url;
20
+ this.body = body;
21
+ this.name = "HttpError";
22
+ this.reason = found.reason;
23
+ this.fieldErrors = found.fields ?? {};
24
+ }
25
+ };
26
+ var text = (value) => typeof value === "string" && value.trim() ? value.trim() : void 0;
27
+ /** A field name from a FastAPI/pydantic `loc`: the path after where it came from (`["body", "address", "city"]` is `"address.city"`). */
28
+ function fieldName(loc) {
29
+ if (!Array.isArray(loc)) return void 0;
30
+ const path = loc.map(String);
31
+ if ([
32
+ "body",
33
+ "query",
34
+ "path",
35
+ "header",
36
+ "cookie",
37
+ "form"
38
+ ].includes(path[0]) && path.length > 1) path.shift();
39
+ return path.join(".") || void 0;
40
+ }
41
+ /**
42
+ * The default reading of an error body, for the shapes most JSON APIs use: `{ detail: "…" }`
43
+ * (FastAPI), `{ message: "…" }`, `{ error: "…" }` or `{ error: { message: "…" } }` for the reason,
44
+ * and FastAPI's validation list `{ detail: [{ loc, msg }] }` for per-field messages. A short
45
+ * plain-text body (not HTML) is taken as the reason too. Pass your own to `fetchJson` for other APIs.
46
+ */
47
+ function readErrorBody(body) {
48
+ if (typeof body === "string") {
49
+ const t = text(body);
50
+ return t && t.length <= 300 && !t.startsWith("<") ? { reason: t } : {};
51
+ }
52
+ if (!body || typeof body !== "object") return {};
53
+ const b = body;
54
+ if (Array.isArray(b.detail)) {
55
+ const fields = {};
56
+ for (const item of b.detail) {
57
+ const entry = item;
58
+ const name = fieldName(entry?.loc);
59
+ const msg = text(entry?.msg);
60
+ if (name && msg && !fields[name]) fields[name] = msg;
61
+ }
62
+ return { fields };
63
+ }
64
+ const nested = b.error && typeof b.error === "object" ? text(b.error.message) : void 0;
65
+ return { reason: text(b.detail) ?? text(b.message) ?? text(b.error) ?? nested };
66
+ }
67
+ /** A sentence ends once: "…absolute path" and "…absolute path." both end in one full stop. */
68
+ var sentence = (s) => /[.!?…]$/.test(s) ? s : `${s}.`;
69
+ function refused(error) {
70
+ if (error.reason) return `The request was refused: ${sentence(error.reason)}`;
71
+ if (Object.keys(error.fieldErrors).length) return "The request was refused: check the fields marked.";
72
+ return `The request was refused (${error.status}): ${error.statusText || "no reason given"}.`;
73
+ }
74
+ /** The default `DescribeError` for loads: the HTTP status in a sentence (with the server's reason for a 4xx), else the error's message, else a plain fallback. */
75
+ var describeHttpError = (error) => error instanceof HttpError ? error.status >= 500 ? `The server could not answer (${error.status}). Nothing was changed.` : refused(error) : error instanceof Error && error.message ? error.message : "The data could not be loaded. Nothing was changed.";
76
+ /** The default for `useAsyncAction`: the HTTP status in a sentence (with the server's reason for a 4xx), else the thrown Error's message, else undefined (the retry label alone). */
77
+ var describeActionError = (error) => error instanceof HttpError ? error.status >= 500 ? `The server could not answer (${error.status}).` : refused(error) : error instanceof Error && error.message ? error.message : void 0;
78
+ /** Messages for individual fields carried by what was thrown: an `HttpError`'s `fieldErrors`, else none. */
79
+ function fieldErrorsOf(error) {
80
+ return error instanceof HttpError ? error.fieldErrors : {};
81
+ }
82
+ // src/query/index.tsx
83
+ /** A QueryClient with Strata's defaults: one retry, 30 s stale time, no refetch on window focus. */
84
+ function createQueryClient(overrides) {
85
+ return new QueryClient({
86
+ ...overrides,
87
+ defaultOptions: {
88
+ ...overrides?.defaultOptions,
89
+ queries: {
90
+ retry: 1,
91
+ staleTime: 3e4,
92
+ refetchOnWindowFocus: false,
93
+ ...overrides?.defaultOptions?.queries
94
+ }
95
+ }
96
+ });
97
+ }
98
+ /** Provides a query client (Strata's defaults unless one is passed) to the app. */
99
+ function StrataQueryProvider({ client, children }) {
100
+ const [fallback] = React.useState(() => client ?? createQueryClient());
101
+ return /* @__PURE__ */ jsx(QueryClientProvider, {
102
+ client: client ?? fallback,
103
+ children
104
+ });
105
+ }
106
+ /**
107
+ * Turns a TanStack query result into the `Load<T>` that `DataView` takes; errors are described for a person by `describe`.
108
+ * A refetch that fails after data arrived stays `ready`, with `stale` saying why and when the data was read.
109
+ */
110
+ function toLoad(query, describe = describeHttpError) {
111
+ if (query.status === "success") return {
112
+ status: "ready",
113
+ data: query.data
114
+ };
115
+ if (query.status === "error" && query.data !== void 0) return {
116
+ status: "ready",
117
+ data: query.data,
118
+ stale: staleOf(query, describe)
119
+ };
120
+ if (query.status === "error") return {
121
+ status: "error",
122
+ message: describe(query.error),
123
+ retry: () => void query.refetch()
124
+ };
125
+ return { status: "loading" };
126
+ }
127
+ /** The `Stale` of a query whose refetch failed after a good read. Shared by `toLoad` and `useInfiniteLoad`. */
128
+ function staleOf(query, describe = describeHttpError) {
129
+ return {
130
+ message: describe(query.error),
131
+ readAt: new Date(query.dataUpdatedAt),
132
+ retry: () => void query.refetch(),
133
+ retrying: query.isFetching
134
+ };
135
+ }
136
+ /** `useQuery`, returned as a `Load<T>` for `DataView`. */
137
+ function useLoad(options) {
138
+ const { describeError, ...rest } = options;
139
+ return toLoad(useQuery(rest), describeError);
140
+ }
141
+ /**
142
+ * fetch() that throws an HttpError on a non-2xx response and parses JSON: the queryFn default, and the usual commit for a write.
143
+ * A 204 or empty body resolves to undefined. An error response's body is read onto the HttpError (`body`, `reason`, `fieldErrors`).
144
+ */
145
+ async function fetchJson(input, init, { readError = readErrorBody } = {}) {
146
+ const headers = new Headers(init?.headers);
147
+ if (!headers.has("Accept")) headers.set("Accept", "application/json");
148
+ const res = await fetch(input, {
149
+ ...init,
150
+ headers
151
+ });
152
+ if (!res.ok) {
153
+ const raw = await res.text().catch(() => "");
154
+ let body = raw || void 0;
155
+ try {
156
+ if (raw) body = JSON.parse(raw);
157
+ } catch {}
158
+ throw new HttpError(res.status, res.statusText, String(input), body, readError(body));
159
+ }
160
+ const text = res.status === 204 ? "" : await res.text();
161
+ return text ? JSON.parse(text) : void 0;
162
+ }
163
+ export { toLoad as a, describeActionError as c, readErrorBody as d, staleOf as i, describeHttpError as l, createQueryClient as n, useLoad as o, fetchJson as r, HttpError as s, StrataQueryProvider as t, fieldErrorsOf as u };
164
+
165
+ //# sourceMappingURL=query-CP78goXj.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-CP78goXj.js","names":[],"sources":["../src/lib/errors.ts","../src/query/index.tsx"],"sourcesContent":["// Errors, described for a person. Anything that fails in front of someone (a load in DataView, an\n// action in AsyncButton) says what happened in a sentence, in the product's words, not the\n// developer's: `HttpError`'s own message (\"409 Conflict from /api/bookings\") is for logs. Loads\n// and actions share HttpError's status sentences, so the same failure reads the same everywhere,\n// and differ only in what is true afterwards: a failed load changed nothing, while a failed action\n// may have reached the server, so its sentence does not promise that.\n//\n// A server's own reason beats the status text (strata-react issue #42, from python-app-template).\n// FastAPI and most JSON APIs say why a 4xx happened in the body (`{\"detail\": \"the data folder must\n// be an absolute path\"}`), and a client that drops it has to repeat every server rule to show the\n// person anything better than \"Bad Request\", which drifts and cannot cover rules only the server\n// can check. So `fetchJson` reads an error response's body, `HttpError` keeps it with the reason\n// and any per-field messages found in it, and the sentences below use the reason for a 4xx.\n// Per-field messages (FastAPI's 422 `detail: [{loc, msg}]`) are keyed by field name, so\n// `useAsyncAction`'s `fieldErrors` can put each under its `Field`, never in a toast. A 5xx body is\n// not shown: it is usually a stack trace or a proxy's HTML page, and is kept on `body` for logs.\n\n/** What `readErrorBody` finds in an error response: the server's sentence, and messages per field. */\nexport type ErrorBody = {\n /** Why the server refused, in its own words. */\n reason?: string;\n /** Messages for individual fields, keyed by field name (`\"name\"`, `\"address.city\"`). */\n fields?: Record<string, string>;\n};\n\n/** Thrown by `fetchJson` on a non-2xx response; carries the status, the response body and the server's reason for `describeHttpError` and `describeActionError`. */\nexport class HttpError extends Error {\n /** The server's sentence for why it refused, from the body (`detail`, `message`, `error`), if it gave one. */\n readonly reason?: string;\n /** Messages for individual fields from the body (FastAPI's 422 `detail: [{loc, msg}]`), keyed by field name. Empty when there are none. */\n readonly fieldErrors: Readonly<Record<string, string>>;\n\n constructor(\n readonly status: number,\n readonly statusText: string,\n readonly url: string,\n /** The response body: parsed JSON when it was JSON, else its text; undefined when empty. */\n readonly body?: unknown,\n found: ErrorBody = readErrorBody(body),\n ) {\n super(`${status} ${statusText} from ${url}`);\n this.name = \"HttpError\";\n this.reason = found.reason;\n this.fieldErrors = found.fields ?? {};\n }\n}\n\nconst text = (value: unknown) => (typeof value === \"string\" && value.trim() ? value.trim() : undefined);\n\n/** A field name from a FastAPI/pydantic `loc`: the path after where it came from (`[\"body\", \"address\", \"city\"]` is `\"address.city\"`). */\nfunction fieldName(loc: unknown) {\n if (!Array.isArray(loc)) return undefined;\n const path = loc.map(String);\n if ([\"body\", \"query\", \"path\", \"header\", \"cookie\", \"form\"].includes(path[0]) && path.length > 1) path.shift();\n return path.join(\".\") || undefined;\n}\n\n/**\n * The default reading of an error body, for the shapes most JSON APIs use: `{ detail: \"…\" }`\n * (FastAPI), `{ message: \"…\" }`, `{ error: \"…\" }` or `{ error: { message: \"…\" } }` for the reason,\n * and FastAPI's validation list `{ detail: [{ loc, msg }] }` for per-field messages. A short\n * plain-text body (not HTML) is taken as the reason too. Pass your own to `fetchJson` for other APIs.\n */\nexport function readErrorBody(body: unknown): ErrorBody {\n if (typeof body === \"string\") {\n const t = text(body);\n return t && t.length <= 300 && !t.startsWith(\"<\") ? { reason: t } : {};\n }\n if (!body || typeof body !== \"object\") return {};\n const b = body as Record<string, unknown>;\n if (Array.isArray(b.detail)) {\n const fields: Record<string, string> = {};\n for (const item of b.detail as unknown[]) {\n const entry = item as { loc?: unknown; msg?: unknown } | null;\n const name = fieldName(entry?.loc);\n const msg = text(entry?.msg);\n if (name && msg && !fields[name]) fields[name] = msg;\n }\n return { fields };\n }\n const nested = b.error && typeof b.error === \"object\" ? text((b.error as Record<string, unknown>).message) : undefined;\n return { reason: text(b.detail) ?? text(b.message) ?? text(b.error) ?? nested };\n}\n\n/** Writes an error for a person: what happened, in a sentence. A product passes its own words. */\nexport type DescribeError = (error: unknown) => string;\n\n/** A sentence ends once: \"…absolute path\" and \"…absolute path.\" both end in one full stop. */\nconst sentence = (s: string) => (/[.!?…]$/.test(s) ? s : `${s}.`);\n\nfunction refused(error: HttpError) {\n if (error.reason) return `The request was refused: ${sentence(error.reason)}`;\n if (Object.keys(error.fieldErrors).length) return \"The request was refused: check the fields marked.\";\n return `The request was refused (${error.status}): ${error.statusText || \"no reason given\"}.`;\n}\n\n/** The default `DescribeError` for loads: the HTTP status in a sentence (with the server's reason for a 4xx), else the error's message, else a plain fallback. */\nexport const describeHttpError: DescribeError = (error) =>\n error instanceof HttpError\n ? error.status >= 500\n ? `The server could not answer (${error.status}). Nothing was changed.`\n : refused(error)\n : error instanceof Error && error.message\n ? error.message\n : \"The data could not be loaded. Nothing was changed.\";\n\n/** The default for `useAsyncAction`: the HTTP status in a sentence (with the server's reason for a 4xx), else the thrown Error's message, else undefined (the retry label alone). */\nexport const describeActionError = (error: unknown): string | undefined =>\n error instanceof HttpError\n ? error.status >= 500\n ? `The server could not answer (${error.status}).`\n : refused(error)\n : error instanceof Error && error.message\n ? error.message\n : undefined;\n\n/** Messages for individual fields carried by what was thrown: an `HttpError`'s `fieldErrors`, else none. */\nexport function fieldErrorsOf(error: unknown): Readonly<Record<string, string>> {\n return error instanceof HttpError ? error.fieldErrors : {};\n}\n","import * as React from \"react\";\nimport {\n QueryClient,\n QueryClientProvider,\n useQuery,\n type QueryKey,\n type UseQueryOptions,\n type UseQueryResult,\n} from \"@tanstack/react-query\";\nimport type { Load, Stale } from \"../components/data-view\";\nimport { HttpError, describeHttpError, readErrorBody, type DescribeError, type ErrorBody } from \"../lib/errors\";\n\nexport { HttpError, describeHttpError, readErrorBody, type DescribeError, type ErrorBody };\n\n// Data loading, the Strata way: TanStack Query fetches and caches, and every view of the result\n// goes through DataView, which takes a Load<T>. `toLoad` is the one bridge between them, so a\n// screen never re-derives loading/error/ready from a query's flags and never forgets one.\n//\n// Opinions in createQueryClient: one retry (a second failure is real and the person should see\n// it with a \"Try again\"), 30 s stale time (dashboards are read many times a minute but change\n// over minutes), and no refetch on window focus (a table that reorders itself while someone reads\n// it is worse than one that is 30 s old). Override per query when the data says otherwise.\n\n/** A QueryClient with Strata's defaults: one retry, 30 s stale time, no refetch on window focus. */\nexport function createQueryClient(overrides?: ConstructorParameters<typeof QueryClient>[0]) {\n return new QueryClient({\n ...overrides,\n defaultOptions: {\n ...overrides?.defaultOptions,\n queries: { retry: 1, staleTime: 30_000, refetchOnWindowFocus: false, ...overrides?.defaultOptions?.queries },\n },\n });\n}\n\n/** Provides a query client (Strata's defaults unless one is passed) to the app. */\nexport function StrataQueryProvider({ client, children }: { client?: QueryClient; children: React.ReactNode }) {\n const [fallback] = React.useState(() => client ?? createQueryClient());\n return <QueryClientProvider client={client ?? fallback}>{children}</QueryClientProvider>;\n}\n\n/**\n * Turns a TanStack query result into the `Load<T>` that `DataView` takes; errors are described for a person by `describe`.\n * A refetch that fails after data arrived stays `ready`, with `stale` saying why and when the data was read.\n */\nexport function toLoad<T>(query: UseQueryResult<T>, describe: DescribeError = describeHttpError): Load<T> {\n if (query.status === \"success\") return { status: \"ready\", data: query.data };\n // TanStack keeps the last good data when a refetch fails and sets status \"error\" (isRefetchError).\n // That is old data, not no data: keep it on screen and say how old it is.\n if (query.status === \"error\" && query.data !== undefined) return { status: \"ready\", data: query.data, stale: staleOf(query, describe) };\n if (query.status === \"error\") return { status: \"error\", message: describe(query.error), retry: () => void query.refetch() };\n return { status: \"loading\" };\n}\n\n/** The `Stale` of a query whose refetch failed after a good read. Shared by `toLoad` and `useInfiniteLoad`. */\nexport function staleOf(\n query: { error: unknown; dataUpdatedAt: number; isFetching: boolean; refetch: () => unknown },\n describe: DescribeError = describeHttpError,\n): Stale {\n return { message: describe(query.error), readAt: new Date(query.dataUpdatedAt), retry: () => void query.refetch(), retrying: query.isFetching };\n}\n\n/** `useQuery`, returned as a `Load<T>` for `DataView`. */\nexport function useLoad<T, K extends QueryKey = QueryKey>(\n options: UseQueryOptions<T, Error, T, K> & { describeError?: DescribeError },\n): Load<T> {\n const { describeError, ...rest } = options;\n return toLoad(useQuery(rest), describeError);\n}\n\n/** Options for `fetchJson` beyond `fetch`'s own. */\nexport type FetchJsonOptions = {\n /** Finds the server's reason and per-field messages in an error body. Default `readErrorBody` (FastAPI's `detail`, `message`, `error`). */\n readError?: (body: unknown) => ErrorBody;\n};\n\n/**\n * fetch() that throws an HttpError on a non-2xx response and parses JSON: the queryFn default, and the usual commit for a write.\n * A 204 or empty body resolves to undefined. An error response's body is read onto the HttpError (`body`, `reason`, `fieldErrors`).\n */\nexport async function fetchJson<T>(input: string | URL, init?: RequestInit, { readError = readErrorBody }: FetchJsonOptions = {}): Promise<T> {\n // Headers, tuple arrays and plain objects are all valid HeadersInit; normalise before adding the\n // default so a caller's Authorization (or their own Accept) is never dropped.\n const headers = new Headers(init?.headers);\n if (!headers.has(\"Accept\")) headers.set(\"Accept\", \"application/json\");\n const res = await fetch(input, { ...init, headers });\n if (!res.ok) {\n // The body is read as text and parsed only when it parses: a proxy's HTML 502 page or an empty\n // body must still throw the HttpError, never a JSON SyntaxError in its place.\n const raw = await res.text().catch(() => \"\");\n let body: unknown = raw || undefined;\n try {\n if (raw) body = JSON.parse(raw);\n } catch {\n // Not JSON: keep the text.\n }\n throw new HttpError(res.status, res.statusText, String(input), body, readError(body));\n }\n // Writes (DELETE, a PUT that returns nothing) answer 204 or an empty body; that is success, not a\n // JSON parse error.\n const text = res.status === 204 ? \"\" : await res.text();\n return (text ? JSON.parse(text) : undefined) as T;\n}\n\nexport { useInfiniteLoad, type InfiniteLoad, type InfiniteLoadOptions, type More } from \"./infinite\";\nexport { useJob, type Job, type JobOptions } from \"./job\";\n"],"mappings":";;;;;AA0BA,IAAa,YAAb,cAA+B,MAAM;CAOxB;CACA;CACA;CAEA;;CATX;;CAEA;CAEA,YACE,QACA,YACA,KAEA,MACA,QAAmB,cAAc,IAAI,GACrC;EACA,MAAM,GAAG,OAAO,GAAG,WAAW,QAAQ,KAAK;EAPlC,KAAA,SAAA;EACA,KAAA,aAAA;EACA,KAAA,MAAA;EAEA,KAAA,OAAA;EAIT,KAAK,OAAO;EACZ,KAAK,SAAS,MAAM;EACpB,KAAK,cAAc,MAAM,UAAU,CAAC;CACtC;AACF;AAEA,IAAM,QAAQ,UAAoB,OAAO,UAAU,YAAY,MAAM,KAAK,IAAI,MAAM,KAAK,IAAI,KAAA;;AAG7F,SAAS,UAAU,KAAc;CAC/B,IAAI,CAAC,MAAM,QAAQ,GAAG,GAAG,OAAO,KAAA;CAChC,MAAM,OAAO,IAAI,IAAI,MAAM;CAC3B,IAAI;EAAC;EAAQ;EAAS;EAAQ;EAAU;EAAU;CAAM,CAAC,CAAC,SAAS,KAAK,EAAE,KAAK,KAAK,SAAS,GAAG,KAAK,MAAM;CAC3G,OAAO,KAAK,KAAK,GAAG,KAAK,KAAA;AAC3B;;;;;;;AAQA,SAAgB,cAAc,MAA0B;CACtD,IAAI,OAAO,SAAS,UAAU;EAC5B,MAAM,IAAI,KAAK,IAAI;EACnB,OAAO,KAAK,EAAE,UAAU,OAAO,CAAC,EAAE,WAAW,GAAG,IAAI,EAAE,QAAQ,EAAE,IAAI,CAAC;CACvE;CACA,IAAI,CAAC,Q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CACpE,MAAM,MAAM,MAAM,MAAM,OAAO;EAAE,GAAG;EAAM;CAAQ,CAAC;CACnD,IAAI,CAAC,IAAI,IAAI;EAGX,MAAM,MAAM,MAAM,IAAI,KAAK,CAAC,CAAC,YAAY,EAAE;EAC3C,IAAI,OAAgB,OAAO,KAAA;EAC3B,IAAI;GACF,IAAI,KAAK,OAAO,KAAK,MAAM,GAAG;EAChC,QAAQ,CAER;EACA,MAAM,IAAI,UAAU,IAAI,QAAQ,IAAI,YAAY,OAAO,KAAK,GAAG,MAAM,UAAU,IAAI,CAAC;CACtF;CAGA,MAAM,OAAO,IAAI,WAAW,MAAM,KAAK,MAAM,IAAI,KAAK;CACtD,OAAQ,OAAO,KAAK,MAAM,IAAI,IAAI,KAAA;AACpC"}
@@ -4,6 +4,7 @@ import { extname, join, normalize, resolve, sep } from "node:path";
4
4
  import { PNG } from "pngjs";
5
5
  import { createServer } from "node:http";
6
6
  // src/visual/capture.ts
7
+ var COLOR_SCHEME_STORAGE_KEY = "strata-color-scheme";
7
8
  var freeze = `*, *::before, *::after { animation: none !important; transition: none !important; caret-color: transparent !important; }`;
8
9
  /** Resolves a shot's path under the base URL, keeping the base's own path (`/app/` + `/review`). */
9
10
  function resolveShotUrl(path, baseUrl) {
@@ -67,6 +68,14 @@ async function capture(browser, shot, options) {
67
68
  const problems = [];
68
69
  try {
69
70
  if (options.time !== void 0) await context.clock.setFixedTime(options.time);
71
+ await context.addInitScript(({ key, theme }) => {
72
+ try {
73
+ localStorage.setItem(key, theme);
74
+ } catch {}
75
+ }, {
76
+ key: COLOR_SCHEME_STORAGE_KEY,
77
+ theme: shot.theme
78
+ });
70
79
  if (shot.darkClass) await context.addInitScript(({ cls, dark }) => {
71
80
  const apply = () => document.documentElement?.classList.toggle(cls, dark);
72
81
  apply();
@@ -163,7 +172,9 @@ async function platformFonts(page) {
163
172
  for (const f of fonts) {
164
173
  if (f.isCustomFont || found.has(f.familyName)) continue;
165
174
  const text = t.text.length > 30 ? `${t.text.slice(0, 29)}…` : t.text;
166
- found.set(f.familyName, `"${f.familyName}" in <${t.name}>${text ? ` "${text}"` : ""}`);
175
+ const { computedStyle } = await cdp.send("CSS.getComputedStyleForNode", { nodeId: t.id }).catch(() => ({ computedStyle: [] }));
176
+ const stack = computedStyle.find((p) => p.name === "font-family")?.value;
177
+ found.set(f.familyName, `"${f.familyName}" in <${t.name}>${text ? ` "${text}"` : ""}${stack ? ` (font-family: ${stack})` : ""}`);
167
178
  }
168
179
  }
169
180
  return [...found.values()];
@@ -738,4 +749,4 @@ function formatReport(report) {
738
749
  }
739
750
  export { capture as _, defaultThemes as a, viewports as c, MAX_DIFF_PIXELS as d, THRESHOLD as f, encode as g, decode as h, runVisual as i, serveStatic as l, compare as m, formatReport as n, routeShots as o, boxBlur as p, pinWarnings as r, storybookShots as s, defineVisualConfig as t, BLUR as u, resolveShotUrl as v, toFetchRequest as y };
740
751
 
741
- //# sourceMappingURL=run-Yrgm5xIq.js.map
752
+ //# sourceMappingURL=run-CKlcLpdN.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-CKlcLpdN.js","names":[],"sources":["../src/visual/capture.ts","../src/visual/compare.ts","../src/visual/serve.ts","../src/visual/types.ts","../src/visual/targets.ts","../src/visual/run.ts"],"sourcesContent":["// Taking one shot. Everything here is about determinism: a fresh browser context per shot so\n// shots cannot affect each other, reduced motion and frozen animations so the settled state is\n// what is captured, fonts awaited, the theme set both as the colour scheme and as the class the\n// app reads, the clock optionally frozen, and, for routes, every request the page makes answered\n// by MSW handlers in Node, so the screenshot depends on nothing outside the suite.\nimport type { Browser, BrowserContext, Page, Request as PlaywrightRequest, Route as PlaywrightRoute } from \"playwright\";\nimport type { RequestHandler } from \"msw\";\nimport type { Shot, VisualConfig } from \"./types\";\n\n// Where ThemeProvider and colorSchemeScript() keep the preference (COLOR_SCHEME_STORAGE_KEY in components/theme.tsx; copied, not imported, so the runner loads no React).\nconst COLOR_SCHEME_STORAGE_KEY = \"strata-color-scheme\";\n\n// Animations and transitions off, caret hidden: a screenshot is of the settled state.\nconst freeze = `*, *::before, *::after { animation: none !important; transition: none !important; caret-color: transparent !important; }`;\n\n/** Options shared by every shot of a run. */\nexport interface CaptureOptions {\n /** Where `shot.path` resolves, ending in `/`. */\n baseUrl: string;\n time?: string | number | Date;\n timezone?: string;\n locale?: string;\n /** Block service workers (an app's own MSW worker or PWA cache would bypass the handlers). */\n blockServiceWorkers?: boolean;\n onUnhandledRequest?: \"error\" | \"bypass\";\n /** Look up which faces drew the page's text and return the ones that are not web fonts. Default true. */\n checkFonts?: boolean;\n}\n\n/** What one shot produced. */\nexport interface Capture {\n png: Buffer;\n /** Page errors, console errors and unanswered requests. */\n problems: string[];\n /**\n * Text drawn in a font installed on this machine rather than one the page loaded, one line per\n * face with an example element, e.g. `\"DejaVu Sans\" in <kbd> \"⌘K\"`. Such text renders\n * differently on every machine, so the runner fails the shot (see {@link VisualConfig.systemFonts}).\n */\n systemFonts: string[];\n}\n\n/** Resolves a shot's path under the base URL, keeping the base's own path (`/app/` + `/review`). */\nexport function resolveShotUrl(path: string, baseUrl: string): string {\n if (/^[a-z][a-z0-9+.-]*:/i.test(path)) return path;\n return new URL(path.replace(/^\\/+/, \"\"), baseUrl).href;\n}\n\n/** Converts a request the page made into a Fetch `Request` MSW can match. */\nexport function toFetchRequest(request: Pick<PlaywrightRequest, \"url\" | \"method\" | \"headers\" | \"postDataBuffer\">): Request {\n const method = request.method();\n const body = method === \"GET\" || method === \"HEAD\" ? undefined : (request.postDataBuffer() ?? undefined);\n return new Request(request.url(), { method, headers: request.headers(), body: body ? new Uint8Array(body) : undefined });\n}\n\nasync function answerWithHandlers(\n context: BrowserContext,\n handlers: readonly RequestHandler[],\n baseUrl: string,\n unhandled: \"error\" | \"bypass\",\n problems: string[],\n) {\n const msw = await import(\"msw\").catch(() => {\n throw new Error(\"route shots with handlers need msw: npm install -D msw\");\n });\n const origin = new URL(baseUrl).origin;\n await context.route(\"**/*\", async (route: PlaywrightRoute) => {\n const request = route.request();\n const response = await msw.getResponse([...handlers], toFetchRequest(request), { baseUrl: origin, quiet: true });\n if (response && response.headers.get(\"x-msw-intention\") !== \"passthrough\") {\n const headers: Record<string, string> = {};\n response.headers.forEach((value, key) => (headers[key] = value));\n await route.fulfill({ status: response.status, headers, body: Buffer.from(await response.arrayBuffer()) });\n return;\n }\n if (!response && unhandled === \"error\" && [\"fetch\", \"xhr\", \"eventsource\", \"websocket\"].includes(request.resourceType())) {\n const url = new URL(request.url());\n problems.push(`no handler for ${request.method()} ${url.origin === origin ? \"\" : url.origin}${url.pathname}${url.search}`);\n }\n await route.continue();\n });\n}\n\n/** Takes one shot and returns its PNG, or throws with what went wrong. Page and console errors are returned as problems. */\nexport async function capture(browser: Browser, shot: Shot, options: CaptureOptions): Promise<Capture> {\n const context = await browser.newContext({\n viewport: shot.viewport,\n deviceScaleFactor: 1,\n reducedMotion: \"reduce\",\n colorScheme: shot.theme,\n timezoneId: options.timezone ?? \"UTC\",\n locale: options.locale ?? \"en-US\",\n serviceWorkers: options.blockServiceWorkers ? \"block\" : \"allow\",\n });\n const problems: string[] = [];\n try {\n if (options.time !== undefined) await context.clock.setFixedTime(options.time);\n // The theme the app's ThemeProvider reads before React runs (what `colorSchemeScript()` reads), so a shot's\n // theme reaches an app whose default preference is not \"system\" (issue #136). Failing storage is the app's no-op.\n await context.addInitScript(\n ({ key, theme }) => {\n try {\n localStorage.setItem(key, theme);\n } catch {}\n },\n { key: COLOR_SCHEME_STORAGE_KEY, theme: shot.theme },\n );\n if (shot.darkClass) {\n await context.addInitScript(\n ({ cls, dark }) => {\n const apply = () => document.documentElement?.classList.toggle(cls, dark);\n apply();\n document.addEventListener(\"DOMContentLoaded\", apply);\n },\n { cls: shot.darkClass, dark: shot.theme === \"dark\" },\n );\n }\n if (shot.handlers?.length || options.onUnhandledRequest === \"error\") {\n await answerWithHandlers(context, shot.handlers ?? [], options.baseUrl, options.onUnhandledRequest ?? \"bypass\", problems);\n }\n const page = await context.newPage();\n page.on(\"pageerror\", (e) => problems.push(e.message));\n // Error responses a state serves on purpose (4xx/5xx) are logged by Chromium; not a fault.\n page.on(\"console\", (m) => {\n if (m.type() === \"error\" && !m.text().startsWith(\"Failed to load resource\")) problems.push(m.text());\n });\n await page.goto(resolveShotUrl(shot.path, options.baseUrl), { waitUntil: \"load\" });\n await page.addStyleTag({ content: freeze });\n await page.waitForFunction((root) => (document.querySelector(root)?.childElementCount ?? 0) > 0, shot.root, { timeout: 15_000 }).catch(() => {\n throw new Error(`${shot.root} stayed empty for 15s`);\n });\n if (shot.waitFor) await page.locator(shot.waitFor).first().waitFor({ state: \"visible\", timeout: 15_000 });\n await settle(page);\n if (shot.setup) {\n await shot.setup(page, shot);\n await settle(page);\n }\n let png: Buffer;\n if (shot.clip === \"page\") {\n png = await page.screenshot({ fullPage: true, animations: \"disabled\" });\n } else {\n const clip = await page.evaluate(paintedBox, { root: shot.root, margin: 8 });\n if (!clip) throw new Error(\"rendered nothing visible\");\n png = await page.screenshot({ fullPage: true, clip, animations: \"disabled\" });\n }\n const systemFonts = options.checkFonts === false ? [] : await platformFonts(page);\n return { png, problems, systemFonts };\n } finally {\n await context.close();\n }\n}\n\nasync function settle(page: Page) {\n // A state that is meant to stay loading keeps a request open, so networkidle may not come.\n await page.waitForLoadState(\"networkidle\", { timeout: 3_000 }).catch(() => undefined);\n await page.evaluate(() => document.fonts.ready.then(() => undefined));\n await page.waitForTimeout(250);\n}\n\n// Which faces drew the text. Chromium's DevTools protocol reports, per element, the font files\n// that actually painted its glyphs and whether each came from the page (@font-face) or from the\n// machine. A system face is the largest source of machine-to-machine difference left once the\n// browser is pinned: the same `ui-sans-serif` is Cantarell on one Linux, DejaVu on another and\n// San Francisco on a Mac, and a glyph missing from a web font (an arrow, ⌘) falls back to\n// whatever the machine has. So the shot reports it rather than tolerating it in the comparison.\nasync function platformFonts(page: Page): Promise<string[]> {\n const cdp = await page.context().newCDPSession(page);\n try {\n await cdp.send(\"DOM.enable\");\n await cdp.send(\"CSS.enable\");\n const { root } = await cdp.send(\"DOM.getDocument\", { depth: -1, pierce: true });\n type DomNode = {\n nodeId: number;\n nodeType: number;\n nodeName: string;\n nodeValue: string;\n pseudoType?: string;\n children?: DomNode[];\n shadowRoots?: DomNode[];\n pseudoElements?: DomNode[];\n contentDocument?: DomNode;\n };\n const texts: { id: number; name: string; text: string }[] = [];\n const walk = (n: DomNode) => {\n if (n.nodeName === \"SCRIPT\" || n.nodeName === \"STYLE\" || n.nodeName === \"HEAD\") return;\n const own = n.children?.filter((c) => c.nodeType === 3 && c.nodeValue.trim()) ?? [];\n if (n.nodeType === 1 && own.length) texts.push({ id: n.nodeId, name: n.nodeName.toLowerCase(), text: own.map((c) => c.nodeValue.trim()).join(\" \") });\n // Generated content (`::before { content: \"⌘\" }`) draws text too; it has no text child.\n for (const p of n.pseudoElements ?? []) texts.push({ id: p.nodeId, name: `${n.nodeName.toLowerCase()}::${p.pseudoType ?? \"pseudo\"}`, text: \"\" });\n for (const c of [...(n.children ?? []), ...(n.shadowRoots ?? []), ...(n.contentDocument ? [n.contentDocument] : [])]) walk(c);\n };\n walk(root as DomNode);\n const found = new Map<string, string>();\n for (const t of texts) {\n // A node that is not rendered (display: none) has no fonts and is skipped by Chromium.\n const { fonts } = await cdp.send(\"CSS.getPlatformFontsForNode\", { nodeId: t.id }).catch(() => ({ fonts: [] }));\n for (const f of fonts) {\n if (f.isCustomFont || found.has(f.familyName)) continue;\n const text = t.text.length > 30 ? `${t.text.slice(0, 29)}…` : t.text;\n // The CSS stack that fell through to the machine, so a `--font-mono` that names a face the app did not import is\n // recognisable as such (issue #136): the glyph or the whole stack was missing from the bundled faces.\n const { computedStyle } = await cdp.send(\"CSS.getComputedStyleForNode\", { nodeId: t.id }).catch(() => ({ computedStyle: [] }));\n const stack = computedStyle.find((p) => p.name === \"font-family\")?.value;\n found.set(f.familyName, `\"${f.familyName}\" in <${t.name}>${text ? ` \"${text}\"` : \"\"}${stack ? ` (font-family: ${stack})` : \"\"}`);\n }\n }\n return [...found.values()];\n } finally {\n await cdp.detach().catch(() => undefined);\n }\n}\n\n// Runs in the page. The box around what the root actually paints: text, replaced and form\n// elements, SVGs, and any box with a background, border or shadow, each cut to the scroll\n// containers it sits in. So a row of buttons is cropped to the buttons, not the full-width div\n// holding them, and fixed elements (an undo bar) count wherever they are. Portalled overlays\n// (children of the body outside the root) count too, so an open dialog or popover is in its shot. The screenshot is\n// fullPage, so the box may extend past the viewport and a large component is captured whole.\nfunction paintedBox({ root: selector, margin }: { root: string; margin: number }) {\n const root = document.querySelector(selector);\n if (!root) return null;\n const replaced = new Set([\"IMG\", \"INPUT\", \"SELECT\", \"TEXTAREA\", \"CANVAS\", \"VIDEO\", \"svg\", \"HR\"]);\n const transparent = (c: string) => c === \"transparent\" || /rgba\\(.*,\\s*0\\)$/.test(c) || /\\/\\s*0\\)$/.test(c);\n const paints = (el: Element) => {\n const cs = getComputedStyle(el);\n if (replaced.has(el.tagName)) return true;\n if (!transparent(cs.backgroundColor) || cs.backgroundImage !== \"none\" || cs.boxShadow !== \"none\") return true;\n return ([\"Top\", \"Right\", \"Bottom\", \"Left\"] as const).some(\n (s) => parseFloat(cs[`border${s}Width`]) > 0 && cs[`border${s}Style`] !== \"none\",\n );\n };\n const clipTo = (r: DOMRect, el: Node) => {\n let { left, top, right, bottom } = r;\n for (let a = el.parentElement; a && a !== document.body; a = a.parentElement) {\n const cs = getComputedStyle(a);\n if (cs.overflowX !== \"visible\" || cs.overflowY !== \"visible\" || cs.clipPath !== \"none\" || cs.clip !== \"auto\") {\n const b = a.getBoundingClientRect();\n left = Math.max(left, b.left);\n top = Math.max(top, b.top);\n right = Math.min(right, b.right);\n bottom = Math.min(bottom, b.bottom);\n }\n if (cs.position === \"fixed\") break;\n }\n return right - left > 1 && bottom - top > 1 ? { left, top, right, bottom } : null;\n };\n const rects: { left: number; top: number; right: number; bottom: number }[] = [];\n // Overlays (dialogs, popovers, tooltips, menus) are portalled to the body, outside the root, so\n // the walk covers the root and every other element the body holds besides scripts and styles.\n const roots: Element[] = [root, ...[...document.body.children].filter((c) => !c.contains(root) && ![\"SCRIPT\", \"STYLE\", \"LINK\", \"TEMPLATE\"].includes(c.tagName))];\n const nodes: Node[] = [];\n for (const r of roots) {\n const walker = document.createTreeWalker(r, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT);\n for (let n = walker.nextNode(); n; n = walker.nextNode()) nodes.push(n);\n }\n for (const n of nodes) {\n if (n.nodeType === Node.TEXT_NODE) {\n if (!n.textContent?.trim() || !n.parentElement) continue;\n const range = document.createRange();\n range.selectNodeContents(n);\n for (const r of range.getClientRects()) {\n // From the text node itself, so its own element's clip counts too (an sr-only span is a\n // 1px clipped box, and its text paints nothing).\n const c = clipTo(r, n);\n if (c) rects.push(c);\n }\n continue;\n }\n const el = n as Element;\n if (el.closest(\"svg\") && el.tagName !== \"svg\") continue;\n if (getComputedStyle(el).visibility === \"hidden\" || !paints(el)) continue;\n const c = clipTo(el.getBoundingClientRect(), el);\n if (c) rects.push(c);\n }\n if (!rects.length) return null;\n const x0 = Math.max(0, Math.floor(Math.min(...rects.map((r) => r.left)) + scrollX - margin));\n const y0 = Math.max(0, Math.floor(Math.min(...rects.map((r) => r.top)) + scrollY - margin));\n const x1 = Math.min(document.documentElement.scrollWidth, Math.ceil(Math.max(...rects.map((r) => r.right)) + scrollX + margin));\n const y1 = Math.min(document.documentElement.scrollHeight, Math.ceil(Math.max(...rects.map((r) => r.bottom)) + scrollY + margin));\n return { x: x0, y: y0, width: x1 - x0, height: y1 - y0 };\n}\n","// PNG decode and pixelmatch comparison, kept apart from the browser so it is unit tested without\n// one. The defaults are the ones every Strata suite uses, so a baseline means the same thing in\n// the library and in an app; a config can change them (`VisualConfig.compare`).\n//\n// Why blur first. Two machines running the same Chromium still rasterise edges a little\n// differently (GPU or CPU raster, SIMD paths, a newer Skia): the coverage of an edge pixel moves\n// to its neighbour, so plain pixelmatch sees a scatter of differing pixels along every edge and\n// glyph. Experiments on Strata's 218 shots (CHANGELOG, 2026-11-07) found that noise reached 159\n// pixels at threshold 0.1 under GPU raster, more than one changed letter makes (10 to 50 pixels),\n// so no pixel allowance could tell the two apart. Averaging each pixel with its 3×3 neighbours\n// before comparing keeps the ink an edge or glyph lays down and drops where exactly it fell: the\n// same noise then came to at most 1 pixel, while a changed letter, a weight step, a 1px shift or a\n// colour change still differed by tens to thousands. A size change is always a change (the layout\n// moved).\nimport pixelmatch from \"pixelmatch\";\nimport { PNG } from \"pngjs\";\n\n/** Per-pixel colour distance pixelmatch treats as equal (0–1), measured after the blur. */\nexport const THRESHOLD = 0.1;\n/** Radius in pixels of the box blur applied to both images before comparing (1 is 3×3; 0 turns it off). */\nexport const BLUR = 1;\n/** Differing pixels (after the blur) tolerated before a screenshot counts as changed. */\nexport const MAX_DIFF_PIXELS = 4;\n\n/** How two screenshots are compared. Every field has the default above. */\nexport interface CompareOptions {\n /** Per-pixel colour distance treated as equal, 0–1 (pixelmatch's `threshold`). Default {@link THRESHOLD}. */\n threshold?: number;\n /** Box blur radius in whole pixels applied to both images first, absorbing anti-aliasing differences (0 turns it off). Default {@link BLUR}. */\n blur?: number;\n /** Differing pixels tolerated. Default {@link MAX_DIFF_PIXELS}. */\n maxDiffPixels?: number;\n /** Count pixels pixelmatch judges to be anti-aliasing as differences too. Default false. */\n includeAA?: boolean;\n}\n\n/** A decoded RGBA image. */\nexport interface Image {\n width: number;\n height: number;\n data: Uint8Array;\n}\n\n/** The result of comparing a screenshot with its baseline. */\nexport interface CompareResult {\n /** Within tolerance: the screenshot matches. */\n same: boolean;\n /** Every pixel is identical, before any blur or threshold. */\n identical: boolean;\n /** Pixels that differ beyond the threshold after the blur (Infinity when the size changed). */\n diffPixels: number;\n /** The same count without the blur: how much anti-aliasing the blur absorbed. */\n unblurredDiffPixels: number;\n /** One line for a report: what changed. */\n reason: string;\n /** A PNG highlighting the differing pixels in red over the faded baseline, when the images differ in content. */\n diff?: Buffer;\n}\n\n/** Decodes a PNG file's bytes. */\nexport function decode(buffer: Buffer | Uint8Array): Image {\n return PNG.sync.read(Buffer.from(buffer));\n}\n\n/** Encodes an RGBA image as PNG bytes. */\nexport function encode({ width, height, data }: Image): Buffer {\n const png = new PNG({ width, height });\n png.data = Buffer.from(data);\n return PNG.sync.write(png);\n}\n\n/** Box-blurs an RGBA image with the given radius (separable, edges averaged over what exists). */\nexport function boxBlur({ width: w, height: h, data }: Image, radius: number): Uint8Array {\n if (!Number.isInteger(radius) || radius < 0) throw new Error(`blur must be a whole number of pixels, 0 or more (got ${radius})`);\n if (radius === 0) return data;\n const pass = (src: ArrayLike<number>, horizontal: boolean) => {\n const out = new Float32Array(src.length);\n const [outer, inner] = horizontal ? [h, w] : [w, h];\n for (let o = 0; o < outer; o++) {\n for (let c = 0; c < 4; c++) {\n const at = (i: number) => ((horizontal ? o * w + i : i * w + o) << 2) + c;\n // Running sum over the window, so the cost does not grow with the radius.\n let sum = 0;\n for (let i = 0; i <= Math.min(radius, inner - 1); i++) sum += src[at(i)];\n for (let i = 0; i < inner; i++) {\n const lo = Math.max(0, i - radius);\n const hi = Math.min(inner - 1, i + radius);\n out[at(i)] = sum / (hi - lo + 1);\n if (i + radius + 1 < inner) sum += src[at(i + radius + 1)];\n if (i - radius >= 0) sum -= src[at(i - radius)];\n }\n }\n }\n return out;\n };\n const blurred = pass(pass(data, true), false);\n const out = new Uint8Array(blurred.length);\n for (let i = 0; i < blurred.length; i++) out[i] = Math.round(blurred[i]);\n return out;\n}\n\nfunction sameBytes(a: Uint8Array, b: Uint8Array) {\n return a.length === b.length && Buffer.compare(Buffer.from(a.buffer, a.byteOffset, a.byteLength), Buffer.from(b.buffer, b.byteOffset, b.byteLength)) === 0;\n}\n\n/** Compares two decoded PNGs with pixelmatch after a small blur. A size change is always a change. */\nexport function compare(expected: Image, actual: Image, options: CompareOptions = {}): CompareResult {\n const { threshold = THRESHOLD, blur = BLUR, maxDiffPixels = MAX_DIFF_PIXELS, includeAA = false } = options;\n if (expected.width !== actual.width || expected.height !== actual.height) {\n return {\n same: false,\n identical: false,\n diffPixels: Number.POSITIVE_INFINITY,\n unblurredDiffPixels: Number.POSITIVE_INFINITY,\n reason: `size ${expected.width}×${expected.height} → ${actual.width}×${actual.height}`,\n };\n }\n const { width, height } = expected;\n if (sameBytes(expected.data, actual.data)) return { same: true, identical: true, diffPixels: 0, unblurredDiffPixels: 0, reason: \"identical\" };\n const mask = new Uint8Array(width * height * 4);\n const diffPixels = pixelmatch(boxBlur(expected, blur), boxBlur(actual, blur), mask, width, height, {\n threshold,\n includeAA,\n diffMask: true,\n });\n const unblurredDiffPixels = blur > 0 ? pixelmatch(expected.data, actual.data, null, width, height, { threshold, includeAA }) : diffPixels;\n const same = diffPixels <= maxDiffPixels;\n return {\n same,\n identical: false,\n diffPixels,\n unblurredDiffPixels,\n reason: `${diffPixels} pixels differ (${((diffPixels / (width * height)) * 100).toFixed(3)}%)${blur > 0 ? `, ${unblurredDiffPixels} without the blur` : \"\"}`,\n diff: same ? undefined : diffImage(expected, mask),\n };\n}\n\n// The baseline faded to grey, with the pixels that differ (pixelmatch's red mask) on top: the\n// mask was computed on blurred images, so it is drawn over the sharp baseline to stay readable.\nfunction diffImage(expected: Image, mask: Uint8Array): Buffer {\n const png = new PNG({ width: expected.width, height: expected.height });\n const d = expected.data;\n for (let i = 0; i < d.length; i += 4) {\n if (mask[i + 3] > 0 && mask[i] === 255 && mask[i + 1] === 0) {\n png.data[i] = 255;\n png.data[i + 1] = 0;\n png.data[i + 2] = 0;\n } else {\n const grey = 255 + ((0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2] - 255) * 0.1 * d[i + 3]) / 255;\n png.data[i] = png.data[i + 1] = png.data[i + 2] = grey;\n }\n png.data[i + 3] = 255;\n }\n return PNG.sync.write(png);\n}\n","// A static file server for a build folder, on a free local port. Storybook needs nothing more;\n// an app's build also needs history fallback (a request for /review that asks for HTML gets\n// index.html, as a host like Pages or Netlify would serve it) and its Vite `base`. Requests that\n// do not ask for HTML are never given index.html, so a missed API route fails loudly as a 404\n// instead of a JSON parse error.\nimport { createServer } from \"node:http\";\nimport { createReadStream, existsSync, statSync } from \"node:fs\";\nimport { extname, join, normalize, resolve, sep } from \"node:path\";\n\nconst types: Record<string, string> = {\n \".html\": \"text/html\",\n \".js\": \"text/javascript\",\n \".mjs\": \"text/javascript\",\n \".css\": \"text/css\",\n \".json\": \"application/json\",\n \".map\": \"application/json\",\n \".webmanifest\": \"application/manifest+json\",\n \".svg\": \"image/svg+xml\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".webp\": \"image/webp\",\n \".avif\": \"image/avif\",\n \".gif\": \"image/gif\",\n \".ico\": \"image/x-icon\",\n \".woff2\": \"font/woff2\",\n \".woff\": \"font/woff\",\n \".ttf\": \"font/ttf\",\n \".txt\": \"text/plain\",\n \".wasm\": \"application/wasm\",\n};\n\n/** A running server: its origin plus base, and how to stop it. */\nexport interface StaticServer {\n /** e.g. `http://127.0.0.1:53121/app/` (always ends in `/`). */\n url: string;\n close(): Promise<void>;\n}\n\n/** Serves `dir` on 127.0.0.1 under `base`, with history fallback to `index.html` when `spa` is set. */\nexport async function serveStatic(dir: string, { spa = false, base = \"/\" }: { spa?: boolean; base?: string } = {}): Promise<StaticServer> {\n const root = resolve(dir);\n const prefix = `/${base.replace(/^\\/+|\\/+$/g, \"\")}/`.replace(/^\\/\\/$/, \"/\");\n const server = createServer((req, res) => {\n const pathname = decodeURIComponent(new URL(req.url ?? \"/\", \"http://x\").pathname);\n if (!pathname.startsWith(prefix) && `${pathname}/` !== prefix) {\n res.writeHead(404).end();\n return;\n }\n const rel = normalize(pathname.slice(prefix.length)).replace(/^([/\\\\])+/, \"\");\n let file = join(root, rel || \"index.html\");\n if (file !== root && !file.startsWith(root + sep)) {\n res.writeHead(404).end();\n return;\n }\n if (existsSync(file) && statSync(file).isDirectory()) file = join(file, \"index.html\");\n if (!existsSync(file)) {\n const wantsHtml = (req.headers.accept ?? \"\").includes(\"text/html\");\n if (!spa || !wantsHtml || !existsSync(join(root, \"index.html\"))) {\n res.writeHead(404).end();\n return;\n }\n file = join(root, \"index.html\");\n }\n res.writeHead(200, { \"Content-Type\": types[extname(file)] ?? \"application/octet-stream\", \"Service-Worker-Allowed\": \"/\" });\n createReadStream(file).pipe(res);\n });\n await new Promise<void>((r) => server.listen(0, \"127.0.0.1\", r));\n const address = server.address();\n const port = typeof address === \"object\" && address ? address.port : 0;\n return {\n url: `http://127.0.0.1:${port}${prefix}`,\n close: () => new Promise((r) => server.close(() => r())),\n };\n}\n","// The shapes a visual suite is written in. One Shot is one PNG: a URL, a theme, a viewport, how to\n// tell it has rendered, and what to cut out. Storybook stories and app routes are both turned into\n// shots, so capture, comparison and baselines are the same code for a component library and for\n// an app's screens (strata-react issue #13).\nimport type { Page } from \"playwright\";\nimport type { RequestHandler } from \"msw\";\nimport type { CompareOptions } from \"./compare\";\n\n/** The two colour schemes every shot is taken in. */\nexport type Theme = \"light\" | \"dark\";\n\n/** A viewport in CSS pixels. Screenshots are taken at a device scale factor of 1. */\nexport interface Viewport {\n width: number;\n height: number;\n}\n\n/** A named viewport (see {@link viewports}) or an explicit size. */\nexport type ViewportChoice = keyof typeof viewports | Viewport;\n\n/**\n * Named viewports. `wide` and `phone` are what the Storybook tags `visual-wide` and\n * `visual-phone` select; `default` is a laptop-sized screen for routes. (Untagged stories render\n * 1024 wide and 200 tall and grow with the component, see {@link storybookShots}.)\n */\nexport const viewports = {\n default: { width: 1024, height: 768 },\n wide: { width: 1440, height: 900 },\n phone: { width: 390, height: 844 },\n} as const satisfies Record<string, Viewport>;\n\n/**\n * What a screenshot covers. `paint` is the union of what the root element paints (text,\n * controls, SVGs, and boxes with a background, border or shadow) plus 8px, so a component's\n * baseline shows the component and not the empty canvas. `page` is the whole page, for screens.\n */\nexport type Clip = \"paint\" | \"page\";\n\n/** A step run after a shot has rendered and before it is captured: open a menu, focus a field. */\nexport type Setup = (page: Page, shot: Shot) => Promise<void> | void;\n\n/** One screenshot: everything the runner needs to take it and to name its baseline. */\nexport interface Shot {\n /** The baseline's file name without `.png`, e.g. `review--empty--wide--dark`. */\n name: string;\n /** Path and query under the served base (`/review?tab=queue`), or an absolute URL. */\n path: string;\n theme: Theme;\n viewport: Viewport;\n /** Selector of the element the app renders into; the shot waits until it has children. */\n root: string;\n clip: Clip;\n /** A Playwright selector that must be visible before the shot is taken (see {@link RouteState.waitFor}). */\n waitFor?: string;\n /** MSW handlers answering the page's requests, first match wins. Route shots only. */\n handlers?: readonly RequestHandler[];\n /** Class put on `<html>` in the dark theme (Strata's `dark:` variant reads `.dark`). */\n darkClass?: string | false;\n setup?: Setup;\n}\n\n/** An app's built Storybook. */\nexport interface StorybookTarget {\n /** The `storybook build` output folder. Default `storybook-static`. */\n dir?: string;\n /** The Storybook global the preview reads the theme from. Default `theme`, as Strata's preview. */\n themeGlobal?: string;\n}\n\n/** One state of a route: the MSW handlers that put the server into it, and optional steps. */\nexport interface RouteState {\n /** Handlers tried before the target's base handlers (like `server.use(...)` in a test). */\n handlers?: readonly RequestHandler[];\n /** A different path for this state, e.g. the same screen with `?tab=sync`. */\n path?: string;\n /**\n * A Playwright selector that must be visible before the shot is taken, such as `role=alert` or\n * `text=Try again`. Needed when a state takes longer than the network to show: an error after\n * the query client's retry, a toast after a timer.\n */\n waitFor?: string;\n setup?: Setup;\n}\n\n/** A screen of the app, screenshotted in each of its states. */\nexport interface Route {\n /** Names the baselines: lower-case letters, digits and dashes. */\n name: string;\n /** Path and query under the app's base, e.g. `/review` or `/library?sort=-added`. */\n path: string;\n /**\n * The server states to capture, by name. A list of handlers is shorthand for `{ handlers }`.\n * Default: one state, `default`, served by the base handlers alone.\n */\n states?: Record<string, readonly RequestHandler[] | RouteState>;\n viewports?: readonly ViewportChoice[];\n clip?: Clip;\n root?: string;\n waitFor?: string;\n setup?: Setup;\n}\n\n/** An app served from its production build (or a running server), screenshotted route by route. */\nexport interface AppTarget {\n /** The build folder to serve, e.g. `dist`. Unknown paths that ask for HTML get `index.html`. */\n dir?: string;\n /** Or a server that is already running, e.g. `http://localhost:4173`. */\n url?: string;\n /** The app's base path (Vite's `base`). Default `/`. */\n base?: string;\n /** MSW handlers for every route: the healthy server, usually the app's `handlers.ts`. */\n handlers?: readonly RequestHandler[];\n /** Default `#root`. */\n root?: string;\n /** Default `[\"wide\"]`. Every route is taken at each. */\n viewports?: readonly ViewportChoice[];\n /** Default `page`. */\n clip?: Clip;\n /** Default `dark`; `false` to rely on `prefers-color-scheme` alone. */\n darkClass?: string | false;\n /**\n * A `fetch` or XHR request no handler answers: `error` (default) fails the shot, because a\n * screenshot that depends on a real server is not a baseline; `bypass` lets it through.\n */\n onUnhandledRequest?: \"error\" | \"bypass\";\n routes: readonly Route[];\n}\n\n/** A visual suite: where baselines live and what to screenshot. Paths are relative to the config file. */\nexport interface VisualConfig {\n /** Committed baselines. Default `tests/visual/baselines`. */\n baselines?: string;\n /** Actual, expected and diff PNGs of changed shots (uploaded by CI). Default `tests/visual/output`. */\n output?: string;\n /** Default `[\"light\", \"dark\"]`. */\n themes?: readonly Theme[];\n /** Freeze the page's clock at this time, so \"3 minutes ago\" and today's date stay put. */\n time?: string | number | Date;\n /** The page's time zone. Default `UTC`, so a date renders the same on every machine. */\n timezone?: string;\n /** The page's locale (`navigator.language`, `Intl` defaults). Default `en-US`. */\n locale?: string;\n /**\n * What to do with text drawn in a font installed on the machine rather than one the page\n * loaded (a theme whose `--font-*` falls through to `ui-sans-serif`, or a glyph the web font\n * lacks). `error` (default) fails the shot, because no comparison threshold makes Cantarell\n * match San Francisco; `warn` reports it; `allow` skips the check. Bundle every face with\n * `@fontsource` (or your own `@font-face`) and name it first in the theme's `--font-*`.\n */\n systemFonts?: \"error\" | \"warn\" | \"allow\";\n /**\n * How a screenshot is compared with its baseline. The defaults (a 3×3 blur, then pixelmatch at\n * threshold 0.1 with 4 differing pixels allowed) absorb anti-aliasing differences between\n * machines and still fail on a changed letter; change them only with evidence from your own\n * screens.\n */\n compare?: CompareOptions;\n /** Pages captured at once. Default 4. */\n concurrency?: number;\n storybook?: StorybookTarget | string;\n app?: AppTarget;\n}\n\n/** What a run found. */\nexport interface VisualReport {\n /** Shots taken. */\n total: number;\n same: number;\n /** `name.png: reason` for each shot that matched without being pixel-identical (anti-aliasing absorbed). */\n tolerated: string[];\n /** `name.png: reason` for each shot that differs from its baseline. */\n changed: string[];\n /** Shots with no baseline yet (written, and copied to the output folder). */\n added: string[];\n /** Baselines no shot produced (removed when updating). */\n obsolete: string[];\n /** Shots that failed: page errors, console errors, unhandled requests, nothing rendered. */\n errors: string[];\n /** Things that make baselines less trustworthy, such as an unpinned Playwright. */\n warnings: string[];\n updated: boolean;\n /** Whether the run should fail (in CI a missing baseline fails too). */\n failed: boolean;\n}\n","// Turning what an app has into shots. A component library has stories; an app may have only\n// screens (strata-listory has Review, Library and Settings and no stories), so routes are a\n// first-class target: each route is taken in each server state, viewport and theme, with the\n// state set by MSW handlers, the same handlers its unit tests use. Names are stable and readable\n// (`review--empty--phone--dark.png`) because a person reviews baselines by file name in a diff.\nimport { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { viewports, type AppTarget, type Route, type RouteState, type Shot, type StorybookTarget, type Theme, type Viewport, type ViewportChoice } from \"./types\";\n\n/** The light and dark themes, the default for every target. */\nexport const defaultThemes: readonly Theme[] = [\"light\", \"dark\"];\n\n// Untagged stories lay out in a 1024-wide, 200-tall frame and the clip grows with the component,\n// so a short component's fixed elements (the undo bar) sit near it rather than 768px down.\nconst storyViewport: Viewport = { width: 1024, height: 200 };\n\ninterface IndexEntry {\n id: string;\n type: string;\n title?: string;\n name?: string;\n tags?: string[];\n}\n\n/**\n * Shots for every story in a built Storybook (its `index.json`), in each theme. Tags pick the\n * viewport: `visual-phone` 390×844, `visual-wide` 1440×900, otherwise 1024 wide; `no-visual`\n * skips the story. A story's own tag beats its file's, since Storybook merges both.\n */\nexport function storybookShots(target: StorybookTarget & { dir: string }, themes: readonly Theme[] = defaultThemes): Shot[] {\n const index = JSON.parse(readFileSync(join(target.dir, \"index.json\"), \"utf8\")) as { entries: Record<string, IndexEntry> };\n const global = target.themeGlobal ?? \"theme\";\n return Object.values(index.entries)\n .filter((e) => e.type === \"story\" && !e.tags?.includes(\"no-visual\"))\n .flatMap((story) => {\n const tag = [\"visual-phone\", \"visual-wide\"].find((t) => story.tags?.includes(t));\n const viewport = tag === \"visual-phone\" ? viewports.phone : tag === \"visual-wide\" ? viewports.wide : storyViewport;\n return themes.map((theme) => ({\n name: `${story.id}--${theme}`,\n path: `iframe.html?id=${story.id}&viewMode=story&globals=${global}:${theme}`,\n theme,\n viewport: { ...viewport },\n root: \"#storybook-root\",\n clip: \"paint\" as const,\n darkClass: false as const,\n }));\n });\n}\n\nconst slug = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\nfunction viewportName(v: ViewportChoice): string {\n return typeof v === \"string\" ? v : `${v.width}x${v.height}`;\n}\n\nfunction viewportSize(v: ViewportChoice): Viewport {\n if (typeof v !== \"string\") return { width: v.width, height: v.height };\n const size = viewports[v];\n if (!size) throw new Error(`unknown viewport \"${String(v)}\": use ${Object.keys(viewports).join(\", \")} or { width, height }`);\n return { ...size };\n}\n\nfunction stateOf(value: readonly unknown[] | RouteState): RouteState {\n return Array.isArray(value) ? { handlers: value as RouteState[\"handlers\"] } : (value as RouteState);\n}\n\n/**\n * Shots for every route of an app in each state, viewport and theme, named\n * `route--state--viewport--theme`. A state's handlers come before the target's base handlers, as\n * `server.use(...)` would put them.\n */\nexport function routeShots(app: AppTarget, themes: readonly Theme[] = defaultThemes): Shot[] {\n const shots: Shot[] = [];\n for (const route of app.routes as readonly Route[]) {\n if (!slug.test(route.name)) throw new Error(`route name \"${route.name}\" must be lower-case letters, digits and dashes`);\n const states = Object.entries(route.states ?? { default: [] });\n if (!states.length) throw new Error(`route \"${route.name}\" has an empty states object: leave it out for one default state`);\n const chosen = route.viewports ?? app.viewports ?? [\"wide\"];\n for (const [stateName, value] of states) {\n if (!slug.test(stateName)) throw new Error(`state \"${stateName}\" of route \"${route.name}\" must be lower-case letters, digits and dashes`);\n const state = stateOf(value);\n const setups = [route.setup, state.setup].filter((s) => s !== undefined);\n for (const v of chosen) {\n for (const theme of themes) {\n shots.push({\n name: `${route.name}--${stateName}--${viewportName(v)}--${theme}`,\n path: state.path ?? route.path,\n theme,\n viewport: viewportSize(v),\n root: route.root ?? app.root ?? \"#root\",\n clip: route.clip ?? app.clip ?? \"page\",\n waitFor: state.waitFor ?? route.waitFor,\n handlers: [...(state.handlers ?? []), ...(app.handlers ?? [])],\n darkClass: app.darkClass ?? \"dark\",\n setup: setups.length ? async (page, shot) => { for (const s of setups) await s(page, shot); } : undefined,\n });\n }\n }\n }\n }\n return shots;\n}\n","// Running a suite: serve each target, take its shots a few at a time in one Chromium, compare\n// each with its committed baseline, and report. The rules are the library's own, so an app's\n// suite fails for the same reasons Strata's does: a changed screenshot, a page or console\n// error, an unanswered request, and in CI a shot with no baseline (it was added without one).\n//\n// Baselines are only comparable when written by the same Chromium on the same platform, which\n// is why Playwright is pinned to an exact version. A run records both next to the baselines\n// (`.strata-visual.json`) when it writes them, and says so when a later run differs.\nimport { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport type { Browser } from \"playwright\";\nimport { capture } from \"./capture\";\nimport { compare, decode } from \"./compare\";\nimport { serveStatic, type StaticServer } from \"./serve\";\nimport { defaultThemes, routeShots, storybookShots } from \"./targets\";\nimport type { Shot, VisualConfig, VisualReport } from \"./types\";\n\n/** Returns the config unchanged; it exists so a config file is type-checked. */\nexport function defineVisualConfig(config: VisualConfig): VisualConfig {\n return config;\n}\n\n/** Options for one run, usually from the command line. */\nexport interface RunOptions {\n /** Folder the config's paths are relative to. Default `process.cwd()`. */\n cwd?: string;\n /** Write the screenshots as the baselines and remove obsolete ones, instead of comparing. */\n update?: boolean;\n /** Only shots whose name contains this text (obsolete baselines are then not reported). */\n filter?: string;\n /** Fail when a shot has no baseline. Default: when the `CI` environment variable is set. */\n ci?: boolean;\n /** Progress lines; default none. */\n log?: (line: string) => void;\n}\n\nconst metaFile = \".strata-visual.json\";\ninterface Meta {\n chromium: string;\n platform: string;\n}\n\ninterface Batch {\n shots: Shot[];\n server?: StaticServer;\n baseUrl: string;\n blockServiceWorkers: boolean;\n onUnhandledRequest?: \"error\" | \"bypass\";\n}\n\n/** Screenshots every shot the config describes, compares with the baselines, and reports. */\nexport async function runVisual(config: VisualConfig, options: RunOptions = {}): Promise<VisualReport> {\n const cwd = resolve(options.cwd ?? process.cwd());\n const baselineDir = resolve(cwd, config.baselines ?? \"tests/visual/baselines\");\n const outputDir = resolve(cwd, config.output ?? \"tests/visual/output\");\n const themes = config.themes ?? defaultThemes;\n const update = options.update ?? false;\n const ci = options.ci ?? Boolean(process.env.CI);\n const log = options.log ?? (() => undefined);\n const concurrency = config.concurrency ?? 4;\n // A worker count that is not a positive integer would start no workers and report an empty,\n // passing run, so it is refused up front.\n if (!Number.isInteger(concurrency) || concurrency < 1) throw new Error(`concurrency must be a whole number of pages, 1 or more (got ${String(config.concurrency)})`);\n const report: VisualReport = { total: 0, same: 0, tolerated: [], changed: [], added: [], obsolete: [], errors: [], warnings: pinWarnings(cwd), updated: update, failed: false };\n\n const batches: Batch[] = [];\n try {\n if (config.storybook !== undefined) {\n const target = typeof config.storybook === \"string\" ? { dir: config.storybook } : config.storybook;\n const dir = resolve(cwd, target.dir ?? \"storybook-static\");\n if (!existsSync(join(dir, \"index.json\"))) throw new Error(`${join(dir, \"index.json\")} not found: build Storybook first (storybook build)`);\n // Shots first: if building them throws, no server is left running to hold the process open.\n const shots = storybookShots({ ...target, dir }, themes);\n const batch: Batch = { shots, baseUrl: \"\", blockServiceWorkers: false };\n batches.push(batch);\n batch.server = await serveStatic(dir);\n batch.baseUrl = batch.server.url;\n }\n if (config.app !== undefined) {\n const app = config.app;\n if (!app.dir === !app.url) throw new Error(\"app needs exactly one of dir (a build to serve) or url (a running server)\");\n const shots = routeShots(app, themes);\n const batch: Batch = { shots, baseUrl: \"\", blockServiceWorkers: true, onUnhandledRequest: app.onUnhandledRequest ?? \"error\" };\n batches.push(batch);\n if (app.dir) {\n const dir = resolve(cwd, app.dir);\n if (!existsSync(join(dir, \"index.html\"))) throw new Error(`${join(dir, \"index.html\")} not found: build the app first`);\n batch.server = await serveStatic(dir, { spa: true, base: app.base });\n batch.baseUrl = batch.server.url;\n } else {\n batch.baseUrl = new URL(`${(app.base ?? \"/\").replace(/^\\/*/, \"/\").replace(/\\/*$/, \"/\")}`, app.url).href;\n }\n }\n if (!batches.length) throw new Error(\"nothing to screenshot: the config needs storybook or app\");\n\n const all = batches.flatMap((b) => b.shots);\n const names = new Set<string>();\n for (const s of all) {\n if (names.has(s.name)) throw new Error(`two shots are named ${s.name}: give routes and states distinct names`);\n names.add(s.name);\n }\n for (const b of batches) b.shots = b.shots.filter((s) => !options.filter || s.name.includes(options.filter));\n report.total = batches.reduce((n, b) => n + b.shots.length, 0);\n\n mkdirSync(baselineDir, { recursive: true });\n rmSync(outputDir, { recursive: true, force: true });\n mkdirSync(outputDir, { recursive: true });\n\n const { chromium } = await import(\"playwright\").catch(() => {\n throw new Error(\"strata-visual needs Playwright: npm install -D -E playwright, then npx playwright install chromium\");\n });\n // Font hinting and LCD anti-aliasing off and an sRGB profile: the same pixels on every machine.\n // STRATA_VISUAL_CHROMIUM_ARGS adds flags, for experiments such as checking that the\n // comparison absorbs another rasteriser (the visual-portability workflow).\n const extraArgs = (process.env.STRATA_VISUAL_CHROMIUM_ARGS ?? \"\").split(/\\s+/).filter(Boolean);\n const browser = await chromium.launch({ args: [\"--font-render-hinting=none\", \"--disable-lcd-text\", \"--force-color-profile=srgb\", ...extraArgs] });\n const meta: Meta = { chromium: browser.version(), platform: `${process.platform}-${process.arch}` };\n try {\n for (const batch of batches) await runBatch(browser, batch, { config, baselineDir, outputDir, update, report, log });\n } finally {\n await browser.close();\n }\n\n const pngs = readdirSync(baselineDir).filter((f) => f.endsWith(\".png\"));\n report.obsolete = options.filter ? [] : pngs.filter((f) => !names.has(f.slice(0, -4)));\n if (update) {\n for (const f of report.obsolete) rmSync(join(baselineDir, f));\n if (!options.filter) writeFileSync(join(baselineDir, metaFile), `${JSON.stringify(meta, null, 2)}\\n`);\n } else if (report.changed.length) {\n const written = readMeta(baselineDir);\n if (written && (written.chromium !== meta.chromium || written.platform !== meta.platform)) {\n report.warnings.push(\n `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`,\n );\n }\n }\n } finally {\n for (const b of batches) await b.server?.close();\n }\n report.failed = Boolean(report.errors.length || report.changed.length || (ci && !update && report.added.length));\n return report;\n}\n\nasync function runBatch(\n browser: Browser,\n batch: Batch,\n ctx: { config: VisualConfig; baselineDir: string; outputDir: string; update: boolean; report: VisualReport; log: (l: string) => void },\n) {\n const { baselineDir, outputDir, update, report } = ctx;\n const shoot = async (shot: Shot) => {\n const file = `${shot.name}.png`;\n try {\n const fonts = ctx.config.systemFonts ?? \"error\";\n const { png, problems, systemFonts } = await capture(browser, shot, {\n baseUrl: batch.baseUrl,\n time: ctx.config.time,\n timezone: ctx.config.timezone,\n locale: ctx.config.locale,\n blockServiceWorkers: batch.blockServiceWorkers,\n onUnhandledRequest: batch.onUnhandledRequest,\n checkFonts: fonts !== \"allow\",\n });\n if (systemFonts.length) {\n const line = `${file}: text in a system font, which differs by machine (bundle the face with @fontsource and name it in the theme's --font-*): ${systemFonts.join(\", \")}`;\n if (fonts === \"error\") problems.push(line.slice(file.length + 2));\n else report.warnings.push(line);\n }\n if (problems.length) report.errors.push(`${file}: ${problems.join(\" | \")}`);\n const baselinePath = join(baselineDir, file);\n if (update || !existsSync(baselinePath)) {\n if (!update) report.added.push(file);\n writeFileSync(baselinePath, png);\n if (!update) writeFileSync(join(outputDir, file), png);\n return;\n }\n const expected = readFileSync(baselinePath);\n const result = compare(decode(expected), decode(png), ctx.config.compare);\n if (result.same) {\n report.same++;\n if (!result.identical) report.tolerated.push(`${file}: ${result.reason}`);\n return;\n }\n report.changed.push(`${file}: ${result.reason}`);\n writeFileSync(join(outputDir, `${shot.name}.actual.png`), png);\n writeFileSync(join(outputDir, `${shot.name}.expected.png`), expected);\n if (result.diff) writeFileSync(join(outputDir, `${shot.name}.diff.png`), result.diff);\n } catch (e) {\n report.errors.push(`${file}: ${(e instanceof Error ? e.message : String(e)).split(\"\\n\")[0]}`);\n } finally {\n ctx.log(file);\n }\n };\n // A few pages at once: each shot has its own context, so they cannot affect each other.\n const queue = [...batch.shots];\n await Promise.all(\n Array.from({ length: ctx.config.concurrency ?? 4 }, async () => {\n for (let shot = queue.shift(); shot; shot = queue.shift()) await shoot(shot);\n }),\n );\n}\n\nfunction readMeta(dir: string): Meta | undefined {\n try {\n return JSON.parse(readFileSync(join(dir, metaFile), \"utf8\")) as Meta;\n } catch {\n return undefined;\n }\n}\n\n/** A warning when the app's package.json lets Playwright float, since each version brings its own Chromium. */\nexport function pinWarnings(cwd: string): string[] {\n let pkg: { dependencies?: Record<string, string>; devDependencies?: Record<string, string> };\n try {\n pkg = JSON.parse(readFileSync(join(cwd, \"package.json\"), \"utf8\"));\n } catch {\n return [];\n }\n const deps = { ...pkg.dependencies, ...pkg.devDependencies };\n return [\"playwright\", \"@playwright/test\"]\n .filter((name) => deps[name] !== undefined && !/^\\d+\\.\\d+\\.\\d+$/.test(deps[name]))\n .map(\n (name) =>\n `${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`,\n );\n}\n\n// Sorts by the blurred count, then by the count without the blur.\nconst pixels = (line: string) => {\n const m = /: (\\d+) pixels differ[^,]*(?:, (\\d+) without)?/.exec(line);\n return Number(m?.[1] ?? 0) * 1e9 + Number(m?.[2] ?? 0);\n};\n\n/** The report as the lines the command prints. */\nexport function formatReport(report: VisualReport): string {\n const lines = [\n report.updated\n ? `Wrote ${report.total} baselines${report.obsolete.length ? `, removed ${report.obsolete.length} obsolete` : \"\"}.`\n : `${report.same} of ${report.total} screenshots match their baselines${report.tolerated.length ? ` (${report.same - report.tolerated.length} identical, ${report.tolerated.length} within tolerance)` : \"\"}.`,\n ...report.changed.map((l) => `changed ${l}`),\n // The most-differing few: enough to see how close to the allowance a machine runs.\n ...[...report.tolerated]\n .sort((a, b) => pixels(b) - pixels(a))\n .slice(0, 5)\n .map((l) => `within ${l}`),\n ...(report.tolerated.length > 5 ? [`within … and ${report.tolerated.length - 5} more`] : []),\n ...report.added.map((l) => `new ${l} (baseline written; commit it)`),\n ...report.obsolete.map((l) => `obsolete ${l}${report.updated ? \" (removed)\" : \" (run with --update to remove)\"}`),\n ...report.errors.map((l) => `error ${l}`),\n ...report.warnings.map((l) => `warning ${l}`),\n ];\n if (report.failed) {\n 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.\");\n }\n return lines.join(\"\\n\");\n}\n"],"mappings":";;;;;;AAUA,IAAM,2BAA2B;AAGjC,IAAM,SAAS;;AA8Bf,SAAgB,eAAe,MAAc,SAAyB;CACpE,IAAI,uBAAuB,KAAK,IAAI,GAAG,OAAO;CAC9C,OAAO,IAAI,IAAI,KAAK,QAAQ,QAAQ,EAAE,GAAG,OAAO,CAAC,CAAC;AACpD;;AAGA,SAAgB,eAAe,SAA4F;CACzH,MAAM,SAAS,QAAQ,OAAO;CAC9B,MAAM,OAAO,WAAW,SAAS,WAAW,SAAS,KAAA,IAAa,QAAQ,eAAe,KAAK,KAAA;CAC9F,OAAO,IAAI,QAAQ,QAAQ,IAAI,GAAG;EAAE;EAAQ,SAAS,QAAQ,QAAQ;EAAG,MAAM,OAAO,IAAI,WAAW,IAAI,IAAI,KAAA;CAAU,CAAC;AACzH;AAEA,eAAe,mBACb,SACA,UACA,SACA,WACA,UACA;CACA,MAAM,MAAM,MAAM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; }
171
171
  @utility layer-tip { z-index: 70; }
172
172
 
173
+ /* The dim behind a dialog or full-screen view. Black at an alpha, not the foreground role: in a dark
174
+ theme `foreground` is light, so a foreground scrim brightened the page instead of dimming it
175
+ (strata-react issue #136). Not a theme role, so no app has anything to add; darker in the dark
176
+ scheme, where the same alpha would barely show. */
177
+ @utility scrim {
178
+ background-color: rgb(0 0 0 / 0.4);
179
+ :where(.dark) & { background-color: rgb(0 0 0 / 0.65); }
180
+ }
181
+
173
182
  /* An overlay's entrance: an ordinary effect (fade and 2% scale), CSS only, once on mount. Overlays
174
183
  are occasional (character.md), so the effects duration and no overshoot; they close at once.
175
184
  Reduced motion collapses it in the rule below. */
package/dist/testing.js CHANGED
@@ -1,4 +1,5 @@
1
- import { l as ThemeProvider, n as createQueryClient, t as StrataQueryProvider } from "./query-CIh1Dpgn.js";
1
+ import { n as createQueryClient, t as StrataQueryProvider } from "./query-CP78goXj.js";
2
+ import { r as ThemeProvider } from "./theme-BgTOESmN.js";
2
3
  import "react";
3
4
  import { jsx } from "react/jsx-runtime";
4
5
  import { MemoryRouter, RouterProvider, createMemoryRouter } from "react-router";
@@ -1 +1 @@
1
- {"version":3,"file":"testing.js","names":[],"sources":["../src/testing/layout.ts","../src/testing/buttons.ts","../src/testing/intersection-observer.ts","../src/testing/index.tsx"],"sourcesContent":["// jsdom does no layout: every box is 0×0 and there is no ResizeObserver. Components that measure\n// (LineChart's width; React Aria's Virtualizer draws every row of a list in a test unless the box is mocked, which these shims do not make smaller. A virtualised table with detail rows, or a virtualised grid of tiles, measures each row by its scroll size, which jsdom reports as 0: a test of one gives `Element.prototype.scrollHeight` a value) then render nothing to\n// assert on, so an app testing a screen built from them hits the same wall Strata's own suite did.\n// These shims give every element one fixed box and a ResizeObserver that reports it once on\n// observe. Real layout is checked by the visual suite in Chromium, never here.\n\n// jsdom has no DOMRect constructor in every version, so rects are plain objects of the same shape.\n/** A DOMRect-shaped object, for stand-ins that report geometry. */\nexport function box(x: number, y: number, width: number, height: number): DOMRect {\n return { x, y, width, height, top: y, left: x, right: x + width, bottom: y + height, toJSON() { return this; } } as DOMRect;\n}\n\n/** The box every element reports while the shims are installed. */\nexport interface LayoutBox {\n width: number;\n height: number;\n}\n\n/**\n * Give jsdom a fixed box for every element (`getBoundingClientRect`, `offset*`, `client*`) and a\n * ResizeObserver that reports it on observe, so measuring components render. Defaults to 640×280.\n * Call once in a Vitest setup file; returns a function that puts the originals back.\n */\nexport function installLayoutShims({ width = 640, height = 280 }: Partial<LayoutBox> = {}): () => void {\n const restore: (() => void)[] = [];\n const replace = (target: object, prop: string, descriptor: PropertyDescriptor) => {\n const before = Object.getOwnPropertyDescriptor(target, prop);\n Object.defineProperty(target, prop, { configurable: true, ...descriptor });\n restore.push(() => {\n if (before) Object.defineProperty(target, prop, before);\n else delete (target as Record<string, unknown>)[prop];\n });\n };\n\n class FixedResizeObserver implements ResizeObserver {\n constructor(private readonly callback: ResizeObserverCallback) {}\n observe(target: Element) {\n this.callback([{ target, contentRect: { width, height } } as unknown as ResizeObserverEntry], this);\n }\n unobserve() {}\n disconnect() {}\n }\n if (!globalThis.ResizeObserver) replace(globalThis, \"ResizeObserver\", { writable: true, value: FixedResizeObserver });\n\n replace(Element.prototype, \"getBoundingClientRect\", {\n writable: true,\n value: () => box(0, 0, width, height),\n });\n for (const [prop, value] of [[\"offsetWidth\", width], [\"offsetHeight\", height], [\"clientWidth\", width], [\"clientHeight\", height]] as const) {\n replace(HTMLElement.prototype, prop, { get: () => value });\n }\n\n return () => {\n for (const undo of restore.reverse()) undo();\n };\n}\n","import type { Phase } from \"../components/async-button\";\n\n// Assertions for the rules a screen keeps, read from what the components draw rather than from\n// their class names (strata-react issue #48, from the Tubes Library test, which matched\n// `bg-primary`). `Button` marks its variant (`data-variant`), so \"one filled button per view\"\n// (ux-research patterns.md §2, with the BulkBar hand-over: while rows are chosen the bulk action is\n// the filled one) is a check a screen test can make after every interaction. `AsyncButton` marks\n// its phase (`data-phase`), because it keeps every phase's label in the DOM to hold its width, so\n// its text reads \"AddAdding…AddedTry again\" and only the phase says which one shows.\n\n/** Whether an element is out of the view: hidden, inert or aria-hidden, itself or by an ancestor. */\nfunction outOfView(el: Element) {\n return Boolean(el.closest('[hidden], [inert], [aria-hidden=\"true\"]'));\n}\n\n/** An element's name as a person reads it: its `aria-label`, else its text without the parts hidden from screen readers. */\nfunction nameOf(el: Element): string {\n const label = el.getAttribute(\"aria-label\");\n if (label) return label;\n const walk = (node: Node): string =>\n node.nodeType === 3\n ? (node.textContent ?? \"\")\n : node instanceof Element && node.getAttribute(\"aria-hidden\") === \"true\"\n ? \"\"\n : [...node.childNodes].map(walk).join(\"\");\n return walk(el).replace(/\\s+/g, \" \").trim();\n}\n\n/** The filled (`variant=\"default\"`) buttons and links in `container` (default the whole document) that are in view. */\nexport function filledButtons(container: ParentNode = document.body): HTMLElement[] {\n return [...container.querySelectorAll<HTMLElement>('[data-variant=\"default\"]')].filter((el) => !outOfView(el));\n}\n\n/** Throws unless `container` (default the whole document) has exactly one filled button in view; the message names the ones found. */\nexport function expectOneFilledButton(container: ParentNode = document.body): HTMLElement {\n const found = filledButtons(container);\n if (found.length === 1) return found[0];\n const names = found.map((el) => `\"${nameOf(el)}\"`).join(\", \");\n throw new Error(`Expected one filled button in the view, found ${found.length}${names ? `: ${names}` : \"\"}.`);\n}\n\n/** The phase an `AsyncButton` is in (`idle`, `pending`, `done`, `error`), from the button or any element inside it. */\nexport function asyncButtonPhase(el: Element): Phase {\n const phase = el.closest(\"[data-phase]\")?.getAttribute(\"data-phase\");\n if (phase === \"idle\" || phase === \"pending\" || phase === \"done\" || phase === \"error\") return phase;\n throw new Error(`Not an AsyncButton: ${el.outerHTML.slice(0, 120)}`);\n}\n","// jsdom has no IntersectionObserver and does no layout, so nothing a component observes ever comes\n// into view in a unit test. Infinite lists load the next page when a sentinel at the end of the\n// list intersects, and before this helper every app wrote its own firable fake to test that\n// (strata-react issue #12, from strata-listory). This one stands in for the global, records what\n// each observer watches, and lets the test say when something scrolls into view: `scrollToEnd()`\n// for the common case, `intersect(el)` for one element. Entries are delivered inside `act` so the\n// state updates they cause are flushed before the next assertion, as a real scroll would be.\n\nimport { act } from \"@testing-library/react\";\nimport { box } from \"./layout\";\n\n/** One stand-in observer: its callback, options and the elements it currently watches. */\nexport interface FakeObserver {\n readonly callback: IntersectionObserverCallback;\n readonly options: IntersectionObserverInit;\n readonly targets: ReadonlySet<Element>;\n}\n\n/** The controls `installFakeIntersectionObserver` returns. */\nexport interface FakeIntersectionObserverControls {\n /** Every observer created since install, including disconnected ones (their target sets are empty). */\n readonly observers: readonly FakeObserver[];\n /** Report `el` to every observer watching it: in view by default, or out of view with `false`. Returns how many observers were told. */\n intersect(el: Element, isIntersecting?: boolean): number;\n /** Report every watched element as in view, as if the person scrolled to the end of the list. Returns how many elements were reported. */\n scrollToEnd(): number;\n /** Put back whatever `IntersectionObserver` was there before install. */\n uninstall(): void;\n}\n\nfunction entryFor(target: Element, isIntersecting: boolean): IntersectionObserverEntry {\n const rect = target.getBoundingClientRect();\n return {\n target,\n isIntersecting,\n intersectionRatio: isIntersecting ? 1 : 0,\n boundingClientRect: rect,\n intersectionRect: isIntersecting ? rect : box(0, 0, 0, 0),\n rootBounds: null,\n time: performance.now(),\n };\n}\n\n/**\n * Replace `globalThis.IntersectionObserver` with a stand-in the test fires by hand. Call it in\n * `beforeEach` and call `uninstall()` in `afterEach`.\n *\n * @example\n * let io: FakeIntersectionObserverControls;\n * beforeEach(() => { io = installFakeIntersectionObserver(); });\n * afterEach(() => io.uninstall());\n *\n * it(\"loads the next page at the end of the list\", async () => {\n * renderWithStrata(<Pieces />);\n * await screen.findByRole(\"list\", { name: \"Pieces\" });\n * io.scrollToEnd();\n * expect(await screen.findByText(\"Celadon bowl\")).toBeInTheDocument();\n * });\n */\nexport function installFakeIntersectionObserver(): FakeIntersectionObserverControls {\n const previous = Object.getOwnPropertyDescriptor(globalThis, \"IntersectionObserver\");\n const observers: (FakeObserver & { targets: Set<Element>; self: IntersectionObserver })[] = [];\n\n class FakeIntersectionObserver implements IntersectionObserver {\n readonly root: Element | Document | null;\n readonly rootMargin: string;\n readonly thresholds: readonly number[];\n readonly scrollMargin = \"0px\";\n private readonly record: (typeof observers)[number];\n\n constructor(callback: IntersectionObserverCallback, options: IntersectionObserverInit = {}) {\n this.root = options.root ?? null;\n this.rootMargin = options.rootMargin ?? \"0px\";\n const threshold = options.threshold ?? 0;\n this.thresholds = Array.isArray(threshold) ? threshold : [threshold];\n this.record = { callback, options, targets: new Set(), self: this };\n observers.push(this.record);\n }\n observe(target: Element) {\n this.record.targets.add(target);\n }\n unobserve(target: Element) {\n this.record.targets.delete(target);\n }\n disconnect() {\n this.record.targets.clear();\n }\n takeRecords(): IntersectionObserverEntry[] {\n return [];\n }\n }\n\n Object.defineProperty(globalThis, \"IntersectionObserver\", {\n configurable: true,\n writable: true,\n value: FakeIntersectionObserver,\n });\n\n const deliver = (observer: (typeof observers)[number], targets: readonly Element[], isIntersecting: boolean) => {\n act(() => observer.callback(targets.map((t) => entryFor(t, isIntersecting)), observer.self));\n };\n\n return {\n observers,\n intersect(el, isIntersecting = true) {\n const watching = observers.filter((o) => o.targets.has(el));\n for (const o of watching) deliver(o, [el], isIntersecting);\n return watching.length;\n },\n scrollToEnd() {\n // Snapshot every observer's targets before any callback runs: a callback that loads more\n // may observe a new sentinel, on this observer or another, which the person has not\n // scrolled to yet.\n const batches = observers.map((o) => [o, [...o.targets]] as const).filter(([, targets]) => targets.length > 0);\n for (const [o, targets] of batches) deliver(o, targets, true);\n return batches.reduce((n, [, targets]) => n + targets.length, 0);\n },\n uninstall() {\n if (previous) Object.defineProperty(globalThis, \"IntersectionObserver\", previous);\n else delete (globalThis as { IntersectionObserver?: unknown }).IntersectionObserver;\n },\n };\n}\n","/**\n * Test helpers: render a component, or a whole route tree, inside a router and a query client, as\n * a Strata app runs it,\n * and fill the gaps jsdom leaves (layout, ResizeObserver, IntersectionObserver). Use with MSW for\n * the network, never module mocks.\n *\n * @module strata-react/testing\n */\nimport * as React from \"react\";\nimport { act, render, type RenderOptions } from \"@testing-library/react\";\nimport { MemoryRouter, RouterProvider, createMemoryRouter, type RouteObject, type To } from \"react-router\";\nimport { QueryClient } from \"@tanstack/react-query\";\nimport { StrataQueryProvider, createQueryClient } from \"../query\";\nimport { ThemeProvider, type ColorSchemePreference } from \"../components/theme\";\n\nexport { installLayoutShims, type LayoutBox } from \"./layout\";\nexport { filledButtons, expectOneFilledButton, asyncButtonPhase } from \"./buttons\";\nexport {\n installFakeIntersectionObserver,\n type FakeIntersectionObserverControls,\n type FakeObserver,\n} from \"./intersection-observer\";\n\n// Render a component the way a Strata app runs it: inside a router and a query client. Tests use\n// MSW for the network (see CLAUDE.md), never module mocks, so the real fetch/query/DataView path\n// runs. Each call gets a fresh QueryClient with retries off, so a test that serves a 500 sees the\n// error at once instead of after the retry delay. It also runs inside a ThemeProvider with\n// storage off, so `useColorScheme` works and a test can render the dark scheme with\n// `colorScheme: \"dark\"` without touching localStorage or leaking state into the next test.\n\n/** A query client for tests: no retries, and nothing goes stale or is collected mid-test. */\nexport function createTestQueryClient() {\n return createQueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity, gcTime: Infinity } } });\n}\n\n/** The options `renderWithStrata` and `renderRoutes` share, beside Testing Library's own. */\nexport type StrataRenderOptions = Omit<RenderOptions, \"wrapper\"> & {\n /** The URL the test starts at, with its search and hash (`/bookings?sort=pieces.desc`). Defaults to `/`. */\n route?: string;\n /** The query client; a fresh `createTestQueryClient()` when left out. */\n client?: QueryClient;\n /** The colour scheme to render; `light` when left out. */\n colorScheme?: ColorSchemePreference;\n};\n\n// The providers every Strata app has above its router, in the order an app nests them.\nfunction StrataProviders({\n client,\n colorScheme,\n children,\n}: {\n client: QueryClient;\n colorScheme: ColorSchemePreference;\n children: React.ReactNode;\n}) {\n return (\n <ThemeProvider defaultPreference={colorScheme} storageKey={null}>\n <StrataQueryProvider client={client}>{children}</StrataQueryProvider>\n </ThemeProvider>\n );\n}\n\n/** Testing Library's `render` inside `StrataQueryProvider` and a `MemoryRouter` at `route`. */\nexport function renderWithStrata(\n ui: React.ReactElement,\n { route = \"/\", client = createTestQueryClient(), colorScheme = \"light\", ...options }: StrataRenderOptions = {},\n) {\n const Wrapper = ({ children }: { children: React.ReactNode }) => (\n <StrataProviders client={client} colorScheme={colorScheme}>\n <MemoryRouter initialEntries={[route]}>{children}</MemoryRouter>\n </StrataProviders>\n );\n return { client, ...render(ui, { wrapper: Wrapper, ...options }) };\n}\n\n// Render an app's own route tree: its layout routes and <Outlet />s, index routes, redirects\n// (<Navigate /> or a loader's redirect()), loaders, actions and error elements. Those only run in\n// a data router, which <MemoryRouter> is not, so renderWithStrata cannot show them; this builds\n// the memory twin of the app's createBrowserRouter from the same RouteObject[] the app exports,\n// so the test and the app cannot drift. The providers and options are renderWithStrata's.\n// `basename` is the app's own (the kiln app runs under /kiln), and `route` is the full URL,\n// basename included, as the browser would show it. The router is returned so a test can assert\n// where a redirect landed (`router.state.location`), and `navigate` moves it inside act().\n\n/** `renderRoutes`'s options: `renderWithStrata`'s, plus the app's `basename`. */\nexport type RenderRoutesOptions = StrataRenderOptions & {\n /** The base path the app is served under, as passed to `createBrowserRouter`. */\n basename?: string;\n};\n\n/** Testing Library's `render` of an app's route tree in a memory data router at `route`, with Strata's providers. */\nexport function renderRoutes(\n routes: RouteObject[],\n {\n route,\n basename,\n client = createTestQueryClient(),\n colorScheme = \"light\",\n ...options\n }: RenderRoutesOptions = {},\n) {\n const router = createMemoryRouter(routes, { initialEntries: [route ?? basename ?? \"/\"], basename });\n const result = render(\n <StrataProviders client={client} colorScheme={colorScheme}>\n <RouterProvider router={router} />\n </StrataProviders>,\n options,\n );\n const navigate = (to: To | number) =>\n act(async () => {\n await (typeof to === \"number\" ? router.navigate(to) : router.navigate(to));\n });\n return { client, router, navigate, ...result };\n}\n"],"mappings":";;;;;;;AAQA,SAAgB,IAAI,GAAW,GAAW,OAAe,QAAyB;CACh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;EAC5C,UAAA,oBAAC,gBAAD,EAAwB,OAAS,CAAA;CAClB,CAAA,GACjB,OACF;CACA,MAAM,YAAY,OAChB,IAAI,YAAY;EACd,OAAO,OAAO,OAAO,WAAW,OAAO,SAAS,EAAE,IAAI,OAAO,SAAS,EAAE;CAC1E,CAAC;CACH,OAAO;EAAE;EAAQ;EAAQ;EAAU,GAAG;CAAO;AAC/C"}
1
+ {"version":3,"file":"testing.js","names":[],"sources":["../src/testing/layout.ts","../src/testing/buttons.ts","../src/testing/intersection-observer.ts","../src/testing/index.tsx"],"sourcesContent":["// jsdom does no layout: every box is 0×0 and there is no ResizeObserver. Components that measure\n// (LineChart's width; React Aria's Virtualizer draws every row of a list in a test unless the box is mocked, which these shims do not make smaller. A virtualised table with detail rows, or a virtualised grid of tiles, measures each row by its scroll size, which jsdom reports as 0: a test of one gives `Element.prototype.scrollHeight` a value) then render nothing to\n// assert on, so an app testing a screen built from them hits the same wall Strata's own suite did.\n// These shims give every element one fixed box and a ResizeObserver that reports it once on\n// observe. Real layout is checked by the visual suite in Chromium, never here.\n\n// jsdom has no DOMRect constructor in every version, so rects are plain objects of the same shape.\n/** A DOMRect-shaped object, for stand-ins that report geometry. */\nexport function box(x: number, y: number, width: number, height: number): DOMRect {\n return { x, y, width, height, top: y, left: x, right: x + width, bottom: y + height, toJSON() { return this; } } as DOMRect;\n}\n\n/** The box every element reports while the shims are installed. */\nexport interface LayoutBox {\n width: number;\n height: number;\n}\n\n/**\n * Give jsdom a fixed box for every element (`getBoundingClientRect`, `offset*`, `client*`) and a\n * ResizeObserver that reports it on observe, so measuring components render. Defaults to 640×280.\n * Call once in a Vitest setup file; returns a function that puts the originals back.\n */\nexport function installLayoutShims({ width = 640, height = 280 }: Partial<LayoutBox> = {}): () => void {\n const restore: (() => void)[] = [];\n const replace = (target: object, prop: string, descriptor: PropertyDescriptor) => {\n const before = Object.getOwnPropertyDescriptor(target, prop);\n Object.defineProperty(target, prop, { configurable: true, ...descriptor });\n restore.push(() => {\n if (before) Object.defineProperty(target, prop, before);\n else delete (target as Record<string, unknown>)[prop];\n });\n };\n\n class FixedResizeObserver implements ResizeObserver {\n constructor(private readonly callback: ResizeObserverCallback) {}\n observe(target: Element) {\n this.callback([{ target, contentRect: { width, height } } as unknown as ResizeObserverEntry], this);\n }\n unobserve() {}\n disconnect() {}\n }\n if (!globalThis.ResizeObserver) replace(globalThis, \"ResizeObserver\", { writable: true, value: FixedResizeObserver });\n\n replace(Element.prototype, \"getBoundingClientRect\", {\n writable: true,\n value: () => box(0, 0, width, height),\n });\n for (const [prop, value] of [[\"offsetWidth\", width], [\"offsetHeight\", height], [\"clientWidth\", width], [\"clientHeight\", height]] as const) {\n replace(HTMLElement.prototype, prop, { get: () => value });\n }\n\n return () => {\n for (const undo of restore.reverse()) undo();\n };\n}\n","import type { Phase } from \"../components/async-button\";\n\n// Assertions for the rules a screen keeps, read from what the components draw rather than from\n// their class names (strata-react issue #48, from the Tubes Library test, which matched\n// `bg-primary`). `Button` marks its variant (`data-variant`), so \"one filled button per view\"\n// (ux-research patterns.md §2, with the BulkBar hand-over: while rows are chosen the bulk action is\n// the filled one) is a check a screen test can make after every interaction. `AsyncButton` marks\n// its phase (`data-phase`), because it keeps every phase's label in the DOM to hold its width, so\n// its text reads \"AddAdding…AddedTry again\" and only the phase says which one shows.\n\n/** Whether an element is out of the view: hidden, inert or aria-hidden, itself or by an ancestor. */\nfunction outOfView(el: Element) {\n return Boolean(el.closest('[hidden], [inert], [aria-hidden=\"true\"]'));\n}\n\n/** An element's name as a person reads it: its `aria-label`, else its text without the parts hidden from screen readers. */\nfunction nameOf(el: Element): string {\n const label = el.getAttribute(\"aria-label\");\n if (label) return label;\n const walk = (node: Node): string =>\n node.nodeType === 3\n ? (node.textContent ?? \"\")\n : node instanceof Element && node.getAttribute(\"aria-hidden\") === \"true\"\n ? \"\"\n : [...node.childNodes].map(walk).join(\"\");\n return walk(el).replace(/\\s+/g, \" \").trim();\n}\n\n/** The filled (`variant=\"default\"`) buttons and links in `container` (default the whole document) that are in view. */\nexport function filledButtons(container: ParentNode = document.body): HTMLElement[] {\n return [...container.querySelectorAll<HTMLElement>('[data-variant=\"default\"]')].filter((el) => !outOfView(el));\n}\n\n/** Throws unless `container` (default the whole document) has exactly one filled button in view; the message names the ones found. */\nexport function expectOneFilledButton(container: ParentNode = document.body): HTMLElement {\n const found = filledButtons(container);\n if (found.length === 1) return found[0];\n const names = found.map((el) => `\"${nameOf(el)}\"`).join(\", \");\n throw new Error(`Expected one filled button in the view, found ${found.length}${names ? `: ${names}` : \"\"}.`);\n}\n\n/** The phase an `AsyncButton` is in (`idle`, `pending`, `done`, `error`), from the button or any element inside it. */\nexport function asyncButtonPhase(el: Element): Phase {\n const phase = el.closest(\"[data-phase]\")?.getAttribute(\"data-phase\");\n if (phase === \"idle\" || phase === \"pending\" || phase === \"done\" || phase === \"error\") return phase;\n throw new Error(`Not an AsyncButton: ${el.outerHTML.slice(0, 120)}`);\n}\n","// jsdom has no IntersectionObserver and does no layout, so nothing a component observes ever comes\n// into view in a unit test. Infinite lists load the next page when a sentinel at the end of the\n// list intersects, and before this helper every app wrote its own firable fake to test that\n// (strata-react issue #12, from strata-listory). This one stands in for the global, records what\n// each observer watches, and lets the test say when something scrolls into view: `scrollToEnd()`\n// for the common case, `intersect(el)` for one element. Entries are delivered inside `act` so the\n// state updates they cause are flushed before the next assertion, as a real scroll would be.\n\nimport { act } from \"@testing-library/react\";\nimport { box } from \"./layout\";\n\n/** One stand-in observer: its callback, options and the elements it currently watches. */\nexport interface FakeObserver {\n readonly callback: IntersectionObserverCallback;\n readonly options: IntersectionObserverInit;\n readonly targets: ReadonlySet<Element>;\n}\n\n/** The controls `installFakeIntersectionObserver` returns. */\nexport interface FakeIntersectionObserverControls {\n /** Every observer created since install, including disconnected ones (their target sets are empty). */\n readonly observers: readonly FakeObserver[];\n /** Report `el` to every observer watching it: in view by default, or out of view with `false`. Returns how many observers were told. */\n intersect(el: Element, isIntersecting?: boolean): number;\n /** Report every watched element as in view, as if the person scrolled to the end of the list. Returns how many elements were reported. */\n scrollToEnd(): number;\n /** Put back whatever `IntersectionObserver` was there before install. */\n uninstall(): void;\n}\n\nfunction entryFor(target: Element, isIntersecting: boolean): IntersectionObserverEntry {\n const rect = target.getBoundingClientRect();\n return {\n target,\n isIntersecting,\n intersectionRatio: isIntersecting ? 1 : 0,\n boundingClientRect: rect,\n intersectionRect: isIntersecting ? rect : box(0, 0, 0, 0),\n rootBounds: null,\n time: performance.now(),\n };\n}\n\n/**\n * Replace `globalThis.IntersectionObserver` with a stand-in the test fires by hand. Call it in\n * `beforeEach` and call `uninstall()` in `afterEach`.\n *\n * @example\n * let io: FakeIntersectionObserverControls;\n * beforeEach(() => { io = installFakeIntersectionObserver(); });\n * afterEach(() => io.uninstall());\n *\n * it(\"loads the next page at the end of the list\", async () => {\n * renderWithStrata(<Pieces />);\n * await screen.findByRole(\"list\", { name: \"Pieces\" });\n * io.scrollToEnd();\n * expect(await screen.findByText(\"Celadon bowl\")).toBeInTheDocument();\n * });\n */\nexport function installFakeIntersectionObserver(): FakeIntersectionObserverControls {\n const previous = Object.getOwnPropertyDescriptor(globalThis, \"IntersectionObserver\");\n const observers: (FakeObserver & { targets: Set<Element>; self: IntersectionObserver })[] = [];\n\n class FakeIntersectionObserver implements IntersectionObserver {\n readonly root: Element | Document | null;\n readonly rootMargin: string;\n readonly thresholds: readonly number[];\n readonly scrollMargin = \"0px\";\n private readonly record: (typeof observers)[number];\n\n constructor(callback: IntersectionObserverCallback, options: IntersectionObserverInit = {}) {\n this.root = options.root ?? null;\n this.rootMargin = options.rootMargin ?? \"0px\";\n const threshold = options.threshold ?? 0;\n this.thresholds = Array.isArray(threshold) ? threshold : [threshold];\n this.record = { callback, options, targets: new Set(), self: this };\n observers.push(this.record);\n }\n observe(target: Element) {\n this.record.targets.add(target);\n }\n unobserve(target: Element) {\n this.record.targets.delete(target);\n }\n disconnect() {\n this.record.targets.clear();\n }\n takeRecords(): IntersectionObserverEntry[] {\n return [];\n }\n }\n\n Object.defineProperty(globalThis, \"IntersectionObserver\", {\n configurable: true,\n writable: true,\n value: FakeIntersectionObserver,\n });\n\n const deliver = (observer: (typeof observers)[number], targets: readonly Element[], isIntersecting: boolean) => {\n act(() => observer.callback(targets.map((t) => entryFor(t, isIntersecting)), observer.self));\n };\n\n return {\n observers,\n intersect(el, isIntersecting = true) {\n const watching = observers.filter((o) => o.targets.has(el));\n for (const o of watching) deliver(o, [el], isIntersecting);\n return watching.length;\n },\n scrollToEnd() {\n // Snapshot every observer's targets before any callback runs: a callback that loads more\n // may observe a new sentinel, on this observer or another, which the person has not\n // scrolled to yet.\n const batches = observers.map((o) => [o, [...o.targets]] as const).filter(([, targets]) => targets.length > 0);\n for (const [o, targets] of batches) deliver(o, targets, true);\n return batches.reduce((n, [, targets]) => n + targets.length, 0);\n },\n uninstall() {\n if (previous) Object.defineProperty(globalThis, \"IntersectionObserver\", previous);\n else delete (globalThis as { IntersectionObserver?: unknown }).IntersectionObserver;\n },\n };\n}\n","/**\n * Test helpers: render a component, or a whole route tree, inside a router and a query client, as\n * a Strata app runs it,\n * and fill the gaps jsdom leaves (layout, ResizeObserver, IntersectionObserver). Use with MSW for\n * the network, never module mocks.\n *\n * @module strata-react/testing\n */\nimport * as React from \"react\";\nimport { act, render, type RenderOptions } from \"@testing-library/react\";\nimport { MemoryRouter, RouterProvider, createMemoryRouter, type RouteObject, type To } from \"react-router\";\nimport { QueryClient } from \"@tanstack/react-query\";\nimport { StrataQueryProvider, createQueryClient } from \"../query\";\nimport { ThemeProvider, type ColorSchemePreference } from \"../components/theme\";\n\nexport { installLayoutShims, type LayoutBox } from \"./layout\";\nexport { filledButtons, expectOneFilledButton, asyncButtonPhase } from \"./buttons\";\nexport {\n installFakeIntersectionObserver,\n type FakeIntersectionObserverControls,\n type FakeObserver,\n} from \"./intersection-observer\";\n\n// Render a component the way a Strata app runs it: inside a router and a query client. Tests use\n// MSW for the network (see CLAUDE.md), never module mocks, so the real fetch/query/DataView path\n// runs. Each call gets a fresh QueryClient with retries off, so a test that serves a 500 sees the\n// error at once instead of after the retry delay. It also runs inside a ThemeProvider with\n// storage off, so `useColorScheme` works and a test can render the dark scheme with\n// `colorScheme: \"dark\"` without touching localStorage or leaking state into the next test.\n\n/** A query client for tests: no retries, and nothing goes stale or is collected mid-test. */\nexport function createTestQueryClient() {\n return createQueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity, gcTime: Infinity } } });\n}\n\n/** The options `renderWithStrata` and `renderRoutes` share, beside Testing Library's own. */\nexport type StrataRenderOptions = Omit<RenderOptions, \"wrapper\"> & {\n /** The URL the test starts at, with its search and hash (`/bookings?sort=pieces.desc`). Defaults to `/`. */\n route?: string;\n /** The query client; a fresh `createTestQueryClient()` when left out. */\n client?: QueryClient;\n /** The colour scheme to render; `light` when left out. */\n colorScheme?: ColorSchemePreference;\n};\n\n// The providers every Strata app has above its router, in the order an app nests them.\nfunction StrataProviders({\n client,\n colorScheme,\n children,\n}: {\n client: QueryClient;\n colorScheme: ColorSchemePreference;\n children: React.ReactNode;\n}) {\n return (\n <ThemeProvider defaultPreference={colorScheme} storageKey={null}>\n <StrataQueryProvider client={client}>{children}</StrataQueryProvider>\n </ThemeProvider>\n );\n}\n\n/** Testing Library's `render` inside `StrataQueryProvider` and a `MemoryRouter` at `route`. */\nexport function renderWithStrata(\n ui: React.ReactElement,\n { route = \"/\", client = createTestQueryClient(), colorScheme = \"light\", ...options }: StrataRenderOptions = {},\n) {\n const Wrapper = ({ children }: { children: React.ReactNode }) => (\n <StrataProviders client={client} colorScheme={colorScheme}>\n <MemoryRouter initialEntries={[route]}>{children}</MemoryRouter>\n </StrataProviders>\n );\n return { client, ...render(ui, { wrapper: Wrapper, ...options }) };\n}\n\n// Render an app's own route tree: its layout routes and <Outlet />s, index routes, redirects\n// (<Navigate /> or a loader's redirect()), loaders, actions and error elements. Those only run in\n// a data router, which <MemoryRouter> is not, so renderWithStrata cannot show them; this builds\n// the memory twin of the app's createBrowserRouter from the same RouteObject[] the app exports,\n// so the test and the app cannot drift. The providers and options are renderWithStrata's.\n// `basename` is the app's own (the kiln app runs under /kiln), and `route` is the full URL,\n// basename included, as the browser would show it. The router is returned so a test can assert\n// where a redirect landed (`router.state.location`), and `navigate` moves it inside act().\n\n/** `renderRoutes`'s options: `renderWithStrata`'s, plus the app's `basename`. */\nexport type RenderRoutesOptions = StrataRenderOptions & {\n /** The base path the app is served under, as passed to `createBrowserRouter`. */\n basename?: string;\n};\n\n/** Testing Library's `render` of an app's route tree in a memory data router at `route`, with Strata's providers. */\nexport function renderRoutes(\n routes: RouteObject[],\n {\n route,\n basename,\n client = createTestQueryClient(),\n colorScheme = \"light\",\n ...options\n }: RenderRoutesOptions = {},\n) {\n const router = createMemoryRouter(routes, { initialEntries: [route ?? basename ?? \"/\"], basename });\n const result = render(\n <StrataProviders client={client} colorScheme={colorScheme}>\n <RouterProvider router={router} />\n </StrataProviders>,\n options,\n );\n const navigate = (to: To | number) =>\n act(async () => {\n await (typeof to === \"number\" ? router.navigate(to) : router.navigate(to));\n });\n return { client, router, navigate, ...result };\n}\n"],"mappings":";;;;;;;;AAQA,SAAgB,IAAI,GAAW,GAAW,OAAe,QAAyB;CAChF,OAAO;EAAE;EAAG;EAAG;EAAO;EAAQ,KAAK;EAAG,MAAM;EAAG,OAAO,IAAI;EAAO,QAAQ,IAAI;EAAQ,SAAS;GAAE,OAAO;EAAM;CAAE;AACjH;;;;;;AAaA,SAAgB,mBAAmB,EAAE,QAAQ,KAAK,SAAS,QAA4B,CAAC,GAAe;CACrG,MAAM,UAA0B,CAAC;CACjC,MAAM,WAAW,QAAgB,MAAc,eAAmC;EAChF,MAAM,SAAS,OAAO,yBAAyB,QAAQ,IAAI;EAC3D,OAAO,eAAe,QAAQ,MAAM;GAAE,cAAc;GAAM,GAAG;EAAW,CAAC;EACzE,QAAQ,WAAW;GACjB,IAAI,QAAQ,OAAO,eAAe,QAAQ,MAAM,MAAM;QACjD,OA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