trykeyline-browser 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/audit.mjs ADDED
@@ -0,0 +1,231 @@
1
+ /**
2
+ * The audit's machine half: walk every page of a running product at desktop
3
+ * and phone, light and dark; measure contrast, names, targets, overflow, the
4
+ * type actually rendered, copy and the tells of AI slop inside each page; add
5
+ * the detector's findings from the source; draft a score per domain and one
6
+ * out of 10; write keyline-report/ (findings.json, index.html, shots/).
7
+ *
8
+ * The agent's half follows (commands/audit.md): look at the shots, add the
9
+ * findings only judgement can make, settle the scores, write the summary, and
10
+ * re-render with `keyline report`.
11
+ *
12
+ * keyline audit --base http://localhost:3000 [--root .]
13
+ * keyline audit --serve dist
14
+ * keyline audit --base … --quick [--routes /pricing] one page, the quick read
15
+ *
16
+ * Exit codes: 0 done, 1 errors found, 2 a usage error.
17
+ */
18
+ import { existsSync, rmSync } from "node:fs";
19
+ import { resolve } from "node:path";
20
+ import { add, counts, readRun, writeRun } from "./browse/findings.mjs";
21
+ import { shotKey } from "./browse/capture.mjs";
22
+ import { renderDir } from "./browse/report.mjs";
23
+ import { SHIP, draftScore, scoreCaps } from "./browse/score.mjs";
24
+ import { walk } from "./browse/walk.mjs";
25
+ import { parseOrExplain } from "./browse/args.mjs";
26
+ import { target } from "./browse.mjs";
27
+ import { auditProbe } from "./audit/probe.mjs";
28
+ import { check } from "trykeyline/check";
29
+ import { DOMAINS } from "trykeyline/check/rules";
30
+
31
+ const USAGE = `keyline audit — every page, measured, in one report.
32
+
33
+ keyline audit (--base URL | --serve DIR) [options]
34
+
35
+ Options:
36
+ --base <url> the running product
37
+ --serve <dir> serve a static folder instead
38
+ --root <dir> the project's code: routes, and the detector (default: .)
39
+ --out <dir> where the report goes (default: keyline-report)
40
+ --routes <a,b> only these paths
41
+ --limit <n> at most this many pages (default 40)
42
+ --title <name> the product's name, in the report's heading
43
+ --quick one page (the first route, or /), desktop and phone, light only
44
+ --no-check skip the source detector
45
+ --motion leave motion on (default: reduced, so pages are shot settled)
46
+ --headed show the browser
47
+ -h, --help this`;
48
+
49
+ /** The six law domains the scores are kept for, and where the audit's own rules fall among them. */
50
+ export const SCORED = DOMAINS;
51
+ export { SHIP, draftScore, scoreCaps };
52
+ const SCORE_DOMAIN = {
53
+ a11y: "patterns",
54
+ copy: "patterns",
55
+ states: "patterns",
56
+ runtime: "patterns",
57
+ "a11y/target-size": "layout",
58
+ "a11y/headings": "type",
59
+ "color/contrast": "color",
60
+ "slop/gradient-text": "color",
61
+ "slop/purple-gradient": "color",
62
+ "slop/glass-everywhere": "depth",
63
+ "slop/card-grid": "depth",
64
+ "slop/eyebrows": "type",
65
+ "slop/emoji-bullets": "patterns",
66
+ "slop/generic-copy": "patterns",
67
+ "slop/placeholder-brands": "patterns",
68
+ };
69
+
70
+ export const FIX = {
71
+ type: "/keyline type",
72
+ color: "/keyline color",
73
+ layout: "/keyline layout",
74
+ depth: "/keyline depth",
75
+ motion: "/keyline motion",
76
+ patterns: "/keyline patterns",
77
+ };
78
+
79
+ export function scoreDomain(f) {
80
+ const domain = f.domain ?? f.rule.split("/")[0];
81
+ return SCORE_DOMAIN[f.rule] ?? (SCORED.includes(domain) ? domain : SCORE_DOMAIN[domain] ?? "patterns");
82
+ }
83
+
84
+ /**
85
+ * A draft score per domain from the findings: 4 with nothing to report, down
86
+ * by each distinct rule broken (an error 1.5, a warning 0.75, a note 0.15),
87
+ * plus up to 1 more for how many places break it. The agent settles the
88
+ * real score; the draft keeps a mechanical floor under the judgement.
89
+ */
90
+ export function draftScores(findings) {
91
+ const scores = {};
92
+ for (const d of SCORED) {
93
+ const rules = new Map();
94
+ for (const f of findings) {
95
+ if (f.status === "dismissed" || f.status === "fixed" || scoreDomain(f) !== d) continue;
96
+ const w = f.severity === "error" ? 1.5 : f.severity === "warning" ? 0.75 : 0.15;
97
+ const r = rules.get(f.rule) ?? { w: 0, n: 0 };
98
+ rules.set(f.rule, { w: Math.max(r.w, w), n: r.n + 1 });
99
+ }
100
+ // Each rule broken costs its weight once, plus a little for how widely it's broken.
101
+ const penalty = [...rules.values()].reduce((sum, r) => sum + r.w + Math.min(1, (r.n - 1) * 0.1), 0);
102
+ scores[d] = Math.max(0, Math.min(4, Math.round(4 - penalty)));
103
+ }
104
+ return scores;
105
+ }
106
+
107
+ /**
108
+ * The scores of earlier runs in the same folder over the same pages, oldest
109
+ * first, so a polish loop shows its progress (6 → 7.5 → 8.5). A run over other
110
+ * pages starts a new history.
111
+ */
112
+ export function carryHistory(out, routes) {
113
+ let prev;
114
+ try {
115
+ prev = readRun(out);
116
+ } catch {
117
+ return [];
118
+ }
119
+ if (prev.kind !== "audit" || typeof prev.score !== "number") return [];
120
+ const same = (a, b) => a.length === b.length && a.every((r, i) => r === b[i]);
121
+ if (!same([...(prev.pages ?? [])].map((p) => p.route).sort(), [...routes].sort())) return [];
122
+ return [...(prev.history ?? []), prev.score];
123
+ }
124
+
125
+ /** The detector's findings, as report findings pointing at source lines. Its walk already skips reports, dependencies and build output. */
126
+ export function sourceFindings(run, root, ignores = []) {
127
+ const result = check({ root, paths: ["."], ignores });
128
+ for (const f of result.findings) {
129
+ const [title, ...rest] = f.message.split(/(?<=\.)\s+/);
130
+ add(run, {
131
+ kind: "check",
132
+ rule: f.rule,
133
+ domain: f.domain,
134
+ law: f.law,
135
+ severity: f.severity,
136
+ title: title.replace(/\.$/, ""),
137
+ detail: rest.join(" ") || undefined,
138
+ file: f.file,
139
+ line: f.line,
140
+ fix: FIX[f.domain],
141
+ });
142
+ }
143
+ return result;
144
+ }
145
+
146
+ export const AUDIT_OPTIONS = {
147
+ values: ["base", "serve", "root", "out", "routes", "limit", "title"],
148
+ switches: ["quick", "no-check", "motion", "headed"],
149
+ };
150
+
151
+ export async function run(argv) {
152
+ const opts = parseOrExplain("audit", argv, AUDIT_OPTIONS);
153
+ if (!opts) return 2;
154
+ if (opts._.length) {
155
+ console.error(`keyline audit: no command '${opts._[0]}' (try --help)`);
156
+ return 2;
157
+ }
158
+ if (opts.help) {
159
+ console.log(USAGE);
160
+ return 0;
161
+ }
162
+ const t = await target(opts);
163
+ if (!t) {
164
+ console.error("audit needs --base <url> or --serve <dir>\n");
165
+ console.error(USAGE);
166
+ return 2;
167
+ }
168
+ const out = resolve(opts.out ?? "keyline-report");
169
+ if (existsSync(`${out}/shots`)) rmSync(`${out}/shots`, { recursive: true });
170
+ const quick = Boolean(opts.quick);
171
+ const routes = opts.routes ? String(opts.routes).split(",").map((s) => s.trim()) : quick ? ["/"] : null;
172
+
173
+ try {
174
+ const signatures = new Map();
175
+ const result = await walk({
176
+ kind: "audit",
177
+ title: opts.title ?? null,
178
+ base: t.base,
179
+ root: t.root,
180
+ out,
181
+ routes: quick ? routes.slice(0, 1) : routes,
182
+ limit: quick ? 1 : Number(opts.limit ?? 40),
183
+ viewports: ["desktop", "phone"],
184
+ themes: quick ? ["light"] : ["light", "dark"],
185
+ headless: !opts.headed,
186
+ // Shot and measured as a reader sees the page once it settles: opening sequences and
187
+ // scroll reveals done. --motion audits with motion on, as a first visit plays it.
188
+ reducedMotion: !opts.motion,
189
+ // Structure, type, copy and slop are measured once per page, on the first (desktop, light) pass.
190
+ probeFor: (viewport, theme) => [{ name: "audit", fn: auditProbe, arg: { viewport, theme, firstPass: viewport === "desktop" && theme === "light" } }],
191
+ judge: (run, v) => {
192
+ const raw = v.results.audit;
193
+ // A page without a dark theme renders the same colours in the dark pass; skip its repeats.
194
+ const meta = Array.isArray(raw) ? raw.find((f) => f.meta) : null;
195
+ if (meta) {
196
+ const key = `${v.route}|${v.viewport}`;
197
+ if (v.theme === "light") signatures.set(key, meta.signature);
198
+ else if (signatures.get(key) === meta.signature) return;
199
+ }
200
+ if (!Array.isArray(raw)) {
201
+ if (raw?.error) add(run, { rule: "runtime/probe-failed", severity: "info", title: "The audit's checks couldn't run on this page", evidence: raw.error, page: v.route, viewport: v.viewport, theme: v.theme });
202
+ return;
203
+ }
204
+ for (const f of raw.filter((f) => !f.meta)) {
205
+ add(run, {
206
+ ...f,
207
+ kind: "audit",
208
+ page: v.route,
209
+ viewport: v.viewport,
210
+ theme: v.theme,
211
+ shot: v.shot && f.box ? shotKey(v.viewport, v.theme) : undefined,
212
+ fix: f.fix ?? FIX[scoreDomain(f)],
213
+ });
214
+ }
215
+ },
216
+ });
217
+
218
+ if (!opts["no-check"] && t.root && existsSync(t.root)) sourceFindings(result, t.root);
219
+ result.scores = draftScores(result.findings);
220
+ result.score = draftScore(result.scores, result.findings);
221
+ result.history = carryHistory(out, result.pages.map((p) => p.route));
222
+ result.scoresDraft = true;
223
+ writeRun(out, result);
224
+ const file = renderDir(out);
225
+ const c = counts(result.findings);
226
+ console.log(`\n${result.pages.length} ${result.pages.length === 1 ? "page" : "pages"} · ${c.error} errors · ${c.warning} warnings · ${c.info} notes\n${file}`);
227
+ return c.error ? 1 : 0;
228
+ } finally {
229
+ await t.stop();
230
+ }
231
+ }
@@ -0,0 +1,79 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Keyline's browser tools, a separate package so the core (`trykeyline`) and
4
+ * its skill stay free of Playwright. `npx trykeyline audit …` runs this.
5
+ *
6
+ * trykeyline-browser audit (--base URL | --serve DIR) [options]
7
+ * trykeyline-browser smoke (--base URL | --serve DIR) [options]
8
+ * trykeyline-browser pages | capture | report [options]
9
+ * trykeyline-browser probe <name> [--arg JSON]
10
+ *
11
+ * Exit codes: 0 done, 1 errors found, 2 a usage error.
12
+ */
13
+ import { readFileSync, realpathSync } from "node:fs";
14
+ import { fileURLToPath } from "node:url";
15
+ import { parseOrExplain } from "../browse/args.mjs";
16
+
17
+ const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
18
+
19
+ const USAGE = `trykeyline-browser ${version} — Keyline's browser tools (also: npx trykeyline <command>).
20
+
21
+ audit (--base URL | --serve DIR) every page measured, with the detector's findings, in one report
22
+ smoke (--base URL | --serve DIR) click through the product and report broken flows
23
+ pages the pages it would visit
24
+ capture (--base URL | --serve DIR) visit, screenshot and report load errors
25
+ report [DIR] [--compare DIR] re-render a report, or mark what changed since another
26
+ probe <name> [--arg JSON] print a page check to run in your own browser
27
+
28
+ Each takes --help. Playwright loads from the project, or installs once into
29
+ ~/.cache/keyline, when a command first needs a browser.`;
30
+
31
+ export async function main(argv) {
32
+ const [cmd, ...rest] = argv;
33
+ if (cmd === "audit") return (await import("../audit.mjs")).run(rest);
34
+ if (cmd === "smoke") return (await import("../smoke.mjs")).run(rest);
35
+ if (cmd === "pages" || cmd === "capture" || cmd === "report") return (await import("../browse.mjs")).run(argv);
36
+ if (cmd === "probe") {
37
+ const opts = parseOrExplain("probe", rest, { values: ["arg"] });
38
+ if (!opts) return 2;
39
+ const { PROBES, probeExpression } = await import("../probe.mjs");
40
+ if (opts.help || !opts._[0]) {
41
+ console.log(`keyline probe <name> [--arg JSON] — one expression for your browser's JavaScript tool.\n\nProbes: ${PROBES.join(", ")}`);
42
+ return opts.help ? 0 : 2;
43
+ }
44
+ try {
45
+ console.log(probeExpression(opts._[0], opts.arg ? JSON.parse(opts.arg) : undefined));
46
+ return 0;
47
+ } catch (err) {
48
+ console.error(`keyline probe: ${err.message}`);
49
+ return 2;
50
+ }
51
+ }
52
+ if (cmd === "-v" || cmd === "--version") {
53
+ console.log(version);
54
+ return 0;
55
+ }
56
+ if (!cmd || cmd === "-h" || cmd === "--help") {
57
+ console.log(USAGE);
58
+ return cmd ? 0 : 2;
59
+ }
60
+ console.error(`trykeyline-browser: no command '${cmd}'\n\n${USAGE}`);
61
+ return 2;
62
+ }
63
+
64
+ const isMain = () => {
65
+ try {
66
+ return process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
67
+ } catch {
68
+ return false;
69
+ }
70
+ };
71
+ if (isMain()) {
72
+ main(process.argv.slice(2)).then(
73
+ (code) => process.exit(code),
74
+ (err) => {
75
+ console.error(err?.stack ?? err);
76
+ process.exit(2);
77
+ },
78
+ );
79
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Arguments for the browser tools. Each command names the options it takes:
3
+ * `values` take one (`--base URL` or `--base=URL`, split at the first `=`
4
+ * only, so a URL keeps its query), `switches` take none. Anything else that
5
+ * starts with a dash is an error, so a typo (`--bsae`) is never dropped in
6
+ * silence. `-h` and `--help` are always known.
7
+ *
8
+ * @returns {{ _: string[], [option: string]: string | boolean | string[] } | { error: string }}
9
+ */
10
+ export function parseArgs(argv, { values = [], switches = [] } = {}) {
11
+ const opts = { _: [] };
12
+ for (let i = 0; i < argv.length; i++) {
13
+ const a = argv[i];
14
+ if (a === "-h" || a === "--help") {
15
+ opts.help = true;
16
+ continue;
17
+ }
18
+ if (!a.startsWith("-") || a === "-") {
19
+ opts._.push(a);
20
+ continue;
21
+ }
22
+ const eq = a.indexOf("=");
23
+ const name = a.startsWith("--") ? (eq > 0 ? a.slice(2, eq) : a.slice(2)) : a;
24
+ if (switches.includes(name)) {
25
+ if (eq > 0) return { error: `--${name} takes no value` };
26
+ opts[name] = true;
27
+ } else if (values.includes(name)) {
28
+ const value = eq > 0 ? a.slice(eq + 1) : argv[++i];
29
+ if (value === undefined || value === "" || (eq < 0 && value.startsWith("--"))) return { error: `--${name} needs a value` };
30
+ opts[name] = value;
31
+ } else {
32
+ return { error: `unknown option ${a.startsWith("--") ? `--${name}` : a}` };
33
+ }
34
+ }
35
+ return opts;
36
+ }
37
+
38
+ /** Parse, or print why not and a pointer to --help. Returns null on a usage error (the caller exits 2). */
39
+ export function parseOrExplain(command, argv, spec) {
40
+ const opts = parseArgs(argv, spec);
41
+ if (!opts.error) return opts;
42
+ console.error(`keyline ${command}: ${opts.error} (try --help)`);
43
+ return null;
44
+ }
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Visit a page the way a reader would, and keep what the run needs: the HTTP
3
+ * status, console errors, uncaught exceptions, failed requests, the links the
4
+ * page actually rendered, a full-page screenshot, and whatever the caller's
5
+ * probes measure inside the page.
6
+ *
7
+ * A probe is `{ name, fn }`: `fn` runs in the page (Playwright's
8
+ * `page.evaluate`) after the page has settled and been scrolled through, and
9
+ * returns plain data. The audit's checks and the smoke test's element
10
+ * inventory are probes; the core knows nothing about either.
11
+ */
12
+ import { mkdirSync } from "node:fs";
13
+ import { dirname, join } from "node:path";
14
+ import { linkPath } from "./routes.mjs";
15
+
16
+ export const VIEWPORTS = {
17
+ desktop: { name: "desktop", width: 1440, height: 900, isMobile: false, hasTouch: false },
18
+ phone: { name: "phone", width: 390, height: 844, isMobile: true, hasTouch: true },
19
+ };
20
+
21
+ export const THEMES = ["light", "dark"];
22
+
23
+ /** A screenshot taller than this is clipped: a 40,000px page is a bug, not a picture. */
24
+ const MAX_SHOT_HEIGHT = 9000;
25
+
26
+ export function shotKey(viewport, theme) {
27
+ return `${viewport}-${theme}`;
28
+ }
29
+
30
+ export function shotFile(route, viewport, theme) {
31
+ const slug = route === "/" ? "home" : route.replace(/^\//, "").replace(/[^a-z0-9]+/gi, "-").replace(/-+$/, "").toLowerCase();
32
+ return join("shots", `${slug}--${viewport}-${theme}.png`);
33
+ }
34
+
35
+ /**
36
+ * One browser context per viewport × theme: colour scheme and touch are
37
+ * context-wide, and a fresh context means no state leaks between passes.
38
+ */
39
+ export async function openContext(browser, { viewport = "desktop", theme = "light", reducedMotion = false, storageState } = {}) {
40
+ const vp = VIEWPORTS[viewport] ?? viewport;
41
+ return browser.newContext({
42
+ viewport: { width: vp.width, height: vp.height },
43
+ isMobile: vp.isMobile,
44
+ hasTouch: vp.hasTouch,
45
+ colorScheme: theme,
46
+ reducedMotion: reducedMotion ? "reduce" : "no-preference",
47
+ deviceScaleFactor: 1,
48
+ storageState,
49
+ });
50
+ }
51
+
52
+ /** Scroll to the bottom in steps and back, so lazy images and reveal-on-scroll content are present. */
53
+ async function settle(page) {
54
+ await page.evaluate(async () => {
55
+ const step = Math.max(400, Math.floor(window.innerHeight * 0.8));
56
+ const wait = (ms) => new Promise((r) => setTimeout(r, ms));
57
+ for (let y = 0; y < document.documentElement.scrollHeight && y < 40000; y += step) {
58
+ window.scrollTo(0, y);
59
+ await wait(60);
60
+ }
61
+ window.scrollTo(0, 0);
62
+ await wait(120);
63
+ await document.fonts?.ready;
64
+ // Let finite animations land (an opening sequence, a reveal), up to 4s, so the page is shot as it settles.
65
+ const finite = document.getAnimations().filter((a) => a.effect?.getComputedTiming().endTime !== Infinity);
66
+ await Promise.race([Promise.all(finite.map((a) => a.finished.catch(() => {}))), wait(4000)]);
67
+ });
68
+ }
69
+
70
+ /**
71
+ * Wire a page's listeners. Returned arrays fill as the page runs, so a smoke
72
+ * step can read them before and after a click.
73
+ */
74
+ export function listen(page, origin) {
75
+ const log = { console: [], pageErrors: [], failedRequests: [] };
76
+ page.on("console", (msg) => {
77
+ if (msg.type() === "error" || msg.type() === "warning") log.console.push({ type: msg.type(), text: msg.text().slice(0, 500), at: msg.location()?.url ?? null });
78
+ });
79
+ page.on("pageerror", (err) => log.pageErrors.push({ text: String(err?.message ?? err).slice(0, 500) }));
80
+ page.on("requestfailed", (req) => {
81
+ const failure = req.failure()?.errorText ?? "failed";
82
+ if (/ERR_ABORTED/.test(failure)) return; // navigations and cancelled prefetches
83
+ log.failedRequests.push({ url: req.url(), method: req.method(), status: null, error: failure, sameOrigin: req.url().startsWith(origin) });
84
+ });
85
+ page.on("response", (res) => {
86
+ if (res.status() >= 400) log.failedRequests.push({ url: res.url(), method: res.request().method(), status: res.status(), error: null, sameOrigin: res.url().startsWith(origin) });
87
+ });
88
+ return log;
89
+ }
90
+
91
+ /**
92
+ * Visit one route in an open context. Returns the page record for
93
+ * findings.json plus the raw logs and probe results for the caller to judge.
94
+ */
95
+ export async function visit(context, { base, route, out, viewport = "desktop", theme = "light", probes = [], shoot = true, timeout = 30000 }) {
96
+ const page = await context.newPage();
97
+ const origin = new URL(base).origin;
98
+ const log = listen(page, origin);
99
+ const url = new URL(route, base).href;
100
+ let status = null;
101
+ let navError = null;
102
+ try {
103
+ const res = await page.goto(url, { waitUntil: "load", timeout });
104
+ status = res?.status() ?? null;
105
+ await page.waitForLoadState("networkidle", { timeout: 5000 }).catch(() => {});
106
+ await settle(page);
107
+ } catch (err) {
108
+ navError = String(err?.message ?? err).split("\n")[0];
109
+ }
110
+
111
+ const title = await page.title().catch(() => "");
112
+ const finalUrl = page.url();
113
+ const links = navError
114
+ ? []
115
+ : [
116
+ ...new Set(
117
+ (await page.$$eval("a[href]", (as) => as.map((a) => a.getAttribute("href"))).catch(() => []))
118
+ .map((h) => linkPath(h, finalUrl, origin))
119
+ .filter(Boolean),
120
+ ),
121
+ ];
122
+
123
+ const results = {};
124
+ if (!navError) {
125
+ for (const probe of probes) {
126
+ try {
127
+ results[probe.name] = await page.evaluate(probe.fn, probe.arg);
128
+ } catch (err) {
129
+ results[probe.name] = { error: String(err?.message ?? err).split("\n")[0] };
130
+ }
131
+ }
132
+ }
133
+
134
+ let shot = null;
135
+ if (shoot && !navError) {
136
+ const file = shotFile(route, viewport, theme);
137
+ mkdirSync(dirname(join(out, file)), { recursive: true });
138
+ const size = await page.evaluate(() => ({ w: document.documentElement.clientWidth, h: document.documentElement.scrollHeight }));
139
+ const height = Math.min(size.h, MAX_SHOT_HEIGHT);
140
+ await page.screenshot({ path: join(out, file), fullPage: true, animations: "disabled", clip: { x: 0, y: 0, width: size.w, height } });
141
+ shot = { path: file, width: size.w, height, clipped: size.h > MAX_SHOT_HEIGHT };
142
+ }
143
+
144
+ await page.close();
145
+ return { route, url, finalUrl, title, status, navError, links, log, results, shot, viewport, theme };
146
+ }
147
+
148
+ /** Selector for an element, short enough to read and stable enough to find again. Runs in the page. */
149
+ export const SELECTOR_HELPER = `
150
+ window.__keylineSelector = function (el) {
151
+ if (!(el instanceof Element)) return null;
152
+ if (el.id && /^[A-Za-z][\\w-]*$/.test(el.id)) return '#' + el.id;
153
+ const parts = [];
154
+ while (el && el.nodeType === 1 && parts.length < 5) {
155
+ let part = el.localName;
156
+ const testId = el.getAttribute('data-testid');
157
+ if (testId) { parts.unshift(part + '[data-testid="' + testId + '"]'); break; }
158
+ const cls = [...el.classList].filter((c) => /^[A-Za-z][\\w-]*$/.test(c) && c.length < 30).slice(0, 2);
159
+ if (cls.length) part += '.' + cls.join('.');
160
+ const parent = el.parentElement;
161
+ if (parent) {
162
+ const same = [...parent.children].filter((c) => c.localName === el.localName);
163
+ if (same.length > 1) part += ':nth-of-type(' + (same.indexOf(el) + 1) + ')';
164
+ }
165
+ parts.unshift(part);
166
+ if (el.id) break;
167
+ el = parent;
168
+ }
169
+ return parts.join(' > ');
170
+ };
171
+ window.__keylineBox = function (el) {
172
+ const r = el.getBoundingClientRect();
173
+ return { x: Math.round(r.left + window.scrollX), y: Math.round(r.top + window.scrollY), w: Math.round(r.width), h: Math.round(r.height) };
174
+ };
175
+ `;
176
+
177
+ /** Install the helpers on every page of a context, before any probe runs. */
178
+ export async function withHelpers(context) {
179
+ await context.addInitScript(SELECTOR_HELPER);
180
+ return context;
181
+ }