diff --git a/packages/cli/src/commands/blank-span.browser.js b/packages/cli/src/commands/blank-span.browser.js
index e1bd0d690ea..f322d1435f1 100644
--- a/packages/cli/src/commands/blank-span.browser.js
+++ b/packages/cli/src/commands/blank-span.browser.js
@@ -1,8 +1,7 @@
-// blank_span's page half (utils/blankSpan.ts): does a frame show only the bare stage, by motion-signature's framesDiffer.
+// blank_span's page half (utils/blankSpan.ts): the stage's own colour while nothing on it renders, else null.
(function () {
const CONTENT_TAGS = new Set(["IMG", "VIDEO", "CANVAS", "SVG", "IFRAME", "OBJECT", "EMBED"]);
const RENDERED_OPTIONS = { opacityProperty: true, visibilityProperty: true };
- const PNG_PREFIX = "data:image/png;base64,";
// An `rgb()` or `rgba()` colour's alpha; null for any other notation, which is never read as transparent.
function alphaOf(color) {
@@ -49,23 +48,19 @@
);
}
- async function stageFrame(color, png) {
- const image = new Image();
- image.src = PNG_PREFIX + png;
- await image.decode();
+ // Any CSS colour notation, as the canvas paints it.
+ function painted(color) {
const canvas = document.createElement("canvas");
- canvas.width = image.naturalWidth;
- canvas.height = image.naturalHeight;
+ canvas.width = canvas.height = 1;
const context = canvas.getContext("2d");
context.fillStyle = color;
- context.fillRect(0, 0, canvas.width, canvas.height);
- return canvas.toDataURL("image/png").slice(PNG_PREFIX.length);
+ context.fillRect(0, 0, 1, 1);
+ return Array.from(context.getImageData(0, 0, 1, 1).data);
}
- window.__hyperframesStageIsEmpty = async function stageIsEmpty(png) {
+ window.__hyperframesEmptyStageColor = function emptyStageColor() {
const root = window.__hyperframesMotionSignature.compositionRoot();
const color = stageColor(root);
- if (color === null || rendersAnything(root)) return false;
- return !(await window.__hyperframesFramesDiffer(await stageFrame(color, png), png));
+ return color === null || rendersAnything(root) ? null : painted(color);
};
})();
diff --git a/packages/cli/src/commands/check.test.ts b/packages/cli/src/commands/check.test.ts
index 75d25b10de2..8ee02a93fcd 100644
--- a/packages/cli/src/commands/check.test.ts
+++ b/packages/cli/src/commands/check.test.ts
@@ -3,7 +3,6 @@ import { runCommand } from "citty";
import {
mkdirSync,
mkdtempSync,
- readFileSync,
rmSync,
statSync,
symlinkSync,
@@ -269,10 +268,6 @@ function fixtureRect(left: number, top: number, width: number, height: number):
return { left, top, right: left + width, bottom: top + height, width, height };
}
-function checkBrowserSource(): string {
- return readFileSync(new URL("../utils/checkBrowser.ts", import.meta.url), "utf8");
-}
-
async function gateCandidates(
time: number,
request: { text: boolean; media: boolean; tolerance: number },
@@ -4392,20 +4387,6 @@ describe("check report telemetry", () => {
});
});
-describe("contrast candidate round-trip", () => {
- it("passes the browser script's raw candidates back to finish, never the normalized copies", () => {
- const source = checkBrowserSource();
-
- // __contrastAuditFinish samples pixels via the page script's own bbox
- // shape ({x, y, w, h}); sending the Node-normalized candidate
- // ({width, height}) makes every sample rect NaN and the audit silently
- // reports zero checked elements. The raw object must round-trip verbatim.
- expect(source).toMatch(/prepared\.map\(\(entry\) => entry\.raw\)/);
- expect(source).toMatch(/raw: unknown;/);
- expect(source).not.toMatch(/prepared\.map\(\(entry\) => entry\.candidate\)/);
- });
-});
-
describe("dense motion-overlap re-sampling", () => {
// Collision lives inside (3.5, 4.5), a gap the sparse base grid seeks past; only the 8fps dense pass observes it.
const inBetweenGridWindow = (time: number): boolean => time >= 3.6 && time <= 4.4;
diff --git a/packages/cli/src/commands/contrast-audit.browser.js b/packages/cli/src/commands/contrast-audit.browser.js
index fa51384d506..a80b664e765 100644
--- a/packages/cli/src/commands/contrast-audit.browser.js
+++ b/packages/cli/src/commands/contrast-audit.browser.js
@@ -1,13 +1,10 @@
// Browser-side WCAG contrast audit, injected as a raw string so esbuild can't mangle it.
// __contrastAuditPrepare() hides each text element's own paint (layout-neutral) and returns candidates;
// the caller takes one screenshot, full frame or clipped to the candidates (collectContrast in checkBrowser.ts);
-// __contrastAuditFinish(png, time, candidates, region) restores paint first, then samples inside each box.
+// __contrastAuditRestoreIfPending() restores the paint, and contrast-measure.ts reads the shot in Node.
// Sampling inside the box reads the exact pixels behind the glyphs; a ring outside the text misreads
// neighbouring panels, rounded pills, blurred glass and partial decorations.
-// __contrastAuditRestoreIfPending() restores hidden paint if the screenshot or finish() throws.
-
-// The "which rect to sample" decision is mirrored and unit-tested in contrast-sample.ts.
/* eslint-disable */
window.__contrastAuditPrepare = function () {
@@ -513,167 +510,7 @@ function __contrastAuditRestoreAll() {
window.__contrastAuditRestores = null;
}
-// Safety net for the caller: if the screenshot or finish() call throws
-// between prepare() and finish(), call this to restore any still-hidden
-// paint so the next sample in the loop isn't auditing a page with stale
-// invisible text. No-op if finish() already ran normally.
+// Called right after the screenshot, and again if anything threw before that: a no-op once restored.
window.__contrastAuditRestoreIfPending = function () {
__contrastAuditRestoreAll();
};
-
-window.__contrastAuditFinish = async function (imgBase64, time, candidates, region) {
- function relLum(r, g, b) {
- function ch(v) {
- var s = v / 255;
- return s <= 0.03928 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);
- }
- return 0.2126 * ch(r) + 0.7152 * ch(g) + 0.0722 * ch(b);
- }
-
- function wcagRatio(r1, g1, b1, r2, g2, b2) {
- var l1 = relLum(r1, g1, b1),
- l2 = relLum(r2, g2, b2);
- var hi = l1 > l2 ? l1 : l2,
- lo = l1 > l2 ? l2 : l1;
- return (hi + 0.05) / (lo + 0.05);
- }
-
- function median(arr) {
- var s = arr.slice().sort(function (a, b) {
- return a - b;
- });
- return s[Math.floor(s.length / 2)];
- }
-
- // Restore original paint first — we already have the screenshot, and we
- // never want a decode failure below to leave the page's text invisible.
- __contrastAuditRestoreAll();
-
- // No image when every candidate's background is known from styles.
- var canvas = { width: region ? region.frameWidth : 0, height: region ? region.frameHeight : 0 };
- var px = null;
- if (imgBase64) {
- var img = new Image();
- await new Promise(function (resolve) {
- img.onload = resolve;
- img.onerror = function () {
- resolve();
- };
- img.src = "data:image/png;base64," + imgBase64;
- });
- if (!img.naturalWidth) return [];
- canvas = document.createElement("canvas");
- canvas.width = img.naturalWidth || 1920;
- canvas.height = img.naturalHeight || 1080;
- var ctx = canvas.getContext("2d");
- if (!ctx) return [];
- ctx.drawImage(img, 0, 0);
- px = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
- }
- // A clipped shot holds `region.clip` of the frame: clamp to the frame, read at the offset.
- var w = region ? region.frameWidth : canvas.width;
- var h = region ? region.frameHeight : canvas.height;
- var ox = region ? region.clip.x : 0;
- var oy = region ? region.clip.y : 0;
-
- var out = [];
- for (var ci = 0; ci < candidates.length; ci++) {
- var c = candidates[ci];
- var bbox = c.bbox;
-
- // Sample the element's OWN box (glyphs are hidden in this screenshot),
- // inset 1px on each side to dodge anti-aliased edge pixels, clamped to
- // the canvas. Mirrors contrast-sample.ts's computeSampleRect.
- var x0 = Math.max(0, Math.round(bbox.x) + 1);
- var x1 = Math.min(w - 1, Math.round(bbox.x + bbox.w) - 1);
- var y0 = Math.max(0, Math.round(bbox.y) + 1);
- var y1 = Math.min(h - 1, Math.round(bbox.y + bbox.h) - 1);
- if (x1 <= x0 || y1 <= y0) continue;
-
- // Bounded grid, not a full scan — dense enough to catch a
- // partially-overlapping decoration without turning a wide caption bar
- // into thousands of samples. Mirrors contrast-sample.ts's
- // sampleGridPoints.
- var stepX = Math.max(1, Math.floor((x1 - x0) / 12));
- var stepY = Math.max(1, Math.floor((y1 - y0) / 6));
- var known = c.ownBg && c.ownBg.length >= 4 && c.ownBg[3] >= 0.99 ? c.ownBg : c.solidBg;
- var rr = [],
- gg = [],
- bb = [],
- aa = [];
- for (var y = y0; !known && y <= y1; y += stepY) {
- for (var x = x0; x <= x1; x += stepX) {
- var idx = ((y - oy) * canvas.width + (x - ox)) * 4;
- rr.push(px[idx]);
- gg.push(px[idx + 1]);
- bb.push(px[idx + 2]);
- aa.push(px[idx + 3]);
- }
- }
- if (!known && rr.length === 0) continue;
-
- var bgR, bgG, bgB;
- if (known) {
- bgR = known[0];
- bgG = known[1];
- bgB = known[2];
- } else {
- // A transparent sampled backdrop is supplied by the downstream editor,
- // not this composition. WCAG contrast cannot be inferred until that live
- // video/image is known, so do not invent an opaque browser default and
- // hard-fail an otherwise valid alpha overlay.
- if (median(aa) < 255) continue;
- bgR = median(rr);
- bgG = median(gg);
- bgB = median(bb);
- }
-
- // Composite foreground alpha over the measured background; a gradient's weakest stop sets the ratio.
- var compR = 0,
- compG = 0,
- compB = 0,
- ratio = Infinity;
- var fills = c.fgStops || [c.fg];
- for (var pi = 0; pi < fills.length; pi++) {
- var fg = fills[pi];
- var paintR = Math.round(fg[0] * fg[3] + bgR * (1 - fg[3]));
- var paintG = Math.round(fg[1] * fg[3] + bgG * (1 - fg[3]));
- var paintB = Math.round(fg[2] * fg[3] + bgB * (1 - fg[3]));
- var paintRatio = +wcagRatio(paintR, paintG, paintB, bgR, bgG, bgB).toFixed(2);
- if (paintRatio >= ratio) continue;
- compR = paintR;
- compG = paintG;
- compB = paintB;
- ratio = paintRatio;
- }
-
- // A solid text stroke is part of the visible glyph paint. Use whichever
- // of fill or stroke provides the stronger edge contrast, rather than
- // failing readable outlined captions based on fill alone.
- if (c.stroke) {
- var stroke = c.stroke;
- var strokeR = Math.round(stroke[0] * stroke[3] + bgR * (1 - stroke[3]));
- var strokeG = Math.round(stroke[1] * stroke[3] + bgG * (1 - stroke[3]));
- var strokeB = Math.round(stroke[2] * stroke[3] + bgB * (1 - stroke[3]));
- var strokeRatio = +wcagRatio(strokeR, strokeG, strokeB, bgR, bgG, bgB).toFixed(2);
- if (strokeRatio > ratio) {
- compR = strokeR;
- compG = strokeG;
- compB = strokeB;
- ratio = strokeRatio;
- }
- }
-
- out.push({
- time: time,
- selector: c.selector,
- text: c.text,
- ratio: ratio,
- wcagAA: c.large ? ratio >= 3 : ratio >= 4.5,
- large: c.large,
- fg: "rgb(" + compR + "," + compG + "," + compB + ")",
- bg: "rgb(" + bgR + "," + bgG + "," + bgB + ")",
- });
- }
- return out;
-};
diff --git a/packages/cli/src/commands/contrast-bg.ts b/packages/cli/src/commands/contrast-bg.ts
index 778a9e64ae3..d8999b0a4db 100644
--- a/packages/cli/src/commands/contrast-bg.ts
+++ b/packages/cli/src/commands/contrast-bg.ts
@@ -1,26 +1,9 @@
-// Pure background-resolution logic for the WCAG contrast audit.
-//
-// HISTORICAL NOTE: contrast-audit.browser.js used to sample a 4px pixel ring
-// just OUTSIDE an element's bounding box to estimate its background, with
-// pickOpaqueBackground() below as a pre-check: prefer an element's own opaque
-// background-color over the ring for solid CTA/pill/card cases. The audit has
-// since moved to sampling the ACTUAL composited pixels directly inside each
-// element's own bbox (hiding the glyphs first) — see contrast-sample.ts — which
-// gets pill/card backgrounds right AND fixes the ring's blind spots (rounded
-// corners, backdrop-filter blur, cross-component bleed, partially-overlapping
-// translucent decoration). pickOpaqueBackground()/parseColorRGBA() are no
-// longer called by the live audit but are kept here — still correct, still
-// unit-tested, and contrast-fg.ts imports parseColorRGBA from this module.
-//
-// This module hosts pure decisions so they can be unit-tested without a
-// browser. Historically the same logic was inlined into
-// contrast-audit.browser.js (which is injected as a raw string and cannot
-// import) — see contrast-sample.ts for what's actually mirrored today.
+// Pure colour decisions for the WCAG contrast audit, unit-testable without a browser.
export type Rgb = [number, number, number];
export type Rgba = [number, number, number, number];
-/** WCAG relative luminance for an sRGB color. Mirrors contrast-audit.browser.js. */
+/** WCAG relative luminance for an sRGB color. */
export function relativeLuminance(color: Rgb): number {
const channel = (value: number) => {
const srgb = value / 255;
diff --git a/packages/cli/src/commands/contrast-clip.browser.test.ts b/packages/cli/src/commands/contrast-clip.browser.test.ts
index f0c4299d3d6..801a91b7abc 100644
--- a/packages/cli/src/commands/contrast-clip.browser.test.ts
+++ b/packages/cli/src/commands/contrast-clip.browser.test.ts
@@ -4,6 +4,8 @@ import type { AddressInfo } from "node:net";
import { join } from "node:path";
import { afterAll, beforeAll, expect, it } from "vitest";
import { openSettledCompositionPage } from "../capture/captureCompositionFrame.js";
+import { framePixels } from "../utils/framePixels.js";
+import { measureContrast, parseContrastCandidate, type TextRegion } from "./contrast-measure.js";
// Text over a two-tone backdrop, away from the origin: reading a clipped shot at the wrong offset picks the other tone.
const HTML = `
@@ -54,17 +56,17 @@ it("measures the same contrast from a shot clipped to the text as from the full
omitBackground: true,
...(clipped ? { clip, captureBeyondViewport: false } : {}),
});
- const region = clipped ? { clip, frameWidth: 640, frameHeight: 360 } : null;
- return page.evaluate(
- (png: string, items: unknown[], at: unknown) =>
- Reflect.apply(Reflect.get(window, "__contrastAuditFinish"), window, [png, 0, items, at]),
- shot,
- candidates,
- region,
- );
+ await page.evaluate("window.__contrastAuditRestoreIfPending()");
+ const region: TextRegion | undefined = clipped
+ ? { clip, frameWidth: 640, frameHeight: 360 }
+ : undefined;
+ return candidates.map((value) => {
+ const candidate = parseContrastCandidate(value);
+ return candidate && measureContrast(candidate, framePixels(shot), region);
+ });
};
- const full = (await measure(false)) as { bg: number[] }[];
+ const full = await measure(false);
expect(full).toHaveLength(2);
expect(full[0]?.bg).not.toEqual(full[1]?.bg);
expect(await measure(true)).toEqual(full);
diff --git a/packages/cli/src/commands/contrast-measure.test.ts b/packages/cli/src/commands/contrast-measure.test.ts
new file mode 100644
index 00000000000..c7657c23fb1
--- /dev/null
+++ b/packages/cli/src/commands/contrast-measure.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from "vitest";
+import { measureContrast, parseContrastCandidate } from "./contrast-measure.js";
+
+const prepared = {
+ selector: "#a",
+ text: "Words",
+ fg: [255, 255, 255, 1],
+ fgStops: null,
+ stroke: null,
+ large: false,
+ ownBg: null,
+ solidBg: null,
+ bbox: { x: 0, y: 0, w: 8, h: 8 },
+};
+const frame = (...pixel: number[]) => ({
+ width: 10,
+ height: 10,
+ data: Uint8Array.from({ length: 400 }, (_, i) => pixel[i % 4] ?? 0),
+});
+const measure = (value: object, pixels: ReturnType | null) => {
+ const candidate = parseContrastCandidate({ ...prepared, ...value });
+ return candidate && measureContrast(candidate, pixels, undefined);
+};
+
+describe("measureContrast", () => {
+ it("judges text by the pixels behind it", () => {
+ expect(measure({}, frame(0, 0, 0, 255))).toMatchObject({ ratio: 21, wcagAA: true });
+ expect(measure({}, frame(255, 255, 255, 255))).toMatchObject({ ratio: 1, wcagAA: false });
+ });
+
+ it("judges a gradient fill by its weakest stop, and an outline that reads better instead", () => {
+ const fgStops = [
+ [255, 255, 255, 1],
+ [0, 0, 0, 1],
+ ];
+ expect(measure({ fgStops }, frame(0, 0, 0, 255))?.fg).toBe("rgb(0,0,0)");
+ expect(measure({ fgStops, stroke: [255, 255, 0, 1] }, frame(0, 0, 0, 255))?.fg).toBe(
+ "rgb(255,255,0)",
+ );
+ });
+
+ it("leaves text over a transparent backdrop alone", () => {
+ expect(measure({}, frame(0, 0, 0, 0))).toBeNull();
+ });
+
+ it("reads no pixel where styles prove the backdrop", () => {
+ const region = { clip: { x: 0, y: 0, width: 10, height: 10 }, frameWidth: 10, frameHeight: 10 };
+ const candidate = parseContrastCandidate({ ...prepared, solidBg: [0, 0, 0] });
+ expect(candidate && measureContrast(candidate, null, region)).toMatchObject({ ratio: 21 });
+ });
+});
+
+describe("parseContrastCandidate", () => {
+ it.each([
+ ["no selector", { selector: "" }],
+ ["a colour that is not numbers", { fg: ["x", 0, 0, 1] }],
+ ["a gradient stop that is not a colour", { fgStops: [[0, 0, 0, 1], {}] }],
+ ["a box without a height", { bbox: { x: 0, y: 0, w: 8 } }],
+ ["a box that is not finite", { bbox: { x: 0, y: 0, w: Number.POSITIVE_INFINITY, h: 8 } }],
+ ])("drops a candidate with %s", (_, value) => {
+ expect(parseContrastCandidate({ ...prepared, ...value })).toBeNull();
+ });
+});
diff --git a/packages/cli/src/commands/contrast-measure.ts b/packages/cli/src/commands/contrast-measure.ts
new file mode 100644
index 00000000000..74ca8c9308b
--- /dev/null
+++ b/packages/cli/src/commands/contrast-measure.ts
@@ -0,0 +1,140 @@
+import type { FramePixels } from "../utils/framePixels.js";
+import { contrastRatio, requiredContrastRatio, type Rgb, type Rgba } from "./contrast-bg.js";
+import {
+ computeSampleRect,
+ sampleGridPoints,
+ type PixelRect,
+ type Rect,
+} from "./contrast-sample.js";
+
+/** One text __contrastAuditPrepare hid: what the page knows about it before any pixel is read. */
+export interface ContrastCandidate {
+ selector: string;
+ text: string;
+ /** The fill, or each stop of a gradient fill: the weakest sets the ratio. */
+ fills: Rgba[];
+ stroke: Rgba | null;
+ /** The backdrop where styles alone prove it, so no pixel is read. */
+ knownBackdrop: Rgb | null;
+ large: boolean;
+ bbox: Rect;
+}
+
+/** Where a clipped shot sits in the frame. */
+export interface TextRegion {
+ clip: { x: number; y: number; width: number; height: number };
+ frameWidth: number;
+ frameHeight: number;
+}
+
+export interface ContrastMeasurement {
+ ratio: number;
+ wcagAA: boolean;
+ large: boolean;
+ fg: string;
+ bg: string;
+}
+
+export function parseContrastCandidate(value: unknown): ContrastCandidate | null {
+ if (typeof value !== "object" || value === null) return null;
+ const { selector, text, fg, fgStops, stroke, ownBg, solidBg, large, bbox } = value as Record<
+ string,
+ unknown
+ >;
+ const fills = (Array.isArray(fgStops) ? fgStops : [fg]).map(rgba);
+ const box = rect(bbox);
+ if (typeof selector !== "string" || !selector || typeof text !== "string") return null;
+ if (typeof large !== "boolean" || !box || !fills.every((fill) => fill !== null)) return null;
+ return {
+ selector,
+ text,
+ fills,
+ stroke: rgba(stroke),
+ knownBackdrop: opaque(rgba(ownBg)) ?? rgb(solidBg),
+ large,
+ bbox: box,
+ };
+}
+
+/** The contrast of one text against what is behind its glyphs; null where that cannot be known. */
+export function measureContrast(
+ candidate: ContrastCandidate,
+ pixels: FramePixels | null,
+ region?: TextRegion,
+): ContrastMeasurement | null {
+ const bg = backdrop(candidate, pixels, region);
+ if (!bg) return null;
+ const { stroke, large } = candidate;
+ const paints = candidate.fills.map((fill) => over(fill, bg));
+ const [weakest] = paints.sort((a, b) => a.ratio - b.ratio);
+ if (!weakest) return null;
+ // A solid text stroke is visible glyph paint too: the stronger of fill and stroke decides.
+ const outline = stroke && over(stroke, bg);
+ const { color, ratio } = outline && outline.ratio > weakest.ratio ? outline : weakest;
+ if (!Number.isFinite(ratio)) return null;
+ return {
+ ratio,
+ wcagAA: ratio >= requiredContrastRatio(large),
+ large,
+ fg: `rgb(${color.join(",")})`,
+ bg: `rgb(${bg.join(",")})`,
+ };
+}
+
+function backdrop(
+ { bbox, knownBackdrop }: ContrastCandidate,
+ pixels: FramePixels | null,
+ region: TextRegion | undefined,
+): Rgb | null {
+ const { clip, frameWidth, frameHeight } = region ?? wholeFrame(pixels);
+ const box = computeSampleRect(bbox, frameWidth, frameHeight);
+ if (!box || knownBackdrop) return box && knownBackdrop;
+ return pixels && sampledColor(pixels, box, clip);
+}
+
+function wholeFrame(pixels: FramePixels | null): TextRegion {
+ const { width, height } = pixels ?? { width: 0, height: 0 };
+ return { clip: { x: 0, y: 0, width, height }, frameWidth: width, frameHeight: height };
+}
+
+function sampledColor(
+ { data, width }: FramePixels,
+ box: PixelRect,
+ clip: TextRegion["clip"],
+): Rgb | null {
+ const offsets = sampleGridPoints(box).map(([x, y]) => ((y - clip.y) * width + (x - clip.x)) * 4);
+ const channel = (index: number) => median(offsets.map((at) => data[at + index] ?? 0));
+ // The editor supplies what a transparent backdrop shows, so its contrast cannot be known here.
+ return channel(3) < 255 ? null : [channel(0), channel(1), channel(2)];
+}
+
+function over([r, g, b, alpha]: Rgba, bg: Rgb): { color: Rgb; ratio: number } {
+ const mix = (paint: number, under: number) => Math.round(paint * alpha + under * (1 - alpha));
+ const color: Rgb = [mix(r, bg[0]), mix(g, bg[1]), mix(b, bg[2])];
+ return { color, ratio: +contrastRatio(color, bg).toFixed(2) };
+}
+
+function median(values: number[]): number {
+ const sorted = [...values].sort((a, b) => a - b);
+ return sorted[Math.floor(sorted.length / 2)] ?? 0;
+}
+
+function numbers(value: unknown, count: number): number[] | null {
+ if (!Array.isArray(value) || value.length < count) return null;
+ const read: unknown[] = value.slice(0, count);
+ return read.every((entry) => typeof entry === "number" && Number.isFinite(entry))
+ ? (read as number[])
+ : null;
+}
+
+const rgba = (value: unknown) => numbers(value, 4) as Rgba | null;
+const rgb = (value: unknown) => numbers(value, 3) as Rgb | null;
+const opaque = (color: Rgba | null): Rgb | null =>
+ color && color[3] >= 0.99 ? [color[0], color[1], color[2]] : null;
+
+function rect(value: unknown): Rect | null {
+ if (typeof value !== "object" || value === null) return null;
+ const { x, y, w, h } = value as Record;
+ const read = numbers([x, y, w, h], 4);
+ return read ? { x: read[0]!, y: read[1]!, w: read[2]!, h: read[3]! } : null;
+}
diff --git a/packages/cli/src/commands/contrast-occlusion.browser.test.ts b/packages/cli/src/commands/contrast-occlusion.browser.test.ts
index 521c95abe6a..d69cbb825fd 100644
--- a/packages/cli/src/commands/contrast-occlusion.browser.test.ts
+++ b/packages/cli/src/commands/contrast-occlusion.browser.test.ts
@@ -71,7 +71,6 @@ afterEach(() => {
Reflect.deleteProperty(document, "elementsFromPoint");
for (const name of [
"__contrastAuditPrepare",
- "__contrastAuditFinish",
"__contrastAuditRestoreIfPending",
"__contrastAuditRestores",
])
diff --git a/packages/cli/src/commands/contrast-sample.ts b/packages/cli/src/commands/contrast-sample.ts
index 7df00457350..07ae2a02251 100644
--- a/packages/cli/src/commands/contrast-sample.ts
+++ b/packages/cli/src/commands/contrast-sample.ts
@@ -8,9 +8,7 @@
// invisible, and samples the composited pixels INSIDE the element's own bbox.
// This module hosts the pure "which rect do we sample" decision (inset to
// dodge anti-aliased edge pixels, clamp to canvas bounds, and reject a rect
-// that's too small to sample) so it's unit-testable without a browser. The
-// same logic is inlined into contrast-audit.browser.js (which is injected as
-// a raw string and cannot import) — keep both in sync.
+// that's too small to sample) so it's unit-testable without a browser.
export interface Rect {
x: number;
diff --git a/packages/cli/src/commands/contrast-solid.browser.test.ts b/packages/cli/src/commands/contrast-solid.browser.test.ts
index 04ae5b215b5..9abea589a71 100644
--- a/packages/cli/src/commands/contrast-solid.browser.test.ts
+++ b/packages/cli/src/commands/contrast-solid.browser.test.ts
@@ -4,6 +4,8 @@ import type { AddressInfo } from "node:net";
import { join } from "node:path";
import { afterAll, beforeAll, expect, it } from "vitest";
import { openSettledCompositionPage } from "../capture/captureCompositionFrame.js";
+import { framePixels } from "../utils/framePixels.js";
+import { measureContrast, parseContrastCandidate } from "./contrast-measure.js";
const P = "position:absolute;margin:0;font:28px sans-serif;color:#9ab";
const HTML = `
@@ -52,17 +54,12 @@ it("reads a backdrop from styles only where pixels would give the same contrast"
const prepared = (await page.evaluate("window.__contrastAuditPrepare()")) as Candidate[];
const shot = await page.screenshot({ encoding: "base64", omitBackground: true });
const candidates = dropSolid ? prepared.map((c) => ({ ...c, solidBg: null })) : prepared;
- const entries = await page.evaluate(
- (png: string, items: unknown[]) =>
- Reflect.apply(Reflect.get(window, "__contrastAuditFinish"), window, [
- png,
- 0,
- items,
- null,
- ]),
- shot,
- candidates,
- );
+ await page.evaluate("window.__contrastAuditRestoreIfPending()");
+ const entries = candidates.map((value) => {
+ const candidate = parseContrastCandidate(value);
+ return candidate && measureContrast(candidate, framePixels(shot));
+ });
+ expect(entries).not.toContain(null);
return { prepared, entries };
};
diff --git a/packages/cli/src/commands/contrast-svg-gradient.browser.test.ts b/packages/cli/src/commands/contrast-svg-gradient.browser.test.ts
index b06de0db1b8..4c2187f2588 100644
--- a/packages/cli/src/commands/contrast-svg-gradient.browser.test.ts
+++ b/packages/cli/src/commands/contrast-svg-gradient.browser.test.ts
@@ -4,6 +4,8 @@ import type { AddressInfo } from "node:net";
import { join } from "node:path";
import { afterAll, beforeAll, expect, it } from "vitest";
import { openSettledCompositionPage } from "../capture/captureCompositionFrame.js";
+import { framePixels } from "../utils/framePixels.js";
+import { measureContrast, parseContrastCandidate } from "./contrast-measure.js";
const TEXT = `x="20" font-family="sans-serif" font-weight="700" font-size="40"`;
const HTML = `
@@ -49,14 +51,13 @@ it("judges SVG gradient text by its stops and skips a pattern fill", async () =>
});
try {
await page.addScriptTag({ content: SCRIPT });
- const candidates = await page.evaluate("window.__contrastAuditPrepare()");
+ const candidates = (await page.evaluate("window.__contrastAuditPrepare()")) as unknown[];
const shot = await page.screenshot({ encoding: "base64", omitBackground: true });
- const entries = (await page.evaluate(
- (png: string, items: unknown) =>
- Reflect.apply(Reflect.get(window, "__contrastAuditFinish"), window, [png, 0, items, null]),
- shot,
- candidates,
- )) as { selector: string; fg: string; wcagAA: boolean }[];
+ const entries = candidates.flatMap((value) => {
+ const candidate = parseContrastCandidate(value);
+ const measured = candidate && measureContrast(candidate, framePixels(shot));
+ return measured ? [{ selector: candidate.selector, ...measured }] : [];
+ });
const bySelector = Object.fromEntries(
entries.map(({ selector, fg, wcagAA }) => [selector, { fg, wcagAA }]),
);
diff --git a/packages/cli/src/commands/layout-audit.browser.test.ts b/packages/cli/src/commands/layout-audit.browser.test.ts
index 53523fbef56..d42a5411599 100644
--- a/packages/cli/src/commands/layout-audit.browser.test.ts
+++ b/packages/cli/src/commands/layout-audit.browser.test.ts
@@ -3,6 +3,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
+import { measureContrast, parseContrastCandidate } from "./contrast-measure.js";
const __dirname = dirname(fileURLToPath(import.meta.url));
const script = readFileSync(join(__dirname, "layout-audit.browser.js"), "utf-8");
@@ -2623,12 +2624,10 @@ describe("contrast-audit.browser clip-path visibility", () => {
delete (
window as unknown as {
__contrastAuditPrepare?: unknown;
- __contrastAuditFinish?: unknown;
__contrastAuditRestoreIfPending?: unknown;
__contrastAuditRestores?: unknown;
}
).__contrastAuditPrepare;
- delete (window as unknown as { __contrastAuditFinish?: unknown }).__contrastAuditFinish;
delete (window as unknown as { __contrastAuditRestoreIfPending?: unknown })
.__contrastAuditRestoreIfPending;
delete (window as unknown as { __contrastAuditRestores?: unknown }).__contrastAuditRestores;
@@ -2813,23 +2812,12 @@ describe("contrast-audit.browser background sampling", () => {
document.body.innerHTML = "";
delete (document as unknown as { elementFromPoint?: unknown }).elementFromPoint;
delete (window as unknown as { __contrastAuditPrepare?: unknown }).__contrastAuditPrepare;
- delete (window as unknown as { __contrastAuditFinish?: unknown }).__contrastAuditFinish;
delete (window as unknown as { __contrastAuditRestoreIfPending?: unknown })
.__contrastAuditRestoreIfPending;
delete (window as unknown as { __contrastAuditRestores?: unknown }).__contrastAuditRestores;
});
- // Locks in the "already correct" finding from investigating the
- // solid-fill-pill/button false-positive report: a rounded pill/button
- // with its own solid background, sitting on a busy/bright page
- // background, must NOT be flagged even though the two-phase
- // prepare()/finish() path (hide text, sample the real pixels directly
- // inside the element's own bbox) replaced the ring+own-background-walk
- // heuristic this used to rely on. The pixel buffer here is real per-pixel
- // data (not the flat-white default), with a dark region standing in for
- // the pill sitting inside a bright page background, so this exercises the
- // actual bbox-sampling logic in __contrastAuditFinish rather than a fixed
- // stub value.
+ // A dark pill with its own solid fill on a bright, busy page: only the pixels inside the text's box count.
it("does not flag a solid-fill pill/button with adequate contrast", async () => {
document.body.innerHTML = `
@@ -4032,27 +4020,7 @@ function installAuditScript(): void {
// position (e.g. a solid-fill pill sitting on a busy page background) so the
// two-phase prepare/finish sampling has something real to distinguish.
function installContrastScript(pixels?: Uint8ClampedArray): void {
- class MockImage {
- onload: (() => void) | null = null;
- onerror: (() => void) | null = null;
- naturalWidth = 640;
- naturalHeight = 360;
-
- set src(_value: string) {
- this.onload?.();
- }
- }
-
- vi.stubGlobal("Image", MockImage);
- const getContextSpy = vi.spyOn(HTMLCanvasElement.prototype, "getContext") as unknown as {
- mockReturnValue(value: CanvasRenderingContext2D): void;
- };
- getContextSpy.mockReturnValue({
- drawImage() {},
- getImageData() {
- return { data: pixels ?? new Uint8ClampedArray(640 * 360 * 4).fill(255) };
- },
- } as unknown as CanvasRenderingContext2D);
+ contrastPixels = pixels ?? new Uint8ClampedArray(640 * 360 * 4).fill(255);
window.eval(contrastScript);
}
@@ -4087,17 +4055,16 @@ function pixelsWithRegion(
return data;
}
+let contrastPixels: Uint8ClampedArray = new Uint8ClampedArray();
+
async function runContrastAudit(): Promise>> {
- const w = window as unknown as {
- __contrastAuditPrepare: () => Array>;
- __contrastAuditFinish: (
- imgBase64: string,
- time: number,
- candidates: Array>,
- ) => Promise>>;
- };
- const candidates = w.__contrastAuditPrepare();
- return w.__contrastAuditFinish("stub", 0, candidates);
+ const candidates: unknown[] = Reflect.get(window, "__contrastAuditPrepare")();
+ const pixels = { width: 640, height: 360, data: new Uint8Array(contrastPixels) };
+ return candidates.flatMap((value) => {
+ const candidate = parseContrastCandidate(value);
+ const measured = candidate && measureContrast(candidate, pixels);
+ return measured ? [{ selector: candidate.selector, text: candidate.text, ...measured }] : [];
+ });
}
interface AuditIssue {
diff --git a/packages/cli/src/commands/motion-signature.browser.js b/packages/cli/src/commands/motion-signature.browser.js
index f69647b387f..fcb287152cc 100644
--- a/packages/cli/src/commands/motion-signature.browser.js
+++ b/packages/cli/src/commands/motion-signature.browser.js
@@ -1,7 +1,7 @@
// Shared "what counts as motion" classifier, injected before layout-audit.browser.js and motion-sample.browser.js.
// The frozen-sweep guard (sweep_static) and keepsMoving liveness (motion_frozen) meet in one decision, so both
// must count the same channels as motion; only quantization differs (liveness buckets 2px and 0.08 opacity).
-// Where both read still, check asks framesDiffer below, which compares the rendered frames.
+// Where both read still, check compares the rendered frames (utils/framePixels.ts).
// A channel reader returns a string equal across samples iff it did not visibly change, "" when it does not apply.
(function () {
const IGNORE_TAGS = new Set(["SCRIPT", "STYLE", "TEMPLATE", "NOSCRIPT", "META", "LINK"]);
@@ -429,57 +429,6 @@
return parts.join("|");
}
- // --- Rendered frames: the last word where DOM channels cannot see paint ------
- // A frame moved when enough pixels changed by more than render noise (antialiasing, dither) on some channel.
- // ponytail: fewer than FRAME_MIN_CHANGED_PIXELS changed pixels reads as still; lower it for tinier motion.
- const FRAME_CHANNEL_NOISE = 24;
- const FRAME_MIN_CHANGED_PIXELS = 16;
- let reference = { png: "", pixels: null };
-
- // Decoded in the page like the contrast pass, so no image library is needed.
- async function framePixels(png) {
- const image = new Image();
- image.src = "data:image/png;base64," + png;
- await image.decode();
- const canvas = document.createElement("canvas");
- canvas.width = image.naturalWidth;
- canvas.height = image.naturalHeight;
- const ctx2d = canvas.getContext("2d", { willReadFrequently: true });
- ctx2d.drawImage(image, 0, 0);
- return ctx2d.getImageData(0, 0, canvas.width, canvas.height);
- }
-
- function pixelChanged(a, b, i) {
- return (
- Math.abs(a[i] - b[i]) > FRAME_CHANNEL_NOISE ||
- Math.abs(a[i + 1] - b[i + 1]) > FRAME_CHANNEL_NOISE ||
- Math.abs(a[i + 2] - b[i + 2]) > FRAME_CHANNEL_NOISE ||
- Math.abs(a[i + 3] - b[i + 3]) > FRAME_CHANNEL_NOISE
- );
- }
-
- // Base64 PNG screenshots in, "did anything visible change" out. The first frame is usually a run's
- // reference compared against many, so its decode is kept.
- // fallow-ignore-next-line complexity
- async function framesDiffer(first, second) {
- if (first === second) return false;
- if (!first || !second) return true;
- if (reference.png !== first) reference = { png: first, pixels: await framePixels(first) };
- return pixelsDiffer(reference.pixels, await framePixels(second));
- }
-
- // fallow-ignore-next-line complexity
- function pixelsDiffer(a, b) {
- if (a.width !== b.width || a.height !== b.height) return true;
- let changed = 0;
- for (let i = 0; i < a.data.length; i += 4) {
- if (pixelChanged(a.data, b.data, i) && ++changed >= FRAME_MIN_CHANGED_PIXELS) return true;
- }
- return false;
- }
-
- window.__hyperframesFramesDiffer = framesDiffer;
-
window.__hyperframesMotionSignature = {
compositionRoot,
isVisibleElement,
diff --git a/packages/cli/src/commands/motionShot.ts b/packages/cli/src/commands/motionShot.ts
index c6ae302d857..da9864e8a00 100644
--- a/packages/cli/src/commands/motionShot.ts
+++ b/packages/cli/src/commands/motionShot.ts
@@ -19,6 +19,7 @@ import { dirname, resolve } from "node:path";
import { pageNavigationTimeoutMs } from "../utils/renderArgs.js";
import { gotoWhenSent } from "../capture/navigateForCapture.js";
import { resolveCompositionViewportFromHtml } from "../utils/compositionViewport.js";
+import { screenshotOnBlankPage } from "../utils/blankPageShot.js";
import { waitForRuntimeReady } from "../capture/captureCompositionFrame.js";
import {
assertWebGpuAdapterAvailable,
@@ -731,11 +732,9 @@ async function captureRenderedSvgStrip(
height: size.height,
label: `${cameraLabel(camera)} · filmstrip · ${times.length} frames${windowStr}`,
});
- await page.evaluate((svg: string) => document.body.insertAdjacentHTML("beforeend", svg), markup);
- await new Promise((resolveWait) => setTimeout(resolveWait, 60));
- const output = await page.screenshot({ type: "png" });
+ const output = await screenshotOnBlankPage(page, (blank) => blank.setContent(markup));
if (!output) throw new Error("screenshot returned no data");
- replaceFileAtomically(outPath, output as Uint8Array);
+ replaceFileAtomically(outPath, Buffer.from(output, "base64"));
return outPath;
}
diff --git a/packages/cli/src/commands/validate.ts b/packages/cli/src/commands/validate.ts
index 90939456079..ee0bafd1005 100644
--- a/packages/cli/src/commands/validate.ts
+++ b/packages/cli/src/commands/validate.ts
@@ -31,6 +31,8 @@ import {
waitForRuntimeReady,
} from "../capture/captureCompositionFrame.js";
import { failureMessage, jsonFailure } from "../utils/jsonError.js";
+import { framePixels } from "../utils/framePixels.js";
+import { measureContrast, parseContrastCandidate } from "./contrast-measure.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -286,17 +288,9 @@ export async function auditClipDurations(
return warnings;
}
-interface ContrastCandidate {
- selector: string;
- text: string;
- fg: [number, number, number, number];
- fontSize: number;
- fontWeight: number;
- large: boolean;
- bbox: { x: number; y: number; w: number; h: number };
-}
-
-async function runContrastAudit(page: import("puppeteer-core").Page): Promise {
+export async function runContrastAudit(
+ page: import("puppeteer-core").Page,
+): Promise {
const duration = await getCompositionDuration(page);
if (duration <= 0) return [];
@@ -313,54 +307,29 @@ async function runContrastAudit(page: import("puppeteer-core").Page): Promise
- typeof (window as unknown as Record).__contrastAuditPrepare === "function"
- ? (
- (window as unknown as Record).__contrastAuditPrepare as () => unknown
- )()
- : [],
- )) as ContrastCandidate[];
-
- const screenshot = (await page.screenshot({
+ // First inside the try: if it throws partway through hiding text, the finally still restores it.
+ const prepared = await page.evaluate(() => {
+ const prepare = Reflect.get(window, "__contrastAuditPrepare");
+ return typeof prepare === "function" ? Reflect.apply(prepare, window, []) : [];
+ });
+ const candidates = (Array.isArray(prepared) ? prepared : []).flatMap(
+ (value) => parseContrastCandidate(value) ?? [],
+ );
+ const screenshot = await page.screenshot({
encoding: "base64",
type: "png",
omitBackground: true,
- })) as string;
- const entries = await page.evaluate(
- (b64: string, time: number, cands: ContrastCandidate[]) =>
- typeof (window as unknown as Record).__contrastAuditFinish === "function"
- ? ((window as unknown as Record).__contrastAuditFinish as Function)(
- b64,
- time,
- cands,
- )
- : [],
- screenshot,
- t,
- candidates,
- );
- results.push(...(entries as ContrastEntry[]));
+ });
+ const pixels = framePixels(screenshot);
+ for (const candidate of candidates) {
+ const measured = measureContrast(candidate, pixels);
+ const { selector, text } = candidate;
+ if (measured) results.push({ time: t, selector, text, ...measured });
+ }
} finally {
- // If prepare(), the screenshot, or finish() above throws, this restores
- // any still-hidden text paint so the NEXT sample in the loop doesn't
- // audit a page with stale invisible elements. No-op after a normal
- // finish() call.
await page.evaluate(() => {
- const restore = (window as unknown as Record)
- .__contrastAuditRestoreIfPending;
- if (typeof restore === "function") (restore as () => void)();
+ const restore = Reflect.get(window, "__contrastAuditRestoreIfPending");
+ if (typeof restore === "function") Reflect.apply(restore, window, []);
});
}
}
diff --git a/packages/cli/src/utils/blankPageShot.ts b/packages/cli/src/utils/blankPageShot.ts
new file mode 100644
index 00000000000..ebd6556f35d
--- /dev/null
+++ b/packages/cli/src/utils/blankPageShot.ts
@@ -0,0 +1,17 @@
+import type { Page } from "puppeteer-core";
+
+/** A screenshot of what `build` draws on a blank page of the same size, which shares nothing with `page`. */
+export async function screenshotOnBlankPage(
+ page: Page,
+ build: (blank: Page) => Promise,
+): Promise {
+ const blank = await page.browser().newPage();
+ try {
+ const viewport = page.viewport();
+ if (viewport) await blank.setViewport(viewport);
+ await build(blank);
+ return await blank.screenshot({ encoding: "base64", type: "png" });
+ } finally {
+ await blank.close();
+ }
+}
diff --git a/packages/cli/src/utils/checkBrowser.test.ts b/packages/cli/src/utils/checkBrowser.test.ts
index 338c1e42748..d9fb1d9b6f8 100644
--- a/packages/cli/src/utils/checkBrowser.test.ts
+++ b/packages/cli/src/utils/checkBrowser.test.ts
@@ -2,6 +2,7 @@
// fallow-ignore-file code-duplication
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { DEFAULT_CONFIG } from "@hyperframes/engine";
+import { encodePng } from "@hyperframes/engine/alpha-blit";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
import os, { tmpdir } from "node:os";
@@ -34,6 +35,16 @@ import { closeManagedBrowser } from "../browser/launch.js";
import { serveStaticProjectHtml } from "./staticProjectServer.js";
import type { ProjectDir } from "./project.js";
+const solidPng = (channel: number) =>
+ encodePng(
+ 640,
+ 360,
+ new Uint8Array(640 * 360 * 4).map((_, i) => (i % 4 === 3 ? 255 : channel)),
+ ).toString("base64");
+const WHITE_PNG = solidPng(255);
+const BLACK_PNG = solidPng(0);
+const GRAY_PNG = solidPng(128);
+
const mocks = vi.hoisted(() => ({
stopListeners: new Set<() => void>(),
proxyProgress: {
@@ -188,7 +199,6 @@ afterEach(() => {
Reflect.deleteProperty(window, "__hyperframesGeometryCandidates");
Reflect.deleteProperty(window, "__hyperframesLayoutAudit");
Reflect.deleteProperty(window, "__contrastAuditPrepare");
- Reflect.deleteProperty(window, "__contrastAuditFinish");
Reflect.deleteProperty(window, "__contrastAuditRestores");
Reflect.deleteProperty(window, "__contrastAuditRestoreIfPending");
mocks.scanProjectMediaCodecMap.mockResolvedValue({});
@@ -555,12 +565,7 @@ it("fails at once when the page crashes, instead of waiting out the deadline", a
}
});
-it("round-trips the browser script's raw contrast candidates back into finish", async () => {
- // The U2 regression class: Node parses prepare's candidates for reporting,
- // but must hand the UNTOUCHED objects back to __contrastAuditFinish — the
- // page script samples pixels via its own bbox shape (w/h). A normalized
- // candidate (width/height) makes every sample rect NaN and the audit
- // silently reports zero checked elements as green.
+it("measures the contrast of the browser script's own candidates", async () => {
vi.spyOn(Date, "now").mockReturnValue(100);
mountCanvasFixture(`