@krizaka/page-audit 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,41 @@
1
- # Temporary Holding Version
1
+ # @krizaka/page-audit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The page audit of every Krizaka app, in one place (ADR-013: one source per rule set). It measures a rendered page in a real browser:
4
+ horizontal overflow, a card out of its panel, sections covering each other, a column cut by a clipping ancestor, top chrome that
5
+ overlaps, content cut inside its box, a token wrapped per character, unnamed buttons, empty headings. Closed `<details>`, `aria-hidden`
6
+ layers, scrollers and fixed elements are not counted. Library code, not UI: it lives in krizaka-ts.
7
+
8
+ ```bash
9
+ npm i -D @krizaka/page-audit playwright-core
10
+ npx krizaka-page-audit --self-test # proves it on its own fixtures
11
+ npx krizaka-page-audit --base http://localhost:3000 --routes /en,/fr --widths 360,390,1440 --themes dark,light
12
+ ```
13
+
14
+ ```js
15
+ import { auditRoutes, auditContext, loadSettled, resizeSettled, auditPage, problemsOf } from "@krizaka/page-audit";
16
+ const problems = await auditRoutes({ base, routes: ["/en", "/fr"], checks: { h1: true } }); // [] when fine
17
+ ```
18
+
19
+ `auditContext` / `loadSettled` / `resizeSettled` open a context with reduced motion and no View Transition, and wait for none to run
20
+ before anything is measured (yomizaka#354). `prepare(page, route)` signs in or seeds; `launch` gives your own browser.
21
+
22
+ ## The dev-preview crawls, in one audit (0.3)
23
+
24
+ Opt-in through `checks` (nothing changes for a repo that does not ask): `status` (HTTP 4xx/5xx or no response), `emptyMain`, `frame`
25
+ (the signed-in frame, `[data-app-frame-slot]`, forces a scroll), `minAction` (a button-styled action under N px), `boxes` (a landmark
26
+ wider than its box), `landmarks` (`"public"` one footer naming Krizaka and a nav, `"app"`, `"auth"`), `pictures`, `emptyControls`,
27
+ `hardColors`. Console noise the app tolerates: `ignoreConsole: [/…/]` (`[]` counts every error); `attempts` retries a route.
28
+
29
+ ```js
30
+ const routes = await routesFromSitemap(base, { first: ["/", "/docs"], limit: 14 }); // a crawl as the route source (null: nothing answers)
31
+ await auditRoutes({
32
+ base, routes: [...routes, { url: "/login", chrome: "auth" }, { url: "/chat", session: true, chrome: "app" }],
33
+ widths: [{ width: 1440, height: 900 }, { width: 390, height: 844 }],
34
+ session: { storageState }, // or { signIn(context, { base, theme }) {…}, routes: async (page) => […] } for pages found once signed in
35
+ a11y: { app: "my-app", baseline: "a11y-baseline.json", widths: [390, 1440], session: { app: "my-app-app", baseline: "a11y-baseline.app.json" } },
36
+ checks: { status: true, emptyMain: true, minAction: 36, landmarks: "public", frame: true },
37
+ });
38
+ ```
39
+
40
+ `a11y` runs axe through `@krizaka/a11y-audit` (an optional peer) and ratchets with the repo's own baseline file; `--a11y-update` and
41
+ `--a11y-init` work as there. The CLI takes `--sitemap`, `--status`, `--empty-main`, `--min-action`, `--a11y app:baseline.json`.
package/package.json CHANGED
@@ -1,6 +1,74 @@
1
1
  {
2
2
  "name": "@krizaka/page-audit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.0",
4
+ "description": "The page audit of every Krizaka app, in one place: HTTP status, empty main, horizontal overflow, a card out of its panel, sections covering each other, a column cut off, top chrome overlaps, unnamed buttons, empty headings. Runs in a real browser (Playwright) over a route list, viewports and themes, with View Transitions neutralised and a self-test on its own fixtures.",
5
+ "keywords": [
6
+ "krizaka",
7
+ "audit",
8
+ "overflow",
9
+ "layout",
10
+ "playwright"
11
+ ],
12
+ "homepage": "https://ts.krizaka.com/page-audit",
13
+ "bugs": "https://github.com/krizaka/krizaka-ts/issues",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/krizaka/krizaka-ts.git",
17
+ "directory": "packages/page-audit"
18
+ },
19
+ "license": "Apache-2.0",
20
+ "author": "Krizaka (https://www.krizaka.com)",
21
+ "type": "module",
22
+ "main": "./src/index.mjs",
23
+ "types": "./src/index.d.ts",
24
+ "bin": {
25
+ "krizaka-page-audit": "./src/cli.mjs"
26
+ },
27
+ "exports": {
28
+ ".": {
29
+ "types": "./src/index.d.ts",
30
+ "import": "./src/index.mjs"
31
+ },
32
+ "./settle": {
33
+ "types": "./src/index.d.ts",
34
+ "import": "./src/settle.mjs"
35
+ },
36
+ "./fixtures": "./src/fixtures.mjs",
37
+ "./package.json": "./package.json"
38
+ },
39
+ "files": [
40
+ "src",
41
+ "README.md",
42
+ "LICENSE"
43
+ ],
44
+ "sideEffects": false,
45
+ "peerDependencies": {
46
+ "@krizaka/a11y-audit": ">=0.2.0",
47
+ "playwright-core": ">=1.40"
48
+ },
49
+ "peerDependenciesMeta": {
50
+ "@krizaka/a11y-audit": {
51
+ "optional": true
52
+ }
53
+ },
54
+ "devDependencies": {
55
+ "@krizaka/a11y-audit": "0.2.0",
56
+ "@types/node": "^22.10.0",
57
+ "eslint": "^9.39.0",
58
+ "playwright-core": "^1.55.0",
59
+ "vitest": "^4.1.11",
60
+ "@krizaka/config": "^0.14.0"
61
+ },
62
+ "engines": {
63
+ "node": ">=22"
64
+ },
65
+ "publishConfig": {
66
+ "access": "public"
67
+ },
68
+ "scripts": {
69
+ "lint": "eslint . --max-warnings 0",
70
+ "typecheck": "node --check src/index.mjs",
71
+ "test": "vitest run",
72
+ "check": "pnpm run lint && pnpm run test"
73
+ }
6
74
  }
package/src/cli.mjs ADDED
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+ // krizaka-page-audit --base http://localhost:3000 --routes /en,/fr [--widths 360,390,1440] [--themes dark,light]
3
+ // [--theme-key kz-theme] [--h1] [--shots dir]
4
+ // [--sitemap [--limit 14]] [--status] [--empty-main] [--min-action 36] [--a11y app:baseline.json] | krizaka-page-audit --self-test
5
+ import { auditRoutes, routesFromSitemap, THEMES, WIDTHS } from "./run.mjs";
6
+ import { selfTest } from "./self-test.mjs";
7
+
8
+ const arg = (name, fallback) => {
9
+ const i = process.argv.indexOf(`--${name}`);
10
+ return i >= 0 ? process.argv[i + 1] : fallback;
11
+ };
12
+ const list = (value, fallback) => (value ? value.split(",").filter(Boolean) : fallback);
13
+
14
+ if (process.argv.includes("--self-test")) {
15
+ const failures = await selfTest();
16
+ if (failures.length) {
17
+ console.error(`page-audit self-test failed:\n ${failures.join("\n ")}`);
18
+ process.exit(1);
19
+ }
20
+ console.log("page-audit self-test: every broken layout seen, the fine ones clean");
21
+ } else {
22
+ const base = arg("base", "http://localhost:3000");
23
+ const has = (name) => process.argv.includes(`--${name}`);
24
+ const routes = has("sitemap") ? await routesFromSitemap(base, { first: list(arg("routes"), ["/"]), limit: Number(arg("limit", 14)) }) : list(arg("routes"), ["/"]);
25
+ if (!routes) {
26
+ console.error(`Nothing answers at ${base}/sitemap.xml`);
27
+ process.exit(2);
28
+ }
29
+ const [app, baseline] = (arg("a11y") ?? "").split(":");
30
+ const widths = list(arg("widths"), WIDTHS).map(Number);
31
+ const themes = list(arg("themes"), THEMES);
32
+ const problems = await auditRoutes({ base, routes, widths, themes, themeKey: arg("theme-key", "kz-theme"), shots: arg("shots"), a11y: baseline ? { app, baseline } : undefined, checks: { h1: has("h1"), status: has("status"), emptyMain: has("empty-main"), minAction: arg("min-action") ? Number(arg("min-action")) : undefined } });
33
+ if (problems.length) {
34
+ console.error(`${problems.length} page problem(s):\n ${problems.join("\n ")}`);
35
+ process.exit(1);
36
+ }
37
+ console.log(`no page problem: ${routes.length} routes x ${widths.length} widths x ${themes.length} themes`);
38
+ }
@@ -0,0 +1,45 @@
1
+ // Small pages that reproduce what the layout audit must catch (yomizaka#435) and one that is fine, for `check-page-audit.mjs`:
2
+ // the guard is proven on its own fixtures before it is trusted on the app.
3
+
4
+ const page = (body, css = "") => `<!doctype html><html><head><meta charset="utf-8"><style>*{box-sizing:border-box}body{margin:0;font:16px sans-serif}${css}</style></head><body><main>${body}</main></body></html>`;
5
+
6
+ /** The binder as it was: the open folder's card is as tall as its grid row (a fixed height) and runs over the next section. */
7
+ export const CARD_OVER_NEXT = page(
8
+ `<section data-testid="binder" style="height:200px"><h2>Le classeur</h2><div data-testid="collection-card" style="height:500px">Mes documents · 0 fichiers</div></section><section data-testid="latest-checks"><h2>Dernières vérifications</h2></section>`,
9
+ "section{display:block}",
10
+ );
11
+ /** Two sections laid out on top of each other. */
12
+ export const SECTIONS_OVERLAP = page(`<section data-testid="a" style="height:100px">A</section><section data-testid="b" style="margin-top:-60px;height:100px;position:relative">B</section>`);
13
+ /** A two-column layout whose wrapper clips the right column. */
14
+ export const COLUMN_CUT = page(
15
+ `<div style="overflow:hidden;width:600px"><div style="display:grid;grid-template-columns:400px 400px"><section data-testid="main">Main</section><aside data-testid="activity"><section data-testid="activity-figures">Activité</section></aside></div></div>`,
16
+ );
17
+ /** What it should be: the card follows its content, the columns fit, a wide table scrolls inside its own scroller. */
18
+ export const FINE = page(
19
+ `<div style="display:grid;grid-template-columns:minmax(0,1fr) 320px;gap:16px"><section data-testid="binder"><h2>Le classeur</h2><div data-testid="collection-card">Mes documents · 0 fichiers</div></section><aside><section data-testid="activity">Activité</section></aside></div><section data-testid="latest-checks"><h2>Dernières vérifications</h2><div style="overflow:auto;width:300px"><div style="width:900px">table</div></div></section>`,
20
+ );
21
+ /** Not drawn, so not a problem: a chart's text version in a visually hidden wrapper, and the content of a folded `<details>` (the browser still gives both a box). */
22
+ export const HIDDEN_CONTENT = page(
23
+ `<section data-testid="activity" style="height:120px"><h2>Activité</h2><div style="position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0)"><table><tbody>${"<tr><td>21 oct.</td><td>7</td></tr>".repeat(40)}</tbody></table></div></section><section data-testid="report"><details><summary>Détails</summary><div style="height:400px">Texte du rapport</div></details></section>`,
24
+ );
25
+
26
+ /** The report tab: a section inside a folded details (the closing note) beside sections it must not be taken to cover. */
27
+ export const FOLDED_SECTION = page(
28
+ `<div style="display:flex;flex-direction:column"><section data-testid="facts" style="height:80px">Faits</section><details><summary>Détails</summary><section data-testid="closing-note" style="padding:16px">Ce que nous avons vérifié</section></details><section data-testid="other" style="height:80px">Autres</section></div>`,
29
+ );
30
+
31
+ /** A page whose `<main>` draws nothing. */
32
+ export const EMPTY_MAIN = page("");
33
+ /** The signed-in frame asks 1000 px of a 700 px screen under a 60 px notice (akinaza#444). */
34
+ export const FRAME_FORCES_SCROLL = page(`<div style="height:60px">notice</div><div data-app-frame-slot><div style="min-height:1000px">shell</div></div>`);
35
+ /** The same frame, sized to what is left of the screen. */
36
+ export const FRAME_FITS = page(`<div style="height:60px">notice</div><div data-app-frame-slot><div style="min-height:500px">shell</div></div>`);
37
+ /** A button-styled action 24 px tall, under the 36 px tap target. */
38
+ export const SMALL_ACTION = page(`<a class="kz-button" href="/" style="display:block;height:24px;width:120px">Go</a>`);
39
+ /** A landmark whose content is wider than its box. */
40
+ export const BOX_TOO_WIDE = page(`<aside style="width:200px"><div style="width:500px">wide</div></aside>`);
41
+ /** Broken picture, a tile that draws nothing, an inline hard-coded colour. */
42
+ export const BROKEN_PARTS = page(`<img src="data:image/png;base64,AAAA" width="40" height="40" alt=""><a href="/" style="display:block;width:60px;height:60px"></a><p style="color:#ff0000">x</p>`);
43
+ /** Chrome that fits the family: one footer naming Krizaka, a nav. */
44
+ export const CHROME_FINE = `<!doctype html><html><body><nav>n</nav><main><p>Hello</p></main><footer>A Krizaka product</footer></body></html>`;
45
+ export const CHROME_BAD = `<!doctype html><html><body><main><p>Hello</p></main><footer>one</footer><footer>two</footer></body></html>`;
package/src/index.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ /* Minimal structural types: playwright-core is a peer dependency, not imported here. */
2
+ export type Page = Record<string, unknown>;
3
+ export type BrowserContext = Record<string, unknown>;
4
+ export type Browser = { newContext(o?: object): Promise<BrowserContext>; close(): Promise<void> };
5
+ export const auditPage: string;
6
+ export type Chrome = "public" | "app" | "auth";
7
+ export interface ProblemChecks {
8
+ errors?: string[]; h1?: boolean; headerAction?: boolean; fileLabels?: boolean;
9
+ /** HTTP status of the load (`null`: no response); a 4xx/5xx is a problem. */
10
+ status?: number | null;
11
+ emptyMain?: boolean; frame?: boolean; minAction?: number; boxes?: boolean; landmarks?: Chrome; pictures?: boolean; emptyControls?: boolean; hardColors?: boolean;
12
+ }
13
+ export function problemsOf(where: string, result: Record<string, unknown>, checks?: ProblemChecks): string[];
14
+ export function auditOptions<T extends object>(options?: T): T & { reducedMotion: "reduce" };
15
+ export function withoutViewTransitions(): void;
16
+ export function auditContext(browser: { newContext(o?: object): Promise<BrowserContext> }, options?: object): Promise<BrowserContext>;
17
+ export function settled(page: Page): Promise<unknown>;
18
+ export function loadSettled(page: Page, url: string, options?: object): Promise<BrowserContext>;
19
+ export function resizeSettled(page: Page, size: { width: number; height: number }): Promise<void>;
20
+ export const WIDTHS: number[];
21
+ export const THEMES: string[];
22
+ export function isPageError(message: { type(): string; text(): string }, ignore?: RegExp[]): boolean;
23
+ export function routesFromSitemap(base: string, options?: { first?: string[]; limit?: number; fetcher?: typeof fetch }): Promise<string[] | null>;
24
+ export interface RouteSpec { url: string; name?: string; chrome?: Chrome; session?: boolean }
25
+ export interface A11yOptions { app: string; baseline: string; widths?: number[]; log?: (line: string) => void; session?: { app: string; baseline: string } }
26
+ export interface SessionOptions {
27
+ storageState?: object | string;
28
+ signIn?: (context: BrowserContext, o: { base: string; theme: string; page: Page }) => Promise<void>;
29
+ routes?: (page: Page, o: { base: string; theme: string }) => Promise<Array<string | RouteSpec>>;
30
+ }
31
+ export interface AuditRoutesOptions {
32
+ base: string; routes: Array<string | RouteSpec>; widths?: Array<number | { width: number; height?: number }>; themes?: string[]; height?: number; themeKey?: string; shots?: string; settleMs?: number;
33
+ ignoreConsole?: RegExp[]; attempts?: number; a11y?: A11yOptions; session?: SessionOptions;
34
+ checks?: Omit<ProblemChecks, "errors">; prepare?: (page: Page, route: string) => Promise<void>; launch?: () => Promise<BrowserContext>;
35
+ }
36
+ export function auditRoutes(options: AuditRoutesOptions): Promise<string[]>;
37
+ export function selfTest(options?: { launch?: () => Promise<BrowserContext> }): Promise<string[]>;
package/src/index.mjs ADDED
@@ -0,0 +1,4 @@
1
+ export { auditPage, problemsOf } from "./page-audit.mjs";
2
+ export { auditRoutes, isPageError, routesFromSitemap, THEMES, WIDTHS } from "./run.mjs";
3
+ export { selfTest } from "./self-test.mjs";
4
+ export { auditContext, auditOptions, loadSettled, resizeSettled,settled, withoutViewTransitions } from "./settle.mjs";
@@ -0,0 +1,404 @@
1
+ // What a rendered page is measured on, in a real browser (Playwright `page.evaluate(auditPage)`), and what counts as a problem.
2
+ // Shared by the responsive guard of the public pages (check-overflow.mjs) and the signed-in pages' check (check-app-pages.mjs).
3
+
4
+ // The probes below run in the page, so each uses only the browser's globals and the other probes (all of them are serialised together
5
+ // into `auditPage`). They are small on purpose: one measure each, proven on its own fixture (check-page-audit.mjs).
6
+
7
+ const ARIA_HIDDEN = '[aria-hidden="true"]';
8
+ const className = (el, n) => String(el.className).split(" ").filter(Boolean).slice(0, n).join(".");
9
+ const nameOf = (el) => {
10
+ const id = el.dataset?.testid;
11
+ return el.tagName.toLowerCase() + (id ? "[" + id + "]" : "") + "." + className(el, 2);
12
+ };
13
+ const scrolls = (el) => ["auto", "scroll"].includes(getComputedStyle(el).overflowY) || ["auto", "scroll"].includes(getComputedStyle(el).overflowX);
14
+ const meets = (ra, rb) => Math.min(ra.right, rb.right) - Math.max(ra.left, rb.left) > 2 && Math.min(ra.bottom, rb.bottom) - Math.max(ra.top, rb.top) > 2;
15
+ const apart = (a, b) => !a.contains(b) && !b.contains(a);
16
+
17
+ /** An element that pokes out only matters when nothing clips it: decorative layers (aria-hidden) and anything inside a clipping or scrolling ancestor are meant to extend. */
18
+ function clipped(el) {
19
+ for (let n = el; n && n !== document.body; n = n.parentElement) {
20
+ if (n.getAttribute("aria-hidden") === "true" || n.hasAttribute("inert")) return true;
21
+ if (n !== el && ["hidden", "clip", "auto", "scroll"].includes(getComputedStyle(n).overflowX)) return true;
22
+ }
23
+ return false;
24
+ }
25
+
26
+ function wideOf(doc) {
27
+ return [...document.querySelectorAll("body *")]
28
+ .filter((el) => {
29
+ const r = el.getBoundingClientRect();
30
+ return r.width > 0 && getComputedStyle(el).visibility !== "hidden" && (r.right > doc.clientWidth + 1 || r.left < -1) && !clipped(el);
31
+ })
32
+ .slice(0, 3)
33
+ .map((el) => `${el.tagName.toLowerCase()}.${String(el.className).split(" ").slice(0, 3).join(".")}`);
34
+ }
35
+
36
+ /** A button's accessible name: its text, aria-label, aria-labelledby, title — or a <label for> pointing at it (a checkbox, a switch). */
37
+ function named(b) {
38
+ const labelled = !!b.id && !!document.querySelector(`label[for="${CSS.escape(b.id)}"]`);
39
+ return !!((b.textContent || "").trim() || b.getAttribute("aria-label") || b.getAttribute("aria-labelledby") || b.title || labelled);
40
+ }
41
+
42
+ function unnamedOf() {
43
+ const unnamed = [...document.querySelectorAll("button")].filter((b) => !named(b));
44
+ return { unnamedButtons: unnamed.length, unnamedSamples: unnamed.slice(0, 2).map((b) => b.outerHTML.slice(0, 160).replace(/\s+/g, " ")) };
45
+ }
46
+
47
+ function headerActionOf(doc) {
48
+ const action = document.querySelector('[data-testid="header-check"]');
49
+ if (!action) return null;
50
+ const box = action.getBoundingClientRect();
51
+ const visible = box.width > 0 && box.height > 0 && box.left >= 0 && box.right <= doc.clientWidth + 1 && box.top >= 0;
52
+ return { visible, named: !!(action.getAttribute("aria-label") || action.textContent || "").trim() };
53
+ }
54
+
55
+ /** What a folded `<details>` holds is not drawn, though the browser still gives it a box (its summary is). */
56
+ function folded(el) {
57
+ return !!el.closest("details:not([open])") && !el.closest("summary");
58
+ }
59
+
60
+ /** Whether an ancestor between the element and the panel keeps what runs out of it: a scroller, or a visually hidden wrapper (`sr-only`: a 1 px clipped box, the text version of a chart). */
61
+ function keptBetween(el, panel) {
62
+ for (let n = el.parentElement; n && n !== panel; n = n.parentElement) {
63
+ if (scrolls(n)) return true;
64
+ const nb = n.getBoundingClientRect();
65
+ if ((nb.width <= 2 || nb.height <= 2) && getComputedStyle(n).overflowY !== "visible") return true;
66
+ }
67
+ return false;
68
+ }
69
+
70
+ function notDrawn(el, r) {
71
+ return r.width === 0 || r.height === 0 || getComputedStyle(el).position === "fixed" || !!el.closest(ARIA_HIDDEN) || !!el.closest("[data-radix-popper-content-wrapper]") || folded(el);
72
+ }
73
+
74
+ function runsOut(el, panel, box) {
75
+ const r = el.getBoundingClientRect();
76
+ if (notDrawn(el, r) || keptBetween(el, panel)) return false;
77
+ return r.bottom > box.bottom + 1.5 || r.right > box.right + 1.5;
78
+ }
79
+
80
+ /** `overflowing`: a panel's content that runs out of the panel (a card taller than its panel, over the next section). `spill` holds those elements. */
81
+ function spillOf(panels) {
82
+ const overflowing = [];
83
+ const spill = [];
84
+ for (const panel of panels) {
85
+ if (scrolls(panel) || ["hidden", "clip"].includes(getComputedStyle(panel).overflowY)) continue;
86
+ const box = panel.getBoundingClientRect();
87
+ const out = [...panel.querySelectorAll("*")].find((el) => runsOut(el, panel, box));
88
+ if (!out) continue;
89
+ overflowing.push(`${nameOf(out)} out of ${nameOf(panel)}`);
90
+ spill.push(out);
91
+ }
92
+ return { overflowing, spill };
93
+ }
94
+
95
+ /** `overlaps`: two sections that are not nested and cover each other, or what ran out of its panel and lands on another section (the card covering « Dernières vérifications »). */
96
+ function overlapsOf(panels, spill) {
97
+ const overlaps = [];
98
+ for (const el of spill) {
99
+ for (const other of panels) if (apart(el, other) && meets(el.getBoundingClientRect(), other.getBoundingClientRect())) overlaps.push(`${nameOf(el)} over ${nameOf(other)}`);
100
+ }
101
+ panels.forEach((a, i) => {
102
+ for (const b of panels.slice(i + 1)) if (apart(a, b) && meets(a.getBoundingClientRect(), b.getBoundingClientRect())) overlaps.push(`${nameOf(a)} over ${nameOf(b)}`);
103
+ });
104
+ return overlaps;
105
+ }
106
+
107
+ /** The clipping ancestor that cuts an element sideways (overflow hidden / clip), or null; a scroller stops the search (it keeps what runs out of it). */
108
+ function cutBy(el, r) {
109
+ for (let n = el.parentElement; n && n !== document.documentElement; n = n.parentElement) {
110
+ const style = getComputedStyle(n);
111
+ if (["auto", "scroll"].includes(style.overflowX)) return null;
112
+ if (!["hidden", "clip"].includes(style.overflowX)) continue;
113
+ const c = n.getBoundingClientRect();
114
+ return r.right > c.right + 2 || r.left < c.left - 2 ? n : null;
115
+ }
116
+ return null;
117
+ }
118
+
119
+ /** `cutColumns`: a section or a column cut by a clipping ancestor, which hides part of its content. */
120
+ function cutColumnsOf() {
121
+ const cut = [];
122
+ for (const el of document.querySelectorAll("main section, main aside, main [data-testid], [data-panel]")) {
123
+ const r = el.getBoundingClientRect();
124
+ if (el.closest(ARIA_HIDDEN) || r.width === 0 || r.height === 0) continue;
125
+ const by = cutBy(el, r);
126
+ if (by) cut.push(`${nameOf(el)} cut by ${nameOf(by)}`);
127
+ }
128
+ return [...new Set(cut)].slice(0, 3);
129
+ }
130
+
131
+ /** The top chrome never overlaps (yomizaka#449): the in-flow blocks above the page (`[data-top-chrome]`, e.g. the development-version notice) and a bar that is fixed or sticky at the top of the viewport. Two of them that share pixels hide one another. */
132
+ function topBoxOf(el) {
133
+ return el.getBoundingClientRect().height === 0 && el.firstElementChild ? el.firstElementChild : el;
134
+ }
135
+
136
+ /** A bar is whatever is fixed or sticky across the top of the viewport (a wrapper, whatever its tag): wide, short, near the top. The site's bar stands in a sticky wrapper of zero height, so what it holds is measured. */
137
+ function isTopBar(el, width) {
138
+ const pos = getComputedStyle(el).position;
139
+ if (pos !== "fixed" && pos !== "sticky") return false;
140
+ const r = topBoxOf(el).getBoundingClientRect();
141
+ return r.width > width * 0.5 && r.height > 8 && r.height < 200 && r.top < 160 && r.bottom > 0 && !el.closest("[data-top-chrome]");
142
+ }
143
+
144
+ function chromeOverlapsOf(doc) {
145
+ const chrome = [...document.querySelectorAll("[data-top-chrome]")].filter((el) => el.getBoundingClientRect().height > 0);
146
+ const bars = [...document.querySelectorAll("body *")].filter((el) => isTopBar(el, doc.clientWidth)).map(topBoxOf);
147
+ const stack = [...chrome, ...bars];
148
+ const found = [];
149
+ stack.forEach((a, i) => {
150
+ for (const b of stack.slice(i + 1)) if (apart(a, b) && meets(a.getBoundingClientRect(), b.getBoundingClientRect())) found.push(`${nameOf(a)} / ${nameOf(b)}`);
151
+ });
152
+ return found;
153
+ }
154
+
155
+ /** « Never overflows »: a control or a card that clips its own content (overflow hidden / clip with more content than room) cuts a word. */
156
+ function clipsOf() {
157
+ return [...document.querySelectorAll("button, a, [role=button], [data-testid], [class*=badge], [class*=chip]")]
158
+ .filter((el) => {
159
+ const r = el.getBoundingClientRect();
160
+ const style = getComputedStyle(el);
161
+ return r.width > 4 && r.height > 4 && ["hidden", "clip"].includes(style.overflowX) && style.textOverflow !== "ellipsis" && el.scrollWidth > el.clientWidth + 1 && !clipped(el);
162
+ })
163
+ .slice(0, 3)
164
+ .map(nameOf);
165
+ }
166
+
167
+ /** A long token (an id, an address) that wraps character by character: a cell taller than two lines for text without a space. */
168
+ function tooTall(el) {
169
+ const text = (el.textContent || "").trim();
170
+ if (text.length < 12 || /\s/.test(text) || el.children.length > 1) return false;
171
+ const cs = getComputedStyle(el);
172
+ const lh = Number.parseFloat(cs.lineHeight) || Number.parseFloat(cs.fontSize) * 1.4;
173
+ const content = el.getBoundingClientRect().height - Number.parseFloat(cs.paddingTop) - Number.parseFloat(cs.paddingBottom);
174
+ return content > lh * 2.5;
175
+ }
176
+
177
+ function wrappedOf() {
178
+ return [...document.querySelectorAll("td, th, code, [role=cell]")]
179
+ .filter(tooTall)
180
+ .slice(0, 2)
181
+ .map((el) => (el.textContent || "").trim().slice(0, 24));
182
+ }
183
+
184
+ /** The whole measure of a page. Decorative layers (aria-hidden), fixed elements and anything inside a scroller are left out of the layout probes (yomizaka#435). */
185
+ /** A heading with no text (and no image or labelled icon) says nothing to a screen reader. */
186
+ function emptyHeadingsOf() {
187
+ return [...document.querySelectorAll("h1, h2, h3")].filter((h) => !(h.textContent || "").trim() && !h.querySelector("img, svg[aria-label]")).length;
188
+ }
189
+
190
+ /** A file input that no label, `aria-label` or title names. */
191
+ function unlabelledFilesOf() {
192
+ return [...document.querySelectorAll("input[type=file]")].filter((i) => !(i.getAttribute("aria-label") || i.getAttribute("aria-labelledby") || i.title || i.labels?.length)).length;
193
+ }
194
+
195
+ /** `<main>` with no text at all: the page answered but drew nothing (a route that fell through, a failed fetch). */
196
+ function emptyMainOf() {
197
+ return document.querySelector("main")?.innerText.trim().length === 0;
198
+ }
199
+
200
+ /** Height of every action of the page's main (a button-styled link): the tap targets the responsive guard keeps over `minAction`. */
201
+ function actionsOf() {
202
+ return [...document.querySelectorAll("main a[class*='kz-button'], main a[data-slot='button'], main .kz-button")].filter((a) => a.getBoundingClientRect().width > 0).map((a) => Math.round(a.getBoundingClientRect().height));
203
+ }
204
+
205
+ /**
206
+ * The signed-in frame's own screen (akinaza#444): its shell (`min-height`) and its sticky rail must fit in what is left of the viewport
207
+ * under the notice, or every page, an empty one included, scrolls by the notice's height. `null` when the page has no `[data-app-frame-slot]`.
208
+ */
209
+ function frameOf(doc) {
210
+ const shell = document.querySelector("[data-app-frame-slot] > *");
211
+ if (!shell) return null;
212
+ const rail = [...shell.querySelectorAll("nav")].find((n) => getComputedStyle(n).position === "sticky");
213
+ return {
214
+ top: Math.round(shell.getBoundingClientRect().top + window.scrollY),
215
+ forced: Math.round(Math.max(Number.parseFloat(getComputedStyle(shell).minHeight) || 0, rail ? rail.getBoundingClientRect().height : 0)),
216
+ viewport: doc.clientHeight,
217
+ };
218
+ }
219
+
220
+ /** A landmark (`main`, `aside`, `header`, `nav`) whose content is wider than its own box, with nothing to scroll it. */
221
+ function boxesOf() {
222
+ return [...document.querySelectorAll("main, aside, header, nav")]
223
+ .filter((box) => getComputedStyle(box).overflowX === "visible" && box.scrollWidth > box.clientWidth + 1 && box.clientWidth > 0)
224
+ .slice(0, 3)
225
+ .map((box) => `<${box.tagName.toLowerCase()}> ${box.scrollWidth}px in ${box.clientWidth}px`);
226
+ }
227
+
228
+ /** The family contract of the page chrome: the page's own footers (not those of an article or a dialog), whether the first names Krizaka, a navigation landmark. */
229
+ function landmarksOf() {
230
+ const footers = [...document.querySelectorAll("footer")].filter((f) => !f.closest("main, article, section, dialog, [role=dialog]"));
231
+ return { footers: footers.length, footerNamesKrizaka: /krizaka/i.test(footers[0]?.textContent || ""), nav: !!document.querySelector("nav") };
232
+ }
233
+
234
+ /** A picture drawn at a real size that never loaded. */
235
+ function brokenPicturesOf() {
236
+ return [...document.querySelectorAll("img")]
237
+ .filter((img) => {
238
+ const box = img.getBoundingClientRect();
239
+ return box.width > 8 && box.height > 8 && img.complete && img.naturalWidth === 0 && !!img.currentSrc;
240
+ })
241
+ .slice(0, 3)
242
+ .map((img) => img.currentSrc.slice(0, 80));
243
+ }
244
+
245
+ /** A control of the main that collapsed (under 4 px tall), or a tile that renders nothing (no text, label or image). */
246
+ function emptyControlsOf() {
247
+ const found = [];
248
+ for (const el of document.querySelectorAll("main a[href], main button")) {
249
+ const box = el.getBoundingClientRect();
250
+ const style = getComputedStyle(el);
251
+ if (style.visibility === "hidden" || style.display === "none") continue;
252
+ if (box.width > 0 && box.height > 0 && box.height < 4) found.push(`collapsed control ${(el.getAttribute("aria-label") || el.textContent || "").trim().slice(0, 30)}`);
253
+ else if (box.width > 24 && box.height > 24 && !el.textContent?.trim() && !el.getAttribute("aria-label") && !el.getAttribute("aria-labelledby") && !el.querySelector("img, svg, video, picture, canvas")) found.push("empty tile");
254
+ }
255
+ return [...new Set(found)].slice(0, 3);
256
+ }
257
+
258
+ /** Elements whose inline style carries a colour that is not a token (`var(--kz-*)`). */
259
+ function hardColorsOf() {
260
+ return [...document.querySelectorAll("[style]")].filter((e) => /#[0-9a-f]{3,8}\b|rgba?\(/i.test(e.getAttribute("style") || "") && !/var\(/.test(e.getAttribute("style") || "")).length;
261
+ }
262
+
263
+ function measurePage() {
264
+ const doc = document.documentElement;
265
+ const panels = [...document.querySelectorAll("[data-panel], main section, main [role=region]")].filter((el) => !el.closest(ARIA_HIDDEN) && !folded(el));
266
+ const { overflowing, spill } = spillOf(panels);
267
+ const chips = [...document.querySelectorAll('[data-testid="audience-picker"] a')].map((a) => Math.round(a.getBoundingClientRect().height));
268
+ return {
269
+ h1: document.querySelectorAll("h1").length,
270
+ scrollWidth: doc.scrollWidth,
271
+ clientWidth: doc.clientWidth,
272
+ wide: wideOf(doc),
273
+ ...unnamedOf(),
274
+ headerAction: headerActionOf(doc),
275
+ chips,
276
+ overflowing: overflowing.slice(0, 3),
277
+ overlaps: overlapsOf(panels, spill).slice(0, 3),
278
+ cutColumns: cutColumnsOf(),
279
+ chromeOverlaps: chromeOverlapsOf(doc).slice(0, 3),
280
+ clips: clipsOf(),
281
+ emptyHeadings: emptyHeadingsOf(),
282
+ unlabelledFiles: unlabelledFilesOf(),
283
+ wrapped: wrappedOf(),
284
+ emptyMain: emptyMainOf(),
285
+ actions: actionsOf(),
286
+ frame: frameOf(doc),
287
+ boxes: boxesOf(),
288
+ landmarks: landmarksOf(),
289
+ brokenPictures: brokenPicturesOf(),
290
+ emptyControls: emptyControlsOf(),
291
+ hardColors: hardColorsOf(),
292
+ segmentError: !!document.querySelector('[data-testid="segment-error"]'),
293
+ };
294
+ }
295
+
296
+ const PROBES = [tooTall, wrappedOf, className, nameOf, scrolls, meets, apart, clipped, wideOf, named, unnamedOf, headerActionOf, folded, keptBetween, notDrawn, runsOut, spillOf, overlapsOf, cutBy, cutColumnsOf, topBoxOf, isTopBar, chromeOverlapsOf, clipsOf, emptyHeadingsOf, unlabelledFilesOf, emptyMainOf, actionsOf, frameOf, boxesOf, landmarksOf, brokenPicturesOf, emptyControlsOf, hardColorsOf, measurePage];
297
+
298
+ /** The expression Playwright runs in the page (`page.evaluate(auditPage)`): the probes, serialised together, then the measure. */
299
+ export const auditPage = `(() => {\nconst ARIA_HIDDEN = ${JSON.stringify(ARIA_HIDDEN)};\n${PROBES.map((f) => `const ${f.name} = ${f.toString()};`).join("\n")}\nreturn measurePage();\n})()`;
300
+
301
+ /**
302
+ * The problems of one page × width × theme, in words: console errors, a horizontal overflow (or elements past the edge),
303
+ * not exactly one h1 (when asked), unnamed buttons, the header's action off screen or unnamed (when the page has one).
304
+ */
305
+ /** Empty headings; file inputs without a label (opt-in until `Dropzone` of @krizaka/ui names its hidden input, a prop of the package). */
306
+ function accessibilityProblems(where, result, fileLabels) {
307
+ const problems = [];
308
+ if (result.emptyHeadings) problems.push(`${where}: ${result.emptyHeadings} empty heading(s)`);
309
+ if (fileLabels && result.unlabelledFiles) problems.push(`${where}: ${result.unlabelledFiles} file input(s) without a label`);
310
+ return problems;
311
+ }
312
+
313
+ export function problemsOf(where, result, { errors = [], h1 = false, headerAction = false, fileLabels = false, status, emptyMain = false, frame = false, minAction, boxes = false, landmarks, pictures = false, emptyControls = false, hardColors = false } = {}) {
314
+ return [
315
+ ...statusProblems(where, status),
316
+ ...(emptyMain && result.emptyMain ? [`${where}: empty <main>`] : []),
317
+ ...(frame ? frameProblems(where, result.frame) : []),
318
+ ...(minAction ? actionProblems(where, result.actions ?? [], minAction) : []),
319
+ ...(boxes ? boxProblems(where, result.boxes ?? []) : []),
320
+ ...(landmarks ? landmarkProblems(where, result.landmarks, landmarks) : []),
321
+ ...(pictures && result.brokenPictures?.length ? [`${where}: broken picture ${result.brokenPictures.join(", ")}`] : []),
322
+ ...(emptyControls ? (result.emptyControls ?? []).map((c) => `${where}: ${c}`) : []),
323
+ ...(hardColors && result.hardColors ? [`${where}: ${result.hardColors} element(s) with a hard-coded colour in an inline style`] : []),
324
+ ...errorsOf(where, errors),
325
+ ...layoutProblems(where, result),
326
+ ...(h1 ? namingProblems(where, result) : []),
327
+ ...(headerAction ? headerActionProblems(where, result.headerAction) : []),
328
+ ...chipProblems(where, result.chips ?? []),
329
+ ...accessibilityProblems(where, result, fileLabels),
330
+ ];
331
+ }
332
+
333
+ function errorsOf(where, errors) {
334
+ return errors.length ? [`${where}: console error — ${errors[0]}`] : [];
335
+ }
336
+
337
+ /** Overflow, elements past the edge, boxes that cover or cut one another, a token wrapped per character, the error state. */
338
+ function layoutProblems(where, result) {
339
+ const problems = [];
340
+ if (result.scrollWidth > result.clientWidth) problems.push(`${where}: scrollWidth ${result.scrollWidth} > ${result.clientWidth} (${result.wide.join(", ")})`);
341
+ else if (result.wide.length) problems.push(`${where}: elements past the edge (${result.wide.join(", ")})`);
342
+ const lists = [[result.overflowing, "overflows its panel"], [result.overlaps, "covers a neighbouring section"], [result.cutColumns, "is cut off"]];
343
+ for (const [list, words] of lists) {
344
+ if (list?.length) problems.push(`${where}: ${words} (${list.join(", ")})`);
345
+ }
346
+ if (result.wrapped?.length) problems.push(`${where}: a token wraps one character per line (${result.wrapped.join(", ")}) — truncate it`);
347
+ if (result.segmentError) problems.push(`${where}: the page rendered its error state (segment-error), e.g. React #441`);
348
+ if (result.chromeOverlaps?.length) problems.push(`${where}: the top chrome chromeOverlaps (${result.chromeOverlaps.slice(0, 2).join(", ")})`);
349
+ if (result.clips?.length) problems.push(`${where}: content cut inside its box (${result.clips.join(", ")})`);
350
+ return problems;
351
+ }
352
+
353
+ /** Exactly one h1 and every button named. */
354
+ function namingProblems(where, result) {
355
+ const problems = [];
356
+ if (result.h1 !== 1) problems.push(`${where}: ${result.h1} h1 (expected exactly one)`);
357
+ if (result.unnamedButtons > 0) {
358
+ const samples = (result.unnamedSamples ?? []).join(" | ");
359
+ problems.push(`${where}: ${result.unnamedButtons} unnamed button(s) ${samples}`.trimEnd());
360
+ }
361
+ return problems;
362
+ }
363
+
364
+ function headerActionProblems(where, action) {
365
+ if (!action) return [`${where}: no header action`];
366
+ if (!action.visible) return [`${where}: the header's action is off screen`];
367
+ return action.named ? [] : [`${where}: the header's action has no accessible name`];
368
+ }
369
+
370
+ function chipProblems(where, chips) {
371
+ return chips.some((h) => h < 44) ? [`${where}: a chip is ${Math.min(...chips)} px tall (< 44)`] : [];
372
+ }
373
+
374
+ /** The HTTP status of the page's own load (`undefined`: not asked): a 4xx or 5xx, or no response at all. */
375
+ function statusProblems(where, status) {
376
+ if (status === undefined) return [];
377
+ return status === null || status >= 400 ? [`${where}: HTTP ${status ?? "none"}`] : [];
378
+ }
379
+
380
+ /** The signed-in frame forces a scroll when what it asks of the screen (its shell, its rail) does not fit under what is above it. */
381
+ function frameProblems(where, frame) {
382
+ if (!frame || frame.top + frame.forced <= frame.viewport + 1) return [];
383
+ return [`${where}: the frame forces a scroll (starts at ${frame.top} px and asks ${frame.forced} px of a ${frame.viewport} px screen)`];
384
+ }
385
+
386
+ /** A button-styled action under `min` px tall is hard to tap. */
387
+ function actionProblems(where, actions, min) {
388
+ return actions.some((h) => h < min) ? [`${where}: an action is ${Math.min(...actions)} px tall (< ${min})`] : [];
389
+ }
390
+
391
+ function boxProblems(where, boxes) {
392
+ return boxes.map((b) => `${where}: never overflows — ${b} content wider than its box`);
393
+ }
394
+
395
+ /** `kind`: "public" (one page footer that names Krizaka, a nav), "app" (at most one footer, a nav), "auth" (at most one footer, no nav asked). */
396
+ function landmarkProblems(where, found, kind) {
397
+ const problems = [];
398
+ if (kind === "public") {
399
+ if (found.footers !== 1) problems.push(`${where}: ${found.footers} page footers (one « A Krizaka product » footer expected)`);
400
+ else if (!found.footerNamesKrizaka) problems.push(`${where}: the footer does not name Krizaka`);
401
+ } else if (found.footers > 1) problems.push(`${where}: ${found.footers} page footers (at most one)`);
402
+ if (kind !== "auth" && !found.nav) problems.push(`${where}: no <nav> landmark`);
403
+ return problems;
404
+ }
package/src/run.mjs ADDED
@@ -0,0 +1,198 @@
1
+ // The audit over a route list: every route × viewport width × theme, in a real browser, the problems in words.
2
+ import { existsSync, mkdirSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
5
+ import { auditPage, problemsOf } from "./page-audit.mjs";
6
+ import { auditContext, loadSettled, resizeSettled } from "./settle.mjs";
7
+
8
+ export const WIDTHS = [360, 390, 430, 768, 1024, 1440];
9
+ export const THEMES = ["dark", "light"];
10
+
11
+ /** A blocked third-party resource is not a page error; a script error and a hydration mismatch are. `ignore`: the messages the app tolerates. */
12
+ export const isPageError = (message, ignore = [/Failed to load resource/]) => message.type() === "error" && !ignore.some((re) => re.test(message.text()));
13
+
14
+ async function chromiumOf(launch) {
15
+ if (launch) return launch();
16
+ const { chromium } = await import("playwright-core");
17
+ return chromium.launch();
18
+ }
19
+
20
+ /** Persists the theme the way the apps do, before any page script runs. */
21
+ function rememberTheme([key, value]) {
22
+ try {
23
+ localStorage.setItem(key, value);
24
+ } catch {
25
+ // storage blocked: the colour scheme is still emulated
26
+ }
27
+ }
28
+
29
+ /** The page's console errors and uncaught exceptions, read and cleared by `take()`. */
30
+ function collectErrors(page, ignore) {
31
+ let errors = [];
32
+ page.on("console", (m) => {
33
+ if (isPageError(m, ignore)) errors.push(m.text().slice(0, 140));
34
+ });
35
+ page.on("pageerror", (e) => errors.push(String(e).slice(0, 140)));
36
+ return {
37
+ take() {
38
+ const seen = errors;
39
+ errors = [];
40
+ return seen;
41
+ },
42
+ };
43
+ }
44
+
45
+ const viewportOf = (w, height) => (typeof w === "number" ? { width: w, height } : { height, ...w });
46
+ const specOf = (r) => (typeof r === "string" ? { url: r } : { ...r, url: r.url ?? r.route });
47
+ const nameOfRoute = (r) => r.name ?? r.url;
48
+
49
+ /**
50
+ * A route source that is a crawl: the paths of the site's own sitemap (a page added there is audited), the `first` ones always first,
51
+ * at most `limit`. Returns `null` when nothing answers at `${base}/sitemap.xml` (the caller says so and stops).
52
+ * @param {string} base
53
+ * @param {{ first?: string[], limit?: number, fetcher?: typeof fetch }} [o]
54
+ * @returns {Promise<string[] | null>}
55
+ */
56
+ export async function routesFromSitemap(base, { first = ["/"], limit = 14, fetcher = fetch } = {}) {
57
+ const origin = base.replace(/\/$/, "");
58
+ const xml = await fetcher(`${origin}/sitemap.xml`).then((r) => (r.ok ? r.text() : null), () => null);
59
+ if (xml === null) return null;
60
+ const paths = [...xml.matchAll(/<loc>([^<]+)<\/loc>/g)].map((m) => new URL(m[1]).pathname || "/");
61
+ return [...new Set([...first, ...paths])].slice(0, limit);
62
+ }
63
+
64
+ /** The optional axe step: `@krizaka/a11y-audit` (a peer, loaded only when asked), one collector per kind of page, each ratcheted by the repo's own baseline file. */
65
+ async function a11yOf(a11y) {
66
+ if (!a11y) return null;
67
+ const lib = await import("@krizaka/a11y-audit");
68
+ const kinds = { public: { collector: new lib.A11yCollector(a11y.app), baseline: a11y.baseline } };
69
+ if (a11y.session) kinds.session = { collector: new lib.A11yCollector(a11y.session.app), baseline: a11y.session.baseline, optional: true };
70
+ return { lib, kinds, widths: a11y.widths ?? [390, 1440], log: a11y.log ?? ((line) => process.stdout.write(`${line}\n`)) };
71
+ }
72
+
73
+ /** The ratchet's verdict, per kind. A baseline not recorded yet (`optional`) is counted, not enforced, until `--a11y-init`. */
74
+ function a11yProblems(state) {
75
+ const problems = [];
76
+ for (const { collector, baseline, optional } of Object.values(state.kinds)) {
77
+ if (optional && !existsSync(baseline) && !process.argv.includes("--a11y-init")) {
78
+ state.log(`· a11y baseline missing: counted, not enforced (${collector.summary().join("; ") || "no violation"}); record it with --a11y-init`);
79
+ continue;
80
+ }
81
+ const guard = state.lib.finish(collector, { baseline });
82
+ for (const note of guard.notes) state.log(note);
83
+ problems.push(...guard.problems);
84
+ }
85
+ return problems;
86
+ }
87
+
88
+ /** The HTTP status of the load when asked for (`null`: no response), else `undefined`. */
89
+ function statusOf(response, checks) {
90
+ if (!checks.status) return undefined;
91
+ return response ? response.status() : null;
92
+ }
93
+
94
+ /** One route at one width: load, settle, measure, screenshot. */
95
+ async function measure(page, { base, spec, viewport, settleMs, prepare, checks, errors, where, shots, a11y, kind, theme }) {
96
+ await resizeSettled(page, viewport);
97
+ // « load » and the faces, not « networkidle »: router prefetches can keep the page from ever going idle.
98
+ const response = await loadSettled(page, `${base}${spec.url}`);
99
+ if (prepare) await prepare(page, spec.url);
100
+ if (settleMs) await page.waitForTimeout(settleMs);
101
+ const result = await page.evaluate(auditPage);
102
+ if (a11y?.widths.includes(viewport.width)) {
103
+ const { collector } = a11y.kinds[kind] ?? a11y.kinds.public;
104
+ collector.add({ route: spec.url, theme }, await a11y.lib.auditPage(page));
105
+ }
106
+ if (shots) {
107
+ mkdirSync(shots, { recursive: true });
108
+ await page.screenshot({ path: join(shots, `${where.replace(/[/?=&@ ]/g, "_")}.png`) });
109
+ }
110
+ const status = statusOf(response, checks);
111
+ const landmarks = spec.chrome ?? checks.landmarks;
112
+ return problemsOf(where, result, { ...checks, landmarks, status, errors: errors.take() });
113
+ }
114
+
115
+ /** One route at one width, with `attempts` tries before it counts as « could not be audited ». */
116
+ async function measureWithRetries(page, o, spec, viewport, where) {
117
+ let failure;
118
+ for (let attempt = 1; attempt <= o.attempts; attempt++) {
119
+ try {
120
+ return await measure(page, { ...o, spec, viewport, where });
121
+ } catch (error) {
122
+ failure = error;
123
+ }
124
+ }
125
+ return [`${where}: could not be audited — ${String(failure?.message).split("\n")[0]}`];
126
+ }
127
+
128
+ /** Audits the routes of one page (one context), each width. */
129
+ async function auditPageRoutes(page, routes, o) {
130
+ const problems = [];
131
+ for (const spec of routes) {
132
+ for (const w of o.widths) {
133
+ const viewport = viewportOf(w, o.height);
134
+ problems.push(...(await measureWithRetries(page, o, spec, viewport, `${nameOfRoute(spec)} @${viewport.width} ${o.theme}`)));
135
+ }
136
+ }
137
+ return problems;
138
+ }
139
+
140
+ async function newPage(browser, o, extra = {}) {
141
+ const context = await auditContext(browser, { colorScheme: o.theme, ...extra });
142
+ if (o.themeKey) await context.addInitScript(rememberTheme, [o.themeKey, o.theme]);
143
+ const page = await context.newPage();
144
+ return { context, page, errors: collectErrors(page, o.ignoreConsole) };
145
+ }
146
+
147
+ /** The signed-in pages of one theme: a context with the session (a stored state, or `signIn` on the context), the routes the session names, then the flagged ones. */
148
+ async function auditSession(browser, session, flagged, o) {
149
+ const { context, page, errors } = await newPage(browser, o, session.storageState ? { storageState: session.storageState } : {});
150
+ try {
151
+ if (session.signIn) await session.signIn(context, { base: o.base, theme: o.theme, page });
152
+ const own = session.routes ? await session.routes(page, { base: o.base, theme: o.theme }) : [];
153
+ return await auditPageRoutes(page, [...own, ...flagged].map(specOf), { ...o, errors, kind: "session" });
154
+ } finally {
155
+ await context.close();
156
+ }
157
+ }
158
+
159
+ /**
160
+ * @param {object} o
161
+ * @param {string} o.base origin of the running app
162
+ * @param {Array<string | { url: string, name?: string, chrome?: "public" | "app" | "auth", session?: boolean }>} o.routes paths to audit (a route flagged `session` is audited signed in; `chrome` replaces `checks.landmarks` for that route)
163
+ * @param {Array<number | { width: number, height?: number }>} [o.widths] viewports (default widths 360 to 1440)
164
+ * @param {string[]} [o.themes] "dark" | "light" (default both): emulated colour scheme and, when `themeKey` is set, localStorage
165
+ * @param {number} [o.height] viewport height (default 900)
166
+ * @param {string} [o.themeKey] localStorage key the app persists its theme in (default "kz-theme")
167
+ * @param {string} [o.shots] directory for one screenshot per route × width × theme
168
+ * @param {number} [o.settleMs] pause after load, for late layout (default 300)
169
+ * @param {object} [o.checks] options of `problemsOf`: h1, headerAction, fileLabels, and the opt-in status, emptyMain, frame, minAction, boxes, landmarks, pictures, emptyControls, hardColors
170
+ * @param {RegExp[]} [o.ignoreConsole] console errors the app tolerates (default: « Failed to load resource »; `[]` counts every error)
171
+ * @param {number} [o.attempts] tries per route before it counts as not audited (default 1)
172
+ * @param {{ app: string, baseline: string, widths?: number[], log?: (line: string) => void, session?: { app: string, baseline: string } }} [o.a11y] the axe step (`@krizaka/a11y-audit`, a peer) and the repo's ratchet file
173
+ * @param {{ storageState?: object | string, signIn?: Function, routes?: Function }} [o.session] how the signed-in pages are reached
174
+ * @param {(page: object, route: string) => Promise<void>} [o.prepare] before each route is measured (sign in, seed)
175
+ * @param {() => Promise<object>} [o.launch] returns a Playwright browser (default: chromium of playwright-core)
176
+ * @returns {Promise<string[]>} the problems, empty when the pages are fine
177
+ */
178
+ export async function auditRoutes({ base, routes, widths = WIDTHS, themes = THEMES, height = 900, themeKey = "kz-theme", shots, settleMs = 300, checks = {}, ignoreConsole, attempts = 1, a11y, session, prepare, launch }) {
179
+ const browser = await chromiumOf(launch);
180
+ const state = await a11yOf(a11y);
181
+ const specs = routes.map(specOf);
182
+ const plain = specs.filter((r) => !r.session);
183
+ const flagged = specs.filter((r) => r.session);
184
+ const problems = [];
185
+ try {
186
+ for (const theme of themes) {
187
+ const o = { base, widths, height, theme, themeKey, shots, settleMs, checks, ignoreConsole, attempts, prepare, a11y: state };
188
+ const { context, page, errors } = await newPage(browser, o);
189
+ problems.push(...(await auditPageRoutes(page, plain, { ...o, errors, kind: "public" })));
190
+ await context.close();
191
+ if (session && (session.routes || flagged.length)) problems.push(...(await auditSession(browser, session, flagged, o)));
192
+ }
193
+ } finally {
194
+ await browser.close();
195
+ }
196
+ if (state) problems.push(...a11yProblems(state));
197
+ return problems;
198
+ }
@@ -0,0 +1,62 @@
1
+ // The audit proven on its own fixtures, in a real browser: each broken fixture must be reported, the fine ones must not.
2
+ // A guard that stopped seeing is itself a red build.
3
+ import { BOX_TOO_WIDE, BROKEN_PARTS, CARD_OVER_NEXT, CHROME_BAD, CHROME_FINE, COLUMN_CUT, EMPTY_MAIN, FINE, FOLDED_SECTION, FRAME_FITS, FRAME_FORCES_SCROLL, HIDDEN_CONTENT, SECTIONS_OVERLAP, SMALL_ACTION } from "./fixtures.mjs";
4
+ import { auditPage, problemsOf } from "./page-audit.mjs";
5
+ import { auditContext } from "./settle.mjs";
6
+
7
+ const EXPECT = [
8
+ ["a card taller than its panel", CARD_OVER_NEXT, /overflows its panel/],
9
+ ["a card over the next section", CARD_OVER_NEXT, /covers a neighbouring section/],
10
+ ["two sections on top of each other", SECTIONS_OVERLAP, /covers a neighbouring section/],
11
+ ["a column cut by a clipping wrapper", COLUMN_CUT, /is cut off/],
12
+ ["an empty <main>", EMPTY_MAIN, /empty <main>/, { emptyMain: true }],
13
+ ["a frame that forces a scroll", FRAME_FORCES_SCROLL, /the frame forces a scroll/, { frame: true }],
14
+ ["an action under the tap target", SMALL_ACTION, /an action is 24 px tall \(< 36\)/, { minAction: 36 }],
15
+ ["a landmark wider than its box", BOX_TOO_WIDE, /content wider than its box/, { boxes: true }],
16
+ ["a broken picture", BROKEN_PARTS, /broken picture/, { pictures: true }],
17
+ ["a tile that draws nothing", BROKEN_PARTS, /empty tile/, { emptyControls: true }],
18
+ ["a hard-coded inline colour", BROKEN_PARTS, /hard-coded colour/, { hardColors: true }],
19
+ ["two page footers and no nav", CHROME_BAD, /2 page footers/, { landmarks: "public" }],
20
+ ["no nav landmark", CHROME_BAD, /no <nav> landmark/, { landmarks: "app" }],
21
+ ];
22
+ const FINES = [
23
+ ["a fine layout", FINE],
24
+ ["content that is not drawn (a visually hidden table, a folded details)", HIDDEN_CONTENT],
25
+ ["a section folded in a details", FOLDED_SECTION],
26
+ ];
27
+ /** Fixtures that must stay clean even with every opt-in check on. */
28
+ const ALL = { emptyMain: true, frame: true, minAction: 36, boxes: true, pictures: true, emptyControls: true, hardColors: true, landmarks: "public" };
29
+ const FINES_STRICT = [
30
+ ["a frame that fits its screen", FRAME_FITS, { frame: true, emptyMain: false }],
31
+ ["the family chrome", CHROME_FINE, ALL],
32
+ ];
33
+
34
+ async function problemsOn(page, html, checks) {
35
+ await page.setContent(html);
36
+ return problemsOf("fixture", await page.evaluate(auditPage), checks);
37
+ }
38
+
39
+ /** The failure for a fixture that must be clean and is not (none, when it is). */
40
+ async function reported(page, name, html, checks) {
41
+ const fine = await problemsOn(page, html, checks);
42
+ return fine.length ? [`the audit reports ${String(name)}: ${fine.join(" | ")}`] : [];
43
+ }
44
+
45
+ /** @returns {Promise<string[]>} the failures (empty when the audit sees what it must and nothing else) */
46
+ export async function selfTest({ launch } = {}) {
47
+ const browser = launch ? await launch() : await (await import("playwright-core")).chromium.launch();
48
+ const failures = [];
49
+ try {
50
+ const page = await (await auditContext(browser, { viewport: { width: 1280, height: 800 } })).newPage();
51
+ for (const [name, html, pattern, checks] of EXPECT) {
52
+ const problems = await problemsOn(page, html, checks);
53
+ if (!problems.some((p) => pattern.test(p))) failures.push(`the audit does not see ${String(name)}: ${problems.join(" | ") || "no problem reported"}`);
54
+ }
55
+ for (const [name, html] of FINES) failures.push(...(await reported(page, name, html)));
56
+ await page.setViewportSize({ width: 1280, height: 700 });
57
+ for (const [name, html, checks] of FINES_STRICT) failures.push(...(await reported(page, name, html, checks)));
58
+ } finally {
59
+ await browser.close();
60
+ }
61
+ return failures;
62
+ }
package/src/settle.mjs ADDED
@@ -0,0 +1,54 @@
1
+ // One way for every browser audit to measure (yomizaka#354): never while a View Transition is swapping the page.
2
+ //
3
+ // The flake: the page was read while a transition was running (« Viewport size changed », 0 of 2 h1). The cure is the
4
+ // same everywhere, so it lives here and nowhere else: the context emulates reduced motion (the app honours it, the page
5
+ // change is instant — motion.css of @krizaka/ui) and every load or resize waits, explicitly, until no transition is
6
+ // active. No retry, no sleep standing in for a condition. `tests/browser-audits.test.mjs` fails a script that
7
+ // opens a context, loads a page or resizes without these.
8
+
9
+ /** The options of an audit's browser context: the caller's, plus reduced motion. */
10
+ export const auditOptions = (options = {}) => ({ ...options, reducedMotion: "reduce" });
11
+
12
+ /**
13
+ * Runs before any page script: the browser offers no View Transition, so PageTransition (@krizaka/ui) changes the page
14
+ * at once. Reduced motion alone is not enough: the transition still starts, and a resize or a load under it, or a slow
15
+ * runner, makes the browser log « Transition was aborted » / « DOM update timed out » as a console error that has
16
+ * nothing to do with the page (main and two PRs, 2026-10-27). An audit measures layout, not motion.
17
+ */
18
+ export const withoutViewTransitions = () => {
19
+ Object.defineProperty(Document.prototype, "startViewTransition", { value: undefined, configurable: true });
20
+ };
21
+
22
+ /** A browser context for an audit (reduced motion emulated, no View Transition). */
23
+ export async function auditContext(browser, options) {
24
+ const context = await browser.newContext(auditOptions(options));
25
+ await context.addInitScript(withoutViewTransitions);
26
+ return context;
27
+ }
28
+
29
+ /** Resolves once no view transition is running (none starts under reduced motion; this makes the wait explicit). */
30
+ export const settled = (page) =>
31
+ page.waitForFunction(() => !document.activeViewTransition && !document.documentElement.matches(":active-view-transition"), null, { timeout: 10_000 });
32
+
33
+ /**
34
+ * Loads a page, then waits for the faces and for the transitions: what is read afterwards is final. Returns the response.
35
+ * It first lets the page we are leaving finish any transition it started after the last measure (a router refresh, a
36
+ * poll): leaving one running aborts it, and the browser reports « Transition was aborted » as a console error (#354).
37
+ */
38
+ export async function loadSettled(page, url, options = { waitUntil: "load" }) {
39
+ if (page.url() !== "about:blank") await settled(page);
40
+ const response = await page.goto(url, options);
41
+ await page.evaluate(() => document.fonts.ready);
42
+ await settled(page);
43
+ return response;
44
+ }
45
+
46
+ /**
47
+ * Resizes the viewport, then waits for the transitions a resize can start. A transition already running is let finish
48
+ * first: a resize under it aborts it (« Viewport size changed », a console error), which is how this audit once failed.
49
+ */
50
+ export async function resizeSettled(page, size) {
51
+ await settled(page);
52
+ await page.setViewportSize(size);
53
+ await settled(page);
54
+ }