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.
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Walk a running product: every route × viewport × theme, one fresh browser
3
+ * context per pass. The first pass also follows the links each page renders,
4
+ * so a client-side app's pages are found even when its server HTML shows none.
5
+ *
6
+ * `walk()` returns a run (see findings.mjs) with the pages, their shots and the
7
+ * runtime findings every walk can make: pages that fail to load, error
8
+ * statuses, console errors, uncaught exceptions and failed requests. Callers
9
+ * pass `probes` to measure more inside each page and `judge` to turn what they
10
+ * measured into findings: the audit and the smoke test are both a walk plus
11
+ * their own probes and judges. `probeFor(viewport, theme, route)` adds probes
12
+ * that depend on the pass.
13
+ */
14
+ import { add, newRun } from "./findings.mjs";
15
+ import { THEMES, openContext, shotKey, visit, withHelpers } from "./capture.mjs";
16
+ import { discover } from "./routes.mjs";
17
+ import { launch } from "./playwright.mjs";
18
+
19
+ export async function walk({
20
+ kind = "capture",
21
+ title = null,
22
+ base,
23
+ root = null,
24
+ out,
25
+ routes = null,
26
+ limit = 40,
27
+ viewports = ["desktop", "phone"],
28
+ themes = THEMES,
29
+ probes = [],
30
+ probeFor = null,
31
+ judge = null,
32
+ headless = true,
33
+ reducedMotion = false,
34
+ // Optional, for callers that drive more than a walk (the smoke test):
35
+ browser: shared = null, // a browser already launched; left open
36
+ storageState = undefined, // a signed-in session for every context
37
+ prepare = null, // async (context, { viewport, theme }) before any page opens: route guards, init scripts
38
+ follow = () => true, // (path) => whether to follow a link the page rendered
39
+ log = (m) => process.stderr.write(m + "\n"),
40
+ }) {
41
+ const run = newRun({ kind, title, base, root });
42
+ const found = routes ? { routes: routes.map((path) => ({ path, sources: ["given"] })), dynamic: [] } : await discover({ root, base, limit });
43
+ const queue = found.routes.map((r) => r.path);
44
+ const known = new Set(queue);
45
+ for (const d of found.dynamic) {
46
+ if (d.sample && !known.has(d.sample)) {
47
+ queue.push(d.sample);
48
+ known.add(d.sample);
49
+ }
50
+ }
51
+ run.dynamic = found.dynamic.map((d) => ({ path: d.path, sample: d.sample, file: d.file ?? null }));
52
+
53
+ const browser = shared ?? (await launch({ root: root ?? process.cwd(), headless, log }));
54
+ const pages = new Map();
55
+ try {
56
+ let first = true;
57
+ for (const viewport of viewports) {
58
+ for (const theme of themes) {
59
+ const context = await withHelpers(await openContext(browser, { viewport, theme, reducedMotion, storageState }));
60
+ if (prepare) await prepare(context, { viewport, theme });
61
+ for (let i = 0; i < queue.length; i++) {
62
+ const route = queue[i];
63
+ log(` ${viewport} ${theme} ${route}`);
64
+ const v = await visit(context, { base, route, out, viewport, theme, probes: probeFor ? [...probes, ...probeFor(viewport, theme, route)] : probes });
65
+ if (first) {
66
+ for (const link of v.links) {
67
+ if (!known.has(link) && known.size < limit && follow(link)) {
68
+ known.add(link);
69
+ queue.push(link);
70
+ }
71
+ }
72
+ }
73
+ const page = pages.get(route) ?? { route, url: v.url, title: v.title, status: v.status, finalUrl: v.finalUrl, shots: {} };
74
+ if (v.shot) page.shots[shotKey(viewport, theme)] = v.shot;
75
+ pages.set(route, page);
76
+ runtimeFindings(run, v, first);
77
+ if (judge) await judge(run, v);
78
+ }
79
+ await context.close();
80
+ first = false;
81
+ }
82
+ }
83
+ } finally {
84
+ if (!shared) await browser.close();
85
+ }
86
+ run.pages = [...pages.values()];
87
+ return run;
88
+ }
89
+
90
+ /** What any walk can say about a page from its load alone. Console and network only on the first pass, so one bug isn't reported four times. */
91
+ export function runtimeFindings(run, v, firstPass) {
92
+ const at = { page: v.route, viewport: v.viewport, theme: v.theme, shot: v.shot ? shotKey(v.viewport, v.theme) : undefined };
93
+ if (v.navError) {
94
+ add(run, { ...at, rule: "runtime/load-failed", severity: "error", title: "The page didn't load", evidence: v.navError, detail: "Opening this URL failed or timed out, so nothing on it could be checked." });
95
+ return;
96
+ }
97
+ if (v.status >= 400) {
98
+ add(run, { ...at, rule: "runtime/http-status", severity: "error", title: `The page answers ${v.status}`, evidence: `HTTP ${v.status}`, detail: "A route the product links to or declares returns an error status." });
99
+ }
100
+ if (!firstPass) return;
101
+ for (const e of v.log.pageErrors) {
102
+ add(run, { ...at, rule: "runtime/exception", severity: "error", title: "An uncaught exception on load", evidence: e.text, detail: "Script threw while the page loaded. Whatever ran after it may be missing." });
103
+ }
104
+ // The browser logs every failed request as a console error too; those are reported once, as requests.
105
+ for (const e of v.log.console.filter((c) => c.type === "error" && !/^Failed to load resource/.test(c.text))) {
106
+ add(run, { ...at, rule: "runtime/console-error", severity: "warning", title: "A console error on load", evidence: e.text });
107
+ }
108
+ for (const r of v.log.failedRequests) {
109
+ add(run, {
110
+ ...at,
111
+ rule: "runtime/request-failed",
112
+ severity: r.sameOrigin ? "error" : "warning",
113
+ title: r.sameOrigin ? "A request to the product failed" : "A third-party request failed",
114
+ evidence: `${r.method} ${r.url.slice(0, 160)} → ${r.status ?? r.error}`,
115
+ });
116
+ }
117
+ }
package/browse.mjs ADDED
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Keyline's browser tools: the pages a product has, a walk through them, and
3
+ * the report. The audit and the smoke test are built on these.
4
+ *
5
+ * keyline pages [--root .] [--base URL] [--json]
6
+ * keyline capture (--base URL | --serve DIR) [--root .] [--out keyline-report]
7
+ * keyline report [DIR] [--compare PREVIOUS-DIR]
8
+ *
9
+ * Exit codes: 0 done, 1 the walk found errors, 2 a usage error.
10
+ */
11
+ import { existsSync, rmSync } from "node:fs";
12
+ import { resolve } from "node:path";
13
+ import { parseOrExplain } from "./browse/args.mjs";
14
+ import { counts, writeRun } from "./browse/findings.mjs";
15
+ import { renderDir } from "./browse/report.mjs";
16
+ import { compareDirs } from "./browse/compare.mjs";
17
+ import { discover } from "./browse/routes.mjs";
18
+ import { serve } from "./browse/serve.mjs";
19
+ import { walk } from "./browse/walk.mjs";
20
+
21
+ const USAGE = `keyline browse — find a product's pages, walk them, and report.
22
+
23
+ keyline pages [--root .] [--base URL] [--json]
24
+ Every route: from the router's files, the sitemap and a crawl.
25
+
26
+ keyline capture (--base URL | --serve DIR) [options]
27
+ Visit every page at desktop and phone, light and dark; screenshot each,
28
+ record load failures, error statuses, console errors, exceptions and
29
+ failed requests; write findings.json and index.html.
30
+
31
+ keyline report [DIR] [--compare PREVIOUS-DIR]
32
+ Re-render DIR/index.html from DIR/findings.json (default keyline-report).
33
+ With --compare, first mark each finding new, still or back since the
34
+ run in PREVIOUS-DIR, list what was fixed, and diff the screenshots.
35
+
36
+ Options:
37
+ --base <url> the running product, e.g. http://localhost:3000
38
+ --serve <dir> serve a static folder on a free port instead
39
+ --root <dir> the project's code, for routes (default: .)
40
+ --out <dir> where the report goes (default: keyline-report)
41
+ --routes <a,b> only these paths
42
+ --limit <n> at most this many pages (default 40)
43
+ --viewports <list> desktop,phone (default both)
44
+ --themes <list> light,dark (default both)
45
+ --headed show the browser
46
+ --json pages as JSON
47
+ --compare <dir> an earlier report to compare with (report, capture)
48
+ --threshold <pct> a page whose screenshot changed more than this gets a
49
+ visual/changed note (default 0.01; one changed heading
50
+ on a 1440×900 page is about 0.08)
51
+ --no-diff compare findings only, not screenshots
52
+ -h, --help this`;
53
+
54
+ /** What pages, capture and report take. */
55
+ export const BROWSE_OPTIONS = {
56
+ values: ["base", "serve", "root", "out", "routes", "limit", "viewports", "themes", "compare", "threshold"],
57
+ switches: ["headed", "json", "no-diff"],
58
+ };
59
+
60
+ const list = (v, fallback) => (v ? String(v).split(",").map((s) => s.trim()).filter(Boolean) : fallback);
61
+
62
+ /** The base URL to walk: the one given, or a static server over --serve. */
63
+ export async function target(opts) {
64
+ if (opts.base) return { base: opts.base, root: resolve(opts.root ?? "."), stop: async () => {} };
65
+ if (opts.serve) {
66
+ const dir = resolve(opts.serve);
67
+ if (!existsSync(dir)) throw new Error(`no folder ${opts.serve}`);
68
+ const s = await serve(dir);
69
+ return { base: s.url, root: resolve(opts.root ?? dir), stop: s.close };
70
+ }
71
+ return null;
72
+ }
73
+
74
+ /** Why `--compare` can't run, or null. A capture writes over its own folder, so the earlier run must live elsewhere. */
75
+ function compareProblem(dir, prev, { before = false } = {}) {
76
+ const p = resolve(prev);
77
+ if (p === dir) return `--compare needs an earlier report in another folder: ${before ? "a capture writes over its own, so copy it first (cp -R keyline-report keyline-report-before) or pass --out" : "this is the same one"}`;
78
+ if (!existsSync(`${p}/findings.json`)) return `no findings.json in ${prev} to compare with`;
79
+ return null;
80
+ }
81
+
82
+ const compareOptions = (opts) => ({ diff: !opts["no-diff"], threshold: Number(opts.threshold ?? 0.01) });
83
+
84
+ function sinceLine(run) {
85
+ const c = run.compare;
86
+ const v = c.visual;
87
+ return `Since ${c.against}: ${c.new} new · ${c.returned} back · ${c.still} still · ${c.fixed} fixed${v ? ` · ${v.changed} of ${v.compared} screenshots changed` : ""}`;
88
+ }
89
+
90
+ export async function run(argv) {
91
+ const opts = parseOrExplain(["pages", "capture", "report"].includes(argv[0]) ? argv[0] : "browse", argv, BROWSE_OPTIONS);
92
+ if (!opts) return 2;
93
+ const [cmd, arg] = opts._;
94
+ if (opts.help || !cmd) {
95
+ console.log(USAGE);
96
+ return cmd ? 0 : 2;
97
+ }
98
+
99
+ if (cmd === "report") {
100
+ const dir = resolve(arg ?? opts.out ?? "keyline-report");
101
+ if (opts.compare) {
102
+ const err = compareProblem(dir, opts.compare);
103
+ if (err) {
104
+ console.error(err);
105
+ return 2;
106
+ }
107
+ const run = await compareDirs(dir, resolve(opts.compare), compareOptions(opts));
108
+ console.log(sinceLine(run));
109
+ }
110
+ console.log(renderDir(dir));
111
+ return 0;
112
+ }
113
+
114
+ if (cmd === "pages") {
115
+ const t = await target(opts);
116
+ const found = await discover({ root: t?.root ?? resolve(opts.root ?? "."), base: t?.base ?? null, limit: Number(opts.limit ?? 200) });
117
+ await t?.stop();
118
+ if (opts.json) {
119
+ console.log(JSON.stringify(found, null, 2));
120
+ return 0;
121
+ }
122
+ for (const r of found.routes) console.log(`${r.path.padEnd(40)} ${r.sources.join(", ")}`);
123
+ if (found.dynamic.length) {
124
+ console.log(`\nNeed an example to visit:`);
125
+ for (const d of found.dynamic) console.log(`${d.path.padEnd(40)} ${d.sample ? `→ ${d.sample}` : "no example found"}`);
126
+ }
127
+ return 0;
128
+ }
129
+
130
+ if (cmd === "capture") {
131
+ const t = await target(opts);
132
+ if (!t) {
133
+ console.error("capture needs --base <url> or --serve <dir>\n");
134
+ console.error(USAGE);
135
+ return 2;
136
+ }
137
+ const out = resolve(opts.out ?? "keyline-report");
138
+ if (opts.compare) {
139
+ const err = compareProblem(out, opts.compare, { before: true });
140
+ if (err) {
141
+ await t.stop();
142
+ console.error(err);
143
+ return 2;
144
+ }
145
+ }
146
+ if (existsSync(`${out}/shots`)) rmSync(`${out}/shots`, { recursive: true });
147
+ if (existsSync(`${out}/diffs`)) rmSync(`${out}/diffs`, { recursive: true });
148
+ try {
149
+ const result = await walk({
150
+ kind: "capture",
151
+ base: t.base,
152
+ root: t.root,
153
+ out,
154
+ routes: opts.routes ? list(opts.routes) : null,
155
+ limit: Number(opts.limit ?? 40),
156
+ viewports: list(opts.viewports, ["desktop", "phone"]),
157
+ themes: list(opts.themes, ["light", "dark"]),
158
+ headless: !opts.headed,
159
+ });
160
+ writeRun(out, result);
161
+ const final = opts.compare ? await compareDirs(out, resolve(opts.compare), compareOptions(opts)) : result;
162
+ const file = renderDir(out);
163
+ const c = counts(final.findings);
164
+ // Against an earlier run, only errors this run added fail it, as with the detector's baseline.
165
+ const failing = final.compare ? counts(final.findings.filter((f) => f.change === "new" || f.change === "returned")) : c;
166
+ console.log(`\n${final.pages.length} pages · ${c.error} errors · ${c.warning} warnings · ${c.info} notes${final.compare ? `\n${sinceLine(final)}` : ""}\n${file}`);
167
+ return failing.error ? 1 : 0;
168
+ } finally {
169
+ await t.stop();
170
+ }
171
+ }
172
+
173
+ console.error(`no command '${cmd}'\n\n${USAGE}`);
174
+ return 2;
175
+ }
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "trykeyline-browser",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.0",
4
+ "description": "Keyline's browser tools: find a product's pages, walk them at desktop and phone in light and dark, and report what the audit and the smoke test find. Run through `npx trykeyline audit|smoke|pages|capture|report|probe`.",
5
+ "keywords": [
6
+ "design",
7
+ "ui",
8
+ "accessibility",
9
+ "audit",
10
+ "smoke-test",
11
+ "playwright",
12
+ "agent-skills",
13
+ "claude-code"
14
+ ],
15
+ "homepage": "https://github.com/Mihirmodi27/keyline#readme",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/Mihirmodi27/keyline.git",
19
+ "directory": "packages/browser"
20
+ },
21
+ "license": "MIT",
22
+ "author": "Mihir Modi (https://modimihir.com)",
23
+ "type": "module",
24
+ "bin": {
25
+ "trykeyline-browser": "bin/trykeyline-browser.mjs"
26
+ },
27
+ "files": [
28
+ "bin",
29
+ "browse",
30
+ "smoke",
31
+ "audit",
32
+ "browse.mjs",
33
+ "smoke.mjs",
34
+ "audit.mjs",
35
+ "probe.mjs"
36
+ ],
37
+ "engines": {
38
+ "node": ">=18"
39
+ },
40
+ "dependencies": {
41
+ "trykeyline": "0.3.0"
42
+ },
43
+ "peerDependencies": {
44
+ "playwright": "^1.40.0"
45
+ },
46
+ "peerDependenciesMeta": {
47
+ "playwright": {
48
+ "optional": true
49
+ }
50
+ },
51
+ "scripts": {
52
+ "pretest": "node link.mjs",
53
+ "test": "node --test \"test/**/*.test.mjs\""
54
+ }
55
+ }
package/probe.mjs ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The page checks as plain JavaScript, for an agent driving its own browser
3
+ * (Claude's browser, a Playwright or Chrome DevTools MCP). Each prints as one
4
+ * expression to paste into the browser's JavaScript tool; it returns plain
5
+ * data. No Playwright is loaded to print one.
6
+ *
7
+ * keyline probe audit [--arg '{"viewport":"phone","theme":"dark","firstPass":false}']
8
+ * keyline probe inventory | stuck | watch | arm | read | … the smoke test's
9
+ */
10
+ import { auditProbe } from "./audit/probe.mjs";
11
+ import { SELECTOR_HELPER } from "./browse/capture.mjs";
12
+ import { PAGE, expression } from "./smoke/page.mjs";
13
+
14
+ export const PROBES = ["audit", ...Object.keys(PAGE)];
15
+
16
+ /** The audit's own default: the first pass, where structure, type, copy and slop are measured too. */
17
+ const AUDIT_DEFAULT = { viewport: "desktop", theme: "light", firstPass: true };
18
+
19
+ /** One pasteable expression for a probe. The audit's carries the selector helpers capture.mjs installs. */
20
+ export function probeExpression(name, arg) {
21
+ if (name === "audit") {
22
+ return `(() => {${SELECTOR_HELPER}return (${auditProbe.toString()})(${JSON.stringify({ ...AUDIT_DEFAULT, ...arg })});\n})()`;
23
+ }
24
+ if (!PAGE[name]) throw new Error(`no probe called '${name}': one of ${PROBES.join(", ")}`);
25
+ return expression(name, arg ?? (name === "stuck" ? { after: 8000 } : {}));
26
+ }