/** * Named diff settings, from the most sensitive to the least. */ export const DIFF_PRESETS = [ "strict", "sensitive", "standard", "tolerant", "relaxed", ] as const; /** * Named diff settings: * - `strict`: every changed pixel, except anti-aliasing. * - `sensitive`: changes from 5 pixels, including a one-shade color change on * a small element. * - `standard` (default): changes from 20 pixels, and faint color changes over * 3% of the screenshot. * - `tolerant`: changes from 50 pixels, and faint color changes over 10% of * the screenshot. * - `relaxed`: changes from 200 pixels, and faint color changes over a * quarter of the screenshot. For charts, maps and photos. */ export type DiffPreset = (typeof DIFF_PRESETS)[number]; const DIFF_ANTIALIASING = ["classic", "subpixel", "off"] as const; /** * How pixels that differ only by anti-aliasing are told apart: * - `classic` (default): ignores them, as Argos always has. * - `subpixel`: also ignores re-hinted text and edges over gradients, but * reports recolored edges. * - `off`: counts every pixel. */ export type DiffAntialiasing = (typeof DIFF_ANTIALIASING)[number]; /** * A pixel count like `"20px"`, a share of the compared image like `"0.5%"`, * or the smaller of both like `"min(20px, 0.02%)"`. */ export type DiffArea = `${number}px` | `${number}%` | `min(${string})`; /** * Fires when at least `minDiffArea` of the screenshot changed color by more * than `colorThreshold`. */ export interface DiffDetector { /** * How much a pixel's color must change to count, from 0 (any change) to 1 * (nothing counts). Brightness counts most and blue least: for grays, 0.15 * is a step of 40 out of 255. */ colorThreshold: number; /** * How much of the screenshot must change for the detector to fire: a pixel * count like `"20px"`, a share of the compared image like `"0.5%"`, or the * smaller of both like `"min(20px, 0.02%)"`. A change of exactly this size * is reported. */ minDiffArea: DiffArea; } /** * Diff settings chosen detector by detector. */ export interface CustomDiffConfig { /** * Between 1 and 8 detectors. A screenshot is reported as changed when any * of them fires. When several fire, the diff mask comes from the one that * found the most pixels. */ detectors: DiffDetector[]; /** * How pixels that differ only by anti-aliasing are told apart. * @default "classic" */ antialiasing?: DiffAntialiasing; } /** * How a screenshot is compared with its baseline: a preset name, or custom * detectors. * @example "relaxed" * @example { detectors: [{ colorThreshold: 0.1, minDiffArea: "min(10px, 0.01%)" }] } * @see https://argos-ci.com/docs/learn/platform-fundamentals/how-argos-detects-visual-differences#diff-settings */ export type DiffConfig = DiffPreset | CustomDiffConfig; /** Where the move from `threshold` to `diff` is documented. */ export const THRESHOLD_MIGRATION_DOCS_URL = "https://argos-ci.com/docs/learn/platform-fundamentals/how-argos-detects-visual-differences#migrate-from-threshold"; /** Most detectors Argos evaluates for one screenshot. */ const MAX_DIFF_DETECTORS = 8; const AMOUNT = /^(\d+(?:\.\d+)?)(px|%)$/; const SMALLER_OF = /^min\(([^,]+),([^,]+)\)$/; type AmountUnit = "px" | "%"; function parseAmountUnit(value: string): AmountUnit | null { const match = AMOUNT.exec(value.trim()); if (!match) { return null; } const [, number, unit] = match; if (unit === "%") { return Number(number) <= 100 ? "%" : null; } return "px"; } /** * Check a `minDiffArea` the way Argos reads it: a pixel count, a share of the * image up to 100%, or the smaller of one of each. */ function isValidDiffArea(value: unknown): boolean { if (typeof value !== "string") { return false; } const smallerOf = SMALLER_OF.exec(value.trim()); if (smallerOf) { const units = [smallerOf[1], smallerOf[2]].map((amount) => parseAmountUnit(amount ?? ""), ); return units.includes("px") && units.includes("%"); } return parseAmountUnit(value) !== null; } function isObject(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } function quoteList(values: readonly string[]) { const quoted = values.map((value) => `"${value}"`); return `${quoted.slice(0, -1).join(", ")} or ${quoted.at(-1)}`; } function fail(message: string): never { throw new Error(`Invalid diff: ${message}.`); } /** Reject a key Argos doesn't read, in the object at `path` (the root without). */ function checkKeys( value: Record, allowed: readonly string[], path?: string, ) { const unknown = Object.keys(value).find((key) => !allowed.includes(key)); if (unknown !== undefined) { fail( path ? `${path} has an unknown key "${unknown}"` : `unknown key "${unknown}"`, ); } } function validateDetector(detector: unknown, index: number) { const path = `detectors[${index}]`; if (!isObject(detector)) { fail(`${path} must be an object with "colorThreshold" and "minDiffArea"`); } checkKeys(detector, ["colorThreshold", "minDiffArea"], path); const { colorThreshold, minDiffArea } = detector; if ( typeof colorThreshold !== "number" || Number.isNaN(colorThreshold) || colorThreshold < 0 || colorThreshold > 1 ) { fail(`${path}.colorThreshold must be a number between 0 and 1`); } if (!isValidDiffArea(minDiffArea)) { fail( `${path}.minDiffArea must be a pixel count like "20px", a share of the screenshot like "0.5%", or the smaller of both like "min(20px, 0.02%)"`, ); } } /** * Check a `diff` value the way the Argos API does, so a mistake fails where it * is made instead of at upload. */ export function validateDiff(diff: unknown): asserts diff is DiffConfig { if (typeof diff === "string") { if (!(DIFF_PRESETS as readonly string[]).includes(diff)) { fail( `"${diff}" is not a preset. Use ${quoteList(DIFF_PRESETS)}, or an object with "detectors"`, ); } return; } if (!isObject(diff)) { fail( `use a preset (${quoteList(DIFF_PRESETS)}) or an object with "detectors"`, ); } if ("preset" in diff) { fail( `a preset is the whole value, like "strict", and can't be combined with detectors`, ); } checkKeys(diff, ["detectors", "antialiasing"]); const { detectors, antialiasing } = diff; if ( !Array.isArray(detectors) || detectors.length < 1 || detectors.length > MAX_DIFF_DETECTORS ) { fail(`"detectors" must be a list of 1 to ${MAX_DIFF_DETECTORS} detectors`); } detectors.forEach(validateDetector); if ( antialiasing !== undefined && !(DIFF_ANTIALIASING as readonly unknown[]).includes(antialiasing) ) { fail(`"antialiasing" must be ${quoteList(DIFF_ANTIALIASING)}`); } } /** * Read a `diff` written as text, in an environment variable or on the command * line: a preset name, or custom settings as JSON. * @example parseDiff("relaxed") * @example parseDiff('{"detectors":[{"colorThreshold":0.1,"minDiffArea":"10px"}]}') */ export function parseDiff(value: string): DiffConfig { const text = value.trim(); if (!text.startsWith("{")) { validateDiff(text); return text; } let parsed: unknown; try { parsed = JSON.parse(text); } catch { fail("custom settings must be valid JSON"); } validateDiff(parsed); return parsed; } /** * Throw on `threshold`, which `diff` replaced: options that still set it * would otherwise compare with other settings without a word. */ export function assertNoThreshold(options: object): void { if ("threshold" in options && options.threshold != null) { throw new Error( `The "threshold" option was removed. Use "diff" with a preset like "standard", or custom detectors. Learn more: ${THRESHOLD_MIGRATION_DOCS_URL}`, ); } } /** * Read the `diff` option of a screenshot, validated. */ export function getDiffOption(options: { diff?: DiffConfig | undefined; }): DiffConfig | undefined { assertNoThreshold(options); if (options.diff !== undefined) { validateDiff(options.diff); } return options.diff; }