diff --git a/README.md b/README.md index e10bd22..7357651 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ the agent needs a cheap, trustworthy loop: change → `renderdiff` → explain e - intentional redesigns: when everything is meant to change, the score says nothing - cross-browser testing (Chromium only) or stored-baseline snapshot tests (both origins must be live) -- discovering routes: you list them; there is no crawler +- discovering routes: you list them, or `--sitemap` reads the reference's sitemap; there is no crawler - component libraries in isolation; Storybook-based tools fit that better ### 30-second quickstart @@ -115,6 +115,7 @@ renderdiff [options] | `--cache-right` | Replay the right side's network traffic from the last `--cache-right` run in `--out`, when it's under an hour old and covers every shot; otherwise load it live and record it. Keeps `/.cache/` when the out dir is wiped. See **Accepted differences and reruns**. | | `--no-recheck` | Don't reload a differing shot's right side to find content that varies per load. Off anyway under `--cache-right`. | | `--computed` | Also diff the computed style of every rendered element and its `::before`/`::after`, and say per route whether the markup is identical apart from asset hashes and origin. Pixels still decide the score and exit code. See [docs/output.md](docs/output.md#computed-styles---computed). | +| `--sitemap[=]` | Add the paths in the right side's sitemap. Default `/sitemap.xml`; give another URL or path with `=`. | | `--dry-run` | Print the URL pairs and exit. No browser. | | `--open` | Open the report when the run finishes. | | `--progress` | A line per shot as it finishes, then the worst scores. The default on a terminal; piped, renderdiff prints one compact summary at the end. | @@ -122,7 +123,10 @@ renderdiff [options] | `-h, --help` / `-v, --version` | | Routes are **literal paths**: there is no route discovery and globs are rejected. Each -route is loaded on both origins, unless it's a pair. +route is loaded on both origins, unless it's a pair. `--sitemap` adds every path in the right +side's sitemap (one sitemap-index level), host ignored so a local build's production URLs work, +files such as `.pdf` dropped. Routes you list come first and aren't repeated; `--dry-run` fetches +the sitemap and lists them. Default widths are `1440, 1152, 896, 704, 375`: each sits mid-way inside a common breakpoint range rather than on a boundary, so a layout switch never flaps between runs. @@ -131,7 +135,7 @@ range rather than on a boundary, so a layout switch never flaps between runs. | --- | --- | | `0` | No route errored and no shot differs (with `--threshold`: none scored below it). Accepted differences don't count; nor do unstable pixels or a failed asset alone, which still get their own row. | | `1` | A shot differs, or with `--threshold` scored below it. Wins over `3` when both happen. A difference that can't be accepted (unstable pixels beside it, content that varies per load, a width change, a height change whose rows don't align) exits 1 even on the `--accept` run. | -| `2` | Bad arguments or config, an origin that isn't responding, an unreadable storage state or `renderdiff.accepted.json`, an out dir holding files renderdiff didn't write, or a `--rerun-failed` that doesn't repeat the last run. | +| `2` | Bad arguments or config, an origin that isn't responding, a `--sitemap` it can't fetch or read, an unreadable storage state or `renderdiff.accepted.json`, an out dir holding files renderdiff didn't write, or a `--rerun-failed` that doesn't repeat the last run. | | `3` | A route errored, so it went unmeasured, or the run crashed (e.g. no Chromium). | ### Moved pages, components, interactions, sign-in diff --git a/skills/renderdiff/SKILL.md b/skills/renderdiff/SKILL.md index 6070472..07be547 100644 --- a/skills/renderdiff/SKILL.md +++ b/skills/renderdiff/SKILL.md @@ -31,7 +31,7 @@ Pixels decide the score and the exit code in every mode. 1. **Serve both sides as production builds**: the base commit in a `git worktree` on one port (right), your change on another (left), same data (static build: `npx serve -l 3002 dist`). Production as the reference is a later second pass. Routes: - every page the change can reach, from the sitemap; `--dry-run` prints the pairs. + every page the change can reach (`--sitemap`); `--dry-run` prints the pairs. § Reference and routes; moved page, component, sign-in, click state: § Scoping. 2. **Baseline**: base vs base. Before changing code, the untouched change side against the reference; if the change is already made, the base build served on two ports. Whatever diff --git a/skills/renderdiff/reference.md b/skills/renderdiff/reference.md index c003c61..0976199 100644 --- a/skills/renderdiff/reference.md +++ b/skills/renderdiff/reference.md @@ -22,8 +22,10 @@ results.json · Gotchas. marketing one: `ln -s "$PWD/docs/dist" dist/docs`, redone after each rebuild (`rewrites` only remap paths inside the served dir). `redirects` and more: serve-handler's README. - **Routes** are literal (no globs, no discovery): every template or page the change can - reach, from the sitemap or router; skip search results, pagination and admin. For removed - CSS, every page where its selectors could match. Pages you don't list go under Not verified. + reach, from the sitemap or router; skip search results, pagination and admin. `--sitemap` + adds the right side's sitemap paths (files dropped); still list what it misses: the 404 + page, states, moved pairs. For removed CSS, every page where its selectors could match. + Pages you don't list go under Not verified. Routes normalize to no trailing slash (`/` stays `/`). `--dry-run` shows how each was read. - **Baseline when the change is already made:** serve the base build twice, on two ports, and diff it against itself; whatever differs varies per load. diff --git a/src/cli.ts b/src/cli.ts index 65bd342..e77c04a 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -17,6 +17,7 @@ import type { Results } from "./report.ts"; import { label, loadConfig, + normalize, parseRoutes, resolveConfig, selectorText, @@ -43,6 +44,8 @@ interface Args extends CliOverrides { rerunFailed: boolean; cacheRight: boolean; recheck: boolean; + /** `true` for the right side's /sitemap.xml, else a URL or path read against right. */ + sitemap?: string | true; } /** `Number(raw)`, but reject anything that isn't a finite number with a flag-named error. */ @@ -97,7 +100,10 @@ function parseArgs(argv: string[]): Args { else if (v === "--computed") a.computed = true; else if (v === "--mask-media") a.maskMedia = true; else if (v === "--no-freeze-video") a.freezeVideo = false; - else if (v === "--accept") { + else if (v === "--sitemap") { + if (inline === "") throw new Error("--sitemap= needs a URL or path"); + a.sitemap = inline ?? true; + } else if (v === "--accept") { a.accept = next().trim(); if (!a.accept) throw new Error("--accept needs a reason"); } else if (v === "--left") a.left = next(); @@ -200,8 +206,8 @@ const HELP = ` Writes report.html, results.json and crops of each change to --out. Exits 1 if any shot differs and isn't accepted (with --threshold, only if one scores below it; --threshold 0 never fails on a diff), 3 if a route errored (unmeasured) or the run - crashed, 2 on bad arguments or config, an origin that is down, or an out dir it won't - wipe. + crashed, 2 on bad arguments or config, an origin that is down, a sitemap it can't use, + or an out dir it won't wipe. Options --left Left origin, instead of the first positional one. @@ -231,6 +237,8 @@ const HELP = ` varies per load. Off anyway under --cache-right. --computed Also diff every element's computed style and ::before/::after, and say whether the markup is identical. Pixels still decide. + --sitemap[=] Add the paths in the right side's sitemap (one index level, files + dropped). Default /sitemap.xml; give a URL or path with =. --dry-run Print the URL pairs and exit. No browser. --open Open the report when the run finishes. --progress A line per shot as it finishes. The default on a terminal; @@ -290,6 +298,58 @@ async function preflight(left: string, right: string) { process.exit(2); } +const FILE = + /\.(pdf|xml|gz|zip|json|txt|csv|rss|atom|png|jpe?g|gif|svg|webp|avif|mp4|webm|mp3|docx?|xlsx?|pptx?)$/i; +const ENTITY: Record = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" }; + +/** The `` paths of one sitemap, host dropped, and whether it is a sitemap index. */ +async function locs(url: URL): Promise<{ index: boolean; paths: string[] }> { + let res: Response, xml: string; + try { + res = await fetch(url, { signal: AbortSignal.timeout(10_000) }); + xml = await res.text(); + } catch (e) { + // Node's fetch says only "fetch failed"; the cause names ECONNREFUSED, ENOTFOUND, ... + const why = e instanceof Error ? (e.cause instanceof Error ? e.cause : e).message : e; + throw new Error(`sitemap: could not fetch ${url} (${why})`); + } + if (res.status >= 400) throw new Error(`sitemap: HTTP ${res.status} at ${url}`); + if (!/<(urlset|sitemapindex)[\s>]/.test(xml)) throw new Error(`sitemap: ${url} is not a sitemap`); + const paths = [...xml.matchAll(/\s*(?:)?\s*<\/loc>/gs)].flatMap( + (m) => { + const loc = m[1]!.replace(/&(amp|lt|gt|quot|apos);/g, (_, e: string) => ENTITY[e]!); + if (!URL.canParse(loc, url)) return []; + // A local build's sitemap names the production host, so keep only the path. + const u = new URL(loc, url); + return [u.pathname + u.search]; + }, + ); + return { index: /]/.test(xml), paths }; +} + +/** Sitemap paths not already covered by `routes`, as routes; one level of index followed. */ +async function sitemapRoutes(spec: string | true, routes: Route[]): Promise { + const base = cfg.right + "/"; + const url = new URL(spec === true ? "sitemap.xml" : spec, base); + const root = await locs(url); + const all = root.index + ? (await Promise.all(root.paths.map((p) => locs(new URL(p, base))))).flatMap((s) => s.paths) + : root.paths; + const unique = [...new Set(all.map(normalize))]; + const pages = unique.filter((p) => !FILE.test(new URL(p, base).pathname)); + const dropped = unique.length - pages.length; + if (!pages.length) throw new Error(`sitemap ${url} gave no routes`); + console.log( + `Sitemap: ${url}: ${pages.length} routes` + (dropped ? `, ${dropped} files dropped` : ""), + ); + const covered = new Set(routes.flatMap((r) => [r.left, r.right])); + return parseRoutes( + pages.filter((p) => !covered.has(p)), + args.selector, + fileConfig.before, + ); +} + /** `renderdiff report `: report.html and evidence.html from results.json, no browser. */ async function report(argv: string[]): Promise { try { @@ -357,7 +417,7 @@ try { const rawRoutes = args.routes.length ? args.routes : (fileConfig.routes ?? []); -if (!rawRoutes.length) { +if (!rawRoutes.length && !args.sitemap) { die("no routes given."); } @@ -369,6 +429,16 @@ try { } if (configPath) console.log(`Config: ${configPath}`); + +if (args.sitemap) { + try { + routes = [...routes, ...(await sitemapRoutes(args.sitemap, routes))]; + } catch (e) { + console.error(`✗ ${e instanceof Error ? e.message : String(e)}`); + process.exit(2); + } +} + console.log(`Routes: ${routes.length}`); if (args.dryRun) { diff --git a/tests/unit/cli-args.test.ts b/tests/unit/cli-args.test.ts index 6547d36..fa595b1 100644 --- a/tests/unit/cli-args.test.ts +++ b/tests/unit/cli-args.test.ts @@ -61,6 +61,7 @@ describe("help and version", () => { "--mask-media", "--no-freeze-video", "--no-recheck", + "--sitemap", ]) { assert.ok(r.stdout.includes(flag), `--help does not mention ${flag}`); } diff --git a/tests/unit/sitemap.test.ts b/tests/unit/sitemap.test.ts new file mode 100644 index 0000000..e7cd4a8 --- /dev/null +++ b/tests/unit/sitemap.test.ts @@ -0,0 +1,143 @@ +/** + * `--sitemap`: routes read from the right side's sitemap. + * + * All through `--dry-run`, so no browser; the sitemaps come from a local HTTP server that + * stands in for the right origin. Left is never fetched. + */ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import http from "node:http"; +import type { AddressInfo } from "node:net"; +import path from "node:path"; +import { after, before, beforeEach, describe, test } from "node:test"; +import { cleanupTempDirs, runCli, tempDir } from "../helpers/cli.ts"; + +const L = "http://left.test"; +let R = ""; +let pages: Record = {}; + +const server = http.createServer((req, res) => { + const page = pages[req.url ?? ""]; + res.writeHead(page?.status ?? (page ? 200 : 404), { + "content-type": page?.type ?? "application/xml", + }); + res.end(page?.body ?? "not found"); +}); + +before(async () => { + await new Promise((done) => server.listen(0, "127.0.0.1", done)); + R = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; +}); +after(() => { + server.close(); + cleanupTempDirs(); +}); +beforeEach(() => { + pages = {}; +}); + +const urlset = (...locs: string[]) => + `\n\n` + + locs.map((l) => ` ${l}\n`).join("") + + `\n`; + +const dry = (extra: string[], cwd?: string) => + runCli(["--dry-run", "--left", L, "--right", R, ...extra], { noOut: true, cwd }); + +/** The route labels a dry run listed, in order. */ +const listed = (stdout: string) => + stdout + .split("\n") + .filter((l) => l.startsWith(" ")) + .map((l) => l.trim().split(/\s+/)[0]); + +async function rejects(extra: string[], needle: string) { + const r = await dry(extra); + assert.equal(r.code, 2, `expected exit 2\n${r.stdout}\n${r.stderr}`); + assert.ok(r.stderr.includes(needle), `stderr lacks "${needle}":\n${r.stderr}`); +} + +describe("--sitemap", () => { + test("reads /sitemap.xml: paths on right whatever the host, deduped, files dropped", async () => { + pages["/sitemap.xml"] = { + body: urlset( + "https://example.com/", + "https://example.com/about", + "https://example.com/about/", + "https://example.com/doc.pdf", + "", + ), + }; + const r = await dry(["--sitemap"]); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(listed(r.stdout), ["/", "/about", "/blog/a?x=1&y=2"]); + assert.ok(r.stdout.includes(`Sitemap: ${R}/sitemap.xml: 3 routes, 1 files dropped`), r.stdout); + assert.ok(r.stdout.includes(`${R}/about`), r.stdout); + }); + + test("decodes XML entities in a and trims the whitespace around it", async () => { + pages["/sitemap.xml"] = { body: urlset("\n https://example.com/s?a=1&b=2\n ") }; + const r = await dry(["--sitemap"]); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(listed(r.stdout), ["/s?a=1&b=2"]); + }); + + test("follows a sitemap index one level, fetching each child from right", async () => { + pages["/sitemap.xml"] = { + body: + `\n\n` + + `https://example.com/sitemap-0.xml\n\n`, + }; + pages["/sitemap-0.xml"] = { body: urlset("https://example.com/x", "https://example.com/y") }; + const r = await dry(["--sitemap"]); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(listed(r.stdout), ["/x", "/y"]); + }); + + test("--sitemap= resolves against right", async () => { + pages["/custom.xml"] = { body: urlset("/c") }; + const r = await dry(["--sitemap=/custom.xml"]); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(listed(r.stdout), ["/c"]); + }); + + test("explicit routes come first and the sitemap doesn't repeat their paths", async () => { + pages["/sitemap.xml"] = { body: urlset("/plans", "/contact", "/x") }; + const r = await dry(["/contact", "/pricing::/plans", "--sitemap"]); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(listed(r.stdout), ["/contact", "/pricing::/plans", "/x"]); + }); + + test("a config route with its own before hook isn't clashed by the sitemap's same path", async () => { + pages["/sitemap.xml"] = { body: urlset("/a", "/b") }; + const cwd = tempDir("renderdiff-cfg-"); + fs.writeFileSync( + path.join(cwd, "renderdiff.config.mjs"), + 'export default { routes: [{ left: "/a", before: async () => {} }] };\n', + ); + const r = await dry(["--sitemap"], cwd); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(listed(r.stdout), ["/a", "/b"]); + }); + + test("a bare --sitemap before the origins leaves both as origins", async () => { + pages["/sitemap.xml"] = { body: urlset("/z") }; + const r = await runCli(["--dry-run", "--sitemap", L, R], { noOut: true }); + assert.equal(r.code, 0, r.stderr); + assert.ok(r.stdout.includes(`${L}/z | ${R}/z`), r.stdout); + }); + + test("exit 2 on a sitemap it can't use", async () => { + await rejects(["--sitemap"], `sitemap: HTTP 404 at ${R}/sitemap.xml`); + pages["/sitemap.xml"] = { body: "", type: "text/html" }; + await rejects(["--sitemap"], "is not a sitemap"); + pages["/sitemap.xml"] = { body: urlset() }; + await rejects(["--sitemap"], "gave no routes"); + pages["/sitemap.xml"] = { body: urlset("/a.pdf", "/b.png") }; + await rejects(["/a", "--sitemap"], "gave no routes"); + await rejects(["--sitemap=http://127.0.0.1:1/sitemap.xml"], "sitemap: could not fetch"); + const r = await dry(["--sitemap="]); + assert.equal(r.code, 2); + assert.match(r.stderr, /--sitemap= needs a URL or path/); + }); +});