Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -115,14 +115,18 @@ renderdiff <left-origin> <right-origin> <route…> [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 `<out>/.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[=<url>]` | Add the paths in the right side's sitemap. Default `<right>/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. |
| `--no-progress` | The compact summary even on a terminal. |
| `-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.
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion skills/renderdiff/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 4 additions & 2 deletions skills/renderdiff/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
78 changes: 74 additions & 4 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import type { Results } from "./report.ts";
import {
label,
loadConfig,
normalize,
parseRoutes,
resolveConfig,
selectorText,
Expand All @@ -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. */
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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 <url> Left origin, instead of the first positional one.
Expand Down Expand Up @@ -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[=<url>] Add the paths in the right side's sitemap (one index level, files
dropped). Default <right>/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;
Expand Down Expand Up @@ -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<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };

/** The `<loc>` 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(/<loc>\s*(?:<!\[CDATA\[)?(.*?)(?:\]\]>)?\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: /<sitemapindex[\s>]/.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<Route[]> {
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 <out-dir>`: report.html and evidence.html from results.json, no browser. */
async function report(argv: string[]): Promise<never> {
try {
Expand Down Expand Up @@ -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.");
}

Expand All @@ -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) {
Expand Down
1 change: 1 addition & 0 deletions tests/unit/cli-args.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}`);
}
Expand Down
143 changes: 143 additions & 0 deletions tests/unit/sitemap.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, { body: string; type?: string; status?: number }> = {};

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<void>((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[]) =>
`<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n` +
locs.map((l) => ` <url><loc>${l}</loc></url>\n`).join("") +
`</urlset>\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 <right>/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",
"<![CDATA[https://example.com/blog/a?x=1&y=2]]>",
),
};
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 <loc> and trims the whitespace around it", async () => {
pages["/sitemap.xml"] = { body: urlset("\n https://example.com/s?a=1&amp;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:
`<?xml version="1.0"?>\n<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n` +
`<sitemap><loc>https://example.com/sitemap-0.xml</loc></sitemap>\n</sitemapindex>\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=<path> 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: "<!doctype html><html></html>", 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/);
});
});
Loading