@a.incantalupo/web-tools 0.2.0 → 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/README.md CHANGED
@@ -8,18 +8,55 @@ stack-tools browser [url] # your own Chromium window: sign in by hand, to
8
8
  stack-tools refs <url...> [--full] [--mine] [--out dir | --out-root dir] # desktop + mobile screenshots -> ./design-refs/<date>
9
9
  stack-tools snap <dir> <url...> # computed styles + screenshots of pages, in every theme
10
10
  stack-tools diff <before> <after>
11
- stack-tools text <url...> [--verbose] [--login <email>] # reading ease (Gulpease), text size, contrast, fields, tap targets, sideways scroll at 320 px, the phone with text at 130-200%
12
- stack-tools glyphs <url...> # characters the page fonts don't cover
13
- stack-tools images <url...> # which image file each slot downloads (3x phone, 2x laptop, 1x monitor)
11
+ stack-tools text <url...> [--verbose] [--login <email>] [--brief | --json] # reading ease (Gulpease), text size, contrast, fields, tap targets, sideways scroll at 320 px, the phone with text at 130-200%
12
+ stack-tools glyphs <url...> [--brief | --json] # characters the page fonts don't cover
13
+ stack-tools images <url...> [--budget 600] [--brief | --json] # which image file each slot downloads (3x phone, 2x laptop, 1x monitor)
14
+ stack-tools lighthouse <url...> [--budget] [--min-perf <n>] [--runs <n>] [--out dir] [--json] [--header 'Name: value'] # Lighthouse on phone and desktop; use it instead of the Lighthouse CLI (on WSL that one leaves Chrome's profile in your folder)
14
15
  stack-tools audit <url> [--profile file.ts] [--render] [--teaser] [--reviews a.json...] [--preview] [--header 'Name: value'] [--keys .env] [--out dir | --out-root dir]
15
16
  stack-tools audit-rerender <dir> [--profile file.ts] [--teaser] # rebuild a report from its findings.json, no new crawl
16
17
  ```
17
18
 
18
19
  Outputs go where you run the command (`./design-refs`, `./site-eval/<host>/<date>`) unless `--out` or `--out-root` says otherwise. A project keeps its own outputs; nothing is written inside this package.
19
20
 
21
+ ## Short output, for agents and scripts
22
+
23
+ `text`, `images` and `glyphs` print in one of three forms. What is measured and the exit code (1 when something failed) are the same in all three.
24
+
25
+ | Form | Chosen by | Prints |
26
+ | --- | --- | --- |
27
+ | full | the default, or `--full` | every finding with its detail |
28
+ | brief | `--brief`, or `STACK_TOOLS_OUTPUT=brief` in the environment | one line per page (`ok`, `warn` or `FAIL`, the page, its key numbers), every failure in full under it, the warnings as a count with their kinds, the totals last |
29
+ | JSON | `--json`, or `STACK_TOOLS_OUTPUT=json` | the same counts and findings, for a script |
30
+
31
+ A flag wins over the variable, and `--full` wins over everything. Set the variable once where an AI coding agent runs its commands (its settings' environment): the agent then reads a few lines per check, and you still get the full form in your own terminal.
32
+
33
+ ```text
34
+ $ stack-tools text https://example.com/ https://example.com/contact --brief
35
+ ok / reading ease 68
36
+ FAIL /contact reading ease 61 · 1 fail · 2 warn (small-text, target-44)
37
+ phone 390: 1 field(s) under 16 px: "email" 14 px
38
+ 2 pages · 1 fail · 2 warn · --full lists the warnings
39
+ ```
40
+
41
+ ## Speed against a budget
42
+
43
+ `stack-tools lighthouse <url...> --budget` judges every run (phone and desktop) against the limits a public page should hold, and exits 1 when one is passed:
44
+
45
+ | Number | Limit |
46
+ | --- | --- |
47
+ | Largest contentful paint | 2.5 s |
48
+ | Layout shift (CLS) | 0.1 |
49
+ | The server's first byte | 800 ms |
50
+ | Scripts, as sent | 100 kB |
51
+
52
+ - A `FAIL` line names the number and its limit; for the largest paint, also the element that was timed.
53
+ - `--min-perf <n>` adds a floor on the performance score (with or without `--budget`).
54
+ - `--runs <n>` runs each page n times and keeps the middle run: one lab run proves little, and the phone run simulates a slow network.
55
+ - Without these flags the command prints what it always did.
56
+
20
57
  ## Setup
21
58
 
22
- - In a project: `pnpm add -D @a.incantalupo/web-tools`, then scripts like `"check:text": "stack-tools text"`.
59
+ - In a project: `pnpm add -D @a.incantalupo/web-tools`, then scripts like `"check:text": "stack-tools text"` and `"check:speed": "stack-tools lighthouse --budget"`.
23
60
  - Chromium: the tools use Playwright's (`CHROME_PATH`, default `~/.cache/ms-playwright/chromium-1194/chrome-linux/chrome`). Install it with `pnpm dlx playwright@1.56.1 install chromium`.
24
61
  - `stack-tools browser` keeps its profile in `~/.cache/stack-tools/chrome-profile` (`MY_CHROME_PROFILE` to change it) and listens on `127.0.0.1:9222` only (`MY_CHROME_PORT`).
25
62
 
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,112 @@
1
+ // stack-tools lighthouse <url...>: Lighthouse on a phone and on a desktop, for each URL.
2
+ // Use this instead of the Lighthouse CLI: on WSL the CLI leaves Chrome's profile in the
3
+ // folder you run it from, as a folder literally named "C:\Users\...\lighthouse.*".
4
+ // Here the profile sits in the system temp folder and is removed at the end.
5
+ //
6
+ // --budget judges every run against the limits a public page should hold: LCP 2.5 s,
7
+ // CLS 0.1, the server's first byte 800 ms, scripts 100 KB as sent. --min-perf <n> adds a
8
+ // floor on the performance score. Past a limit: a FAIL line with the number, the limit
9
+ // and, for LCP, the element that was timed; exit code 1. --runs <n> keeps the middle
10
+ // run of n, since one lab run proves little.
11
+ import { mkdir, mkdtemp } from "node:fs/promises";
12
+ import { tmpdir } from "node:os";
13
+ import { join, resolve } from "node:path";
14
+ import { parseArgs } from "node:util";
15
+ import { extraHeaders } from "./fetch.js";
16
+ import { runLighthouse } from "./lighthouse.js";
17
+ const { values, positionals } = parseArgs({
18
+ allowPositionals: true,
19
+ options: {
20
+ // Where the HTML reports go (default: a new folder in the system temp folder).
21
+ out: { type: "string" },
22
+ json: { type: "boolean", default: false },
23
+ // "Name: value", sent with every request: the site owner's firewall allowlist.
24
+ header: { type: "string", multiple: true, default: [] },
25
+ budget: { type: "boolean", default: false },
26
+ "min-perf": { type: "string" },
27
+ runs: { type: "string", default: "1" },
28
+ },
29
+ });
30
+ const minPerf = values["min-perf"] == null ? null : Number(values["min-perf"]);
31
+ const times = Number(values.runs);
32
+ if (!positionals.length ||
33
+ (minPerf != null && !(minPerf >= 0 && minPerf <= 100)) ||
34
+ !(Number.isInteger(times) && times >= 1 && times <= 9)) {
35
+ console.error("Usage: stack-tools lighthouse <url...> [--budget] [--min-perf 0-100] [--runs 1-9] [--out dir] [--json] [--header 'Name: value']");
36
+ process.exit(positionals.length ? 2 : 1);
37
+ }
38
+ for (const h of values.header ?? []) {
39
+ const i = h.indexOf(":");
40
+ if (i > 0)
41
+ extraHeaders[h.slice(0, i).trim()] = h.slice(i + 1).trim();
42
+ }
43
+ const outDir = values.out
44
+ ? resolve(process.env.INIT_CWD ?? process.cwd(), values.out)
45
+ : await mkdtemp(join(tmpdir(), "stack-tools-lighthouse-"));
46
+ await mkdir(outDir, { recursive: true });
47
+ const runs = await runLighthouse(positionals, outDir, times);
48
+ // The limits of a public page. Lab numbers on a simulated mid-range phone and on a
49
+ // desktop: limits, not goals.
50
+ const LIMITS = { lcpMs: 2500, cls: 0.1, ttfbMs: 800, scriptBytes: 100 * 1024 };
51
+ const judging = values.budget || minPerf != null;
52
+ const over = [];
53
+ for (const r of runs) {
54
+ if (!judging || r.error)
55
+ continue;
56
+ const add = (what, note) => over.push({ url: r.url, formFactor: r.formFactor, what, note });
57
+ const m = r.metrics;
58
+ const perf = r.scores.performance;
59
+ if (minPerf != null && perf != null && perf < minPerf)
60
+ add("performance", `performance ${perf} under ${minPerf}`);
61
+ if (!values.budget)
62
+ continue;
63
+ if (m.lcpMs != null && m.lcpMs > LIMITS.lcpMs)
64
+ add("lcp", `LCP ${(m.lcpMs / 1000).toFixed(1)} s over ${LIMITS.lcpMs / 1000} s${r.lcpElement ? `: ${r.lcpElement}` : ""}`);
65
+ if (m.cls != null && m.cls > LIMITS.cls)
66
+ add("cls", `CLS ${m.cls.toFixed(3)} over ${LIMITS.cls}`);
67
+ if (m.ttfbMs != null && m.ttfbMs > LIMITS.ttfbMs)
68
+ add("ttfb", `first byte ${Math.round(m.ttfbMs)} ms over ${LIMITS.ttfbMs} ms`);
69
+ if (r.scriptBytes != null && r.scriptBytes > LIMITS.scriptBytes)
70
+ add("js", `scripts ${Math.round(r.scriptBytes / 1024)} kB over ${LIMITS.scriptBytes / 1024} kB`);
71
+ }
72
+ if (values.json) {
73
+ console.log(JSON.stringify(judging
74
+ ? {
75
+ outDir,
76
+ runs,
77
+ budget: { limits: values.budget ? LIMITS : {}, minPerf, over },
78
+ }
79
+ : { outDir, runs }, null, 2));
80
+ }
81
+ else {
82
+ const score = (n) => n == null ? " -" : String(n).padStart(3);
83
+ const seconds = (ms) => ms == null ? "-" : `${(ms / 1000).toFixed(1)} s`;
84
+ for (const r of runs) {
85
+ const m = r.metrics;
86
+ console.log([
87
+ r.formFactor.padEnd(7),
88
+ `perf ${score(r.scores.performance)}`,
89
+ `a11y ${score(r.scores.accessibility)}`,
90
+ `best ${score(r.scores["best-practices"])}`,
91
+ `seo ${score(r.scores.seo)}`,
92
+ `LCP ${seconds(m.lcpMs)}`,
93
+ `CLS ${m.cls == null ? "-" : m.cls.toFixed(3)}`,
94
+ `TBT ${m.tbtMs == null ? "-" : `${Math.round(m.tbtMs)} ms`}`,
95
+ r.totalBytes == null ? "" : `${Math.round(r.totalBytes / 1024)} kB`,
96
+ r.url,
97
+ ].join(" "));
98
+ if (r.error)
99
+ console.log(` ${r.error}`);
100
+ for (const o of over)
101
+ if (o.url === r.url && o.formFactor === r.formFactor)
102
+ console.log(` FAIL ${o.note}`);
103
+ }
104
+ if (judging)
105
+ console.log(`\n${runs.length} run(s)${times > 1 ? `, the middle of ${times} each` : ""}: ${over.length ? `${over.length} over the limits` : "all within the limits"}.`);
106
+ console.log(`${judging ? "" : "\n"}Reports: ${outDir}`);
107
+ }
108
+ // One run per URL and form factor: fewer means Lighthouse returned nothing for one.
109
+ const failed = runs.length < positionals.length * 2 ||
110
+ runs.some((r) => r.error) ||
111
+ over.length > 0;
112
+ process.exit(failed ? 1 : 0);
@@ -1,2 +1,7 @@
1
1
  import type { LighthouseRun } from "./types.ts";
2
- export declare function runLighthouse(urls: string[], outDir: string): Promise<LighthouseRun[]>;
2
+ /**
3
+ * Lighthouse on a phone and on a desktop for each URL; the HTML report and the final
4
+ * screenshot go to `outDir`. With `times` > 1 each one is run that many times and the
5
+ * middle run is kept (its report and screenshot too).
6
+ */
7
+ export declare function runLighthouse(urls: string[], outDir: string, times?: number): Promise<LighthouseRun[]>;
@@ -1,9 +1,12 @@
1
1
  import * as chromeLauncher from "chrome-launcher";
2
2
  import lighthouse from "lighthouse";
3
3
  import desktopConfig from "lighthouse/core/config/desktop-config.js";
4
- import { mkdtemp, rm, writeFile } from "node:fs/promises";
4
+ import { spawn } from "node:child_process";
5
+ import { existsSync } from "node:fs";
6
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
5
7
  import { tmpdir } from "node:os";
6
8
  import { join } from "node:path";
9
+ import { executablePath } from "../browser/index.js";
7
10
  import { extraHeaders } from "./fetch.js";
8
11
  const METRICS = {
9
12
  lcpMs: "largest-contentful-paint",
@@ -13,72 +16,154 @@ const METRICS = {
13
16
  speedIndexMs: "speed-index",
14
17
  ttfbMs: "server-response-time",
15
18
  };
16
- export async function runLighthouse(urls, outDir) {
17
- // Own profile dir, passed as a raw flag: on WSL chrome-launcher rewrites its
18
- // `userDataDir` option to a Windows path and creates it as a relative folder
19
- // in the cwd ("C:\\Users\\...\\lighthouse.*"), even for a Linux Chrome.
20
- const userDataDir = await mkdtemp(join(tmpdir(), "site-eval-chrome-"));
21
- const chrome = await chromeLauncher.launch({
22
- chromeFlags: [
23
- "--headless=new",
24
- "--no-first-run",
25
- `--user-data-dir=${userDataDir}`,
26
- ],
27
- userDataDir: false,
19
+ /** The node of the "Largest Contentful Paint element" audit: a list whose first table holds it. */
20
+ function lcpElementOf(details) {
21
+ const lists = details?.items ??
22
+ [];
23
+ const node = lists.flatMap((l) => l.items ?? []).find((i) => i.node)?.node;
24
+ if (!node?.selector && !node?.snippet)
25
+ return null;
26
+ const snippet = (node.snippet ?? "").replace(/\s+/g, " ");
27
+ return [
28
+ node.selector,
29
+ snippet.length > 120 ? `${snippet.slice(0, 120)}…` : snippet,
30
+ ]
31
+ .filter(Boolean)
32
+ .join(" ");
33
+ }
34
+ /** The middle run of several: by performance score, then by LCP. Lab runs vary; one run proves little. */
35
+ function median(tries) {
36
+ const sorted = [...tries].sort((a, b) => (a.run.scores.performance ?? -1) - (b.run.scores.performance ?? -1) ||
37
+ (b.run.metrics.lcpMs ?? Infinity) - (a.run.metrics.lcpMs ?? Infinity));
38
+ return sorted[Math.floor((sorted.length - 1) / 2)];
39
+ }
40
+ /**
41
+ * Starts a headless Chrome with its profile in the system temp folder and returns the
42
+ * DevTools port; `stop()` closes it and removes the profile.
43
+ *
44
+ * Not `chromeLauncher.launch()`: on WSL it asks Windows for a temp folder even for a
45
+ * Linux Chrome. With its own profile, Chrome gets a Windows path it reads as a relative
46
+ * one, and a folder named "C:\Users\...\lighthouse.*" appears where you run the
47
+ * command (what the Lighthouse CLI does). With `userDataDir: false` it still leaves a
48
+ * folder of logs in Windows' AppData\Local at every run.
49
+ */
50
+ async function startChrome() {
51
+ const chromePath = process.env.CHROME_PATH ??
52
+ (existsSync(executablePath)
53
+ ? executablePath
54
+ : chromeLauncher.getChromePath());
55
+ const profile = await mkdtemp(join(tmpdir(), "stack-tools-chrome-"));
56
+ const child = spawn(chromePath, [
57
+ ...chromeLauncher.Launcher.defaultFlags(),
58
+ "--headless=new",
59
+ "--no-first-run",
60
+ "--remote-debugging-port=0",
61
+ `--user-data-dir=${profile}`,
62
+ "about:blank",
63
+ ], { stdio: "ignore" });
64
+ let gone = false;
65
+ const exited = new Promise((done) => {
66
+ const end = () => {
67
+ gone = true;
68
+ done();
69
+ };
70
+ child.once("exit", end);
71
+ child.once("error", end);
28
72
  });
73
+ const stop = async () => {
74
+ if (!gone)
75
+ child.kill();
76
+ await exited;
77
+ await rm(profile, {
78
+ recursive: true,
79
+ force: true,
80
+ maxRetries: 10,
81
+ retryDelay: 200,
82
+ });
83
+ };
84
+ // Chrome writes the port it picked on the first line of this file.
85
+ for (let i = 0; i < 80 && !gone; i++) {
86
+ const text = await readFile(join(profile, "DevToolsActivePort"), "utf8").catch(() => "");
87
+ const port = Number(text.split("\n")[0]);
88
+ if (port)
89
+ return { port, stop };
90
+ await new Promise((r) => setTimeout(r, 250));
91
+ }
92
+ await stop();
93
+ throw new Error(`Chrome didn't start (${chromePath})`);
94
+ }
95
+ /**
96
+ * Lighthouse on a phone and on a desktop for each URL; the HTML report and the final
97
+ * screenshot go to `outDir`. With `times` > 1 each one is run that many times and the
98
+ * middle run is kept (its report and screenshot too).
99
+ */
100
+ export async function runLighthouse(urls, outDir, times = 1) {
101
+ const chrome = await startChrome();
29
102
  const runs = [];
30
103
  try {
31
104
  for (const [i, url] of urls.entries()) {
32
105
  for (const formFactor of ["mobile", "desktop"]) {
33
- const audit = () => lighthouse(url, {
34
- port: chrome.port,
35
- output: "html",
36
- logLevel: "error",
37
- extraHeaders,
38
- }, formFactor === "desktop" ? desktopConfig : undefined);
39
- let result = await audit();
40
- // Trace errors like NO_NAVSTART are often transient; one retry is usually enough
41
- if (result?.lhr.runtimeError)
42
- result = (await audit()) ?? result;
43
- if (!result)
106
+ const tries = [];
107
+ for (let t = 0; t < Math.max(1, times); t++) {
108
+ const audit = () => lighthouse(url, {
109
+ port: chrome.port,
110
+ output: "html",
111
+ logLevel: "error",
112
+ extraHeaders,
113
+ }, formFactor === "desktop" ? desktopConfig : undefined);
114
+ let result = await audit();
115
+ // Trace errors like NO_NAVSTART are often transient; one retry is usually enough
116
+ if (result?.lhr.runtimeError)
117
+ result = (await audit()) ?? result;
118
+ if (!result)
119
+ continue;
120
+ const { lhr } = result;
121
+ const reportFile = `lighthouse-${i + 1}-${formFactor}.html`;
122
+ const shot = lhr.audits["final-screenshot"]?.details?.data?.match(/^data:image\/jpeg;base64,(.+)$/)?.[1];
123
+ const screenshot = shot ? `screen-${i + 1}-${formFactor}.jpg` : null;
124
+ const resources = lhr.audits["resource-summary"]?.details?.items ?? [];
125
+ const bytesOf = (type) => resources.find((r) => r.resourceType === type)?.transferSize ??
126
+ null;
127
+ const metricError = Object.values(METRICS)
128
+ .map((id) => lhr.audits[id]?.errorMessage)
129
+ .find(Boolean);
130
+ tries.push({
131
+ report: result.report,
132
+ shot,
133
+ run: {
134
+ url,
135
+ formFactor,
136
+ scores: Object.fromEntries(Object.entries(lhr.categories).map(([k, c]) => [
137
+ k,
138
+ c.score === null ? null : Math.round(c.score * 100),
139
+ ])),
140
+ metrics: Object.fromEntries(Object.entries(METRICS).map(([k, id]) => [
141
+ k,
142
+ lhr.audits[id]?.numericValue ?? null,
143
+ ])),
144
+ totalBytes: bytesOf("total"),
145
+ scriptBytes: bytesOf("script"),
146
+ imageBytes: bytesOf("image"),
147
+ thirdPartyBytes: bytesOf("third-party"),
148
+ error: lhr.runtimeError?.message ?? metricError ?? null,
149
+ reportFile,
150
+ screenshot,
151
+ lcpElement: lcpElementOf(lhr.audits["largest-contentful-paint-element"]?.details),
152
+ },
153
+ });
154
+ }
155
+ if (!tries.length)
44
156
  continue;
45
- const { lhr } = result;
46
- const reportFile = `lighthouse-${i + 1}-${formFactor}.html`;
47
- await writeFile(join(outDir, reportFile), result.report);
48
- const shot = lhr.audits["final-screenshot"]?.details?.data?.match(/^data:image\/jpeg;base64,(.+)$/)?.[1];
49
- const screenshot = shot ? `screen-${i + 1}-${formFactor}.jpg` : null;
50
- if (shot && screenshot)
51
- await writeFile(join(outDir, screenshot), Buffer.from(shot, "base64"));
52
- const resources = lhr.audits["resource-summary"]?.details?.items ?? [];
53
- const bytesOf = (type) => resources.find((r) => r.resourceType === type)?.transferSize ?? null;
54
- const metricError = Object.values(METRICS)
55
- .map((id) => lhr.audits[id]?.errorMessage)
56
- .find(Boolean);
57
- runs.push({
58
- url,
59
- formFactor,
60
- scores: Object.fromEntries(Object.entries(lhr.categories).map(([k, c]) => [
61
- k,
62
- c.score === null ? null : Math.round(c.score * 100),
63
- ])),
64
- metrics: Object.fromEntries(Object.entries(METRICS).map(([k, id]) => [
65
- k,
66
- lhr.audits[id]?.numericValue ?? null,
67
- ])),
68
- totalBytes: bytesOf("total"),
69
- scriptBytes: bytesOf("script"),
70
- imageBytes: bytesOf("image"),
71
- thirdPartyBytes: bytesOf("third-party"),
72
- error: lhr.runtimeError?.message ?? metricError ?? null,
73
- reportFile,
74
- screenshot,
75
- });
157
+ const kept = median(tries);
158
+ await writeFile(join(outDir, kept.run.reportFile), kept.report);
159
+ if (kept.shot && kept.run.screenshot)
160
+ await writeFile(join(outDir, kept.run.screenshot), Buffer.from(kept.shot, "base64"));
161
+ runs.push(kept.run);
76
162
  }
77
163
  }
78
164
  }
79
165
  finally {
80
- chrome.kill();
81
- await rm(userDataDir, { recursive: true, force: true });
166
+ await chrome.stop();
82
167
  }
83
168
  return runs;
84
169
  }
@@ -63,6 +63,8 @@ export type LighthouseRun = {
63
63
  reportFile: string;
64
64
  /** What the page looked like at the end of the load (Lighthouse's final screenshot), a JPEG next to the report. */
65
65
  screenshot: string | null;
66
+ /** The element Lighthouse timed as the largest contentful paint: its selector and the start of its HTML. */
67
+ lcpElement?: string | null;
66
68
  };
67
69
  /** Real visitors' numbers from the Chrome UX Report (75th percentile, last 28 days), phones. */
68
70
  export type Crux = {
package/dist/cli.js CHANGED
@@ -14,9 +14,10 @@ const commands = {
14
14
  refs: { file: "./refs/cli.js", about: "desktop + mobile screenshots of sites: <url...> [--full] [--mine] [--out dir | --out-root dir]" },
15
15
  snap: { file: "./refs/snapshot.js", keepName: true, about: "computed styles + screenshots of pages: <dir> <url...>" },
16
16
  diff: { file: "./refs/snapshot.js", keepName: true, about: "what changed between two snaps: <before> <after>" },
17
- text: { file: "./refs/text.js", about: "readability, text size, contrast, fields, tap targets, text at 200%: <url...> [--verbose] [--login email]" },
18
- glyphs: { file: "./refs/glyphs.js", about: "characters the page fonts do not cover: <url...>" },
19
- images: { file: "./refs/images.js", about: "which image file each slot downloads, weights, lazy LCP: <url...>" },
17
+ text: { file: "./refs/text.js", about: "readability, text size, contrast, fields, tap targets, text at 200%: <url...> [--verbose] [--login email] [--brief|--json]" },
18
+ glyphs: { file: "./refs/glyphs.js", about: "characters the page fonts do not cover: <url...> [--brief|--json]" },
19
+ images: { file: "./refs/images.js", about: "which image file each slot downloads, weights, lazy LCP: <url...> [--brief|--json]" },
20
+ lighthouse: { file: "./audit/lighthouse-cli.js", about: "Lighthouse on phone and desktop, judged against the budgets with --budget: <url...> [--budget] [--min-perf n] [--runs n] [--out dir] [--json]" },
20
21
  audit: { file: "./audit/cli.js", about: "audit a site (SEO, AI visibility, speed, contacts): <url> [--profile file.ts] [--render] [--teaser]" },
21
22
  "audit-rerender": { file: "./audit/rerender.js", about: "rebuild an audit report from its findings.json: <dir> [--profile file.ts] [--teaser]" }
22
23
  };
@@ -4,21 +4,33 @@
4
4
  // draws it from a system font, with other metrics and baseline (the "→" that sat low on
5
5
  // some phones). Exit code 1 when something is missing, so it can gate CI.
6
6
  //
7
- // Usage: stack-tools glyphs <url...> (e.g. the home, catalog, a vehicle page, chi-siamo)
7
+ // Usage: stack-tools glyphs <url...> [--brief | --full | --json]
8
+ // (e.g. the home, the catalog, an item page, the about page)
9
+ //
10
+ // --brief (or STACK_TOOLS_OUTPUT=brief): one line per page with its missing characters;
11
+ // --json: the same as JSON; --full: one list for all the pages (the default).
8
12
  import { chromium } from "playwright-core";
9
13
  import { homedir } from "node:os";
10
14
  import { join } from "node:path";
11
- const urls = process.argv.slice(2);
15
+ import { parseArgs } from "node:util";
16
+ import { outputMode, outputOptions, outputUsage, Report } from "../report.js";
17
+ const { values, positionals: urls } = parseArgs({
18
+ allowPositionals: true,
19
+ options: outputOptions,
20
+ });
12
21
  if (!urls.length) {
13
- console.error("Usage: stack-tools glyphs <url...>");
22
+ console.error(`Usage: stack-tools glyphs <url...> ${outputUsage}`);
14
23
  process.exit(1);
15
24
  }
25
+ const out = new Report("glyphs", urls, outputMode(values));
16
26
  const executablePath = process.env.CHROME_PATH ??
17
27
  join(homedir(), ".cache/ms-playwright/chromium-1194/chrome-linux/chrome");
18
28
  const browser = await chromium.launch({ executablePath });
19
29
  const all = new Map();
20
30
  try {
21
31
  for (const url of urls) {
32
+ const pg = out.page(url);
33
+ const here = new Set();
22
34
  for (const width of [390, 1440]) {
23
35
  const page = await browser.newPage({ viewport: { width, height: 900 } });
24
36
  await page.goto(url, { waitUntil: "networkidle" });
@@ -79,23 +91,26 @@ try {
79
91
  });
80
92
  for (const m of missing) {
81
93
  const key = `${m.family} ${m.code}`;
94
+ if (!here.has(key)) {
95
+ here.add(key);
96
+ pg.fail("missing-glyph", `${m.char} ${m.code} in ${m.family} e.g. "${m.sample}"`);
97
+ }
82
98
  const entry = all.get(key) ?? { ...m, pages: new Set() };
83
99
  entry.pages.add(url);
84
100
  all.set(key, entry);
85
101
  }
86
102
  await page.close();
87
103
  }
104
+ pg.end();
88
105
  }
89
106
  }
90
107
  finally {
91
108
  await browser.close();
92
109
  }
93
- if (!all.size) {
94
- console.log(`All characters covered by our fonts on ${urls.length} page(s).`);
95
- }
96
- else {
97
- console.log(`${all.size} character(s) drawn from a system font:`);
110
+ // The full form: one list for all the pages, each character once.
111
+ if (all.size) {
112
+ out.say(`${all.size} character(s) drawn from a system font:`);
98
113
  for (const m of all.values())
99
- console.log(` ${m.char} ${m.code} in ${m.family} e.g. "${m.sample}" (${[...m.pages].length} page(s))`);
100
- process.exitCode = 1;
114
+ out.say(` ${m.char} ${m.code} in ${m.family} e.g. "${m.sample}" (${[...m.pages].length} page(s))`);
101
115
  }
116
+ out.done(all.size ? "" : `All characters covered by our fonts on ${urls.length} page(s).`);
@@ -3,7 +3,10 @@
3
3
  // mid-range phone, and a page can score well while a retina laptop downloads four times
4
4
  // the photos.
5
5
  //
6
- // Usage: stack-tools images <url...> [--budget 600]
6
+ // Usage: stack-tools images <url...> [--budget 600] [--brief | --full | --json]
7
+ //
8
+ // --brief (or STACK_TOOLS_OUTPUT=brief): one line per page, the failures in full, the
9
+ // warnings as a count; --json: the same as JSON; --full: every finding (the default).
7
10
  //
8
11
  // Fails (exit 1) on what is always wrong: an image that didn't load, or a lazy-loaded
9
12
  // largest image (LCP). Warns on what is usually wrong: a file much larger than its slot,
@@ -12,12 +15,13 @@ import { chromium } from "playwright-core";
12
15
  import { homedir } from "node:os";
13
16
  import { join } from "node:path";
14
17
  import { parseArgs } from "node:util";
18
+ import { outputMode, outputOptions, outputUsage, Report } from "../report.js";
15
19
  const { values, positionals: urls } = parseArgs({
16
20
  allowPositionals: true,
17
- options: { budget: { type: "string", default: "600" } },
21
+ options: { budget: { type: "string", default: "600" }, ...outputOptions },
18
22
  });
19
23
  if (!urls.length) {
20
- console.error("Usage: stack-tools images <url...> [--budget 600]");
24
+ console.error(`Usage: stack-tools images <url...> [--budget 600] ${outputUsage}`);
21
25
  process.exit(1);
22
26
  }
23
27
  const budget = Number(values.budget);
@@ -41,11 +45,12 @@ const browser = await chromium.launch({
41
45
  executablePath: process.env.CHROME_PATH ??
42
46
  join(homedir(), ".cache/ms-playwright/chromium-1194/chrome-linux/chrome"),
43
47
  });
44
- let failures = 0;
45
- let warnings = 0;
48
+ const out = new Report("images", urls, outputMode(values));
46
49
  const kb = (bytes) => `${Math.round(bytes / 1024)} KB`;
47
50
  for (const url of urls) {
48
- console.log(`\n${url}`);
51
+ const pg = out.page(url);
52
+ const firsts = [];
53
+ out.say(`\n${url}`);
49
54
  for (const [name, options] of Object.entries(screens)) {
50
55
  const context = await browser.newContext(options);
51
56
  const page = await context.newPage();
@@ -116,48 +121,45 @@ for (const url of urls) {
116
121
  const dpr = options.deviceScaleFactor;
117
122
  const notes = [];
118
123
  const broken = slots.filter((s) => s.broken || failed.has(s.url));
119
- if (broken.length) {
120
- failures++;
121
- notes.push(`FAIL ${broken.length} image(s) didn't load, e.g. ${broken[0].url.split("/").slice(-2).join("/")}`);
122
- }
123
- if (lcp?.lazy) {
124
- failures++;
125
- notes.push(`FAIL the largest image is lazy-loaded (${lcp.what})`);
126
- }
124
+ if (broken.length)
125
+ notes.push(pg.fail("broken", out.mode === "full"
126
+ ? `${broken.length} image(s) didn't load, e.g. ${broken[0].url.split("/").slice(-2).join("/")}`
127
+ : `${broken.length} image(s) didn't load: ${broken
128
+ .slice(0, 12)
129
+ .map((s) => s.url.split("/").slice(-2).join("/"))
130
+ .join(", ")}`, name));
131
+ if (lcp?.lazy)
132
+ notes.push(pg.fail("lazy-lcp", `the largest image is lazy-loaded (${lcp.what})`, name));
127
133
  // Much more file than the slot can show, and heavy enough to matter.
128
134
  const big = slots.filter((s) => s.css > 0 &&
129
135
  s.file / (s.css * dpr) > 2 &&
130
136
  (bytes.get(s.url) ?? 0) > 40_000);
131
- if (big.length) {
132
- warnings++;
133
- notes.push(`warn ${big.length} file(s) over twice their slot, e.g. ${big[0].file} px for ${big[0].css} px shown (${kb(bytes.get(big[0].url) ?? 0)})`);
134
- }
137
+ if (big.length)
138
+ notes.push(pg.warn("oversized", `${big.length} file(s) over twice their slot, e.g. ${big[0].file} px for ${big[0].css} px shown (${kb(bytes.get(big[0].url) ?? 0)})`, name));
135
139
  // Stretched: under 1.5 file pixels per CSS pixel on a dense screen (the eye stops
136
140
  // gaining around 2x, so a 3x phone isn't held to 3x), under 0.9 on a 1x one.
137
141
  const soft = slots.filter((s) => s.css >= 200 &&
138
142
  s.file > 0 &&
139
143
  s.file / s.css < (dpr >= 2 ? 1.5 : 0.9));
140
- if (soft.length) {
141
- warnings++;
142
- notes.push(`warn ${soft.length} photo(s) stretched, e.g. ${soft[0].file} px for ${soft[0].css} px at ${dpr}x`);
143
- }
144
- if (first / 1024 > budget) {
145
- warnings++;
146
- notes.push(`warn images before any scroll over ${budget} KB`);
147
- }
144
+ if (soft.length)
145
+ notes.push(pg.warn("stretched", `${soft.length} photo(s) stretched, e.g. ${soft[0].file} px for ${soft[0].css} px at ${dpr}x`, name));
146
+ if (first / 1024 > budget)
147
+ notes.push(pg.warn("over-budget", `images before any scroll over ${budget} KB`, name));
148
+ firsts.push(Math.round(first / 1024));
148
149
  const picks = new Map();
149
150
  for (const s of slots.filter((s) => s.css >= 60 && bytes.has(s.url))) {
150
151
  const key = `${s.css}→${s.file}`;
151
152
  picks.set(key, (picks.get(key) ?? 0) + 1);
152
153
  }
153
- console.log(` ${name.padEnd(17)} first screen ${kb(first).padStart(7)}, whole page ${kb(total).padStart(7)}, largest: ${lcp?.what ?? "?"}`);
154
- console.log(` ${"".padEnd(17)} shown→file px: ${[...picks].map(([k, n]) => `${n}× ${k}`).join(", ") || "none"}`);
154
+ out.say(` ${name.padEnd(17)} first screen ${kb(first).padStart(7)}, whole page ${kb(total).padStart(7)}, largest: ${lcp?.what ?? "?"}`);
155
+ out.say(` ${"".padEnd(17)} shown→file px: ${[...picks].map(([k, n]) => `${n}× ${k}`).join(", ") || "none"}`);
155
156
  for (const note of notes)
156
- console.log(` ${"".padEnd(17)} ${note}`);
157
+ out.say(` ${"".padEnd(17)} ${note}`);
157
158
  await context.close();
158
159
  }
160
+ // Phone, laptop, monitor: what downloads before any scroll.
161
+ pg.key(`first screen ${firsts.join("/")} KB`);
162
+ pg.end();
159
163
  }
160
164
  await browser.close();
161
- console.log(`\n${failures} failure(s), ${warnings} warning(s) on ${urls.length} page(s).`);
162
- if (failures)
163
- process.exitCode = 1;
165
+ out.done();
package/dist/refs/text.js CHANGED
@@ -2,7 +2,10 @@
2
2
  // dark the text is, whether the fields and the things you tap are large and visible
3
3
  // enough (WCAG 2.2 AA, plus a stricter bar for small text).
4
4
  //
5
- // Usage: stack-tools text <url...> [--verbose] [--login <email>]
5
+ // Usage: stack-tools text <url...> [--verbose] [--login <email>] [--brief | --full | --json]
6
+ //
7
+ // --brief (or STACK_TOOLS_OUTPUT=brief): one line per page, the failures in full, the
8
+ // warnings as a count; --json: the same as JSON; --full: every finding (the default).
6
9
  //
7
10
  // --login signs in at /admin/login of the first URL's site first (password from
8
11
  // CHECK_PASSWORD), so admin pages can be measured. Use a login on the dev database.
@@ -28,15 +31,17 @@ import { chromium } from "playwright-core";
28
31
  import { homedir } from "node:os";
29
32
  import { join } from "node:path";
30
33
  import { parseArgs } from "node:util";
34
+ import { outputMode, outputOptions, outputUsage, Report } from "../report.js";
31
35
  const { values, positionals: urls } = parseArgs({
32
36
  allowPositionals: true,
33
37
  options: {
34
38
  verbose: { type: "boolean", default: false },
35
39
  login: { type: "string" },
40
+ ...outputOptions,
36
41
  },
37
42
  });
38
43
  if (!urls.length) {
39
- console.error("Usage: stack-tools text <url...> [--verbose] [--login <email>]");
44
+ console.error(`Usage: stack-tools text <url...> [--verbose] [--login <email>] ${outputUsage}`);
40
45
  process.exit(1);
41
46
  }
42
47
  const screens = {
@@ -546,8 +551,9 @@ const browser = await chromium.launch({
546
551
  executablePath: process.env.CHROME_PATH ??
547
552
  join(homedir(), ".cache/ms-playwright/chromium-1194/chrome-linux/chrome"),
548
553
  });
549
- let failures = 0;
550
- let warnings = 0;
554
+ const out = new Report("text", urls, outputMode(values));
555
+ // The short forms name every example of a failure: the reader fixes from that line alone.
556
+ const every = out.mode === "full" ? undefined : 12;
551
557
  const pad = "".padEnd(15);
552
558
  const short = (s, n = 44) => (s.length > n ? `${s.slice(0, n)}…` : s);
553
559
  const list = (rows, show, n = 3) => rows
@@ -602,7 +608,8 @@ async function open(url, options) {
602
608
  return { context, page };
603
609
  }
604
610
  for (const url of urls) {
605
- console.log(`\n${url}`);
611
+ const pg = out.page(url);
612
+ out.say(`\n${url}`);
606
613
  let first = true;
607
614
  for (const [name, options] of Object.entries(screens)) {
608
615
  const phone = name.startsWith("phone");
@@ -610,18 +617,19 @@ for (const url of urls) {
610
617
  const m = await page.evaluate(measure);
611
618
  const photos = await onPhotos(page, await context.newPage(), m.texts);
612
619
  await context.close();
613
- const fail = (note) => (failures++, `FAIL ${note}`);
614
- const warn = (note) => (warnings++, `warn ${note}`);
620
+ const fail = (kind, note) => pg.fail(kind, note, name);
621
+ const warn = (kind, note) => pg.warn(kind, note, name);
615
622
  const notes = [];
616
623
  if (first) {
617
624
  first = false;
618
625
  const p = prose(m.blocks);
619
626
  const score = p.score == null ? "no prose" : `reading ease ${Math.round(p.score)}`;
620
- console.log(` ${"words".padEnd(15)}${score} on ${p.sentences} sentence(s)${m.quoted ? `, ${m.quoted} quoted block(s) left out` : ""}`);
627
+ pg.key(score);
628
+ out.say(` ${"words".padEnd(15)}${score} on ${p.sentences} sentence(s)${m.quoted ? `, ${m.quoted} quoted block(s) left out` : ""}`);
621
629
  if (p.score != null && p.score < 60)
622
- console.log(` ${pad}${warn("reading ease under 60 (hard with the licenza media)")}`);
630
+ out.say(` ${pad}${pg.warn("reading-ease", "reading ease under 60 (hard with the licenza media)", "words")}`);
623
631
  if (p.long.length)
624
- console.log(` ${pad}${warn(`${p.long.length} sentence(s) over 25 words: ${list(p.long, (x) => `${x.n} "${short(x.s)}"`, 2)}`)}`);
632
+ out.say(` ${pad}${pg.warn("long-sentence", `${p.long.length} sentence(s) over 25 words: ${list(p.long, (x) => `${x.n} "${short(x.s)}"`, 2)}`, "words")}`);
625
633
  }
626
634
  const total = m.texts.reduce((a, t) => a + t.chars, 0) || 1;
627
635
  const share = (rows) => Math.round((100 * rows.reduce((a, t) => a + t.chars, 0)) / total);
@@ -631,32 +639,32 @@ for (const url of urls) {
631
639
  const pale = plain.filter((t) => t.size < 16 && t.ratio >= 4.5 && t.ratio < 7);
632
640
  const lowPhoto = photos.filter((p) => p.ratio < (p.text.large ? 3 : 4.5));
633
641
  if (low.length)
634
- notes.push(fail(`${low.length} text(s) under 4.5:1: ${list(low, (t) => `${t.ratio.toFixed(1)} "${short(t.text, 24)}"`)}`));
642
+ notes.push(fail("contrast", `${low.length} text(s) under 4.5:1: ${list(low, (t) => `${t.ratio.toFixed(1)} "${short(t.text, 24)}"`, every)}`));
635
643
  if (small.length)
636
- notes.push(warn(`${share(small)}% of the text under 16 px (${share(m.texts.filter((t) => t.size < 14))}% under 14 px)`));
644
+ notes.push(warn("small-text", `${share(small)}% of the text under 16 px (${share(m.texts.filter((t) => t.size < 14))}% under 14 px)`));
637
645
  if (pale.length)
638
- notes.push(warn(`${pale.length} small text(s) under 7:1: ${list(pale, (t) => `${t.ratio.toFixed(1)} "${short(t.text, 24)}"`, 2)}`));
646
+ notes.push(warn("pale-small-text", `${pale.length} small text(s) under 7:1: ${list(pale, (t) => `${t.ratio.toFixed(1)} "${short(t.text, 24)}"`, 2)}`));
639
647
  if (lowPhoto.length)
640
- notes.push(warn(`text on a bright part of a photo: ${list(lowPhoto, (p) => `${p.ratio.toFixed(1)} "${short(p.text.text, 24)}"`)}`));
648
+ notes.push(warn("text-on-photo", `text on a bright part of a photo: ${list(lowPhoto, (p) => `${p.ratio.toFixed(1)} "${short(p.text.text, 24)}"`)}`));
641
649
  const smallFields = m.fields.filter((f) => f.size < 16);
642
650
  const faint = m.fields.filter((f) => f.edge < 3);
643
651
  if (smallFields.length)
644
- notes.push(fail(`${smallFields.length} field(s) under 16 px: ${list(smallFields, (f) => `"${f.what}" ${f.size} px`)}`));
652
+ notes.push(fail("field-size", `${smallFields.length} field(s) under 16 px: ${list(smallFields, (f) => `"${f.what}" ${f.size} px`, every)}`));
645
653
  if (faint.length)
646
- notes.push(warn(`${faint.length} field(s) with an edge under 3:1: ${list(faint, (f) => `${f.edge.toFixed(2)} "${f.what}"`, 2)}`));
654
+ notes.push(warn("field-edge", `${faint.length} field(s) with an edge under 3:1: ${list(faint, (f) => `${f.edge.toFixed(2)} "${f.what}"`, 2)}`));
647
655
  const tiny = m.targets.filter((t) => t.w < 24 || t.h < 24);
648
656
  const under = m.targets.filter((t) => (t.w < 44 || t.h < 44) && !tiny.includes(t));
649
657
  const size = (t) => `"${t.what}" ${t.w}×${t.h}`;
650
658
  if (tiny.length)
651
- notes.push(fail(`${tiny.length} target(s) under 24 px: ${list(tiny, size)}`));
659
+ notes.push(fail("target-24", `${tiny.length} target(s) under 24 px: ${list(tiny, size, every)}`));
652
660
  if (phone && under.length)
653
- notes.push(warn(`${under.length} target(s) under 44 px: ${list(under, size)}`));
661
+ notes.push(warn("target-44", `${under.length} target(s) under 44 px: ${list(under, size)}`));
654
662
  const wide = m.lines.filter((l) => l.chars > 80);
655
663
  if (wide.length)
656
- notes.push(warn(`${wide.length} paragraph(s) over 80 characters a line: ${list(wide, (l) => `${l.chars} "${l.text}"`, 2)}`));
657
- console.log(` ${name.padEnd(15)}${m.texts.length} texts, ${m.fields.length} field(s), ${m.targets.length} target(s)${notes.length ? "" : ": nothing to report"}`);
664
+ notes.push(warn("line-length", `${wide.length} paragraph(s) over 80 characters a line: ${list(wide, (l) => `${l.chars} "${l.text}"`, 2)}`));
665
+ out.say(` ${name.padEnd(15)}${m.texts.length} texts, ${m.fields.length} field(s), ${m.targets.length} target(s)${notes.length ? "" : ": nothing to report"}`);
658
666
  for (const note of notes)
659
- console.log(` ${pad}${note}`);
667
+ out.say(` ${pad}${note}`);
660
668
  }
661
669
  const { context, page } = await open(url, {
662
670
  viewport: { width: 320, height: 640 },
@@ -667,17 +675,16 @@ for (const url of urls) {
667
675
  // screen widens innerWidth to the page, and the difference reads 0.
668
676
  const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
669
677
  await context.close();
670
- if (overflow > 1) {
671
- failures++;
672
- console.log(` ${"narrow 320".padEnd(15)}FAIL scrolls sideways by ${overflow} px`);
673
- }
678
+ if (overflow > 1)
679
+ out.say(` ${"narrow 320".padEnd(15)}${pg.fail("sideways-scroll-320", `scrolls sideways by ${overflow} px`, "narrow 320")}`);
674
680
  // The reader's text size, raised: does the phone layout hold?
675
681
  {
676
682
  const { context, page } = await open(url, screens["phone 390"]);
677
683
  const { base, runs } = await bigText(page);
678
684
  await context.close();
679
- const fail = (note) => (failures++, `FAIL ${note}`);
680
- const warn = (note) => (warnings++, `warn ${note}`);
685
+ const zoom = "text 130-200%";
686
+ const fail = (kind, note) => pg.fail(kind, note, zoom);
687
+ const warn = (kind, note) => pg.warn(kind, note, zoom);
681
688
  const notes = [];
682
689
  const top = runs[runs.length - 1];
683
690
  const pct = (s) => `${Math.round(s * 100)}%`;
@@ -693,36 +700,35 @@ for (const url of urls) {
693
700
  // Only what the bigger text breaks: a clamp or an overlap there at 100% is a choice.
694
701
  const newly = (r, kind) => r.p.rows.flatMap((row, i) => row.clip === kind && base.rows[i].clip === 0 ? [i] : []);
695
702
  if (!base.meta)
696
- notes.push(warn('no <meta name="text-scale" content="scale">: phones keep this page at their default text size'));
703
+ notes.push(warn("text-scale-meta", 'no <meta name="text-scale" content="scale">: phones keep this page at their default text size'));
697
704
  if (top.p.root < base.root * 1.25)
698
- notes.push(warn(`the page fixes its root font size (${base.root} px at 100%, ${top.p.root} px at ${pct(top.scale)}): nothing in rem follows the reader`));
705
+ notes.push(warn("fixed-root-size", `the page fixes its root font size (${base.root} px at 100%, ${top.p.root} px at ${pct(top.scale)}): nothing in rem follows the reader`));
699
706
  const wide = first((r) => r.p.overflow > 1);
700
707
  if (wide)
701
- notes.push(fail(`scrolls sideways by ${wide.run.p.overflow} px at ${pct(wide.run.scale)}${since(wide.from)}: ${list(wide.run.p.culprits, (c) => c)}`));
708
+ notes.push(fail("sideways-scroll-zoom", `scrolls sideways by ${wide.run.p.overflow} px at ${pct(wide.run.scale)}${since(wide.from)}: ${list(wide.run.p.culprits, (c) => c, every)}`));
702
709
  const cut = first((r) => newly(r, 1).length > 0);
703
710
  if (cut) {
704
711
  const rows = newly(cut.run, 1);
705
- notes.push(fail(`${rows.length} text(s) cut off by a box that doesn't grow${since(cut.from)}: ${list(rows, label)}`));
712
+ notes.push(fail("cut-off-zoom", `${rows.length} text(s) cut off by a box that doesn't grow${since(cut.from)}: ${list(rows, label, every)}`));
706
713
  }
707
714
  const clamped = first((r) => newly(r, 2).length > 0);
708
715
  if (clamped) {
709
716
  const rows = newly(clamped.run, 2);
710
- notes.push(warn(`${rows.length} text(s) shortened with "…" or a line clamp${since(clamped.from)}: ${list(rows, label, 2)}`));
717
+ notes.push(warn("clamped-zoom", `${rows.length} text(s) shortened with "…" or a line clamp${since(clamped.from)}: ${list(rows, label, 2)}`));
711
718
  }
712
719
  const crossed = first((r) => r.overlaps.length > 0);
713
720
  if (crossed)
714
- notes.push(warn(`${crossed.run.overlaps.length} pair(s) of texts overlap${since(crossed.from)}: ${list(crossed.run.overlaps, (k) => k.split(",").map((i) => label(Number(i))).join(" on "), 2)}`));
721
+ notes.push(warn("overlap-zoom", `${crossed.run.overlaps.length} pair(s) of texts overlap${since(crossed.from)}: ${list(crossed.run.overlaps, (k) => k.split(",").map((i) => label(Number(i))).join(" on "), 2)}`));
715
722
  const chars = base.rows.reduce((a, r) => a + r.text.length, 0) || 1;
716
723
  const fixed = base.rows.flatMap((row, i) => top.p.rows[i] && top.p.rows[i].size < row.size * 1.25 ? [i] : []);
717
724
  const fixedShare = Math.round((100 * fixed.reduce((a, i) => a + base.rows[i].text.length, 0)) / chars);
718
725
  if (fixed.length && fixedShare >= 1)
719
- notes.push(warn(`${fixedShare}% of the text keeps its size (set in px?): ${list(fixed, label, 2)}`));
720
- console.log(` ${"text 130-200%".padEnd(15)}${base.rows.length} texts on the phone${notes.length ? "" : ": holds at 200%"}`);
726
+ notes.push(warn("fixed-size-text", `${fixedShare}% of the text keeps its size (set in px?): ${list(fixed, label, 2)}`));
727
+ out.say(` ${zoom.padEnd(15)}${base.rows.length} texts on the phone${notes.length ? "" : ": holds at 200%"}`);
721
728
  for (const note of notes)
722
- console.log(` ${pad}${note}`);
729
+ out.say(` ${pad}${note}`);
723
730
  }
731
+ pg.end();
724
732
  }
725
733
  await browser.close();
726
- console.log(`\n${failures} failure(s), ${warnings} warning(s) on ${urls.length} page(s).`);
727
- if (failures)
728
- process.exitCode = 1;
734
+ out.done();
@@ -0,0 +1,70 @@
1
+ export type Mode = "full" | "brief" | "json";
2
+ /** The three flags, for a check's `parseArgs` options. */
3
+ export declare const outputOptions: {
4
+ readonly brief: {
5
+ readonly type: "boolean";
6
+ readonly default: false;
7
+ };
8
+ readonly full: {
9
+ readonly type: "boolean";
10
+ readonly default: false;
11
+ };
12
+ readonly json: {
13
+ readonly type: "boolean";
14
+ readonly default: false;
15
+ };
16
+ };
17
+ export declare const outputUsage = "[--brief | --full | --json]";
18
+ export declare function outputMode(flags: {
19
+ brief?: boolean;
20
+ full?: boolean;
21
+ json?: boolean;
22
+ }): Mode;
23
+ export type Finding = {
24
+ /** A short, stable name for the rule (`contrast`, `lazy-lcp`): what brief counts by. */
25
+ kind: string;
26
+ note: string;
27
+ /** The screen or step it was found on (`phone 390`). */
28
+ where?: string;
29
+ };
30
+ export type PageResult = {
31
+ url: string;
32
+ status: "ok" | "warn" | "FAIL";
33
+ /** The page's key numbers, shown on its line in the brief form. */
34
+ keys: string[];
35
+ failures: Finding[];
36
+ warnings: Finding[];
37
+ };
38
+ export declare class PageReport {
39
+ readonly result: PageResult;
40
+ private ended;
41
+ private readonly report;
42
+ constructor(report: Report, url: string);
43
+ /** A key number for this page's line in the brief form (`reading ease 68`). */
44
+ key(text: string): void;
45
+ /** Records a failure; returns its line for the full form (`FAIL <note>`). */
46
+ fail(kind: string, note: string, where?: string): string;
47
+ /** Records a warning; returns its line for the full form (`warn <note>`). */
48
+ warn(kind: string, note: string, where?: string): string;
49
+ /** The page is measured: the brief form prints its line now. */
50
+ end(): void;
51
+ }
52
+ export declare class Report {
53
+ readonly pages: PageReport[];
54
+ readonly check: string;
55
+ readonly mode: Mode;
56
+ private readonly oneSite;
57
+ constructor(check: string, urls: string[], mode: Mode);
58
+ /** A line of the full form: printed only there. */
59
+ say(line?: string): void;
60
+ /** How a page is named on its brief line: its path when every page is on one site. */
61
+ label(url: string): string;
62
+ page(url: string): PageReport;
63
+ get failures(): number;
64
+ get warnings(): number;
65
+ /**
66
+ * The totals, in the chosen form, and the exit code: 1 when anything failed.
67
+ * `fullLine` replaces the full form's usual last line ("" for none).
68
+ */
69
+ done(fullLine?: string): void;
70
+ }
package/dist/report.js ADDED
@@ -0,0 +1,148 @@
1
+ // One reporter for the page checks (text, images, glyphs). A check measures and records
2
+ // `fail(kind, note)` and `warn(kind, note)` per page; the reporter prints them in one of
3
+ // three forms. The measuring and the exit code are the same in all three.
4
+ //
5
+ // full every finding with its detail, as the check always printed it. The default.
6
+ // brief one line per page (ok | warn | FAIL, the page, its key numbers), every failure
7
+ // in full under it, warnings as a count with their kinds, the totals last.
8
+ // For agents and scripts that pay for every character they read.
9
+ // json the same counts and findings as JSON.
10
+ //
11
+ // Chosen by a flag (--full, --json, --brief) or by STACK_TOOLS_OUTPUT=brief|json in the
12
+ // environment; a flag wins over the variable, and --full wins over everything.
13
+ /** The three flags, for a check's `parseArgs` options. */
14
+ export const outputOptions = {
15
+ brief: { type: "boolean", default: false },
16
+ full: { type: "boolean", default: false },
17
+ json: { type: "boolean", default: false },
18
+ };
19
+ export const outputUsage = "[--brief | --full | --json]";
20
+ export function outputMode(flags) {
21
+ if (flags.full)
22
+ return "full";
23
+ if (flags.json)
24
+ return "json";
25
+ if (flags.brief)
26
+ return "brief";
27
+ const env = (process.env.STACK_TOOLS_OUTPUT ?? "").toLowerCase();
28
+ return env === "brief" || env === "json" ? env : "full";
29
+ }
30
+ export class PageReport {
31
+ result;
32
+ ended = false;
33
+ report;
34
+ constructor(report, url) {
35
+ this.report = report;
36
+ this.result = { url, status: "ok", keys: [], failures: [], warnings: [] };
37
+ }
38
+ /** A key number for this page's line in the brief form (`reading ease 68`). */
39
+ key(text) {
40
+ this.result.keys.push(text);
41
+ }
42
+ /** Records a failure; returns its line for the full form (`FAIL <note>`). */
43
+ fail(kind, note, where) {
44
+ this.result.failures.push({ kind, note, ...(where ? { where } : {}) });
45
+ this.result.status = "FAIL";
46
+ return `FAIL ${note}`;
47
+ }
48
+ /** Records a warning; returns its line for the full form (`warn <note>`). */
49
+ warn(kind, note, where) {
50
+ this.result.warnings.push({ kind, note, ...(where ? { where } : {}) });
51
+ if (this.result.status === "ok")
52
+ this.result.status = "warn";
53
+ return `warn ${note}`;
54
+ }
55
+ /** The page is measured: the brief form prints its line now. */
56
+ end() {
57
+ if (this.ended)
58
+ return;
59
+ this.ended = true;
60
+ if (this.report.mode !== "brief")
61
+ return;
62
+ const { status, keys, failures, warnings } = this.result;
63
+ const kinds = new Map();
64
+ for (const w of warnings)
65
+ kinds.set(w.kind, (kinds.get(w.kind) ?? 0) + 1);
66
+ const parts = [
67
+ ...keys,
68
+ ...(failures.length ? [`${failures.length} fail`] : []),
69
+ ...(warnings.length
70
+ ? [
71
+ `${warnings.length} warn (${[...kinds].map(([k, n]) => (n > 1 ? `${k} ${n}` : k)).join(", ")})`,
72
+ ]
73
+ : []),
74
+ ];
75
+ console.log(`${status.padEnd(5)} ${this.report.label(this.result.url)}${parts.length ? ` ${parts.join(" · ")}` : ""}`);
76
+ for (const f of failures)
77
+ console.log(` ${f.where ? `${f.where}: ` : ""}${f.note}`);
78
+ }
79
+ }
80
+ export class Report {
81
+ pages = [];
82
+ check;
83
+ mode;
84
+ oneSite;
85
+ constructor(check, urls, mode) {
86
+ this.check = check;
87
+ this.mode = mode;
88
+ const origins = new Set(urls.map((u) => {
89
+ try {
90
+ return new URL(u).origin;
91
+ }
92
+ catch {
93
+ return u;
94
+ }
95
+ }));
96
+ this.oneSite = origins.size <= 1;
97
+ }
98
+ /** A line of the full form: printed only there. */
99
+ say(line = "") {
100
+ if (this.mode === "full")
101
+ console.log(line);
102
+ }
103
+ /** How a page is named on its brief line: its path when every page is on one site. */
104
+ label(url) {
105
+ if (!this.oneSite)
106
+ return url;
107
+ try {
108
+ const { pathname, search } = new URL(url);
109
+ return pathname + search;
110
+ }
111
+ catch {
112
+ return url;
113
+ }
114
+ }
115
+ page(url) {
116
+ this.pages.at(-1)?.end();
117
+ const page = new PageReport(this, url);
118
+ this.pages.push(page);
119
+ return page;
120
+ }
121
+ get failures() {
122
+ return this.pages.reduce((a, p) => a + p.result.failures.length, 0);
123
+ }
124
+ get warnings() {
125
+ return this.pages.reduce((a, p) => a + p.result.warnings.length, 0);
126
+ }
127
+ /**
128
+ * The totals, in the chosen form, and the exit code: 1 when anything failed.
129
+ * `fullLine` replaces the full form's usual last line ("" for none).
130
+ */
131
+ done(fullLine) {
132
+ this.pages.at(-1)?.end();
133
+ const [f, w, n] = [this.failures, this.warnings, this.pages.length];
134
+ if (this.mode === "json")
135
+ console.log(JSON.stringify({
136
+ check: this.check,
137
+ failures: f,
138
+ warnings: w,
139
+ pages: this.pages.map((p) => p.result),
140
+ }, null, 2));
141
+ else if (this.mode === "brief")
142
+ console.log(`${n} page${n === 1 ? "" : "s"} · ${f} fail · ${w} warn${w ? " · --full lists the warnings" : ""}`);
143
+ else if (fullLine !== "")
144
+ console.log(fullLine ?? `\n${f} failure(s), ${w} warning(s) on ${n} page(s).`);
145
+ if (f)
146
+ process.exitCode = 1;
147
+ }
148
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a.incantalupo/web-tools",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Checks and captures for any website: readability and contrast, screenshots, style snapshots and diffs, glyph and image checks, a site audit with niche profiles, your own signed-in browser.",
5
5
  "type": "module",
6
6
  "bin": {