@cappa/core 0.16.0 → 0.18.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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["open","readFile","writeFile","gmsd","fsp","path","os","fs","blazediffCompare","interpret","path","path","fsp","glob","getLogger","fs","path","fsp","path","glob","randomUUID","relative","getLogger","path","path","fsp","path","path","createHash","glob","path","spawn","path","getLogger","path","readSize","path","path","fsp","createHash","interpret","path"],"sources":["../src/features/png/util.ts","../src/features/png/png.ts","../src/compare/gmsd.ts","../src/compare/pixel.ts","../src/config.ts","../src/consoleEvents.ts","../src/mapWithConcurrency.ts","../src/paths.ts","../src/filesystem.ts","../src/screenshots/manifest.ts","../src/webServer/unreachable.ts","../src/runner/tasks.ts","../src/runner/types.ts","../src/runner/CaptureRunner.ts","../src/screenshot.ts","../src/agent/paths.ts","../src/agent/verdict.ts","../src/agent/reviewIndex.ts","../src/screenshots/groupScreenshots.ts","../src/screenshots/collectScreenshots.ts","../src/webServer/process.ts","../src/webServer/readiness.ts","../src/webServer/WebServerPool.ts","../src/engine/RunStore.ts","../src/engine/types.ts","../src/engine/WarmBrowser.ts","../src/engine/WatchSession.ts","../src/engine/LocalEngine.ts","../src/store.ts","../src/agent/tiles.ts","../src/agent/review.ts","../src/webServer/resolve.ts"],"sourcesContent":["import { open } from \"node:fs/promises\";\nimport type { MetadataEntries } from \"./types\";\n\ntype ParsedChunk = {\n type: string;\n data: Buffer;\n length: number;\n offset: number;\n};\n\n// Magic Bytes:\n// The first 8 bytes of every valid PNG file.\n// Used to verify that the file is actually a PNG before processing.\nconst pngSignature = Buffer.from([\n 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,\n]);\n\n// A pre-calculated lookup table for the CRC32 algorithm.\n// We use this to quickly calculate the checksum for each chunk we write.\n// Without this table, calculating CRC bit-by-bit would be significantly slower.\nconst crcTable = new Uint32Array(256).map((_, index) => {\n let c = index;\n for (let k = 0; k < 8; k++) {\n c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n }\n\n return c >>> 0;\n});\n\n/**\n * Chunk Parser Generator\n *\n * A PNG file is essentially a list of chunks.\n * Structure of a chunk:\n * 1. Length (4 bytes): The size of the data field.\n * 2. Type (4 bytes): ASCII name (e.g., 'IHDR', 'tEXt', 'IEND').\n * 3. Data (Length bytes): The actual payload.\n * 4. CRC (4 bytes): Checksum.\n */\nfunction* readChunks(buffer: Buffer): Generator<ParsedChunk> {\n let offset = pngSignature.length;\n\n while (offset + 8 <= buffer.length) {\n const length = buffer.readUInt32BE(offset);\n const type = buffer.toString(\"ascii\", offset + 4, offset + 8);\n const dataStart = offset + 8;\n const dataEnd = dataStart + length;\n\n if (dataEnd > buffer.length) {\n return;\n }\n\n const data = buffer.subarray(dataStart, dataEnd);\n\n yield { type, data, length, offset };\n\n offset = dataEnd + 4; // Skip CRC\n\n if (type === \"IEND\") {\n return;\n }\n }\n}\n\n/**\n * Constructs a raw binary `tEXt` chunk.\n */\nexport function createTextChunk(key: string, value: string) {\n const keyBuffer = Buffer.from(key, \"latin1\");\n const valueBuffer = Buffer.from(value, \"latin1\");\n const data = Buffer.concat([keyBuffer, Buffer.from([0]), valueBuffer]);\n const lengthBuffer = Buffer.alloc(4);\n const typeBuffer = Buffer.from(\"tEXt\");\n\n lengthBuffer.writeUInt32BE(data.length, 0);\n\n const crcBuffer = Buffer.alloc(4);\n crcBuffer.writeUInt32BE(crc32(Buffer.concat([typeBuffer, data])), 0);\n\n return Buffer.concat([lengthBuffer, typeBuffer, data, crcBuffer]);\n}\n\n/**\n * Calculates the CRC32 checksum for a buffer.\n * Used to ensure data integrity.\n */\nexport function crc32(buffer: Buffer) {\n let crc = 0 ^ -1;\n\n for (let i = 0; i < buffer.length; i++) {\n // biome-ignore lint/style/noNonNullAssertion: we know the index is valid\n crc = (crc >>> 8) ^ crcTable[(crc ^ buffer[i]!) & 0xff]!;\n }\n\n return (crc ^ -1) >>> 0;\n}\n\n/**\n * Helper to locate the IEND chunk, which marks the end of a PNG stream.\n */\nfunction findIendChunk(buffer: Buffer): ParsedChunk | undefined {\n for (const chunk of readChunks(buffer)) {\n if (chunk.type === \"IEND\") {\n return chunk;\n }\n }\n\n return undefined;\n}\n\n/**\n * Inserts metadata chunks into a PNG buffer.\n * It places them right before the final `IEND` chunk.\n */\nexport function injectTextMetadata(buffer: Buffer, metadata: MetadataEntries) {\n if (!buffer.subarray(0, pngSignature.length).equals(pngSignature)) {\n return buffer;\n }\n\n const iendChunk = findIendChunk(buffer);\n if (!iendChunk) {\n return buffer;\n }\n\n const textChunks = Object.entries(metadata).map(([key, value]) =>\n createTextChunk(key, value),\n );\n\n return Buffer.concat([\n buffer.subarray(0, iendChunk.offset),\n ...textChunks,\n buffer.subarray(iendChunk.offset),\n ]);\n}\n\nexport function isValidPngSignature(buffer: Buffer): boolean {\n if (buffer.length < pngSignature.length) return false;\n return buffer.subarray(0, pngSignature.length).equals(pngSignature);\n}\n\nconst IHDR_MIN_BYTES = 24;\n\nexport async function readIhdrDimensions(\n source: string | Buffer,\n): Promise<{ width: number; height: number }> {\n let buf: Buffer;\n\n if (typeof source === \"string\") {\n const fh = await open(source, \"r\");\n try {\n buf = Buffer.alloc(IHDR_MIN_BYTES);\n await fh.read(buf, 0, IHDR_MIN_BYTES, 0);\n } finally {\n await fh.close();\n }\n } else {\n buf = source;\n }\n\n if (\n buf.length < IHDR_MIN_BYTES ||\n !buf.subarray(0, pngSignature.length).equals(pngSignature)\n ) {\n throw new Error(\"Not a valid PNG\");\n }\n\n const width = buf.readUInt32BE(16);\n const height = buf.readUInt32BE(20);\n return { width, height };\n}\n\n/**\n * Scans a raw PNG buffer and extracts key-value pairs from `tEXt` chunks.\n */\nexport function extractTextMetadata(buffer: Buffer): MetadataEntries {\n if (!buffer.subarray(0, pngSignature.length).equals(pngSignature)) {\n return {};\n }\n\n const metadata: MetadataEntries = {};\n\n for (const chunk of readChunks(buffer)) {\n if (chunk.type !== \"tEXt\") {\n continue;\n }\n\n const separatorIndex = chunk.data.indexOf(0);\n if (separatorIndex < 0) {\n continue;\n }\n\n const key = chunk.data.toString(\"latin1\", 0, separatorIndex);\n const value = chunk.data.toString(\"latin1\", separatorIndex + 1);\n\n metadata[key] = value;\n }\n\n return metadata;\n}\n","import { readFile, writeFile } from \"node:fs/promises\";\nimport sharp from \"sharp\";\nimport type { MetadataEntries } from \"./types\";\nimport { extractTextMetadata, injectTextMetadata } from \"./util\";\n\n/**\n * A wrapper around `sharp` that adds support for reading and writing\n * textual metadata (tEXt chunks). Used for fast PNG decode/encode.\n */\nexport class PNG {\n private width_: number;\n private height_: number;\n private data_: Buffer;\n private sourcePath?: string;\n private metadataEntries: MetadataEntries;\n\n private constructor(\n width: number,\n height: number,\n data: Buffer,\n sourcePath?: string,\n metadata?: MetadataEntries,\n ) {\n this.width_ = width;\n this.height_ = height;\n this.data_ = data;\n this.sourcePath = sourcePath;\n this.metadataEntries = { ...(metadata ?? {}) };\n }\n\n static create(width: number, height: number): PNG {\n const data = Buffer.alloc(width * height * 4, 0);\n return new PNG(width, height, data);\n }\n\n static async load(source: string | Buffer): Promise<PNG> {\n const buffer = typeof source === \"string\" ? await readFile(source) : source;\n const metadata = extractTextMetadata(buffer);\n\n const pipeline = sharp(buffer).ensureAlpha();\n const { data: raw, info } = await pipeline\n .raw()\n .toBuffer({ resolveWithObject: true });\n\n const data = Buffer.from(raw);\n const sourcePath = typeof source === \"string\" ? source : undefined;\n\n return new PNG(info.width, info.height, data, sourcePath, metadata);\n }\n\n get width(): number {\n return this.width_;\n }\n\n get height(): number {\n return this.height_;\n }\n\n get data(): Buffer {\n return this.data_;\n }\n\n get metadata(): MetadataEntries {\n return { ...this.metadataEntries };\n }\n\n setMetadata(key: string, value: string): void {\n this.metadataEntries = { ...this.metadataEntries, [key]: value };\n }\n\n replaceMetadata(metadata: MetadataEntries): void {\n this.metadataEntries = { ...metadata };\n }\n\n removeMetadata(key: string): void {\n const { [key]: _, ...remaining } = this.metadataEntries;\n this.metadataEntries = remaining;\n }\n\n clearMetadata(): void {\n this.metadataEntries = {};\n }\n\n async toBuffer(): Promise<Buffer> {\n const baseBuffer = await sharp(this.data_, {\n raw: { width: this.width_, height: this.height_, channels: 4 },\n })\n .png()\n .toBuffer();\n\n if (Object.keys(this.metadataEntries).length === 0) {\n return baseBuffer;\n }\n\n return injectTextMetadata(baseBuffer, this.metadataEntries);\n }\n\n async save(filepath?: string): Promise<void> {\n const targetPath = filepath ?? this.sourcePath;\n\n if (!targetPath) {\n throw new Error(\"No filepath provided for saving PNG\");\n }\n\n await writeFile(targetPath, await this.toBuffer());\n }\n}\n","import fs from \"node:fs\";\nimport gmsd, { type GmsdOptions } from \"@blazediff/gmsd\";\nimport { getLogger } from \"@cappa/logger\";\nimport { PNG } from \"../features/png/png\";\nimport type { DiffConfigGMSD } from \"../types\";\n\nexport type CompareOptions = GmsdOptions;\n\nexport interface CompareResult {\n gmsd: number;\n diffBuffer?: Buffer; // PNG buffer of the diff image\n passed: boolean; // Whether the comparison passed based on threshold\n error?: string; // Error message if the comparison failed\n}\n\nconst compare = (\n image1: Uint8Array | Uint8ClampedArray,\n image2: Uint8Array | Uint8ClampedArray,\n diff: Uint8Array | Uint8ClampedArray | undefined,\n width: number,\n height: number,\n options?: GmsdOptions,\n) => {\n return gmsd(image1, image2, diff, width, height, options);\n};\n\n/**\n * Compare two PNG images and return the difference\n * @param image1 - Baseline (expected) image (file path or Buffer)\n * @param image2 - Current (actual) image (file path or Buffer)\n * @param withDiff - Whether to create a diff image\n * @param options - Comparison options\n * @returns Comparison result\n */\nexport async function compareImagesGMSD(\n image1: string | Buffer,\n image2: string | Buffer,\n withDiff: boolean = false,\n options: DiffConfigGMSD = {},\n): Promise<CompareResult> {\n // Load both PNGs in parallel with sharp for better performance\n const [png1, png2] = await Promise.all([loadPNG(image1), loadPNG(image2)]);\n\n const { width, height } = png1;\n\n if (width !== png2.width || height !== png2.height) {\n return { gmsd: Infinity, passed: false };\n }\n\n const diff = withDiff ? PNG.create(width, height) : undefined;\n\n try {\n const gmsd = compare(png1.data, png2.data, diff?.data, width, height, {\n downsample: options.downsample ?? 0,\n c: options.c ?? 170,\n });\n\n // Convert diff image to buffer\n const diffBuffer = diff\n ? await annotateDiffImage(diff, options).toBuffer()\n : undefined;\n\n return {\n gmsd,\n diffBuffer,\n passed: gmsd <= (options.threshold ?? 0.1),\n };\n } catch (error) {\n getLogger().error((error as Error).message || \"Unknown error\");\n\n return {\n gmsd: Infinity,\n passed: false,\n error: (error as Error).message || \"Unknown error\",\n };\n }\n}\n\n/**\n * Load a PNG image from file path or Buffer\n */\nasync function loadPNG(source: string | Buffer): Promise<PNG> {\n return PNG.load(source);\n}\n\nfunction annotateDiffImage(image: PNG, options: DiffConfigGMSD) {\n image.setMetadata(\"cappa.diff.algorithm\", \"gmsd\");\n\n for (const [key, value] of Object.entries(options)) {\n if (value === undefined) {\n continue;\n }\n\n image.setMetadata(`cappa.diff.${key}`, String(value));\n }\n\n return image;\n}\n\n/**\n * Save a comparison result diff image to file\n * @param result - Comparison result containing diffBuffer\n * @param outputPath - Path to save the diff image\n */\nexport function saveDiffImage(result: CompareResult, outputPath: string): void {\n if (!result.diffBuffer) {\n throw new Error(\"No diff buffer available in comparison result\");\n }\n\n fs.writeFileSync(outputPath, result.diffBuffer);\n}\n\n/**\n * Quick comparison function that returns only pass/fail\n * @param image1 - Baseline (expected) image (file path or Buffer)\n * @param image2 - Current (actual) image (file path or Buffer)\n * @param options - Comparison options\n * @returns Whether the images match\n */\nexport async function imagesMatchGMSD(\n image1: string | Buffer,\n image2: string | Buffer,\n options: DiffConfigGMSD = {},\n): Promise<boolean> {\n const result = await compareImagesGMSD(image1, image2, false, options);\n\n return result.passed;\n}\n","import fs from \"node:fs\";\nimport fsp from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport {\n type BlazeDiffOptions,\n type BlazeDiffResult,\n compare as blazediffCompare,\n} from \"@blazediff/core-native\";\nimport { type InterpretResult, interpret } from \"@blazediff/interpret-native\";\nimport { getLogger } from \"@cappa/logger\";\nimport { PNG } from \"../features/png/png\";\nimport {\n injectTextMetadata,\n isValidPngSignature,\n readIhdrDimensions,\n} from \"../features/png/util\";\nimport type { DiffConfig } from \"../types\";\n\n/** Pixel diff options: Cappa `DiffConfig` plus optional native-only output tuning. */\nexport type CompareOptions = DiffConfig &\n Partial<Pick<BlazeDiffOptions, \"diffMask\" | \"compression\" | \"quality\">>;\n\nexport interface CompareResult {\n numDiffPixels: number;\n totalPixels: number;\n percentDifference: number;\n diffBuffer?: Buffer; // PNG buffer of the diff image\n passed: boolean; // Whether the comparison passed based on threshold\n error?: string; // Error message if the comparison failed\n differentSizes: boolean; // Whether the images have different sizes\n interpretation?: InterpretResult; // Structured diff analysis (when `interpret` is enabled)\n}\n\ntype TempState = { tempRoot?: string };\n\nasync function ensureTempRoot(state: TempState): Promise<string> {\n if (!state.tempRoot) {\n state.tempRoot = await fsp.mkdtemp(path.join(os.tmpdir(), \"cappa-pxl-\"));\n }\n return state.tempRoot;\n}\n\nasync function resolveInputPath(\n source: string | Buffer,\n fileName: string,\n state: TempState,\n): Promise<string> {\n if (typeof source === \"string\") {\n await fsp.access(source, fs.constants.R_OK);\n return path.resolve(source);\n }\n\n if (!isValidPngSignature(source)) {\n throw new Error(\"Invalid PNG buffer: missing PNG signature\");\n }\n\n const root = await ensureTempRoot(state);\n const dest = path.join(root, fileName);\n await fsp.writeFile(dest, source);\n return dest;\n}\n\nfunction toNativeOptions(config: DiffConfig): BlazeDiffOptions {\n const extra = config as CompareOptions;\n const out: BlazeDiffOptions = {\n threshold: extra.threshold,\n antialiasing: extra.includeAA ?? false,\n };\n\n if (extra.diffMask !== undefined) {\n out.diffMask = extra.diffMask;\n }\n if (extra.compression !== undefined) {\n out.compression = extra.compression;\n }\n if (extra.quality !== undefined) {\n out.quality = extra.quality;\n }\n\n return out;\n}\n\n/**\n * Compare two PNG images and return the difference\n * @param image1 - Baseline (expected) image (file path or Buffer)\n * @param image2 - Current (actual) image (file path or Buffer). Order matters\n * for `interpret`: content only in `image2` is reported as an addition.\n * @param withDiff - Whether to create a diff image\n * @param options - Comparison options\n * @returns Comparison result\n */\nexport async function compareImages(\n image1: string | Buffer,\n image2: string | Buffer,\n withDiff: boolean = false,\n options: DiffConfig = {},\n): Promise<CompareResult> {\n const state: TempState = {};\n let diffPath: string | undefined;\n\n try {\n const p1 = await resolveInputPath(image1, \"expected.png\", state);\n const p2 = await resolveInputPath(image2, \"actual.png\", state);\n\n if (withDiff) {\n const root = await ensureTempRoot(state);\n diffPath = path.join(root, \"diff.png\");\n }\n\n const wantInterpret = !!(options as CompareOptions).interpret && withDiff;\n\n let nativeResult: BlazeDiffResult;\n\n try {\n // Never pass `interpret` to `compare` — the native binding skips writing\n // the diff image when interpret mode is on. Interpretation is fetched in\n // a separate call below when needed.\n nativeResult = await blazediffCompare(\n p1,\n p2,\n withDiff ? diffPath : undefined,\n toNativeOptions(options),\n );\n } catch (error) {\n getLogger().error((error as Error).message || \"Unknown error\");\n\n return {\n numDiffPixels: 0,\n totalPixels: 0,\n percentDifference: 0,\n passed: false,\n differentSizes: false,\n error: (error as Error).message || \"Unknown error\",\n };\n }\n\n if (nativeResult.match === false) {\n if (nativeResult.reason === \"file-not-exists\") {\n throw new Error(`File not found: ${nativeResult.file}`);\n }\n\n if (nativeResult.reason === \"layout-diff\") {\n return {\n numDiffPixels: 0,\n totalPixels: 0,\n percentDifference: 0,\n passed: false,\n differentSizes: true,\n };\n }\n }\n\n const { width, height } = await readIhdrDimensions(p1);\n const totalPixels = width * height;\n\n if (nativeResult.match) {\n return {\n numDiffPixels: 0,\n totalPixels,\n percentDifference: 0,\n diffBuffer: undefined,\n passed: isPassed(0, 0, options),\n differentSizes: false,\n };\n }\n\n let diffBuffer: Buffer | undefined;\n if (withDiff && diffPath) {\n const rawDiff = await fsp.readFile(diffPath);\n const diffMetadata: Record<string, string> = {\n \"cappa.diff.algorithm\": \"pixel\",\n };\n for (const [key, value] of Object.entries(options)) {\n if (value !== undefined) {\n diffMetadata[`cappa.diff.${key}`] = String(value);\n }\n }\n diffBuffer = injectTextMetadata(rawDiff, diffMetadata);\n }\n\n const numDiffPixels = nativeResult.diffCount;\n const percentDifference = nativeResult.diffPercentage;\n\n let interpretation: InterpretResult | undefined;\n if (wantInterpret && !nativeResult.match) {\n try {\n interpretation = await interpret(p1, p2, undefined, {\n source: \"pixel\",\n threshold: options.threshold,\n antialiasing: options.includeAA ?? false,\n });\n } catch {\n // Interpretation is best-effort; don't fail the comparison.\n }\n }\n\n return {\n numDiffPixels,\n totalPixels,\n percentDifference,\n diffBuffer,\n passed: isPassed(percentDifference, numDiffPixels, options),\n differentSizes: false,\n interpretation,\n };\n } finally {\n if (state.tempRoot) {\n await fsp\n .rm(state.tempRoot, { recursive: true, force: true })\n .catch(() => {\n // ignore cleanup errors\n });\n }\n }\n}\n\n/**\n * Save a comparison result diff image to file\n * @param result - Comparison result containing diffBuffer\n * @param outputPath - Path to save the diff image\n */\nexport function saveDiffImage(result: CompareResult, outputPath: string): void {\n if (!result.diffBuffer) {\n throw new Error(\"No diff buffer available in comparison result\");\n }\n\n fs.writeFileSync(outputPath, result.diffBuffer);\n}\n\n/**\n * Quick comparison function that returns only pass/fail\n * @param image1 - Baseline (expected) image (file path or Buffer)\n * @param image2 - Current (actual) image (file path or Buffer). Order matters\n * for `interpret`: content only in `image2` is reported as an addition.\n * @param options - Comparison options\n * @returns Whether the images match\n */\nexport async function imagesMatch(\n image1: string | Buffer,\n image2: string | Buffer,\n options: DiffConfig = {},\n): Promise<boolean> {\n const result = await compareImages(image1, image2, false, options);\n\n return result.passed;\n}\n\n/**\n * Check if the comparison passed based on the options\n * @param percentDifference - Percentage difference between the images\n * @param numDiffPixels - Number of different pixels\n * @param options - Comparison options\n * @returns Whether the comparison passed\n */\nconst isPassed = (\n percentDifference: number,\n numDiffPixels: number,\n options: DiffConfig,\n) => {\n if (options.maxDiffPercentage && options.maxDiffPixels) {\n return (\n percentDifference <= options.maxDiffPercentage &&\n numDiffPixels <= options.maxDiffPixels\n );\n }\n\n if (options.maxDiffPercentage) {\n return percentDifference <= options.maxDiffPercentage;\n }\n\n if (options.maxDiffPixels) {\n return numDiffPixels <= options.maxDiffPixels;\n }\n\n // fallback to 0 pixels\n return numDiffPixels === 0;\n};\n\n/**\n * Create different size png image with all pixels red\n * @returns\n */\nexport async function createDiffSizePngImage(\n width: number,\n height: number,\n): Promise<Buffer> {\n const png = PNG.create(width, height);\n\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const idx = (width * y + x) << 2;\n png.data[idx] = 255; // red\n png.data[idx + 1] = 0; // green\n png.data[idx + 2] = 0; // blue\n png.data[idx + 3] = 255; // alpha\n }\n }\n\n return png.toBuffer();\n}\n","import type { ConfigEnv, PossiblePromise, UserConfig } from \"./types\";\n\n/**\n * Type helper to make it easier to use cappa.config.ts, or a function that returns it. The function receives a ConfigEnv object.\n */\nexport function defineConfig(\n options:\n | PossiblePromise<UserConfig>\n | ((env: ConfigEnv) => PossiblePromise<UserConfig>),\n): typeof options {\n return options;\n}\n","import type { ConsoleMessage, Page } from \"playwright-core\";\n\n/**\n * Minimum severity of browser console output to forward, ordered from most\n * to least severe. Browser `console.warn` is reported by Playwright as\n * `warning`; it maps to `\"warn\"` here.\n */\nexport type ConsoleLogLevel = \"error\" | \"warn\" | \"info\" | \"log\" | \"debug\";\n\n/**\n * `true` forwards every console message at the logger's debug level (the\n * historical behaviour), `false` forwards none, and a {@link ConsoleLogLevel}\n * forwards messages at or above that severity at their matching logger level.\n */\nexport type LogConsoleEvents = boolean | ConsoleLogLevel;\n\nexport const CONSOLE_LOG_LEVELS: readonly ConsoleLogLevel[] = [\n \"error\",\n \"warn\",\n \"info\",\n \"log\",\n \"debug\",\n];\n\ntype ConsoleEventLogger = Record<\n ConsoleLogLevel,\n (message: any, ...args: any[]) => void\n>;\n\n/** Maps a Playwright `ConsoleMessage.type()` onto a {@link ConsoleLogLevel}. */\nexport const toConsoleLogLevel = (\n type: ReturnType<ConsoleMessage[\"type\"]> | string,\n): ConsoleLogLevel => {\n switch (type) {\n case \"error\":\n case \"assert\":\n return \"error\";\n case \"warning\":\n return \"warn\";\n case \"info\":\n return \"info\";\n case \"debug\":\n case \"trace\":\n return \"debug\";\n default:\n return \"log\";\n }\n};\n\nconst severity = (level: ConsoleLogLevel) => CONSOLE_LOG_LEVELS.indexOf(level);\n\n/**\n * Wires a page's `console` and `pageerror` events to `logger` according to\n * `setting`. Uncaught page errors are always forwarded — at error level when\n * a severity threshold is set, at debug level otherwise.\n */\nexport const attachConsoleLogging = (\n page: Pick<Page, \"on\">,\n setting: LogConsoleEvents | undefined,\n logger: ConsoleEventLogger,\n): void => {\n const threshold = setting ?? true;\n\n if (threshold === true) {\n page.on(\"console\", (message) => {\n logger.debug(\"console\", message.text());\n });\n } else if (threshold !== false) {\n page.on(\"console\", (message) => {\n const level = toConsoleLogLevel(message.type());\n if (severity(level) > severity(threshold)) return;\n logger[level](`[browser ${level}]`, message.text());\n });\n }\n\n page.on(\"pageerror\", (error) => {\n if (typeof threshold === \"string\") {\n logger.error(\"[browser pageerror]\", error);\n } else {\n logger.debug(\"pageerror\", error);\n }\n });\n};\n","/**\n * Run async work over `items` with at most `concurrency` tasks in flight.\n * Preserves failure behavior: the first rejection rejects the returned promise.\n * Results are returned in the same order as the input items.\n */\nexport async function mapWithConcurrency<T, R = void>(\n concurrency: number,\n items: readonly T[],\n fn: (item: T, workerIndex: number) => Promise<R>,\n): Promise<R[]> {\n if (items.length === 0) {\n return [];\n }\n\n const limit = Math.max(1, concurrency);\n const workerCount = Math.min(limit, items.length);\n const results: R[] = new Array(items.length);\n let next = 0;\n\n const worker = async (workerIndex: number): Promise<void> => {\n while (true) {\n const i = next++;\n if (i >= items.length) {\n return;\n }\n const item = items[i];\n if (item === undefined) {\n return;\n }\n results[i] = await fn(item, workerIndex);\n }\n };\n\n await Promise.all(Array.from({ length: workerCount }, (_, i) => worker(i)));\n\n return results;\n}\n","import path from \"node:path\";\n\n/**\n * Screenshot filenames are not a trusted input.\n *\n * A name is whatever a plugin chose, and a plugin may derive it from something\n * it does not control either: `@cappa/plugin-storybook` reads\n * `parameters.cappa.variants[].filename` out of the browser, so the string\n * originates in story-author code. Every name eventually lands in\n * `path.resolve(<bucket dir>, name)`, which honours both absolute paths and\n * `../`, so without a guard a single story could write a PNG anywhere the\n * process can write.\n *\n * Two layers live here: `sanitizeScreenshotFilename` turns a name into a\n * relative path that cannot escape (used where a bad name should degrade rather\n * than fail a run), and `resolveInside` is the hard backstop at the write sink.\n */\n\n/**\n * Whether `target` resolves to something strictly inside `base`.\n *\n * Note this is deliberately stricter than a `startsWith(\"..\")` check on the\n * relative path, which also rejects legitimate names such as `..foo.png`.\n */\nexport function isPathInside(base: string, target: string): boolean {\n const relative = path.relative(base, target);\n\n return (\n relative !== \"\" &&\n relative !== \"..\" &&\n !relative.startsWith(`..${path.sep}`) &&\n !path.isAbsolute(relative)\n );\n}\n\n/**\n * Resolve `filename` inside `base`, rejecting absolute paths and any name that\n * escapes `base`.\n *\n * @param label - The bucket name used in the error message (`actual`, `diff`, …)\n */\nexport function resolveInside(\n base: string,\n filename: string,\n label: string,\n): string {\n const resolved = path.resolve(base, filename);\n\n if (path.isAbsolute(filename) || !isPathInside(base, resolved)) {\n throw new Error(\n `Refusing to resolve screenshot path outside of the ${label} directory: ${filename}`,\n );\n }\n\n return resolved;\n}\n\n/**\n * Turn a screenshot filename into a relative path that stays inside its bucket.\n *\n * Path separators are kept — they are how plugins express folders — but\n * traversal (`..`), no-op (`.`) and empty segments are dropped, backslashes are\n * normalised to `/`, and a Windows drive prefix is removed. Returns an empty\n * string when nothing usable is left, which callers treat as \"no name given\".\n */\nexport function sanitizeScreenshotFilename(filename: string): string {\n const segments = filename\n // Backslashes are separators on Windows, so `..\\\\escape.png` traverses there.\n .replace(/\\\\/g, \"/\")\n .split(\"/\")\n // A NUL byte would make the eventual `writeFile` throw.\n .map((segment) => segment.replace(/\\0/g, \"\").trim())\n .filter((segment) => segment !== \"\" && segment !== \".\" && segment !== \"..\");\n\n // `C:foo.png` is drive-relative on Windows, so the drive letter goes too.\n if (segments[0] && /^[a-zA-Z]:$/.test(segments[0])) {\n segments.shift();\n }\n\n return segments.join(\"/\");\n}\n","import fs from \"node:fs\";\nimport fsp, { glob } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { getLogger } from \"@cappa/logger\";\nimport { imagesMatch } from \"./compare/pixel\";\nimport { extractTextMetadata, injectTextMetadata } from \"./features/png/util\";\nimport { mapWithConcurrency } from \"./mapWithConcurrency\";\nimport { isPathInside, resolveInside } from \"./paths\";\nimport type {\n DiffConfig,\n DiffMetadata,\n DiffOptions,\n Screenshot,\n} from \"./types\";\n\nconst APPROVE_SCREENSHOTS_CONCURRENCY = 8;\n\n/**\n * Map a diff image path to its sidecar metadata path (`.png` -> `.json`).\n */\nexport function toDiffMetaPath(diffImagePath: string): string {\n const ext = path.extname(diffImagePath);\n return ext\n ? `${diffImagePath.slice(0, -ext.length)}.json`\n : `${diffImagePath}.json`;\n}\n\n/**\n * Read a diff metadata sidecar, returning `undefined` when it is missing or\n * cannot be parsed (so callers can degrade gracefully).\n */\nexport async function readDiffMeta(\n diffImagePath: string,\n): Promise<DiffMetadata | undefined> {\n try {\n const raw = await fsp.readFile(toDiffMetaPath(diffImagePath), \"utf8\");\n return JSON.parse(raw) as DiffMetadata;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Class for interacting with the local file system to store the screenshots.\n */\nexport class ScreenshotFileSystem {\n private readonly actual: string;\n private readonly expected: string;\n private readonly diff: string;\n\n constructor(outputDir: string) {\n this.actual = path.resolve(outputDir, \"actual\");\n this.expected = path.resolve(outputDir, \"expected\");\n this.diff = path.resolve(outputDir, \"diff\");\n\n this.ensureParentDirSync(this.actual);\n this.ensureParentDirSync(this.expected);\n this.ensureParentDirSync(this.diff);\n }\n\n clearActual() {\n this.removeDir(this.actual);\n }\n\n clearDiff() {\n this.removeDir(this.diff);\n }\n\n getActualScreenshots(): Promise<string[]> {\n return Array.fromAsync(glob(path.resolve(this.actual, \"**/*.png\")));\n }\n\n getExpectedScreenshots(): Promise<string[]> {\n return Array.fromAsync(glob(path.resolve(this.expected, \"**/*.png\")));\n }\n\n getDiffScreenshots(): Promise<string[]> {\n return Array.fromAsync(glob(path.resolve(this.diff, \"**/*.png\")));\n }\n\n clearActualAndDiff() {\n this.clearActual();\n this.clearDiff();\n }\n\n /**\n * Approve a screenshot based on its actual file path.\n * @param actualFilePath - The path to the actual screenshot file.\n * @returns The paths to the actual, expected, and diff screenshot files.\n */\n async approveFromActualPath(actualFilePath: string) {\n const actualAbsolute = this.resolveActualPath(actualFilePath);\n\n if (!isPathInside(this.actual, actualAbsolute)) {\n throw new Error(\n `Cannot approve screenshot outside of actual directory: ${actualFilePath}`,\n );\n }\n\n return this.approveRelative(path.relative(this.actual, actualAbsolute));\n }\n\n /**\n * Apply baseline updates for grouped screenshots (same rules as `cappa approve`).\n */\n async approveScreenshots(\n screenshots: Screenshot[],\n diff: DiffOptions,\n ): Promise<void> {\n const outputDir = path.dirname(this.actual);\n\n await mapWithConcurrency(\n APPROVE_SCREENSHOTS_CONCURRENCY,\n screenshots,\n (screenshot) => this.approveOneScreenshot(screenshot, outputDir, diff),\n );\n }\n\n private async approveOneScreenshot(\n screenshot: Screenshot,\n outputDir: string,\n diff: DiffOptions,\n ): Promise<void> {\n const logger = getLogger();\n\n logger.debug(`Approving screenshot with category: ${screenshot.category}`);\n\n if (screenshot.category === \"new\") {\n logger.debug(`Approving new screenshot: ${screenshot.actualPath}`);\n await this.approveFromActualPath(\n path.resolve(outputDir, screenshot.actualPath),\n );\n return;\n }\n\n if (screenshot.category === \"deleted\") {\n logger.debug(`Deleting expected screenshot: ${screenshot.expectedPath}`);\n await fsp.unlink(path.resolve(outputDir, screenshot.expectedPath));\n return;\n }\n\n if (screenshot.category === \"changed\") {\n logger.debug(`Deleting diff screenshot: ${screenshot.diffPath}`);\n const diffPath = path.resolve(outputDir, screenshot.diffPath);\n await fsp.unlink(diffPath);\n await fsp.rm(toDiffMetaPath(diffPath), { force: true });\n await this.approveFromActualPath(\n path.resolve(outputDir, screenshot.actualPath),\n );\n return;\n }\n\n if (screenshot.category === \"passed\") {\n if (!screenshot.expectedPath) {\n throw new Error(\"Expected path is required for passed screenshots\");\n }\n\n const matches = await imagesMatch(\n path.resolve(outputDir, screenshot.expectedPath),\n path.resolve(outputDir, screenshot.actualPath),\n diff.type === \"gmsd\"\n ? { threshold: diff.threshold }\n : (diff as DiffConfig),\n );\n\n if (!matches) {\n await this.approveFromActualPath(\n path.resolve(outputDir, screenshot.actualPath),\n );\n }\n }\n }\n\n /**\n * Approve a screenshot based on its name.\n * @param name - The name of the screenshot. Can include '.png' extension.\n * @returns The paths to the actual, expected, and diff screenshot files.\n */\n async approveByName(name: string) {\n const relativeWithExtension = name.endsWith(\".png\") ? name : `${name}.png`;\n\n return this.approveRelative(relativeWithExtension);\n }\n\n /**\n * Approve a screenshot based on a relative path.\n * @param relativePath - The relative path to the screenshot.\n * @returns The paths to the actual, expected, and diff screenshot files.\n */\n private async approveRelative(relativePath: string) {\n const actualPath = path.resolve(this.actual, relativePath);\n const expectedPath = path.resolve(this.expected, relativePath);\n const diffPath = path.resolve(this.diff, relativePath);\n\n await this.ensureParentDir(expectedPath);\n\n await fsp.copyFile(actualPath, expectedPath);\n\n try {\n await fsp.access(diffPath);\n } catch {\n return {\n actualPath,\n expectedPath,\n diffPath,\n };\n }\n\n await this.copyDiffMetadataToExpected(diffPath, expectedPath);\n await fsp.unlink(diffPath);\n await fsp.rm(toDiffMetaPath(diffPath), { force: true });\n\n return {\n actualPath,\n expectedPath,\n diffPath,\n };\n }\n\n private async copyDiffMetadataToExpected(\n diffPath: string,\n expectedPath: string,\n ): Promise<void> {\n const diffExtension = path.extname(diffPath).toLowerCase();\n const expectedExtension = path.extname(expectedPath).toLowerCase();\n\n if (diffExtension !== \".png\" || expectedExtension !== \".png\") {\n return;\n }\n\n try {\n const diffBuffer = await fsp.readFile(diffPath);\n const diffMetadata = extractTextMetadata(diffBuffer);\n\n if (Object.keys(diffMetadata).length === 0) {\n return;\n }\n\n const expectedBuffer = await fsp.readFile(expectedPath);\n const expectedMetadata = extractTextMetadata(expectedBuffer);\n\n const mergedMetadata = {\n ...expectedMetadata,\n ...diffMetadata,\n };\n\n const expectedWithMetadata = injectTextMetadata(\n expectedBuffer,\n mergedMetadata,\n );\n await fsp.writeFile(expectedPath, expectedWithMetadata);\n } catch {\n // Ignore metadata transfer errors to keep approval resilient.\n }\n }\n\n /**\n * Ensure the parent directory of a file exists. If not, it creates it.\n * @param filePath - The path to the file.\n */\n async ensureParentDir(filePath: string) {\n const dir = path.dirname(filePath);\n await fsp.mkdir(dir, { recursive: true });\n }\n\n /**\n * Synchronous version used only during constructor initialization.\n */\n private ensureParentDirSync(filePath: string) {\n const dir = path.dirname(filePath);\n\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n }\n\n /**\n * Remove a directory and all its contents.\n * @param dir - The path to the directory.\n */\n private removeDir(dir: string) {\n if (fs.existsSync(dir)) {\n fs.rmSync(dir, { recursive: true, force: true });\n }\n }\n\n /**\n * Get the actual directory path\n */\n getActualDir(): string {\n return this.actual;\n }\n\n /**\n * Get the expected directory path\n */\n getExpectedDir(): string {\n return this.expected;\n }\n\n /**\n * Get the diff directory path\n */\n getDiffDir(): string {\n return this.diff;\n }\n\n /**\n * Resolve a screenshot filename inside one of the buckets.\n *\n * This is the single sink every read and write funnels through, so it is also\n * where an untrusted filename is stopped: plugin-supplied names (Storybook\n * variant filenames come straight from story code) must never escape the\n * bucket they belong to.\n */\n private resolveBucketPath(\n directory: \"actual\" | \"expected\" | \"diff\",\n filename: string,\n ): string {\n return resolveInside(this[directory], filename, directory);\n }\n\n /**\n * Get the path to an actual screenshot file\n */\n getActualFilePath(filename: string): string {\n return this.resolveBucketPath(\"actual\", filename);\n }\n\n /**\n * Get the path to an expected screenshot file\n */\n getExpectedFilePath(filename: string): string {\n return this.resolveBucketPath(\"expected\", filename);\n }\n\n /**\n * Get the path to a diff screenshot file\n */\n getDiffFilePath(filename: string): string {\n return this.resolveBucketPath(\"diff\", filename);\n }\n\n /**\n * Write a file to the actual directory\n */\n async writeActualFile(filename: string, data: Buffer): Promise<void> {\n const filepath = this.getActualFilePath(filename);\n await this.ensureParentDir(filepath);\n await fsp.writeFile(filepath, data);\n }\n\n /**\n * Write a file to the diff directory\n */\n async writeDiffFile(filename: string, data: Buffer): Promise<void> {\n const filepath = this.getDiffFilePath(filename);\n await this.ensureParentDir(filepath);\n await fsp.writeFile(filepath, data);\n }\n\n /**\n * Remove a screenshot's diff image and metadata sidecar, if any.\n *\n * A run that does not clear `diff/` — a filtered or single-screenshot\n * re-capture — would otherwise leave the previous run's diff behind for a\n * screenshot that now passes, and a screenshot with a diff is `changed`.\n */\n async removeDiffFiles(filename: string): Promise<void> {\n const filepath = this.getDiffFilePath(filename);\n await Promise.all([\n fsp.rm(filepath, { force: true }),\n fsp.rm(toDiffMetaPath(filepath), { force: true }),\n ]);\n }\n\n /**\n * Get the path to a diff metadata sidecar file (`<name>.json`)\n */\n getDiffMetaFilePath(filename: string): string {\n return toDiffMetaPath(this.getDiffFilePath(filename));\n }\n\n /**\n * Write a diff metadata sidecar (`diff/<name>.json`) next to the diff image.\n */\n async writeDiffMetaFile(filename: string, meta: DiffMetadata): Promise<void> {\n const filepath = this.getDiffMetaFilePath(filename);\n await this.ensureParentDir(filepath);\n await fsp.writeFile(filepath, JSON.stringify(meta));\n }\n\n /**\n * Check if an expected file exists\n */\n async hasExpectedFile(filename: string): Promise<boolean> {\n const expectedPath = this.getExpectedFilePath(filename);\n try {\n await fsp.access(expectedPath);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Read an expected file\n */\n async readExpectedFile(filename: string): Promise<Buffer> {\n const expectedPath = this.getExpectedFilePath(filename);\n try {\n return await fsp.readFile(expectedPath);\n } catch {\n throw new Error(`Expected image not found: ${expectedPath}`);\n }\n }\n\n /**\n * Resolve the actual path of a screenshot file.\n * @param filePath - The path to the screenshot file.\n * @returns The actual path of the screenshot file.\n */\n private resolveActualPath(filePath: string) {\n if (path.isAbsolute(filePath)) {\n return filePath;\n }\n\n return path.resolve(this.actual, filePath);\n }\n\n getRelativePath(directory: \"actual\" | \"expected\" | \"diff\", filePath: string) {\n if (!isPathInside(this[directory], filePath)) {\n throw new Error(\n `Cannot resolve relative path outside of ${directory} directory: ${filePath}`,\n );\n }\n\n return path.relative(this[directory], filePath);\n }\n}\n","import fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/**\n * Maps a screenshot back to the capture task that produced it.\n *\n * Nothing on disk carries this. A screenshot's name comes from the filename a\n * plugin chose (`example/button/primary`), while the task id comes from the\n * plugin's own addressing scheme (`example-button--primary` for Storybook) —\n * and there is no rule connecting the two. Without a record written at capture\n * time, \"re-capture this one screenshot\" has no task to ask for, which is\n * exactly how the review UI's re-capture button came to send a name the engine\n * had never heard of.\n *\n * Kept beside `actual/` and `expected/` rather than inside them so it is never\n * mistaken for a screenshot, and dot-prefixed so `@fastify/static` (which is\n * configured with `serveDotFiles: false`) will not serve it.\n */\nexport const MANIFEST_FILENAME = \".cappa-manifest.json\";\n\n/** Bumped only if the on-disk shape changes incompatibly. */\nexport const MANIFEST_VERSION = 1;\n\n/** Where a screenshot came from. */\nexport type ScreenshotOrigin = {\n /** Task id as `discover` produced it — what `startRun` accepts. */\n taskId: string;\n /** Plugin that owns the task. */\n plugin: string;\n};\n\nexport type CaptureManifest = {\n version: number;\n /** Keyed by screenshot name (relative path, no `.png`). */\n screenshots: Record<string, ScreenshotOrigin>;\n};\n\nexport const emptyManifest = (): CaptureManifest => ({\n version: MANIFEST_VERSION,\n screenshots: {},\n});\n\nexport const manifestPath = (outputDir: string): string =>\n path.resolve(outputDir, MANIFEST_FILENAME);\n\n/**\n * The key a capture filename is recorded under.\n *\n * Must match the `name` `groupScreenshots` derives, or a lookup silently\n * misses: the relative path with its `.png` dropped, and separators normalised\n * so a manifest written on Windows is readable on Linux.\n */\nexport const toManifestKey = (filename: string): string =>\n filename\n .split(path.sep)\n .join(\"/\")\n .replace(/\\.png$/i, \"\");\n\nconst isOrigin = (value: unknown): value is ScreenshotOrigin =>\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as ScreenshotOrigin).taskId === \"string\" &&\n typeof (value as ScreenshotOrigin).plugin === \"string\";\n\n/**\n * Read the manifest, or an empty one.\n *\n * Never throws: the manifest is an optimisation, and a missing, truncated or\n * hand-edited file must degrade to \"we do not know where this came from\"\n * rather than break the screenshot index every command depends on.\n */\nexport const readCaptureManifest = async (\n outputDir: string,\n): Promise<CaptureManifest> => {\n try {\n const raw = await fsp.readFile(manifestPath(outputDir), \"utf8\");\n const parsed: unknown = JSON.parse(raw);\n\n if (\n typeof parsed !== \"object\" ||\n parsed === null ||\n (parsed as CaptureManifest).version !== MANIFEST_VERSION\n ) {\n return emptyManifest();\n }\n\n const screenshots = (parsed as CaptureManifest).screenshots;\n if (typeof screenshots !== \"object\" || screenshots === null) {\n return emptyManifest();\n }\n\n const entries = Object.entries(screenshots).filter(([, origin]) =>\n isOrigin(origin),\n );\n\n return {\n version: MANIFEST_VERSION,\n screenshots: Object.fromEntries(entries) as Record<\n string,\n ScreenshotOrigin\n >,\n };\n } catch {\n return emptyManifest();\n }\n};\n\n/**\n * Merge freshly captured origins into whatever the manifest already holds.\n *\n * A run only captures the tasks it was asked for, so existing entries have to\n * survive — otherwise re-capturing one screenshot would strip every other\n * screenshot's origin and disable the button that started it.\n *\n * `knownNames`, when given, is the set of screenshots that currently exist;\n * entries outside it are dropped so renames and deletions do not accumulate\n * forever. New origins are always kept, whether or not they appear in it.\n */\nexport const mergeCaptureManifest = (\n existing: CaptureManifest,\n origins: Record<string, ScreenshotOrigin>,\n knownNames?: Iterable<string>,\n): CaptureManifest => {\n const keep = knownNames ? new Set(knownNames) : undefined;\n\n const merged: Record<string, ScreenshotOrigin> = {};\n\n for (const [name, origin] of Object.entries(existing.screenshots)) {\n if (!keep || keep.has(name)) {\n merged[name] = origin;\n }\n }\n\n for (const [name, origin] of Object.entries(origins)) {\n merged[name] = origin;\n }\n\n return { version: MANIFEST_VERSION, screenshots: merged };\n};\n\n/**\n * Persist `origins`, merged over what is already recorded.\n *\n * Best-effort by design: a read-only or full disk must not turn a successful\n * capture run into a failed one, so a write failure is reported to the caller\n * as `false` rather than thrown.\n */\nexport const recordCaptureOrigins = async (\n outputDir: string,\n origins: Record<string, ScreenshotOrigin>,\n knownNames?: Iterable<string>,\n): Promise<boolean> => {\n try {\n const merged = mergeCaptureManifest(\n await readCaptureManifest(outputDir),\n origins,\n knownNames,\n );\n\n await fsp.mkdir(path.resolve(outputDir), { recursive: true });\n await fsp.writeFile(\n manifestPath(outputDir),\n `${JSON.stringify(merged, null, 2)}\\n`,\n \"utf8\",\n );\n\n return true;\n } catch {\n return false;\n }\n};\n","/** The advice for a refused connection when the config has no `webServer`. */\nexport const NO_WEB_SERVER_HINT =\n \"Start it before capturing, or add a `webServer` entry to cappa.config.ts so cappa starts it for you.\";\n\n/**\n * How a refused connection reads, across the places one surfaces: Node's\n * sockets and `fetch` (`ECONNREFUSED`), Chromium (`net::ERR_CONNECTION_REFUSED`),\n * Firefox (`NS_ERROR_CONNECTION_REFUSED`) and WebKit.\n */\nconst REFUSED_PATTERN =\n /\\bECONNREFUSED\\b|\\bERR_CONNECTION_REFUSED\\b|\\bNS_ERROR_CONNECTION_REFUSED\\b|Could not connect to (?:the )?server|Connection refused/i;\n\nconst URL_PATTERN = /\\bhttps?:\\/\\/[^\\s\"'`<>)\\]]+/i;\n\nexport type RefusedConnection = {\n /** Origin of the URL that refused, when the error names one. */\n origin?: string;\n};\n\nconst toOrigin = (url: string): string | undefined => {\n try {\n // A URL that ends a sentence takes its full stop with it.\n return new URL(url.replace(/[.,;:!?]+$/, \"\")).origin;\n } catch {\n return undefined;\n }\n};\n\n/**\n * Whether `error` — an `Error`, a plain object, or just a message string, as\n * plugins report task failures — is a refused connection.\n *\n * Walks `cause` and `AggregateError.errors`: Node's `fetch` says only\n * \"fetch failed\" and puts `ECONNREFUSED` on its cause, and a plugin that wraps\n * the error in a friendlier one keeps it there too.\n *\n * Works on any plugin's errors, third-party included, because it reads the\n * error rather than asking the plugin.\n */\nexport function findRefusedConnection(\n error: unknown,\n): RefusedConnection | undefined {\n let refused = false;\n let origin: string | undefined;\n let socketOrigin: string | undefined;\n\n const seen = new Set<unknown>();\n const visit = (value: unknown, depth: number) => {\n if (value === null || value === undefined || depth > 8 || seen.has(value)) {\n return;\n }\n seen.add(value);\n\n if (typeof value === \"string\") {\n if (REFUSED_PATTERN.test(value)) {\n refused = true;\n }\n const url = value.match(URL_PATTERN)?.[0];\n origin ??= url ? toOrigin(url) : undefined;\n return;\n }\n\n if (typeof value !== \"object\") {\n return;\n }\n\n const record = value as {\n message?: unknown;\n code?: unknown;\n address?: unknown;\n port?: unknown;\n cause?: unknown;\n errors?: unknown;\n };\n\n if (record.code === \"ECONNREFUSED\") {\n refused = true;\n if (typeof record.address === \"string\" && record.port !== undefined) {\n const host = record.address.includes(\":\")\n ? `[${record.address}]`\n : record.address;\n socketOrigin ??= `http://${host}:${record.port}`;\n }\n }\n\n visit(record.message, depth + 1);\n visit(record.cause, depth + 1);\n if (Array.isArray(record.errors)) {\n for (const inner of record.errors) {\n visit(inner, depth + 1);\n }\n }\n };\n\n visit(error, 0);\n\n if (!refused) {\n return undefined;\n }\n\n // A URL in a message is what the user configured; a socket address is what\n // it resolved to. The first is the one they will recognise.\n const resolved = origin ?? socketOrigin;\n return resolved ? { origin: resolved } : {};\n}\n\nconst LOOPBACK_HOSTS = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\", \"0.0.0.0\"]);\n\n/**\n * Whether two origins name the same server.\n *\n * Loopback spellings are interchangeable: a plugin configured with\n * `localhost:6006` and a socket error reporting `127.0.0.1:6006` are the same\n * Storybook.\n */\nexport function sameServer(a: string, b: string): boolean {\n try {\n const left = new URL(a);\n const right = new URL(b);\n const port = (url: URL) =>\n url.port || (url.protocol === \"https:\" ? \"443\" : \"80\");\n\n if (port(left) !== port(right)) {\n return false;\n }\n return (\n left.hostname === right.hostname ||\n (LOOPBACK_HOSTS.has(left.hostname) && LOOPBACK_HOSTS.has(right.hostname))\n );\n } catch {\n return false;\n }\n}\n","import { glob } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { PluginTask } from \"../plugin\";\nimport type { PluginCaptureResult, TaskStatus } from \"./types\";\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\n/**\n * Decide whether a plugin's `execute` result represents a failed screenshot.\n *\n * Plugins return loosely-shaped objects, so this inspects the three signals that\n * matter: an explicit `error`, an explicit `success: false`, or a missing\n * `filepath` on a task that was not skipped.\n */\nexport const didScreenshotFail = (result: unknown): boolean => {\n if (!isObject(result)) {\n return false;\n }\n\n if (\"error\" in result && result.error != null) {\n return true;\n }\n\n if (\"success\" in result) {\n const { success } = result as PluginCaptureResult;\n if (success === false) {\n return true;\n }\n }\n\n if (\"filepath\" in result) {\n const { filepath, skipped } = result as PluginCaptureResult;\n if (!filepath && skipped !== true) {\n return true;\n }\n }\n\n return false;\n};\n\n/**\n * Map a plugin result onto the status shown in the UI.\n *\n * Mirrors the screenshot categories: a capture with no baseline is `new`, a\n * failing comparison is `changed`, and anything `didScreenshotFail` flags for\n * another reason is `failed`.\n */\nexport const toTaskStatus = (result: unknown): TaskStatus => {\n if (!isObject(result)) {\n return \"passed\";\n }\n\n const typed = result as PluginCaptureResult;\n\n if (typed.skipped === true) {\n return \"skipped\";\n }\n\n if (\"error\" in typed && typed.error != null) {\n return \"failed\";\n }\n\n if (typed.isNew === true) {\n return \"new\";\n }\n\n if (typed.success === false) {\n return \"changed\";\n }\n\n if (didScreenshotFail(typed)) {\n return \"failed\";\n }\n\n return \"passed\";\n};\n\n/** Restrict `tasks` to those whose id matches the glob `filter`. */\nexport function filterTasks(tasks: PluginTask[], filter: string): PluginTask[] {\n return tasks.filter((task) => path.matchesGlob(task.id, filter));\n}\n\n/** Restrict `tasks` to an explicit set of ids. */\nexport function selectTasks(\n tasks: PluginTask[],\n taskIds: readonly string[],\n): PluginTask[] {\n const wanted = new Set(taskIds);\n return tasks.filter((task) => wanted.has(task.id));\n}\n\n/**\n * Baselines in `expected/` that have no counterpart in `actual/` — screenshots\n * that existed when the baseline was approved but were not captured this run.\n */\nexport async function getDeletedScreenshots(\n outputDir: string,\n): Promise<string[]> {\n const actualDir = path.resolve(outputDir, \"actual\");\n const expectedDir = path.resolve(outputDir, \"expected\");\n\n const [actualFiles, expectedFiles] = await Promise.all([\n Array.fromAsync(glob(path.join(actualDir, \"**/*.png\"))),\n Array.fromAsync(glob(path.join(expectedDir, \"**/*.png\"))),\n ]);\n\n const actualRelative = new Set(\n actualFiles.map((p) => path.relative(actualDir, p)),\n );\n\n return expectedFiles\n .map((p) => path.relative(expectedDir, p))\n .filter((rel) => !actualRelative.has(rel));\n}\n","import type { PluginTask, PluginWatch } from \"../plugin\";\n\n/**\n * Lifecycle of a single capture run.\n *\n * ```\n * idle → discovering → running → (completed | failed | cancelled)\n * ```\n */\nexport type RunState =\n | \"idle\"\n | \"discovering\"\n | \"running\"\n | \"completed\"\n | \"failed\"\n | \"cancelled\";\n\n/**\n * Terminal state of an individual capture task.\n *\n * `passed` / `changed` / `new` mirror the screenshot categories; `failed` means\n * the plugin reported a failure (see `didScreenshotFail`); `skipped` means the\n * plugin deliberately skipped the task.\n */\nexport type TaskStatus =\n | \"pending\"\n | \"running\"\n | \"passed\"\n | \"changed\"\n | \"new\"\n | \"failed\"\n | \"skipped\";\n\n/** A discovered, runnable capture task together with the plugin that owns it. */\nexport type Target = {\n id: string;\n url: string;\n plugin: string;\n};\n\n/**\n * Why a run was started, when it was not started by hand.\n *\n * Purely informational — the runner does nothing with it. It rides along on the\n * request so a run list can say \"this one came from saving Button.stories.tsx\"\n * without a second lookup or a parallel event stream.\n */\nexport type RunTrigger = {\n source: \"watch\";\n /** Changed files that triggered the run, relative to the watch root. */\n files: string[];\n};\n\n/**\n * Describes which subset of the discovered tasks a run should capture.\n *\n * `filter` and `taskIds` compose: a task must satisfy both when both are given.\n */\nexport type StartRunRequest = {\n /** Restrict the run to these plugin names. Omit to run every plugin. */\n plugins?: string[];\n /** Glob matched against task ids (`path.matchesGlob` semantics). */\n filter?: string;\n /** Explicit task ids to capture. Ids not discovered are ignored. */\n taskIds?: string[];\n /**\n * Clear `actual/` and `diff/` before capturing.\n *\n * Always `true` for a full CLI run. A UI re-capturing a single screenshot must\n * pass `false`, otherwise the rest of the run's output is destroyed.\n * @default true\n */\n clearActual?: boolean;\n /** What started this run, when it was not a person. */\n trigger?: RunTrigger;\n};\n\n/** An error flattened into something that survives a structured-clone or JSON. */\nexport type SerializedError = {\n name: string;\n message: string;\n stack?: string;\n};\n\nexport const toSerializedError = (error: unknown): SerializedError => {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack,\n };\n }\n\n return { name: \"Error\", message: String(error) };\n};\n\n/**\n * The shape plugins return from `execute`. Every field is optional because\n * plugins are free to return whatever they want — only these keys are\n * interpreted (by `didScreenshotFail`) and surfaced in failure reports.\n */\nexport type PluginCaptureResult = {\n success?: boolean;\n skipped?: boolean;\n isNew?: boolean;\n error?: unknown;\n filepath?: string;\n storyId?: string;\n storyName?: string;\n [key: string]: unknown;\n};\n\n/** A task that did not produce a passing screenshot. */\nexport type TaskFailure = {\n taskId: string;\n taskUrl: string;\n pluginName: string;\n result: PluginCaptureResult;\n};\n\n/** Per-task record kept for the lifetime of a run. */\nexport type TaskRecord = {\n id: string;\n url: string;\n plugin: string;\n status: TaskStatus;\n durationMs?: number;\n result?: PluginCaptureResult;\n};\n\n/** Coarse, serializable view of a run — enough to render a list row. */\nexport type RunSummary = {\n id: string;\n state: RunState;\n request: StartRunRequest;\n startedAt: number;\n finishedAt?: number;\n durationMs?: number;\n totalTasks: number;\n completedTasks: number;\n failedTasks: number;\n /** Baselines in `expected/` with no matching `actual/` after the run. */\n deletedScreenshots: string[];\n /** `false` when discovery produced nothing (or everything was filtered out). */\n anyTasksRan: boolean;\n error?: SerializedError;\n};\n\n/** Full run view, including every task and failure. */\nexport type RunDetail = RunSummary & {\n tasks: TaskRecord[];\n failures: TaskFailure[];\n};\n\n/**\n * Levels the run event stream can carry.\n *\n * `success` is here because `ScreenshotTool` uses it — \"Screenshot saved\",\n * \"Screenshot passed visual comparison\" — and those lines have to reach a\n * remote client, not just the host's own terminal. Adding a level is a wire\n * change: this one lands before `PROTOCOL_VERSION` 1 has ever been published,\n * so it is part of what v1 will be. A later addition needs a version bump.\n */\nexport type RunLogLevel = \"debug\" | \"info\" | \"warn\" | \"error\" | \"success\";\n\ntype RunEventBase = {\n /** Monotonic, 1-based, per run. Used for SSE `Last-Event-ID` replay. */\n seq: number;\n runId: string;\n at: number;\n};\n\n/**\n * Everything an observer needs to follow a run. Emitted synchronously, so a\n * consumer forwarding these to a logger keeps ordering with logs written\n * directly by `ScreenshotTool`.\n */\nexport type RunEvent =\n | (RunEventBase & { type: \"run:start\"; request: StartRunRequest })\n | (RunEventBase & { type: \"discover:start\"; plugins: string[] })\n | (RunEventBase & {\n type: \"discover:plugin\";\n plugin: string;\n taskCount: number;\n })\n | (RunEventBase & {\n type: \"discover:complete\";\n targets: Target[];\n totalTasks: number;\n })\n | (RunEventBase & {\n type: \"filter:applied\";\n filter?: string;\n taskIds?: string[];\n plugins: { plugin: string; before: number; after: number }[];\n })\n | (RunEventBase & {\n type: \"plugin:start\";\n plugin: string;\n taskCount: number;\n })\n | (RunEventBase & {\n type: \"task:start\";\n plugin: string;\n taskId: string;\n url: string;\n })\n | (RunEventBase & {\n type: \"task:complete\";\n plugin: string;\n taskId: string;\n url: string;\n status: TaskStatus;\n completed: number;\n total: number;\n durationMs: number;\n result?: PluginCaptureResult;\n })\n | (RunEventBase & {\n type: \"plugin:complete\";\n plugin: string;\n resultCount: number;\n failed: boolean;\n })\n | (RunEventBase & {\n type: \"log\";\n level: RunLogLevel;\n message: string;\n args: unknown[];\n })\n | (RunEventBase & { type: \"run:complete\"; summary: RunSummary })\n | (RunEventBase & { type: \"run:error\"; error: SerializedError })\n | (RunEventBase & { type: \"run:cancelled\" });\n\nexport type RunEventType = RunEvent[\"type\"];\n\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown\n ? Omit<T, K>\n : never;\n\n/**\n * A run event before the runner stamps it with `seq`, `runId` and `at`.\n *\n * `Omit` must distribute over the union here — a plain `Omit<RunEvent, …>`\n * collapses to the keys every member shares, which is just `type`.\n */\nexport type EmittableRunEvent = DistributiveOmit<\n RunEvent,\n \"seq\" | \"runId\" | \"at\"\n>;\n\nexport type RunEventListener = (event: RunEvent) => void;\n\n/** Plugin shape the runner needs. Kept structural so tests can pass fakes. */\nexport type RunnablePlugin = {\n name: string;\n description?: string;\n discover: (screenshotTool: any) => Promise<PluginTask[]>;\n execute: (\n task: PluginTask,\n page: any,\n screenshotTool: any,\n context: any,\n ) => Promise<unknown>;\n initPage?: (page: any, screenshotTool: any) => Promise<unknown>;\n /** How this plugin maps a changed file onto tasks. Absent means \"cannot\". */\n watch?: PluginWatch;\n};\n","import { randomUUID } from \"node:crypto\";\nimport { relative } from \"node:path\";\nimport { ScreenshotFileSystem } from \"../filesystem\";\nimport { mapWithConcurrency } from \"../mapWithConcurrency\";\nimport type { PluginTask } from \"../plugin\";\nimport type ScreenshotTool from \"../screenshot\";\nimport {\n recordCaptureOrigins,\n type ScreenshotOrigin,\n toManifestKey,\n} from \"../screenshots/manifest\";\nimport {\n findRefusedConnection,\n NO_WEB_SERVER_HINT,\n} from \"../webServer/unreachable\";\nimport {\n didScreenshotFail,\n filterTasks,\n getDeletedScreenshots,\n selectTasks,\n toTaskStatus,\n} from \"./tasks\";\nimport type {\n EmittableRunEvent,\n PluginCaptureResult,\n RunDetail,\n RunEvent,\n RunEventListener,\n RunLogLevel,\n RunnablePlugin,\n RunState,\n RunSummary,\n StartRunRequest,\n Target,\n TaskFailure,\n TaskRecord,\n} from \"./types\";\nimport { toSerializedError } from \"./types\";\n\nexport type CaptureRunnerOptions = {\n /**\n * An **already initialised** `ScreenshotTool`. The runner never calls `init()`\n * or `close()` — browser lifetime belongs to the caller, so a long-lived\n * server can keep one browser warm across many runs while the CLI can keep\n * its init/close-per-run shape.\n */\n screenshotTool: ScreenshotTool;\n plugins: RunnablePlugin[];\n /** Defaults to the screenshot tool's output directory. */\n outputDir?: string;\n /**\n * Filesystem used to clear `actual/` and `diff/`. Defaults to the screenshot\n * tool's own instance, falling back to one built from `outputDir`.\n */\n fileSystem?: ScreenshotFileSystem;\n /** Stable run id. Generated when omitted. */\n id?: string;\n /** Injectable clock, for deterministic tests. */\n now?: () => number;\n /**\n * Runs after `run:start` and before anything is cleared or discovered —\n * the engine starts its web servers here. Its log lines become run events,\n * and a rejection fails the run with `actual/` still intact.\n */\n prepare?: (\n log: (level: RunLogLevel, message: string) => void,\n ) => Promise<void>;\n /**\n * The advice appended to a refused connection, given the origin that\n * refused when the error names one. Defaults to suggesting a `webServer`.\n */\n explainUnreachable?: (origin: string | undefined) => string;\n};\n\n/**\n * Orchestrates a single capture run: discover → filter → execute, emitting\n * typed events as it goes.\n *\n * Deliberately free of any presentation or process concerns — no logger calls,\n * no `chalk`, no `process.exit`. Consumers render the events however they like:\n * the CLI writes them to the terminal, the server streams them over SSE.\n *\n * One instance represents one run. Create a new one per run.\n */\nexport class CaptureRunner {\n readonly id: string;\n\n private readonly screenshotTool: ScreenshotTool;\n private readonly plugins: RunnablePlugin[];\n private readonly outputDir: string;\n private readonly fileSystem: ScreenshotFileSystem;\n private readonly now: () => number;\n private readonly prepare: CaptureRunnerOptions[\"prepare\"];\n private readonly explainUnreachable: (origin: string | undefined) => string;\n private readonly listeners = new Set<RunEventListener>();\n private readonly controller = new AbortController();\n\n private seq = 0;\n private state: RunState = \"idle\";\n private request: StartRunRequest = {};\n private startedAt = 0;\n private finishedAt: number | undefined;\n private error: unknown;\n private anyTasksRan = false;\n private deletedScreenshots: string[] = [];\n private readonly taskRecords = new Map<string, TaskRecord>();\n private readonly failures: TaskFailure[] = [];\n private started = false;\n\n /**\n * Which task currently owns each pooled page.\n *\n * Tasks run concurrently, one per page, so the page is what disambiguates\n * the capture sink's reports. Populated only while a task is executing.\n */\n private readonly taskByPage = new Map<unknown, ScreenshotOrigin>();\n /** Screenshot name → the task that captured it, for the capture manifest. */\n private readonly capturedOrigins = new Map<string, ScreenshotOrigin>();\n\n constructor(options: CaptureRunnerOptions) {\n this.screenshotTool = options.screenshotTool;\n this.plugins = options.plugins;\n this.outputDir = options.outputDir ?? options.screenshotTool.outputDir;\n this.fileSystem =\n options.fileSystem ??\n options.screenshotTool.filesystem ??\n new ScreenshotFileSystem(this.outputDir);\n this.id = options.id ?? randomUUID();\n this.now = options.now ?? (() => Date.now());\n this.prepare = options.prepare;\n this.explainUnreachable =\n options.explainUnreachable ?? (() => NO_WEB_SERVER_HINT);\n }\n\n /** Subscribe to run events. Returns an unsubscribe function. */\n on(listener: RunEventListener): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n get signal(): AbortSignal {\n return this.controller.signal;\n }\n\n /**\n * Request cancellation. In-flight tasks finish (Playwright gives us no safe\n * mid-screenshot abort), but no further tasks are started.\n */\n abort(): void {\n if (this.state === \"completed\" || this.state === \"failed\") {\n return;\n }\n this.controller.abort();\n }\n\n getSummary(): RunSummary {\n const tasks = [...this.taskRecords.values()];\n const completedTasks = tasks.filter(\n (task) => task.status !== \"pending\" && task.status !== \"running\",\n ).length;\n\n return {\n id: this.id,\n state: this.state,\n request: this.request,\n startedAt: this.startedAt,\n finishedAt: this.finishedAt,\n durationMs:\n this.finishedAt === undefined\n ? undefined\n : this.finishedAt - this.startedAt,\n totalTasks: tasks.length,\n completedTasks,\n failedTasks: this.failures.length,\n deletedScreenshots: this.deletedScreenshots,\n anyTasksRan: this.anyTasksRan,\n error:\n this.error === undefined ? undefined : toSerializedError(this.error),\n };\n }\n\n getDetail(): RunDetail {\n return {\n ...this.getSummary(),\n tasks: [...this.taskRecords.values()],\n failures: [...this.failures],\n };\n }\n\n /**\n * Whether the run produced at least one failing screenshot or detected a\n * deleted baseline — the condition the CLI exits non-zero on.\n */\n get hasScreenshotFailure(): boolean {\n return this.failures.length > 0 || this.deletedScreenshots.length > 0;\n }\n\n private emit(event: EmittableRunEvent): void {\n this.seq += 1;\n const full = {\n ...event,\n seq: this.seq,\n runId: this.id,\n at: this.now(),\n } as RunEvent;\n\n for (const listener of this.listeners) {\n try {\n listener(full);\n } catch {\n // A misbehaving observer must never take down the run.\n }\n }\n }\n\n private log(level: RunLogLevel, message: string, ...args: unknown[]): void {\n this.emit({ type: \"log\", level, message, args });\n }\n\n /**\n * Run the capture. Resolves with the final detail; rejects if a plugin threw,\n * after emitting `run:error`.\n */\n async run(request: StartRunRequest = {}): Promise<RunDetail> {\n if (this.started) {\n throw new Error(`Run ${this.id} has already been started`);\n }\n this.started = true;\n\n this.request = request;\n this.startedAt = this.now();\n this.emit({ type: \"run:start\", request });\n\n // For the duration of the run, the tool's own output becomes part of the\n // event stream rather than going straight to whatever logger this process\n // happens to have. That is what lets a client watching a remote run see\n // \"Screenshot saved\" and the retry warnings at all.\n this.attachToolLogSink();\n this.attachToolCaptureSink();\n\n try {\n try {\n if (this.prepare) {\n // Not `idle`: starting the app can take as long as a build, and a\n // client polling the run should see it working.\n this.state = \"discovering\";\n await this.prepare((level, message) => this.log(level, message));\n }\n\n if (request.clearActual ?? true) {\n this.log(\"debug\", `Cleaning output directory: ${this.outputDir}`);\n this.fileSystem.clearActual();\n this.fileSystem.clearDiff();\n }\n\n const pluginTasks = await this.discover(request);\n\n if (!this.controller.signal.aborted) {\n await this.execute(pluginTasks);\n }\n } catch (thrown) {\n const error = this.toUnreachableError(thrown) ?? thrown;\n this.error = error;\n this.state = \"failed\";\n this.finishedAt = this.now();\n this.emit({ type: \"run:error\", error: toSerializedError(error) });\n throw error;\n }\n\n await this.collectDeleted();\n\n // Before the terminal event, not after: consumers refresh their\n // screenshot index the moment they see `run:complete`, and a manifest\n // written after that would leave the re-capture button dark until the\n // next refresh.\n await this.persistCaptureOrigins();\n\n this.finishedAt = this.now();\n this.state = this.controller.signal.aborted ? \"cancelled\" : \"completed\";\n\n if (this.state === \"cancelled\") {\n this.emit({ type: \"run:cancelled\" });\n }\n\n const summary = this.getSummary();\n this.emit({ type: \"run:complete\", summary });\n\n return this.getDetail();\n } finally {\n this.detachToolLogSink();\n this.detachToolCaptureSink();\n // Runs after the terminal event on purpose: a cancelled or failed run\n // still captured something, and the origins it did record are what make\n // those screenshots re-capturable.\n await this.persistCaptureOrigins();\n }\n }\n\n /**\n * Route `ScreenshotTool`'s log output through this run's events.\n *\n * Guarded rather than called outright: tests inject minimal stand-ins for the\n * tool, and a fake without the method should not fail a run.\n */\n private attachToolLogSink(): void {\n this.screenshotTool.setLogSink?.((level, message, ...args) => {\n this.log(level, message, ...args);\n });\n }\n\n private detachToolLogSink(): void {\n this.screenshotTool.setLogSink?.(null);\n }\n\n /**\n * Record which task produces which screenshot file.\n *\n * Guarded like the log sink: tests inject minimal tool stand-ins, and one\n * without the method must not fail a run — it only loses the manifest.\n */\n private attachToolCaptureSink(): void {\n this.screenshotTool.setCaptureSink?.((page, filename) => {\n const origin = this.taskByPage.get(page);\n if (origin) {\n this.capturedOrigins.set(toManifestKey(filename), origin);\n }\n });\n }\n\n private detachToolCaptureSink(): void {\n this.screenshotTool.setCaptureSink?.(null);\n this.taskByPage.clear();\n }\n\n /**\n * Write what this run learned about screenshot origins.\n *\n * Idempotent, because it is called once on the happy path and again from\n * `run`'s `finally` for the paths that never reach it. Existing entries are\n * preserved and only names that no longer exist on disk are dropped, so a\n * run of one task does not erase every other screenshot's origin.\n */\n private async persistCaptureOrigins(): Promise<void> {\n if (this.capturedOrigins.size === 0) {\n return;\n }\n\n const origins = Object.fromEntries(this.capturedOrigins);\n this.capturedOrigins.clear();\n\n let knownNames: string[] | undefined;\n try {\n const [actual, expected] = await Promise.all([\n this.fileSystem.getActualScreenshots(),\n this.fileSystem.getExpectedScreenshots(),\n ]);\n knownNames = [\n ...actual.map((file) =>\n toManifestKey(relative(this.fileSystem.getActualDir(), file)),\n ),\n ...expected.map((file) =>\n toManifestKey(relative(this.fileSystem.getExpectedDir(), file)),\n ),\n ];\n } catch {\n // Could not enumerate what exists, so prune nothing rather than\n // discarding entries that are probably still valid.\n knownNames = undefined;\n }\n\n const written = await recordCaptureOrigins(\n this.outputDir,\n origins,\n knownNames,\n );\n\n if (!written) {\n this.log(\n \"debug\",\n \"Could not write the capture manifest; re-capturing a single screenshot may be unavailable.\",\n );\n }\n }\n\n private async discover(\n request: StartRunRequest,\n ): Promise<{ plugin: RunnablePlugin; tasks: PluginTask[] }[]> {\n this.state = \"discovering\";\n\n const wanted = request.plugins ? new Set(request.plugins) : undefined;\n const plugins = wanted\n ? this.plugins.filter((plugin) => wanted.has(plugin.name))\n : this.plugins;\n\n this.emit({\n type: \"discover:start\",\n plugins: plugins.map((plugin) => plugin.name),\n });\n\n const pluginTasks = await Promise.all(\n plugins.map(async (plugin) => {\n this.log(\"debug\", `Discovering tasks for plugin: ${plugin.name}`);\n const tasks = await plugin.discover(this.screenshotTool);\n this.emit({\n type: \"discover:plugin\",\n plugin: plugin.name,\n taskCount: tasks.length,\n });\n return { plugin, tasks };\n }),\n );\n\n const targets: Target[] = pluginTasks.flatMap(({ plugin, tasks }) =>\n tasks.map((task) => ({\n id: task.id,\n url: task.url,\n plugin: plugin.name,\n })),\n );\n\n this.emit({\n type: \"discover:complete\",\n targets,\n totalTasks: targets.length,\n });\n\n if (request.filter === undefined && request.taskIds === undefined) {\n return pluginTasks;\n }\n\n const applied: { plugin: string; before: number; after: number }[] = [];\n\n for (const entry of pluginTasks) {\n const before = entry.tasks.length;\n let tasks = entry.tasks;\n\n if (request.filter !== undefined) {\n tasks = filterTasks(tasks, request.filter);\n }\n if (request.taskIds !== undefined) {\n tasks = selectTasks(tasks, request.taskIds);\n }\n\n entry.tasks = tasks;\n applied.push({ plugin: entry.plugin.name, before, after: tasks.length });\n }\n\n this.emit({\n type: \"filter:applied\",\n filter: request.filter,\n taskIds: request.taskIds,\n plugins: applied,\n });\n\n return pluginTasks;\n }\n\n private async execute(\n pluginTasks: { plugin: RunnablePlugin; tasks: PluginTask[] }[],\n ): Promise<void> {\n this.state = \"running\";\n\n for (const { plugin, tasks } of pluginTasks) {\n if (tasks.length === 0) {\n continue;\n }\n\n if (this.controller.signal.aborted) {\n return;\n }\n\n this.anyTasksRan = true;\n let pluginHasFailure = false;\n\n for (const task of tasks) {\n this.taskRecords.set(task.id, {\n id: task.id,\n url: task.url,\n plugin: plugin.name,\n status: \"pending\",\n });\n }\n\n this.emit({\n type: \"plugin:start\",\n plugin: plugin.name,\n taskCount: tasks.length,\n });\n\n this.log(\n \"debug\",\n `Processing ${tasks.length} tasks with concurrency ${this.screenshotTool.concurrency}`,\n );\n\n let completedTasks = 0;\n const pageContexts = new Map<number, unknown>();\n\n const results = await mapWithConcurrency(\n this.screenshotTool.concurrency,\n tasks,\n async (task, workerIndex) => {\n if (this.controller.signal.aborted) {\n return undefined;\n }\n\n const page = this.screenshotTool.getPageFromPool(workerIndex);\n\n if (!pageContexts.has(workerIndex) && plugin.initPage) {\n pageContexts.set(\n workerIndex,\n await plugin.initPage(page, this.screenshotTool),\n );\n }\n const context = pageContexts.get(workerIndex);\n\n const record = this.taskRecords.get(task.id);\n if (record) {\n record.status = \"running\";\n }\n\n this.emit({\n type: \"task:start\",\n plugin: plugin.name,\n taskId: task.id,\n url: task.url,\n });\n\n const taskStart = this.now();\n // Claim the page for this task so the capture sink can attribute the\n // files written during `execute` — including variants, whose\n // filenames only the tool ever sees.\n this.taskByPage.set(page, { taskId: task.id, plugin: plugin.name });\n let result: unknown;\n try {\n result = await plugin.execute(\n task,\n page,\n this.screenshotTool,\n context,\n );\n } finally {\n this.taskByPage.delete(page);\n }\n const durationMs = this.now() - taskStart;\n\n completedTasks++;\n\n result = this.explainTaskError(result);\n\n const failed = didScreenshotFail(result);\n const status = toTaskStatus(result);\n const typedResult = result as PluginCaptureResult | undefined;\n\n if (record) {\n record.status = status;\n record.durationMs = durationMs;\n record.result = typedResult;\n }\n\n if (failed) {\n pluginHasFailure = true;\n this.failures.push({\n taskId: task.id,\n taskUrl: task.url,\n result: typedResult ?? {},\n pluginName: plugin.name,\n });\n }\n\n this.emit({\n type: \"task:complete\",\n plugin: plugin.name,\n taskId: task.id,\n url: task.url,\n status,\n completed: completedTasks,\n total: tasks.length,\n durationMs,\n result: typedResult,\n });\n\n return result;\n },\n );\n\n this.emit({\n type: \"plugin:complete\",\n plugin: plugin.name,\n resultCount: results.length,\n failed: pluginHasFailure,\n });\n }\n }\n\n /**\n * The message for a refused connection: where, and what to do about it.\n *\n * Identical for every task that hit the same server — no task id, no path —\n * so a report can collapse 300 of them into one line.\n */\n private unreachableMessage(origin: string | undefined): string {\n const where = origin ?? \"the app under test\";\n return `Cannot reach ${where}: connection refused. ${this.explainUnreachable(origin)}`;\n }\n\n private toUnreachableError(error: unknown): Error | undefined {\n const refused = findRefusedConnection(error);\n if (!refused) {\n return undefined;\n }\n return new Error(this.unreachableMessage(refused.origin), {\n cause: error,\n });\n }\n\n /**\n * Replace a plugin's refused-connection error with the explained one.\n *\n * Reads the result rather than asking the plugin, so third-party plugins get\n * the same message without an API change.\n */\n private explainTaskError(result: unknown): unknown {\n const error = (result as PluginCaptureResult | undefined)?.error;\n if (error === undefined || error === null) {\n return result;\n }\n\n const refused = findRefusedConnection(error);\n if (!refused) {\n return result;\n }\n\n return {\n ...(result as PluginCaptureResult),\n error: this.unreachableMessage(refused.origin),\n };\n }\n\n private async collectDeleted(): Promise<void> {\n if (!this.anyTasksRan) {\n return;\n }\n\n try {\n this.deletedScreenshots = await getDeletedScreenshots(this.outputDir);\n } catch (error) {\n this.log(\"warn\", \"Could not check for deleted screenshots:\", error);\n }\n }\n}\n\nexport type { TaskRecord };\n","import path from \"node:path\";\nimport { getLogger, type Logger } from \"@cappa/logger\";\nimport {\n type Browser,\n type BrowserContext,\n chromium,\n firefox,\n type Page,\n type PageScreenshotOptions,\n webkit,\n} from \"playwright-core\";\nimport {\n compareImagesGMSD,\n type CompareResult as GMSDCompareResult,\n} from \"./compare/gmsd\";\nimport {\n compareImages,\n createDiffSizePngImage,\n type CompareResult as PixelCompareResult,\n} from \"./compare/pixel\";\nimport type { LogConsoleEvents } from \"./consoleEvents\";\nimport { ScreenshotFileSystem } from \"./filesystem\";\nimport { sanitizeScreenshotFilename } from \"./paths\";\nimport type { RunLogLevel } from \"./runner/types\";\nimport type {\n DiffConfig,\n DiffConfigGMSD,\n DiffOptions,\n DiffOptionsGMSD,\n DiffOptionsPixel,\n ScreenshotOptions,\n ScreenshotSettings,\n ScreenshotVariant,\n ScreenshotVariantWithUrl,\n} from \"./types\";\n\nconst defaultPixelDiffConfig: DiffOptionsPixel = {\n type: \"pixel\",\n threshold: 0.1,\n includeAA: false,\n fastBufferCheck: true,\n maxDiffPixels: 0,\n maxDiffPercentage: 0,\n};\n\nconst defaultGMSDDiffConfig: DiffOptionsGMSD = {\n type: \"gmsd\",\n threshold: 0.1,\n downsample: 0,\n c: 170,\n};\n\nexport interface ScreenshotCaptureDetails {\n filename: string;\n filepath?: string;\n comparisonResult?: PixelCompareResult | GMSDCompareResult;\n diffImagePath?: string;\n skipped?: boolean;\n}\n\nexport interface ScreenshotVariantCaptureDetails\n extends ScreenshotCaptureDetails {\n id: string;\n label?: string;\n}\n\nexport interface ScreenshotCaptureResult {\n base: ScreenshotCaptureDetails;\n variants: ScreenshotVariantCaptureDetails[];\n}\n\nexport interface ScreenshotCaptureExtras {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n variants?: Record<\n string,\n {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n diff?: DiffOptions;\n }\n >;\n /**\n * Optional diff configuration override applied to this capture.\n * Merged on top of the global ScreenshotTool diff config.\n */\n diff?: DiffOptions;\n /**\n * Skip navigating to the base URL before capturing the base screenshot.\n * Use this when the page is already at the correct URL and in a stable state,\n * to avoid the redundant navigation.\n */\n skipBaseNavigation?: boolean;\n /**\n * Optional callback invoked after each navigation (variants only, or base when\n * skipBaseNavigation is false) to wait for visual stability before capturing.\n */\n waitForStability?: (page: Page) => Promise<void>;\n /**\n * Timestamp (from `performance.now()`) marking when the screenshot process\n * started — i.e. when the browser first navigated to the page. When provided,\n * the logged duration covers the full journey: navigation → stability waits →\n * capture. When omitted, timing begins at the capture step itself.\n */\n captureStart?: number;\n}\n\n/** The logger surface `ScreenshotTool` actually uses. */\nexport type ScreenshotLogger = Pick<\n Logger,\n \"debug\" | \"info\" | \"warn\" | \"error\" | \"success\"\n>;\n\n/** Receives this tool's log output instead of the global logger. */\nexport type ScreenshotLogSink = (\n level: RunLogLevel,\n message: string,\n ...args: unknown[]\n) => void;\n\n/**\n * Notified whenever this tool writes a screenshot.\n *\n * `page` identifies the caller: a run captures several tasks in parallel, one\n * per pooled page, so the page is the only thing that ties a filename back to\n * the task that asked for it.\n */\nexport type ScreenshotCaptureSink = (page: Page, filename: string) => void;\n\nconst LOG_SINK_LEVELS = [\n \"debug\",\n \"info\",\n \"warn\",\n \"error\",\n \"success\",\n] as const satisfies readonly RunLogLevel[];\n\n/** A logger-shaped object that forwards every call to `sink`. */\nconst toSinkLogger = (sink: ScreenshotLogSink): ScreenshotLogger =>\n Object.fromEntries(\n LOG_SINK_LEVELS.map((level) => [\n level,\n (message: unknown, ...args: unknown[]) =>\n sink(level, String(message), ...args),\n ]),\n ) as ScreenshotLogger;\n\nclass ScreenshotTool {\n browserType: \"chromium\" | \"firefox\" | \"webkit\";\n headless: boolean;\n viewport: { width: number; height: number };\n fullPage: boolean;\n outputDir: string;\n browser: Browser | null = null;\n context: BrowserContext | null = null;\n page: Page | null = null;\n concurrency: number;\n contexts: BrowserContext[] = [];\n pages: Page[] = [];\n diff: DiffOptions;\n /**\n * Where this tool's own output goes.\n *\n * Normally the global logger. While a `CaptureRunner` owns the tool it is\n * swapped for a shim that forwards into the run's event stream instead — see\n * `setLogSink`.\n */\n logger: ScreenshotLogger;\n retries: number;\n filesystem: ScreenshotFileSystem;\n logConsoleEvents: LogConsoleEvents;\n connectionTimeout: number;\n private defaultUserAgent = \"\";\n /** The real logger, kept so `setLogSink(null)` restores the same instance. */\n private readonly baseLogger: ScreenshotLogger;\n /** Set while a `CaptureRunner` owns this tool — see `setCaptureSink`. */\n private captureSink: ScreenshotCaptureSink | null = null;\n\n constructor(options: {\n browserType?: \"chromium\" | \"firefox\" | \"webkit\";\n headless?: boolean;\n viewport?: { width: number; height: number };\n fullPage?: boolean;\n outputDir?: string;\n diff?: DiffOptions;\n retries?: number;\n concurrency?: number;\n logConsoleEvents?: LogConsoleEvents;\n connectionTimeout?: number;\n }) {\n this.browserType = options.browserType || \"chromium\";\n this.headless = options.headless !== false; // Default to headless\n this.viewport = options.viewport || { width: 1920, height: 1080 };\n this.fullPage = options.fullPage ?? true;\n this.outputDir = options.outputDir || \"./screenshots\";\n this.diff = this.resolveDiffOptions(options.diff);\n this.concurrency = Math.max(1, options.concurrency || 1);\n this.logConsoleEvents = options.logConsoleEvents ?? true;\n this.connectionTimeout = options.connectionTimeout ?? 20000;\n\n this.baseLogger = getLogger();\n this.logger = this.baseLogger;\n this.retries = options.retries || 2;\n this.filesystem = new ScreenshotFileSystem(this.outputDir);\n }\n\n /**\n * Send this tool's own log output to `sink` instead of the global logger.\n *\n * `ScreenshotTool` writes lines a user expects to see — \"Screenshot saved\",\n * \"Screenshot passed visual comparison\", the retry warnings — straight to the\n * logger. That is fine in-process and useless over a network: with the\n * browser on another machine those lines would stay in the *host's* terminal\n * while the client showed a run with no commentary. A `CaptureRunner` installs\n * a sink for the duration of a run so they travel as `log` events instead.\n *\n * Pass `null` to restore the real logger.\n */\n setLogSink(sink: ScreenshotLogSink | null): void {\n this.logger = sink ? toSinkLogger(sink) : this.baseLogger;\n }\n\n /**\n * Report every screenshot this tool writes to `sink`.\n *\n * A `CaptureRunner` installs one for the duration of a run so it can record\n * which task produced which file. Nothing else can know: a plugin picks the\n * filename inside `execute` and is free to derive it from the task however\n * it likes, so the only reliable observation point is the write itself —\n * which also catches variants, whose filenames the plugin never states.\n *\n * Pass `null` to stop reporting.\n */\n setCaptureSink(sink: ScreenshotCaptureSink | null): void {\n this.captureSink = sink;\n }\n\n private resolveDiffOptions(diff?: DiffOptions): DiffOptions {\n if (diff?.type === \"gmsd\") {\n return { ...defaultGMSDDiffConfig, ...diff };\n }\n\n return { ...defaultPixelDiffConfig, ...diff, type: \"pixel\" };\n }\n\n private mergeDiffOptions(override?: DiffOptions): DiffOptions {\n const base = this.resolveDiffOptions(this.diff);\n\n if (!override) {\n return base;\n }\n\n if (override.type === \"gmsd\" || base.type === \"gmsd\") {\n const gmsdBase: DiffOptionsGMSD =\n base.type === \"gmsd\" ? base : defaultGMSDDiffConfig;\n\n return { ...gmsdBase, ...override, type: \"gmsd\" };\n }\n\n return {\n ...(base as DiffOptionsPixel),\n ...(override as DiffOptionsPixel),\n type: \"pixel\",\n };\n }\n\n /**\n * Initialize playwright and page\n */\n async init() {\n // Launch browser based on type\n const browserMap = {\n chromium,\n firefox,\n webkit,\n };\n\n const browserClass = browserMap[this.browserType];\n if (!browserClass) {\n throw new Error(`Unsupported browser type: ${this.browserType}`);\n }\n\n const browser = await browserClass.launch({\n headless: this.headless,\n });\n\n if (!browser)\n throw new Error(\"Something went wrong with starting the browser.\");\n\n this.browser = browser;\n\n const tempCtx = await browser.newContext();\n const tempPage = await tempCtx.newPage();\n this.defaultUserAgent = await tempPage.evaluate(() => navigator.userAgent);\n await tempCtx.close();\n\n await this.createContexts();\n }\n\n /**\n * Create the pool of browser contexts and pages.\n */\n private async createContexts() {\n const browser = this.browser;\n if (!browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n // Create N contexts and pages in parallel\n const results = await Promise.all(\n Array.from({ length: this.concurrency }, async () => {\n const context = await browser.newContext({\n reducedMotion: \"reduce\",\n deviceScaleFactor: 2,\n userAgent: `${this.defaultUserAgent} CappaStorybook`,\n viewport: this.viewport,\n });\n const page = await context.newPage();\n return { context, page };\n }),\n );\n\n this.contexts = results.map((r) => r.context);\n this.pages = results.map((r) => r.page);\n\n // Backward compatibility\n this.context = this.contexts[0] ?? null;\n this.page = this.pages[0] ?? null;\n }\n\n /**\n * Closes every context and page, leaving the browser process running.\n */\n async closeContexts() {\n for (const context of this.contexts) {\n await context.close();\n }\n\n this.contexts = [];\n this.pages = [];\n this.context = null;\n this.page = null;\n }\n\n /**\n * Throw away the current contexts and build a fresh pool on the same browser.\n *\n * A long-lived process that keeps the browser warm between capture runs must\n * call this first: contexts accumulate cookies, storage and scroll position,\n * and a screenshot taken against leaked state is not the screenshot the CLI\n * would have taken with a fresh browser.\n */\n async recycleContexts() {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n await this.closeContexts();\n await this.createContexts();\n }\n\n /**\n * Closes browser\n * If not closed, the process will not exit\n *\n * Tolerant of a browser that is already gone. A Ctrl-C in a terminal is\n * delivered to the whole foreground process group, Chromium included, so by\n * the time a signal handler gets here every context can already be dead and\n * closing one throws `Failed to find context with id …`. Letting that escape\n * turns a clean shutdown into an uncaught exception, which is the one thing\n * teardown must never do.\n */\n async close() {\n try {\n await this.closeContexts();\n } catch (error) {\n getLogger().debug(\"Error closing browser contexts:\", error);\n this.contexts = [];\n this.pages = [];\n this.context = null;\n this.page = null;\n }\n\n if (this.browser) {\n try {\n await this.browser.close();\n } catch (error) {\n getLogger().debug(\"Error closing the browser:\", error);\n }\n this.browser = null;\n }\n }\n\n /**\n * Navigates to a URL with \"domcontentloaded\" waitUntil\n */\n async goTo(page: Page, url: string) {\n if (!this.context) {\n throw new Error(\"Browser not initialized\");\n }\n await page.goto(url, {\n waitUntil: \"domcontentloaded\",\n timeout: this.connectionTimeout,\n });\n }\n\n /**\n * Takes a screenshot of the page\n */\n async takeScreenshot(\n page: Page,\n filename: string,\n options: ScreenshotSettings,\n ) {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n if (options.skip) {\n return;\n }\n\n try {\n // Generate filename - save to actual directory\n const filepath = this.filesystem.getActualFilePath(filename);\n\n // Ensure parent directories exist before taking screenshot\n await this.filesystem.ensureParentDir(filepath);\n\n // Take screenshot\n const screenshotOptions = {\n path: filepath,\n fullPage: options.fullPage ?? this.fullPage,\n type: \"png\" as const,\n timeout: 60000,\n mask: options.mask,\n omitBackground: options.omitBackground,\n scale: \"css\" as const,\n animations: \"disabled\",\n caret: \"hide\",\n } satisfies PageScreenshotOptions;\n\n await this.withViewport(page, options.viewport, async () => {\n if (options.delay) {\n this.logger.debug(\n `Waiting ${options.delay}ms before taking screenshot`,\n );\n await page.waitForTimeout(options.delay);\n }\n\n await page.screenshot(screenshotOptions);\n });\n\n this.logger.success(`Screenshot saved: ${filepath}`);\n\n return filepath;\n } catch (error) {\n this.logger.error(\n `Error taking screenshot of ${page.url()}:`,\n (error as Error).message,\n );\n throw error;\n }\n }\n\n /**\n * Sets the viewport size and executes the action, ensuring the original viewport is restored\n * even if the action throws an error.\n */\n private async withViewport<T>(\n page: Page,\n viewport: ScreenshotSettings[\"viewport\"],\n action: () => Promise<T>,\n ): Promise<T> {\n if (!viewport) {\n return action();\n }\n\n const previousViewport = page.viewportSize();\n\n // Check if the new viewport is the same as the current one\n if (\n previousViewport &&\n previousViewport.width === viewport.width &&\n previousViewport.height === viewport.height\n ) {\n return action();\n }\n\n await page.setViewportSize(viewport);\n\n try {\n return await action();\n } finally {\n // Always restore the original viewport, even if the action throws an error\n if (previousViewport) {\n await page.setViewportSize(previousViewport);\n }\n }\n }\n\n /**\n * Takes a screenshot and returns the buffer (for comparison purposes)\n */\n async takeScreenshotBuffer(\n page: Page,\n options: ScreenshotSettings,\n ): Promise<Buffer> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n if (options.skip) {\n throw new Error(\"Screenshot skipped\");\n }\n\n try {\n // Take screenshot without saving to file\n const screenshotOptions = {\n fullPage: options.fullPage ?? this.fullPage,\n type: \"png\" as const,\n timeout: 60000,\n mask: options.mask,\n omitBackground: options.omitBackground,\n scale: \"css\" as const,\n animations: \"disabled\",\n caret: \"hide\",\n } satisfies PageScreenshotOptions;\n\n const buffer = await this.withViewport(\n page,\n options.viewport,\n async () => {\n if (options.delay) {\n this.logger.debug(\n `Waiting ${options.delay}ms before taking screenshot`,\n );\n await page.waitForTimeout(options.delay);\n }\n\n return page.screenshot(screenshotOptions);\n },\n );\n\n return buffer;\n } catch (error) {\n this.logger.error(\n `Error taking screenshot of ${page.url()}:`,\n (error as Error).message,\n );\n throw error;\n }\n }\n\n async takeScreenshotWithComparison(\n page: Page,\n filename: string,\n referenceImage: string | Buffer,\n options: ScreenshotSettings & {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n },\n diffOverride?: DiffOptions,\n ): Promise<{\n screenshotPath: string;\n comparisonResult: PixelCompareResult | GMSDCompareResult;\n diffImagePath?: string;\n }> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n try {\n // Generate filename and take screenshot - save to actual directory\n const filepath = this.filesystem.getActualFilePath(filename);\n\n const screenshotSettings: ScreenshotSettings = {\n fullPage: options.fullPage ?? this.fullPage,\n mask: options.mask,\n omitBackground: options.omitBackground,\n delay: options.delay,\n viewport: options.viewport,\n };\n\n const retryScreenshot = await this.retryScreenshot(\n page,\n referenceImage,\n screenshotSettings,\n diffOverride,\n );\n\n if (!retryScreenshot.screenshotPath) {\n throw new Error(\"Screenshot buffer is undefined\");\n }\n\n // Save screenshot to actual directory\n await this.filesystem.writeActualFile(\n filename,\n retryScreenshot.screenshotPath,\n );\n this.logger.debug(`Actual screenshot saved: ${filepath}`);\n\n if (retryScreenshot.passed) {\n this.logger.success(`Screenshot passed visual comparison`);\n } else {\n this.logger.error(`Screenshot failed visual comparison`);\n }\n\n let diffImagePath: string | undefined;\n\n // Save diff image if requested and there are differences\n if (\n options.saveDiffImage &&\n retryScreenshot.comparisonResult?.diffBuffer &&\n !retryScreenshot.passed\n ) {\n const diffFilename = options.diffImageFilename || filename;\n // Save to diff directory\n diffImagePath = this.filesystem.getDiffFilePath(diffFilename);\n\n await this.filesystem.writeDiffFile(\n diffFilename,\n retryScreenshot.comparisonResult.diffBuffer,\n );\n\n this.logger.debug(`Diff image saved: ${diffImagePath}`);\n\n // When interpretation is enabled, persist diff stats + interpretation as\n // a sidecar so the review UI and CLI can surface them after rebuilding\n // state from disk. Skipped entirely otherwise so no extra files appear\n // for users who have not opted in (pixel only).\n const result = retryScreenshot.comparisonResult;\n if (\"numDiffPixels\" in result && result.interpretation) {\n await this.filesystem.writeDiffMetaFile(diffFilename, {\n numDiffPixels: result.numDiffPixels,\n percentDifference: result.percentDifference,\n interpretation: result.interpretation,\n });\n }\n }\n\n // different sizes diff image\n if (\n retryScreenshot.comparisonResult !== null &&\n typeof retryScreenshot.comparisonResult === \"object\" &&\n \"differentSizes\" in retryScreenshot.comparisonResult &&\n retryScreenshot.comparisonResult.differentSizes\n ) {\n this.logger.warn(`Screenshot has different sizes than reference image`);\n\n const diffFilename = options.diffImageFilename || filename;\n diffImagePath = this.filesystem.getDiffFilePath(diffFilename);\n const diffBuffer = await createDiffSizePngImage(200, 200);\n\n await this.filesystem.writeDiffFile(diffFilename, diffBuffer);\n\n this.logger.debug(`Diff Size image saved: ${diffImagePath}`);\n }\n\n return {\n screenshotPath: filepath,\n comparisonResult: retryScreenshot.comparisonResult,\n diffImagePath,\n };\n } catch (error) {\n this.logger.error(\n `Error taking screenshot with comparison of ${page.url()}:`,\n (error as Error).message,\n );\n throw error;\n }\n }\n\n async retryScreenshot(\n page: Page,\n referenceImage: string | Buffer,\n options: ScreenshotSettings,\n diffOverride?: DiffOptions,\n ) {\n const diffConfig = this.mergeDiffOptions(diffOverride);\n\n for (let i = 0; i < this.retries; i++) {\n try {\n const screenshotBuffer = await this.takeScreenshotBuffer(page, {\n ...options,\n delay: this.getIncBackoffDelay(i, options.delay || 0),\n });\n\n if (!screenshotBuffer) {\n throw new Error(\"Screenshot buffer is undefined\");\n }\n\n const comparisonResult =\n diffConfig.type === \"gmsd\"\n ? await compareImagesGMSD(\n referenceImage,\n screenshotBuffer,\n true,\n diffConfig as DiffConfigGMSD,\n )\n : await compareImages(\n referenceImage,\n screenshotBuffer,\n true,\n diffConfig as DiffConfig,\n );\n\n // last retry\n if (i === this.retries - 1 && !comparisonResult.passed) {\n this.logger.error(\n `Failed to match screenshot after ${this.retries} retries`,\n );\n return {\n screenshotPath: screenshotBuffer,\n comparisonResult,\n passed: false,\n };\n }\n\n if (comparisonResult.passed) {\n return {\n screenshotPath: screenshotBuffer,\n comparisonResult,\n passed: true,\n };\n } else {\n const summary =\n \"numDiffPixels\" in comparisonResult\n ? comparisonResult.differentSizes\n ? \"different image sizes\"\n : `${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%)`\n : `gmsd score ${comparisonResult.gmsd.toFixed(4)}`;\n\n this.logger.warn(\n `Comparison did not match. Retrying in ${this.getIncBackoffDelay(i + 1, options.delay || 0)}ms... \\nComparison result: ${summary}`,\n );\n }\n } catch (error) {\n this.logger.error(\n `Error taking screenshot after ${i + 1} retries:`,\n (error as Error).message,\n );\n }\n }\n\n return {\n screenshotPath: null,\n comparisonResult: null,\n passed: false,\n };\n }\n\n /**\n * Resolve the filename a variant is written under.\n *\n * An explicit `variant.filename` wins, but it is sanitized first: for\n * `@cappa/plugin-storybook` it arrives from the browser as a story parameter,\n * so it is story-author input and could otherwise carry `../` or an absolute\n * path into the write sink. A name left empty by sanitization falls back to\n * the derived one.\n */\n getVariantFilename(filename: string, variant: ScreenshotVariant): string {\n if (variant.filename) {\n const safeFilename = sanitizeScreenshotFilename(variant.filename);\n\n if (safeFilename !== variant.filename) {\n this.logger.warn(\n `Variant filename \"${variant.filename}\" is not a valid screenshot path, using \"${safeFilename || \"the derived name\"}\" instead`,\n );\n }\n\n if (safeFilename) {\n return safeFilename;\n }\n }\n\n const parsed = path.parse(filename);\n const sanitizedId = variant.id\n .trim()\n .replace(/[^a-zA-Z0-9_-]+/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n const suffix = sanitizedId || \"variant\";\n const ext = parsed.ext || \".png\";\n const variantName = `${parsed.name}--${suffix}${ext}`;\n\n return parsed.dir ? path.join(parsed.dir, variantName) : variantName;\n }\n\n /**\n * Captures a single screenshot with the given options\n */\n private async captureSingleScreenshot(\n page: Page,\n filename: string,\n options: ScreenshotSettings,\n extras: {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n diff?: DiffOptions;\n captureStart?: number;\n } = {},\n ): Promise<ScreenshotCaptureDetails> {\n const result: ScreenshotCaptureDetails = { filename };\n\n if (options.skip) {\n result.skipped = true;\n return result;\n }\n\n const start = extras.captureStart ?? performance.now();\n const saveDiff = extras.saveDiffImage ?? false;\n const diffFilename = extras.diffImageFilename ?? filename;\n const diffOverride = extras.diff;\n\n // This capture decides the screenshot's diff afresh: whatever the last run\n // left in `diff/` describes an image that is about to be replaced.\n await this.filesystem.removeDiffFiles(diffFilename);\n\n if (!(await this.filesystem.hasExpectedFile(filename))) {\n this.logger.debug(\n `Expected image not found for ${filename}, taking screenshot`,\n );\n\n result.filepath = await this.takeScreenshot(page, filename, options);\n } else {\n const { screenshotPath, comparisonResult, diffImagePath } =\n await this.takeScreenshotWithComparison(\n page,\n filename,\n this.filesystem.getExpectedFilePath(filename),\n {\n ...options,\n saveDiffImage: saveDiff,\n diffImageFilename: diffFilename,\n },\n diffOverride,\n );\n\n result.filepath = screenshotPath;\n result.comparisonResult = comparisonResult;\n result.diffImagePath = diffImagePath;\n }\n\n const duration = Math.round(performance.now() - start);\n this.logger.debug(`${filename} captured in ${duration}ms`);\n\n // Reported after the capture, so a task that threw on the way here does not\n // claim a file it never wrote. A failing sink is the observer's problem and\n // must not fail the capture.\n try {\n this.captureSink?.(page, filename);\n } catch {\n // ignored\n }\n\n return result;\n }\n\n async capture(\n page: Page,\n filename: string,\n options: ScreenshotOptions,\n extras: ScreenshotCaptureExtras = {},\n ): Promise<ScreenshotCaptureResult> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n const { variants = [], ...baseOptions } = options;\n const baseResult: ScreenshotCaptureDetails = { filename };\n const variantResults: ScreenshotVariantCaptureDetails[] = [];\n\n const baseSaveDiff = extras.saveDiffImage ?? false;\n const baseDiffFilename = extras.diffImageFilename ?? filename;\n const baseDiffOverride = extras.diff;\n\n if (baseOptions.skip) {\n return {\n base: { ...baseResult, skipped: true },\n variants: variants.map((variant) => ({\n id: variant.id,\n label: variant.label,\n filename: this.getVariantFilename(filename, variant),\n skipped: true,\n })),\n };\n }\n\n // Capture base screenshot\n const baseCaptureResult = await this.captureSingleScreenshot(\n page,\n filename,\n baseOptions,\n {\n saveDiffImage: baseSaveDiff,\n diffImageFilename: baseDiffFilename,\n diff: baseDiffOverride,\n captureStart: extras.captureStart,\n },\n );\n\n baseResult.filepath = baseCaptureResult.filepath;\n baseResult.comparisonResult = baseCaptureResult.comparisonResult;\n baseResult.diffImagePath = baseCaptureResult.diffImagePath;\n baseResult.skipped = baseCaptureResult.skipped;\n\n for (const variant of variants) {\n const variantFilename = this.getVariantFilename(filename, variant);\n const variantOptions: ScreenshotSettings = {\n ...baseOptions,\n ...variant.options,\n };\n\n const variantResult: ScreenshotVariantCaptureDetails = {\n id: variant.id,\n label: variant.label,\n filename: variantFilename,\n };\n\n if (variantOptions.skip) {\n variantResult.skipped = true;\n variantResults.push(variantResult);\n continue;\n }\n\n const variantExtra = extras.variants?.[variant.id];\n const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;\n const variantDiffFilename =\n variantExtra?.diffImageFilename ?? variantFilename;\n const variantDiffOverride = variantExtra?.diff ?? baseDiffOverride;\n\n const variantCaptureResult = await this.captureSingleScreenshot(\n page,\n variantFilename,\n variantOptions,\n {\n saveDiffImage: variantSaveDiff,\n diffImageFilename: variantDiffFilename,\n diff: variantDiffOverride,\n },\n );\n\n variantResult.filepath = variantCaptureResult.filepath;\n variantResult.comparisonResult = variantCaptureResult.comparisonResult;\n variantResult.diffImagePath = variantCaptureResult.diffImagePath;\n variantResult.skipped = variantCaptureResult.skipped;\n\n variantResults.push(variantResult);\n }\n\n return {\n base: baseResult,\n variants: variantResults,\n };\n }\n\n /**\n * Applies SVG and UI optimizations for screenshots\n */\n private async applyScreenshotOptimizations(page: Page) {\n await page.addStyleTag({\n content: `\n *, *::before, *::after {\n -moz-animation: none !important;\n -moz-transition: none !important;\n transition: none !important; \n animation: none !important;\n }\n *, input, textarea { caret-color: transparent !important }\n *:focus { outline: none !important }\n *:focus-visible { outline: none !important }\n *:focus-within { outline: none !important }\n * { text-rendering: optimizeLegibility !important }\n ::-webkit-scrollbar { display: none !important }\n html { scroll-behavior: auto !important }\n svg, svg * {\n shape-rendering: crispEdges !important;\n text-rendering: geometricPrecision !important;\n vector-effect: non-scaling-stroke !important;\n }\n img { image-rendering: crisp-edges !important }\n `,\n });\n }\n\n /**\n * Captures screenshots for multiple variants, each with their own URL\n */\n async captureWithVariants(\n page: Page,\n baseFilename: string,\n baseUrl: string,\n baseOptions: ScreenshotSettings,\n variants: ScreenshotVariantWithUrl[],\n extras: ScreenshotCaptureExtras = {},\n ): Promise<ScreenshotCaptureResult> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n const baseResult: ScreenshotCaptureDetails = { filename: baseFilename };\n const variantResults: ScreenshotVariantCaptureDetails[] = [];\n\n const baseSaveDiff = extras.saveDiffImage ?? false;\n const baseDiffFilename = extras.diffImageFilename ?? baseFilename;\n const baseDiffOverride = extras.diff;\n\n // Capture base screenshot\n let baseStart: number;\n if (!extras.skipBaseNavigation) {\n baseStart = performance.now();\n getLogger().debug(`Going to base URL: ${baseUrl}`);\n await page.goto(baseUrl, { timeout: this.connectionTimeout });\n await this.applyScreenshotOptimizations(page);\n await extras.waitForStability?.(page);\n } else {\n baseStart = performance.now();\n }\n\n const baseCaptureResult = await this.captureSingleScreenshot(\n page,\n baseFilename,\n baseOptions,\n {\n saveDiffImage: baseSaveDiff,\n diffImageFilename: baseDiffFilename,\n diff: baseDiffOverride,\n captureStart: extras.captureStart ?? baseStart,\n },\n );\n\n baseResult.filepath = baseCaptureResult.filepath;\n baseResult.comparisonResult = baseCaptureResult.comparisonResult;\n baseResult.diffImagePath = baseCaptureResult.diffImagePath;\n baseResult.skipped = baseCaptureResult.skipped;\n\n // Capture variant screenshots\n for (const variant of variants) {\n const variantFilename = this.getVariantFilename(baseFilename, variant);\n const variantOptions: ScreenshotSettings = {\n ...baseOptions,\n ...variant.options,\n };\n\n const variantResult: ScreenshotVariantCaptureDetails = {\n id: variant.id,\n label: variant.label,\n filename: variantFilename,\n };\n\n if (variantOptions.skip) {\n variantResult.skipped = true;\n variantResults.push(variantResult);\n continue;\n }\n\n // Navigate to variant URL and apply optimizations\n const variantStart = performance.now();\n getLogger().debug(`Going to variant URL: ${variant.url}`);\n await page.goto(variant.url, { timeout: this.connectionTimeout });\n await this.applyScreenshotOptimizations(page);\n await extras.waitForStability?.(page);\n\n const variantExtra = extras.variants?.[variant.id];\n const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;\n const variantDiffFilename =\n variantExtra?.diffImageFilename ?? variantFilename;\n const variantDiffOverride = variantExtra?.diff ?? baseDiffOverride;\n\n const variantCaptureResult = await this.captureSingleScreenshot(\n page,\n variantFilename,\n variantOptions,\n {\n saveDiffImage: variantSaveDiff,\n diffImageFilename: variantDiffFilename,\n diff: variantDiffOverride,\n captureStart: variantStart,\n },\n );\n\n variantResult.filepath = variantCaptureResult.filepath;\n variantResult.comparisonResult = variantCaptureResult.comparisonResult;\n variantResult.diffImagePath = variantCaptureResult.diffImagePath;\n variantResult.skipped = variantCaptureResult.skipped;\n\n variantResults.push(variantResult);\n }\n\n return {\n base: baseResult,\n variants: variantResults,\n };\n }\n\n /**\n * Gets the exponential backoff delay\n */\n getIncBackoffDelay(i: number, delay: number): number {\n return i > 0 ? 500 * 2 ** (i - 1) + (delay || 0) : 0;\n }\n\n /**\n * Get a page from the pool by index\n */\n getPageFromPool(index: number): Page {\n if (index < 0) {\n throw new Error(`Page index ${index} must be non-negative`);\n }\n\n if (index >= this.pages.length) {\n throw new Error(\n `Page index ${index} exceeds pool size ${this.pages.length}`,\n );\n }\n\n if (!this.pages[index]) {\n throw new Error(`Page index ${index} is undefined`);\n }\n\n return this.pages[index];\n }\n}\n\nexport default ScreenshotTool;\n","import path from \"node:path\";\n\n/**\n * Where agent review keeps its state, inside `outputDir`.\n *\n * Its own module so screenshot collection can read the report without\n * importing the review pipeline, which itself collects screenshots.\n */\nexport const AGENT_DIRNAME = \".cappa-agent\";\n\n/** Bumped only if `request.json` or `report.json` change incompatibly. */\nexport const AGENT_REPORT_VERSION = 1;\n\nexport const agentDir = (outputDir: string): string =>\n path.resolve(outputDir, AGENT_DIRNAME);\n\nexport const judgmentsRoot = (outputDir: string): string =>\n path.join(agentDir(outputDir), \"judgments\");\n\nexport const agentReportPath = (outputDir: string): string =>\n path.join(agentDir(outputDir), \"report.json\");\n","import type {\n ChangeRegion,\n InterpretResult,\n} from \"@blazediff/interpret-native\";\n\n/**\n * What a reviewer — heuristic or agent — believes a changed screenshot is.\n *\n * `ambiguous` is only ever produced by the heuristic: it is the signal that\n * the change has to be looked at, and an agent's verdict must resolve it into\n * one of the other three.\n */\nexport const VERDICT_LABELS = [\n \"regression-likely\",\n \"intentional-likely\",\n \"noise-likely\",\n \"ambiguous\",\n] as const;\n\nexport type VerdictLabel = (typeof VERDICT_LABELS)[number];\n\n/** The labels a judge may hand back — everything but `ambiguous`. */\nexport const JUDGED_LABELS = [\n \"regression-likely\",\n \"intentional-likely\",\n \"noise-likely\",\n] as const;\n\nexport type JudgedLabel = (typeof JUDGED_LABELS)[number];\n\n/** What to do next with a screenshot carrying a label. */\nexport type VerdictAction =\n | \"investigate\"\n | \"approve-if-intended\"\n | \"mask-or-approve\";\n\nexport const ACTION_BY_LABEL: Record<VerdictLabel, VerdictAction> = {\n \"regression-likely\": \"investigate\",\n \"intentional-likely\": \"approve-if-intended\",\n \"noise-likely\": \"mask-or-approve\",\n ambiguous: \"investigate\",\n};\n\nexport type Verdict = {\n label: VerdictLabel;\n /** One line, e.g. `2 regions: 1 addition, 1 color-change @ top-left (1.20%, medium)`. */\n headline: string;\n rationale: string[];\n action: VerdictAction;\n};\n\nexport const isVerdictLabel = (value: unknown): value is VerdictLabel =>\n typeof value === \"string\" &&\n (VERDICT_LABELS as readonly string[]).includes(value);\n\nexport const isJudgedLabel = (value: unknown): value is JudgedLabel =>\n typeof value === \"string\" &&\n (JUDGED_LABELS as readonly string[]).includes(value);\n\n/**\n * Change types are normalised to kebab-case before they are compared.\n *\n * `@blazediff/interpret-native` reports `color-change` today but earlier\n * releases reported `ColorChange`; normalising keeps the heuristic working\n * across a diff-engine upgrade instead of silently degrading every screenshot\n * to `ambiguous`.\n */\nexport const normalizeChangeType = (changeType: string): string =>\n changeType\n .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .replace(/[\\s_]+/g, \"-\")\n .toLowerCase();\n\nconst normalizeSeverity = (severity: string | undefined): string =>\n (severity ?? \"\").toLowerCase();\n\n/** Structural: something appeared, vanished or was replaced. */\nconst REGRESSIVE_TYPES = new Set([\"content-change\", \"addition\", \"deletion\"]);\n/** Restyled or moved, with structure intact. */\nconst RESTYLE_TYPES = new Set([\"color-change\", \"shift\"]);\nconst NOISE_TYPES = new Set([\"rendering-noise\"]);\nconst ELEVATED_SEVERITY = new Set([\"medium\", \"high\"]);\n\n/** Below this share of the image, a low-severity change is not perceptible. */\nexport const SUB_PERCEPTUAL_PERCENT = 0.01;\n\n/** Mean region confidence above which a pure recolour is trusted. */\nconst RECOLOR_CONFIDENCE = 0.7;\n\nexport type VerdictInput = {\n /** Percentage of differing pixels (0-100), from the pixel diff. */\n percentDifference?: number;\n numDiffPixels?: number;\n interpretation?: InterpretResult;\n /** Expected and actual have different dimensions. */\n differentSizes?: boolean;\n};\n\nconst formatPercent = (percent: number | undefined): string => {\n if (percent === undefined) return \"?%\";\n return percent >= 0.01 ? `${percent.toFixed(2)}%` : `${percent.toFixed(3)}%`;\n};\n\nconst countByType = (regions: readonly ChangeRegion[]) => {\n const counts = new Map<string, number>();\n for (const region of regions) {\n const type = normalizeChangeType(region.changeType);\n counts.set(type, (counts.get(type) ?? 0) + 1);\n }\n return counts;\n};\n\nconst formatBreakdown = (counts: Map<string, number>): string =>\n [...counts]\n .sort((a, b) => b[1] - a[1])\n .map(([type, count]) => `${count} ${type}`)\n .join(\", \");\n\nconst largestRegion = (regions: readonly ChangeRegion[]) =>\n regions.reduce<ChangeRegion | undefined>(\n (best, region) =>\n !best || region.pixelCount > best.pixelCount ? region : best,\n undefined,\n );\n\nconst meanConfidence = (regions: readonly ChangeRegion[]): number =>\n regions.length === 0\n ? 0\n : regions.reduce((sum, region) => sum + (region.confidence ?? 0), 0) /\n regions.length;\n\n/**\n * A one-line description of a change, shaped so that the same kind of change\n * on different screenshots produces the same headline — which is what lets an\n * agent spot one shared cause (a footer timestamp, a theme toggle) across\n * dozens of screenshots without opening any of them.\n */\nexport const buildHeadline = (input: VerdictInput): string => {\n if (input.differentSizes) return \"image dimensions changed\";\n\n const interpretation = input.interpretation;\n const percent = input.percentDifference ?? interpretation?.diffPercentage;\n\n if (!interpretation || interpretation.regions.length === 0) {\n const pixels = input.numDiffPixels ?? interpretation?.diffCount;\n return `${pixels?.toLocaleString(\"en-US\") ?? \"?\"} px (${formatPercent(percent)}) - no region analysis`;\n }\n\n const regions = interpretation.regions;\n const counts = countByType(regions);\n const position = largestRegion(regions)?.position;\n const at = position ? ` @ ${position}` : \"\";\n const severity = normalizeSeverity(interpretation.severity) || \"?\";\n\n if (regions.length === 1) {\n return `1 ${[...counts.keys()][0]}${at} (${formatPercent(percent)}, ${severity})`;\n }\n\n return `${regions.length} regions: ${formatBreakdown(counts)}${at} (${formatPercent(percent)}, ${severity})`;\n};\n\nconst verdict = (\n label: VerdictLabel,\n headline: string,\n rationale: string[],\n): Verdict => ({ label, headline, rationale, action: ACTION_BY_LABEL[label] });\n\n/**\n * Classify a changed screenshot from its diff interpretation alone.\n *\n * Deliberately conservative: only the cases the signals settle are labelled,\n * and everything else is `ambiguous` so that it reaches a judge who can look\n * at the pixels. A wrong `noise-likely` hides a regression; a wrong\n * `ambiguous` costs one look.\n */\nexport const deriveVerdict = (input: VerdictInput): Verdict => {\n const headline = buildHeadline(input);\n\n if (input.differentSizes) {\n return verdict(\"ambiguous\", headline, [\n \"expected and actual have different dimensions — content likely grew or shrank\",\n \"could be an intended content change or a broken layout\",\n ]);\n }\n\n const interpretation = input.interpretation;\n if (!interpretation || interpretation.regions.length === 0) {\n return verdict(\"ambiguous\", headline, [\n \"pixels differ but no change regions were found\",\n ]);\n }\n\n const regions = interpretation.regions;\n const types = regions.map((region) => normalizeChangeType(region.changeType));\n const severity = normalizeSeverity(interpretation.severity);\n const percent = input.percentDifference ?? interpretation.diffPercentage;\n const counts = countByType(regions);\n\n if (types.every((type) => NOISE_TYPES.has(type))) {\n return verdict(\"noise-likely\", headline, [\n \"every region is classified as rendering noise\",\n ]);\n }\n\n if (percent < SUB_PERCEPTUAL_PERCENT && severity === \"low\") {\n return verdict(\"noise-likely\", headline, [\n `less than ${SUB_PERCEPTUAL_PERCENT}% of the image differs (${formatPercent(percent)}) at low severity`,\n \"sub-perceptual change\",\n ]);\n }\n\n if (\n types.some((type) => REGRESSIVE_TYPES.has(type)) &&\n ELEVATED_SEVERITY.has(severity)\n ) {\n const structural = [...counts]\n .filter(([type]) => REGRESSIVE_TYPES.has(type))\n .map(([type, count]) => `${count} ${type}`)\n .join(\", \");\n return verdict(\"regression-likely\", headline, [\n `${severity} severity with structural changes (${structural})`,\n \"content or layout changed, not just styling\",\n ]);\n }\n\n const allRecolor = types.every((type) => type === \"color-change\");\n if (allRecolor && meanConfidence(regions) > RECOLOR_CONFIDENCE) {\n return verdict(\"intentional-likely\", headline, [\n `${regions.length} confident color-change ${regions.length === 1 ? \"region\" : \"regions\"}`,\n \"edge structure preserved — looks like a theming or palette change\",\n ]);\n }\n\n if (!allRecolor && types.every((type) => RESTYLE_TYPES.has(type))) {\n return verdict(\"intentional-likely\", headline, [\n \"every region is a shift or color change — content moved or was restyled, structure preserved\",\n ]);\n }\n\n return verdict(\"ambiguous\", headline, [\n `mix of change types (${formatBreakdown(counts)}) at ${severity || \"unknown\"} severity`,\n `${formatPercent(percent)} of the image differs`,\n ]);\n};\n","import fsp from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { AgentReview } from \"../types\";\nimport { AGENT_REPORT_VERSION, agentReportPath } from \"./paths\";\nimport { isVerdictLabel } from \"./verdict\";\n\n/**\n * The verdicts of the last `cappa agent check`, keyed by screenshot name.\n *\n * Read on every screenshot listing so the review UI shows them, which is why\n * this reads only `report.json` and never touches the review pipeline.\n */\nexport type AgentReviewIndex = {\n createdAt: number;\n reviews: Map<string, AgentReview>;\n};\n\ntype ReportShape = {\n version?: unknown;\n createdAt?: unknown;\n entries?: unknown;\n};\n\n/**\n * Read the review index, or nothing.\n *\n * Never throws: like the capture manifest, the report is an extra, and a\n * missing or hand-edited file must not break the screenshot listing.\n */\nexport const readAgentReviewIndex = async (\n outputDir: string,\n): Promise<AgentReviewIndex | undefined> => {\n let raw: ReportShape;\n try {\n raw = JSON.parse(await fsp.readFile(agentReportPath(outputDir), \"utf8\"));\n } catch {\n return undefined;\n }\n\n const createdAt =\n typeof raw?.createdAt === \"string\" ? Date.parse(raw.createdAt) : NaN;\n if (\n raw?.version !== AGENT_REPORT_VERSION ||\n Number.isNaN(createdAt) ||\n !Array.isArray(raw.entries)\n ) {\n return undefined;\n }\n\n const reviews = new Map<string, AgentReview>();\n for (const entry of raw.entries) {\n if (typeof entry !== \"object\" || entry === null) continue;\n const { name, category, verdict, pending } = entry as Record<\n string,\n unknown\n >;\n if (typeof name !== \"string\" || category !== \"changed\") continue;\n if (typeof verdict !== \"object\" || verdict === null) continue;\n\n const v = verdict as Record<string, unknown>;\n if (!isVerdictLabel(v.label) || typeof v.headline !== \"string\") continue;\n\n reviews.set(name, {\n label: v.label,\n headline: v.headline,\n rationale: Array.isArray(v.rationale)\n ? v.rationale.filter((line): line is string => typeof line === \"string\")\n : [],\n action: v.action as AgentReview[\"action\"],\n source: v.source === \"agent\" ? \"agent\" : \"heuristic\",\n ...(typeof v.confidence === \"number\" ? { confidence: v.confidence } : {}),\n pending: pending === true,\n reviewedAt: new Date(createdAt).toISOString(),\n });\n }\n\n return { createdAt, reviews };\n};\n\nconst modifiedAt = async (file: string): Promise<number> => {\n try {\n return (await fsp.stat(file)).mtimeMs;\n } catch {\n return Number.POSITIVE_INFINITY;\n }\n};\n\n/**\n * The review for a changed screenshot, if it is still about these images.\n *\n * A capture after the check rewrites `actual/`, an approval rewrites\n * `expected/`; either makes the verdict describe pixels that are gone. File\n * times are compared rather than content hashed because this runs on every\n * listing the review UI makes.\n */\nexport const freshAgentReview = async (\n index: AgentReviewIndex | undefined,\n outputDir: string,\n screenshot: { name: string; actualPath: string; expectedPath: string },\n): Promise<AgentReview | undefined> => {\n const review = index?.reviews.get(screenshot.name);\n if (!index || !review) return undefined;\n\n const [actual, expected] = await Promise.all([\n modifiedAt(path.resolve(outputDir, screenshot.actualPath)),\n modifiedAt(path.resolve(outputDir, screenshot.expectedPath)),\n ]);\n\n return actual <= index.createdAt && expected <= index.createdAt\n ? review\n : undefined;\n};\n","import { createHash } from \"node:crypto\";\nimport path from \"node:path\";\nimport { readDiffMeta } from \"../filesystem\";\nimport type { Screenshot } from \"../types\";\n\nexport const groupScreenshots = async (\n actualScreenshots: string[],\n expectedScreenshots: string[],\n diffScreenshots: string[],\n outputDir: string,\n): Promise<Screenshot[]> => {\n const screenshotRepresentations: Screenshot[] = [];\n\n // Build Maps for O(1) lookups instead of O(n) .find() calls\n const expectedByRelativePath = new Map<string, string>();\n for (const screenshot of expectedScreenshots) {\n const relativePath = path.relative(`${outputDir}/expected`, screenshot);\n expectedByRelativePath.set(relativePath, screenshot);\n }\n\n const diffByRelativePath = new Map<string, string>();\n for (const screenshot of diffScreenshots) {\n const relativePath = path.relative(`${outputDir}/diff`, screenshot);\n diffByRelativePath.set(relativePath, screenshot);\n }\n\n const actualRelativePaths = new Set<string>();\n\n for (const screenshot of actualScreenshots) {\n const relativePath = path.relative(`${outputDir}/actual`, screenshot);\n actualRelativePaths.add(relativePath);\n\n const name = relativePath.replace(\".png\", \"\");\n const id = createHash(\"sha256\").update(relativePath).digest(\"hex\");\n\n const expectedScreenshot = expectedByRelativePath.get(relativePath);\n const diffScreenshot = diffByRelativePath.get(relativePath);\n\n // Load the diff metadata sidecar (stats + interpretation) for changed\n // screenshots so it can be surfaced in the review UI and CLI.\n const diffMeta = diffScreenshot\n ? await readDiffMeta(diffScreenshot)\n : undefined;\n\n screenshotRepresentations.push({\n id: id,\n name: name,\n category: buildCategory(expectedScreenshot, diffScreenshot),\n expectedPath: expectedScreenshot\n ? path.relative(outputDir, expectedScreenshot)\n : undefined,\n diffPath: diffScreenshot\n ? path.relative(outputDir, diffScreenshot)\n : undefined,\n actualPath: path.relative(outputDir, screenshot),\n ...(diffMeta ? { diffMeta } : {}),\n } as Screenshot);\n }\n\n for (const expectedScreenshot of expectedScreenshots) {\n const relativePath = path.relative(\n `${outputDir}/expected`,\n expectedScreenshot,\n );\n\n // If the actual screenshot exists, it means we already added it\n if (actualRelativePaths.has(relativePath)) {\n continue;\n }\n\n const name = relativePath.replace(\".png\", \"\");\n const id = createHash(\"sha256\").update(relativePath).digest(\"hex\");\n\n screenshotRepresentations.push({\n id: id,\n name: name,\n category: \"deleted\",\n expectedPath: path.relative(outputDir, expectedScreenshot),\n });\n }\n\n return screenshotRepresentations.sort((a, b) => {\n return CATEGORY_ORDER[a.category] - CATEGORY_ORDER[b.category];\n });\n};\n\nconst buildCategory = (\n expectedScreenshot: string | undefined,\n diffScreenshot: string | undefined,\n) => {\n if (expectedScreenshot && diffScreenshot) {\n return \"changed\";\n }\n if (expectedScreenshot) {\n return \"passed\";\n }\n\n return \"new\";\n};\n\nconst CATEGORY_ORDER: Record<Screenshot[\"category\"], number> = {\n new: 0,\n deleted: 1,\n changed: 2,\n passed: 3,\n};\n","import { glob } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { freshAgentReview, readAgentReviewIndex } from \"../agent/reviewIndex\";\nimport type { Screenshot } from \"../types\";\nimport { groupScreenshots } from \"./groupScreenshots\";\nimport { readCaptureManifest } from \"./manifest\";\n\nconst listPngs = async (dir: string): Promise<string[]> =>\n Array.fromAsync(await glob(path.resolve(dir, \"**/*.png\")));\n\n/**\n * Read the `actual/`, `expected/` and `diff/` directories of `outputDir` and\n * group them into the screenshot representations used by the CLI commands\n * (including the diff metadata sidecar with the optional interpretation).\n *\n * The capture manifest is folded in here so every consumer — the CLI, the\n * server, the review UI — sees the same `taskId`, and so a screenshot captured\n * before manifests existed simply has none rather than a wrong one. The last\n * `cappa agent check` verdict is folded in the same way, as `review`, while it\n * still describes the images on disk.\n */\nexport const collectScreenshots = async (\n outputDir: string,\n): Promise<Screenshot[]> => {\n const [\n actualScreenshots,\n expectedScreenshots,\n diffScreenshots,\n manifest,\n reviewIndex,\n ] = await Promise.all([\n listPngs(path.resolve(outputDir, \"actual\")),\n listPngs(path.resolve(outputDir, \"expected\")),\n listPngs(path.resolve(outputDir, \"diff\")),\n readCaptureManifest(outputDir),\n readAgentReviewIndex(outputDir),\n ]);\n\n const screenshots = await groupScreenshots(\n actualScreenshots,\n expectedScreenshots,\n diffScreenshots,\n outputDir,\n );\n\n return Promise.all(\n screenshots.map(async (screenshot) => {\n const origin = manifest.screenshots[screenshot.name];\n const withOrigin: Screenshot = origin\n ? { ...screenshot, taskId: origin.taskId, plugin: origin.plugin }\n : screenshot;\n\n if (withOrigin.category !== \"changed\" || !reviewIndex) {\n return withOrigin;\n }\n\n const review = await freshAgentReview(reviewIndex, outputDir, withOrigin);\n return review ? { ...withOrigin, review } : withOrigin;\n }),\n );\n};\n","import {\n type ChildProcess,\n execFile,\n execFileSync,\n spawn,\n} from \"node:child_process\";\n\n/** Grace period between SIGTERM and SIGKILL. */\nexport const DEFAULT_KILL_GRACE_MS = 5000;\n\n/** How long to wait for the kernel to reap a SIGKILLed group. */\nconst SIGKILL_WAIT_MS = 2000;\n\nconst isWindows = process.platform === \"win32\";\n\n/**\n * The last part of a process's output, kept in memory.\n *\n * Bounded by bytes rather than lines: a dev server that prints one enormous\n * line is no reason to hold on to all of it, and the tail exists to explain a\n * failure, not to be a log.\n */\nexport class OutputTail {\n private chunks: string[] = [];\n private size = 0;\n\n constructor(private readonly maxBytes = 64 * 1024) {}\n\n push(chunk: string): void {\n this.chunks.push(chunk);\n this.size += chunk.length;\n\n while (this.size > this.maxBytes && this.chunks.length > 1) {\n this.size -= this.chunks.shift()?.length ?? 0;\n }\n }\n\n /** The last `maxLines` non-empty lines. */\n lines(maxLines = 30): string[] {\n return this.chunks\n .join(\"\")\n .split(/\\r?\\n/)\n .filter((line) => line.trim() !== \"\")\n .slice(-maxLines);\n }\n}\n\nexport type ProcessExit = {\n code: number | null;\n signal: NodeJS.Signals | null;\n};\n\nexport type ServerProcess = {\n readonly pid: number | undefined;\n /** Settles once the direct child has exited. Never rejects. */\n readonly exited: Promise<ProcessExit>;\n /** The exit, once there is one. */\n readonly exit: ProcessExit | undefined;\n readonly output: OutputTail;\n /** Stop the whole process tree. Safe to call repeatedly. */\n kill(graceMs?: number): Promise<void>;\n};\n\nexport type SpawnServerOptions = {\n cwd: string;\n env?: Record<string, string>;\n /** Called with every chunk of output as it arrives. */\n onOutput?: (chunk: string) => void;\n};\n\n/**\n * Process groups this process started and has not stopped yet.\n *\n * Exists for the one exit no `close()` covers: the process leaving without\n * shutting down. A server left running holds its port, and the next run would\n * silently *reuse* it — a stale build answering for the current one.\n */\nconst liveProcesses = new Set<ChildProcess>();\nlet exitHookInstalled = false;\n\nconst installExitHook = () => {\n if (exitHookInstalled) {\n return;\n }\n exitHookInstalled = true;\n\n // Synchronous by necessity: nothing asynchronous runs after `exit`. There is\n // no time for a graceful SIGTERM either, so this goes straight to SIGKILL.\n process.on(\"exit\", () => {\n for (const child of liveProcesses) {\n killTreeNow(child);\n }\n liveProcesses.clear();\n });\n};\n\nconst killTreeNow = (child: ChildProcess) => {\n if (child.pid === undefined) {\n return;\n }\n\n try {\n if (isWindows) {\n execFileSync(\"taskkill\", [\"/pid\", String(child.pid), \"/T\", \"/F\"], {\n stdio: \"ignore\",\n });\n } else {\n process.kill(-child.pid, \"SIGKILL\");\n }\n } catch {\n // Already gone.\n }\n};\n\n/**\n * Start `command` through a shell, as the leader of its own process group.\n *\n * A group, because the command is rarely the server itself: `pnpm storybook`\n * is pnpm, running a shell, running storybook, running workers. Killing only\n * the direct child would leave the rest holding the port.\n *\n * Output is buffered, never written anywhere unless `onOutput` asks for it —\n * `cappa capture --json` must stay a single clean document on stdout.\n */\nexport function spawnServerProcess(\n command: string,\n options: SpawnServerOptions,\n): ServerProcess {\n const child = spawn(command, {\n cwd: options.cwd,\n env: { ...process.env, ...options.env },\n shell: true,\n // On POSIX this makes the child a process-group leader. On Windows it\n // would open a console window instead, and `taskkill /T` walks the tree\n // without needing a group.\n detached: !isWindows,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n windowsHide: true,\n });\n\n const output = new OutputTail();\n const onData = (data: Buffer) => {\n const chunk = data.toString();\n output.push(chunk);\n options.onOutput?.(chunk);\n };\n child.stdout?.on(\"data\", onData);\n child.stderr?.on(\"data\", onData);\n\n liveProcesses.add(child);\n installExitHook();\n\n let exit: ProcessExit | undefined;\n const exited = new Promise<ProcessExit>((resolve) => {\n const settle = (value: ProcessExit) => {\n if (exit) {\n return;\n }\n exit = value;\n resolve(value);\n };\n\n child.once(\"exit\", (code, signal) => settle({ code, signal }));\n child.once(\"error\", (error) => {\n output.push(`${error.message}\\n`);\n settle({ code: null, signal: null });\n });\n });\n\n let killing: Promise<void> | undefined;\n\n return {\n get pid() {\n return child.pid;\n },\n exited,\n get exit() {\n return exit;\n },\n output,\n kill(graceMs = DEFAULT_KILL_GRACE_MS) {\n killing ??= killProcessTree(child, exited, graceMs).finally(() => {\n liveProcesses.delete(child);\n });\n return killing;\n },\n };\n}\n\n/** True while any process in the group led by `pid` is alive. */\nconst groupAlive = (pid: number): boolean => {\n try {\n process.kill(-pid, 0);\n return true;\n } catch (error) {\n // EPERM means it exists but is not ours to signal — still alive.\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n};\n\nconst delay = (ms: number) =>\n new Promise<void>((resolve) => {\n setTimeout(resolve, ms);\n });\n\n/**\n * SIGTERM the whole group, then SIGKILL whatever is left after `graceMs`.\n *\n * Waits on the group, not the child: the shell can exit at once while the\n * server it started is still shutting down — and still holding the port.\n */\nasync function killProcessTree(\n child: ChildProcess,\n exited: Promise<ProcessExit>,\n graceMs: number,\n): Promise<void> {\n const pid = child.pid;\n if (pid === undefined) {\n return;\n }\n\n if (isWindows) {\n // `/F` is the only reliable option: console apps ignore a polite taskkill.\n await new Promise<void>((resolve) => {\n execFile(\"taskkill\", [\"/pid\", String(pid), \"/T\", \"/F\"], () => resolve());\n });\n await exited;\n return;\n }\n\n if (!groupAlive(pid)) {\n return;\n }\n\n try {\n process.kill(-pid, \"SIGTERM\");\n } catch {\n return;\n }\n\n const deadline = Date.now() + graceMs;\n while (groupAlive(pid) && Date.now() < deadline) {\n await delay(50);\n }\n\n if (groupAlive(pid)) {\n try {\n process.kill(-pid, \"SIGKILL\");\n } catch {\n // Gone in the meantime.\n }\n\n // `kill` only queues the signal, and the shell that led the group has\n // usually exited on the SIGTERM already — so `exited` settled long ago and\n // says nothing about the server. Wait until the group is actually gone,\n // or the port is still held when this returns.\n const killDeadline = Date.now() + SIGKILL_WAIT_MS;\n while (groupAlive(pid) && Date.now() < killDeadline) {\n await delay(20);\n }\n }\n\n await exited;\n}\n","const PROBE_TIMEOUT_MS = 5000;\n/** Delays between probes; the last one repeats. */\nconst POLL_DELAYS_MS = [100, 250, 500, 1000];\n\n/**\n * Whether `url` answers with a 2xx or 3xx status.\n *\n * Redirects are not followed: a dev server that redirects `/` to `/login` is\n * up, and following it would make readiness depend on a page cappa never asked\n * about.\n */\nexport async function isUrlReady(\n url: string,\n timeoutMs = PROBE_TIMEOUT_MS,\n): Promise<boolean> {\n try {\n const response = await fetch(url, {\n redirect: \"manual\",\n signal: AbortSignal.timeout(Math.max(1, timeoutMs)),\n });\n // Nobody reads the body; let the socket go.\n await response.body?.cancel().catch(() => {});\n return response.status >= 200 && response.status < 400;\n } catch {\n return false;\n }\n}\n\nexport type WaitForUrlOptions = {\n timeoutMs: number;\n /** Stop waiting as soon as this settles — the server process exited. */\n abort?: Promise<unknown>;\n /** Injectable for tests. */\n probe?: (url: string, timeoutMs: number) => Promise<boolean>;\n};\n\nexport type WaitForUrlResult = \"ready\" | \"timeout\" | \"aborted\";\n\n/** Poll `url` until it is ready, the deadline passes, or `abort` settles. */\nexport async function waitForUrl(\n url: string,\n options: WaitForUrlOptions,\n): Promise<WaitForUrlResult> {\n const probe = options.probe ?? isUrlReady;\n const deadline = Date.now() + options.timeoutMs;\n\n let aborted = false;\n const abort = (options.abort ?? new Promise<never>(() => {})).then(\n () => {\n aborted = true;\n },\n () => {\n aborted = true;\n },\n );\n\n for (let attempt = 0; ; attempt++) {\n const remaining = deadline - Date.now();\n if (aborted) {\n return \"aborted\";\n }\n if (remaining <= 0) {\n return \"timeout\";\n }\n\n if (await probe(url, Math.min(remaining, PROBE_TIMEOUT_MS))) {\n return \"ready\";\n }\n\n const wait = Math.min(\n POLL_DELAYS_MS[Math.min(attempt, POLL_DELAYS_MS.length - 1)] ?? 1000,\n Math.max(0, deadline - Date.now()),\n );\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n new Promise<void>((resolve) => {\n timer = setTimeout(resolve, wait);\n }),\n abort,\n ]);\n clearTimeout(timer);\n }\n}\n","import type { WebServerConfig } from \"../types\";\nimport {\n type ProcessExit,\n type ServerProcess,\n type SpawnServerOptions,\n spawnServerProcess,\n} from \"./process\";\nimport { isUrlReady, waitForUrl } from \"./readiness\";\nimport { NO_WEB_SERVER_HINT, sameServer } from \"./unreachable\";\n\n/** A `webServer` entry with every default applied. */\nexport type ResolvedWebServerConfig = Required<WebServerConfig>;\n\nexport type WebServerLogLevel = \"debug\" | \"info\" | \"warn\" | \"error\" | \"success\";\n\nexport type WebServerLog = (level: WebServerLogLevel, message: string) => void;\n\nexport type WebServerPoolOptions = {\n servers: ResolvedWebServerConfig[];\n /** Where lifecycle messages go when `ensure` is not handed a log. */\n log?: WebServerLog;\n /** Live output, for `--log-level 4`. Output is buffered either way. */\n onOutput?: (server: ResolvedWebServerConfig, chunk: string) => void;\n /** Overrides process spawning. Tests use this. */\n spawn?: (command: string, options: SpawnServerOptions) => ServerProcess;\n /** Overrides the readiness probe. Tests use this. */\n probe?: (url: string, timeoutMs: number) => Promise<boolean>;\n /** Grace period between SIGTERM and SIGKILL. @default 5000 */\n killGraceMs?: number;\n};\n\n/** A web server could not be started, or would not become ready. */\nexport class WebServerError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"WebServerError\";\n }\n}\n\ntype EntryState =\n | { kind: \"idle\" }\n /** Something else was already answering at `url`. Never stopped by cappa. */\n | { kind: \"reused\" }\n | { kind: \"running\"; process: ServerProcess }\n /** Exited on its own after it was ready. Started again on the next run. */\n | { kind: \"exited\"; exit: ProcessExit; tail: string[] };\n\ntype Entry = {\n config: ResolvedWebServerConfig;\n state: EntryState;\n starting: Promise<void> | null;\n};\n\nconst describeExit = (exit: ProcessExit): string =>\n exit.signal\n ? `signal ${exit.signal}`\n : exit.code === null\n ? \"an error\"\n : `code ${exit.code}`;\n\nconst formatTail = (command: string, lines: string[]): string =>\n lines.length === 0\n ? `\\`${command}\\` printed nothing.`\n : `Last output of \\`${command}\\`:\\n${lines.map((line) => ` ${line}`).join(\"\\n\")}`;\n\nconst seconds = (ms: number) => `${Math.round(ms / 100) / 10}s`;\n\n/**\n * The servers a config's `webServer` describes, started on demand.\n *\n * Lazy and restartable rather than started once: the owning engine calls\n * `ensure` before every run and `stop` when the browser goes idle, so a review\n * session that sits unused gives the port back, and the next capture starts —\n * and rebuilds — the app again, picking up whatever changed in between.\n *\n * Every `ensure` says which way it went, because \"reusing a server\" and\n * \"started one\" look identical in screenshots, and a stale build, another\n * branch or another project on the same port is otherwise very hard to spot.\n */\nexport class WebServerPool {\n private readonly entries: Entry[];\n private readonly options: WebServerPoolOptions;\n private readonly probe: (url: string, timeoutMs: number) => Promise<boolean>;\n /** Bumped by `stop`, so a start in flight knows it was cancelled. */\n private generation = 0;\n\n constructor(options: WebServerPoolOptions) {\n this.options = options;\n this.probe = options.probe ?? isUrlReady;\n this.entries = options.servers.map((config) => ({\n config,\n state: { kind: \"idle\" },\n starting: null,\n }));\n }\n\n /** Whether the config has any `webServer` entry at all. */\n get configured(): boolean {\n return this.entries.length > 0;\n }\n\n /** Number of processes cappa started that are still running. */\n get running(): number {\n return this.entries.filter(\n (entry) => entry.state.kind === \"running\" && !entry.state.process.exit,\n ).length;\n }\n\n /**\n * Make every server ready, in parallel, starting the ones that are not.\n *\n * All of them, even for a run that only captures one plugin's tasks: nothing\n * maps a plugin to a server, and guessing would start the wrong one.\n */\n async ensure(log: WebServerLog = this.defaultLog): Promise<void> {\n if (this.entries.length === 0) {\n return;\n }\n\n const results = await Promise.allSettled(\n this.entries.map((entry) => this.ensureEntry(entry, log)),\n );\n\n const errors = results.flatMap((result) =>\n result.status === \"rejected\" ? [result.reason] : [],\n );\n\n if (errors.length === 1) {\n throw errors[0];\n }\n if (errors.length > 1) {\n throw new WebServerError(\n errors\n .map((error) => (error instanceof Error ? error.message : error))\n .join(\"\\n\\n\"),\n );\n }\n }\n\n /**\n * Stop every server cappa started. A reused server is left alone — cappa did\n * not start it, so it is not cappa's to stop.\n */\n async stop(): Promise<void> {\n this.generation += 1;\n\n await Promise.all(\n this.entries.map(async (entry) => {\n const state = entry.state;\n // Before the kill, so the exit watcher sees a deliberate stop rather\n // than a crash.\n entry.state = { kind: \"idle\" };\n\n if (state.kind === \"running\") {\n await state.process.kill(this.options.killGraceMs);\n }\n }),\n );\n }\n\n /**\n * What to tell the user about a connection refused at `origin`.\n *\n * Always an actionable sentence: the bare \"ECONNREFUSED\" it replaces is the\n * single most common capture failure, and says nothing about what to do.\n */\n explainUnreachable(origin?: string): string {\n if (this.entries.length === 0) {\n return NO_WEB_SERVER_HINT;\n }\n\n const matching = origin\n ? this.entries.find((entry) => sameServer(entry.config.url, origin))\n : undefined;\n\n const crashed =\n matching?.state.kind === \"exited\"\n ? matching\n : this.entries.find((entry) => entry.state.kind === \"exited\");\n\n if (crashed && crashed.state.kind === \"exited\") {\n return `The web server \\`${crashed.config.command}\\` exited with ${describeExit(crashed.state.exit)} during the run; it is started again on the next run.\\n${formatTail(crashed.config.command, crashed.state.tail)}`;\n }\n\n if (origin && !matching) {\n const urls = this.entries.map((entry) => entry.config.url).join(\", \");\n return `No \\`webServer\\` entry serves ${origin} (configured: ${urls}). Check that the plugin's URL matches \\`webServer.url\\`.`;\n }\n\n return \"The configured `webServer` was ready, but stopped accepting connections.\";\n }\n\n private readonly defaultLog: WebServerLog = (level, message) => {\n this.options.log?.(level, message);\n };\n\n private ensureEntry(entry: Entry, log: WebServerLog): Promise<void> {\n // Two callers asking at once — discovery from the UI and a run, say — share\n // one start rather than spawning the command twice.\n entry.starting ??= this.startEntry(entry, log).finally(() => {\n entry.starting = null;\n });\n return entry.starting;\n }\n\n private async startEntry(entry: Entry, log: WebServerLog): Promise<void> {\n const { command, url, timeout, cwd, env, reuseExistingServer } =\n entry.config;\n const previous = entry.state;\n\n if (previous.kind === \"running\" && !previous.process.exit) {\n log(\"info\", `Using \\`${command}\\` at ${url}, started earlier by cappa`);\n return;\n }\n\n if (previous.kind === \"exited\") {\n log(\n \"warn\",\n `\\`${command}\\` exited with ${describeExit(previous.exit)} after the last run; starting it again`,\n );\n }\n\n if (await this.probe(url, Math.min(timeout, 5000))) {\n if (reuseExistingServer) {\n entry.state = { kind: \"reused\" };\n log(\"info\", `Reusing server at ${url} — \\`${command}\\` was not run`);\n return;\n }\n\n throw new WebServerError(\n `${url} is already in use, and \\`webServer.reuseExistingServer\\` is false. Stop whatever is serving it, or allow reusing it.`,\n );\n }\n\n const generation = this.generation;\n const startedAt = Date.now();\n\n log(\n \"info\",\n `Starting \\`${command}\\` — waiting up to ${seconds(timeout)} for ${url}`,\n );\n\n const child = (this.options.spawn ?? spawnServerProcess)(command, {\n cwd,\n env,\n onOutput: this.options.onOutput\n ? (chunk) => this.options.onOutput?.(entry.config, chunk)\n : undefined,\n });\n\n // Recorded before it is ready, so a `stop` during start-up kills it too.\n entry.state = { kind: \"running\", process: child };\n\n const result = await waitForUrl(url, {\n timeoutMs: timeout,\n abort: child.exited,\n probe: this.probe,\n });\n\n if (generation !== this.generation) {\n await child.kill(this.options.killGraceMs);\n throw new WebServerError(\n `\\`${command}\\` was stopped before ${url} was ready.`,\n );\n }\n\n if (result === \"ready\") {\n this.watchForCrash(entry, child);\n log(\n \"success\",\n `Started \\`${command}\\` — ${url} ready in ${seconds(Date.now() - startedAt)}`,\n );\n return;\n }\n\n entry.state = { kind: \"idle\" };\n\n if (result === \"aborted\") {\n const exit = await child.exited;\n throw new WebServerError(\n `\\`${command}\\` exited with ${describeExit(exit)} before ${url} was ready.\\n${formatTail(command, child.output.lines())}`,\n );\n }\n\n await child.kill(this.options.killGraceMs);\n throw new WebServerError(\n `Timed out after ${seconds(timeout)} waiting for \\`${command}\\` to serve ${url}. If it needs longer — a build step, say — raise \\`webServer.timeout\\`.\\n${formatTail(command, child.output.lines())}`,\n );\n }\n\n /**\n * Record a server that exits on its own, so the failures it causes can say\n * why and the next run starts it again. Deliberately no restart loop: a\n * server that keeps crashing should fail loudly, not flap.\n */\n private watchForCrash(entry: Entry, child: ServerProcess): void {\n void child.exited.then((exit) => {\n const state = entry.state;\n if (state.kind !== \"running\" || state.process !== child) {\n // Stopped on purpose.\n return;\n }\n\n entry.state = { kind: \"exited\", exit, tail: child.output.lines() };\n // The process group may outlive the shell that led it.\n void child.kill(this.options.killGraceMs);\n this.defaultLog(\n \"error\",\n `\\`${entry.config.command}\\` exited with ${describeExit(exit)} while cappa was using it.`,\n );\n });\n }\n}\n","import type { CaptureRunner } from \"../runner/CaptureRunner\";\nimport type { RunDetail, RunEvent, RunSummary } from \"../runner/types\";\n\nexport type RunStoreOptions = {\n /**\n * Events buffered per run, for replay to a (re)connecting subscriber.\n * @default 5000\n */\n maxEventsPerRun?: number;\n /**\n * Finished runs kept in memory. Oldest are dropped first.\n * @default 20\n */\n maxRuns?: number;\n};\n\ntype RunEntry = {\n id: string;\n runner: CaptureRunner;\n events: RunEvent[];\n /** Events dropped off the front of the buffer, so replay gaps are detectable. */\n dropped: number;\n listeners: Set<(event: RunEvent) => void>;\n /** Frozen once the run finishes, so detail survives after the runner is gone. */\n finalDetail?: RunDetail;\n};\n\n/**\n * In-memory registry of capture runs and their event history.\n *\n * The event buffer is what lets an SSE client reconnect without losing\n * anything: subscribers replay from the last `seq` they saw before live\n * delivery starts.\n */\nexport class RunStore {\n private readonly maxEventsPerRun: number;\n private readonly maxRuns: number;\n private readonly runs = new Map<string, RunEntry>();\n /** Insertion order, oldest first — the eviction queue. */\n private readonly order: string[] = [];\n\n constructor(options: RunStoreOptions = {}) {\n this.maxEventsPerRun = options.maxEventsPerRun ?? 5000;\n this.maxRuns = options.maxRuns ?? 20;\n }\n\n /** Register a runner and start buffering its events. */\n add(runner: CaptureRunner): void {\n const entry: RunEntry = {\n id: runner.id,\n runner,\n events: [],\n dropped: 0,\n listeners: new Set(),\n };\n\n this.runs.set(runner.id, entry);\n this.order.push(runner.id);\n this.evictOldRuns();\n\n runner.on((event) => {\n entry.events.push(event);\n if (entry.events.length > this.maxEventsPerRun) {\n entry.dropped += entry.events.length - this.maxEventsPerRun;\n entry.events.splice(0, entry.events.length - this.maxEventsPerRun);\n }\n\n for (const listener of entry.listeners) {\n try {\n listener(event);\n } catch {\n // A failing subscriber must not disturb the run or other subscribers.\n }\n }\n });\n }\n\n /**\n * Freeze the final detail of a finished run so it stays queryable after the\n * runner is discarded.\n */\n finalize(runId: string): void {\n const entry = this.runs.get(runId);\n if (entry) {\n entry.finalDetail = entry.runner.getDetail();\n }\n }\n\n get(runId: string): RunDetail | undefined {\n const entry = this.runs.get(runId);\n if (!entry) {\n return undefined;\n }\n\n return entry.finalDetail ?? entry.runner.getDetail();\n }\n\n getRunner(runId: string): CaptureRunner | undefined {\n return this.runs.get(runId)?.runner;\n }\n\n /** Newest first. */\n list(): RunSummary[] {\n return [...this.order]\n .reverse()\n .map((id) => {\n const entry = this.runs.get(id);\n if (!entry) {\n return undefined;\n }\n return entry.finalDetail ?? entry.runner.getSummary();\n })\n .filter((summary): summary is RunSummary => summary !== undefined);\n }\n\n /**\n * Subscribe to a run, replaying buffered events first.\n *\n * Replay is synchronous, so a subscriber cannot miss events that arrive\n * between the buffer read and the listener being registered.\n */\n subscribe(\n runId: string,\n onEvent: (event: RunEvent) => void,\n options: { sinceSeq?: number } = {},\n ): () => void {\n const entry = this.runs.get(runId);\n if (!entry) {\n return () => {};\n }\n\n const sinceSeq = options.sinceSeq ?? 0;\n for (const event of entry.events) {\n if (event.seq > sinceSeq) {\n onEvent(event);\n }\n }\n\n entry.listeners.add(onEvent);\n return () => {\n entry.listeners.delete(onEvent);\n };\n }\n\n /** How many events were dropped from a run's buffer (0 when none were). */\n droppedEvents(runId: string): number {\n return this.runs.get(runId)?.dropped ?? 0;\n }\n\n private evictOldRuns(): void {\n while (this.order.length > this.maxRuns) {\n const oldest = this.order.shift();\n if (oldest !== undefined) {\n this.runs.delete(oldest);\n }\n }\n }\n}\n","import type {\n RunDetail,\n RunEvent,\n RunSummary,\n StartRunRequest,\n Target,\n} from \"../runner/types\";\nimport type { Screenshot } from \"../types\";\n\nexport type PluginInfo = {\n name: string;\n description?: string;\n};\n\nexport type ScreenshotQuery = {\n search?: string;\n category?: Screenshot[\"category\"];\n};\n\nexport type ApproveResult = {\n approved: string[];\n errors: { name: string; error: string }[];\n};\n\nexport type ListTargetsOptions = {\n /** Re-run plugin discovery instead of serving the cached target list. */\n refresh?: boolean;\n};\n\nexport type SubscribeOptions = {\n /**\n * Replay buffered events with `seq > sinceSeq` before streaming live ones.\n * This is what makes a dropped SSE connection invisible to the client.\n */\n sinceSeq?: number;\n};\n\n/**\n * How a watch iteration decided what to capture.\n *\n * - `tasks` — an explicit set of task ids, resolved by the plugins.\n * - `plugins` — every task of one or more plugins, because at least one could\n * not attribute the change (or ships no `watch` at all).\n * - `all` — everything under the session's filter: the resolved set was larger\n * than the cap, or discovery itself failed.\n * - `none` — nothing to capture.\n */\nexport type WatchScope = \"tasks\" | \"plugins\" | \"all\" | \"none\";\n\n/** What one settled batch of file changes led to. */\nexport type WatchChange = {\n /** Changed files, relative to the watch root. */\n files: string[];\n scope: WatchScope;\n /** Resolved task ids, when the scope is `tasks`. */\n taskIds?: string[];\n /** The run the change started, absent when none could be started. */\n runId?: string;\n /** Why no run was started, when that is what happened. */\n error?: string;\n at: number;\n};\n\ntype WatchEventBase = {\n /** Monotonic, 1-based, per engine. Used for replay, like run events. */\n seq: number;\n at: number;\n};\n\n/**\n * The watch event stream.\n *\n * Separate from `RunEvent` because these events belong to a session that\n * outlives any single run — a watch session is a scheduler for runs, and the\n * runs it starts report themselves through the ordinary run stream.\n */\nexport type WatchEvent =\n | (WatchEventBase & {\n type: \"watch:start\";\n paths: string[];\n filter?: string;\n debounceMs: number;\n })\n | (WatchEventBase & { type: \"watch:change\" } & Omit<WatchChange, \"at\">)\n | (WatchEventBase & {\n type: \"watch:stop\";\n reason: \"requested\" | \"engine-closed\";\n });\n\nexport type WatchEventType = WatchEvent[\"type\"];\n\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown\n ? Omit<T, K>\n : never;\n\n/** A watch event before the engine stamps it with `seq` and `at`. */\nexport type EmittableWatchEvent = DistributiveOmit<WatchEvent, \"seq\" | \"at\">;\n\n/** What a watch session is doing, readable at any time. */\nexport type WatchStatus = {\n active: boolean;\n /** Roots being watched, relative to the working directory. */\n paths: string[];\n filter?: string;\n debounceMs: number;\n startedAt?: number;\n /** The most recent settled batch of changes, when there has been one. */\n lastChange?: WatchChange;\n};\n\n/** Options for `startWatch`. */\nexport type StartWatchRequest = {\n /**\n * Directories to watch, relative to the working directory.\n * @default [\".\"]\n */\n paths?: string[];\n /** Glob every watch-triggered run is restricted to (`path.matchesGlob`). */\n filter?: string;\n /**\n * How long changes must settle before a run starts.\n * @default 300\n */\n debounceMs?: number;\n /**\n * Above this many resolved task ids, capture everything under `filter`\n * instead. A branch switch is what this guards against.\n * @default 200\n */\n maxTasks?: number;\n};\n\n/**\n * Everything a UI needs to drive and observe captures.\n *\n * There are two implementations: `LocalEngine` runs the browser in-process, and\n * (later) a remote engine speaks HTTP + SSE to a server that does. The UI only\n * ever holds this interface, so moving the browser to another machine is a\n * different implementation rather than a rewrite.\n *\n * That is only true if the interface stays serializable: **no `Page`, `Browser`,\n * or plugin object may cross it** — arguments and return values must survive a\n * JSON round-trip. Plugins are live closures from `cappa.config.ts` and cannot\n * be sent anywhere; whichever process holds the engine is the one that loaded\n * the config.\n */\nexport interface CaptureEngine {\n /** Plugins this engine can run. */\n listPlugins(): Promise<PluginInfo[]>;\n\n /** Discovered, runnable tasks. Cached until `refresh` is requested. */\n listTargets(options?: ListTargetsOptions): Promise<Target[]>;\n\n /**\n * Start a capture. Resolves as soon as the run is registered — progress\n * arrives through `subscribeRun`.\n *\n * @throws {RunInProgressError} when a run is already active.\n */\n startRun(request?: StartRunRequest): Promise<RunSummary>;\n\n getRun(id: string): Promise<RunDetail | undefined>;\n\n /** Newest first. */\n listRuns(): Promise<RunSummary[]>;\n\n cancelRun(id: string): Promise<void>;\n\n /**\n * Observe a run. Returns an unsubscribe function.\n *\n * Buffered events are replayed synchronously before live delivery begins, so\n * a subscriber that attaches after `startRun` still sees the whole run.\n */\n subscribeRun(\n id: string,\n onEvent: (event: RunEvent) => void,\n options?: SubscribeOptions,\n ): () => void;\n\n listScreenshots(query?: ScreenshotQuery): Promise<Screenshot[]>;\n\n approve(names: string[]): Promise<ApproveResult>;\n\n /**\n * Re-capture on file change until `stopWatch`.\n *\n * Optional, because only an engine that can see the files is able to do it:\n * a remote engine drives the watcher on the *host*, and an engine with no\n * local filesystem at all has nothing to offer. Callers must feature-detect\n * rather than assume.\n *\n * @throws {WatchInProgressError} when a session is already active.\n */\n startWatch?(request?: StartWatchRequest): Promise<WatchStatus>;\n\n /**\n * Stop the active watch session and answer the status it left behind.\n *\n * A no-op when there is none — the status simply says it is inactive.\n */\n stopWatch?(): Promise<WatchStatus>;\n\n /** What the watch session is doing, or an inactive status when there is none. */\n getWatchStatus?(): Promise<WatchStatus>;\n\n /**\n * Observe the watch event stream. Returns an unsubscribe function.\n *\n * Buffered events are replayed synchronously before live delivery, exactly\n * as `subscribeRun` does.\n */\n subscribeWatch?(\n onEvent: (event: WatchEvent) => void,\n options?: SubscribeOptions,\n ): () => void;\n\n /** Release resources (browser, timers). Safe to call more than once. */\n close(): Promise<void>;\n}\n\n/**\n * Stable discriminators for engine errors.\n *\n * These exist because `instanceof` is not reliable across the package\n * boundary. `@cappa/core` ships dual ESM/CJS builds, so a CJS consumer (the\n * CLI binary) and an ESM one (the server) each load their own copy of these\n * classes: an error thrown by one is not an `instanceof` the other's class,\n * and the check silently fails — turning a 409 into a 500. Callers must use\n * the guards below rather than `instanceof`.\n */\nexport const ENGINE_ERROR_CODES = {\n runInProgress: \"CAPPA_RUN_IN_PROGRESS\",\n unknownTargets: \"CAPPA_UNKNOWN_TARGETS\",\n watchInProgress: \"CAPPA_WATCH_IN_PROGRESS\",\n} as const;\n\n/** Thrown by `startRun` when the engine is already running something. */\nexport class RunInProgressError extends Error {\n readonly code = ENGINE_ERROR_CODES.runInProgress;\n readonly activeRunId: string;\n\n constructor(activeRunId: string) {\n super(`A capture run is already in progress (${activeRunId})`);\n this.name = \"RunInProgressError\";\n this.activeRunId = activeRunId;\n }\n}\n\n/** Thrown by `startRun` when `taskIds` names tasks that were never discovered. */\nexport class UnknownTargetsError extends Error {\n readonly code = ENGINE_ERROR_CODES.unknownTargets;\n readonly taskIds: string[];\n\n constructor(taskIds: string[]) {\n super(`Unknown task ids: ${taskIds.join(\", \")}`);\n this.name = \"UnknownTargetsError\";\n this.taskIds = taskIds;\n }\n}\n\n/** Thrown by `startWatch` when a watch session is already running. */\nexport class WatchInProgressError extends Error {\n readonly code = ENGINE_ERROR_CODES.watchInProgress;\n\n constructor() {\n super(\"A watch session is already running\");\n this.name = \"WatchInProgressError\";\n }\n}\n\nconst hasCode = (error: unknown, code: string): boolean =>\n error instanceof Error && (error as { code?: unknown }).code === code;\n\n/**\n * Identity-independent check for `RunInProgressError`.\n *\n * Prefer this over `instanceof` — see `ENGINE_ERROR_CODES`.\n */\nexport const isRunInProgressError = (\n error: unknown,\n): error is RunInProgressError =>\n hasCode(error, ENGINE_ERROR_CODES.runInProgress);\n\n/** Identity-independent check for `UnknownTargetsError`. */\nexport const isUnknownTargetsError = (\n error: unknown,\n): error is UnknownTargetsError =>\n hasCode(error, ENGINE_ERROR_CODES.unknownTargets);\n\n/** Identity-independent check for `WatchInProgressError`. */\nexport const isWatchInProgressError = (\n error: unknown,\n): error is WatchInProgressError =>\n hasCode(error, ENGINE_ERROR_CODES.watchInProgress);\n","import type ScreenshotTool from \"../screenshot\";\n\nexport type WarmBrowserOptions = {\n /** Builds an un-initialised `ScreenshotTool`. Called once per cold start. */\n create: () => ScreenshotTool;\n /**\n * How long the browser may sit unused before it is shut down.\n * `0` disables warm reuse entirely (close immediately after each release).\n * @default 300_000 (5 minutes)\n */\n idleTimeoutMs?: number;\n /**\n * Called whenever the browser shuts down — idle eviction and `close()`\n * alike. Whatever only makes sense while a browser is warm (the app under\n * test, started for it) goes down with it.\n */\n onShutdown?: () => Promise<void>;\n};\n\n/**\n * Keeps a Playwright browser alive between capture runs.\n *\n * Interactively, a cold Chromium start on every \"Capture\" click is the\n * difference between a snappy tool and a sluggish one — but a browser left\n * running forever is a memory leak, so it is evicted after an idle period.\n *\n * Contexts are recycled on every acquire after the first, because a warm\n * browser's pages carry cookies, storage and scroll position from the previous\n * run and a screenshot taken against leaked state is not the screenshot the CLI\n * would have taken.\n */\nexport class WarmBrowser {\n private readonly createTool: () => ScreenshotTool;\n private readonly idleTimeoutMs: number;\n private readonly onShutdown: (() => Promise<void>) | undefined;\n\n private tool: ScreenshotTool | null = null;\n private idleTimer: ReturnType<typeof setTimeout> | null = null;\n private inUse = false;\n private closed = false;\n /** Outstanding `hold()` leases. While any is held, eviction is suspended. */\n private holds = 0;\n /** Serializes acquire/close so concurrent callers cannot race the browser. */\n private pending: Promise<unknown> = Promise.resolve();\n\n constructor(options: WarmBrowserOptions) {\n this.createTool = options.create;\n this.idleTimeoutMs = options.idleTimeoutMs ?? 300_000;\n this.onShutdown = options.onShutdown;\n }\n\n /** True while a browser process is alive. */\n get isWarm(): boolean {\n return this.tool !== null;\n }\n\n /**\n * Get a ready-to-use `ScreenshotTool`, starting or reusing the browser.\n * Always pair with `release()`.\n */\n async acquire(): Promise<ScreenshotTool> {\n return this.serialize(async () => {\n if (this.closed) {\n throw new Error(\"WarmBrowser has been closed\");\n }\n\n this.cancelIdleTimer();\n this.inUse = true;\n\n if (this.tool) {\n // Reused browser: give the run a clean set of contexts.\n await this.tool.recycleContexts();\n return this.tool;\n }\n\n const tool = this.createTool();\n await tool.init();\n this.tool = tool;\n return tool;\n });\n }\n\n /**\n * Hand the browser back. It stays warm until the idle timeout elapses.\n */\n release(): void {\n this.inUse = false;\n\n if (this.closed || !this.tool) {\n return;\n }\n\n // A lease outranks the idle policy in both directions, including\n // `idleTimeoutMs: 0` — the CLI's one-shot setting, which watch mode\n // otherwise turns into a cold Chromium start on every save.\n if (this.holds > 0) {\n this.cancelIdleTimer();\n return;\n }\n\n if (this.idleTimeoutMs <= 0) {\n void this.close();\n return;\n }\n\n this.startIdleTimer();\n }\n\n /**\n * Suspend idle eviction until the returned function is called.\n *\n * Held by an active watch session. Without it, `WarmBrowser` closes the\n * browser between saves during a coffee break and the next save pays full\n * start-up — which is the entire premise of watch mode, defeated by its own\n * idle handling.\n */\n hold(): () => void {\n this.holds += 1;\n this.cancelIdleTimer();\n\n let released = false;\n return () => {\n if (released) {\n return;\n }\n released = true;\n this.holds -= 1;\n\n // Back to the normal idle policy for a browser nobody is using.\n if (this.holds === 0 && !this.inUse) {\n this.release();\n }\n };\n }\n\n /** True while at least one lease suspends idle eviction. */\n get isHeld(): boolean {\n return this.holds > 0;\n }\n\n /** Shut the browser down now. Safe to call repeatedly. */\n async close(): Promise<void> {\n this.closed = true;\n this.cancelIdleTimer();\n\n await this.serialize(async () => {\n const tool = this.tool;\n this.tool = null;\n this.inUse = false;\n\n try {\n if (tool) {\n await tool.close();\n }\n } finally {\n await this.onShutdown?.();\n }\n });\n }\n\n private startIdleTimer(): void {\n this.cancelIdleTimer();\n\n const timer = setTimeout(() => {\n this.idleTimer = null;\n if (this.inUse || this.closed || this.holds > 0 || !this.tool) {\n return;\n }\n\n void this.evict();\n }, this.idleTimeoutMs);\n\n // Never let an idle browser keep the process alive.\n if (typeof (timer as { unref?: () => void }).unref === \"function\") {\n (timer as { unref: () => void }).unref();\n }\n\n this.idleTimer = timer;\n }\n\n private cancelIdleTimer(): void {\n if (this.idleTimer !== null) {\n clearTimeout(this.idleTimer);\n this.idleTimer = null;\n }\n }\n\n /** Shut the browser down but stay usable — the next acquire starts cold. */\n private async evict(): Promise<void> {\n await this.serialize(async () => {\n if (this.inUse || this.closed || this.holds > 0) {\n return;\n }\n\n const tool = this.tool;\n this.tool = null;\n\n try {\n if (tool) {\n await tool.close();\n }\n } finally {\n await this.onShutdown?.();\n }\n });\n }\n\n private serialize<T>(work: () => Promise<T>): Promise<T> {\n const next = this.pending.then(work, work);\n // Keep the chain alive even when a caller's promise rejects.\n this.pending = next.then(\n () => undefined,\n () => undefined,\n );\n return next;\n }\n}\n","import path from \"node:path\";\nimport type { PluginTask } from \"../plugin\";\nimport type {\n RunnablePlugin,\n RunSummary,\n StartRunRequest,\n} from \"../runner/types\";\nimport type {\n EmittableWatchEvent,\n WatchChange,\n WatchScope,\n WatchStatus,\n} from \"./types\";\n\n/**\n * The slice of a file watcher this session uses.\n *\n * Structural rather than chokidar's own type, so a test can drive a session\n * with a stand-in instead of real filesystem events — which are slow, ordered\n * by the OS rather than by the test, and different on every platform.\n */\nexport interface FileWatcher {\n on(\n event: \"all\",\n listener: (event: string, changedPath: string) => void,\n ): unknown;\n on(event: \"ready\", listener: () => void): unknown;\n on(event: \"error\", listener: (error: unknown) => void): unknown;\n close(): Promise<void>;\n}\n\nexport type CreateFileWatcher = (\n roots: string[],\n options: { cwd: string; ignored: (candidate: string) => boolean },\n) => FileWatcher | Promise<FileWatcher>;\n\n/**\n * Directories no watch should ever descend into.\n *\n * `outputDir` is not here because it is not a fixed name — the engine passes it\n * in. Missing it would be fatal rather than merely noisy: a capture writes PNGs\n * into it, every write is a change, and the session would trigger itself\n * forever.\n */\nexport const DEFAULT_IGNORED_DIRS = new Set([\n \".git\",\n \".cache\",\n \".next\",\n \".nuxt\",\n \".output\",\n \".parcel-cache\",\n \".svelte-kit\",\n \".turbo\",\n \".vercel\",\n \"build\",\n \"coverage\",\n \"dist\",\n \"node_modules\",\n \"storybook-static\",\n]);\n\n/** Watch-mode defaults, exported so the CLI and docs can quote one source. */\nexport const DEFAULT_DEBOUNCE_MS = 300;\nexport const DEFAULT_MAX_TASKS = 200;\n/** How long `start()` waits for the initial filesystem scan before giving up on it. */\nconst READY_TIMEOUT_MS = 10_000;\n\nexport type WatchSessionOptions = {\n plugins: RunnablePlugin[];\n /** Discovered tasks per plugin name. Called once per settled batch. */\n discover: () => Promise<Map<string, PluginTask[]>>;\n /** Start a run. Resolves as soon as the run is registered. */\n startRun: (request: StartRunRequest) => Promise<RunSummary>;\n /** Resolve when the given run reaches a terminal event. */\n waitForRun: (runId: string) => Promise<void>;\n emit?: (event: EmittableWatchEvent) => void;\n cwd?: string;\n /** Roots to watch, relative to `cwd`. @default [\".\"] */\n paths?: string[];\n /** Absolute or `cwd`-relative paths never to watch (the output directory). */\n ignoredPaths?: string[];\n filter?: string;\n debounceMs?: number;\n maxTasks?: number;\n createWatcher?: CreateFileWatcher;\n now?: () => number;\n};\n\n/** What a settled batch of changes resolved to. */\ntype WatchResolution = {\n scope: WatchScope;\n taskIds?: string[];\n request: StartRunRequest;\n};\n\n/**\n * chokidar, loaded on first use.\n *\n * Imported lazily so that requiring `@cappa/core` — which the CLI does for\n * every command, and a plugin does just to get types — never starts a file\n * watcher's dependency tree for a process that will not watch anything.\n */\nconst defaultCreateWatcher: CreateFileWatcher = async (roots, options) => {\n const { watch } = await import(\"chokidar\");\n\n return watch(roots, {\n cwd: options.cwd,\n ignoreInitial: true,\n ignored: (candidate: string) => options.ignored(candidate),\n }) as unknown as FileWatcher;\n};\n\n/**\n * Re-captures affected tasks when files change.\n *\n * A scheduler for runs, deliberately not a second orchestrator: every iteration\n * goes through the engine's ordinary `startRun`, so watch-triggered captures\n * emit the same events, land in the same run store and honour the same\n * one-run-at-a-time rule as a capture somebody clicked.\n *\n * Two behaviours matter more than they look:\n *\n * - **`clearActual` is always false.** Clearing on every save would delete the\n * diffs the user is looking at for tasks they did not touch.\n * - **Changes during a run are queued, never rejected.** The engine's single-run\n * rule stays intact, and the user gets the run they expect rather than a\n * conflict error they did not cause.\n */\nexport class WatchSession {\n private readonly options: WatchSessionOptions;\n private readonly cwd: string;\n private readonly roots: string[];\n private readonly ignoredRoots: string[];\n private readonly debounceMs: number;\n private readonly maxTasks: number;\n private readonly now: () => number;\n\n private watcher: FileWatcher | null = null;\n private readonly pending = new Set<string>();\n private timer: ReturnType<typeof setTimeout> | null = null;\n private draining = false;\n private stopped = false;\n private startedAt: number | undefined;\n private lastChange: WatchChange | undefined;\n\n constructor(options: WatchSessionOptions) {\n this.options = options;\n this.cwd = options.cwd ?? process.cwd();\n this.debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;\n this.maxTasks = options.maxTasks ?? DEFAULT_MAX_TASKS;\n this.now = options.now ?? (() => Date.now());\n\n this.roots = resolveRoots(options.paths, options.plugins);\n this.ignoredRoots = (options.ignoredPaths ?? []).map((entry) =>\n path.resolve(this.cwd, entry),\n );\n }\n\n /** Begin watching. Resolves once the initial scan has settled. */\n async start(): Promise<WatchStatus> {\n if (this.watcher) {\n return this.getStatus();\n }\n\n const create = this.options.createWatcher ?? defaultCreateWatcher;\n const watcher = await create(this.roots, {\n cwd: this.cwd,\n ignored: (candidate) => this.isIgnored(candidate),\n });\n\n // `stop()` can land while the watcher is still being built; closing it here\n // is what stops that race leaving a watcher nobody holds a handle to.\n if (this.stopped) {\n await watcher.close();\n return this.getStatus();\n }\n\n this.watcher = watcher;\n\n watcher.on(\"all\", (event, changedPath) => {\n // Directory events say nothing about what a screenshot would look like;\n // the file events inside them do.\n if (event !== \"add\" && event !== \"change\" && event !== \"unlink\") {\n return;\n }\n this.onFileChanged(changedPath);\n });\n\n // Swallowed on purpose: a watcher that reports an unreadable directory has\n // not stopped watching everything else, and taking the session down over it\n // would be worse than the noise.\n watcher.on(\"error\", () => {});\n\n await this.waitForReady(watcher);\n\n this.startedAt = this.now();\n this.emit({\n type: \"watch:start\",\n paths: this.roots,\n filter: this.options.filter,\n debounceMs: this.debounceMs,\n });\n\n return this.getStatus();\n }\n\n /**\n * Stop watching.\n *\n * Deliberately does not cancel a run already in flight: that run is the\n * answer to a save the user made, and killing it half-way leaves `actual/`\n * holding a partial capture.\n */\n async stop(\n reason: \"requested\" | \"engine-closed\" = \"requested\",\n ): Promise<void> {\n if (this.stopped) {\n return;\n }\n this.stopped = true;\n\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n this.pending.clear();\n\n const watcher = this.watcher;\n this.watcher = null;\n\n try {\n await watcher?.close();\n } finally {\n this.emit({ type: \"watch:stop\", reason });\n }\n }\n\n getStatus(): WatchStatus {\n return {\n active: this.watcher !== null && !this.stopped,\n paths: this.roots,\n filter: this.options.filter,\n debounceMs: this.debounceMs,\n startedAt: this.startedAt,\n lastChange: this.lastChange,\n };\n }\n\n private emit(event: EmittableWatchEvent): void {\n this.options.emit?.(event);\n }\n\n private async waitForReady(watcher: FileWatcher): Promise<void> {\n await new Promise<void>((resolve) => {\n let settled = false;\n const finish = () => {\n if (settled) {\n return;\n }\n settled = true;\n clearTimeout(timer);\n resolve();\n };\n\n // Bounded: a large tree can take a while to scan, but a `ready` that\n // never arrives must not leave `startWatch` hanging forever. Events flow\n // during the scan either way, so proceeding early costs nothing.\n const timer = setTimeout(finish, READY_TIMEOUT_MS);\n timer.unref?.();\n\n watcher.on(\"ready\", finish);\n watcher.on(\"error\", finish);\n });\n }\n\n private onFileChanged(changedPath: string): void {\n if (this.stopped) {\n return;\n }\n\n this.pending.add(toRelative(this.cwd, changedPath));\n\n if (this.timer) {\n clearTimeout(this.timer);\n }\n\n const timer = setTimeout(() => {\n this.timer = null;\n void this.drain();\n }, this.debounceMs);\n timer.unref?.();\n this.timer = timer;\n }\n\n /**\n * Capture for everything pending, one batch at a time.\n *\n * The loop re-reads `pending` after each iteration, which is what turns a\n * save arriving mid-run into the next iteration rather than into a `409`.\n */\n private async drain(): Promise<void> {\n if (this.draining) {\n return;\n }\n this.draining = true;\n\n try {\n while (this.pending.size > 0 && !this.stopped) {\n const files = [...this.pending].sort();\n this.pending.clear();\n await this.captureFor(files);\n }\n } finally {\n this.draining = false;\n }\n }\n\n private async captureFor(files: string[]): Promise<void> {\n const resolution = await this.resolveFiles(files);\n\n if (resolution.scope === \"none\") {\n this.record({ files, scope: \"none\", taskIds: [], at: this.now() });\n return;\n }\n\n let runId: string | undefined;\n let error: string | undefined;\n\n try {\n const summary = await this.options.startRun(resolution.request);\n runId = summary.id;\n } catch (cause) {\n // Most likely a run somebody else started — the CLI in another terminal,\n // or the review UI. Say so and wait for the next save rather than\n // retrying into the same conflict.\n error = cause instanceof Error ? cause.message : String(cause);\n }\n\n this.record({\n files,\n scope: resolution.scope,\n taskIds: resolution.taskIds,\n runId,\n error,\n at: this.now(),\n });\n\n if (runId) {\n await this.options.waitForRun(runId);\n }\n }\n\n private record(change: WatchChange): void {\n this.lastChange = change;\n const { at: _at, ...rest } = change;\n this.emit({ type: \"watch:change\", ...rest });\n }\n\n /**\n * Ask every plugin what the changed files affect, and turn the answers into\n * one run request.\n */\n private async resolveFiles(files: string[]): Promise<WatchResolution> {\n const trigger = { source: \"watch\" as const, files };\n const everything: WatchResolution = {\n scope: \"all\",\n request: {\n filter: this.options.filter,\n clearActual: false,\n trigger,\n },\n };\n\n let tasksByPlugin: Map<string, PluginTask[]>;\n try {\n tasksByPlugin = await this.options.discover();\n } catch {\n // Discovery failing — a dev server mid-restart, most likely — is not a\n // reason to capture nothing. Run everything and let the run report it.\n return everything;\n }\n\n const fullPlugins = new Set<string>();\n const taskIds = new Set<string>();\n\n for (const plugin of this.options.plugins) {\n const tasks = tasksByPlugin.get(plugin.name) ?? [];\n\n if (!plugin.watch) {\n fullPlugins.add(plugin.name);\n continue;\n }\n\n for (const file of files) {\n let resolved: string[] | null;\n try {\n resolved = plugin.watch.resolve(file, tasks);\n } catch {\n // A plugin that throws is a plugin that cannot tell.\n resolved = null;\n }\n\n if (resolved === null) {\n fullPlugins.add(plugin.name);\n break;\n }\n\n for (const id of resolved) {\n taskIds.add(id);\n }\n }\n }\n\n if (fullPlugins.size === 0) {\n if (taskIds.size === 0) {\n return { scope: \"none\", request: {} };\n }\n return this.byTaskIds([...taskIds], trigger, everything);\n }\n\n if (taskIds.size === 0) {\n return {\n scope: \"plugins\",\n request: {\n plugins: [...fullPlugins],\n filter: this.options.filter,\n clearActual: false,\n trigger,\n },\n };\n }\n\n // Mixed: some plugins named tasks, others need everything they own. A\n // request cannot express that directly — `plugins` and `taskIds` compose as\n // \"and\" — so the full plugins are expanded to the ids discovery just\n // produced. The one thing this misses is a task created since that\n // discovery, which the next iteration picks up.\n const expanded = new Set(taskIds);\n for (const name of fullPlugins) {\n for (const task of tasksByPlugin.get(name) ?? []) {\n expanded.add(task.id);\n }\n }\n\n return this.byTaskIds([...expanded], trigger, everything);\n }\n\n /**\n * A run of explicit ids, unless there are so many that naming them is\n * pointless — a branch switch or a formatter pass resolves half the project,\n * and a filtered full run is both cheaper to express and easier to read.\n */\n private byTaskIds(\n taskIds: string[],\n trigger: { source: \"watch\"; files: string[] },\n everything: WatchResolution,\n ): WatchResolution {\n if (taskIds.length > this.maxTasks) {\n return everything;\n }\n\n return {\n scope: \"tasks\",\n taskIds,\n request: {\n taskIds,\n filter: this.options.filter,\n clearActual: false,\n trigger,\n },\n };\n }\n\n private isIgnored(candidate: string): boolean {\n const absolute = path.resolve(this.cwd, candidate);\n const relative = path.relative(this.cwd, absolute);\n\n // Outside the working directory: nothing here can be attributed to a task.\n if (relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n return true;\n }\n\n for (const ignored of this.ignoredRoots) {\n if (\n absolute === ignored ||\n absolute.startsWith(`${ignored}${path.sep}`)\n ) {\n return true;\n }\n }\n\n return relative\n .split(path.sep)\n .some((segment) => DEFAULT_IGNORED_DIRS.has(segment));\n }\n}\n\n/** The part of a glob before its first magic character — the directory to watch. */\nexport const globRoot = (pattern: string): string => {\n const segments = pattern.split(\"/\");\n const staticSegments: string[] = [];\n\n for (const segment of segments) {\n if (/[*?[\\]{}!+@(]/.test(segment)) {\n break;\n }\n staticSegments.push(segment);\n }\n\n // Drop the last static segment only when it is the file itself; a pattern\n // with no magic at all is a literal path and stays as it is.\n const root = staticSegments.join(\"/\");\n return root === \"\" ? \".\" : root;\n};\n\n/**\n * What to hand the watcher.\n *\n * The project root by default, plus the roots of whatever globs the plugins\n * declared. Plugin globs can only widen the set: a plugin that maps story files\n * precisely still has to be told about the component those stories render, and\n * that component is not in its globs.\n */\nconst resolveRoots = (\n paths: string[] | undefined,\n plugins: RunnablePlugin[],\n): string[] => {\n const roots = new Set(paths && paths.length > 0 ? paths : [\".\"]);\n\n for (const plugin of plugins) {\n for (const pattern of plugin.watch?.paths ?? []) {\n roots.add(globRoot(pattern));\n }\n }\n\n // \".\" subsumes everything else.\n if (roots.has(\".\")) {\n return [\".\"];\n }\n\n return [...roots];\n};\n\nconst toRelative = (cwd: string, changedPath: string): string => {\n if (!path.isAbsolute(changedPath)) {\n return changedPath.split(path.sep).join(\"/\");\n }\n return path.relative(cwd, changedPath).split(path.sep).join(\"/\");\n};\n","import { getLogger } from \"@cappa/logger\";\nimport type { LogConsoleEvents } from \"../consoleEvents\";\nimport { ScreenshotFileSystem } from \"../filesystem\";\nimport type { PluginTask } from \"../plugin\";\nimport { CaptureRunner } from \"../runner/CaptureRunner\";\nimport type {\n RunDetail,\n RunEvent,\n RunnablePlugin,\n RunSummary,\n StartRunRequest,\n Target,\n} from \"../runner/types\";\nimport ScreenshotTool from \"../screenshot\";\nimport { collectScreenshots } from \"../screenshots/collectScreenshots\";\nimport type { DiffOptions, Screenshot, Viewport } from \"../types\";\nimport {\n type ResolvedWebServerConfig,\n WebServerPool,\n type WebServerPoolOptions,\n} from \"../webServer/WebServerPool\";\nimport { RunStore, type RunStoreOptions } from \"./RunStore\";\nimport {\n type ApproveResult,\n type CaptureEngine,\n type EmittableWatchEvent,\n type ListTargetsOptions,\n type PluginInfo,\n RunInProgressError,\n type ScreenshotQuery,\n type StartWatchRequest,\n type SubscribeOptions,\n UnknownTargetsError,\n type WatchEvent,\n WatchInProgressError,\n type WatchStatus,\n} from \"./types\";\nimport { WarmBrowser } from \"./WarmBrowser\";\nimport {\n type CreateFileWatcher,\n DEFAULT_DEBOUNCE_MS,\n WatchSession,\n} from \"./WatchSession\";\n\nexport type LocalEngineOptions = {\n outputDir: string;\n plugins: RunnablePlugin[];\n diff?: DiffOptions;\n retries?: number;\n concurrency?: number;\n logConsoleEvents?: LogConsoleEvents;\n fullPage?: boolean;\n viewport?: Viewport;\n connectionTimeout?: number;\n /**\n * How long the browser stays warm between runs.\n * @default 300_000 (5 minutes)\n */\n browserIdleTimeoutMs?: number;\n runStore?: RunStoreOptions;\n /** Overrides the screenshot tool factory. Tests use this. */\n createScreenshotTool?: () => ScreenshotTool;\n /** Working directory a watch session watches. @default process.cwd() */\n cwd?: string;\n /** Overrides the file watcher factory. Tests use this. */\n createWatcher?: CreateFileWatcher;\n /** Watch events buffered for replay to a (re)connecting subscriber. @default 200 */\n maxWatchEvents?: number;\n /**\n * The app under test, started before the first run and stopped with the\n * browser — on `close()` and when it goes idle.\n */\n webServer?: ResolvedWebServerConfig[];\n /** Overrides the web server pool's process and probe hooks. Tests use this. */\n webServerPool?: Pick<WebServerPoolOptions, \"spawn\" | \"probe\" | \"killGraceMs\">;\n};\n\nconst defaultLog: NonNullable<WebServerPoolOptions[\"log\"]> = (\n level,\n message,\n) => {\n try {\n getLogger()[level](message);\n } catch {\n // No logger initialised — an embedder that did not ask for output.\n }\n};\n\n/**\n * Stream a web server's output live at debug level. Buffered regardless: the\n * tail is what explains a server that failed to start.\n *\n * To stderr, never stdout — `capture --json` owns stdout.\n */\nconst streamOutputAtDebug = (\n server: ResolvedWebServerConfig,\n chunk: string,\n) => {\n let level = 0;\n try {\n level = getLogger().level;\n } catch {\n return;\n }\n if (level < 4) {\n return;\n }\n const prefix = `[webServer ${server.url}] `;\n process.stderr.write(\n chunk\n .split(/(?<=\\n)/)\n .map((line) => prefix + line)\n .join(\"\"),\n );\n};\n\n/**\n * `CaptureEngine` backed by an in-process Playwright browser.\n *\n * Holds the config's live plugin objects, so it must live in the process that\n * loaded `cappa.config.ts`. The server takes one of these by injection rather\n * than building it, which is what keeps `@cappa/server` free of config loading\n * and makes a remote engine a drop-in alternative.\n *\n * One run at a time. Queuing is deliberately not implemented: the browser pool\n * is the real constraint, and a second concurrent run would fight it.\n */\nexport class LocalEngine implements CaptureEngine {\n private readonly options: LocalEngineOptions;\n private readonly plugins: RunnablePlugin[];\n private readonly fileSystem: ScreenshotFileSystem;\n private readonly browser: WarmBrowser;\n private readonly runs: RunStore;\n private readonly webServers: WebServerPool;\n\n /**\n * Set synchronously the moment a run is claimed, before any `await`, so two\n * concurrent `startRun` calls cannot both pass the check and then fight over\n * the browser. Covers the window between claiming and the run finishing.\n */\n private busy = false;\n private activeRunId: string | null = null;\n private targetsCache: Target[] | null = null;\n /**\n * The tasks behind `targetsCache`, kept whole.\n *\n * A `Target` is what crosses the wire; a plugin's `watch.resolve` needs the\n * task it came from, `data` included — that is where a story's `importPath`\n * lives. Same discovery, two shapes, one cache lifetime.\n */\n private taskCache: Map<string, PluginTask[]> | null = null;\n private closed = false;\n\n private watchSession: WatchSession | null = null;\n private releaseBrowserHold: (() => void) | null = null;\n private readonly watchListeners = new Set<(event: WatchEvent) => void>();\n private watchEvents: WatchEvent[] = [];\n private watchSeq = 0;\n\n constructor(options: LocalEngineOptions) {\n this.options = options;\n this.plugins = options.plugins;\n this.fileSystem = new ScreenshotFileSystem(options.outputDir);\n this.runs = new RunStore(options.runStore);\n this.webServers = new WebServerPool({\n servers: options.webServer ?? [],\n log: defaultLog,\n onOutput: streamOutputAtDebug,\n ...options.webServerPool,\n });\n this.browser = new WarmBrowser({\n create: options.createScreenshotTool ?? (() => this.buildTool()),\n idleTimeoutMs: options.browserIdleTimeoutMs,\n // Same lifetime as the browser, idle timeout included: a review session\n // left open gives the port back, and the next run starts — and rebuilds\n // — the app again.\n onShutdown: () => this.webServers.stop(),\n });\n }\n\n private buildTool(): ScreenshotTool {\n return new ScreenshotTool({\n outputDir: this.options.outputDir,\n diff: this.options.diff,\n retries: this.options.retries,\n concurrency: this.options.concurrency,\n logConsoleEvents: this.options.logConsoleEvents,\n fullPage: this.options.fullPage ?? true,\n viewport: this.options.viewport ?? { width: 1920, height: 1080 },\n connectionTimeout: this.options.connectionTimeout,\n });\n }\n\n async listPlugins(): Promise<PluginInfo[]> {\n return this.plugins.map((plugin) => ({\n name: plugin.name,\n description: plugin.description,\n }));\n }\n\n /**\n * Discovery needs a browser (plugins query the app under test through it), so\n * this warms the browser on a cache miss.\n *\n * While a run holds the browser, only the cache can be served: discovering\n * would recycle the very contexts the run is capturing with.\n */\n async listTargets(options: ListTargetsOptions = {}): Promise<Target[]> {\n this.assertOpen();\n\n if (this.targetsCache && !options.refresh) {\n return this.targetsCache;\n }\n\n if (this.busy) {\n if (this.targetsCache) {\n return this.targetsCache;\n }\n throw new RunInProgressError(this.activeRunId ?? \"starting\");\n }\n\n return this.discoverTargets();\n }\n\n async startRun(request: StartRunRequest = {}): Promise<RunSummary> {\n this.assertOpen();\n\n if (this.busy) {\n throw new RunInProgressError(this.activeRunId ?? \"starting\");\n }\n\n // Claim before the first await — see the `busy` field comment.\n this.busy = true;\n\n try {\n await this.validateTaskIds(request);\n\n const tool = await this.browser.acquire();\n\n const runner = new CaptureRunner({\n screenshotTool: tool,\n plugins: this.plugins,\n outputDir: this.options.outputDir,\n fileSystem: this.fileSystem,\n // Inside the run rather than before it: `startRun` returns at once\n // even when a build takes a minute, and the start-up lines reach a\n // remote client as ordinary run events.\n prepare: (log) => this.webServers.ensure(log),\n explainUnreachable: (origin) =>\n this.webServers.explainUnreachable(origin),\n });\n\n const finish = () => {\n if (this.activeRunId !== runner.id) {\n return;\n }\n\n // Discovery results may be stale after a run changed what exists.\n this.targetsCache = null;\n this.taskCache = null;\n this.runs.finalize(runner.id);\n this.activeRunId = null;\n this.busy = false;\n this.browser.release();\n };\n\n // Registered *before* the run store, so cleanup completes inside the same\n // synchronous emit as the terminal event and therefore before any\n // subscriber observes it. Without this, the obvious client behaviour —\n // \"the run finished, start the next one\" — races the engine's own\n // teardown and is rejected as though a run were still in progress.\n runner.on((event) => {\n if (event.type === \"run:complete\" || event.type === \"run:error\") {\n finish();\n }\n });\n\n this.runs.add(runner);\n this.activeRunId = runner.id;\n\n // Deliberately not awaited: the caller gets the run id immediately and\n // follows progress through `subscribeRun`.\n void runner\n .run(request)\n .catch(() => {\n // The failure is already on the event stream as `run:error`, and is\n // readable via `getRun`. Swallow it so it is not an unhandled\n // rejection.\n })\n // Belt and braces: `finish` is idempotent, and this covers any terminal\n // path that somehow did not emit an event.\n .finally(finish);\n\n return runner.getSummary();\n } catch (error) {\n this.busy = false;\n this.activeRunId = null;\n throw error;\n }\n }\n\n async getRun(id: string): Promise<RunDetail | undefined> {\n return this.runs.get(id);\n }\n\n async listRuns(): Promise<RunSummary[]> {\n return this.runs.list();\n }\n\n async cancelRun(id: string): Promise<void> {\n this.runs.getRunner(id)?.abort();\n }\n\n subscribeRun(\n id: string,\n onEvent: (event: RunEvent) => void,\n options: SubscribeOptions = {},\n ): () => void {\n return this.runs.subscribe(id, onEvent, options);\n }\n\n /**\n * Read the screenshot index from disk.\n *\n * Always a fresh read rather than a cached snapshot — anything can write to\n * `outputDir` while the server is up, including a CLI run in another terminal.\n */\n async listScreenshots(query: ScreenshotQuery = {}): Promise<Screenshot[]> {\n let screenshots = await collectScreenshots(this.options.outputDir);\n\n if (query.category) {\n screenshots = screenshots.filter(\n (screenshot) => screenshot.category === query.category,\n );\n }\n\n if (query.search) {\n const term = query.search.toLowerCase();\n screenshots = screenshots.filter((screenshot) =>\n screenshot.name.toLowerCase().includes(term),\n );\n }\n\n return screenshots;\n }\n\n async approve(names: string[]): Promise<ApproveResult> {\n const screenshots = await this.listScreenshots();\n const approved: string[] = [];\n const errors: { name: string; error: string }[] = [];\n\n for (const name of names) {\n const screenshot = screenshots.find((entry) => entry.name === name);\n if (!screenshot) {\n errors.push({ name, error: \"Screenshot not found\" });\n continue;\n }\n\n try {\n await this.fileSystem.approveScreenshots(\n [screenshot],\n this.options.diff ?? { type: \"pixel\" },\n );\n approved.push(name);\n } catch (error) {\n errors.push({\n name,\n error: error instanceof Error ? error.message : \"Approval failed\",\n });\n }\n }\n\n return { approved, errors };\n }\n\n /**\n * Re-capture affected tasks on file change until `stopWatch`.\n *\n * Every iteration goes through `startRun`, so a watch-triggered capture is an\n * ordinary run: same events, same run store, same single-run rule, visible in\n * `listRuns` and in the UI. Watch is a scheduler, not a second orchestrator.\n */\n async startWatch(request: StartWatchRequest = {}): Promise<WatchStatus> {\n this.assertOpen();\n\n if (this.watchSession) {\n throw new WatchInProgressError();\n }\n\n // Held for the session's whole life: without it the idle timer closes the\n // browser between saves, and the next save pays a cold start — the exact\n // cost watch mode exists to avoid.\n const release = this.browser.hold();\n\n const session = new WatchSession({\n plugins: this.plugins,\n cwd: this.options.cwd,\n paths: request.paths,\n // Captures write into `outputDir`. Watching it would make every run\n // trigger the next one, forever.\n ignoredPaths: [this.options.outputDir],\n filter: request.filter,\n debounceMs: request.debounceMs,\n maxTasks: request.maxTasks,\n createWatcher: this.options.createWatcher,\n discover: () => this.discoverTasks(),\n startRun: (runRequest) => this.startRun(runRequest),\n waitForRun: (runId) => this.waitForRun(runId),\n emit: (event) => this.emitWatchEvent(event),\n });\n\n this.watchSession = session;\n this.releaseBrowserHold = release;\n\n try {\n return await session.start();\n } catch (error) {\n this.watchSession = null;\n this.releaseBrowserHold = null;\n release();\n throw error;\n }\n }\n\n async stopWatch(): Promise<WatchStatus> {\n await this.endWatch(\"requested\");\n return this.getWatchStatus();\n }\n\n async getWatchStatus(): Promise<WatchStatus> {\n return (\n this.watchSession?.getStatus() ?? {\n active: false,\n paths: [],\n debounceMs: DEFAULT_DEBOUNCE_MS,\n }\n );\n }\n\n subscribeWatch(\n onEvent: (event: WatchEvent) => void,\n options: SubscribeOptions = {},\n ): () => void {\n const sinceSeq = options.sinceSeq ?? 0;\n for (const event of this.watchEvents) {\n if (event.seq > sinceSeq) {\n onEvent(event);\n }\n }\n\n this.watchListeners.add(onEvent);\n return () => {\n this.watchListeners.delete(onEvent);\n };\n }\n\n async close(): Promise<void> {\n this.closed = true;\n\n await this.endWatch(\"engine-closed\");\n\n const runner = this.activeRunId\n ? this.runs.getRunner(this.activeRunId)\n : undefined;\n runner?.abort();\n\n try {\n await this.browser.close();\n } finally {\n // Also covered by the browser's shutdown hook — but a browser that never\n // started has nothing to shut down, and a server may still be starting.\n await this.webServers.stop();\n }\n }\n\n private async endWatch(reason: \"requested\" | \"engine-closed\"): Promise<void> {\n const session = this.watchSession;\n const release = this.releaseBrowserHold;\n this.watchSession = null;\n this.releaseBrowserHold = null;\n\n try {\n await session?.stop(reason);\n } finally {\n release?.();\n }\n }\n\n private emitWatchEvent(event: EmittableWatchEvent): void {\n this.watchSeq += 1;\n const full = { ...event, seq: this.watchSeq, at: Date.now() } as WatchEvent;\n\n this.watchEvents.push(full);\n const max = this.options.maxWatchEvents ?? 200;\n if (this.watchEvents.length > max) {\n this.watchEvents = this.watchEvents.slice(-max);\n }\n\n for (const listener of this.watchListeners) {\n try {\n listener(full);\n } catch {\n // A failing subscriber must not stop the watch session.\n }\n }\n }\n\n /** Resolve once a run reaches a terminal event. */\n private waitForRun(id: string): Promise<void> {\n return new Promise<void>((resolve) => {\n let unsubscribe: (() => void) | undefined;\n let finished = false;\n\n const finish = () => {\n if (finished) {\n return;\n }\n finished = true;\n unsubscribe?.();\n resolve();\n };\n\n unsubscribe = this.runs.subscribe(id, (event) => {\n if (event.type === \"run:complete\" || event.type === \"run:error\") {\n finish();\n }\n });\n\n // Buffered events replay synchronously, so a run that is already over\n // finished before `unsubscribe` existed.\n if (finished) {\n unsubscribe();\n }\n });\n }\n\n /** True while a browser process is alive. Exposed for tests and diagnostics. */\n get isWarm(): boolean {\n return this.browser.isWarm;\n }\n\n private assertOpen(): void {\n if (this.closed) {\n throw new Error(\"Engine has been closed\");\n }\n }\n\n /**\n * A client may only ask for tasks that discovery produced.\n *\n * This is a security boundary as much as a correctness one: it is what stops\n * a request from steering the browser to an arbitrary URL.\n */\n private async validateTaskIds(request: StartRunRequest): Promise<void> {\n if (!request.taskIds || request.taskIds.length === 0) {\n return;\n }\n\n // Bypasses the public `listTargets` busy guard on purpose: this runs after\n // the run is claimed but before the browser is acquired, so discovery here\n // cannot disturb an in-flight capture.\n const targets = this.targetsCache ?? (await this.discoverTargets());\n const known = new Set(targets.map((target) => target.id));\n const unknown = request.taskIds.filter((id) => !known.has(id));\n\n if (unknown.length > 0) {\n throw new UnknownTargetsError(unknown);\n }\n }\n\n /** Discovered tasks per plugin, whole. Cached with `targetsCache`. */\n private async discoverTasks(): Promise<Map<string, PluginTask[]>> {\n if (this.taskCache) {\n return this.taskCache;\n }\n\n await this.discoverTargets();\n return this.taskCache ?? new Map();\n }\n\n private async discoverTargets(): Promise<Target[]> {\n const tool = await this.browser.acquire();\n\n try {\n // Plugins discover by asking the app, so it has to be up.\n await this.webServers.ensure();\n\n const discovered = await Promise.all(\n this.plugins.map(async (plugin) => {\n const tasks = await plugin.discover(tool);\n return { plugin: plugin.name, tasks };\n }),\n );\n\n this.taskCache = new Map(\n discovered.map(({ plugin, tasks }) => [plugin, tasks]),\n );\n\n this.targetsCache = discovered.flatMap(({ plugin, tasks }) =>\n tasks.map((task) => ({\n id: task.id,\n url: task.url,\n plugin,\n })),\n );\n return this.targetsCache;\n } finally {\n this.browser.release();\n }\n }\n}\n","import path from \"node:path\";\nimport { ScreenshotFileSystem } from \"./filesystem\";\nimport type { DiffMetadata } from \"./types\";\n\n/** The three buckets a screenshot can live in. */\nexport type ScreenshotBucket = \"actual\" | \"expected\" | \"diff\";\n\n/**\n * Byte storage for screenshots, addressed by bucket + relative key\n * (`button--primary.png`, `nested/card.png`).\n *\n * `ScreenshotFileSystem` is local-disk by construction, which is correct for\n * the CLI and a local server but not for an engine running on a machine the\n * reviewer cannot reach. This interface is the seam: an object-store\n * implementation later is an implementation, not a fork.\n *\n * Only `FsScreenshotStore` exists today — nothing in the codebase depends on a\n * second implementation, and none is planned in this change.\n */\nexport interface ScreenshotStore {\n has(bucket: ScreenshotBucket, key: string): Promise<boolean>;\n read(bucket: ScreenshotBucket, key: string): Promise<Buffer>;\n write(bucket: ScreenshotBucket, key: string, data: Buffer): Promise<void>;\n /** Relative keys, recursively. */\n list(bucket: ScreenshotBucket): Promise<string[]>;\n remove(bucket: ScreenshotBucket, key: string): Promise<void>;\n /** Drop every object in a bucket. */\n clear(bucket: ScreenshotBucket): Promise<void>;\n readMeta(key: string): Promise<DiffMetadata | undefined>;\n writeMeta(key: string, meta: DiffMetadata): Promise<void>;\n}\n\n/**\n * `ScreenshotStore` over the local filesystem, delegating to\n * `ScreenshotFileSystem` so both views stay consistent.\n */\nexport class FsScreenshotStore implements ScreenshotStore {\n private readonly fs: ScreenshotFileSystem;\n\n constructor(outputDirOrFs: string | ScreenshotFileSystem) {\n this.fs =\n typeof outputDirOrFs === \"string\"\n ? new ScreenshotFileSystem(outputDirOrFs)\n : outputDirOrFs;\n }\n\n private dirFor(bucket: ScreenshotBucket): string {\n if (bucket === \"actual\") return this.fs.getActualDir();\n if (bucket === \"expected\") return this.fs.getExpectedDir();\n return this.fs.getDiffDir();\n }\n\n private pathFor(bucket: ScreenshotBucket, key: string): string {\n if (bucket === \"actual\") return this.fs.getActualFilePath(key);\n if (bucket === \"expected\") return this.fs.getExpectedFilePath(key);\n return this.fs.getDiffFilePath(key);\n }\n\n async has(bucket: ScreenshotBucket, key: string): Promise<boolean> {\n if (bucket === \"expected\") {\n return this.fs.hasExpectedFile(key);\n }\n\n const fsp = await import(\"node:fs/promises\");\n try {\n await fsp.access(this.pathFor(bucket, key));\n return true;\n } catch {\n return false;\n }\n }\n\n async read(bucket: ScreenshotBucket, key: string): Promise<Buffer> {\n if (bucket === \"expected\") {\n return this.fs.readExpectedFile(key);\n }\n\n const fsp = await import(\"node:fs/promises\");\n return fsp.readFile(this.pathFor(bucket, key));\n }\n\n async write(\n bucket: ScreenshotBucket,\n key: string,\n data: Buffer,\n ): Promise<void> {\n if (bucket === \"actual\") {\n await this.fs.writeActualFile(key, data);\n return;\n }\n if (bucket === \"diff\") {\n await this.fs.writeDiffFile(key, data);\n return;\n }\n\n const filePath = this.pathFor(bucket, key);\n await this.fs.ensureParentDir(filePath);\n const fsp = await import(\"node:fs/promises\");\n await fsp.writeFile(filePath, data);\n }\n\n async list(bucket: ScreenshotBucket): Promise<string[]> {\n const files =\n bucket === \"actual\"\n ? await this.fs.getActualScreenshots()\n : bucket === \"expected\"\n ? await this.fs.getExpectedScreenshots()\n : await this.fs.getDiffScreenshots();\n\n const dir = this.dirFor(bucket);\n return files.map((file) => path.relative(dir, file));\n }\n\n async remove(bucket: ScreenshotBucket, key: string): Promise<void> {\n const fsp = await import(\"node:fs/promises\");\n await fsp.rm(this.pathFor(bucket, key), { force: true });\n }\n\n async clear(bucket: ScreenshotBucket): Promise<void> {\n if (bucket === \"actual\") {\n this.fs.clearActual();\n return;\n }\n if (bucket === \"diff\") {\n this.fs.clearDiff();\n return;\n }\n\n throw new Error(\n \"Refusing to clear the expected/ bucket: it holds the approved baselines\",\n );\n }\n\n async readMeta(key: string): Promise<DiffMetadata | undefined> {\n const { readDiffMeta } = await import(\"./filesystem\");\n return readDiffMeta(this.fs.getDiffFilePath(key));\n }\n\n async writeMeta(key: string, meta: DiffMetadata): Promise<void> {\n await this.fs.writeDiffMetaFile(key, meta);\n }\n}\n","import path from \"node:path\";\nimport type { BoundingBox } from \"@blazediff/interpret-native\";\nimport sharp, { type OverlayOptions } from \"sharp\";\n\n/**\n * Evidence images for a judge, sized for a model's context window rather than\n * for a human's screen.\n *\n * A full-page screenshot is easily 1920x8000 — expensive to read and mostly\n * unchanged. A judge needs two things instead: where the changes are\n * (`locator.png`, a small outlined thumbnail) and what each one looks like\n * before and after (`regions.png`, tight crops side by side). Together they\n * are typically one to two orders of magnitude smaller than the full images.\n */\n\nexport type TileOptions = {\n expectedPath: string;\n actualPath: string;\n /** Diff image to outline the regions on; falls back to the actual image. */\n diffPath?: string;\n /** Regions, largest first — row order in `regions.png` follows this. */\n regions: readonly BoundingBox[];\n outDir: string;\n /** Regions rendered into `regions.png`. Default 8. */\n maxRegions?: number;\n /**\n * Minimum context kept around each region, in pixels; grows with the\n * region's size. Default 24.\n */\n padding?: number;\n /** Largest width a single crop is rendered at. Default 640. */\n maxCropWidth?: number;\n};\n\nexport type TileResult = {\n /** Absolute path, or undefined when nothing could be drawn. */\n locator?: string;\n /** Absolute path, or undefined when there were no regions. */\n regions?: string;\n /** How many regions `regions.png` holds (≤ `maxRegions`). */\n renderedRegions: number;\n};\n\nconst LOCATOR_MAX_WIDTH = 400;\nconst LOCATOR_MAX_HEIGHT = 1200;\nconst GUTTER = 12;\nconst ROW_GUTTER = 16;\nconst LABEL_HEIGHT = 18;\nconst BACKGROUND = { r: 128, g: 128, b: 128 };\n\nconst escapeXml = (text: string) =>\n text.replace(/[<>&\"]/g, (c) => `&#${c.charCodeAt(0)};`);\n\n/** A caption strip, so a row reads as \"#2 expected | #2 actual\" at a glance. */\nconst label = (text: string, width: number): Buffer =>\n Buffer.from(\n `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${width}\" height=\"${LABEL_HEIGHT}\"><rect width=\"100%\" height=\"100%\" fill=\"#222\"/><text x=\"4\" y=\"13\" font-family=\"sans-serif\" font-size=\"12\" fill=\"#fff\">${escapeXml(text)}</text></svg>`,\n );\n\nexport const padAndClamp = (\n bbox: BoundingBox,\n padding: number | { x: number; y: number },\n width: number,\n height: number,\n): BoundingBox => {\n const padX = typeof padding === \"number\" ? padding : padding.x;\n const padY = typeof padding === \"number\" ? padding : padding.y;\n const x = Math.max(0, Math.floor(bbox.x - padX));\n const y = Math.max(0, Math.floor(bbox.y - padY));\n const right = Math.min(width, Math.ceil(bbox.x + bbox.width + padX));\n const bottom = Math.min(height, Math.ceil(bbox.y + bbox.height + padY));\n return {\n x,\n y,\n width: Math.max(1, right - x),\n height: Math.max(1, bottom - y),\n };\n};\n\nconst clamp = (value: number, min: number, max: number) =>\n Math.min(max, Math.max(min, value));\n\n/**\n * Context kept around a region: proportional to its size, within bounds.\n *\n * A fixed margin is too tight for small regions — a changed letter cropped\n * with 24px around it says nothing about whether a button label got\n * truncated — and wasteful for large ones.\n */\nexport const contextPadding = (\n bbox: BoundingBox,\n minimum: number,\n): { x: number; y: number } => ({\n x: clamp(bbox.width, minimum * 2, 160),\n y: clamp(bbox.height, minimum, 96),\n});\n\n/** Scale that fits `width`x`height` into the bounds without upscaling. */\nconst fitScale = (\n width: number,\n height: number,\n maxWidth: number,\n maxHeight: number,\n) => Math.min(1, maxWidth / width, maxHeight / height);\n\nconst readSize = async (file: string) => {\n const { width, height } = await sharp(file).metadata();\n if (!width || !height) {\n throw new Error(`Unable to read image dimensions: ${file}`);\n }\n return { width, height };\n};\n\nconst renderCrop = async (\n file: string,\n box: BoundingBox,\n scale: number,\n): Promise<Buffer> => {\n const crop = sharp(file).extract({\n left: box.x,\n top: box.y,\n width: box.width,\n height: box.height,\n });\n if (scale < 1) {\n crop.resize(\n Math.max(1, Math.round(box.width * scale)),\n Math.max(1, Math.round(box.height * scale)),\n );\n }\n return crop.png().toBuffer();\n};\n\nconst renderRegions = async (\n options: TileOptions,\n width: number,\n height: number,\n): Promise<{ file: string; count: number } | undefined> => {\n const padding = options.padding ?? 24;\n const maxCropWidth = options.maxCropWidth ?? 640;\n const regions = options.regions.slice(0, options.maxRegions ?? 8);\n\n if (regions.length === 0) return undefined;\n\n const rows = await Promise.all(\n regions.map(async (region) => {\n const box = padAndClamp(\n region,\n contextPadding(region, padding),\n width,\n height,\n );\n const scale = Math.min(1, maxCropWidth / box.width);\n const [expected, actual] = await Promise.all([\n renderCrop(options.expectedPath, box, scale),\n renderCrop(options.actualPath, box, scale),\n ]);\n return {\n expected,\n actual,\n width: Math.max(1, Math.round(box.width * scale)),\n height: Math.max(1, Math.round(box.height * scale)),\n };\n }),\n );\n\n // Wide enough for the captions even when a crop is a sliver.\n const columnWidth = (row: { width: number }) => Math.max(row.width, 96);\n const canvasWidth = Math.max(\n ...rows.map((row) => columnWidth(row) * 2 + GUTTER),\n );\n const canvasHeight =\n rows.reduce((sum, row) => sum + LABEL_HEIGHT + row.height, 0) +\n ROW_GUTTER * (rows.length - 1);\n\n const composites: OverlayOptions[] = [];\n let top = 0;\n rows.forEach((row, index) => {\n const column = columnWidth(row);\n const right = column + GUTTER;\n composites.push(\n { input: label(`#${index + 1} expected`, column), left: 0, top },\n { input: label(`#${index + 1} actual`, column), left: right, top },\n { input: row.expected, left: 0, top: top + LABEL_HEIGHT },\n { input: row.actual, left: right, top: top + LABEL_HEIGHT },\n );\n top += LABEL_HEIGHT + row.height + ROW_GUTTER;\n });\n\n const file = path.join(options.outDir, \"regions.png\");\n await sharp({\n create: {\n width: canvasWidth,\n height: canvasHeight,\n channels: 3,\n background: BACKGROUND,\n },\n })\n .composite(composites)\n .png()\n .toFile(file);\n\n return { file, count: rows.length };\n};\n\nconst renderLocator = async (\n options: TileOptions,\n width: number,\n height: number,\n): Promise<string> => {\n const scale = fitScale(width, height, LOCATOR_MAX_WIDTH, LOCATOR_MAX_HEIGHT);\n const locatorWidth = Math.max(1, Math.round(width * scale));\n const locatorHeight = Math.max(1, Math.round(height * scale));\n\n // Numbered so a region in the thumbnail can be matched to its row in\n // `regions.png` and its entry in `request.json` without counting boxes.\n const shapes = options.regions\n .map((region, index) => {\n const x = Math.round(region.x * scale);\n const y = Math.round(region.y * scale);\n const w = Math.max(2, Math.round(region.width * scale));\n const h = Math.max(2, Math.round(region.height * scale));\n return `<rect x=\"${x}\" y=\"${y}\" width=\"${w}\" height=\"${h}\" fill=\"none\" stroke=\"red\" stroke-width=\"2\"/><text x=\"${x + 2}\" y=\"${Math.max(12, y - 3)}\" font-family=\"sans-serif\" font-size=\"12\" font-weight=\"bold\" fill=\"red\" stroke=\"#fff\" stroke-width=\"3\" paint-order=\"stroke\">${index + 1}</text>`;\n })\n .join(\"\");\n const svg = `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${locatorWidth}\" height=\"${locatorHeight}\">${shapes}</svg>`;\n\n const file = path.join(options.outDir, \"locator.png\");\n await sharp(options.diffPath ?? options.actualPath)\n .resize(locatorWidth, locatorHeight, { fit: \"fill\" })\n .composite([{ input: Buffer.from(svg), left: 0, top: 0 }])\n .png()\n .toFile(file);\n\n return file;\n};\n\n/**\n * Write `locator.png` and `regions.png` into `outDir`.\n *\n * Expected and actual must have the same dimensions — region boxes are only\n * meaningful when both images share a coordinate space. Use\n * {@link renderOverview} when they do not.\n */\nexport const renderJudgmentTiles = async (\n options: TileOptions,\n): Promise<TileResult> => {\n const { width, height } = await readSize(options.actualPath);\n\n const [regions, locator] = await Promise.all([\n renderRegions(options, width, height),\n renderLocator(options, width, height),\n ]);\n\n return {\n locator,\n regions: regions?.file,\n renderedRegions: regions?.count ?? 0,\n };\n};\n\n/**\n * Write `overview.png`: expected and actual, scaled down side by side.\n *\n * For screenshots whose dimensions changed, where no region can be located,\n * this is what the judge looks at instead of two full-size images.\n */\nexport const renderOverview = async (options: {\n expectedPath: string;\n actualPath: string;\n outDir: string;\n}): Promise<string> => {\n const [expectedSize, actualSize] = await Promise.all([\n readSize(options.expectedPath),\n readSize(options.actualPath),\n ]);\n\n // One scale for both, so a height difference stays visible as one.\n const scale = Math.min(\n fitScale(\n expectedSize.width,\n expectedSize.height,\n LOCATOR_MAX_WIDTH,\n LOCATOR_MAX_HEIGHT,\n ),\n fitScale(\n actualSize.width,\n actualSize.height,\n LOCATOR_MAX_WIDTH,\n LOCATOR_MAX_HEIGHT,\n ),\n );\n\n const scaled = (size: { width: number; height: number }) => ({\n width: Math.max(1, Math.round(size.width * scale)),\n height: Math.max(1, Math.round(size.height * scale)),\n });\n const expected = scaled(expectedSize);\n const actual = scaled(actualSize);\n\n const [expectedBuffer, actualBuffer] = await Promise.all([\n sharp(options.expectedPath)\n .resize(expected.width, expected.height, { fit: \"fill\" })\n .png()\n .toBuffer(),\n sharp(options.actualPath)\n .resize(actual.width, actual.height, { fit: \"fill\" })\n .png()\n .toBuffer(),\n ]);\n\n const file = path.join(options.outDir, \"overview.png\");\n await sharp({\n create: {\n width: expected.width + GUTTER + actual.width,\n height: LABEL_HEIGHT + Math.max(expected.height, actual.height),\n channels: 3,\n background: BACKGROUND,\n },\n })\n .composite([\n {\n input: label(\n `expected ${expectedSize.width}x${expectedSize.height}`,\n expected.width,\n ),\n left: 0,\n top: 0,\n },\n {\n input: label(\n `actual ${actualSize.width}x${actualSize.height}`,\n actual.width,\n ),\n left: expected.width + GUTTER,\n top: 0,\n },\n { input: expectedBuffer, left: 0, top: LABEL_HEIGHT },\n {\n input: actualBuffer,\n left: expected.width + GUTTER,\n top: LABEL_HEIGHT,\n },\n ])\n .png()\n .toFile(file);\n\n return file;\n};\n","import { createHash } from \"node:crypto\";\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n type ChangeRegion,\n type InterpretResult,\n interpret,\n} from \"@blazediff/interpret-native\";\nimport sharp from \"sharp\";\nimport { mapWithConcurrency } from \"../mapWithConcurrency\";\nimport { collectScreenshots } from \"../screenshots/collectScreenshots\";\nimport type { DiffOptions, Screenshot } from \"../types\";\nimport {\n AGENT_REPORT_VERSION,\n agentDir,\n agentReportPath,\n judgmentsRoot,\n} from \"./paths\";\nimport { renderJudgmentTiles, renderOverview } from \"./tiles\";\nimport {\n ACTION_BY_LABEL,\n deriveVerdict,\n isJudgedLabel,\n type JudgedLabel,\n normalizeChangeType,\n type Verdict,\n} from \"./verdict\";\n\n/**\n * Agent review: turn the screenshots on disk into something a coding agent\n * can judge cheaply, and fold its judgments back in.\n *\n * Nothing here captures. It reads `actual/`, `expected/` and `diff/` as the\n * last `cappa capture` left them, so it is safe to run repeatedly — a re-run\n * is how an agent's verdicts are applied, and a re-capture invalidates them\n * automatically because every judgment is tied to a fingerprint of the two\n * images it was made about.\n *\n * Layout, all inside `<outputDir>/.cappa-agent/` (dot-prefixed, so neither\n * screenshot collection nor the review server's static handler touch it):\n *\n * ```\n * report.json full report of the last check\n * judgments/<name>/request.json what to judge and where the evidence is\n * judgments/<name>/locator.png thumbnail with every region outlined\n * judgments/<name>/regions.png [expected | actual] crop per region\n * judgments/<name>/overview.png instead of the two above when sizes differ\n * judgments/<name>/verdict.json written by the judge\n * ```\n */\nconst REQUEST_FILE = \"request.json\";\nconst VERDICT_FILE = \"verdict.json\";\nconst JUDGMENT_FILES = [\n REQUEST_FILE,\n VERDICT_FILE,\n \"locator.png\",\n \"regions.png\",\n \"overview.png\",\n];\n\n/**\n * Which changed screenshots get a judgment request.\n *\n * - `ambiguous`: only those the heuristic could not label (default)\n * - `all`: every changed screenshot, for a full second opinion\n * - `none`: heuristic labels only, no new requests\n *\n * Judgments that already exist are kept and applied in every mode.\n */\nexport type JudgeMode = \"ambiguous\" | \"all\" | \"none\";\n\nexport const JUDGE_MODES: readonly JudgeMode[] = [\"ambiguous\", \"all\", \"none\"];\n\nexport type AgentRegion = {\n /** 1-based, matching the numbers in `locator.png` and rows in `regions.png`. */\n index: number;\n bbox: { x: number; y: number; width: number; height: number };\n pixelCount: number;\n percentage: number;\n position: string;\n shape: string;\n changeType: string;\n confidence: number;\n};\n\nexport type AppliedVerdict = Verdict & {\n /** Whether the label came from the heuristic or from a judge. */\n source: \"heuristic\" | \"agent\";\n confidence?: number;\n};\n\nexport type JudgmentPaths = {\n dir: string;\n request: string;\n verdict: string;\n locator?: string;\n regions?: string;\n overview?: string;\n};\n\nexport type AgentReportEntry = {\n name: string;\n category: \"changed\" | \"new\" | \"deleted\";\n taskId?: string;\n plugin?: string;\n /** Absolute paths to the screenshot files. */\n paths: { expected?: string; actual?: string; diff?: string };\n percentDifference?: number;\n numDiffPixels?: number;\n dimensions?: {\n expected: { width: number; height: number };\n actual: { width: number; height: number };\n };\n severity?: string;\n summary?: string;\n /** Largest first. */\n regions?: AgentRegion[];\n heuristic?: Verdict;\n /** The judge's verdict when there is a current one, else the heuristic's. */\n verdict?: AppliedVerdict;\n /** A judgment was requested and no valid verdict has been written yet. */\n pending: boolean;\n judgment?: JudgmentPaths;\n /** Why a `verdict.json` that exists was ignored. */\n verdictError?: string;\n};\n\nexport type AgentReport = {\n version: number;\n createdAt: string;\n outputDir: string;\n reportPath: string;\n judge: JudgeMode;\n totals: {\n total: number;\n passed: number;\n changed: number;\n new: number;\n deleted: number;\n pendingJudgments: number;\n };\n /** Every non-passing screenshot, changed ones first. */\n entries: AgentReportEntry[];\n};\n\n/**\n * The directory holding a screenshot's judgment.\n *\n * Screenshot names are relative paths (`example/button/primary`), so they map\n * onto nested directories directly; anything that would resolve outside the\n * judgments root is refused rather than written.\n */\nexport const judgmentDir = (outputDir: string, name: string): string => {\n const root = judgmentsRoot(outputDir);\n const dir = path.resolve(root, name);\n const relative = path.relative(root, dir);\n if (!relative || relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n throw new Error(`Invalid screenshot name for a judgment: ${name}`);\n }\n return dir;\n};\n\nconst exists = async (file: string): Promise<boolean> => {\n try {\n await fsp.access(file);\n return true;\n } catch {\n return false;\n }\n};\n\nconst readJson = async (file: string): Promise<unknown> => {\n try {\n return JSON.parse(await fsp.readFile(file, \"utf8\"));\n } catch {\n return undefined;\n }\n};\n\nconst writeJson = async (file: string, value: unknown): Promise<void> => {\n await fsp.mkdir(path.dirname(file), { recursive: true });\n await fsp.writeFile(file, `${JSON.stringify(value, null, 2)}\\n`, \"utf8\");\n};\n\n/** Ties a judgment to the exact pair of images it was made about. */\nexport const fingerprintImages = async (\n expectedPath: string,\n actualPath: string,\n): Promise<string> => {\n const [expected, actual] = await Promise.all([\n fsp.readFile(expectedPath),\n fsp.readFile(actualPath),\n ]);\n return createHash(\"sha256\")\n .update(expected)\n .update(\"\\0\")\n .update(actual)\n .digest(\"hex\");\n};\n\nexport type ParsedAgentVerdict =\n | {\n ok: true;\n label: JudgedLabel;\n headline: string;\n rationale: string[];\n confidence?: number;\n }\n | { ok: false; error: string };\n\n/**\n * Read a judge's verdict, accepting both the nested shape blazediff uses\n * (`{ verdict: { label, headline, rationale }, confidence }`) and a flat one\n * (`{ label, headline, rationale, confidence }`) — a judge that writes either\n * should not have its work thrown away over nesting.\n */\nexport const parseAgentVerdict = (raw: unknown): ParsedAgentVerdict => {\n if (typeof raw !== \"object\" || raw === null) {\n return { ok: false, error: \"verdict.json is not a JSON object\" };\n }\n\n const outer = raw as Record<string, unknown>;\n const inner =\n typeof outer.verdict === \"object\" && outer.verdict !== null\n ? (outer.verdict as Record<string, unknown>)\n : outer;\n\n const label = inner.label;\n if (!isJudgedLabel(label)) {\n return {\n ok: false,\n error: `label must be one of regression-likely, intentional-likely, noise-likely (got ${JSON.stringify(label)})`,\n };\n }\n\n const headline =\n typeof inner.headline === \"string\" && inner.headline.trim()\n ? inner.headline.trim()\n : undefined;\n if (!headline) {\n return { ok: false, error: \"headline must be a non-empty string\" };\n }\n\n const toLines = (value: unknown): string[] =>\n Array.isArray(value)\n ? value.filter((line): line is string => typeof line === \"string\")\n : typeof value === \"string\" && value.trim()\n ? [value.trim()]\n : [];\n const rationale = [...toLines(inner.rationale)];\n if (inner !== outer) rationale.push(...toLines(outer.rationale));\n\n const rawConfidence = outer.confidence ?? inner.confidence;\n const confidence =\n typeof rawConfidence === \"number\" && Number.isFinite(rawConfidence)\n ? Math.min(1, Math.max(0, rawConfidence))\n : undefined;\n\n return {\n ok: true,\n label,\n headline,\n rationale,\n ...(confidence !== undefined ? { confidence } : {}),\n };\n};\n\nconst readSize = async (file: string) => {\n const { width = 0, height = 0 } = await sharp(file).metadata();\n return { width, height };\n};\n\nconst toAgentRegions = (regions: readonly ChangeRegion[]): AgentRegion[] =>\n [...regions]\n .sort((a, b) => b.pixelCount - a.pixelCount)\n .map((region, index) => ({\n index: index + 1,\n bbox: {\n x: region.bbox.x,\n y: region.bbox.y,\n width: region.bbox.width,\n height: region.bbox.height,\n },\n pixelCount: region.pixelCount,\n percentage: region.percentage,\n position: region.position,\n shape: region.shape,\n changeType: normalizeChangeType(region.changeType),\n confidence: region.confidence,\n }));\n\n/**\n * The interpretation a capture already persisted, or a fresh one.\n *\n * `diff.interpret` is off by default, so most changed screenshots arrive\n * without one; computing it here means agent review works on any project\n * rather than only on those that opted into interpretation at capture time.\n */\nconst interpretationFor = async (\n screenshot: Extract<Screenshot, { category: \"changed\" }>,\n expectedPath: string,\n actualPath: string,\n diff: DiffOptions | undefined,\n): Promise<InterpretResult | undefined> => {\n if (screenshot.diffMeta?.interpretation) {\n return screenshot.diffMeta.interpretation;\n }\n\n const pixel = diff && diff.type !== \"gmsd\" ? diff : undefined;\n try {\n return await interpret(expectedPath, actualPath, undefined, {\n source: \"pixel\",\n threshold: pixel?.threshold,\n antialiasing: pixel?.includeAA ?? false,\n });\n } catch {\n return undefined;\n }\n};\n\nconst JUDGE_INSTRUCTIONS = [\n \"Read locator.png and regions.png together. locator.png outlines every region (numbered) on a thumbnail; regions.png stacks one [expected | actual] row per region, in `regions` order.\",\n \"Open overview.png when it exists instead — the image dimensions changed, so no regions could be located.\",\n \"Only open paths.expected / paths.actual / paths.diff (full size) when a change clearly continues outside its crop.\",\n \"Write verdict.json next to this file, or run `cappa agent judge <name> --label <label> --headline <text>`.\",\n];\n\nconst VERDICT_SCHEMA = {\n label: \"regression-likely | intentional-likely | noise-likely\",\n headline: \"one line describing what changed\",\n rationale: [\"short reasons\"],\n confidence: \"0..1\",\n};\n\nexport type RunAgentCheckOptions = {\n outputDir: string;\n /** The project's diff config — its threshold is reused for interpretation. */\n diff?: DiffOptions;\n judge?: JudgeMode;\n /** Regions rendered into `regions.png` per screenshot. Default 8. */\n maxTileRegions?: number;\n /** Screenshots analysed in parallel. Default 4. */\n concurrency?: number;\n now?: () => Date;\n};\n\nconst analyseChanged = async (\n screenshot: Extract<Screenshot, { category: \"changed\" }>,\n options: Required<Pick<RunAgentCheckOptions, \"outputDir\" | \"judge\">> &\n RunAgentCheckOptions,\n createdAt: string,\n): Promise<AgentReportEntry> => {\n const { outputDir } = options;\n const expectedPath = path.resolve(outputDir, screenshot.expectedPath);\n const actualPath = path.resolve(outputDir, screenshot.actualPath);\n const diffPath = path.resolve(outputDir, screenshot.diffPath);\n\n const [expectedSize, actualSize, diffExists] = await Promise.all([\n readSize(expectedPath),\n readSize(actualPath),\n exists(diffPath),\n ]);\n const differentSizes =\n expectedSize.width !== actualSize.width ||\n expectedSize.height !== actualSize.height;\n\n const interpretation = differentSizes\n ? undefined\n : await interpretationFor(\n screenshot,\n expectedPath,\n actualPath,\n options.diff,\n );\n\n const percentDifference =\n screenshot.diffMeta?.percentDifference ?? interpretation?.diffPercentage;\n const numDiffPixels =\n screenshot.diffMeta?.numDiffPixels ?? interpretation?.diffCount;\n const regions = toAgentRegions(interpretation?.regions ?? []);\n\n const heuristic = deriveVerdict({\n percentDifference,\n numDiffPixels,\n interpretation,\n differentSizes,\n });\n\n const entry: AgentReportEntry = {\n name: screenshot.name,\n category: \"changed\",\n ...(screenshot.taskId\n ? { taskId: screenshot.taskId, plugin: screenshot.plugin }\n : {}),\n paths: {\n expected: expectedPath,\n actual: actualPath,\n ...(diffExists ? { diff: diffPath } : {}),\n },\n percentDifference,\n numDiffPixels,\n dimensions: { expected: expectedSize, actual: actualSize },\n severity: interpretation?.severity?.toLowerCase(),\n summary: interpretation?.summary,\n regions,\n heuristic,\n verdict: { ...heuristic, source: \"heuristic\" },\n pending: false,\n };\n\n const dir = judgmentDir(outputDir, screenshot.name);\n const requestPath = path.join(dir, REQUEST_FILE);\n const verdictPath = path.join(dir, VERDICT_FILE);\n\n // A judgment that already exists is kept whatever the mode: a verdict the\n // judge wrote after `--judge all` must survive the next plain check rather\n // than be pruned because the heuristic happened to have an opinion too.\n const wantsJudgment =\n options.judge === \"all\" ||\n (options.judge === \"ambiguous\" && heuristic.label === \"ambiguous\") ||\n (await exists(requestPath));\n if (!wantsJudgment) return entry;\n\n const fingerprint = await fingerprintImages(expectedPath, actualPath);\n\n // A request made about different images makes its verdict meaningless:\n // drop the whole judgment and start over rather than apply a stale label.\n const previous = (await readJson(requestPath)) as\n | { fingerprint?: unknown }\n | undefined;\n if (previous && previous.fingerprint !== fingerprint) {\n await clearJudgmentFiles(dir);\n }\n\n await fsp.mkdir(dir, { recursive: true });\n\n const judgment: JudgmentPaths = {\n dir,\n request: requestPath,\n verdict: verdictPath,\n };\n if (differentSizes) {\n judgment.overview = await renderOverview({\n expectedPath,\n actualPath,\n outDir: dir,\n });\n } else {\n const tiles = await renderJudgmentTiles({\n expectedPath,\n actualPath,\n diffPath: diffExists ? diffPath : undefined,\n regions: regions.map((region) => region.bbox),\n outDir: dir,\n maxRegions: options.maxTileRegions,\n });\n if (tiles.locator) judgment.locator = tiles.locator;\n if (tiles.regions) judgment.regions = tiles.regions;\n }\n entry.judgment = judgment;\n\n await writeJson(requestPath, {\n version: AGENT_REPORT_VERSION,\n name: entry.name,\n taskId: entry.taskId,\n plugin: entry.plugin,\n fingerprint,\n createdAt,\n instructions: JUDGE_INSTRUCTIONS,\n verdictSchema: VERDICT_SCHEMA,\n heuristic,\n percentDifference,\n numDiffPixels,\n dimensions: entry.dimensions,\n severity: entry.severity,\n summary: entry.summary,\n regions,\n paths: {\n locator: judgment.locator,\n regions: judgment.regions,\n overview: judgment.overview,\n expected: expectedPath,\n actual: actualPath,\n diff: entry.paths.diff,\n verdict: verdictPath,\n },\n });\n\n if (!(await exists(verdictPath))) {\n entry.pending = true;\n return entry;\n }\n\n const parsed = parseAgentVerdict(await readJson(verdictPath));\n if (!parsed.ok) {\n entry.pending = true;\n entry.verdictError = parsed.error;\n return entry;\n }\n\n entry.verdict = {\n label: parsed.label,\n headline: parsed.headline,\n rationale: parsed.rationale,\n action: ACTION_BY_LABEL[parsed.label],\n source: \"agent\",\n ...(parsed.confidence !== undefined\n ? { confidence: parsed.confidence }\n : {}),\n };\n return entry;\n};\n\nconst clearJudgmentFiles = async (dir: string): Promise<void> => {\n await Promise.all(\n JUDGMENT_FILES.map((file) => fsp.rm(path.join(dir, file), { force: true })),\n );\n};\n\n/**\n * Remove a screenshot's judgment — after it was approved, or because it is no\n * longer changed. Only the judgment's own files go: a directory can also be\n * the parent of another screenshot's judgment (`button` and `button/primary`).\n */\nexport const clearJudgment = async (\n outputDir: string,\n name: string,\n): Promise<void> => {\n const dir = judgmentDir(outputDir, name);\n await clearJudgmentFiles(dir);\n await removeEmptyDirs(dir, judgmentsRoot(outputDir));\n};\n\n/** Remove `dir` and its parents up to (excluding) `root` while empty. */\nconst removeEmptyDirs = async (dir: string, root: string): Promise<void> => {\n let current = dir;\n while (current !== root && current.startsWith(root)) {\n try {\n await fsp.rmdir(current);\n } catch {\n return;\n }\n current = path.dirname(current);\n }\n};\n\nconst listRequestDirs = async (root: string): Promise<string[]> => {\n if (!(await exists(root))) return [];\n const files = await Array.fromAsync(\n fsp.glob(`**/${REQUEST_FILE}`, { cwd: root }),\n );\n return files.map((file) => path.resolve(root, path.dirname(file)));\n};\n\n/** Drop judgments for screenshots that no longer need one. */\nconst pruneJudgments = async (\n outputDir: string,\n keep: ReadonlySet<string>,\n): Promise<void> => {\n const root = judgmentsRoot(outputDir);\n for (const dir of await listRequestDirs(root)) {\n if (keep.has(dir)) continue;\n await clearJudgmentFiles(dir);\n await removeEmptyDirs(dir, root);\n }\n};\n\n/**\n * Analyse every non-passing screenshot, write judgment requests for the ones\n * that need a judge, apply any verdicts already written, and persist the\n * full report to `<outputDir>/.cappa-agent/report.json`.\n */\nexport const runAgentCheck = async (\n options: RunAgentCheckOptions,\n): Promise<AgentReport> => {\n const outputDir = path.resolve(options.outputDir);\n const judge = options.judge ?? \"ambiguous\";\n const createdAt = (options.now?.() ?? new Date()).toISOString();\n\n const screenshots = await collectScreenshots(outputDir);\n\n // Never commit agent scratch state: a judgment is only valid for the\n // images on this machine.\n await fsp.mkdir(agentDir(outputDir), { recursive: true });\n await fsp.writeFile(path.join(agentDir(outputDir), \".gitignore\"), \"*\\n\");\n\n const changed = screenshots.filter(\n (s): s is Extract<Screenshot, { category: \"changed\" }> =>\n s.category === \"changed\",\n );\n\n const changedEntries = await mapWithConcurrency(\n options.concurrency ?? 4,\n changed,\n (screenshot) =>\n analyseChanged(screenshot, { ...options, outputDir, judge }, createdAt),\n );\n\n await pruneJudgments(\n outputDir,\n new Set(\n changedEntries.flatMap((entry) =>\n entry.judgment ? [entry.judgment.dir] : [],\n ),\n ),\n );\n\n const otherEntries = screenshots.flatMap((s): AgentReportEntry[] => {\n if (s.category === \"new\") {\n return [\n {\n name: s.name,\n category: \"new\",\n ...(s.taskId ? { taskId: s.taskId, plugin: s.plugin } : {}),\n paths: { actual: path.resolve(outputDir, s.actualPath) },\n pending: false,\n },\n ];\n }\n if (s.category === \"deleted\") {\n return [\n {\n name: s.name,\n category: \"deleted\",\n paths: { expected: path.resolve(outputDir, s.expectedPath) },\n pending: false,\n },\n ];\n }\n return [];\n });\n\n const entries = [...changedEntries, ...otherEntries];\n const count = (category: Screenshot[\"category\"]) =>\n screenshots.filter((s) => s.category === category).length;\n\n const report: AgentReport = {\n version: AGENT_REPORT_VERSION,\n createdAt,\n outputDir,\n reportPath: agentReportPath(outputDir),\n judge,\n totals: {\n total: screenshots.length,\n passed: count(\"passed\"),\n changed: count(\"changed\"),\n new: count(\"new\"),\n deleted: count(\"deleted\"),\n pendingJudgments: entries.filter((entry) => entry.pending).length,\n },\n entries,\n };\n\n await writeJson(report.reportPath, report);\n\n return report;\n};\n\n/** Read the report the last {@link runAgentCheck} wrote, if any. */\nexport const readAgentReport = async (\n outputDir: string,\n): Promise<AgentReport | undefined> => {\n const raw = (await readJson(agentReportPath(outputDir))) as\n | AgentReport\n | undefined;\n return raw?.version === AGENT_REPORT_VERSION ? raw : undefined;\n};\n\nexport type SlimAgentReport = {\n reportPath: string;\n total: number;\n passed: number;\n changed: number;\n new: number;\n deleted: number;\n pendingJudgments: number;\n results: Array<{\n name: string;\n category: AgentReportEntry[\"category\"];\n verdict?: Pick<AppliedVerdict, \"label\" | \"headline\" | \"action\" | \"source\">;\n pending?: true;\n /** Judgment directory, present while a verdict is pending. */\n judgment?: string;\n verdictError?: string;\n }>;\n};\n\n/**\n * The report as an agent should first see it: one line of state per\n * screenshot, with the detail left in `report.json` and the judgment\n * requests for when it is actually needed.\n */\nexport const toSlimAgentReport = (report: AgentReport): SlimAgentReport => ({\n reportPath: report.reportPath,\n ...report.totals,\n results: report.entries.map((entry) => ({\n name: entry.name,\n category: entry.category,\n ...(entry.verdict\n ? {\n verdict: {\n label: entry.verdict.label,\n headline: entry.verdict.headline,\n action: entry.verdict.action,\n source: entry.verdict.source,\n },\n }\n : {}),\n ...(entry.pending ? { pending: true as const } : {}),\n ...(entry.pending && entry.judgment\n ? { judgment: entry.judgment.dir }\n : {}),\n ...(entry.verdictError ? { verdictError: entry.verdictError } : {}),\n })),\n});\n\nexport type AgentVerdictInput = {\n label: JudgedLabel;\n headline: string;\n rationale?: string[];\n confidence?: number;\n};\n\n/**\n * Record a judge's verdict for a screenshot with a pending request — the\n * validated alternative to hand-writing `verdict.json`.\n */\nexport const writeAgentVerdict = async (\n outputDir: string,\n name: string,\n input: AgentVerdictInput,\n): Promise<string> => {\n const dir = judgmentDir(outputDir, name);\n if (!(await exists(path.join(dir, REQUEST_FILE)))) {\n throw new Error(\n `No judgment request for \"${name}\" — run \\`cappa agent check\\` first (use --judge all to request one for any changed screenshot).`,\n );\n }\n\n const parsed = parseAgentVerdict(input);\n if (!parsed.ok) throw new Error(parsed.error);\n\n const verdictPath = path.join(dir, VERDICT_FILE);\n await writeJson(verdictPath, {\n name,\n verdict: {\n label: parsed.label,\n headline: parsed.headline,\n rationale: parsed.rationale,\n action: ACTION_BY_LABEL[parsed.label],\n },\n ...(parsed.confidence !== undefined\n ? { confidence: parsed.confidence }\n : {}),\n });\n return verdictPath;\n};\n","import path from \"node:path\";\nimport type { WebServerConfig } from \"../types\";\nimport type { ResolvedWebServerConfig } from \"./WebServerPool\";\n\nexport const DEFAULT_WEB_SERVER_TIMEOUT_MS = 60_000;\n\n// `localhost:6006` parses — as a URL with the scheme `localhost:`.\nconst isHttpUrl = (value: string): boolean =>\n URL.canParse(value) && [\"http:\", \"https:\"].includes(new URL(value).protocol);\n\n/**\n * Normalise `webServer` to a list with every default applied.\n *\n * A relative `cwd` resolves against `configDir` — the directory of\n * `cappa.config.ts` — not the process's working directory, so the same config\n * works whether cappa runs from the repository root or from inside the package\n * (`pnpm -F visual-tests cappa capture`).\n */\nexport function resolveWebServerConfig(\n webServer: WebServerConfig | WebServerConfig[] | undefined,\n configDir: string,\n env: NodeJS.ProcessEnv = process.env,\n): ResolvedWebServerConfig[] {\n if (webServer === undefined) {\n return [];\n }\n\n const entries = Array.isArray(webServer) ? webServer : [webServer];\n\n return entries.map((entry, index) => {\n const where = Array.isArray(webServer)\n ? `webServer[${index}]`\n : \"webServer\";\n\n if (typeof entry?.command !== \"string\" || entry.command.trim() === \"\") {\n throw new Error(`Invalid configuration: ${where}.command is required.`);\n }\n if (typeof entry.url !== \"string\" || !isHttpUrl(entry.url)) {\n throw new Error(\n `Invalid configuration: ${where}.url must be an absolute URL, e.g. \"http://localhost:6006\".`,\n );\n }\n if (\n entry.timeout !== undefined &&\n !(Number.isFinite(entry.timeout) && entry.timeout > 0)\n ) {\n throw new Error(\n `Invalid configuration: ${where}.timeout must be a positive number of milliseconds.`,\n );\n }\n\n return {\n command: entry.command,\n url: entry.url,\n reuseExistingServer: entry.reuseExistingServer ?? !env.CI,\n timeout: entry.timeout ?? DEFAULT_WEB_SERVER_TIMEOUT_MS,\n cwd: path.resolve(configDir, entry.cwd ?? \".\"),\n env: entry.env ?? {},\n };\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,MAAM,eAAe,OAAO,KAAK;CAC/B;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;AAC5C,CAAC;AAKD,MAAM,4BAAW,IAAI,YAAY,GAAG,EAAA,CAAE,KAAK,GAAG,UAAU;CACtD,IAAI,IAAI;CACR,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KACrB,IAAI,IAAI,IAAI,aAAc,MAAM,IAAK,MAAM;CAG7C,OAAO,MAAM;AACf,CAAC;;;;;;;;;;;AAYD,UAAU,WAAW,QAAwC;CAC3D,IAAI,SAAS,aAAa;CAE1B,OAAO,SAAS,KAAK,OA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;;;;AAU7E,SAAgB,uBACd,WACA,WACA,MAAyB,QAAQ,KACN;CAC3B,IAAI,cAAc,KAAA,GAChB,OAAO,CAAC;CAKV,QAFgB,MAAM,QAAQ,SAAS,IAAI,YAAY,CAAC,SAAS,EAAA,CAElD,KAAK,OAAO,UAAU;EACnC,MAAM,QAAQ,MAAM,QAAQ,SAAS,IACjC,aAAa,MAAM,KACnB;EAEJ,IAAI,OAAO,OAAO,YAAY,YAAY,MAAM,QAAQ,KAAK,MAAM,IACjE,MAAM,IAAI,MAAM,0BAA0B,MAAM,sBAAsB;EAExE,IAAI,OAAO,MAAM,QAAQ,YAAY,CAAC,UAAU,MAAM,GAAG,GACvD,MAAM,IAAI,MACR,0BAA0B,MAAM,4DAClC;EAEF,IACE,MAAM,YAAY,KAAA,KAClB,EAAE,OAAO,SAAS,MAAM,OAAO,KAAK,MAAM,UAAU,IAEpD,MAAM,IAAI,MACR,0BAA0B,MAAM,oDAClC;EAGF,OAAO;GACL,SAAS,MAAM;GACf,KAAK,MAAM;GACX,qBAAqB,MAAM,uBAAuB,CAAC,IAAI;GACvD,SAAS,MAAM,WAAA;GACf,KAAKI,UAAAA,QAAK,QAAQ,WAAW,MAAM,OAAO,GAAG;GAC7C,KAAK,MAAM,OAAO,CAAC;EACrB;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"index.cjs","names":["open","readFile","writeFile","gmsd","path","fsp","path","os","fs","blazediffCompare","interpret","path","path","fsp","glob","getLogger","fs","path","fsp","path","glob","randomUUID","relative","getLogger","path","path","fsp","path","path","createHash","glob","path","spawn","path","getLogger","path","readSize","path","path","fsp","createHash","interpret","os","path"],"sources":["../src/features/png/util.ts","../src/features/png/png.ts","../src/compare/gmsd.ts","../src/features/png/canvas.ts","../src/compare/pixel.ts","../src/config.ts","../src/consoleEvents.ts","../src/crop.ts","../src/mapWithConcurrency.ts","../src/paths.ts","../src/filesystem.ts","../src/screenshots/manifest.ts","../src/webServer/unreachable.ts","../src/runner/tasks.ts","../src/runner/types.ts","../src/runner/CaptureRunner.ts","../src/screenshot.ts","../src/agent/paths.ts","../src/agent/verdict.ts","../src/agent/reviewIndex.ts","../src/screenshots/groupScreenshots.ts","../src/screenshots/collectScreenshots.ts","../src/webServer/process.ts","../src/webServer/readiness.ts","../src/webServer/WebServerPool.ts","../src/engine/RunStore.ts","../src/engine/types.ts","../src/engine/WarmBrowser.ts","../src/engine/WatchSession.ts","../src/engine/LocalEngine.ts","../src/store.ts","../src/agent/tiles.ts","../src/agent/review.ts","../src/webServer/resolve.ts"],"sourcesContent":["import { open } from \"node:fs/promises\";\nimport type { MetadataEntries } from \"./types\";\n\ntype ParsedChunk = {\n type: string;\n data: Buffer;\n length: number;\n offset: number;\n};\n\n// Magic Bytes:\n// The first 8 bytes of every valid PNG file.\n// Used to verify that the file is actually a PNG before processing.\nconst pngSignature = Buffer.from([\n 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,\n]);\n\n// A pre-calculated lookup table for the CRC32 algorithm.\n// We use this to quickly calculate the checksum for each chunk we write.\n// Without this table, calculating CRC bit-by-bit would be significantly slower.\nconst crcTable = new Uint32Array(256).map((_, index) => {\n let c = index;\n for (let k = 0; k < 8; k++) {\n c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n }\n\n return c >>> 0;\n});\n\n/**\n * Chunk Parser Generator\n *\n * A PNG file is essentially a list of chunks.\n * Structure of a chunk:\n * 1. Length (4 bytes): The size of the data field.\n * 2. Type (4 bytes): ASCII name (e.g., 'IHDR', 'tEXt', 'IEND').\n * 3. Data (Length bytes): The actual payload.\n * 4. CRC (4 bytes): Checksum.\n */\nfunction* readChunks(buffer: Buffer): Generator<ParsedChunk> {\n let offset = pngSignature.length;\n\n while (offset + 8 <= buffer.length) {\n const length = buffer.readUInt32BE(offset);\n const type = buffer.toString(\"ascii\", offset + 4, offset + 8);\n const dataStart = offset + 8;\n const dataEnd = dataStart + length;\n\n if (dataEnd > buffer.length) {\n return;\n }\n\n const data = buffer.subarray(dataStart, dataEnd);\n\n yield { type, data, length, offset };\n\n offset = dataEnd + 4; // Skip CRC\n\n if (type === \"IEND\") {\n return;\n }\n }\n}\n\n/**\n * Constructs a raw binary `tEXt` chunk.\n */\nexport function createTextChunk(key: string, value: string) {\n const keyBuffer = Buffer.from(key, \"latin1\");\n const valueBuffer = Buffer.from(value, \"latin1\");\n const data = Buffer.concat([keyBuffer, Buffer.from([0]), valueBuffer]);\n const lengthBuffer = Buffer.alloc(4);\n const typeBuffer = Buffer.from(\"tEXt\");\n\n lengthBuffer.writeUInt32BE(data.length, 0);\n\n const crcBuffer = Buffer.alloc(4);\n crcBuffer.writeUInt32BE(crc32(Buffer.concat([typeBuffer, data])), 0);\n\n return Buffer.concat([lengthBuffer, typeBuffer, data, crcBuffer]);\n}\n\n/**\n * Calculates the CRC32 checksum for a buffer.\n * Used to ensure data integrity.\n */\nexport function crc32(buffer: Buffer) {\n let crc = 0 ^ -1;\n\n for (let i = 0; i < buffer.length; i++) {\n // biome-ignore lint/style/noNonNullAssertion: we know the index is valid\n crc = (crc >>> 8) ^ crcTable[(crc ^ buffer[i]!) & 0xff]!;\n }\n\n return (crc ^ -1) >>> 0;\n}\n\n/**\n * Helper to locate the IEND chunk, which marks the end of a PNG stream.\n */\nfunction findIendChunk(buffer: Buffer): ParsedChunk | undefined {\n for (const chunk of readChunks(buffer)) {\n if (chunk.type === \"IEND\") {\n return chunk;\n }\n }\n\n return undefined;\n}\n\n/**\n * Inserts metadata chunks into a PNG buffer.\n * It places them right before the final `IEND` chunk.\n */\nexport function injectTextMetadata(buffer: Buffer, metadata: MetadataEntries) {\n if (!buffer.subarray(0, pngSignature.length).equals(pngSignature)) {\n return buffer;\n }\n\n const iendChunk = findIendChunk(buffer);\n if (!iendChunk) {\n return buffer;\n }\n\n const textChunks = Object.entries(metadata).map(([key, value]) =>\n createTextChunk(key, value),\n );\n\n return Buffer.concat([\n buffer.subarray(0, iendChunk.offset),\n ...textChunks,\n buffer.subarray(iendChunk.offset),\n ]);\n}\n\nexport function isValidPngSignature(buffer: Buffer): boolean {\n if (buffer.length < pngSignature.length) return false;\n return buffer.subarray(0, pngSignature.length).equals(pngSignature);\n}\n\nconst IHDR_MIN_BYTES = 24;\n\nexport async function readIhdrDimensions(\n source: string | Buffer,\n): Promise<{ width: number; height: number }> {\n let buf: Buffer;\n\n if (typeof source === \"string\") {\n const fh = await open(source, \"r\");\n try {\n buf = Buffer.alloc(IHDR_MIN_BYTES);\n await fh.read(buf, 0, IHDR_MIN_BYTES, 0);\n } finally {\n await fh.close();\n }\n } else {\n buf = source;\n }\n\n if (\n buf.length < IHDR_MIN_BYTES ||\n !buf.subarray(0, pngSignature.length).equals(pngSignature)\n ) {\n throw new Error(\"Not a valid PNG\");\n }\n\n const width = buf.readUInt32BE(16);\n const height = buf.readUInt32BE(20);\n return { width, height };\n}\n\n/**\n * Scans a raw PNG buffer and extracts key-value pairs from `tEXt` chunks.\n */\nexport function extractTextMetadata(buffer: Buffer): MetadataEntries {\n if (!buffer.subarray(0, pngSignature.length).equals(pngSignature)) {\n return {};\n }\n\n const metadata: MetadataEntries = {};\n\n for (const chunk of readChunks(buffer)) {\n if (chunk.type !== \"tEXt\") {\n continue;\n }\n\n const separatorIndex = chunk.data.indexOf(0);\n if (separatorIndex < 0) {\n continue;\n }\n\n const key = chunk.data.toString(\"latin1\", 0, separatorIndex);\n const value = chunk.data.toString(\"latin1\", separatorIndex + 1);\n\n metadata[key] = value;\n }\n\n return metadata;\n}\n","import { readFile, writeFile } from \"node:fs/promises\";\nimport sharp from \"sharp\";\nimport type { MetadataEntries } from \"./types\";\nimport { extractTextMetadata, injectTextMetadata } from \"./util\";\n\n/**\n * A wrapper around `sharp` that adds support for reading and writing\n * textual metadata (tEXt chunks). Used for fast PNG decode/encode.\n */\nexport class PNG {\n private width_: number;\n private height_: number;\n private data_: Buffer;\n private sourcePath?: string;\n private metadataEntries: MetadataEntries;\n\n private constructor(\n width: number,\n height: number,\n data: Buffer,\n sourcePath?: string,\n metadata?: MetadataEntries,\n ) {\n this.width_ = width;\n this.height_ = height;\n this.data_ = data;\n this.sourcePath = sourcePath;\n this.metadataEntries = { ...(metadata ?? {}) };\n }\n\n static create(width: number, height: number): PNG {\n const data = Buffer.alloc(width * height * 4, 0);\n return new PNG(width, height, data);\n }\n\n static async load(source: string | Buffer): Promise<PNG> {\n const buffer = typeof source === \"string\" ? await readFile(source) : source;\n const metadata = extractTextMetadata(buffer);\n\n const pipeline = sharp(buffer).ensureAlpha();\n const { data: raw, info } = await pipeline\n .raw()\n .toBuffer({ resolveWithObject: true });\n\n const data = Buffer.from(raw);\n const sourcePath = typeof source === \"string\" ? source : undefined;\n\n return new PNG(info.width, info.height, data, sourcePath, metadata);\n }\n\n /**\n * A copy of this image on a `width` × `height` canvas, anchored top-left,\n * with the added area filled with `fill` (RGBA, transparent by default).\n *\n * This is how two screenshots of different sizes are given a shared\n * coordinate space: a component that grew keeps its pixels where they were.\n */\n padTo(\n width: number,\n height: number,\n fill: readonly [number, number, number, number] = [0, 0, 0, 0],\n ): PNG {\n if (width < this.width_ || height < this.height_) {\n throw new Error(\n `Cannot pad a ${this.width_}x${this.height_} image to a smaller ${width}x${height} canvas`,\n );\n }\n\n if (width === this.width_ && height === this.height_) {\n return new PNG(width, height, Buffer.from(this.data_));\n }\n\n const data = Buffer.alloc(width * height * 4);\n const pixel = Buffer.from(fill);\n for (let offset = 0; offset < data.length; offset += 4) {\n pixel.copy(data, offset);\n }\n\n const rowBytes = this.width_ * 4;\n for (let y = 0; y < this.height_; y++) {\n this.data_.copy(data, y * width * 4, y * rowBytes, (y + 1) * rowBytes);\n }\n\n return new PNG(width, height, data);\n }\n\n /**\n * The most common colour along the right column and the bottom row — the\n * edges a top-left anchored {@link padTo} extends. For a screenshot that is\n * its background, which is what the area it never covered should read as.\n */\n edgeColor(): [number, number, number, number] {\n const counts = new Map<number, number>();\n let best = 0;\n let bestCount = 0;\n\n const count = (x: number, y: number) => {\n const value = this.data_.readUInt32BE((y * this.width_ + x) * 4);\n const next = (counts.get(value) ?? 0) + 1;\n counts.set(value, next);\n if (next > bestCount) {\n best = value;\n bestCount = next;\n }\n };\n\n if (this.width_ === 0 || this.height_ === 0) return [0, 0, 0, 0];\n\n for (let y = 0; y < this.height_; y++) count(this.width_ - 1, y);\n for (let x = 0; x < this.width_ - 1; x++) count(x, this.height_ - 1);\n\n return [\n (best >>> 24) & 0xff,\n (best >>> 16) & 0xff,\n (best >>> 8) & 0xff,\n best & 0xff,\n ];\n }\n\n get width(): number {\n return this.width_;\n }\n\n get height(): number {\n return this.height_;\n }\n\n get data(): Buffer {\n return this.data_;\n }\n\n get metadata(): MetadataEntries {\n return { ...this.metadataEntries };\n }\n\n setMetadata(key: string, value: string): void {\n this.metadataEntries = { ...this.metadataEntries, [key]: value };\n }\n\n replaceMetadata(metadata: MetadataEntries): void {\n this.metadataEntries = { ...metadata };\n }\n\n removeMetadata(key: string): void {\n const { [key]: _, ...remaining } = this.metadataEntries;\n this.metadataEntries = remaining;\n }\n\n clearMetadata(): void {\n this.metadataEntries = {};\n }\n\n async toBuffer(): Promise<Buffer> {\n const baseBuffer = await sharp(this.data_, {\n raw: { width: this.width_, height: this.height_, channels: 4 },\n })\n .png()\n .toBuffer();\n\n if (Object.keys(this.metadataEntries).length === 0) {\n return baseBuffer;\n }\n\n return injectTextMetadata(baseBuffer, this.metadataEntries);\n }\n\n async save(filepath?: string): Promise<void> {\n const targetPath = filepath ?? this.sourcePath;\n\n if (!targetPath) {\n throw new Error(\"No filepath provided for saving PNG\");\n }\n\n await writeFile(targetPath, await this.toBuffer());\n }\n}\n","import fs from \"node:fs\";\nimport gmsd, { type GmsdOptions } from \"@blazediff/gmsd\";\nimport { getLogger } from \"@cappa/logger\";\nimport { PNG } from \"../features/png/png\";\nimport type { DiffConfigGMSD } from \"../types\";\n\nexport type CompareOptions = GmsdOptions;\n\nexport interface CompareResult {\n gmsd: number;\n diffBuffer?: Buffer; // PNG buffer of the diff image\n passed: boolean; // Whether the comparison passed based on threshold\n error?: string; // Error message if the comparison failed\n /**\n * Whether the images have different sizes. Both are then scored on a canvas\n * padded to the larger width and height (anchored top-left, each with its\n * own edge colour), and the comparison never passes.\n */\n differentSizes?: boolean;\n}\n\nconst compare = (\n image1: Uint8Array | Uint8ClampedArray,\n image2: Uint8Array | Uint8ClampedArray,\n diff: Uint8Array | Uint8ClampedArray | undefined,\n width: number,\n height: number,\n options?: GmsdOptions,\n) => {\n return gmsd(image1, image2, diff, width, height, options);\n};\n\n/**\n * Compare two PNG images and return the difference\n * @param image1 - Baseline (expected) image (file path or Buffer)\n * @param image2 - Current (actual) image (file path or Buffer)\n * @param withDiff - Whether to create a diff image\n * @param options - Comparison options\n * @returns Comparison result\n */\nexport async function compareImagesGMSD(\n image1: string | Buffer,\n image2: string | Buffer,\n withDiff: boolean = false,\n options: DiffConfigGMSD = {},\n): Promise<CompareResult> {\n // Load both PNGs in parallel with sharp for better performance\n const [loaded1, loaded2] = await Promise.all([\n loadPNG(image1),\n loadPNG(image2),\n ]);\n\n // A size change is still scored, on a shared canvas, so it gets a diff image\n // showing where the images diverge rather than a bare `Infinity`.\n const differentSizes =\n loaded1.width !== loaded2.width || loaded1.height !== loaded2.height;\n const width = Math.max(loaded1.width, loaded2.width);\n const height = Math.max(loaded1.height, loaded2.height);\n const png1 = differentSizes\n ? loaded1.padTo(width, height, loaded1.edgeColor())\n : loaded1;\n const png2 = differentSizes\n ? loaded2.padTo(width, height, loaded2.edgeColor())\n : loaded2;\n\n const diff = withDiff ? PNG.create(width, height) : undefined;\n\n try {\n const gmsd = compare(png1.data, png2.data, diff?.data, width, height, {\n downsample: options.downsample ?? 0,\n c: options.c ?? 170,\n });\n\n // Convert diff image to buffer\n const diffBuffer = diff\n ? await annotateDiffImage(diff, options).toBuffer()\n : undefined;\n\n if (differentSizes) {\n return { gmsd, diffBuffer, passed: false, differentSizes: true };\n }\n\n return {\n gmsd,\n diffBuffer,\n passed: gmsd <= (options.threshold ?? 0.1),\n };\n } catch (error) {\n getLogger().error((error as Error).message || \"Unknown error\");\n\n return {\n gmsd: Infinity,\n passed: false,\n error: (error as Error).message || \"Unknown error\",\n };\n }\n}\n\n/**\n * Load a PNG image from file path or Buffer\n */\nasync function loadPNG(source: string | Buffer): Promise<PNG> {\n return PNG.load(source);\n}\n\nfunction annotateDiffImage(image: PNG, options: DiffConfigGMSD) {\n image.setMetadata(\"cappa.diff.algorithm\", \"gmsd\");\n\n for (const [key, value] of Object.entries(options)) {\n if (value === undefined) {\n continue;\n }\n\n image.setMetadata(`cappa.diff.${key}`, String(value));\n }\n\n return image;\n}\n\n/**\n * Save a comparison result diff image to file\n * @param result - Comparison result containing diffBuffer\n * @param outputPath - Path to save the diff image\n */\nexport function saveDiffImage(result: CompareResult, outputPath: string): void {\n if (!result.diffBuffer) {\n throw new Error(\"No diff buffer available in comparison result\");\n }\n\n fs.writeFileSync(outputPath, result.diffBuffer);\n}\n\n/**\n * Quick comparison function that returns only pass/fail\n * @param image1 - Baseline (expected) image (file path or Buffer)\n * @param image2 - Current (actual) image (file path or Buffer)\n * @param options - Comparison options\n * @returns Whether the images match\n */\nexport async function imagesMatchGMSD(\n image1: string | Buffer,\n image2: string | Buffer,\n options: DiffConfigGMSD = {},\n): Promise<boolean> {\n const result = await compareImagesGMSD(image1, image2, false, options);\n\n return result.passed;\n}\n","import path from \"node:path\";\nimport { PNG } from \"./png\";\n\nexport type Size = { width: number; height: number };\n\nexport type CommonCanvas = {\n /** The padded copy of the expected image. */\n expectedPath: string;\n /** The padded copy of the actual image. */\n actualPath: string;\n /** The shared canvas: the larger width and the larger height of the two. */\n width: number;\n height: number;\n /** Both images' own dimensions, before padding. */\n dimensions: { expected: Size; actual: Size };\n};\n\n/**\n * Write copies of two images, padded to a shared canvas, into `dir`.\n *\n * Both are anchored top-left and padded up to the larger width and the larger\n * height, so every pixel keeps its original coordinates and a region found on\n * the canvas points at the same spot in either image.\n *\n * Each image is padded with its own background — the most common colour on\n * the edges being extended — rather than with transparency. Area an image\n * never covered then reads as empty rather than as content: a list that grew\n * by one item diffs as that item (an addition), not as a whole strip that\n * changed, and a component that only gained whitespace diffs as nothing at\n * all, leaving the size change itself as the finding.\n */\nexport async function writeCommonCanvas(\n expected: string | Buffer,\n actual: string | Buffer,\n dir: string,\n): Promise<CommonCanvas> {\n const [expectedPng, actualPng] = await Promise.all([\n PNG.load(expected),\n PNG.load(actual),\n ]);\n\n const width = Math.max(expectedPng.width, actualPng.width);\n const height = Math.max(expectedPng.height, actualPng.height);\n const expectedPath = path.join(dir, \"expected-canvas.png\");\n const actualPath = path.join(dir, \"actual-canvas.png\");\n\n await Promise.all([\n expectedPng\n .padTo(width, height, expectedPng.edgeColor())\n .save(expectedPath),\n actualPng.padTo(width, height, actualPng.edgeColor()).save(actualPath),\n ]);\n\n return {\n expectedPath,\n actualPath,\n width,\n height,\n dimensions: {\n expected: { width: expectedPng.width, height: expectedPng.height },\n actual: { width: actualPng.width, height: actualPng.height },\n },\n };\n}\n","import fs from \"node:fs\";\nimport fsp from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport {\n type BlazeDiffOptions,\n type BlazeDiffResult,\n compare as blazediffCompare,\n} from \"@blazediff/core-native\";\nimport { type InterpretResult, interpret } from \"@blazediff/interpret-native\";\nimport { getLogger } from \"@cappa/logger\";\nimport { writeCommonCanvas } from \"../features/png/canvas\";\nimport { PNG } from \"../features/png/png\";\nimport {\n injectTextMetadata,\n isValidPngSignature,\n readIhdrDimensions,\n} from \"../features/png/util\";\nimport type { DiffConfig } from \"../types\";\n\n/** Pixel diff options: Cappa `DiffConfig` plus optional native-only output tuning. */\nexport type CompareOptions = DiffConfig &\n Partial<Pick<BlazeDiffOptions, \"diffMask\" | \"compression\" | \"quality\">>;\n\nexport interface CompareResult {\n numDiffPixels: number;\n totalPixels: number;\n percentDifference: number;\n diffBuffer?: Buffer; // PNG buffer of the diff image\n passed: boolean; // Whether the comparison passed based on threshold\n error?: string; // Error message if the comparison failed\n /**\n * Whether the images have different sizes.\n *\n * When they do, both are compared on a canvas padded to the larger width\n * and height (anchored top-left, each padded with its own background), so\n * the pixel counts, the diff image and the interpretation still describe\n * what changed. Such a comparison never passes, even with no differing\n * pixels — the size change is itself the finding.\n */\n differentSizes: boolean;\n /** Both images' own dimensions — set when `differentSizes` is. */\n dimensions?: {\n expected: { width: number; height: number };\n actual: { width: number; height: number };\n };\n interpretation?: InterpretResult; // Structured diff analysis (when `interpret` is enabled)\n}\n\ntype TempState = { tempRoot?: string };\n\nasync function ensureTempRoot(state: TempState): Promise<string> {\n if (!state.tempRoot) {\n state.tempRoot = await fsp.mkdtemp(path.join(os.tmpdir(), \"cappa-pxl-\"));\n }\n return state.tempRoot;\n}\n\nasync function resolveInputPath(\n source: string | Buffer,\n fileName: string,\n state: TempState,\n): Promise<string> {\n if (typeof source === \"string\") {\n await fsp.access(source, fs.constants.R_OK);\n return path.resolve(source);\n }\n\n if (!isValidPngSignature(source)) {\n throw new Error(\"Invalid PNG buffer: missing PNG signature\");\n }\n\n const root = await ensureTempRoot(state);\n const dest = path.join(root, fileName);\n await fsp.writeFile(dest, source);\n return dest;\n}\n\nfunction toNativeOptions(config: DiffConfig): BlazeDiffOptions {\n const extra = config as CompareOptions;\n const out: BlazeDiffOptions = {\n threshold: extra.threshold,\n antialiasing: extra.includeAA ?? false,\n };\n\n if (extra.diffMask !== undefined) {\n out.diffMask = extra.diffMask;\n }\n if (extra.compression !== undefined) {\n out.compression = extra.compression;\n }\n if (extra.quality !== undefined) {\n out.quality = extra.quality;\n }\n\n return out;\n}\n\n/**\n * Compare two PNG images and return the difference\n * @param image1 - Baseline (expected) image (file path or Buffer)\n * @param image2 - Current (actual) image (file path or Buffer). Order matters\n * for `interpret`: content only in `image2` is reported as an addition.\n * @param withDiff - Whether to create a diff image\n * @param options - Comparison options\n * @returns Comparison result\n */\nexport async function compareImages(\n image1: string | Buffer,\n image2: string | Buffer,\n withDiff: boolean = false,\n options: DiffConfig = {},\n): Promise<CompareResult> {\n const state: TempState = {};\n let diffPath: string | undefined;\n\n try {\n const p1 = await resolveInputPath(image1, \"expected.png\", state);\n const p2 = await resolveInputPath(image2, \"actual.png\", state);\n\n if (withDiff) {\n const root = await ensureTempRoot(state);\n diffPath = path.join(root, \"diff.png\");\n }\n\n const wantInterpret = !!(options as CompareOptions).interpret && withDiff;\n\n let nativeResult: BlazeDiffResult;\n\n try {\n // Never pass `interpret` to `compare` — the native binding skips writing\n // the diff image when interpret mode is on. Interpretation is fetched in\n // a separate call below when needed.\n nativeResult = await blazediffCompare(\n p1,\n p2,\n withDiff ? diffPath : undefined,\n toNativeOptions(options),\n );\n } catch (error) {\n getLogger().error((error as Error).message || \"Unknown error\");\n\n return {\n numDiffPixels: 0,\n totalPixels: 0,\n percentDifference: 0,\n passed: false,\n differentSizes: false,\n error: (error as Error).message || \"Unknown error\",\n };\n }\n\n if (nativeResult.match === false) {\n if (nativeResult.reason === \"file-not-exists\") {\n throw new Error(`File not found: ${nativeResult.file}`);\n }\n\n if (nativeResult.reason === \"layout-diff\") {\n return await compareOnCommonCanvas(p1, p2, withDiff, options, state);\n }\n }\n\n const { width, height } = await readIhdrDimensions(p1);\n const totalPixels = width * height;\n\n if (nativeResult.match) {\n return {\n numDiffPixels: 0,\n totalPixels,\n percentDifference: 0,\n diffBuffer: undefined,\n passed: isPassed(0, 0, options),\n differentSizes: false,\n };\n }\n\n const diffBuffer =\n withDiff && diffPath ? await readDiffImage(diffPath, options) : undefined;\n\n const numDiffPixels = nativeResult.diffCount;\n const percentDifference = nativeResult.diffPercentage;\n\n const interpretation = wantInterpret\n ? await interpretBestEffort(p1, p2, options)\n : undefined;\n\n return {\n numDiffPixels,\n totalPixels,\n percentDifference,\n diffBuffer,\n passed: isPassed(percentDifference, numDiffPixels, options),\n differentSizes: false,\n interpretation,\n };\n } finally {\n if (state.tempRoot) {\n await fsp\n .rm(state.tempRoot, { recursive: true, force: true })\n .catch(() => {\n // ignore cleanup errors\n });\n }\n }\n}\n\nasync function readDiffImage(\n diffPath: string,\n options: DiffConfig,\n): Promise<Buffer | undefined> {\n let rawDiff: Buffer;\n try {\n rawDiff = await fsp.readFile(diffPath);\n } catch {\n // blazediff writes no diff image when the images match\n return undefined;\n }\n\n return injectTextMetadata(rawDiff, diffMetadataFor(options));\n}\n\nfunction diffMetadataFor(options: DiffConfig): Record<string, string> {\n const diffMetadata: Record<string, string> = {\n \"cappa.diff.algorithm\": \"pixel\",\n };\n for (const [key, value] of Object.entries(options)) {\n if (value !== undefined) {\n diffMetadata[`cappa.diff.${key}`] = String(value);\n }\n }\n return diffMetadata;\n}\n\n/**\n * The diff for a size change whose padded images match: only background was\n * added or removed. blazediff writes nothing for a match, so this draws one in\n * the same spirit — the image faded out, with the area only one of the two\n * images covers tinted — rather than leave the reviewer a placeholder.\n */\nasync function renderSizeOnlyDiff(\n paddedActualPath: string,\n dimensions: NonNullable<CompareResult[\"dimensions\"]>,\n): Promise<PNG> {\n const image = await PNG.load(paddedActualPath);\n const sharedWidth = Math.min(\n dimensions.expected.width,\n dimensions.actual.width,\n );\n const sharedHeight = Math.min(\n dimensions.expected.height,\n dimensions.actual.height,\n );\n\n const data = image.data;\n for (let y = 0; y < image.height; y++) {\n for (let x = 0; x < image.width; x++) {\n const i = (y * image.width + x) * 4;\n const gray =\n 0.299 * (data[i] ?? 0) +\n 0.587 * (data[i + 1] ?? 0) +\n 0.114 * (data[i + 2] ?? 0);\n const faded = 255 + ((gray - 255) * 0.1 * (data[i + 3] ?? 0)) / 255;\n const outside = x >= sharedWidth || y >= sharedHeight;\n data[i] = outside ? 255 : faded;\n data[i + 1] = outside ? faded * 0.75 : faded;\n data[i + 2] = outside ? faded * 0.75 : faded;\n data[i + 3] = 255;\n }\n }\n\n return image;\n}\n\nasync function interpretBestEffort(\n expectedPath: string,\n actualPath: string,\n options: DiffConfig,\n): Promise<InterpretResult | undefined> {\n try {\n return await interpret(expectedPath, actualPath, undefined, {\n source: \"pixel\",\n threshold: options.threshold,\n antialiasing: options.includeAA ?? false,\n });\n } catch {\n // Interpretation is best-effort; don't fail the comparison.\n return undefined;\n }\n}\n\n/**\n * Compare two images of different sizes on a shared canvas.\n *\n * blazediff refuses a size mismatch outright (`layout-diff`), which used to\n * leave a changed screenshot with no pixel count, no diff image and no\n * regions — exactly the screenshots where something grew or shrank and a\n * reviewer most needs to see where. Padding both to the larger width and\n * height keeps every pixel at its original coordinates, so the diff, the\n * interpretation's region boxes and the review UI all line up with the\n * top-left of either image.\n */\nasync function compareOnCommonCanvas(\n expectedPath: string,\n actualPath: string,\n withDiff: boolean,\n options: DiffConfig,\n state: TempState,\n): Promise<CompareResult> {\n const root = await ensureTempRoot(state);\n const canvas = await writeCommonCanvas(expectedPath, actualPath, root);\n const { dimensions, width, height } = canvas;\n const paddedExpected = canvas.expectedPath;\n const paddedActual = canvas.actualPath;\n const diffPath = withDiff ? path.join(root, \"diff-canvas.png\") : undefined;\n\n let nativeResult: BlazeDiffResult;\n try {\n nativeResult = await blazediffCompare(\n paddedExpected,\n paddedActual,\n diffPath,\n toNativeOptions(options),\n );\n } catch (error) {\n const message = (error as Error).message || \"Unknown error\";\n getLogger().error(message);\n return {\n numDiffPixels: 0,\n totalPixels: 0,\n percentDifference: 0,\n passed: false,\n differentSizes: true,\n dimensions,\n error: message,\n };\n }\n\n const matched = nativeResult.match;\n const numDiffPixels =\n \"diffCount\" in nativeResult ? nativeResult.diffCount : 0;\n const percentDifference =\n \"diffPercentage\" in nativeResult ? nativeResult.diffPercentage : 0;\n\n let diffBuffer: Buffer | undefined;\n if (withDiff && diffPath) {\n if (matched) {\n const image = await renderSizeOnlyDiff(canvas.actualPath, dimensions);\n diffBuffer = injectTextMetadata(\n await image.toBuffer(),\n diffMetadataFor(options),\n );\n } else {\n diffBuffer = await readDiffImage(diffPath, options);\n }\n }\n\n const interpretation =\n !matched && (options as CompareOptions).interpret && withDiff\n ? await interpretBestEffort(paddedExpected, paddedActual, options)\n : undefined;\n\n return {\n numDiffPixels,\n totalPixels: width * height,\n percentDifference,\n diffBuffer,\n passed: false,\n differentSizes: true,\n dimensions,\n interpretation,\n };\n}\n\n/**\n * Save a comparison result diff image to file\n * @param result - Comparison result containing diffBuffer\n * @param outputPath - Path to save the diff image\n */\nexport function saveDiffImage(result: CompareResult, outputPath: string): void {\n if (!result.diffBuffer) {\n throw new Error(\"No diff buffer available in comparison result\");\n }\n\n fs.writeFileSync(outputPath, result.diffBuffer);\n}\n\n/**\n * Quick comparison function that returns only pass/fail\n * @param image1 - Baseline (expected) image (file path or Buffer)\n * @param image2 - Current (actual) image (file path or Buffer). Order matters\n * for `interpret`: content only in `image2` is reported as an addition.\n * @param options - Comparison options\n * @returns Whether the images match\n */\nexport async function imagesMatch(\n image1: string | Buffer,\n image2: string | Buffer,\n options: DiffConfig = {},\n): Promise<boolean> {\n const result = await compareImages(image1, image2, false, options);\n\n return result.passed;\n}\n\n/**\n * Check if the comparison passed based on the options\n * @param percentDifference - Percentage difference between the images\n * @param numDiffPixels - Number of different pixels\n * @param options - Comparison options\n * @returns Whether the comparison passed\n */\nconst isPassed = (\n percentDifference: number,\n numDiffPixels: number,\n options: DiffConfig,\n) => {\n if (options.maxDiffPercentage && options.maxDiffPixels) {\n return (\n percentDifference <= options.maxDiffPercentage &&\n numDiffPixels <= options.maxDiffPixels\n );\n }\n\n if (options.maxDiffPercentage) {\n return percentDifference <= options.maxDiffPercentage;\n }\n\n if (options.maxDiffPixels) {\n return numDiffPixels <= options.maxDiffPixels;\n }\n\n // fallback to 0 pixels\n return numDiffPixels === 0;\n};\n\n/**\n * Create different size png image with all pixels red\n * @returns\n */\nexport async function createDiffSizePngImage(\n width: number,\n height: number,\n): Promise<Buffer> {\n const png = PNG.create(width, height);\n\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const idx = (width * y + x) << 2;\n png.data[idx] = 255; // red\n png.data[idx + 1] = 0; // green\n png.data[idx + 2] = 0; // blue\n png.data[idx + 3] = 255; // alpha\n }\n }\n\n return png.toBuffer();\n}\n","import type { ConfigEnv, PossiblePromise, UserConfig } from \"./types\";\n\n/**\n * Type helper to make it easier to use cappa.config.ts, or a function that returns it. The function receives a ConfigEnv object.\n */\nexport function defineConfig(\n options:\n | PossiblePromise<UserConfig>\n | ((env: ConfigEnv) => PossiblePromise<UserConfig>),\n): typeof options {\n return options;\n}\n","import type { ConsoleMessage, Page } from \"playwright-core\";\n\n/**\n * Minimum severity of browser console output to forward, ordered from most\n * to least severe. Browser `console.warn` is reported by Playwright as\n * `warning`; it maps to `\"warn\"` here.\n */\nexport type ConsoleLogLevel = \"error\" | \"warn\" | \"info\" | \"log\" | \"debug\";\n\n/**\n * `true` forwards every console message at the logger's debug level (the\n * historical behaviour), `false` forwards none, and a {@link ConsoleLogLevel}\n * forwards messages at or above that severity at their matching logger level.\n */\nexport type LogConsoleEvents = boolean | ConsoleLogLevel;\n\nexport const CONSOLE_LOG_LEVELS: readonly ConsoleLogLevel[] = [\n \"error\",\n \"warn\",\n \"info\",\n \"log\",\n \"debug\",\n];\n\ntype ConsoleEventLogger = Record<\n ConsoleLogLevel,\n (message: any, ...args: any[]) => void\n>;\n\n/** Maps a Playwright `ConsoleMessage.type()` onto a {@link ConsoleLogLevel}. */\nexport const toConsoleLogLevel = (\n type: ReturnType<ConsoleMessage[\"type\"]> | string,\n): ConsoleLogLevel => {\n switch (type) {\n case \"error\":\n case \"assert\":\n return \"error\";\n case \"warning\":\n return \"warn\";\n case \"info\":\n return \"info\";\n case \"debug\":\n case \"trace\":\n return \"debug\";\n default:\n return \"log\";\n }\n};\n\nconst severity = (level: ConsoleLogLevel) => CONSOLE_LOG_LEVELS.indexOf(level);\n\n/**\n * Wires a page's `console` and `pageerror` events to `logger` according to\n * `setting`. Uncaught page errors are always forwarded — at error level when\n * a severity threshold is set, at debug level otherwise.\n */\nexport const attachConsoleLogging = (\n page: Pick<Page, \"on\">,\n setting: LogConsoleEvents | undefined,\n logger: ConsoleEventLogger,\n): void => {\n const threshold = setting ?? true;\n\n if (threshold === true) {\n page.on(\"console\", (message) => {\n logger.debug(\"console\", message.text());\n });\n } else if (threshold !== false) {\n page.on(\"console\", (message) => {\n const level = toConsoleLogLevel(message.type());\n if (severity(level) > severity(threshold)) return;\n logger[level](`[browser ${level}]`, message.text());\n });\n }\n\n page.on(\"pageerror\", (error) => {\n if (typeof threshold === \"string\") {\n logger.error(\"[browser pageerror]\", error);\n } else {\n logger.debug(\"pageerror\", error);\n }\n });\n};\n","import type { Page } from \"playwright-core\";\n\n/**\n * Crop a screenshot to the content actually painted on the page.\n *\n * - `false` (default): no crop — the viewport, or the whole page with\n * `fullPage`.\n * - `true`: crop to the content of `document.body`, with the default padding.\n * - an object: crop with a different root or padding.\n */\nexport type CropSetting = boolean | ContentCropOptions;\n\nexport type ContentCropOptions = {\n /**\n * CSS selector of the element whose content is measured. Only what it\n * paints counts, not its own box, background or border.\n * @default \"body\"\n */\n root?: string;\n /**\n * Space kept around the content, in CSS pixels — room for focus rings,\n * text shadows and other paint that has no box of its own.\n * @default 8\n */\n padding?: number;\n};\n\nexport type ResolvedContentCrop = Required<ContentCropOptions>;\n\nexport type CropRect = { x: number; y: number; width: number; height: number };\n\nexport const DEFAULT_CROP_PADDING = 8;\n\n/** The crop to apply, or `undefined` for none. */\nexport const resolveCrop = (\n crop: CropSetting | undefined,\n): ResolvedContentCrop | undefined => {\n if (!crop) return undefined;\n const options = crop === true ? {} : crop;\n return {\n root: options.root ?? \"body\",\n padding: Math.max(0, options.padding ?? DEFAULT_CROP_PADDING),\n };\n};\n\ntype MeasureArgs = { root: string };\n\ntype MeasuredBox = {\n /** Union of everything painted, in document coordinates. */\n box: CropRect | null;\n scrollX: number;\n scrollY: number;\n documentWidth: number;\n documentHeight: number;\n};\n\n/**\n * Runs in the page: the union of the boxes of everything `root` paints, in\n * document coordinates.\n *\n * This is the box of the *ink*, not of the elements: a full-width wrapper\n * `div` with nothing of its own to draw does not count, the text and the\n * button inside it do. An element counts when it draws something itself — a\n * background, a border, an outline, a shadow — or is replaced content (an\n * image, an SVG, a canvas, a form control); text counts by the boxes of its\n * line fragments. Descendants of an element that clips its overflow are\n * clipped to it, and nothing inside a hidden or fully transparent subtree is\n * counted.\n *\n * Portals need no special case: anything a component renders elsewhere in\n * `body` — a popover, a dialog and its backdrop — is measured like the rest.\n *\n * Kept free of syntax a bundler might rewrite with a helper (spread, optional\n * catch binding): Playwright ships this function to the browser as source.\n */\nfunction measurePaintedBox(args: MeasureArgs): MeasuredBox {\n const doc = document;\n const win = window;\n const scrollX = win.scrollX;\n const scrollY = win.scrollY;\n const scrolling = doc.scrollingElement || doc.documentElement;\n const result: MeasuredBox = {\n box: null,\n scrollX: scrollX,\n scrollY: scrollY,\n documentWidth: Math.max(scrolling.scrollWidth, win.innerWidth),\n documentHeight: Math.max(scrolling.scrollHeight, win.innerHeight),\n };\n\n const root = doc.querySelector(args.root);\n if (!root) return result;\n\n type Edges = { l: number; t: number; r: number; b: number };\n const NO_CLIP: Edges = {\n l: -Infinity,\n t: -Infinity,\n r: Infinity,\n b: Infinity,\n };\n let l = Infinity;\n let t = Infinity;\n let r = -Infinity;\n let b = -Infinity;\n\n const add = (rect: DOMRect | DOMRectReadOnly, grow: number, clip: Edges) => {\n if (rect.width <= 0 || rect.height <= 0) return;\n const left = Math.max(rect.left - grow, clip.l);\n const top = Math.max(rect.top - grow, clip.t);\n const right = Math.min(rect.right + grow, clip.r);\n const bottom = Math.min(rect.bottom + grow, clip.b);\n if (right <= left || bottom <= top) return;\n if (left < l) l = left;\n if (top < t) t = top;\n if (right > r) r = right;\n if (bottom > b) b = bottom;\n };\n\n // Computed colours serialise as `rgba(r, g, b, 0)` when transparent, or\n // `color(srgb r g b / 0)` and friends for other colour spaces. Only the\n // alpha is looked at: `rgb(255, 0, 0)` also ends in `, 0)`.\n const visibleColor = (color: string) => {\n if (!color || color === \"transparent\") return false;\n const slash = color.match(/\\/\\s*([\\d.]+)(%?)\\s*\\)$/);\n if (slash) return parseFloat(slash[1] || \"0\") > 0;\n const rgba = color.match(/^rgba\\((?:[^,]+,){3}\\s*([\\d.]+)(%?)\\s*\\)$/);\n if (rgba) return parseFloat(rgba[1] || \"0\") > 0;\n return true;\n };\n\n // Largest distance a shadow list paints outside the box.\n const shadowExtent = (value: string) => {\n if (!value || value === \"none\") return 0;\n let stripped = value;\n let previous = \"\";\n while (previous !== stripped) {\n previous = stripped;\n stripped = stripped.replace(/[a-z-]+\\([^()]*\\)/gi, \" \");\n }\n let extent = 0;\n const shadows = stripped.split(\",\");\n for (let i = 0; i < shadows.length; i++) {\n const shadow = shadows[i] || \"\";\n if (/\\binset\\b/.test(shadow)) continue;\n const lengths = (shadow.match(/-?\\d*\\.?\\d+px/g) || []).map(parseFloat);\n const offset = Math.max(\n Math.abs(lengths[0] || 0),\n Math.abs(lengths[1] || 0),\n );\n const reach = offset + Math.max(0, lengths[2] || 0) + (lengths[3] || 0);\n if (reach > extent) extent = reach;\n }\n return extent;\n };\n\n const REPLACED: Record<string, true> = {\n IMG: true,\n SVG: true,\n CANVAS: true,\n VIDEO: true,\n IFRAME: true,\n EMBED: true,\n OBJECT: true,\n INPUT: true,\n TEXTAREA: true,\n SELECT: true,\n PROGRESS: true,\n METER: true,\n HR: true,\n };\n const SKIPPED: Record<string, true> = {\n SCRIPT: true,\n STYLE: true,\n LINK: true,\n META: true,\n TEMPLATE: true,\n NOSCRIPT: true,\n };\n\n const range = doc.createRange();\n\n const paintsSelf = (style: CSSStyleDeclaration) => {\n if (visibleColor(style.backgroundColor)) return true;\n if (style.backgroundImage && style.backgroundImage !== \"none\") return true;\n const sides = [\"Top\", \"Right\", \"Bottom\", \"Left\"];\n for (let i = 0; i < sides.length; i++) {\n const side = sides[i];\n const width = parseFloat(\n style.getPropertyValue(`border-${side?.toLowerCase()}-width`),\n );\n const kind = style.getPropertyValue(\n `border-${side?.toLowerCase()}-style`,\n );\n const color = style.getPropertyValue(\n `border-${side?.toLowerCase()}-color`,\n );\n if (\n width > 0 &&\n kind !== \"none\" &&\n kind !== \"hidden\" &&\n visibleColor(color)\n )\n return true;\n }\n return false;\n };\n\n const walk = (node: Node, clip: Edges, visible: boolean, isRoot: boolean) => {\n if (node.nodeType === 3) {\n if (!visible || !(node.textContent || \"\").trim()) return;\n range.selectNodeContents(node);\n const rects = range.getClientRects();\n for (let i = 0; i < rects.length; i++) {\n const rect = rects[i];\n if (rect) add(rect, 0, clip);\n }\n return;\n }\n if (node.nodeType !== 1) return;\n\n const el = node as Element;\n if (SKIPPED[el.tagName.toUpperCase()]) return;\n\n const style = win.getComputedStyle(el);\n if (style.display === \"none\") return;\n if (parseFloat(style.opacity) === 0) return;\n\n // `visibility` is inherited but can be overridden by a descendant.\n const selfVisible =\n style.visibility !== \"hidden\" && style.visibility !== \"collapse\";\n const rect = el.getBoundingClientRect();\n\n if (!isRoot && selfVisible) {\n const tag = el.tagName.toUpperCase();\n if (REPLACED[tag]) {\n add(rect, 0, clip);\n } else if (paintsSelf(style)) {\n add(rect, 0, clip);\n }\n\n const shadow = shadowExtent(style.boxShadow);\n if (shadow > 0) add(rect, shadow, clip);\n\n if (style.outlineStyle !== \"none\") {\n const outline =\n (parseFloat(style.outlineWidth) || 0) +\n (parseFloat(style.outlineOffset) || 0);\n if (outline > 0) add(rect, outline, clip);\n }\n\n // An SVG or a form control paints its children inside its own box.\n if (REPLACED[tag]) return;\n }\n\n // Overflow clips descendants to the padding box — except `position:\n // fixed` ones, which escape it; those are approximated as clipped too.\n let childClip = clip;\n const clipsX = style.overflowX !== \"visible\";\n const clipsY = style.overflowY !== \"visible\";\n if (!isRoot && (clipsX || clipsY)) {\n childClip = {\n l: clipsX ? Math.max(clip.l, rect.left) : clip.l,\n t: clipsY ? Math.max(clip.t, rect.top) : clip.t,\n r: clipsX ? Math.min(clip.r, rect.right) : clip.r,\n b: clipsY ? Math.min(clip.b, rect.bottom) : clip.b,\n };\n }\n\n const shadowRoot = (el as HTMLElement).shadowRoot;\n if (shadowRoot) {\n const shadowChildren = shadowRoot.childNodes;\n for (let i = 0; i < shadowChildren.length; i++) {\n const child = shadowChildren[i];\n if (child) walk(child, childClip, selfVisible, false);\n }\n }\n const children = el.childNodes;\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n if (child) walk(child, childClip, selfVisible, false);\n }\n };\n\n walk(root, NO_CLIP, true, true);\n range.detach();\n\n if (r <= l || b <= t) return result;\n\n result.box = {\n x: l + scrollX,\n y: t + scrollY,\n width: r - l,\n height: b - t,\n };\n return result;\n}\n\n/**\n * The clip for a content-cropped screenshot, or `undefined` when there is\n * nothing to crop to (nothing painted, or the root is missing) — the caller\n * then takes the uncropped screenshot rather than fail.\n *\n * Coordinates follow Playwright's `clip`: relative to the document with\n * `fullPage`, to the viewport without it. Edges are rounded outwards to whole\n * pixels so the crop never cuts into anti-aliased edges, and the padding is\n * clamped to the document so it never asks for pixels that do not exist.\n */\nexport async function measureContentClip(\n page: Page,\n crop: ResolvedContentCrop,\n fullPage: boolean,\n): Promise<CropRect | undefined> {\n const measured = await page.evaluate(measurePaintedBox, { root: crop.root });\n if (!measured.box) return undefined;\n\n const { box } = measured;\n let left = Math.max(0, Math.floor(box.x - crop.padding));\n let top = Math.max(0, Math.floor(box.y - crop.padding));\n let right = Math.min(\n measured.documentWidth,\n Math.ceil(box.x + box.width + crop.padding),\n );\n let bottom = Math.min(\n measured.documentHeight,\n Math.ceil(box.y + box.height + crop.padding),\n );\n\n if (!fullPage) {\n const viewport = page.viewportSize();\n const scrollX = Math.floor(measured.scrollX);\n const scrollY = Math.floor(measured.scrollY);\n left = Math.max(0, left - scrollX);\n top = Math.max(0, top - scrollY);\n right -= scrollX;\n bottom -= scrollY;\n if (viewport) {\n right = Math.min(right, viewport.width);\n bottom = Math.min(bottom, viewport.height);\n }\n }\n\n if (right <= left || bottom <= top) return undefined;\n\n return { x: left, y: top, width: right - left, height: bottom - top };\n}\n","/**\n * Run async work over `items` with at most `concurrency` tasks in flight.\n * Preserves failure behavior: the first rejection rejects the returned promise.\n * Results are returned in the same order as the input items.\n */\nexport async function mapWithConcurrency<T, R = void>(\n concurrency: number,\n items: readonly T[],\n fn: (item: T, workerIndex: number) => Promise<R>,\n): Promise<R[]> {\n if (items.length === 0) {\n return [];\n }\n\n const limit = Math.max(1, concurrency);\n const workerCount = Math.min(limit, items.length);\n const results: R[] = new Array(items.length);\n let next = 0;\n\n const worker = async (workerIndex: number): Promise<void> => {\n while (true) {\n const i = next++;\n if (i >= items.length) {\n return;\n }\n const item = items[i];\n if (item === undefined) {\n return;\n }\n results[i] = await fn(item, workerIndex);\n }\n };\n\n await Promise.all(Array.from({ length: workerCount }, (_, i) => worker(i)));\n\n return results;\n}\n","import path from \"node:path\";\n\n/**\n * Screenshot filenames are not a trusted input.\n *\n * A name is whatever a plugin chose, and a plugin may derive it from something\n * it does not control either: `@cappa/plugin-storybook` reads\n * `parameters.cappa.variants[].filename` out of the browser, so the string\n * originates in story-author code. Every name eventually lands in\n * `path.resolve(<bucket dir>, name)`, which honours both absolute paths and\n * `../`, so without a guard a single story could write a PNG anywhere the\n * process can write.\n *\n * Two layers live here: `sanitizeScreenshotFilename` turns a name into a\n * relative path that cannot escape (used where a bad name should degrade rather\n * than fail a run), and `resolveInside` is the hard backstop at the write sink.\n */\n\n/**\n * Whether `target` resolves to something strictly inside `base`.\n *\n * Note this is deliberately stricter than a `startsWith(\"..\")` check on the\n * relative path, which also rejects legitimate names such as `..foo.png`.\n */\nexport function isPathInside(base: string, target: string): boolean {\n const relative = path.relative(base, target);\n\n return (\n relative !== \"\" &&\n relative !== \"..\" &&\n !relative.startsWith(`..${path.sep}`) &&\n !path.isAbsolute(relative)\n );\n}\n\n/**\n * Resolve `filename` inside `base`, rejecting absolute paths and any name that\n * escapes `base`.\n *\n * @param label - The bucket name used in the error message (`actual`, `diff`, …)\n */\nexport function resolveInside(\n base: string,\n filename: string,\n label: string,\n): string {\n const resolved = path.resolve(base, filename);\n\n if (path.isAbsolute(filename) || !isPathInside(base, resolved)) {\n throw new Error(\n `Refusing to resolve screenshot path outside of the ${label} directory: ${filename}`,\n );\n }\n\n return resolved;\n}\n\n/**\n * Turn a screenshot filename into a relative path that stays inside its bucket.\n *\n * Path separators are kept — they are how plugins express folders — but\n * traversal (`..`), no-op (`.`) and empty segments are dropped, backslashes are\n * normalised to `/`, and a Windows drive prefix is removed. Returns an empty\n * string when nothing usable is left, which callers treat as \"no name given\".\n */\nexport function sanitizeScreenshotFilename(filename: string): string {\n const segments = filename\n // Backslashes are separators on Windows, so `..\\\\escape.png` traverses there.\n .replace(/\\\\/g, \"/\")\n .split(\"/\")\n // A NUL byte would make the eventual `writeFile` throw.\n .map((segment) => segment.replace(/\\0/g, \"\").trim())\n .filter((segment) => segment !== \"\" && segment !== \".\" && segment !== \"..\");\n\n // `C:foo.png` is drive-relative on Windows, so the drive letter goes too.\n if (segments[0] && /^[a-zA-Z]:$/.test(segments[0])) {\n segments.shift();\n }\n\n return segments.join(\"/\");\n}\n","import fs from \"node:fs\";\nimport fsp, { glob } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { getLogger } from \"@cappa/logger\";\nimport { imagesMatch } from \"./compare/pixel\";\nimport { extractTextMetadata, injectTextMetadata } from \"./features/png/util\";\nimport { mapWithConcurrency } from \"./mapWithConcurrency\";\nimport { isPathInside, resolveInside } from \"./paths\";\nimport type {\n DiffConfig,\n DiffMetadata,\n DiffOptions,\n Screenshot,\n} from \"./types\";\n\nconst APPROVE_SCREENSHOTS_CONCURRENCY = 8;\n\n/**\n * Map a diff image path to its sidecar metadata path (`.png` -> `.json`).\n */\nexport function toDiffMetaPath(diffImagePath: string): string {\n const ext = path.extname(diffImagePath);\n return ext\n ? `${diffImagePath.slice(0, -ext.length)}.json`\n : `${diffImagePath}.json`;\n}\n\n/**\n * Read a diff metadata sidecar, returning `undefined` when it is missing or\n * cannot be parsed (so callers can degrade gracefully).\n */\nexport async function readDiffMeta(\n diffImagePath: string,\n): Promise<DiffMetadata | undefined> {\n try {\n const raw = await fsp.readFile(toDiffMetaPath(diffImagePath), \"utf8\");\n return JSON.parse(raw) as DiffMetadata;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Class for interacting with the local file system to store the screenshots.\n */\nexport class ScreenshotFileSystem {\n private readonly actual: string;\n private readonly expected: string;\n private readonly diff: string;\n\n constructor(outputDir: string) {\n this.actual = path.resolve(outputDir, \"actual\");\n this.expected = path.resolve(outputDir, \"expected\");\n this.diff = path.resolve(outputDir, \"diff\");\n\n this.ensureParentDirSync(this.actual);\n this.ensureParentDirSync(this.expected);\n this.ensureParentDirSync(this.diff);\n }\n\n clearActual() {\n this.removeDir(this.actual);\n }\n\n clearDiff() {\n this.removeDir(this.diff);\n }\n\n getActualScreenshots(): Promise<string[]> {\n return Array.fromAsync(glob(path.resolve(this.actual, \"**/*.png\")));\n }\n\n getExpectedScreenshots(): Promise<string[]> {\n return Array.fromAsync(glob(path.resolve(this.expected, \"**/*.png\")));\n }\n\n getDiffScreenshots(): Promise<string[]> {\n return Array.fromAsync(glob(path.resolve(this.diff, \"**/*.png\")));\n }\n\n clearActualAndDiff() {\n this.clearActual();\n this.clearDiff();\n }\n\n /**\n * Approve a screenshot based on its actual file path.\n * @param actualFilePath - The path to the actual screenshot file.\n * @returns The paths to the actual, expected, and diff screenshot files.\n */\n async approveFromActualPath(actualFilePath: string) {\n const actualAbsolute = this.resolveActualPath(actualFilePath);\n\n if (!isPathInside(this.actual, actualAbsolute)) {\n throw new Error(\n `Cannot approve screenshot outside of actual directory: ${actualFilePath}`,\n );\n }\n\n return this.approveRelative(path.relative(this.actual, actualAbsolute));\n }\n\n /**\n * Apply baseline updates for grouped screenshots (same rules as `cappa approve`).\n */\n async approveScreenshots(\n screenshots: Screenshot[],\n diff: DiffOptions,\n ): Promise<void> {\n const outputDir = path.dirname(this.actual);\n\n await mapWithConcurrency(\n APPROVE_SCREENSHOTS_CONCURRENCY,\n screenshots,\n (screenshot) => this.approveOneScreenshot(screenshot, outputDir, diff),\n );\n }\n\n private async approveOneScreenshot(\n screenshot: Screenshot,\n outputDir: string,\n diff: DiffOptions,\n ): Promise<void> {\n const logger = getLogger();\n\n logger.debug(`Approving screenshot with category: ${screenshot.category}`);\n\n if (screenshot.category === \"new\") {\n logger.debug(`Approving new screenshot: ${screenshot.actualPath}`);\n await this.approveFromActualPath(\n path.resolve(outputDir, screenshot.actualPath),\n );\n return;\n }\n\n if (screenshot.category === \"deleted\") {\n logger.debug(`Deleting expected screenshot: ${screenshot.expectedPath}`);\n await fsp.unlink(path.resolve(outputDir, screenshot.expectedPath));\n return;\n }\n\n if (screenshot.category === \"changed\") {\n logger.debug(`Deleting diff screenshot: ${screenshot.diffPath}`);\n const diffPath = path.resolve(outputDir, screenshot.diffPath);\n await fsp.unlink(diffPath);\n await fsp.rm(toDiffMetaPath(diffPath), { force: true });\n await this.approveFromActualPath(\n path.resolve(outputDir, screenshot.actualPath),\n );\n return;\n }\n\n if (screenshot.category === \"passed\") {\n if (!screenshot.expectedPath) {\n throw new Error(\"Expected path is required for passed screenshots\");\n }\n\n const matches = await imagesMatch(\n path.resolve(outputDir, screenshot.expectedPath),\n path.resolve(outputDir, screenshot.actualPath),\n diff.type === \"gmsd\"\n ? { threshold: diff.threshold }\n : (diff as DiffConfig),\n );\n\n if (!matches) {\n await this.approveFromActualPath(\n path.resolve(outputDir, screenshot.actualPath),\n );\n }\n }\n }\n\n /**\n * Approve a screenshot based on its name.\n * @param name - The name of the screenshot. Can include '.png' extension.\n * @returns The paths to the actual, expected, and diff screenshot files.\n */\n async approveByName(name: string) {\n const relativeWithExtension = name.endsWith(\".png\") ? name : `${name}.png`;\n\n return this.approveRelative(relativeWithExtension);\n }\n\n /**\n * Approve a screenshot based on a relative path.\n * @param relativePath - The relative path to the screenshot.\n * @returns The paths to the actual, expected, and diff screenshot files.\n */\n private async approveRelative(relativePath: string) {\n const actualPath = path.resolve(this.actual, relativePath);\n const expectedPath = path.resolve(this.expected, relativePath);\n const diffPath = path.resolve(this.diff, relativePath);\n\n await this.ensureParentDir(expectedPath);\n\n await fsp.copyFile(actualPath, expectedPath);\n\n try {\n await fsp.access(diffPath);\n } catch {\n return {\n actualPath,\n expectedPath,\n diffPath,\n };\n }\n\n await this.copyDiffMetadataToExpected(diffPath, expectedPath);\n await fsp.unlink(diffPath);\n await fsp.rm(toDiffMetaPath(diffPath), { force: true });\n\n return {\n actualPath,\n expectedPath,\n diffPath,\n };\n }\n\n private async copyDiffMetadataToExpected(\n diffPath: string,\n expectedPath: string,\n ): Promise<void> {\n const diffExtension = path.extname(diffPath).toLowerCase();\n const expectedExtension = path.extname(expectedPath).toLowerCase();\n\n if (diffExtension !== \".png\" || expectedExtension !== \".png\") {\n return;\n }\n\n try {\n const diffBuffer = await fsp.readFile(diffPath);\n const diffMetadata = extractTextMetadata(diffBuffer);\n\n if (Object.keys(diffMetadata).length === 0) {\n return;\n }\n\n const expectedBuffer = await fsp.readFile(expectedPath);\n const expectedMetadata = extractTextMetadata(expectedBuffer);\n\n const mergedMetadata = {\n ...expectedMetadata,\n ...diffMetadata,\n };\n\n const expectedWithMetadata = injectTextMetadata(\n expectedBuffer,\n mergedMetadata,\n );\n await fsp.writeFile(expectedPath, expectedWithMetadata);\n } catch {\n // Ignore metadata transfer errors to keep approval resilient.\n }\n }\n\n /**\n * Ensure the parent directory of a file exists. If not, it creates it.\n * @param filePath - The path to the file.\n */\n async ensureParentDir(filePath: string) {\n const dir = path.dirname(filePath);\n await fsp.mkdir(dir, { recursive: true });\n }\n\n /**\n * Synchronous version used only during constructor initialization.\n */\n private ensureParentDirSync(filePath: string) {\n const dir = path.dirname(filePath);\n\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n }\n\n /**\n * Remove a directory and all its contents.\n * @param dir - The path to the directory.\n */\n private removeDir(dir: string) {\n if (fs.existsSync(dir)) {\n fs.rmSync(dir, { recursive: true, force: true });\n }\n }\n\n /**\n * Get the actual directory path\n */\n getActualDir(): string {\n return this.actual;\n }\n\n /**\n * Get the expected directory path\n */\n getExpectedDir(): string {\n return this.expected;\n }\n\n /**\n * Get the diff directory path\n */\n getDiffDir(): string {\n return this.diff;\n }\n\n /**\n * Resolve a screenshot filename inside one of the buckets.\n *\n * This is the single sink every read and write funnels through, so it is also\n * where an untrusted filename is stopped: plugin-supplied names (Storybook\n * variant filenames come straight from story code) must never escape the\n * bucket they belong to.\n */\n private resolveBucketPath(\n directory: \"actual\" | \"expected\" | \"diff\",\n filename: string,\n ): string {\n return resolveInside(this[directory], filename, directory);\n }\n\n /**\n * Get the path to an actual screenshot file\n */\n getActualFilePath(filename: string): string {\n return this.resolveBucketPath(\"actual\", filename);\n }\n\n /**\n * Get the path to an expected screenshot file\n */\n getExpectedFilePath(filename: string): string {\n return this.resolveBucketPath(\"expected\", filename);\n }\n\n /**\n * Get the path to a diff screenshot file\n */\n getDiffFilePath(filename: string): string {\n return this.resolveBucketPath(\"diff\", filename);\n }\n\n /**\n * Write a file to the actual directory\n */\n async writeActualFile(filename: string, data: Buffer): Promise<void> {\n const filepath = this.getActualFilePath(filename);\n await this.ensureParentDir(filepath);\n await fsp.writeFile(filepath, data);\n }\n\n /**\n * Write a file to the diff directory\n */\n async writeDiffFile(filename: string, data: Buffer): Promise<void> {\n const filepath = this.getDiffFilePath(filename);\n await this.ensureParentDir(filepath);\n await fsp.writeFile(filepath, data);\n }\n\n /**\n * Remove a screenshot's diff image and metadata sidecar, if any.\n *\n * A run that does not clear `diff/` — a filtered or single-screenshot\n * re-capture — would otherwise leave the previous run's diff behind for a\n * screenshot that now passes, and a screenshot with a diff is `changed`.\n */\n async removeDiffFiles(filename: string): Promise<void> {\n const filepath = this.getDiffFilePath(filename);\n await Promise.all([\n fsp.rm(filepath, { force: true }),\n fsp.rm(toDiffMetaPath(filepath), { force: true }),\n ]);\n }\n\n /**\n * Get the path to a diff metadata sidecar file (`<name>.json`)\n */\n getDiffMetaFilePath(filename: string): string {\n return toDiffMetaPath(this.getDiffFilePath(filename));\n }\n\n /**\n * Write a diff metadata sidecar (`diff/<name>.json`) next to the diff image.\n */\n async writeDiffMetaFile(filename: string, meta: DiffMetadata): Promise<void> {\n const filepath = this.getDiffMetaFilePath(filename);\n await this.ensureParentDir(filepath);\n await fsp.writeFile(filepath, JSON.stringify(meta));\n }\n\n /**\n * Check if an expected file exists\n */\n async hasExpectedFile(filename: string): Promise<boolean> {\n const expectedPath = this.getExpectedFilePath(filename);\n try {\n await fsp.access(expectedPath);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Read an expected file\n */\n async readExpectedFile(filename: string): Promise<Buffer> {\n const expectedPath = this.getExpectedFilePath(filename);\n try {\n return await fsp.readFile(expectedPath);\n } catch {\n throw new Error(`Expected image not found: ${expectedPath}`);\n }\n }\n\n /**\n * Resolve the actual path of a screenshot file.\n * @param filePath - The path to the screenshot file.\n * @returns The actual path of the screenshot file.\n */\n private resolveActualPath(filePath: string) {\n if (path.isAbsolute(filePath)) {\n return filePath;\n }\n\n return path.resolve(this.actual, filePath);\n }\n\n getRelativePath(directory: \"actual\" | \"expected\" | \"diff\", filePath: string) {\n if (!isPathInside(this[directory], filePath)) {\n throw new Error(\n `Cannot resolve relative path outside of ${directory} directory: ${filePath}`,\n );\n }\n\n return path.relative(this[directory], filePath);\n }\n}\n","import fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/**\n * Maps a screenshot back to the capture task that produced it.\n *\n * Nothing on disk carries this. A screenshot's name comes from the filename a\n * plugin chose (`example/button/primary`), while the task id comes from the\n * plugin's own addressing scheme (`example-button--primary` for Storybook) —\n * and there is no rule connecting the two. Without a record written at capture\n * time, \"re-capture this one screenshot\" has no task to ask for, which is\n * exactly how the review UI's re-capture button came to send a name the engine\n * had never heard of.\n *\n * Kept beside `actual/` and `expected/` rather than inside them so it is never\n * mistaken for a screenshot, and dot-prefixed so `@fastify/static` (which is\n * configured with `serveDotFiles: false`) will not serve it.\n */\nexport const MANIFEST_FILENAME = \".cappa-manifest.json\";\n\n/** Bumped only if the on-disk shape changes incompatibly. */\nexport const MANIFEST_VERSION = 1;\n\n/** Where a screenshot came from. */\nexport type ScreenshotOrigin = {\n /** Task id as `discover` produced it — what `startRun` accepts. */\n taskId: string;\n /** Plugin that owns the task. */\n plugin: string;\n};\n\nexport type CaptureManifest = {\n version: number;\n /** Keyed by screenshot name (relative path, no `.png`). */\n screenshots: Record<string, ScreenshotOrigin>;\n};\n\nexport const emptyManifest = (): CaptureManifest => ({\n version: MANIFEST_VERSION,\n screenshots: {},\n});\n\nexport const manifestPath = (outputDir: string): string =>\n path.resolve(outputDir, MANIFEST_FILENAME);\n\n/**\n * The key a capture filename is recorded under.\n *\n * Must match the `name` `groupScreenshots` derives, or a lookup silently\n * misses: the relative path with its `.png` dropped, and separators normalised\n * so a manifest written on Windows is readable on Linux.\n */\nexport const toManifestKey = (filename: string): string =>\n filename\n .split(path.sep)\n .join(\"/\")\n .replace(/\\.png$/i, \"\");\n\nconst isOrigin = (value: unknown): value is ScreenshotOrigin =>\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as ScreenshotOrigin).taskId === \"string\" &&\n typeof (value as ScreenshotOrigin).plugin === \"string\";\n\n/**\n * Read the manifest, or an empty one.\n *\n * Never throws: the manifest is an optimisation, and a missing, truncated or\n * hand-edited file must degrade to \"we do not know where this came from\"\n * rather than break the screenshot index every command depends on.\n */\nexport const readCaptureManifest = async (\n outputDir: string,\n): Promise<CaptureManifest> => {\n try {\n const raw = await fsp.readFile(manifestPath(outputDir), \"utf8\");\n const parsed: unknown = JSON.parse(raw);\n\n if (\n typeof parsed !== \"object\" ||\n parsed === null ||\n (parsed as CaptureManifest).version !== MANIFEST_VERSION\n ) {\n return emptyManifest();\n }\n\n const screenshots = (parsed as CaptureManifest).screenshots;\n if (typeof screenshots !== \"object\" || screenshots === null) {\n return emptyManifest();\n }\n\n const entries = Object.entries(screenshots).filter(([, origin]) =>\n isOrigin(origin),\n );\n\n return {\n version: MANIFEST_VERSION,\n screenshots: Object.fromEntries(entries) as Record<\n string,\n ScreenshotOrigin\n >,\n };\n } catch {\n return emptyManifest();\n }\n};\n\n/**\n * Merge freshly captured origins into whatever the manifest already holds.\n *\n * A run only captures the tasks it was asked for, so existing entries have to\n * survive — otherwise re-capturing one screenshot would strip every other\n * screenshot's origin and disable the button that started it.\n *\n * `knownNames`, when given, is the set of screenshots that currently exist;\n * entries outside it are dropped so renames and deletions do not accumulate\n * forever. New origins are always kept, whether or not they appear in it.\n */\nexport const mergeCaptureManifest = (\n existing: CaptureManifest,\n origins: Record<string, ScreenshotOrigin>,\n knownNames?: Iterable<string>,\n): CaptureManifest => {\n const keep = knownNames ? new Set(knownNames) : undefined;\n\n const merged: Record<string, ScreenshotOrigin> = {};\n\n for (const [name, origin] of Object.entries(existing.screenshots)) {\n if (!keep || keep.has(name)) {\n merged[name] = origin;\n }\n }\n\n for (const [name, origin] of Object.entries(origins)) {\n merged[name] = origin;\n }\n\n return { version: MANIFEST_VERSION, screenshots: merged };\n};\n\n/**\n * Persist `origins`, merged over what is already recorded.\n *\n * Best-effort by design: a read-only or full disk must not turn a successful\n * capture run into a failed one, so a write failure is reported to the caller\n * as `false` rather than thrown.\n */\nexport const recordCaptureOrigins = async (\n outputDir: string,\n origins: Record<string, ScreenshotOrigin>,\n knownNames?: Iterable<string>,\n): Promise<boolean> => {\n try {\n const merged = mergeCaptureManifest(\n await readCaptureManifest(outputDir),\n origins,\n knownNames,\n );\n\n await fsp.mkdir(path.resolve(outputDir), { recursive: true });\n await fsp.writeFile(\n manifestPath(outputDir),\n `${JSON.stringify(merged, null, 2)}\\n`,\n \"utf8\",\n );\n\n return true;\n } catch {\n return false;\n }\n};\n","/** The advice for a refused connection when the config has no `webServer`. */\nexport const NO_WEB_SERVER_HINT =\n \"Start it before capturing, or add a `webServer` entry to cappa.config.ts so cappa starts it for you.\";\n\n/**\n * How a refused connection reads, across the places one surfaces: Node's\n * sockets and `fetch` (`ECONNREFUSED`), Chromium (`net::ERR_CONNECTION_REFUSED`),\n * Firefox (`NS_ERROR_CONNECTION_REFUSED`) and WebKit.\n */\nconst REFUSED_PATTERN =\n /\\bECONNREFUSED\\b|\\bERR_CONNECTION_REFUSED\\b|\\bNS_ERROR_CONNECTION_REFUSED\\b|Could not connect to (?:the )?server|Connection refused/i;\n\nconst URL_PATTERN = /\\bhttps?:\\/\\/[^\\s\"'`<>)\\]]+/i;\n\nexport type RefusedConnection = {\n /** Origin of the URL that refused, when the error names one. */\n origin?: string;\n};\n\nconst toOrigin = (url: string): string | undefined => {\n try {\n // A URL that ends a sentence takes its full stop with it.\n return new URL(url.replace(/[.,;:!?]+$/, \"\")).origin;\n } catch {\n return undefined;\n }\n};\n\n/**\n * Whether `error` — an `Error`, a plain object, or just a message string, as\n * plugins report task failures — is a refused connection.\n *\n * Walks `cause` and `AggregateError.errors`: Node's `fetch` says only\n * \"fetch failed\" and puts `ECONNREFUSED` on its cause, and a plugin that wraps\n * the error in a friendlier one keeps it there too.\n *\n * Works on any plugin's errors, third-party included, because it reads the\n * error rather than asking the plugin.\n */\nexport function findRefusedConnection(\n error: unknown,\n): RefusedConnection | undefined {\n let refused = false;\n let origin: string | undefined;\n let socketOrigin: string | undefined;\n\n const seen = new Set<unknown>();\n const visit = (value: unknown, depth: number) => {\n if (value === null || value === undefined || depth > 8 || seen.has(value)) {\n return;\n }\n seen.add(value);\n\n if (typeof value === \"string\") {\n if (REFUSED_PATTERN.test(value)) {\n refused = true;\n }\n const url = value.match(URL_PATTERN)?.[0];\n origin ??= url ? toOrigin(url) : undefined;\n return;\n }\n\n if (typeof value !== \"object\") {\n return;\n }\n\n const record = value as {\n message?: unknown;\n code?: unknown;\n address?: unknown;\n port?: unknown;\n cause?: unknown;\n errors?: unknown;\n };\n\n if (record.code === \"ECONNREFUSED\") {\n refused = true;\n if (typeof record.address === \"string\" && record.port !== undefined) {\n const host = record.address.includes(\":\")\n ? `[${record.address}]`\n : record.address;\n socketOrigin ??= `http://${host}:${record.port}`;\n }\n }\n\n visit(record.message, depth + 1);\n visit(record.cause, depth + 1);\n if (Array.isArray(record.errors)) {\n for (const inner of record.errors) {\n visit(inner, depth + 1);\n }\n }\n };\n\n visit(error, 0);\n\n if (!refused) {\n return undefined;\n }\n\n // A URL in a message is what the user configured; a socket address is what\n // it resolved to. The first is the one they will recognise.\n const resolved = origin ?? socketOrigin;\n return resolved ? { origin: resolved } : {};\n}\n\nconst LOOPBACK_HOSTS = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\", \"0.0.0.0\"]);\n\n/**\n * Whether two origins name the same server.\n *\n * Loopback spellings are interchangeable: a plugin configured with\n * `localhost:6006` and a socket error reporting `127.0.0.1:6006` are the same\n * Storybook.\n */\nexport function sameServer(a: string, b: string): boolean {\n try {\n const left = new URL(a);\n const right = new URL(b);\n const port = (url: URL) =>\n url.port || (url.protocol === \"https:\" ? \"443\" : \"80\");\n\n if (port(left) !== port(right)) {\n return false;\n }\n return (\n left.hostname === right.hostname ||\n (LOOPBACK_HOSTS.has(left.hostname) && LOOPBACK_HOSTS.has(right.hostname))\n );\n } catch {\n return false;\n }\n}\n","import { glob } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { PluginTask } from \"../plugin\";\nimport type { PluginCaptureResult, TaskStatus } from \"./types\";\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\n/**\n * Decide whether a plugin's `execute` result represents a failed screenshot.\n *\n * Plugins return loosely-shaped objects, so this inspects the three signals that\n * matter: an explicit `error`, an explicit `success: false`, or a missing\n * `filepath` on a task that was not skipped.\n */\nexport const didScreenshotFail = (result: unknown): boolean => {\n if (!isObject(result)) {\n return false;\n }\n\n if (\"error\" in result && result.error != null) {\n return true;\n }\n\n if (\"success\" in result) {\n const { success } = result as PluginCaptureResult;\n if (success === false) {\n return true;\n }\n }\n\n if (\"filepath\" in result) {\n const { filepath, skipped } = result as PluginCaptureResult;\n if (!filepath && skipped !== true) {\n return true;\n }\n }\n\n return false;\n};\n\n/**\n * Map a plugin result onto the status shown in the UI.\n *\n * Mirrors the screenshot categories: a capture with no baseline is `new`, a\n * failing comparison is `changed`, and anything `didScreenshotFail` flags for\n * another reason is `failed`.\n */\nexport const toTaskStatus = (result: unknown): TaskStatus => {\n if (!isObject(result)) {\n return \"passed\";\n }\n\n const typed = result as PluginCaptureResult;\n\n if (typed.skipped === true) {\n return \"skipped\";\n }\n\n if (\"error\" in typed && typed.error != null) {\n return \"failed\";\n }\n\n if (typed.isNew === true) {\n return \"new\";\n }\n\n if (typed.success === false) {\n return \"changed\";\n }\n\n if (didScreenshotFail(typed)) {\n return \"failed\";\n }\n\n return \"passed\";\n};\n\n/** Restrict `tasks` to those whose id matches the glob `filter`. */\nexport function filterTasks(tasks: PluginTask[], filter: string): PluginTask[] {\n return tasks.filter((task) => path.matchesGlob(task.id, filter));\n}\n\n/** Restrict `tasks` to an explicit set of ids. */\nexport function selectTasks(\n tasks: PluginTask[],\n taskIds: readonly string[],\n): PluginTask[] {\n const wanted = new Set(taskIds);\n return tasks.filter((task) => wanted.has(task.id));\n}\n\n/**\n * Baselines in `expected/` that have no counterpart in `actual/` — screenshots\n * that existed when the baseline was approved but were not captured this run.\n */\nexport async function getDeletedScreenshots(\n outputDir: string,\n): Promise<string[]> {\n const actualDir = path.resolve(outputDir, \"actual\");\n const expectedDir = path.resolve(outputDir, \"expected\");\n\n const [actualFiles, expectedFiles] = await Promise.all([\n Array.fromAsync(glob(path.join(actualDir, \"**/*.png\"))),\n Array.fromAsync(glob(path.join(expectedDir, \"**/*.png\"))),\n ]);\n\n const actualRelative = new Set(\n actualFiles.map((p) => path.relative(actualDir, p)),\n );\n\n return expectedFiles\n .map((p) => path.relative(expectedDir, p))\n .filter((rel) => !actualRelative.has(rel));\n}\n","import type { PluginTask, PluginWatch } from \"../plugin\";\n\n/**\n * Lifecycle of a single capture run.\n *\n * ```\n * idle → discovering → running → (completed | failed | cancelled)\n * ```\n */\nexport type RunState =\n | \"idle\"\n | \"discovering\"\n | \"running\"\n | \"completed\"\n | \"failed\"\n | \"cancelled\";\n\n/**\n * Terminal state of an individual capture task.\n *\n * `passed` / `changed` / `new` mirror the screenshot categories; `failed` means\n * the plugin reported a failure (see `didScreenshotFail`); `skipped` means the\n * plugin deliberately skipped the task.\n */\nexport type TaskStatus =\n | \"pending\"\n | \"running\"\n | \"passed\"\n | \"changed\"\n | \"new\"\n | \"failed\"\n | \"skipped\";\n\n/** A discovered, runnable capture task together with the plugin that owns it. */\nexport type Target = {\n id: string;\n url: string;\n plugin: string;\n};\n\n/**\n * Why a run was started, when it was not started by hand.\n *\n * Purely informational — the runner does nothing with it. It rides along on the\n * request so a run list can say \"this one came from saving Button.stories.tsx\"\n * without a second lookup or a parallel event stream.\n */\nexport type RunTrigger = {\n source: \"watch\";\n /** Changed files that triggered the run, relative to the watch root. */\n files: string[];\n};\n\n/**\n * Describes which subset of the discovered tasks a run should capture.\n *\n * `filter` and `taskIds` compose: a task must satisfy both when both are given.\n */\nexport type StartRunRequest = {\n /** Restrict the run to these plugin names. Omit to run every plugin. */\n plugins?: string[];\n /** Glob matched against task ids (`path.matchesGlob` semantics). */\n filter?: string;\n /** Explicit task ids to capture. Ids not discovered are ignored. */\n taskIds?: string[];\n /**\n * Clear `actual/` and `diff/` before capturing.\n *\n * Always `true` for a full CLI run. A UI re-capturing a single screenshot must\n * pass `false`, otherwise the rest of the run's output is destroyed.\n * @default true\n */\n clearActual?: boolean;\n /** What started this run, when it was not a person. */\n trigger?: RunTrigger;\n};\n\n/** An error flattened into something that survives a structured-clone or JSON. */\nexport type SerializedError = {\n name: string;\n message: string;\n stack?: string;\n};\n\nexport const toSerializedError = (error: unknown): SerializedError => {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack,\n };\n }\n\n return { name: \"Error\", message: String(error) };\n};\n\n/**\n * The shape plugins return from `execute`. Every field is optional because\n * plugins are free to return whatever they want — only these keys are\n * interpreted (by `didScreenshotFail`) and surfaced in failure reports.\n */\nexport type PluginCaptureResult = {\n success?: boolean;\n skipped?: boolean;\n isNew?: boolean;\n error?: unknown;\n filepath?: string;\n storyId?: string;\n storyName?: string;\n [key: string]: unknown;\n};\n\n/** A task that did not produce a passing screenshot. */\nexport type TaskFailure = {\n taskId: string;\n taskUrl: string;\n pluginName: string;\n result: PluginCaptureResult;\n};\n\n/** Per-task record kept for the lifetime of a run. */\nexport type TaskRecord = {\n id: string;\n url: string;\n plugin: string;\n status: TaskStatus;\n durationMs?: number;\n result?: PluginCaptureResult;\n};\n\n/** Coarse, serializable view of a run — enough to render a list row. */\nexport type RunSummary = {\n id: string;\n state: RunState;\n request: StartRunRequest;\n startedAt: number;\n finishedAt?: number;\n durationMs?: number;\n totalTasks: number;\n completedTasks: number;\n failedTasks: number;\n /** Baselines in `expected/` with no matching `actual/` after the run. */\n deletedScreenshots: string[];\n /** `false` when discovery produced nothing (or everything was filtered out). */\n anyTasksRan: boolean;\n error?: SerializedError;\n};\n\n/** Full run view, including every task and failure. */\nexport type RunDetail = RunSummary & {\n tasks: TaskRecord[];\n failures: TaskFailure[];\n};\n\n/**\n * Levels the run event stream can carry.\n *\n * `success` is here because `ScreenshotTool` uses it — \"Screenshot saved\",\n * \"Screenshot passed visual comparison\" — and those lines have to reach a\n * remote client, not just the host's own terminal. Adding a level is a wire\n * change: this one lands before `PROTOCOL_VERSION` 1 has ever been published,\n * so it is part of what v1 will be. A later addition needs a version bump.\n */\nexport type RunLogLevel = \"debug\" | \"info\" | \"warn\" | \"error\" | \"success\";\n\ntype RunEventBase = {\n /** Monotonic, 1-based, per run. Used for SSE `Last-Event-ID` replay. */\n seq: number;\n runId: string;\n at: number;\n};\n\n/**\n * Everything an observer needs to follow a run. Emitted synchronously, so a\n * consumer forwarding these to a logger keeps ordering with logs written\n * directly by `ScreenshotTool`.\n */\nexport type RunEvent =\n | (RunEventBase & { type: \"run:start\"; request: StartRunRequest })\n | (RunEventBase & { type: \"discover:start\"; plugins: string[] })\n | (RunEventBase & {\n type: \"discover:plugin\";\n plugin: string;\n taskCount: number;\n })\n | (RunEventBase & {\n type: \"discover:complete\";\n targets: Target[];\n totalTasks: number;\n })\n | (RunEventBase & {\n type: \"filter:applied\";\n filter?: string;\n taskIds?: string[];\n plugins: { plugin: string; before: number; after: number }[];\n })\n | (RunEventBase & {\n type: \"plugin:start\";\n plugin: string;\n taskCount: number;\n })\n | (RunEventBase & {\n type: \"task:start\";\n plugin: string;\n taskId: string;\n url: string;\n })\n | (RunEventBase & {\n type: \"task:complete\";\n plugin: string;\n taskId: string;\n url: string;\n status: TaskStatus;\n completed: number;\n total: number;\n durationMs: number;\n result?: PluginCaptureResult;\n })\n | (RunEventBase & {\n type: \"plugin:complete\";\n plugin: string;\n resultCount: number;\n failed: boolean;\n })\n | (RunEventBase & {\n type: \"log\";\n level: RunLogLevel;\n message: string;\n args: unknown[];\n })\n | (RunEventBase & { type: \"run:complete\"; summary: RunSummary })\n | (RunEventBase & { type: \"run:error\"; error: SerializedError })\n | (RunEventBase & { type: \"run:cancelled\" });\n\nexport type RunEventType = RunEvent[\"type\"];\n\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown\n ? Omit<T, K>\n : never;\n\n/**\n * A run event before the runner stamps it with `seq`, `runId` and `at`.\n *\n * `Omit` must distribute over the union here — a plain `Omit<RunEvent, …>`\n * collapses to the keys every member shares, which is just `type`.\n */\nexport type EmittableRunEvent = DistributiveOmit<\n RunEvent,\n \"seq\" | \"runId\" | \"at\"\n>;\n\nexport type RunEventListener = (event: RunEvent) => void;\n\n/** Plugin shape the runner needs. Kept structural so tests can pass fakes. */\nexport type RunnablePlugin = {\n name: string;\n description?: string;\n discover: (screenshotTool: any) => Promise<PluginTask[]>;\n execute: (\n task: PluginTask,\n page: any,\n screenshotTool: any,\n context: any,\n ) => Promise<unknown>;\n initPage?: (page: any, screenshotTool: any) => Promise<unknown>;\n /** How this plugin maps a changed file onto tasks. Absent means \"cannot\". */\n watch?: PluginWatch;\n};\n","import { randomUUID } from \"node:crypto\";\nimport { relative } from \"node:path\";\nimport { ScreenshotFileSystem } from \"../filesystem\";\nimport { mapWithConcurrency } from \"../mapWithConcurrency\";\nimport type { PluginTask } from \"../plugin\";\nimport type ScreenshotTool from \"../screenshot\";\nimport {\n recordCaptureOrigins,\n type ScreenshotOrigin,\n toManifestKey,\n} from \"../screenshots/manifest\";\nimport {\n findRefusedConnection,\n NO_WEB_SERVER_HINT,\n} from \"../webServer/unreachable\";\nimport {\n didScreenshotFail,\n filterTasks,\n getDeletedScreenshots,\n selectTasks,\n toTaskStatus,\n} from \"./tasks\";\nimport type {\n EmittableRunEvent,\n PluginCaptureResult,\n RunDetail,\n RunEvent,\n RunEventListener,\n RunLogLevel,\n RunnablePlugin,\n RunState,\n RunSummary,\n StartRunRequest,\n Target,\n TaskFailure,\n TaskRecord,\n} from \"./types\";\nimport { toSerializedError } from \"./types\";\n\nexport type CaptureRunnerOptions = {\n /**\n * An **already initialised** `ScreenshotTool`. The runner never calls `init()`\n * or `close()` — browser lifetime belongs to the caller, so a long-lived\n * server can keep one browser warm across many runs while the CLI can keep\n * its init/close-per-run shape.\n */\n screenshotTool: ScreenshotTool;\n plugins: RunnablePlugin[];\n /** Defaults to the screenshot tool's output directory. */\n outputDir?: string;\n /**\n * Filesystem used to clear `actual/` and `diff/`. Defaults to the screenshot\n * tool's own instance, falling back to one built from `outputDir`.\n */\n fileSystem?: ScreenshotFileSystem;\n /** Stable run id. Generated when omitted. */\n id?: string;\n /** Injectable clock, for deterministic tests. */\n now?: () => number;\n /**\n * Runs after `run:start` and before anything is cleared or discovered —\n * the engine starts its web servers here. Its log lines become run events,\n * and a rejection fails the run with `actual/` still intact.\n */\n prepare?: (\n log: (level: RunLogLevel, message: string) => void,\n ) => Promise<void>;\n /**\n * The advice appended to a refused connection, given the origin that\n * refused when the error names one. Defaults to suggesting a `webServer`.\n */\n explainUnreachable?: (origin: string | undefined) => string;\n};\n\n/**\n * Orchestrates a single capture run: discover → filter → execute, emitting\n * typed events as it goes.\n *\n * Deliberately free of any presentation or process concerns — no logger calls,\n * no `chalk`, no `process.exit`. Consumers render the events however they like:\n * the CLI writes them to the terminal, the server streams them over SSE.\n *\n * One instance represents one run. Create a new one per run.\n */\nexport class CaptureRunner {\n readonly id: string;\n\n private readonly screenshotTool: ScreenshotTool;\n private readonly plugins: RunnablePlugin[];\n private readonly outputDir: string;\n private readonly fileSystem: ScreenshotFileSystem;\n private readonly now: () => number;\n private readonly prepare: CaptureRunnerOptions[\"prepare\"];\n private readonly explainUnreachable: (origin: string | undefined) => string;\n private readonly listeners = new Set<RunEventListener>();\n private readonly controller = new AbortController();\n\n private seq = 0;\n private state: RunState = \"idle\";\n private request: StartRunRequest = {};\n private startedAt = 0;\n private finishedAt: number | undefined;\n private error: unknown;\n private anyTasksRan = false;\n private deletedScreenshots: string[] = [];\n private readonly taskRecords = new Map<string, TaskRecord>();\n private readonly failures: TaskFailure[] = [];\n private started = false;\n\n /**\n * Which task currently owns each pooled page.\n *\n * Tasks run concurrently, one per page, so the page is what disambiguates\n * the capture sink's reports. Populated only while a task is executing.\n */\n private readonly taskByPage = new Map<unknown, ScreenshotOrigin>();\n /** Screenshot name → the task that captured it, for the capture manifest. */\n private readonly capturedOrigins = new Map<string, ScreenshotOrigin>();\n\n constructor(options: CaptureRunnerOptions) {\n this.screenshotTool = options.screenshotTool;\n this.plugins = options.plugins;\n this.outputDir = options.outputDir ?? options.screenshotTool.outputDir;\n this.fileSystem =\n options.fileSystem ??\n options.screenshotTool.filesystem ??\n new ScreenshotFileSystem(this.outputDir);\n this.id = options.id ?? randomUUID();\n this.now = options.now ?? (() => Date.now());\n this.prepare = options.prepare;\n this.explainUnreachable =\n options.explainUnreachable ?? (() => NO_WEB_SERVER_HINT);\n }\n\n /** Subscribe to run events. Returns an unsubscribe function. */\n on(listener: RunEventListener): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n get signal(): AbortSignal {\n return this.controller.signal;\n }\n\n /**\n * Request cancellation. In-flight tasks finish (Playwright gives us no safe\n * mid-screenshot abort), but no further tasks are started.\n */\n abort(): void {\n if (this.state === \"completed\" || this.state === \"failed\") {\n return;\n }\n this.controller.abort();\n }\n\n getSummary(): RunSummary {\n const tasks = [...this.taskRecords.values()];\n const completedTasks = tasks.filter(\n (task) => task.status !== \"pending\" && task.status !== \"running\",\n ).length;\n\n return {\n id: this.id,\n state: this.state,\n request: this.request,\n startedAt: this.startedAt,\n finishedAt: this.finishedAt,\n durationMs:\n this.finishedAt === undefined\n ? undefined\n : this.finishedAt - this.startedAt,\n totalTasks: tasks.length,\n completedTasks,\n failedTasks: this.failures.length,\n deletedScreenshots: this.deletedScreenshots,\n anyTasksRan: this.anyTasksRan,\n error:\n this.error === undefined ? undefined : toSerializedError(this.error),\n };\n }\n\n getDetail(): RunDetail {\n return {\n ...this.getSummary(),\n tasks: [...this.taskRecords.values()],\n failures: [...this.failures],\n };\n }\n\n /**\n * Whether the run produced at least one failing screenshot or detected a\n * deleted baseline — the condition the CLI exits non-zero on.\n */\n get hasScreenshotFailure(): boolean {\n return this.failures.length > 0 || this.deletedScreenshots.length > 0;\n }\n\n private emit(event: EmittableRunEvent): void {\n this.seq += 1;\n const full = {\n ...event,\n seq: this.seq,\n runId: this.id,\n at: this.now(),\n } as RunEvent;\n\n for (const listener of this.listeners) {\n try {\n listener(full);\n } catch {\n // A misbehaving observer must never take down the run.\n }\n }\n }\n\n private log(level: RunLogLevel, message: string, ...args: unknown[]): void {\n this.emit({ type: \"log\", level, message, args });\n }\n\n /**\n * Run the capture. Resolves with the final detail; rejects if a plugin threw,\n * after emitting `run:error`.\n */\n async run(request: StartRunRequest = {}): Promise<RunDetail> {\n if (this.started) {\n throw new Error(`Run ${this.id} has already been started`);\n }\n this.started = true;\n\n this.request = request;\n this.startedAt = this.now();\n this.emit({ type: \"run:start\", request });\n\n // For the duration of the run, the tool's own output becomes part of the\n // event stream rather than going straight to whatever logger this process\n // happens to have. That is what lets a client watching a remote run see\n // \"Screenshot saved\" and the retry warnings at all.\n this.attachToolLogSink();\n this.attachToolCaptureSink();\n\n try {\n try {\n if (this.prepare) {\n // Not `idle`: starting the app can take as long as a build, and a\n // client polling the run should see it working.\n this.state = \"discovering\";\n await this.prepare((level, message) => this.log(level, message));\n }\n\n if (request.clearActual ?? true) {\n this.log(\"debug\", `Cleaning output directory: ${this.outputDir}`);\n this.fileSystem.clearActual();\n this.fileSystem.clearDiff();\n }\n\n const pluginTasks = await this.discover(request);\n\n if (!this.controller.signal.aborted) {\n await this.execute(pluginTasks);\n }\n } catch (thrown) {\n const error = this.toUnreachableError(thrown) ?? thrown;\n this.error = error;\n this.state = \"failed\";\n this.finishedAt = this.now();\n this.emit({ type: \"run:error\", error: toSerializedError(error) });\n throw error;\n }\n\n await this.collectDeleted();\n\n // Before the terminal event, not after: consumers refresh their\n // screenshot index the moment they see `run:complete`, and a manifest\n // written after that would leave the re-capture button dark until the\n // next refresh.\n await this.persistCaptureOrigins();\n\n this.finishedAt = this.now();\n this.state = this.controller.signal.aborted ? \"cancelled\" : \"completed\";\n\n if (this.state === \"cancelled\") {\n this.emit({ type: \"run:cancelled\" });\n }\n\n const summary = this.getSummary();\n this.emit({ type: \"run:complete\", summary });\n\n return this.getDetail();\n } finally {\n this.detachToolLogSink();\n this.detachToolCaptureSink();\n // Runs after the terminal event on purpose: a cancelled or failed run\n // still captured something, and the origins it did record are what make\n // those screenshots re-capturable.\n await this.persistCaptureOrigins();\n }\n }\n\n /**\n * Route `ScreenshotTool`'s log output through this run's events.\n *\n * Guarded rather than called outright: tests inject minimal stand-ins for the\n * tool, and a fake without the method should not fail a run.\n */\n private attachToolLogSink(): void {\n this.screenshotTool.setLogSink?.((level, message, ...args) => {\n this.log(level, message, ...args);\n });\n }\n\n private detachToolLogSink(): void {\n this.screenshotTool.setLogSink?.(null);\n }\n\n /**\n * Record which task produces which screenshot file.\n *\n * Guarded like the log sink: tests inject minimal tool stand-ins, and one\n * without the method must not fail a run — it only loses the manifest.\n */\n private attachToolCaptureSink(): void {\n this.screenshotTool.setCaptureSink?.((page, filename) => {\n const origin = this.taskByPage.get(page);\n if (origin) {\n this.capturedOrigins.set(toManifestKey(filename), origin);\n }\n });\n }\n\n private detachToolCaptureSink(): void {\n this.screenshotTool.setCaptureSink?.(null);\n this.taskByPage.clear();\n }\n\n /**\n * Write what this run learned about screenshot origins.\n *\n * Idempotent, because it is called once on the happy path and again from\n * `run`'s `finally` for the paths that never reach it. Existing entries are\n * preserved and only names that no longer exist on disk are dropped, so a\n * run of one task does not erase every other screenshot's origin.\n */\n private async persistCaptureOrigins(): Promise<void> {\n if (this.capturedOrigins.size === 0) {\n return;\n }\n\n const origins = Object.fromEntries(this.capturedOrigins);\n this.capturedOrigins.clear();\n\n let knownNames: string[] | undefined;\n try {\n const [actual, expected] = await Promise.all([\n this.fileSystem.getActualScreenshots(),\n this.fileSystem.getExpectedScreenshots(),\n ]);\n knownNames = [\n ...actual.map((file) =>\n toManifestKey(relative(this.fileSystem.getActualDir(), file)),\n ),\n ...expected.map((file) =>\n toManifestKey(relative(this.fileSystem.getExpectedDir(), file)),\n ),\n ];\n } catch {\n // Could not enumerate what exists, so prune nothing rather than\n // discarding entries that are probably still valid.\n knownNames = undefined;\n }\n\n const written = await recordCaptureOrigins(\n this.outputDir,\n origins,\n knownNames,\n );\n\n if (!written) {\n this.log(\n \"debug\",\n \"Could not write the capture manifest; re-capturing a single screenshot may be unavailable.\",\n );\n }\n }\n\n private async discover(\n request: StartRunRequest,\n ): Promise<{ plugin: RunnablePlugin; tasks: PluginTask[] }[]> {\n this.state = \"discovering\";\n\n const wanted = request.plugins ? new Set(request.plugins) : undefined;\n const plugins = wanted\n ? this.plugins.filter((plugin) => wanted.has(plugin.name))\n : this.plugins;\n\n this.emit({\n type: \"discover:start\",\n plugins: plugins.map((plugin) => plugin.name),\n });\n\n const pluginTasks = await Promise.all(\n plugins.map(async (plugin) => {\n this.log(\"debug\", `Discovering tasks for plugin: ${plugin.name}`);\n const tasks = await plugin.discover(this.screenshotTool);\n this.emit({\n type: \"discover:plugin\",\n plugin: plugin.name,\n taskCount: tasks.length,\n });\n return { plugin, tasks };\n }),\n );\n\n const targets: Target[] = pluginTasks.flatMap(({ plugin, tasks }) =>\n tasks.map((task) => ({\n id: task.id,\n url: task.url,\n plugin: plugin.name,\n })),\n );\n\n this.emit({\n type: \"discover:complete\",\n targets,\n totalTasks: targets.length,\n });\n\n if (request.filter === undefined && request.taskIds === undefined) {\n return pluginTasks;\n }\n\n const applied: { plugin: string; before: number; after: number }[] = [];\n\n for (const entry of pluginTasks) {\n const before = entry.tasks.length;\n let tasks = entry.tasks;\n\n if (request.filter !== undefined) {\n tasks = filterTasks(tasks, request.filter);\n }\n if (request.taskIds !== undefined) {\n tasks = selectTasks(tasks, request.taskIds);\n }\n\n entry.tasks = tasks;\n applied.push({ plugin: entry.plugin.name, before, after: tasks.length });\n }\n\n this.emit({\n type: \"filter:applied\",\n filter: request.filter,\n taskIds: request.taskIds,\n plugins: applied,\n });\n\n return pluginTasks;\n }\n\n private async execute(\n pluginTasks: { plugin: RunnablePlugin; tasks: PluginTask[] }[],\n ): Promise<void> {\n this.state = \"running\";\n\n for (const { plugin, tasks } of pluginTasks) {\n if (tasks.length === 0) {\n continue;\n }\n\n if (this.controller.signal.aborted) {\n return;\n }\n\n this.anyTasksRan = true;\n let pluginHasFailure = false;\n\n for (const task of tasks) {\n this.taskRecords.set(task.id, {\n id: task.id,\n url: task.url,\n plugin: plugin.name,\n status: \"pending\",\n });\n }\n\n this.emit({\n type: \"plugin:start\",\n plugin: plugin.name,\n taskCount: tasks.length,\n });\n\n this.log(\n \"debug\",\n `Processing ${tasks.length} tasks with concurrency ${this.screenshotTool.concurrency}`,\n );\n\n let completedTasks = 0;\n const pageContexts = new Map<number, unknown>();\n\n const results = await mapWithConcurrency(\n this.screenshotTool.concurrency,\n tasks,\n async (task, workerIndex) => {\n if (this.controller.signal.aborted) {\n return undefined;\n }\n\n const page = this.screenshotTool.getPageFromPool(workerIndex);\n\n if (!pageContexts.has(workerIndex) && plugin.initPage) {\n pageContexts.set(\n workerIndex,\n await plugin.initPage(page, this.screenshotTool),\n );\n }\n const context = pageContexts.get(workerIndex);\n\n const record = this.taskRecords.get(task.id);\n if (record) {\n record.status = \"running\";\n }\n\n this.emit({\n type: \"task:start\",\n plugin: plugin.name,\n taskId: task.id,\n url: task.url,\n });\n\n const taskStart = this.now();\n // Claim the page for this task so the capture sink can attribute the\n // files written during `execute` — including variants, whose\n // filenames only the tool ever sees.\n this.taskByPage.set(page, { taskId: task.id, plugin: plugin.name });\n let result: unknown;\n try {\n result = await plugin.execute(\n task,\n page,\n this.screenshotTool,\n context,\n );\n } finally {\n this.taskByPage.delete(page);\n }\n const durationMs = this.now() - taskStart;\n\n completedTasks++;\n\n result = this.explainTaskError(result);\n\n const failed = didScreenshotFail(result);\n const status = toTaskStatus(result);\n const typedResult = result as PluginCaptureResult | undefined;\n\n if (record) {\n record.status = status;\n record.durationMs = durationMs;\n record.result = typedResult;\n }\n\n if (failed) {\n pluginHasFailure = true;\n this.failures.push({\n taskId: task.id,\n taskUrl: task.url,\n result: typedResult ?? {},\n pluginName: plugin.name,\n });\n }\n\n this.emit({\n type: \"task:complete\",\n plugin: plugin.name,\n taskId: task.id,\n url: task.url,\n status,\n completed: completedTasks,\n total: tasks.length,\n durationMs,\n result: typedResult,\n });\n\n return result;\n },\n );\n\n this.emit({\n type: \"plugin:complete\",\n plugin: plugin.name,\n resultCount: results.length,\n failed: pluginHasFailure,\n });\n }\n }\n\n /**\n * The message for a refused connection: where, and what to do about it.\n *\n * Identical for every task that hit the same server — no task id, no path —\n * so a report can collapse 300 of them into one line.\n */\n private unreachableMessage(origin: string | undefined): string {\n const where = origin ?? \"the app under test\";\n return `Cannot reach ${where}: connection refused. ${this.explainUnreachable(origin)}`;\n }\n\n private toUnreachableError(error: unknown): Error | undefined {\n const refused = findRefusedConnection(error);\n if (!refused) {\n return undefined;\n }\n return new Error(this.unreachableMessage(refused.origin), {\n cause: error,\n });\n }\n\n /**\n * Replace a plugin's refused-connection error with the explained one.\n *\n * Reads the result rather than asking the plugin, so third-party plugins get\n * the same message without an API change.\n */\n private explainTaskError(result: unknown): unknown {\n const error = (result as PluginCaptureResult | undefined)?.error;\n if (error === undefined || error === null) {\n return result;\n }\n\n const refused = findRefusedConnection(error);\n if (!refused) {\n return result;\n }\n\n return {\n ...(result as PluginCaptureResult),\n error: this.unreachableMessage(refused.origin),\n };\n }\n\n private async collectDeleted(): Promise<void> {\n if (!this.anyTasksRan) {\n return;\n }\n\n try {\n this.deletedScreenshots = await getDeletedScreenshots(this.outputDir);\n } catch (error) {\n this.log(\"warn\", \"Could not check for deleted screenshots:\", error);\n }\n }\n}\n\nexport type { TaskRecord };\n","import path from \"node:path\";\nimport { getLogger, type Logger } from \"@cappa/logger\";\nimport {\n type Browser,\n type BrowserContext,\n chromium,\n firefox,\n type Page,\n type PageScreenshotOptions,\n webkit,\n} from \"playwright-core\";\nimport {\n compareImagesGMSD,\n type CompareResult as GMSDCompareResult,\n} from \"./compare/gmsd\";\nimport {\n compareImages,\n createDiffSizePngImage,\n type CompareResult as PixelCompareResult,\n} from \"./compare/pixel\";\nimport type { LogConsoleEvents } from \"./consoleEvents\";\nimport { type CropSetting, measureContentClip, resolveCrop } from \"./crop\";\nimport { ScreenshotFileSystem } from \"./filesystem\";\nimport { sanitizeScreenshotFilename } from \"./paths\";\nimport type { RunLogLevel } from \"./runner/types\";\nimport type {\n DiffConfig,\n DiffConfigGMSD,\n DiffOptions,\n DiffOptionsGMSD,\n DiffOptionsPixel,\n ScreenshotOptions,\n ScreenshotSettings,\n ScreenshotVariant,\n ScreenshotVariantWithUrl,\n} from \"./types\";\n\nconst defaultPixelDiffConfig: DiffOptionsPixel = {\n type: \"pixel\",\n threshold: 0.1,\n includeAA: false,\n fastBufferCheck: true,\n maxDiffPixels: 0,\n maxDiffPercentage: 0,\n};\n\nconst defaultGMSDDiffConfig: DiffOptionsGMSD = {\n type: \"gmsd\",\n threshold: 0.1,\n downsample: 0,\n c: 170,\n};\n\nexport interface ScreenshotCaptureDetails {\n filename: string;\n filepath?: string;\n comparisonResult?: PixelCompareResult | GMSDCompareResult;\n diffImagePath?: string;\n skipped?: boolean;\n}\n\nexport interface ScreenshotVariantCaptureDetails\n extends ScreenshotCaptureDetails {\n id: string;\n label?: string;\n}\n\nexport interface ScreenshotCaptureResult {\n base: ScreenshotCaptureDetails;\n variants: ScreenshotVariantCaptureDetails[];\n}\n\nexport interface ScreenshotCaptureExtras {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n variants?: Record<\n string,\n {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n diff?: DiffOptions;\n }\n >;\n /**\n * Optional diff configuration override applied to this capture.\n * Merged on top of the global ScreenshotTool diff config.\n */\n diff?: DiffOptions;\n /**\n * Skip navigating to the base URL before capturing the base screenshot.\n * Use this when the page is already at the correct URL and in a stable state,\n * to avoid the redundant navigation.\n */\n skipBaseNavigation?: boolean;\n /**\n * Optional callback invoked after each navigation (variants only, or base when\n * skipBaseNavigation is false) to wait for visual stability before capturing.\n */\n waitForStability?: (page: Page) => Promise<void>;\n /**\n * Timestamp (from `performance.now()`) marking when the screenshot process\n * started — i.e. when the browser first navigated to the page. When provided,\n * the logged duration covers the full journey: navigation → stability waits →\n * capture. When omitted, timing begins at the capture step itself.\n */\n captureStart?: number;\n}\n\n/** The logger surface `ScreenshotTool` actually uses. */\nexport type ScreenshotLogger = Pick<\n Logger,\n \"debug\" | \"info\" | \"warn\" | \"error\" | \"success\"\n>;\n\n/** Receives this tool's log output instead of the global logger. */\nexport type ScreenshotLogSink = (\n level: RunLogLevel,\n message: string,\n ...args: unknown[]\n) => void;\n\n/**\n * Notified whenever this tool writes a screenshot.\n *\n * `page` identifies the caller: a run captures several tasks in parallel, one\n * per pooled page, so the page is the only thing that ties a filename back to\n * the task that asked for it.\n */\nexport type ScreenshotCaptureSink = (page: Page, filename: string) => void;\n\nconst LOG_SINK_LEVELS = [\n \"debug\",\n \"info\",\n \"warn\",\n \"error\",\n \"success\",\n] as const satisfies readonly RunLogLevel[];\n\n/** A logger-shaped object that forwards every call to `sink`. */\nconst toSinkLogger = (sink: ScreenshotLogSink): ScreenshotLogger =>\n Object.fromEntries(\n LOG_SINK_LEVELS.map((level) => [\n level,\n (message: unknown, ...args: unknown[]) =>\n sink(level, String(message), ...args),\n ]),\n ) as ScreenshotLogger;\n\nclass ScreenshotTool {\n browserType: \"chromium\" | \"firefox\" | \"webkit\";\n headless: boolean;\n viewport: { width: number; height: number };\n fullPage: boolean;\n /** Default content crop; a screenshot's own `crop` overrides it. */\n crop: CropSetting;\n outputDir: string;\n browser: Browser | null = null;\n context: BrowserContext | null = null;\n page: Page | null = null;\n concurrency: number;\n contexts: BrowserContext[] = [];\n pages: Page[] = [];\n diff: DiffOptions;\n /**\n * Where this tool's own output goes.\n *\n * Normally the global logger. While a `CaptureRunner` owns the tool it is\n * swapped for a shim that forwards into the run's event stream instead — see\n * `setLogSink`.\n */\n logger: ScreenshotLogger;\n retries: number;\n filesystem: ScreenshotFileSystem;\n logConsoleEvents: LogConsoleEvents;\n connectionTimeout: number;\n private defaultUserAgent = \"\";\n /** The real logger, kept so `setLogSink(null)` restores the same instance. */\n private readonly baseLogger: ScreenshotLogger;\n /** Set while a `CaptureRunner` owns this tool — see `setCaptureSink`. */\n private captureSink: ScreenshotCaptureSink | null = null;\n\n constructor(options: {\n browserType?: \"chromium\" | \"firefox\" | \"webkit\";\n headless?: boolean;\n viewport?: { width: number; height: number };\n fullPage?: boolean;\n crop?: CropSetting;\n outputDir?: string;\n diff?: DiffOptions;\n retries?: number;\n concurrency?: number;\n logConsoleEvents?: LogConsoleEvents;\n connectionTimeout?: number;\n }) {\n this.browserType = options.browserType || \"chromium\";\n this.headless = options.headless !== false; // Default to headless\n this.viewport = options.viewport || { width: 1920, height: 1080 };\n this.fullPage = options.fullPage ?? true;\n this.crop = options.crop ?? false;\n this.outputDir = options.outputDir || \"./screenshots\";\n this.diff = this.resolveDiffOptions(options.diff);\n this.concurrency = Math.max(1, options.concurrency || 1);\n this.logConsoleEvents = options.logConsoleEvents ?? true;\n this.connectionTimeout = options.connectionTimeout ?? 20000;\n\n this.baseLogger = getLogger();\n this.logger = this.baseLogger;\n this.retries = options.retries || 2;\n this.filesystem = new ScreenshotFileSystem(this.outputDir);\n }\n\n /**\n * Send this tool's own log output to `sink` instead of the global logger.\n *\n * `ScreenshotTool` writes lines a user expects to see — \"Screenshot saved\",\n * \"Screenshot passed visual comparison\", the retry warnings — straight to the\n * logger. That is fine in-process and useless over a network: with the\n * browser on another machine those lines would stay in the *host's* terminal\n * while the client showed a run with no commentary. A `CaptureRunner` installs\n * a sink for the duration of a run so they travel as `log` events instead.\n *\n * Pass `null` to restore the real logger.\n */\n setLogSink(sink: ScreenshotLogSink | null): void {\n this.logger = sink ? toSinkLogger(sink) : this.baseLogger;\n }\n\n /**\n * Report every screenshot this tool writes to `sink`.\n *\n * A `CaptureRunner` installs one for the duration of a run so it can record\n * which task produced which file. Nothing else can know: a plugin picks the\n * filename inside `execute` and is free to derive it from the task however\n * it likes, so the only reliable observation point is the write itself —\n * which also catches variants, whose filenames the plugin never states.\n *\n * Pass `null` to stop reporting.\n */\n setCaptureSink(sink: ScreenshotCaptureSink | null): void {\n this.captureSink = sink;\n }\n\n private resolveDiffOptions(diff?: DiffOptions): DiffOptions {\n if (diff?.type === \"gmsd\") {\n return { ...defaultGMSDDiffConfig, ...diff };\n }\n\n return { ...defaultPixelDiffConfig, ...diff, type: \"pixel\" };\n }\n\n private mergeDiffOptions(override?: DiffOptions): DiffOptions {\n const base = this.resolveDiffOptions(this.diff);\n\n if (!override) {\n return base;\n }\n\n if (override.type === \"gmsd\" || base.type === \"gmsd\") {\n const gmsdBase: DiffOptionsGMSD =\n base.type === \"gmsd\" ? base : defaultGMSDDiffConfig;\n\n return { ...gmsdBase, ...override, type: \"gmsd\" };\n }\n\n return {\n ...(base as DiffOptionsPixel),\n ...(override as DiffOptionsPixel),\n type: \"pixel\",\n };\n }\n\n /**\n * Initialize playwright and page\n */\n async init() {\n // Launch browser based on type\n const browserMap = {\n chromium,\n firefox,\n webkit,\n };\n\n const browserClass = browserMap[this.browserType];\n if (!browserClass) {\n throw new Error(`Unsupported browser type: ${this.browserType}`);\n }\n\n const browser = await browserClass.launch({\n headless: this.headless,\n });\n\n if (!browser)\n throw new Error(\"Something went wrong with starting the browser.\");\n\n this.browser = browser;\n\n const tempCtx = await browser.newContext();\n const tempPage = await tempCtx.newPage();\n this.defaultUserAgent = await tempPage.evaluate(() => navigator.userAgent);\n await tempCtx.close();\n\n await this.createContexts();\n }\n\n /**\n * Create the pool of browser contexts and pages.\n */\n private async createContexts() {\n const browser = this.browser;\n if (!browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n // Create N contexts and pages in parallel\n const results = await Promise.all(\n Array.from({ length: this.concurrency }, async () => {\n const context = await browser.newContext({\n reducedMotion: \"reduce\",\n deviceScaleFactor: 2,\n userAgent: `${this.defaultUserAgent} CappaStorybook`,\n viewport: this.viewport,\n });\n const page = await context.newPage();\n return { context, page };\n }),\n );\n\n this.contexts = results.map((r) => r.context);\n this.pages = results.map((r) => r.page);\n\n // Backward compatibility\n this.context = this.contexts[0] ?? null;\n this.page = this.pages[0] ?? null;\n }\n\n /**\n * Closes every context and page, leaving the browser process running.\n */\n async closeContexts() {\n for (const context of this.contexts) {\n await context.close();\n }\n\n this.contexts = [];\n this.pages = [];\n this.context = null;\n this.page = null;\n }\n\n /**\n * Throw away the current contexts and build a fresh pool on the same browser.\n *\n * A long-lived process that keeps the browser warm between capture runs must\n * call this first: contexts accumulate cookies, storage and scroll position,\n * and a screenshot taken against leaked state is not the screenshot the CLI\n * would have taken with a fresh browser.\n */\n async recycleContexts() {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n await this.closeContexts();\n await this.createContexts();\n }\n\n /**\n * Closes browser\n * If not closed, the process will not exit\n *\n * Tolerant of a browser that is already gone. A Ctrl-C in a terminal is\n * delivered to the whole foreground process group, Chromium included, so by\n * the time a signal handler gets here every context can already be dead and\n * closing one throws `Failed to find context with id …`. Letting that escape\n * turns a clean shutdown into an uncaught exception, which is the one thing\n * teardown must never do.\n */\n async close() {\n try {\n await this.closeContexts();\n } catch (error) {\n getLogger().debug(\"Error closing browser contexts:\", error);\n this.contexts = [];\n this.pages = [];\n this.context = null;\n this.page = null;\n }\n\n if (this.browser) {\n try {\n await this.browser.close();\n } catch (error) {\n getLogger().debug(\"Error closing the browser:\", error);\n }\n this.browser = null;\n }\n }\n\n /**\n * Navigates to a URL with \"domcontentloaded\" waitUntil\n */\n async goTo(page: Page, url: string) {\n if (!this.context) {\n throw new Error(\"Browser not initialized\");\n }\n await page.goto(url, {\n waitUntil: \"domcontentloaded\",\n timeout: this.connectionTimeout,\n });\n }\n\n /**\n * Takes a screenshot of the page\n */\n async takeScreenshot(\n page: Page,\n filename: string,\n options: ScreenshotSettings,\n ) {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n if (options.skip) {\n return;\n }\n\n try {\n // Generate filename - save to actual directory\n const filepath = this.filesystem.getActualFilePath(filename);\n\n // Ensure parent directories exist before taking screenshot\n await this.filesystem.ensureParentDir(filepath);\n\n await this.shoot(page, options, filepath);\n\n this.logger.success(`Screenshot saved: ${filepath}`);\n\n return filepath;\n } catch (error) {\n this.logger.error(\n `Error taking screenshot of ${page.url()}:`,\n (error as Error).message,\n );\n throw error;\n }\n }\n\n /**\n * Take one screenshot with `options`, under its viewport and after its\n * delay, cropped to the page's content when `crop` asks for it.\n *\n * The crop is measured right before the shot, after the delay, so it sees\n * the same render the screenshot does — and every retry measures afresh.\n */\n private async shoot(\n page: Page,\n options: ScreenshotSettings,\n filepath?: string,\n ): Promise<Buffer> {\n const fullPage = options.fullPage ?? this.fullPage;\n const crop = resolveCrop(options.crop ?? this.crop);\n\n return this.withViewport(page, options.viewport, async () => {\n if (options.delay) {\n this.logger.debug(\n `Waiting ${options.delay}ms before taking screenshot`,\n );\n await page.waitForTimeout(options.delay);\n }\n\n const clip = crop\n ? await measureContentClip(page, crop, fullPage)\n : undefined;\n if (crop && !clip) {\n this.logger.debug(\n `Nothing painted inside \"${crop.root}\" to crop to; taking the uncropped screenshot`,\n );\n }\n\n const screenshotOptions = {\n path: filepath,\n fullPage,\n clip,\n type: \"png\" as const,\n timeout: 60000,\n mask: options.mask,\n omitBackground: options.omitBackground,\n scale: \"css\" as const,\n animations: \"disabled\",\n caret: \"hide\",\n } satisfies PageScreenshotOptions;\n\n return page.screenshot(screenshotOptions);\n });\n }\n\n /**\n * Sets the viewport size and executes the action, ensuring the original viewport is restored\n * even if the action throws an error.\n */\n private async withViewport<T>(\n page: Page,\n viewport: ScreenshotSettings[\"viewport\"],\n action: () => Promise<T>,\n ): Promise<T> {\n if (!viewport) {\n return action();\n }\n\n const previousViewport = page.viewportSize();\n\n // Check if the new viewport is the same as the current one\n if (\n previousViewport &&\n previousViewport.width === viewport.width &&\n previousViewport.height === viewport.height\n ) {\n return action();\n }\n\n await page.setViewportSize(viewport);\n\n try {\n return await action();\n } finally {\n // Always restore the original viewport, even if the action throws an error\n if (previousViewport) {\n await page.setViewportSize(previousViewport);\n }\n }\n }\n\n /**\n * Takes a screenshot and returns the buffer (for comparison purposes)\n */\n async takeScreenshotBuffer(\n page: Page,\n options: ScreenshotSettings,\n ): Promise<Buffer> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n if (options.skip) {\n throw new Error(\"Screenshot skipped\");\n }\n\n try {\n // Take screenshot without saving to file\n return await this.shoot(page, options);\n } catch (error) {\n this.logger.error(\n `Error taking screenshot of ${page.url()}:`,\n (error as Error).message,\n );\n throw error;\n }\n }\n\n async takeScreenshotWithComparison(\n page: Page,\n filename: string,\n referenceImage: string | Buffer,\n options: ScreenshotSettings & {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n },\n diffOverride?: DiffOptions,\n ): Promise<{\n screenshotPath: string;\n comparisonResult: PixelCompareResult | GMSDCompareResult;\n diffImagePath?: string;\n }> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n try {\n // Generate filename and take screenshot - save to actual directory\n const filepath = this.filesystem.getActualFilePath(filename);\n\n const screenshotSettings: ScreenshotSettings = {\n fullPage: options.fullPage ?? this.fullPage,\n crop: options.crop,\n mask: options.mask,\n omitBackground: options.omitBackground,\n delay: options.delay,\n viewport: options.viewport,\n };\n\n const retryScreenshot = await this.retryScreenshot(\n page,\n referenceImage,\n screenshotSettings,\n diffOverride,\n );\n\n if (!retryScreenshot.screenshotPath) {\n throw new Error(\"Screenshot buffer is undefined\");\n }\n\n // Save screenshot to actual directory\n await this.filesystem.writeActualFile(\n filename,\n retryScreenshot.screenshotPath,\n );\n this.logger.debug(`Actual screenshot saved: ${filepath}`);\n\n if (retryScreenshot.passed) {\n this.logger.success(`Screenshot passed visual comparison`);\n } else {\n this.logger.error(`Screenshot failed visual comparison`);\n }\n\n let diffImagePath: string | undefined;\n\n // Save diff image if requested and there are differences\n if (\n options.saveDiffImage &&\n retryScreenshot.comparisonResult?.diffBuffer &&\n !retryScreenshot.passed\n ) {\n const diffFilename = options.diffImageFilename || filename;\n // Save to diff directory\n diffImagePath = this.filesystem.getDiffFilePath(diffFilename);\n\n await this.filesystem.writeDiffFile(\n diffFilename,\n retryScreenshot.comparisonResult.diffBuffer,\n );\n\n this.logger.debug(`Diff image saved: ${diffImagePath}`);\n\n // When interpretation is enabled, persist diff stats + interpretation as\n // a sidecar so the review UI and CLI can surface them after rebuilding\n // state from disk. Skipped entirely otherwise so no extra files appear\n // for users who have not opted in (pixel only).\n const result = retryScreenshot.comparisonResult;\n if (\"numDiffPixels\" in result && result.interpretation) {\n await this.filesystem.writeDiffMetaFile(diffFilename, {\n numDiffPixels: result.numDiffPixels,\n percentDifference: result.percentDifference,\n interpretation: result.interpretation,\n });\n }\n }\n\n // Size changes are diffed on a padded canvas, so the diff written above\n // already shows where the images diverge. The placeholder is only for a\n // comparison that produced no diff image at all (e.g. the padded images\n // matched because only fully transparent rows were added).\n if (\n retryScreenshot.comparisonResult !== null &&\n typeof retryScreenshot.comparisonResult === \"object\" &&\n \"differentSizes\" in retryScreenshot.comparisonResult &&\n retryScreenshot.comparisonResult.differentSizes\n ) {\n this.logger.warn(`Screenshot has different sizes than reference image`);\n\n if (!diffImagePath) {\n const diffFilename = options.diffImageFilename || filename;\n diffImagePath = this.filesystem.getDiffFilePath(diffFilename);\n const diffBuffer = await createDiffSizePngImage(200, 200);\n\n await this.filesystem.writeDiffFile(diffFilename, diffBuffer);\n\n this.logger.debug(`Diff Size image saved: ${diffImagePath}`);\n }\n }\n\n return {\n screenshotPath: filepath,\n comparisonResult: retryScreenshot.comparisonResult,\n diffImagePath,\n };\n } catch (error) {\n this.logger.error(\n `Error taking screenshot with comparison of ${page.url()}:`,\n (error as Error).message,\n );\n throw error;\n }\n }\n\n async retryScreenshot(\n page: Page,\n referenceImage: string | Buffer,\n options: ScreenshotSettings,\n diffOverride?: DiffOptions,\n ) {\n const diffConfig = this.mergeDiffOptions(diffOverride);\n\n for (let i = 0; i < this.retries; i++) {\n try {\n const screenshotBuffer = await this.takeScreenshotBuffer(page, {\n ...options,\n delay: this.getIncBackoffDelay(i, options.delay || 0),\n });\n\n if (!screenshotBuffer) {\n throw new Error(\"Screenshot buffer is undefined\");\n }\n\n const comparisonResult =\n diffConfig.type === \"gmsd\"\n ? await compareImagesGMSD(\n referenceImage,\n screenshotBuffer,\n true,\n diffConfig as DiffConfigGMSD,\n )\n : await compareImages(\n referenceImage,\n screenshotBuffer,\n true,\n diffConfig as DiffConfig,\n );\n\n // last retry\n if (i === this.retries - 1 && !comparisonResult.passed) {\n this.logger.error(\n `Failed to match screenshot after ${this.retries} retries`,\n );\n return {\n screenshotPath: screenshotBuffer,\n comparisonResult,\n passed: false,\n };\n }\n\n if (comparisonResult.passed) {\n return {\n screenshotPath: screenshotBuffer,\n comparisonResult,\n passed: true,\n };\n } else {\n const summary =\n \"numDiffPixels\" in comparisonResult\n ? `${comparisonResult.differentSizes ? \"different image sizes, \" : \"\"}${comparisonResult.numDiffPixels} pixels different (${comparisonResult.percentDifference.toFixed(2)}%)`\n : `gmsd score ${comparisonResult.gmsd.toFixed(4)}`;\n\n this.logger.warn(\n `Comparison did not match. Retrying in ${this.getIncBackoffDelay(i + 1, options.delay || 0)}ms... \\nComparison result: ${summary}`,\n );\n }\n } catch (error) {\n this.logger.error(\n `Error taking screenshot after ${i + 1} retries:`,\n (error as Error).message,\n );\n }\n }\n\n return {\n screenshotPath: null,\n comparisonResult: null,\n passed: false,\n };\n }\n\n /**\n * Resolve the filename a variant is written under.\n *\n * An explicit `variant.filename` wins, but it is sanitized first: for\n * `@cappa/plugin-storybook` it arrives from the browser as a story parameter,\n * so it is story-author input and could otherwise carry `../` or an absolute\n * path into the write sink. A name left empty by sanitization falls back to\n * the derived one.\n */\n getVariantFilename(filename: string, variant: ScreenshotVariant): string {\n if (variant.filename) {\n const safeFilename = sanitizeScreenshotFilename(variant.filename);\n\n if (safeFilename !== variant.filename) {\n this.logger.warn(\n `Variant filename \"${variant.filename}\" is not a valid screenshot path, using \"${safeFilename || \"the derived name\"}\" instead`,\n );\n }\n\n if (safeFilename) {\n return safeFilename;\n }\n }\n\n const parsed = path.parse(filename);\n const sanitizedId = variant.id\n .trim()\n .replace(/[^a-zA-Z0-9_-]+/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n const suffix = sanitizedId || \"variant\";\n const ext = parsed.ext || \".png\";\n const variantName = `${parsed.name}--${suffix}${ext}`;\n\n return parsed.dir ? path.join(parsed.dir, variantName) : variantName;\n }\n\n /**\n * Captures a single screenshot with the given options\n */\n private async captureSingleScreenshot(\n page: Page,\n filename: string,\n options: ScreenshotSettings,\n extras: {\n saveDiffImage?: boolean;\n diffImageFilename?: string;\n diff?: DiffOptions;\n captureStart?: number;\n } = {},\n ): Promise<ScreenshotCaptureDetails> {\n const result: ScreenshotCaptureDetails = { filename };\n\n if (options.skip) {\n result.skipped = true;\n return result;\n }\n\n const start = extras.captureStart ?? performance.now();\n const saveDiff = extras.saveDiffImage ?? false;\n const diffFilename = extras.diffImageFilename ?? filename;\n const diffOverride = extras.diff;\n\n // This capture decides the screenshot's diff afresh: whatever the last run\n // left in `diff/` describes an image that is about to be replaced.\n await this.filesystem.removeDiffFiles(diffFilename);\n\n if (!(await this.filesystem.hasExpectedFile(filename))) {\n this.logger.debug(\n `Expected image not found for ${filename}, taking screenshot`,\n );\n\n result.filepath = await this.takeScreenshot(page, filename, options);\n } else {\n const { screenshotPath, comparisonResult, diffImagePath } =\n await this.takeScreenshotWithComparison(\n page,\n filename,\n this.filesystem.getExpectedFilePath(filename),\n {\n ...options,\n saveDiffImage: saveDiff,\n diffImageFilename: diffFilename,\n },\n diffOverride,\n );\n\n result.filepath = screenshotPath;\n result.comparisonResult = comparisonResult;\n result.diffImagePath = diffImagePath;\n }\n\n const duration = Math.round(performance.now() - start);\n this.logger.debug(`${filename} captured in ${duration}ms`);\n\n // Reported after the capture, so a task that threw on the way here does not\n // claim a file it never wrote. A failing sink is the observer's problem and\n // must not fail the capture.\n try {\n this.captureSink?.(page, filename);\n } catch {\n // ignored\n }\n\n return result;\n }\n\n async capture(\n page: Page,\n filename: string,\n options: ScreenshotOptions,\n extras: ScreenshotCaptureExtras = {},\n ): Promise<ScreenshotCaptureResult> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n const { variants = [], ...baseOptions } = options;\n const baseResult: ScreenshotCaptureDetails = { filename };\n const variantResults: ScreenshotVariantCaptureDetails[] = [];\n\n const baseSaveDiff = extras.saveDiffImage ?? false;\n const baseDiffFilename = extras.diffImageFilename ?? filename;\n const baseDiffOverride = extras.diff;\n\n if (baseOptions.skip) {\n return {\n base: { ...baseResult, skipped: true },\n variants: variants.map((variant) => ({\n id: variant.id,\n label: variant.label,\n filename: this.getVariantFilename(filename, variant),\n skipped: true,\n })),\n };\n }\n\n // Capture base screenshot\n const baseCaptureResult = await this.captureSingleScreenshot(\n page,\n filename,\n baseOptions,\n {\n saveDiffImage: baseSaveDiff,\n diffImageFilename: baseDiffFilename,\n diff: baseDiffOverride,\n captureStart: extras.captureStart,\n },\n );\n\n baseResult.filepath = baseCaptureResult.filepath;\n baseResult.comparisonResult = baseCaptureResult.comparisonResult;\n baseResult.diffImagePath = baseCaptureResult.diffImagePath;\n baseResult.skipped = baseCaptureResult.skipped;\n\n for (const variant of variants) {\n const variantFilename = this.getVariantFilename(filename, variant);\n const variantOptions: ScreenshotSettings = {\n ...baseOptions,\n ...variant.options,\n };\n\n const variantResult: ScreenshotVariantCaptureDetails = {\n id: variant.id,\n label: variant.label,\n filename: variantFilename,\n };\n\n if (variantOptions.skip) {\n variantResult.skipped = true;\n variantResults.push(variantResult);\n continue;\n }\n\n const variantExtra = extras.variants?.[variant.id];\n const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;\n const variantDiffFilename =\n variantExtra?.diffImageFilename ?? variantFilename;\n const variantDiffOverride = variantExtra?.diff ?? baseDiffOverride;\n\n const variantCaptureResult = await this.captureSingleScreenshot(\n page,\n variantFilename,\n variantOptions,\n {\n saveDiffImage: variantSaveDiff,\n diffImageFilename: variantDiffFilename,\n diff: variantDiffOverride,\n },\n );\n\n variantResult.filepath = variantCaptureResult.filepath;\n variantResult.comparisonResult = variantCaptureResult.comparisonResult;\n variantResult.diffImagePath = variantCaptureResult.diffImagePath;\n variantResult.skipped = variantCaptureResult.skipped;\n\n variantResults.push(variantResult);\n }\n\n return {\n base: baseResult,\n variants: variantResults,\n };\n }\n\n /**\n * Applies SVG and UI optimizations for screenshots\n */\n private async applyScreenshotOptimizations(page: Page) {\n await page.addStyleTag({\n content: `\n *, *::before, *::after {\n -moz-animation: none !important;\n -moz-transition: none !important;\n transition: none !important; \n animation: none !important;\n }\n *, input, textarea { caret-color: transparent !important }\n *:focus { outline: none !important }\n *:focus-visible { outline: none !important }\n *:focus-within { outline: none !important }\n * { text-rendering: optimizeLegibility !important }\n ::-webkit-scrollbar { display: none !important }\n html { scroll-behavior: auto !important }\n svg, svg * {\n shape-rendering: crispEdges !important;\n text-rendering: geometricPrecision !important;\n vector-effect: non-scaling-stroke !important;\n }\n img { image-rendering: crisp-edges !important }\n `,\n });\n }\n\n /**\n * Captures screenshots for multiple variants, each with their own URL\n */\n async captureWithVariants(\n page: Page,\n baseFilename: string,\n baseUrl: string,\n baseOptions: ScreenshotSettings,\n variants: ScreenshotVariantWithUrl[],\n extras: ScreenshotCaptureExtras = {},\n ): Promise<ScreenshotCaptureResult> {\n if (!this.browser) {\n throw new Error(\"Browser not initialized\");\n }\n\n const baseResult: ScreenshotCaptureDetails = { filename: baseFilename };\n const variantResults: ScreenshotVariantCaptureDetails[] = [];\n\n const baseSaveDiff = extras.saveDiffImage ?? false;\n const baseDiffFilename = extras.diffImageFilename ?? baseFilename;\n const baseDiffOverride = extras.diff;\n\n // Capture base screenshot\n let baseStart: number;\n if (!extras.skipBaseNavigation) {\n baseStart = performance.now();\n getLogger().debug(`Going to base URL: ${baseUrl}`);\n await page.goto(baseUrl, { timeout: this.connectionTimeout });\n await this.applyScreenshotOptimizations(page);\n await extras.waitForStability?.(page);\n } else {\n baseStart = performance.now();\n }\n\n const baseCaptureResult = await this.captureSingleScreenshot(\n page,\n baseFilename,\n baseOptions,\n {\n saveDiffImage: baseSaveDiff,\n diffImageFilename: baseDiffFilename,\n diff: baseDiffOverride,\n captureStart: extras.captureStart ?? baseStart,\n },\n );\n\n baseResult.filepath = baseCaptureResult.filepath;\n baseResult.comparisonResult = baseCaptureResult.comparisonResult;\n baseResult.diffImagePath = baseCaptureResult.diffImagePath;\n baseResult.skipped = baseCaptureResult.skipped;\n\n // Capture variant screenshots\n for (const variant of variants) {\n const variantFilename = this.getVariantFilename(baseFilename, variant);\n const variantOptions: ScreenshotSettings = {\n ...baseOptions,\n ...variant.options,\n };\n\n const variantResult: ScreenshotVariantCaptureDetails = {\n id: variant.id,\n label: variant.label,\n filename: variantFilename,\n };\n\n if (variantOptions.skip) {\n variantResult.skipped = true;\n variantResults.push(variantResult);\n continue;\n }\n\n // Navigate to variant URL and apply optimizations\n const variantStart = performance.now();\n getLogger().debug(`Going to variant URL: ${variant.url}`);\n await page.goto(variant.url, { timeout: this.connectionTimeout });\n await this.applyScreenshotOptimizations(page);\n await extras.waitForStability?.(page);\n\n const variantExtra = extras.variants?.[variant.id];\n const variantSaveDiff = variantExtra?.saveDiffImage ?? baseSaveDiff;\n const variantDiffFilename =\n variantExtra?.diffImageFilename ?? variantFilename;\n const variantDiffOverride = variantExtra?.diff ?? baseDiffOverride;\n\n const variantCaptureResult = await this.captureSingleScreenshot(\n page,\n variantFilename,\n variantOptions,\n {\n saveDiffImage: variantSaveDiff,\n diffImageFilename: variantDiffFilename,\n diff: variantDiffOverride,\n captureStart: variantStart,\n },\n );\n\n variantResult.filepath = variantCaptureResult.filepath;\n variantResult.comparisonResult = variantCaptureResult.comparisonResult;\n variantResult.diffImagePath = variantCaptureResult.diffImagePath;\n variantResult.skipped = variantCaptureResult.skipped;\n\n variantResults.push(variantResult);\n }\n\n return {\n base: baseResult,\n variants: variantResults,\n };\n }\n\n /**\n * Gets the exponential backoff delay\n */\n getIncBackoffDelay(i: number, delay: number): number {\n return i > 0 ? 500 * 2 ** (i - 1) + (delay || 0) : 0;\n }\n\n /**\n * Get a page from the pool by index\n */\n getPageFromPool(index: number): Page {\n if (index < 0) {\n throw new Error(`Page index ${index} must be non-negative`);\n }\n\n if (index >= this.pages.length) {\n throw new Error(\n `Page index ${index} exceeds pool size ${this.pages.length}`,\n );\n }\n\n if (!this.pages[index]) {\n throw new Error(`Page index ${index} is undefined`);\n }\n\n return this.pages[index];\n }\n}\n\nexport default ScreenshotTool;\n","import path from \"node:path\";\n\n/**\n * Where agent review keeps its state, inside `outputDir`.\n *\n * Its own module so screenshot collection can read the report without\n * importing the review pipeline, which itself collects screenshots.\n */\nexport const AGENT_DIRNAME = \".cappa-agent\";\n\n/** Bumped only if `request.json` or `report.json` change incompatibly. */\nexport const AGENT_REPORT_VERSION = 2;\n\nexport const agentDir = (outputDir: string): string =>\n path.resolve(outputDir, AGENT_DIRNAME);\n\nexport const judgmentsRoot = (outputDir: string): string =>\n path.join(agentDir(outputDir), \"judgments\");\n\nexport const agentReportPath = (outputDir: string): string =>\n path.join(agentDir(outputDir), \"report.json\");\n","import type {\n ChangeRegion,\n InterpretResult,\n} from \"@blazediff/interpret-native\";\n\n/**\n * What a judge believes a changed screenshot is, after looking at it.\n *\n * Only a judge labels a change. Cappa's diff threshold already absorbs\n * sub-pixel rendering differences, so a screenshot that reaches `changed`\n * differs beyond the tolerance the project configured — and classifying it\n * from diff signals alone (change types, severity, pixel counts) proved to\n * mislabel exactly the changes that matter: a font-size change reads as a\n * harmless shift plus recolour. Every changed screenshot is looked at instead.\n */\nexport const VERDICT_LABELS = [\n \"regression-likely\",\n \"intentional-likely\",\n \"noise-likely\",\n] as const;\n\nexport type VerdictLabel = (typeof VERDICT_LABELS)[number];\n\n/** What to do next with a screenshot carrying a label. */\nexport type VerdictAction =\n | \"investigate\"\n | \"approve-if-intended\"\n | \"mask-or-approve\";\n\nexport const ACTION_BY_LABEL: Record<VerdictLabel, VerdictAction> = {\n \"regression-likely\": \"investigate\",\n \"intentional-likely\": \"approve-if-intended\",\n \"noise-likely\": \"mask-or-approve\",\n};\n\nexport type Verdict = {\n label: VerdictLabel;\n /** One line, e.g. `Submit button label is truncated`. */\n headline: string;\n rationale: string[];\n action: VerdictAction;\n};\n\nexport const isVerdictLabel = (value: unknown): value is VerdictLabel =>\n typeof value === \"string\" &&\n (VERDICT_LABELS as readonly string[]).includes(value);\n\n/**\n * Change types are normalised to kebab-case before they are compared.\n *\n * `@blazediff/interpret-native` reports `color-change` today but earlier\n * releases reported `ColorChange`; normalising keeps the capture report's\n * labels working across a diff-engine upgrade.\n */\nexport const normalizeChangeType = (changeType: string): string =>\n changeType\n .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .replace(/[\\s_]+/g, \"-\")\n .toLowerCase();\n\nexport type ChangeInput = {\n /** Percentage of differing pixels (0-100), from the pixel diff. */\n percentDifference?: number;\n numDiffPixels?: number;\n interpretation?: InterpretResult;\n /**\n * Expected and actual have different dimensions. Pixel counts and the\n * interpretation then describe a comparison on a canvas padded to the\n * larger size.\n */\n differentSizes?: boolean;\n};\n\nconst formatPercent = (percent: number | undefined): string => {\n if (percent === undefined) return \"?%\";\n return percent >= 0.01 ? `${percent.toFixed(2)}%` : `${percent.toFixed(3)}%`;\n};\n\nconst largestRegion = (regions: readonly ChangeRegion[]) =>\n regions.reduce<ChangeRegion | undefined>(\n (best, region) =>\n !best || region.pixelCount > best.pixelCount ? region : best,\n undefined,\n );\n\n/**\n * A one-line description of where and how much a screenshot changed, shaped\n * so that the same change on different screenshots produces the same text —\n * which is what lets a judge spot one shared cause (a footer timestamp, a\n * theme toggle) across dozens of screenshots and judge them together.\n *\n * Deliberately geometry only: no change types, no severity. Those are guesses\n * from pixel signals, and a judge primed with \"noise\" or \"shift\" looks less\n * carefully at what is in fact a regression.\n */\nexport const describeChange = (input: ChangeInput): string => {\n const regions = input.interpretation?.regions ?? [];\n\n if (input.differentSizes) {\n return regions.length > 0\n ? `dimensions changed; ${describeChange({ ...input, differentSizes: false })}`\n : \"image dimensions changed\";\n }\n\n const percent =\n input.percentDifference ?? input.interpretation?.diffPercentage;\n\n if (regions.length === 0) {\n const pixels = input.numDiffPixels ?? input.interpretation?.diffCount;\n return `${pixels?.toLocaleString(\"en-US\") ?? \"?\"} px (${formatPercent(percent)}) - no regions located`;\n }\n\n const position = largestRegion(regions)?.position;\n const at = position ? ` @ ${position}` : \"\";\n const count = `${regions.length} ${regions.length === 1 ? \"region\" : \"regions\"}`;\n return `${count}${at} (${formatPercent(percent)})`;\n};\n","import fsp from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { AgentReview } from \"../types\";\nimport { AGENT_REPORT_VERSION, agentReportPath } from \"./paths\";\nimport { isVerdictLabel } from \"./verdict\";\n\n/**\n * The judges' verdicts applied by the last `cappa agent check`, keyed by\n * screenshot name. A changed screenshot still awaiting judgment has none.\n *\n * Read on every screenshot listing so the review UI shows them, which is why\n * this reads only `report.json` and never touches the review pipeline.\n */\nexport type AgentReviewIndex = {\n createdAt: number;\n reviews: Map<string, AgentReview>;\n};\n\ntype ReportShape = {\n version?: unknown;\n createdAt?: unknown;\n entries?: unknown;\n};\n\n/**\n * Read the review index, or nothing.\n *\n * Never throws: like the capture manifest, the report is an extra, and a\n * missing or hand-edited file must not break the screenshot listing.\n */\nexport const readAgentReviewIndex = async (\n outputDir: string,\n): Promise<AgentReviewIndex | undefined> => {\n let raw: ReportShape;\n try {\n raw = JSON.parse(await fsp.readFile(agentReportPath(outputDir), \"utf8\"));\n } catch {\n return undefined;\n }\n\n const createdAt =\n typeof raw?.createdAt === \"string\" ? Date.parse(raw.createdAt) : NaN;\n if (\n raw?.version !== AGENT_REPORT_VERSION ||\n Number.isNaN(createdAt) ||\n !Array.isArray(raw.entries)\n ) {\n return undefined;\n }\n\n const reviews = new Map<string, AgentReview>();\n for (const entry of raw.entries) {\n if (typeof entry !== \"object\" || entry === null) continue;\n const { name, category, verdict } = entry as Record<string, unknown>;\n if (typeof name !== \"string\" || category !== \"changed\") continue;\n if (typeof verdict !== \"object\" || verdict === null) continue;\n\n const v = verdict as Record<string, unknown>;\n if (!isVerdictLabel(v.label) || typeof v.headline !== \"string\") continue;\n\n reviews.set(name, {\n label: v.label,\n headline: v.headline,\n rationale: Array.isArray(v.rationale)\n ? v.rationale.filter((line): line is string => typeof line === \"string\")\n : [],\n action: v.action as AgentReview[\"action\"],\n source: \"agent\",\n ...(typeof v.confidence === \"number\" ? { confidence: v.confidence } : {}),\n pending: false,\n reviewedAt: new Date(createdAt).toISOString(),\n });\n }\n\n return { createdAt, reviews };\n};\n\n/**\n * A file's modification time at the report's precision: `createdAt` is an ISO\n * string, so whole milliseconds, while `mtimeMs` carries a fraction. Compared\n * unrounded, an image written in the same millisecond the check started would\n * read as newer than the check and drop a verdict made about it.\n */\nconst modifiedAt = async (file: string): Promise<number> => {\n try {\n return Math.floor((await fsp.stat(file)).mtimeMs);\n } catch {\n return Number.POSITIVE_INFINITY;\n }\n};\n\n/**\n * The review for a changed screenshot, if it is still about these images.\n *\n * A capture after the check rewrites `actual/`, an approval rewrites\n * `expected/`; either makes the verdict describe pixels that are gone. File\n * times are compared rather than content hashed because this runs on every\n * listing the review UI makes.\n */\nexport const freshAgentReview = async (\n index: AgentReviewIndex | undefined,\n outputDir: string,\n screenshot: { name: string; actualPath: string; expectedPath: string },\n): Promise<AgentReview | undefined> => {\n const review = index?.reviews.get(screenshot.name);\n if (!index || !review) return undefined;\n\n const [actual, expected] = await Promise.all([\n modifiedAt(path.resolve(outputDir, screenshot.actualPath)),\n modifiedAt(path.resolve(outputDir, screenshot.expectedPath)),\n ]);\n\n return actual <= index.createdAt && expected <= index.createdAt\n ? review\n : undefined;\n};\n","import { createHash } from \"node:crypto\";\nimport path from \"node:path\";\nimport { readDiffMeta } from \"../filesystem\";\nimport type { Screenshot } from \"../types\";\n\nexport const groupScreenshots = async (\n actualScreenshots: string[],\n expectedScreenshots: string[],\n diffScreenshots: string[],\n outputDir: string,\n): Promise<Screenshot[]> => {\n const screenshotRepresentations: Screenshot[] = [];\n\n // Build Maps for O(1) lookups instead of O(n) .find() calls\n const expectedByRelativePath = new Map<string, string>();\n for (const screenshot of expectedScreenshots) {\n const relativePath = path.relative(`${outputDir}/expected`, screenshot);\n expectedByRelativePath.set(relativePath, screenshot);\n }\n\n const diffByRelativePath = new Map<string, string>();\n for (const screenshot of diffScreenshots) {\n const relativePath = path.relative(`${outputDir}/diff`, screenshot);\n diffByRelativePath.set(relativePath, screenshot);\n }\n\n const actualRelativePaths = new Set<string>();\n\n for (const screenshot of actualScreenshots) {\n const relativePath = path.relative(`${outputDir}/actual`, screenshot);\n actualRelativePaths.add(relativePath);\n\n const name = relativePath.replace(\".png\", \"\");\n const id = createHash(\"sha256\").update(relativePath).digest(\"hex\");\n\n const expectedScreenshot = expectedByRelativePath.get(relativePath);\n const diffScreenshot = diffByRelativePath.get(relativePath);\n\n // Load the diff metadata sidecar (stats + interpretation) for changed\n // screenshots so it can be surfaced in the review UI and CLI.\n const diffMeta = diffScreenshot\n ? await readDiffMeta(diffScreenshot)\n : undefined;\n\n screenshotRepresentations.push({\n id: id,\n name: name,\n category: buildCategory(expectedScreenshot, diffScreenshot),\n expectedPath: expectedScreenshot\n ? path.relative(outputDir, expectedScreenshot)\n : undefined,\n diffPath: diffScreenshot\n ? path.relative(outputDir, diffScreenshot)\n : undefined,\n actualPath: path.relative(outputDir, screenshot),\n ...(diffMeta ? { diffMeta } : {}),\n } as Screenshot);\n }\n\n for (const expectedScreenshot of expectedScreenshots) {\n const relativePath = path.relative(\n `${outputDir}/expected`,\n expectedScreenshot,\n );\n\n // If the actual screenshot exists, it means we already added it\n if (actualRelativePaths.has(relativePath)) {\n continue;\n }\n\n const name = relativePath.replace(\".png\", \"\");\n const id = createHash(\"sha256\").update(relativePath).digest(\"hex\");\n\n screenshotRepresentations.push({\n id: id,\n name: name,\n category: \"deleted\",\n expectedPath: path.relative(outputDir, expectedScreenshot),\n });\n }\n\n return screenshotRepresentations.sort((a, b) => {\n return CATEGORY_ORDER[a.category] - CATEGORY_ORDER[b.category];\n });\n};\n\nconst buildCategory = (\n expectedScreenshot: string | undefined,\n diffScreenshot: string | undefined,\n) => {\n if (expectedScreenshot && diffScreenshot) {\n return \"changed\";\n }\n if (expectedScreenshot) {\n return \"passed\";\n }\n\n return \"new\";\n};\n\nconst CATEGORY_ORDER: Record<Screenshot[\"category\"], number> = {\n new: 0,\n deleted: 1,\n changed: 2,\n passed: 3,\n};\n","import { glob } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { freshAgentReview, readAgentReviewIndex } from \"../agent/reviewIndex\";\nimport type { Screenshot } from \"../types\";\nimport { groupScreenshots } from \"./groupScreenshots\";\nimport { readCaptureManifest } from \"./manifest\";\n\nconst listPngs = async (dir: string): Promise<string[]> =>\n Array.fromAsync(await glob(path.resolve(dir, \"**/*.png\")));\n\n/**\n * Read the `actual/`, `expected/` and `diff/` directories of `outputDir` and\n * group them into the screenshot representations used by the CLI commands\n * (including the diff metadata sidecar with the optional interpretation).\n *\n * The capture manifest is folded in here so every consumer — the CLI, the\n * server, the review UI — sees the same `taskId`, and so a screenshot captured\n * before manifests existed simply has none rather than a wrong one. The last\n * `cappa agent check` verdict is folded in the same way, as `review`, while it\n * still describes the images on disk.\n */\nexport const collectScreenshots = async (\n outputDir: string,\n): Promise<Screenshot[]> => {\n const [\n actualScreenshots,\n expectedScreenshots,\n diffScreenshots,\n manifest,\n reviewIndex,\n ] = await Promise.all([\n listPngs(path.resolve(outputDir, \"actual\")),\n listPngs(path.resolve(outputDir, \"expected\")),\n listPngs(path.resolve(outputDir, \"diff\")),\n readCaptureManifest(outputDir),\n readAgentReviewIndex(outputDir),\n ]);\n\n const screenshots = await groupScreenshots(\n actualScreenshots,\n expectedScreenshots,\n diffScreenshots,\n outputDir,\n );\n\n return Promise.all(\n screenshots.map(async (screenshot) => {\n const origin = manifest.screenshots[screenshot.name];\n const withOrigin: Screenshot = origin\n ? { ...screenshot, taskId: origin.taskId, plugin: origin.plugin }\n : screenshot;\n\n if (withOrigin.category !== \"changed\" || !reviewIndex) {\n return withOrigin;\n }\n\n const review = await freshAgentReview(reviewIndex, outputDir, withOrigin);\n return review ? { ...withOrigin, review } : withOrigin;\n }),\n );\n};\n","import {\n type ChildProcess,\n execFile,\n execFileSync,\n spawn,\n} from \"node:child_process\";\n\n/** Grace period between SIGTERM and SIGKILL. */\nexport const DEFAULT_KILL_GRACE_MS = 5000;\n\n/** How long to wait for the kernel to reap a SIGKILLed group. */\nconst SIGKILL_WAIT_MS = 2000;\n\nconst isWindows = process.platform === \"win32\";\n\n/**\n * The last part of a process's output, kept in memory.\n *\n * Bounded by bytes rather than lines: a dev server that prints one enormous\n * line is no reason to hold on to all of it, and the tail exists to explain a\n * failure, not to be a log.\n */\nexport class OutputTail {\n private chunks: string[] = [];\n private size = 0;\n\n constructor(private readonly maxBytes = 64 * 1024) {}\n\n push(chunk: string): void {\n this.chunks.push(chunk);\n this.size += chunk.length;\n\n while (this.size > this.maxBytes && this.chunks.length > 1) {\n this.size -= this.chunks.shift()?.length ?? 0;\n }\n }\n\n /** The last `maxLines` non-empty lines. */\n lines(maxLines = 30): string[] {\n return this.chunks\n .join(\"\")\n .split(/\\r?\\n/)\n .filter((line) => line.trim() !== \"\")\n .slice(-maxLines);\n }\n}\n\nexport type ProcessExit = {\n code: number | null;\n signal: NodeJS.Signals | null;\n};\n\nexport type ServerProcess = {\n readonly pid: number | undefined;\n /** Settles once the direct child has exited. Never rejects. */\n readonly exited: Promise<ProcessExit>;\n /** The exit, once there is one. */\n readonly exit: ProcessExit | undefined;\n readonly output: OutputTail;\n /** Stop the whole process tree. Safe to call repeatedly. */\n kill(graceMs?: number): Promise<void>;\n};\n\nexport type SpawnServerOptions = {\n cwd: string;\n env?: Record<string, string>;\n /** Called with every chunk of output as it arrives. */\n onOutput?: (chunk: string) => void;\n};\n\n/**\n * Process groups this process started and has not stopped yet.\n *\n * Exists for the one exit no `close()` covers: the process leaving without\n * shutting down. A server left running holds its port, and the next run would\n * silently *reuse* it — a stale build answering for the current one.\n */\nconst liveProcesses = new Set<ChildProcess>();\nlet exitHookInstalled = false;\n\nconst installExitHook = () => {\n if (exitHookInstalled) {\n return;\n }\n exitHookInstalled = true;\n\n // Synchronous by necessity: nothing asynchronous runs after `exit`. There is\n // no time for a graceful SIGTERM either, so this goes straight to SIGKILL.\n process.on(\"exit\", () => {\n for (const child of liveProcesses) {\n killTreeNow(child);\n }\n liveProcesses.clear();\n });\n};\n\nconst killTreeNow = (child: ChildProcess) => {\n if (child.pid === undefined) {\n return;\n }\n\n try {\n if (isWindows) {\n execFileSync(\"taskkill\", [\"/pid\", String(child.pid), \"/T\", \"/F\"], {\n stdio: \"ignore\",\n });\n } else {\n process.kill(-child.pid, \"SIGKILL\");\n }\n } catch {\n // Already gone.\n }\n};\n\n/**\n * Start `command` through a shell, as the leader of its own process group.\n *\n * A group, because the command is rarely the server itself: `pnpm storybook`\n * is pnpm, running a shell, running storybook, running workers. Killing only\n * the direct child would leave the rest holding the port.\n *\n * Output is buffered, never written anywhere unless `onOutput` asks for it —\n * `cappa capture --json` must stay a single clean document on stdout.\n */\nexport function spawnServerProcess(\n command: string,\n options: SpawnServerOptions,\n): ServerProcess {\n const child = spawn(command, {\n cwd: options.cwd,\n env: { ...process.env, ...options.env },\n shell: true,\n // On POSIX this makes the child a process-group leader. On Windows it\n // would open a console window instead, and `taskkill /T` walks the tree\n // without needing a group.\n detached: !isWindows,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n windowsHide: true,\n });\n\n const output = new OutputTail();\n const onData = (data: Buffer) => {\n const chunk = data.toString();\n output.push(chunk);\n options.onOutput?.(chunk);\n };\n child.stdout?.on(\"data\", onData);\n child.stderr?.on(\"data\", onData);\n\n liveProcesses.add(child);\n installExitHook();\n\n let exit: ProcessExit | undefined;\n const exited = new Promise<ProcessExit>((resolve) => {\n const settle = (value: ProcessExit) => {\n if (exit) {\n return;\n }\n exit = value;\n resolve(value);\n };\n\n child.once(\"exit\", (code, signal) => settle({ code, signal }));\n child.once(\"error\", (error) => {\n output.push(`${error.message}\\n`);\n settle({ code: null, signal: null });\n });\n });\n\n let killing: Promise<void> | undefined;\n\n return {\n get pid() {\n return child.pid;\n },\n exited,\n get exit() {\n return exit;\n },\n output,\n kill(graceMs = DEFAULT_KILL_GRACE_MS) {\n killing ??= killProcessTree(child, exited, graceMs).finally(() => {\n liveProcesses.delete(child);\n });\n return killing;\n },\n };\n}\n\n/** True while any process in the group led by `pid` is alive. */\nconst groupAlive = (pid: number): boolean => {\n try {\n process.kill(-pid, 0);\n return true;\n } catch (error) {\n // EPERM means it exists but is not ours to signal — still alive.\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n};\n\nconst delay = (ms: number) =>\n new Promise<void>((resolve) => {\n setTimeout(resolve, ms);\n });\n\n/**\n * SIGTERM the whole group, then SIGKILL whatever is left after `graceMs`.\n *\n * Waits on the group, not the child: the shell can exit at once while the\n * server it started is still shutting down — and still holding the port.\n */\nasync function killProcessTree(\n child: ChildProcess,\n exited: Promise<ProcessExit>,\n graceMs: number,\n): Promise<void> {\n const pid = child.pid;\n if (pid === undefined) {\n return;\n }\n\n if (isWindows) {\n // `/F` is the only reliable option: console apps ignore a polite taskkill.\n await new Promise<void>((resolve) => {\n execFile(\"taskkill\", [\"/pid\", String(pid), \"/T\", \"/F\"], () => resolve());\n });\n await exited;\n return;\n }\n\n if (!groupAlive(pid)) {\n return;\n }\n\n try {\n process.kill(-pid, \"SIGTERM\");\n } catch {\n return;\n }\n\n const deadline = Date.now() + graceMs;\n while (groupAlive(pid) && Date.now() < deadline) {\n await delay(50);\n }\n\n if (groupAlive(pid)) {\n try {\n process.kill(-pid, \"SIGKILL\");\n } catch {\n // Gone in the meantime.\n }\n\n // `kill` only queues the signal, and the shell that led the group has\n // usually exited on the SIGTERM already — so `exited` settled long ago and\n // says nothing about the server. Wait until the group is actually gone,\n // or the port is still held when this returns.\n const killDeadline = Date.now() + SIGKILL_WAIT_MS;\n while (groupAlive(pid) && Date.now() < killDeadline) {\n await delay(20);\n }\n }\n\n await exited;\n}\n","const PROBE_TIMEOUT_MS = 5000;\n/** Delays between probes; the last one repeats. */\nconst POLL_DELAYS_MS = [100, 250, 500, 1000];\n\n/**\n * Whether `url` answers with a 2xx or 3xx status.\n *\n * Redirects are not followed: a dev server that redirects `/` to `/login` is\n * up, and following it would make readiness depend on a page cappa never asked\n * about.\n */\nexport async function isUrlReady(\n url: string,\n timeoutMs = PROBE_TIMEOUT_MS,\n): Promise<boolean> {\n try {\n const response = await fetch(url, {\n redirect: \"manual\",\n signal: AbortSignal.timeout(Math.max(1, timeoutMs)),\n });\n // Nobody reads the body; let the socket go.\n await response.body?.cancel().catch(() => {});\n return response.status >= 200 && response.status < 400;\n } catch {\n return false;\n }\n}\n\nexport type WaitForUrlOptions = {\n timeoutMs: number;\n /** Stop waiting as soon as this settles — the server process exited. */\n abort?: Promise<unknown>;\n /** Injectable for tests. */\n probe?: (url: string, timeoutMs: number) => Promise<boolean>;\n};\n\nexport type WaitForUrlResult = \"ready\" | \"timeout\" | \"aborted\";\n\n/** Poll `url` until it is ready, the deadline passes, or `abort` settles. */\nexport async function waitForUrl(\n url: string,\n options: WaitForUrlOptions,\n): Promise<WaitForUrlResult> {\n const probe = options.probe ?? isUrlReady;\n const deadline = Date.now() + options.timeoutMs;\n\n let aborted = false;\n const abort = (options.abort ?? new Promise<never>(() => {})).then(\n () => {\n aborted = true;\n },\n () => {\n aborted = true;\n },\n );\n\n for (let attempt = 0; ; attempt++) {\n const remaining = deadline - Date.now();\n if (aborted) {\n return \"aborted\";\n }\n if (remaining <= 0) {\n return \"timeout\";\n }\n\n if (await probe(url, Math.min(remaining, PROBE_TIMEOUT_MS))) {\n return \"ready\";\n }\n\n const wait = Math.min(\n POLL_DELAYS_MS[Math.min(attempt, POLL_DELAYS_MS.length - 1)] ?? 1000,\n Math.max(0, deadline - Date.now()),\n );\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n new Promise<void>((resolve) => {\n timer = setTimeout(resolve, wait);\n }),\n abort,\n ]);\n clearTimeout(timer);\n }\n}\n","import type { WebServerConfig } from \"../types\";\nimport {\n type ProcessExit,\n type ServerProcess,\n type SpawnServerOptions,\n spawnServerProcess,\n} from \"./process\";\nimport { isUrlReady, waitForUrl } from \"./readiness\";\nimport { NO_WEB_SERVER_HINT, sameServer } from \"./unreachable\";\n\n/** A `webServer` entry with every default applied. */\nexport type ResolvedWebServerConfig = Required<WebServerConfig>;\n\nexport type WebServerLogLevel = \"debug\" | \"info\" | \"warn\" | \"error\" | \"success\";\n\nexport type WebServerLog = (level: WebServerLogLevel, message: string) => void;\n\nexport type WebServerPoolOptions = {\n servers: ResolvedWebServerConfig[];\n /** Where lifecycle messages go when `ensure` is not handed a log. */\n log?: WebServerLog;\n /** Live output, for `--log-level 4`. Output is buffered either way. */\n onOutput?: (server: ResolvedWebServerConfig, chunk: string) => void;\n /** Overrides process spawning. Tests use this. */\n spawn?: (command: string, options: SpawnServerOptions) => ServerProcess;\n /** Overrides the readiness probe. Tests use this. */\n probe?: (url: string, timeoutMs: number) => Promise<boolean>;\n /** Grace period between SIGTERM and SIGKILL. @default 5000 */\n killGraceMs?: number;\n};\n\n/** A web server could not be started, or would not become ready. */\nexport class WebServerError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"WebServerError\";\n }\n}\n\ntype EntryState =\n | { kind: \"idle\" }\n /** Something else was already answering at `url`. Never stopped by cappa. */\n | { kind: \"reused\" }\n | { kind: \"running\"; process: ServerProcess }\n /** Exited on its own after it was ready. Started again on the next run. */\n | { kind: \"exited\"; exit: ProcessExit; tail: string[] };\n\ntype Entry = {\n config: ResolvedWebServerConfig;\n state: EntryState;\n starting: Promise<void> | null;\n};\n\nconst describeExit = (exit: ProcessExit): string =>\n exit.signal\n ? `signal ${exit.signal}`\n : exit.code === null\n ? \"an error\"\n : `code ${exit.code}`;\n\nconst formatTail = (command: string, lines: string[]): string =>\n lines.length === 0\n ? `\\`${command}\\` printed nothing.`\n : `Last output of \\`${command}\\`:\\n${lines.map((line) => ` ${line}`).join(\"\\n\")}`;\n\nconst seconds = (ms: number) => `${Math.round(ms / 100) / 10}s`;\n\n/**\n * The servers a config's `webServer` describes, started on demand.\n *\n * Lazy and restartable rather than started once: the owning engine calls\n * `ensure` before every run and `stop` when the browser goes idle, so a review\n * session that sits unused gives the port back, and the next capture starts —\n * and rebuilds — the app again, picking up whatever changed in between.\n *\n * Every `ensure` says which way it went, because \"reusing a server\" and\n * \"started one\" look identical in screenshots, and a stale build, another\n * branch or another project on the same port is otherwise very hard to spot.\n */\nexport class WebServerPool {\n private readonly entries: Entry[];\n private readonly options: WebServerPoolOptions;\n private readonly probe: (url: string, timeoutMs: number) => Promise<boolean>;\n /** Bumped by `stop`, so a start in flight knows it was cancelled. */\n private generation = 0;\n\n constructor(options: WebServerPoolOptions) {\n this.options = options;\n this.probe = options.probe ?? isUrlReady;\n this.entries = options.servers.map((config) => ({\n config,\n state: { kind: \"idle\" },\n starting: null,\n }));\n }\n\n /** Whether the config has any `webServer` entry at all. */\n get configured(): boolean {\n return this.entries.length > 0;\n }\n\n /** Number of processes cappa started that are still running. */\n get running(): number {\n return this.entries.filter(\n (entry) => entry.state.kind === \"running\" && !entry.state.process.exit,\n ).length;\n }\n\n /**\n * Make every server ready, in parallel, starting the ones that are not.\n *\n * All of them, even for a run that only captures one plugin's tasks: nothing\n * maps a plugin to a server, and guessing would start the wrong one.\n */\n async ensure(log: WebServerLog = this.defaultLog): Promise<void> {\n if (this.entries.length === 0) {\n return;\n }\n\n const results = await Promise.allSettled(\n this.entries.map((entry) => this.ensureEntry(entry, log)),\n );\n\n const errors = results.flatMap((result) =>\n result.status === \"rejected\" ? [result.reason] : [],\n );\n\n if (errors.length === 1) {\n throw errors[0];\n }\n if (errors.length > 1) {\n throw new WebServerError(\n errors\n .map((error) => (error instanceof Error ? error.message : error))\n .join(\"\\n\\n\"),\n );\n }\n }\n\n /**\n * Stop every server cappa started. A reused server is left alone — cappa did\n * not start it, so it is not cappa's to stop.\n */\n async stop(): Promise<void> {\n this.generation += 1;\n\n await Promise.all(\n this.entries.map(async (entry) => {\n const state = entry.state;\n // Before the kill, so the exit watcher sees a deliberate stop rather\n // than a crash.\n entry.state = { kind: \"idle\" };\n\n if (state.kind === \"running\") {\n await state.process.kill(this.options.killGraceMs);\n }\n }),\n );\n }\n\n /**\n * What to tell the user about a connection refused at `origin`.\n *\n * Always an actionable sentence: the bare \"ECONNREFUSED\" it replaces is the\n * single most common capture failure, and says nothing about what to do.\n */\n explainUnreachable(origin?: string): string {\n if (this.entries.length === 0) {\n return NO_WEB_SERVER_HINT;\n }\n\n const matching = origin\n ? this.entries.find((entry) => sameServer(entry.config.url, origin))\n : undefined;\n\n const crashed =\n matching?.state.kind === \"exited\"\n ? matching\n : this.entries.find((entry) => entry.state.kind === \"exited\");\n\n if (crashed && crashed.state.kind === \"exited\") {\n return `The web server \\`${crashed.config.command}\\` exited with ${describeExit(crashed.state.exit)} during the run; it is started again on the next run.\\n${formatTail(crashed.config.command, crashed.state.tail)}`;\n }\n\n if (origin && !matching) {\n const urls = this.entries.map((entry) => entry.config.url).join(\", \");\n return `No \\`webServer\\` entry serves ${origin} (configured: ${urls}). Check that the plugin's URL matches \\`webServer.url\\`.`;\n }\n\n return \"The configured `webServer` was ready, but stopped accepting connections.\";\n }\n\n private readonly defaultLog: WebServerLog = (level, message) => {\n this.options.log?.(level, message);\n };\n\n private ensureEntry(entry: Entry, log: WebServerLog): Promise<void> {\n // Two callers asking at once — discovery from the UI and a run, say — share\n // one start rather than spawning the command twice.\n entry.starting ??= this.startEntry(entry, log).finally(() => {\n entry.starting = null;\n });\n return entry.starting;\n }\n\n private async startEntry(entry: Entry, log: WebServerLog): Promise<void> {\n const { command, url, timeout, cwd, env, reuseExistingServer } =\n entry.config;\n const previous = entry.state;\n\n if (previous.kind === \"running\" && !previous.process.exit) {\n log(\"info\", `Using \\`${command}\\` at ${url}, started earlier by cappa`);\n return;\n }\n\n if (previous.kind === \"exited\") {\n log(\n \"warn\",\n `\\`${command}\\` exited with ${describeExit(previous.exit)} after the last run; starting it again`,\n );\n }\n\n if (await this.probe(url, Math.min(timeout, 5000))) {\n if (reuseExistingServer) {\n entry.state = { kind: \"reused\" };\n log(\"info\", `Reusing server at ${url} — \\`${command}\\` was not run`);\n return;\n }\n\n throw new WebServerError(\n `${url} is already in use, and \\`webServer.reuseExistingServer\\` is false. Stop whatever is serving it, or allow reusing it.`,\n );\n }\n\n const generation = this.generation;\n const startedAt = Date.now();\n\n log(\n \"info\",\n `Starting \\`${command}\\` — waiting up to ${seconds(timeout)} for ${url}`,\n );\n\n const child = (this.options.spawn ?? spawnServerProcess)(command, {\n cwd,\n env,\n onOutput: this.options.onOutput\n ? (chunk) => this.options.onOutput?.(entry.config, chunk)\n : undefined,\n });\n\n // Recorded before it is ready, so a `stop` during start-up kills it too.\n entry.state = { kind: \"running\", process: child };\n\n const result = await waitForUrl(url, {\n timeoutMs: timeout,\n abort: child.exited,\n probe: this.probe,\n });\n\n if (generation !== this.generation) {\n await child.kill(this.options.killGraceMs);\n throw new WebServerError(\n `\\`${command}\\` was stopped before ${url} was ready.`,\n );\n }\n\n if (result === \"ready\") {\n this.watchForCrash(entry, child);\n log(\n \"success\",\n `Started \\`${command}\\` — ${url} ready in ${seconds(Date.now() - startedAt)}`,\n );\n return;\n }\n\n entry.state = { kind: \"idle\" };\n\n if (result === \"aborted\") {\n const exit = await child.exited;\n throw new WebServerError(\n `\\`${command}\\` exited with ${describeExit(exit)} before ${url} was ready.\\n${formatTail(command, child.output.lines())}`,\n );\n }\n\n await child.kill(this.options.killGraceMs);\n throw new WebServerError(\n `Timed out after ${seconds(timeout)} waiting for \\`${command}\\` to serve ${url}. If it needs longer — a build step, say — raise \\`webServer.timeout\\`.\\n${formatTail(command, child.output.lines())}`,\n );\n }\n\n /**\n * Record a server that exits on its own, so the failures it causes can say\n * why and the next run starts it again. Deliberately no restart loop: a\n * server that keeps crashing should fail loudly, not flap.\n */\n private watchForCrash(entry: Entry, child: ServerProcess): void {\n void child.exited.then((exit) => {\n const state = entry.state;\n if (state.kind !== \"running\" || state.process !== child) {\n // Stopped on purpose.\n return;\n }\n\n entry.state = { kind: \"exited\", exit, tail: child.output.lines() };\n // The process group may outlive the shell that led it.\n void child.kill(this.options.killGraceMs);\n this.defaultLog(\n \"error\",\n `\\`${entry.config.command}\\` exited with ${describeExit(exit)} while cappa was using it.`,\n );\n });\n }\n}\n","import type { CaptureRunner } from \"../runner/CaptureRunner\";\nimport type { RunDetail, RunEvent, RunSummary } from \"../runner/types\";\n\nexport type RunStoreOptions = {\n /**\n * Events buffered per run, for replay to a (re)connecting subscriber.\n * @default 5000\n */\n maxEventsPerRun?: number;\n /**\n * Finished runs kept in memory. Oldest are dropped first.\n * @default 20\n */\n maxRuns?: number;\n};\n\ntype RunEntry = {\n id: string;\n runner: CaptureRunner;\n events: RunEvent[];\n /** Events dropped off the front of the buffer, so replay gaps are detectable. */\n dropped: number;\n listeners: Set<(event: RunEvent) => void>;\n /** Frozen once the run finishes, so detail survives after the runner is gone. */\n finalDetail?: RunDetail;\n};\n\n/**\n * In-memory registry of capture runs and their event history.\n *\n * The event buffer is what lets an SSE client reconnect without losing\n * anything: subscribers replay from the last `seq` they saw before live\n * delivery starts.\n */\nexport class RunStore {\n private readonly maxEventsPerRun: number;\n private readonly maxRuns: number;\n private readonly runs = new Map<string, RunEntry>();\n /** Insertion order, oldest first — the eviction queue. */\n private readonly order: string[] = [];\n\n constructor(options: RunStoreOptions = {}) {\n this.maxEventsPerRun = options.maxEventsPerRun ?? 5000;\n this.maxRuns = options.maxRuns ?? 20;\n }\n\n /** Register a runner and start buffering its events. */\n add(runner: CaptureRunner): void {\n const entry: RunEntry = {\n id: runner.id,\n runner,\n events: [],\n dropped: 0,\n listeners: new Set(),\n };\n\n this.runs.set(runner.id, entry);\n this.order.push(runner.id);\n this.evictOldRuns();\n\n runner.on((event) => {\n entry.events.push(event);\n if (entry.events.length > this.maxEventsPerRun) {\n entry.dropped += entry.events.length - this.maxEventsPerRun;\n entry.events.splice(0, entry.events.length - this.maxEventsPerRun);\n }\n\n for (const listener of entry.listeners) {\n try {\n listener(event);\n } catch {\n // A failing subscriber must not disturb the run or other subscribers.\n }\n }\n });\n }\n\n /**\n * Freeze the final detail of a finished run so it stays queryable after the\n * runner is discarded.\n */\n finalize(runId: string): void {\n const entry = this.runs.get(runId);\n if (entry) {\n entry.finalDetail = entry.runner.getDetail();\n }\n }\n\n get(runId: string): RunDetail | undefined {\n const entry = this.runs.get(runId);\n if (!entry) {\n return undefined;\n }\n\n return entry.finalDetail ?? entry.runner.getDetail();\n }\n\n getRunner(runId: string): CaptureRunner | undefined {\n return this.runs.get(runId)?.runner;\n }\n\n /** Newest first. */\n list(): RunSummary[] {\n return [...this.order]\n .reverse()\n .map((id) => {\n const entry = this.runs.get(id);\n if (!entry) {\n return undefined;\n }\n return entry.finalDetail ?? entry.runner.getSummary();\n })\n .filter((summary): summary is RunSummary => summary !== undefined);\n }\n\n /**\n * Subscribe to a run, replaying buffered events first.\n *\n * Replay is synchronous, so a subscriber cannot miss events that arrive\n * between the buffer read and the listener being registered.\n */\n subscribe(\n runId: string,\n onEvent: (event: RunEvent) => void,\n options: { sinceSeq?: number } = {},\n ): () => void {\n const entry = this.runs.get(runId);\n if (!entry) {\n return () => {};\n }\n\n const sinceSeq = options.sinceSeq ?? 0;\n for (const event of entry.events) {\n if (event.seq > sinceSeq) {\n onEvent(event);\n }\n }\n\n entry.listeners.add(onEvent);\n return () => {\n entry.listeners.delete(onEvent);\n };\n }\n\n /** How many events were dropped from a run's buffer (0 when none were). */\n droppedEvents(runId: string): number {\n return this.runs.get(runId)?.dropped ?? 0;\n }\n\n private evictOldRuns(): void {\n while (this.order.length > this.maxRuns) {\n const oldest = this.order.shift();\n if (oldest !== undefined) {\n this.runs.delete(oldest);\n }\n }\n }\n}\n","import type {\n RunDetail,\n RunEvent,\n RunSummary,\n StartRunRequest,\n Target,\n} from \"../runner/types\";\nimport type { Screenshot } from \"../types\";\n\nexport type PluginInfo = {\n name: string;\n description?: string;\n};\n\nexport type ScreenshotQuery = {\n search?: string;\n category?: Screenshot[\"category\"];\n};\n\nexport type ApproveResult = {\n approved: string[];\n errors: { name: string; error: string }[];\n};\n\nexport type ListTargetsOptions = {\n /** Re-run plugin discovery instead of serving the cached target list. */\n refresh?: boolean;\n};\n\nexport type SubscribeOptions = {\n /**\n * Replay buffered events with `seq > sinceSeq` before streaming live ones.\n * This is what makes a dropped SSE connection invisible to the client.\n */\n sinceSeq?: number;\n};\n\n/**\n * How a watch iteration decided what to capture.\n *\n * - `tasks` — an explicit set of task ids, resolved by the plugins.\n * - `plugins` — every task of one or more plugins, because at least one could\n * not attribute the change (or ships no `watch` at all).\n * - `all` — everything under the session's filter: the resolved set was larger\n * than the cap, or discovery itself failed.\n * - `none` — nothing to capture.\n */\nexport type WatchScope = \"tasks\" | \"plugins\" | \"all\" | \"none\";\n\n/** What one settled batch of file changes led to. */\nexport type WatchChange = {\n /** Changed files, relative to the watch root. */\n files: string[];\n scope: WatchScope;\n /** Resolved task ids, when the scope is `tasks`. */\n taskIds?: string[];\n /** The run the change started, absent when none could be started. */\n runId?: string;\n /** Why no run was started, when that is what happened. */\n error?: string;\n at: number;\n};\n\ntype WatchEventBase = {\n /** Monotonic, 1-based, per engine. Used for replay, like run events. */\n seq: number;\n at: number;\n};\n\n/**\n * The watch event stream.\n *\n * Separate from `RunEvent` because these events belong to a session that\n * outlives any single run — a watch session is a scheduler for runs, and the\n * runs it starts report themselves through the ordinary run stream.\n */\nexport type WatchEvent =\n | (WatchEventBase & {\n type: \"watch:start\";\n paths: string[];\n filter?: string;\n debounceMs: number;\n })\n | (WatchEventBase & { type: \"watch:change\" } & Omit<WatchChange, \"at\">)\n | (WatchEventBase & {\n type: \"watch:stop\";\n reason: \"requested\" | \"engine-closed\";\n });\n\nexport type WatchEventType = WatchEvent[\"type\"];\n\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown\n ? Omit<T, K>\n : never;\n\n/** A watch event before the engine stamps it with `seq` and `at`. */\nexport type EmittableWatchEvent = DistributiveOmit<WatchEvent, \"seq\" | \"at\">;\n\n/** What a watch session is doing, readable at any time. */\nexport type WatchStatus = {\n active: boolean;\n /** Roots being watched, relative to the working directory. */\n paths: string[];\n filter?: string;\n debounceMs: number;\n startedAt?: number;\n /** The most recent settled batch of changes, when there has been one. */\n lastChange?: WatchChange;\n};\n\n/** Options for `startWatch`. */\nexport type StartWatchRequest = {\n /**\n * Directories to watch, relative to the working directory.\n * @default [\".\"]\n */\n paths?: string[];\n /** Glob every watch-triggered run is restricted to (`path.matchesGlob`). */\n filter?: string;\n /**\n * How long changes must settle before a run starts.\n * @default 300\n */\n debounceMs?: number;\n /**\n * Above this many resolved task ids, capture everything under `filter`\n * instead. A branch switch is what this guards against.\n * @default 200\n */\n maxTasks?: number;\n};\n\n/**\n * Everything a UI needs to drive and observe captures.\n *\n * There are two implementations: `LocalEngine` runs the browser in-process, and\n * (later) a remote engine speaks HTTP + SSE to a server that does. The UI only\n * ever holds this interface, so moving the browser to another machine is a\n * different implementation rather than a rewrite.\n *\n * That is only true if the interface stays serializable: **no `Page`, `Browser`,\n * or plugin object may cross it** — arguments and return values must survive a\n * JSON round-trip. Plugins are live closures from `cappa.config.ts` and cannot\n * be sent anywhere; whichever process holds the engine is the one that loaded\n * the config.\n */\nexport interface CaptureEngine {\n /** Plugins this engine can run. */\n listPlugins(): Promise<PluginInfo[]>;\n\n /** Discovered, runnable tasks. Cached until `refresh` is requested. */\n listTargets(options?: ListTargetsOptions): Promise<Target[]>;\n\n /**\n * Start a capture. Resolves as soon as the run is registered — progress\n * arrives through `subscribeRun`.\n *\n * @throws {RunInProgressError} when a run is already active.\n */\n startRun(request?: StartRunRequest): Promise<RunSummary>;\n\n getRun(id: string): Promise<RunDetail | undefined>;\n\n /** Newest first. */\n listRuns(): Promise<RunSummary[]>;\n\n cancelRun(id: string): Promise<void>;\n\n /**\n * Observe a run. Returns an unsubscribe function.\n *\n * Buffered events are replayed synchronously before live delivery begins, so\n * a subscriber that attaches after `startRun` still sees the whole run.\n */\n subscribeRun(\n id: string,\n onEvent: (event: RunEvent) => void,\n options?: SubscribeOptions,\n ): () => void;\n\n listScreenshots(query?: ScreenshotQuery): Promise<Screenshot[]>;\n\n approve(names: string[]): Promise<ApproveResult>;\n\n /**\n * Re-capture on file change until `stopWatch`.\n *\n * Optional, because only an engine that can see the files is able to do it:\n * a remote engine drives the watcher on the *host*, and an engine with no\n * local filesystem at all has nothing to offer. Callers must feature-detect\n * rather than assume.\n *\n * @throws {WatchInProgressError} when a session is already active.\n */\n startWatch?(request?: StartWatchRequest): Promise<WatchStatus>;\n\n /**\n * Stop the active watch session and answer the status it left behind.\n *\n * A no-op when there is none — the status simply says it is inactive.\n */\n stopWatch?(): Promise<WatchStatus>;\n\n /** What the watch session is doing, or an inactive status when there is none. */\n getWatchStatus?(): Promise<WatchStatus>;\n\n /**\n * Observe the watch event stream. Returns an unsubscribe function.\n *\n * Buffered events are replayed synchronously before live delivery, exactly\n * as `subscribeRun` does.\n */\n subscribeWatch?(\n onEvent: (event: WatchEvent) => void,\n options?: SubscribeOptions,\n ): () => void;\n\n /** Release resources (browser, timers). Safe to call more than once. */\n close(): Promise<void>;\n}\n\n/**\n * Stable discriminators for engine errors.\n *\n * These exist because `instanceof` is not reliable across the package\n * boundary. `@cappa/core` ships dual ESM/CJS builds, so a CJS consumer (the\n * CLI binary) and an ESM one (the server) each load their own copy of these\n * classes: an error thrown by one is not an `instanceof` the other's class,\n * and the check silently fails — turning a 409 into a 500. Callers must use\n * the guards below rather than `instanceof`.\n */\nexport const ENGINE_ERROR_CODES = {\n runInProgress: \"CAPPA_RUN_IN_PROGRESS\",\n unknownTargets: \"CAPPA_UNKNOWN_TARGETS\",\n watchInProgress: \"CAPPA_WATCH_IN_PROGRESS\",\n} as const;\n\n/** Thrown by `startRun` when the engine is already running something. */\nexport class RunInProgressError extends Error {\n readonly code = ENGINE_ERROR_CODES.runInProgress;\n readonly activeRunId: string;\n\n constructor(activeRunId: string) {\n super(`A capture run is already in progress (${activeRunId})`);\n this.name = \"RunInProgressError\";\n this.activeRunId = activeRunId;\n }\n}\n\n/** Thrown by `startRun` when `taskIds` names tasks that were never discovered. */\nexport class UnknownTargetsError extends Error {\n readonly code = ENGINE_ERROR_CODES.unknownTargets;\n readonly taskIds: string[];\n\n constructor(taskIds: string[]) {\n super(`Unknown task ids: ${taskIds.join(\", \")}`);\n this.name = \"UnknownTargetsError\";\n this.taskIds = taskIds;\n }\n}\n\n/** Thrown by `startWatch` when a watch session is already running. */\nexport class WatchInProgressError extends Error {\n readonly code = ENGINE_ERROR_CODES.watchInProgress;\n\n constructor() {\n super(\"A watch session is already running\");\n this.name = \"WatchInProgressError\";\n }\n}\n\nconst hasCode = (error: unknown, code: string): boolean =>\n error instanceof Error && (error as { code?: unknown }).code === code;\n\n/**\n * Identity-independent check for `RunInProgressError`.\n *\n * Prefer this over `instanceof` — see `ENGINE_ERROR_CODES`.\n */\nexport const isRunInProgressError = (\n error: unknown,\n): error is RunInProgressError =>\n hasCode(error, ENGINE_ERROR_CODES.runInProgress);\n\n/** Identity-independent check for `UnknownTargetsError`. */\nexport const isUnknownTargetsError = (\n error: unknown,\n): error is UnknownTargetsError =>\n hasCode(error, ENGINE_ERROR_CODES.unknownTargets);\n\n/** Identity-independent check for `WatchInProgressError`. */\nexport const isWatchInProgressError = (\n error: unknown,\n): error is WatchInProgressError =>\n hasCode(error, ENGINE_ERROR_CODES.watchInProgress);\n","import type ScreenshotTool from \"../screenshot\";\n\nexport type WarmBrowserOptions = {\n /** Builds an un-initialised `ScreenshotTool`. Called once per cold start. */\n create: () => ScreenshotTool;\n /**\n * How long the browser may sit unused before it is shut down.\n * `0` disables warm reuse entirely (close immediately after each release).\n * @default 300_000 (5 minutes)\n */\n idleTimeoutMs?: number;\n /**\n * Called whenever the browser shuts down — idle eviction and `close()`\n * alike. Whatever only makes sense while a browser is warm (the app under\n * test, started for it) goes down with it.\n */\n onShutdown?: () => Promise<void>;\n};\n\n/**\n * Keeps a Playwright browser alive between capture runs.\n *\n * Interactively, a cold Chromium start on every \"Capture\" click is the\n * difference between a snappy tool and a sluggish one — but a browser left\n * running forever is a memory leak, so it is evicted after an idle period.\n *\n * Contexts are recycled on every acquire after the first, because a warm\n * browser's pages carry cookies, storage and scroll position from the previous\n * run and a screenshot taken against leaked state is not the screenshot the CLI\n * would have taken.\n */\nexport class WarmBrowser {\n private readonly createTool: () => ScreenshotTool;\n private readonly idleTimeoutMs: number;\n private readonly onShutdown: (() => Promise<void>) | undefined;\n\n private tool: ScreenshotTool | null = null;\n private idleTimer: ReturnType<typeof setTimeout> | null = null;\n private inUse = false;\n private closed = false;\n /** Outstanding `hold()` leases. While any is held, eviction is suspended. */\n private holds = 0;\n /** Serializes acquire/close so concurrent callers cannot race the browser. */\n private pending: Promise<unknown> = Promise.resolve();\n\n constructor(options: WarmBrowserOptions) {\n this.createTool = options.create;\n this.idleTimeoutMs = options.idleTimeoutMs ?? 300_000;\n this.onShutdown = options.onShutdown;\n }\n\n /** True while a browser process is alive. */\n get isWarm(): boolean {\n return this.tool !== null;\n }\n\n /**\n * Get a ready-to-use `ScreenshotTool`, starting or reusing the browser.\n * Always pair with `release()`.\n */\n async acquire(): Promise<ScreenshotTool> {\n return this.serialize(async () => {\n if (this.closed) {\n throw new Error(\"WarmBrowser has been closed\");\n }\n\n this.cancelIdleTimer();\n this.inUse = true;\n\n if (this.tool) {\n // Reused browser: give the run a clean set of contexts.\n await this.tool.recycleContexts();\n return this.tool;\n }\n\n const tool = this.createTool();\n await tool.init();\n this.tool = tool;\n return tool;\n });\n }\n\n /**\n * Hand the browser back. It stays warm until the idle timeout elapses.\n */\n release(): void {\n this.inUse = false;\n\n if (this.closed || !this.tool) {\n return;\n }\n\n // A lease outranks the idle policy in both directions, including\n // `idleTimeoutMs: 0` — the CLI's one-shot setting, which watch mode\n // otherwise turns into a cold Chromium start on every save.\n if (this.holds > 0) {\n this.cancelIdleTimer();\n return;\n }\n\n if (this.idleTimeoutMs <= 0) {\n void this.close();\n return;\n }\n\n this.startIdleTimer();\n }\n\n /**\n * Suspend idle eviction until the returned function is called.\n *\n * Held by an active watch session. Without it, `WarmBrowser` closes the\n * browser between saves during a coffee break and the next save pays full\n * start-up — which is the entire premise of watch mode, defeated by its own\n * idle handling.\n */\n hold(): () => void {\n this.holds += 1;\n this.cancelIdleTimer();\n\n let released = false;\n return () => {\n if (released) {\n return;\n }\n released = true;\n this.holds -= 1;\n\n // Back to the normal idle policy for a browser nobody is using.\n if (this.holds === 0 && !this.inUse) {\n this.release();\n }\n };\n }\n\n /** True while at least one lease suspends idle eviction. */\n get isHeld(): boolean {\n return this.holds > 0;\n }\n\n /** Shut the browser down now. Safe to call repeatedly. */\n async close(): Promise<void> {\n this.closed = true;\n this.cancelIdleTimer();\n\n await this.serialize(async () => {\n const tool = this.tool;\n this.tool = null;\n this.inUse = false;\n\n try {\n if (tool) {\n await tool.close();\n }\n } finally {\n await this.onShutdown?.();\n }\n });\n }\n\n private startIdleTimer(): void {\n this.cancelIdleTimer();\n\n const timer = setTimeout(() => {\n this.idleTimer = null;\n if (this.inUse || this.closed || this.holds > 0 || !this.tool) {\n return;\n }\n\n void this.evict();\n }, this.idleTimeoutMs);\n\n // Never let an idle browser keep the process alive.\n if (typeof (timer as { unref?: () => void }).unref === \"function\") {\n (timer as { unref: () => void }).unref();\n }\n\n this.idleTimer = timer;\n }\n\n private cancelIdleTimer(): void {\n if (this.idleTimer !== null) {\n clearTimeout(this.idleTimer);\n this.idleTimer = null;\n }\n }\n\n /** Shut the browser down but stay usable — the next acquire starts cold. */\n private async evict(): Promise<void> {\n await this.serialize(async () => {\n if (this.inUse || this.closed || this.holds > 0) {\n return;\n }\n\n const tool = this.tool;\n this.tool = null;\n\n try {\n if (tool) {\n await tool.close();\n }\n } finally {\n await this.onShutdown?.();\n }\n });\n }\n\n private serialize<T>(work: () => Promise<T>): Promise<T> {\n const next = this.pending.then(work, work);\n // Keep the chain alive even when a caller's promise rejects.\n this.pending = next.then(\n () => undefined,\n () => undefined,\n );\n return next;\n }\n}\n","import path from \"node:path\";\nimport type { PluginTask } from \"../plugin\";\nimport type {\n RunnablePlugin,\n RunSummary,\n StartRunRequest,\n} from \"../runner/types\";\nimport type {\n EmittableWatchEvent,\n WatchChange,\n WatchScope,\n WatchStatus,\n} from \"./types\";\n\n/**\n * The slice of a file watcher this session uses.\n *\n * Structural rather than chokidar's own type, so a test can drive a session\n * with a stand-in instead of real filesystem events — which are slow, ordered\n * by the OS rather than by the test, and different on every platform.\n */\nexport interface FileWatcher {\n on(\n event: \"all\",\n listener: (event: string, changedPath: string) => void,\n ): unknown;\n on(event: \"ready\", listener: () => void): unknown;\n on(event: \"error\", listener: (error: unknown) => void): unknown;\n close(): Promise<void>;\n}\n\nexport type CreateFileWatcher = (\n roots: string[],\n options: { cwd: string; ignored: (candidate: string) => boolean },\n) => FileWatcher | Promise<FileWatcher>;\n\n/**\n * Directories no watch should ever descend into.\n *\n * `outputDir` is not here because it is not a fixed name — the engine passes it\n * in. Missing it would be fatal rather than merely noisy: a capture writes PNGs\n * into it, every write is a change, and the session would trigger itself\n * forever.\n */\nexport const DEFAULT_IGNORED_DIRS = new Set([\n \".git\",\n \".cache\",\n \".next\",\n \".nuxt\",\n \".output\",\n \".parcel-cache\",\n \".svelte-kit\",\n \".turbo\",\n \".vercel\",\n \"build\",\n \"coverage\",\n \"dist\",\n \"node_modules\",\n \"storybook-static\",\n]);\n\n/** Watch-mode defaults, exported so the CLI and docs can quote one source. */\nexport const DEFAULT_DEBOUNCE_MS = 300;\nexport const DEFAULT_MAX_TASKS = 200;\n/** How long `start()` waits for the initial filesystem scan before giving up on it. */\nconst READY_TIMEOUT_MS = 10_000;\n\nexport type WatchSessionOptions = {\n plugins: RunnablePlugin[];\n /** Discovered tasks per plugin name. Called once per settled batch. */\n discover: () => Promise<Map<string, PluginTask[]>>;\n /** Start a run. Resolves as soon as the run is registered. */\n startRun: (request: StartRunRequest) => Promise<RunSummary>;\n /** Resolve when the given run reaches a terminal event. */\n waitForRun: (runId: string) => Promise<void>;\n emit?: (event: EmittableWatchEvent) => void;\n cwd?: string;\n /** Roots to watch, relative to `cwd`. @default [\".\"] */\n paths?: string[];\n /** Absolute or `cwd`-relative paths never to watch (the output directory). */\n ignoredPaths?: string[];\n filter?: string;\n debounceMs?: number;\n maxTasks?: number;\n createWatcher?: CreateFileWatcher;\n now?: () => number;\n};\n\n/** What a settled batch of changes resolved to. */\ntype WatchResolution = {\n scope: WatchScope;\n taskIds?: string[];\n request: StartRunRequest;\n};\n\n/**\n * chokidar, loaded on first use.\n *\n * Imported lazily so that requiring `@cappa/core` — which the CLI does for\n * every command, and a plugin does just to get types — never starts a file\n * watcher's dependency tree for a process that will not watch anything.\n */\nconst defaultCreateWatcher: CreateFileWatcher = async (roots, options) => {\n const { watch } = await import(\"chokidar\");\n\n return watch(roots, {\n cwd: options.cwd,\n ignoreInitial: true,\n ignored: (candidate: string) => options.ignored(candidate),\n }) as unknown as FileWatcher;\n};\n\n/**\n * Re-captures affected tasks when files change.\n *\n * A scheduler for runs, deliberately not a second orchestrator: every iteration\n * goes through the engine's ordinary `startRun`, so watch-triggered captures\n * emit the same events, land in the same run store and honour the same\n * one-run-at-a-time rule as a capture somebody clicked.\n *\n * Two behaviours matter more than they look:\n *\n * - **`clearActual` is always false.** Clearing on every save would delete the\n * diffs the user is looking at for tasks they did not touch.\n * - **Changes during a run are queued, never rejected.** The engine's single-run\n * rule stays intact, and the user gets the run they expect rather than a\n * conflict error they did not cause.\n */\nexport class WatchSession {\n private readonly options: WatchSessionOptions;\n private readonly cwd: string;\n private readonly roots: string[];\n private readonly ignoredRoots: string[];\n private readonly debounceMs: number;\n private readonly maxTasks: number;\n private readonly now: () => number;\n\n private watcher: FileWatcher | null = null;\n private readonly pending = new Set<string>();\n private timer: ReturnType<typeof setTimeout> | null = null;\n private draining = false;\n private stopped = false;\n private startedAt: number | undefined;\n private lastChange: WatchChange | undefined;\n\n constructor(options: WatchSessionOptions) {\n this.options = options;\n this.cwd = options.cwd ?? process.cwd();\n this.debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;\n this.maxTasks = options.maxTasks ?? DEFAULT_MAX_TASKS;\n this.now = options.now ?? (() => Date.now());\n\n this.roots = resolveRoots(options.paths, options.plugins);\n this.ignoredRoots = (options.ignoredPaths ?? []).map((entry) =>\n path.resolve(this.cwd, entry),\n );\n }\n\n /** Begin watching. Resolves once the initial scan has settled. */\n async start(): Promise<WatchStatus> {\n if (this.watcher) {\n return this.getStatus();\n }\n\n const create = this.options.createWatcher ?? defaultCreateWatcher;\n const watcher = await create(this.roots, {\n cwd: this.cwd,\n ignored: (candidate) => this.isIgnored(candidate),\n });\n\n // `stop()` can land while the watcher is still being built; closing it here\n // is what stops that race leaving a watcher nobody holds a handle to.\n if (this.stopped) {\n await watcher.close();\n return this.getStatus();\n }\n\n this.watcher = watcher;\n\n watcher.on(\"all\", (event, changedPath) => {\n // Directory events say nothing about what a screenshot would look like;\n // the file events inside them do.\n if (event !== \"add\" && event !== \"change\" && event !== \"unlink\") {\n return;\n }\n this.onFileChanged(changedPath);\n });\n\n // Swallowed on purpose: a watcher that reports an unreadable directory has\n // not stopped watching everything else, and taking the session down over it\n // would be worse than the noise.\n watcher.on(\"error\", () => {});\n\n await this.waitForReady(watcher);\n\n this.startedAt = this.now();\n this.emit({\n type: \"watch:start\",\n paths: this.roots,\n filter: this.options.filter,\n debounceMs: this.debounceMs,\n });\n\n return this.getStatus();\n }\n\n /**\n * Stop watching.\n *\n * Deliberately does not cancel a run already in flight: that run is the\n * answer to a save the user made, and killing it half-way leaves `actual/`\n * holding a partial capture.\n */\n async stop(\n reason: \"requested\" | \"engine-closed\" = \"requested\",\n ): Promise<void> {\n if (this.stopped) {\n return;\n }\n this.stopped = true;\n\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n this.pending.clear();\n\n const watcher = this.watcher;\n this.watcher = null;\n\n try {\n await watcher?.close();\n } finally {\n this.emit({ type: \"watch:stop\", reason });\n }\n }\n\n getStatus(): WatchStatus {\n return {\n active: this.watcher !== null && !this.stopped,\n paths: this.roots,\n filter: this.options.filter,\n debounceMs: this.debounceMs,\n startedAt: this.startedAt,\n lastChange: this.lastChange,\n };\n }\n\n private emit(event: EmittableWatchEvent): void {\n this.options.emit?.(event);\n }\n\n private async waitForReady(watcher: FileWatcher): Promise<void> {\n await new Promise<void>((resolve) => {\n let settled = false;\n const finish = () => {\n if (settled) {\n return;\n }\n settled = true;\n clearTimeout(timer);\n resolve();\n };\n\n // Bounded: a large tree can take a while to scan, but a `ready` that\n // never arrives must not leave `startWatch` hanging forever. Events flow\n // during the scan either way, so proceeding early costs nothing.\n const timer = setTimeout(finish, READY_TIMEOUT_MS);\n timer.unref?.();\n\n watcher.on(\"ready\", finish);\n watcher.on(\"error\", finish);\n });\n }\n\n private onFileChanged(changedPath: string): void {\n if (this.stopped) {\n return;\n }\n\n this.pending.add(toRelative(this.cwd, changedPath));\n\n if (this.timer) {\n clearTimeout(this.timer);\n }\n\n const timer = setTimeout(() => {\n this.timer = null;\n void this.drain();\n }, this.debounceMs);\n timer.unref?.();\n this.timer = timer;\n }\n\n /**\n * Capture for everything pending, one batch at a time.\n *\n * The loop re-reads `pending` after each iteration, which is what turns a\n * save arriving mid-run into the next iteration rather than into a `409`.\n */\n private async drain(): Promise<void> {\n if (this.draining) {\n return;\n }\n this.draining = true;\n\n try {\n while (this.pending.size > 0 && !this.stopped) {\n const files = [...this.pending].sort();\n this.pending.clear();\n await this.captureFor(files);\n }\n } finally {\n this.draining = false;\n }\n }\n\n private async captureFor(files: string[]): Promise<void> {\n const resolution = await this.resolveFiles(files);\n\n if (resolution.scope === \"none\") {\n this.record({ files, scope: \"none\", taskIds: [], at: this.now() });\n return;\n }\n\n let runId: string | undefined;\n let error: string | undefined;\n\n try {\n const summary = await this.options.startRun(resolution.request);\n runId = summary.id;\n } catch (cause) {\n // Most likely a run somebody else started — the CLI in another terminal,\n // or the review UI. Say so and wait for the next save rather than\n // retrying into the same conflict.\n error = cause instanceof Error ? cause.message : String(cause);\n }\n\n this.record({\n files,\n scope: resolution.scope,\n taskIds: resolution.taskIds,\n runId,\n error,\n at: this.now(),\n });\n\n if (runId) {\n await this.options.waitForRun(runId);\n }\n }\n\n private record(change: WatchChange): void {\n this.lastChange = change;\n const { at: _at, ...rest } = change;\n this.emit({ type: \"watch:change\", ...rest });\n }\n\n /**\n * Ask every plugin what the changed files affect, and turn the answers into\n * one run request.\n */\n private async resolveFiles(files: string[]): Promise<WatchResolution> {\n const trigger = { source: \"watch\" as const, files };\n const everything: WatchResolution = {\n scope: \"all\",\n request: {\n filter: this.options.filter,\n clearActual: false,\n trigger,\n },\n };\n\n let tasksByPlugin: Map<string, PluginTask[]>;\n try {\n tasksByPlugin = await this.options.discover();\n } catch {\n // Discovery failing — a dev server mid-restart, most likely — is not a\n // reason to capture nothing. Run everything and let the run report it.\n return everything;\n }\n\n const fullPlugins = new Set<string>();\n const taskIds = new Set<string>();\n\n for (const plugin of this.options.plugins) {\n const tasks = tasksByPlugin.get(plugin.name) ?? [];\n\n if (!plugin.watch) {\n fullPlugins.add(plugin.name);\n continue;\n }\n\n for (const file of files) {\n let resolved: string[] | null;\n try {\n resolved = plugin.watch.resolve(file, tasks);\n } catch {\n // A plugin that throws is a plugin that cannot tell.\n resolved = null;\n }\n\n if (resolved === null) {\n fullPlugins.add(plugin.name);\n break;\n }\n\n for (const id of resolved) {\n taskIds.add(id);\n }\n }\n }\n\n if (fullPlugins.size === 0) {\n if (taskIds.size === 0) {\n return { scope: \"none\", request: {} };\n }\n return this.byTaskIds([...taskIds], trigger, everything);\n }\n\n if (taskIds.size === 0) {\n return {\n scope: \"plugins\",\n request: {\n plugins: [...fullPlugins],\n filter: this.options.filter,\n clearActual: false,\n trigger,\n },\n };\n }\n\n // Mixed: some plugins named tasks, others need everything they own. A\n // request cannot express that directly — `plugins` and `taskIds` compose as\n // \"and\" — so the full plugins are expanded to the ids discovery just\n // produced. The one thing this misses is a task created since that\n // discovery, which the next iteration picks up.\n const expanded = new Set(taskIds);\n for (const name of fullPlugins) {\n for (const task of tasksByPlugin.get(name) ?? []) {\n expanded.add(task.id);\n }\n }\n\n return this.byTaskIds([...expanded], trigger, everything);\n }\n\n /**\n * A run of explicit ids, unless there are so many that naming them is\n * pointless — a branch switch or a formatter pass resolves half the project,\n * and a filtered full run is both cheaper to express and easier to read.\n */\n private byTaskIds(\n taskIds: string[],\n trigger: { source: \"watch\"; files: string[] },\n everything: WatchResolution,\n ): WatchResolution {\n if (taskIds.length > this.maxTasks) {\n return everything;\n }\n\n return {\n scope: \"tasks\",\n taskIds,\n request: {\n taskIds,\n filter: this.options.filter,\n clearActual: false,\n trigger,\n },\n };\n }\n\n private isIgnored(candidate: string): boolean {\n const absolute = path.resolve(this.cwd, candidate);\n const relative = path.relative(this.cwd, absolute);\n\n // Outside the working directory: nothing here can be attributed to a task.\n if (relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n return true;\n }\n\n for (const ignored of this.ignoredRoots) {\n if (\n absolute === ignored ||\n absolute.startsWith(`${ignored}${path.sep}`)\n ) {\n return true;\n }\n }\n\n return relative\n .split(path.sep)\n .some((segment) => DEFAULT_IGNORED_DIRS.has(segment));\n }\n}\n\n/** The part of a glob before its first magic character — the directory to watch. */\nexport const globRoot = (pattern: string): string => {\n const segments = pattern.split(\"/\");\n const staticSegments: string[] = [];\n\n for (const segment of segments) {\n if (/[*?[\\]{}!+@(]/.test(segment)) {\n break;\n }\n staticSegments.push(segment);\n }\n\n // Drop the last static segment only when it is the file itself; a pattern\n // with no magic at all is a literal path and stays as it is.\n const root = staticSegments.join(\"/\");\n return root === \"\" ? \".\" : root;\n};\n\n/**\n * What to hand the watcher.\n *\n * The project root by default, plus the roots of whatever globs the plugins\n * declared. Plugin globs can only widen the set: a plugin that maps story files\n * precisely still has to be told about the component those stories render, and\n * that component is not in its globs.\n */\nconst resolveRoots = (\n paths: string[] | undefined,\n plugins: RunnablePlugin[],\n): string[] => {\n const roots = new Set(paths && paths.length > 0 ? paths : [\".\"]);\n\n for (const plugin of plugins) {\n for (const pattern of plugin.watch?.paths ?? []) {\n roots.add(globRoot(pattern));\n }\n }\n\n // \".\" subsumes everything else.\n if (roots.has(\".\")) {\n return [\".\"];\n }\n\n return [...roots];\n};\n\nconst toRelative = (cwd: string, changedPath: string): string => {\n if (!path.isAbsolute(changedPath)) {\n return changedPath.split(path.sep).join(\"/\");\n }\n return path.relative(cwd, changedPath).split(path.sep).join(\"/\");\n};\n","import { getLogger } from \"@cappa/logger\";\nimport type { LogConsoleEvents } from \"../consoleEvents\";\nimport type { CropSetting } from \"../crop\";\nimport { ScreenshotFileSystem } from \"../filesystem\";\nimport type { PluginTask } from \"../plugin\";\nimport { CaptureRunner } from \"../runner/CaptureRunner\";\nimport type {\n RunDetail,\n RunEvent,\n RunnablePlugin,\n RunSummary,\n StartRunRequest,\n Target,\n} from \"../runner/types\";\nimport ScreenshotTool from \"../screenshot\";\nimport { collectScreenshots } from \"../screenshots/collectScreenshots\";\nimport type { DiffOptions, Screenshot, Viewport } from \"../types\";\nimport {\n type ResolvedWebServerConfig,\n WebServerPool,\n type WebServerPoolOptions,\n} from \"../webServer/WebServerPool\";\nimport { RunStore, type RunStoreOptions } from \"./RunStore\";\nimport {\n type ApproveResult,\n type CaptureEngine,\n type EmittableWatchEvent,\n type ListTargetsOptions,\n type PluginInfo,\n RunInProgressError,\n type ScreenshotQuery,\n type StartWatchRequest,\n type SubscribeOptions,\n UnknownTargetsError,\n type WatchEvent,\n WatchInProgressError,\n type WatchStatus,\n} from \"./types\";\nimport { WarmBrowser } from \"./WarmBrowser\";\nimport {\n type CreateFileWatcher,\n DEFAULT_DEBOUNCE_MS,\n WatchSession,\n} from \"./WatchSession\";\n\nexport type LocalEngineOptions = {\n outputDir: string;\n plugins: RunnablePlugin[];\n diff?: DiffOptions;\n retries?: number;\n concurrency?: number;\n logConsoleEvents?: LogConsoleEvents;\n fullPage?: boolean;\n crop?: CropSetting;\n viewport?: Viewport;\n connectionTimeout?: number;\n /**\n * How long the browser stays warm between runs.\n * @default 300_000 (5 minutes)\n */\n browserIdleTimeoutMs?: number;\n runStore?: RunStoreOptions;\n /** Overrides the screenshot tool factory. Tests use this. */\n createScreenshotTool?: () => ScreenshotTool;\n /** Working directory a watch session watches. @default process.cwd() */\n cwd?: string;\n /** Overrides the file watcher factory. Tests use this. */\n createWatcher?: CreateFileWatcher;\n /** Watch events buffered for replay to a (re)connecting subscriber. @default 200 */\n maxWatchEvents?: number;\n /**\n * The app under test, started before the first run and stopped with the\n * browser — on `close()` and when it goes idle.\n */\n webServer?: ResolvedWebServerConfig[];\n /** Overrides the web server pool's process and probe hooks. Tests use this. */\n webServerPool?: Pick<WebServerPoolOptions, \"spawn\" | \"probe\" | \"killGraceMs\">;\n};\n\nconst defaultLog: NonNullable<WebServerPoolOptions[\"log\"]> = (\n level,\n message,\n) => {\n try {\n getLogger()[level](message);\n } catch {\n // No logger initialised — an embedder that did not ask for output.\n }\n};\n\n/**\n * Stream a web server's output live at debug level. Buffered regardless: the\n * tail is what explains a server that failed to start.\n *\n * To stderr, never stdout — `capture --json` owns stdout.\n */\nconst streamOutputAtDebug = (\n server: ResolvedWebServerConfig,\n chunk: string,\n) => {\n let level = 0;\n try {\n level = getLogger().level;\n } catch {\n return;\n }\n if (level < 4) {\n return;\n }\n const prefix = `[webServer ${server.url}] `;\n process.stderr.write(\n chunk\n .split(/(?<=\\n)/)\n .map((line) => prefix + line)\n .join(\"\"),\n );\n};\n\n/**\n * `CaptureEngine` backed by an in-process Playwright browser.\n *\n * Holds the config's live plugin objects, so it must live in the process that\n * loaded `cappa.config.ts`. The server takes one of these by injection rather\n * than building it, which is what keeps `@cappa/server` free of config loading\n * and makes a remote engine a drop-in alternative.\n *\n * One run at a time. Queuing is deliberately not implemented: the browser pool\n * is the real constraint, and a second concurrent run would fight it.\n */\nexport class LocalEngine implements CaptureEngine {\n private readonly options: LocalEngineOptions;\n private readonly plugins: RunnablePlugin[];\n private readonly fileSystem: ScreenshotFileSystem;\n private readonly browser: WarmBrowser;\n private readonly runs: RunStore;\n private readonly webServers: WebServerPool;\n\n /**\n * Set synchronously the moment a run is claimed, before any `await`, so two\n * concurrent `startRun` calls cannot both pass the check and then fight over\n * the browser. Covers the window between claiming and the run finishing.\n */\n private busy = false;\n private activeRunId: string | null = null;\n private targetsCache: Target[] | null = null;\n /**\n * The tasks behind `targetsCache`, kept whole.\n *\n * A `Target` is what crosses the wire; a plugin's `watch.resolve` needs the\n * task it came from, `data` included — that is where a story's `importPath`\n * lives. Same discovery, two shapes, one cache lifetime.\n */\n private taskCache: Map<string, PluginTask[]> | null = null;\n private closed = false;\n\n private watchSession: WatchSession | null = null;\n private releaseBrowserHold: (() => void) | null = null;\n private readonly watchListeners = new Set<(event: WatchEvent) => void>();\n private watchEvents: WatchEvent[] = [];\n private watchSeq = 0;\n\n constructor(options: LocalEngineOptions) {\n this.options = options;\n this.plugins = options.plugins;\n this.fileSystem = new ScreenshotFileSystem(options.outputDir);\n this.runs = new RunStore(options.runStore);\n this.webServers = new WebServerPool({\n servers: options.webServer ?? [],\n log: defaultLog,\n onOutput: streamOutputAtDebug,\n ...options.webServerPool,\n });\n this.browser = new WarmBrowser({\n create: options.createScreenshotTool ?? (() => this.buildTool()),\n idleTimeoutMs: options.browserIdleTimeoutMs,\n // Same lifetime as the browser, idle timeout included: a review session\n // left open gives the port back, and the next run starts — and rebuilds\n // — the app again.\n onShutdown: () => this.webServers.stop(),\n });\n }\n\n private buildTool(): ScreenshotTool {\n return new ScreenshotTool({\n outputDir: this.options.outputDir,\n diff: this.options.diff,\n retries: this.options.retries,\n concurrency: this.options.concurrency,\n logConsoleEvents: this.options.logConsoleEvents,\n fullPage: this.options.fullPage ?? true,\n crop: this.options.crop ?? false,\n viewport: this.options.viewport ?? { width: 1920, height: 1080 },\n connectionTimeout: this.options.connectionTimeout,\n });\n }\n\n async listPlugins(): Promise<PluginInfo[]> {\n return this.plugins.map((plugin) => ({\n name: plugin.name,\n description: plugin.description,\n }));\n }\n\n /**\n * Discovery needs a browser (plugins query the app under test through it), so\n * this warms the browser on a cache miss.\n *\n * While a run holds the browser, only the cache can be served: discovering\n * would recycle the very contexts the run is capturing with.\n */\n async listTargets(options: ListTargetsOptions = {}): Promise<Target[]> {\n this.assertOpen();\n\n if (this.targetsCache && !options.refresh) {\n return this.targetsCache;\n }\n\n if (this.busy) {\n if (this.targetsCache) {\n return this.targetsCache;\n }\n throw new RunInProgressError(this.activeRunId ?? \"starting\");\n }\n\n return this.discoverTargets();\n }\n\n async startRun(request: StartRunRequest = {}): Promise<RunSummary> {\n this.assertOpen();\n\n if (this.busy) {\n throw new RunInProgressError(this.activeRunId ?? \"starting\");\n }\n\n // Claim before the first await — see the `busy` field comment.\n this.busy = true;\n\n try {\n await this.validateTaskIds(request);\n\n const tool = await this.browser.acquire();\n\n const runner = new CaptureRunner({\n screenshotTool: tool,\n plugins: this.plugins,\n outputDir: this.options.outputDir,\n fileSystem: this.fileSystem,\n // Inside the run rather than before it: `startRun` returns at once\n // even when a build takes a minute, and the start-up lines reach a\n // remote client as ordinary run events.\n prepare: (log) => this.webServers.ensure(log),\n explainUnreachable: (origin) =>\n this.webServers.explainUnreachable(origin),\n });\n\n const finish = () => {\n if (this.activeRunId !== runner.id) {\n return;\n }\n\n // Discovery results may be stale after a run changed what exists.\n this.targetsCache = null;\n this.taskCache = null;\n this.runs.finalize(runner.id);\n this.activeRunId = null;\n this.busy = false;\n this.browser.release();\n };\n\n // Registered *before* the run store, so cleanup completes inside the same\n // synchronous emit as the terminal event and therefore before any\n // subscriber observes it. Without this, the obvious client behaviour —\n // \"the run finished, start the next one\" — races the engine's own\n // teardown and is rejected as though a run were still in progress.\n runner.on((event) => {\n if (event.type === \"run:complete\" || event.type === \"run:error\") {\n finish();\n }\n });\n\n this.runs.add(runner);\n this.activeRunId = runner.id;\n\n // Deliberately not awaited: the caller gets the run id immediately and\n // follows progress through `subscribeRun`.\n void runner\n .run(request)\n .catch(() => {\n // The failure is already on the event stream as `run:error`, and is\n // readable via `getRun`. Swallow it so it is not an unhandled\n // rejection.\n })\n // Belt and braces: `finish` is idempotent, and this covers any terminal\n // path that somehow did not emit an event.\n .finally(finish);\n\n return runner.getSummary();\n } catch (error) {\n this.busy = false;\n this.activeRunId = null;\n throw error;\n }\n }\n\n async getRun(id: string): Promise<RunDetail | undefined> {\n return this.runs.get(id);\n }\n\n async listRuns(): Promise<RunSummary[]> {\n return this.runs.list();\n }\n\n async cancelRun(id: string): Promise<void> {\n this.runs.getRunner(id)?.abort();\n }\n\n subscribeRun(\n id: string,\n onEvent: (event: RunEvent) => void,\n options: SubscribeOptions = {},\n ): () => void {\n return this.runs.subscribe(id, onEvent, options);\n }\n\n /**\n * Read the screenshot index from disk.\n *\n * Always a fresh read rather than a cached snapshot — anything can write to\n * `outputDir` while the server is up, including a CLI run in another terminal.\n */\n async listScreenshots(query: ScreenshotQuery = {}): Promise<Screenshot[]> {\n let screenshots = await collectScreenshots(this.options.outputDir);\n\n if (query.category) {\n screenshots = screenshots.filter(\n (screenshot) => screenshot.category === query.category,\n );\n }\n\n if (query.search) {\n const term = query.search.toLowerCase();\n screenshots = screenshots.filter((screenshot) =>\n screenshot.name.toLowerCase().includes(term),\n );\n }\n\n return screenshots;\n }\n\n async approve(names: string[]): Promise<ApproveResult> {\n const screenshots = await this.listScreenshots();\n const approved: string[] = [];\n const errors: { name: string; error: string }[] = [];\n\n for (const name of names) {\n const screenshot = screenshots.find((entry) => entry.name === name);\n if (!screenshot) {\n errors.push({ name, error: \"Screenshot not found\" });\n continue;\n }\n\n try {\n await this.fileSystem.approveScreenshots(\n [screenshot],\n this.options.diff ?? { type: \"pixel\" },\n );\n approved.push(name);\n } catch (error) {\n errors.push({\n name,\n error: error instanceof Error ? error.message : \"Approval failed\",\n });\n }\n }\n\n return { approved, errors };\n }\n\n /**\n * Re-capture affected tasks on file change until `stopWatch`.\n *\n * Every iteration goes through `startRun`, so a watch-triggered capture is an\n * ordinary run: same events, same run store, same single-run rule, visible in\n * `listRuns` and in the UI. Watch is a scheduler, not a second orchestrator.\n */\n async startWatch(request: StartWatchRequest = {}): Promise<WatchStatus> {\n this.assertOpen();\n\n if (this.watchSession) {\n throw new WatchInProgressError();\n }\n\n // Held for the session's whole life: without it the idle timer closes the\n // browser between saves, and the next save pays a cold start — the exact\n // cost watch mode exists to avoid.\n const release = this.browser.hold();\n\n const session = new WatchSession({\n plugins: this.plugins,\n cwd: this.options.cwd,\n paths: request.paths,\n // Captures write into `outputDir`. Watching it would make every run\n // trigger the next one, forever.\n ignoredPaths: [this.options.outputDir],\n filter: request.filter,\n debounceMs: request.debounceMs,\n maxTasks: request.maxTasks,\n createWatcher: this.options.createWatcher,\n discover: () => this.discoverTasks(),\n startRun: (runRequest) => this.startRun(runRequest),\n waitForRun: (runId) => this.waitForRun(runId),\n emit: (event) => this.emitWatchEvent(event),\n });\n\n this.watchSession = session;\n this.releaseBrowserHold = release;\n\n try {\n return await session.start();\n } catch (error) {\n this.watchSession = null;\n this.releaseBrowserHold = null;\n release();\n throw error;\n }\n }\n\n async stopWatch(): Promise<WatchStatus> {\n await this.endWatch(\"requested\");\n return this.getWatchStatus();\n }\n\n async getWatchStatus(): Promise<WatchStatus> {\n return (\n this.watchSession?.getStatus() ?? {\n active: false,\n paths: [],\n debounceMs: DEFAULT_DEBOUNCE_MS,\n }\n );\n }\n\n subscribeWatch(\n onEvent: (event: WatchEvent) => void,\n options: SubscribeOptions = {},\n ): () => void {\n const sinceSeq = options.sinceSeq ?? 0;\n for (const event of this.watchEvents) {\n if (event.seq > sinceSeq) {\n onEvent(event);\n }\n }\n\n this.watchListeners.add(onEvent);\n return () => {\n this.watchListeners.delete(onEvent);\n };\n }\n\n async close(): Promise<void> {\n this.closed = true;\n\n await this.endWatch(\"engine-closed\");\n\n const runner = this.activeRunId\n ? this.runs.getRunner(this.activeRunId)\n : undefined;\n runner?.abort();\n\n try {\n await this.browser.close();\n } finally {\n // Also covered by the browser's shutdown hook — but a browser that never\n // started has nothing to shut down, and a server may still be starting.\n await this.webServers.stop();\n }\n }\n\n private async endWatch(reason: \"requested\" | \"engine-closed\"): Promise<void> {\n const session = this.watchSession;\n const release = this.releaseBrowserHold;\n this.watchSession = null;\n this.releaseBrowserHold = null;\n\n try {\n await session?.stop(reason);\n } finally {\n release?.();\n }\n }\n\n private emitWatchEvent(event: EmittableWatchEvent): void {\n this.watchSeq += 1;\n const full = { ...event, seq: this.watchSeq, at: Date.now() } as WatchEvent;\n\n this.watchEvents.push(full);\n const max = this.options.maxWatchEvents ?? 200;\n if (this.watchEvents.length > max) {\n this.watchEvents = this.watchEvents.slice(-max);\n }\n\n for (const listener of this.watchListeners) {\n try {\n listener(full);\n } catch {\n // A failing subscriber must not stop the watch session.\n }\n }\n }\n\n /** Resolve once a run reaches a terminal event. */\n private waitForRun(id: string): Promise<void> {\n return new Promise<void>((resolve) => {\n let unsubscribe: (() => void) | undefined;\n let finished = false;\n\n const finish = () => {\n if (finished) {\n return;\n }\n finished = true;\n unsubscribe?.();\n resolve();\n };\n\n unsubscribe = this.runs.subscribe(id, (event) => {\n if (event.type === \"run:complete\" || event.type === \"run:error\") {\n finish();\n }\n });\n\n // Buffered events replay synchronously, so a run that is already over\n // finished before `unsubscribe` existed.\n if (finished) {\n unsubscribe();\n }\n });\n }\n\n /** True while a browser process is alive. Exposed for tests and diagnostics. */\n get isWarm(): boolean {\n return this.browser.isWarm;\n }\n\n private assertOpen(): void {\n if (this.closed) {\n throw new Error(\"Engine has been closed\");\n }\n }\n\n /**\n * A client may only ask for tasks that discovery produced.\n *\n * This is a security boundary as much as a correctness one: it is what stops\n * a request from steering the browser to an arbitrary URL.\n */\n private async validateTaskIds(request: StartRunRequest): Promise<void> {\n if (!request.taskIds || request.taskIds.length === 0) {\n return;\n }\n\n // Bypasses the public `listTargets` busy guard on purpose: this runs after\n // the run is claimed but before the browser is acquired, so discovery here\n // cannot disturb an in-flight capture.\n const targets = this.targetsCache ?? (await this.discoverTargets());\n const known = new Set(targets.map((target) => target.id));\n const unknown = request.taskIds.filter((id) => !known.has(id));\n\n if (unknown.length > 0) {\n throw new UnknownTargetsError(unknown);\n }\n }\n\n /** Discovered tasks per plugin, whole. Cached with `targetsCache`. */\n private async discoverTasks(): Promise<Map<string, PluginTask[]>> {\n if (this.taskCache) {\n return this.taskCache;\n }\n\n await this.discoverTargets();\n return this.taskCache ?? new Map();\n }\n\n private async discoverTargets(): Promise<Target[]> {\n const tool = await this.browser.acquire();\n\n try {\n // Plugins discover by asking the app, so it has to be up.\n await this.webServers.ensure();\n\n const discovered = await Promise.all(\n this.plugins.map(async (plugin) => {\n const tasks = await plugin.discover(tool);\n return { plugin: plugin.name, tasks };\n }),\n );\n\n this.taskCache = new Map(\n discovered.map(({ plugin, tasks }) => [plugin, tasks]),\n );\n\n this.targetsCache = discovered.flatMap(({ plugin, tasks }) =>\n tasks.map((task) => ({\n id: task.id,\n url: task.url,\n plugin,\n })),\n );\n return this.targetsCache;\n } finally {\n this.browser.release();\n }\n }\n}\n","import path from \"node:path\";\nimport { ScreenshotFileSystem } from \"./filesystem\";\nimport type { DiffMetadata } from \"./types\";\n\n/** The three buckets a screenshot can live in. */\nexport type ScreenshotBucket = \"actual\" | \"expected\" | \"diff\";\n\n/**\n * Byte storage for screenshots, addressed by bucket + relative key\n * (`button--primary.png`, `nested/card.png`).\n *\n * `ScreenshotFileSystem` is local-disk by construction, which is correct for\n * the CLI and a local server but not for an engine running on a machine the\n * reviewer cannot reach. This interface is the seam: an object-store\n * implementation later is an implementation, not a fork.\n *\n * Only `FsScreenshotStore` exists today — nothing in the codebase depends on a\n * second implementation, and none is planned in this change.\n */\nexport interface ScreenshotStore {\n has(bucket: ScreenshotBucket, key: string): Promise<boolean>;\n read(bucket: ScreenshotBucket, key: string): Promise<Buffer>;\n write(bucket: ScreenshotBucket, key: string, data: Buffer): Promise<void>;\n /** Relative keys, recursively. */\n list(bucket: ScreenshotBucket): Promise<string[]>;\n remove(bucket: ScreenshotBucket, key: string): Promise<void>;\n /** Drop every object in a bucket. */\n clear(bucket: ScreenshotBucket): Promise<void>;\n readMeta(key: string): Promise<DiffMetadata | undefined>;\n writeMeta(key: string, meta: DiffMetadata): Promise<void>;\n}\n\n/**\n * `ScreenshotStore` over the local filesystem, delegating to\n * `ScreenshotFileSystem` so both views stay consistent.\n */\nexport class FsScreenshotStore implements ScreenshotStore {\n private readonly fs: ScreenshotFileSystem;\n\n constructor(outputDirOrFs: string | ScreenshotFileSystem) {\n this.fs =\n typeof outputDirOrFs === \"string\"\n ? new ScreenshotFileSystem(outputDirOrFs)\n : outputDirOrFs;\n }\n\n private dirFor(bucket: ScreenshotBucket): string {\n if (bucket === \"actual\") return this.fs.getActualDir();\n if (bucket === \"expected\") return this.fs.getExpectedDir();\n return this.fs.getDiffDir();\n }\n\n private pathFor(bucket: ScreenshotBucket, key: string): string {\n if (bucket === \"actual\") return this.fs.getActualFilePath(key);\n if (bucket === \"expected\") return this.fs.getExpectedFilePath(key);\n return this.fs.getDiffFilePath(key);\n }\n\n async has(bucket: ScreenshotBucket, key: string): Promise<boolean> {\n if (bucket === \"expected\") {\n return this.fs.hasExpectedFile(key);\n }\n\n const fsp = await import(\"node:fs/promises\");\n try {\n await fsp.access(this.pathFor(bucket, key));\n return true;\n } catch {\n return false;\n }\n }\n\n async read(bucket: ScreenshotBucket, key: string): Promise<Buffer> {\n if (bucket === \"expected\") {\n return this.fs.readExpectedFile(key);\n }\n\n const fsp = await import(\"node:fs/promises\");\n return fsp.readFile(this.pathFor(bucket, key));\n }\n\n async write(\n bucket: ScreenshotBucket,\n key: string,\n data: Buffer,\n ): Promise<void> {\n if (bucket === \"actual\") {\n await this.fs.writeActualFile(key, data);\n return;\n }\n if (bucket === \"diff\") {\n await this.fs.writeDiffFile(key, data);\n return;\n }\n\n const filePath = this.pathFor(bucket, key);\n await this.fs.ensureParentDir(filePath);\n const fsp = await import(\"node:fs/promises\");\n await fsp.writeFile(filePath, data);\n }\n\n async list(bucket: ScreenshotBucket): Promise<string[]> {\n const files =\n bucket === \"actual\"\n ? await this.fs.getActualScreenshots()\n : bucket === \"expected\"\n ? await this.fs.getExpectedScreenshots()\n : await this.fs.getDiffScreenshots();\n\n const dir = this.dirFor(bucket);\n return files.map((file) => path.relative(dir, file));\n }\n\n async remove(bucket: ScreenshotBucket, key: string): Promise<void> {\n const fsp = await import(\"node:fs/promises\");\n await fsp.rm(this.pathFor(bucket, key), { force: true });\n }\n\n async clear(bucket: ScreenshotBucket): Promise<void> {\n if (bucket === \"actual\") {\n this.fs.clearActual();\n return;\n }\n if (bucket === \"diff\") {\n this.fs.clearDiff();\n return;\n }\n\n throw new Error(\n \"Refusing to clear the expected/ bucket: it holds the approved baselines\",\n );\n }\n\n async readMeta(key: string): Promise<DiffMetadata | undefined> {\n const { readDiffMeta } = await import(\"./filesystem\");\n return readDiffMeta(this.fs.getDiffFilePath(key));\n }\n\n async writeMeta(key: string, meta: DiffMetadata): Promise<void> {\n await this.fs.writeDiffMetaFile(key, meta);\n }\n}\n","import path from \"node:path\";\nimport type { BoundingBox } from \"@blazediff/interpret-native\";\nimport sharp, { type OverlayOptions } from \"sharp\";\n\n/**\n * Evidence images for a judge, sized for a model's context window rather than\n * for a human's screen.\n *\n * A full-page screenshot is easily 1920x8000 — expensive to read and mostly\n * unchanged. A judge needs two things instead: where the changes are\n * (`locator.png`, a small outlined thumbnail) and what each one looks like\n * before and after (`regions.png`, tight crops side by side). Together they\n * are typically one to two orders of magnitude smaller than the full images.\n */\n\nexport type TileOptions = {\n expectedPath: string;\n actualPath: string;\n /** Diff image to outline the regions on; falls back to the actual image. */\n diffPath?: string;\n /** Regions, largest first — row order in `regions.png` follows this. */\n regions: readonly BoundingBox[];\n outDir: string;\n /** Regions rendered into `regions.png`. Default 8. */\n maxRegions?: number;\n /**\n * Minimum context kept around each region, in pixels; grows with the\n * region's size. Default 24.\n */\n padding?: number;\n /** Largest width a single crop is rendered at. Default 640. */\n maxCropWidth?: number;\n};\n\nexport type TileResult = {\n /** Absolute path, or undefined when nothing could be drawn. */\n locator?: string;\n /** Absolute path, or undefined when there were no regions. */\n regions?: string;\n /** How many regions `regions.png` holds (≤ `maxRegions`). */\n renderedRegions: number;\n};\n\nconst LOCATOR_MAX_WIDTH = 400;\nconst LOCATOR_MAX_HEIGHT = 1200;\nconst GUTTER = 12;\nconst ROW_GUTTER = 16;\nconst LABEL_HEIGHT = 18;\nconst BACKGROUND = { r: 128, g: 128, b: 128 };\n\nconst escapeXml = (text: string) =>\n text.replace(/[<>&\"]/g, (c) => `&#${c.charCodeAt(0)};`);\n\n/** A caption strip, so a row reads as \"#2 expected | #2 actual\" at a glance. */\nconst label = (text: string, width: number): Buffer =>\n Buffer.from(\n `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${width}\" height=\"${LABEL_HEIGHT}\"><rect width=\"100%\" height=\"100%\" fill=\"#222\"/><text x=\"4\" y=\"13\" font-family=\"sans-serif\" font-size=\"12\" fill=\"#fff\">${escapeXml(text)}</text></svg>`,\n );\n\nexport const padAndClamp = (\n bbox: BoundingBox,\n padding: number | { x: number; y: number },\n width: number,\n height: number,\n): BoundingBox => {\n const padX = typeof padding === \"number\" ? padding : padding.x;\n const padY = typeof padding === \"number\" ? padding : padding.y;\n const x = Math.max(0, Math.floor(bbox.x - padX));\n const y = Math.max(0, Math.floor(bbox.y - padY));\n const right = Math.min(width, Math.ceil(bbox.x + bbox.width + padX));\n const bottom = Math.min(height, Math.ceil(bbox.y + bbox.height + padY));\n return {\n x,\n y,\n width: Math.max(1, right - x),\n height: Math.max(1, bottom - y),\n };\n};\n\nconst clamp = (value: number, min: number, max: number) =>\n Math.min(max, Math.max(min, value));\n\n/**\n * Context kept around a region: proportional to its size, within bounds.\n *\n * A fixed margin is too tight for small regions — a changed letter cropped\n * with 24px around it says nothing about whether a button label got\n * truncated — and wasteful for large ones.\n */\nexport const contextPadding = (\n bbox: BoundingBox,\n minimum: number,\n): { x: number; y: number } => ({\n x: clamp(bbox.width, minimum * 2, 160),\n y: clamp(bbox.height, minimum, 96),\n});\n\n/** Scale that fits `width`x`height` into the bounds without upscaling. */\nconst fitScale = (\n width: number,\n height: number,\n maxWidth: number,\n maxHeight: number,\n) => Math.min(1, maxWidth / width, maxHeight / height);\n\nconst readSize = async (file: string) => {\n const { width, height } = await sharp(file).metadata();\n if (!width || !height) {\n throw new Error(`Unable to read image dimensions: ${file}`);\n }\n return { width, height };\n};\n\nconst renderCrop = async (\n file: string,\n box: BoundingBox,\n scale: number,\n): Promise<Buffer> => {\n const crop = sharp(file).extract({\n left: box.x,\n top: box.y,\n width: box.width,\n height: box.height,\n });\n if (scale < 1) {\n crop.resize(\n Math.max(1, Math.round(box.width * scale)),\n Math.max(1, Math.round(box.height * scale)),\n );\n }\n return crop.png().toBuffer();\n};\n\nconst renderRegions = async (\n options: TileOptions,\n width: number,\n height: number,\n): Promise<{ file: string; count: number } | undefined> => {\n const padding = options.padding ?? 24;\n const maxCropWidth = options.maxCropWidth ?? 640;\n const regions = options.regions.slice(0, options.maxRegions ?? 8);\n\n if (regions.length === 0) return undefined;\n\n const rows = await Promise.all(\n regions.map(async (region) => {\n const box = padAndClamp(\n region,\n contextPadding(region, padding),\n width,\n height,\n );\n const scale = Math.min(1, maxCropWidth / box.width);\n const [expected, actual] = await Promise.all([\n renderCrop(options.expectedPath, box, scale),\n renderCrop(options.actualPath, box, scale),\n ]);\n return {\n expected,\n actual,\n width: Math.max(1, Math.round(box.width * scale)),\n height: Math.max(1, Math.round(box.height * scale)),\n };\n }),\n );\n\n // Wide enough for the captions even when a crop is a sliver.\n const columnWidth = (row: { width: number }) => Math.max(row.width, 96);\n const canvasWidth = Math.max(\n ...rows.map((row) => columnWidth(row) * 2 + GUTTER),\n );\n const canvasHeight =\n rows.reduce((sum, row) => sum + LABEL_HEIGHT + row.height, 0) +\n ROW_GUTTER * (rows.length - 1);\n\n const composites: OverlayOptions[] = [];\n let top = 0;\n rows.forEach((row, index) => {\n const column = columnWidth(row);\n const right = column + GUTTER;\n composites.push(\n { input: label(`#${index + 1} expected`, column), left: 0, top },\n { input: label(`#${index + 1} actual`, column), left: right, top },\n { input: row.expected, left: 0, top: top + LABEL_HEIGHT },\n { input: row.actual, left: right, top: top + LABEL_HEIGHT },\n );\n top += LABEL_HEIGHT + row.height + ROW_GUTTER;\n });\n\n const file = path.join(options.outDir, \"regions.png\");\n await sharp({\n create: {\n width: canvasWidth,\n height: canvasHeight,\n channels: 3,\n background: BACKGROUND,\n },\n })\n .composite(composites)\n .png()\n .toFile(file);\n\n return { file, count: rows.length };\n};\n\nconst renderLocator = async (\n options: TileOptions,\n width: number,\n height: number,\n): Promise<string> => {\n const scale = fitScale(width, height, LOCATOR_MAX_WIDTH, LOCATOR_MAX_HEIGHT);\n const locatorWidth = Math.max(1, Math.round(width * scale));\n const locatorHeight = Math.max(1, Math.round(height * scale));\n\n // Numbered so a region in the thumbnail can be matched to its row in\n // `regions.png` and its entry in `request.json` without counting boxes.\n const shapes = options.regions\n .map((region, index) => {\n const x = Math.round(region.x * scale);\n const y = Math.round(region.y * scale);\n const w = Math.max(2, Math.round(region.width * scale));\n const h = Math.max(2, Math.round(region.height * scale));\n return `<rect x=\"${x}\" y=\"${y}\" width=\"${w}\" height=\"${h}\" fill=\"none\" stroke=\"red\" stroke-width=\"2\"/><text x=\"${x + 2}\" y=\"${Math.max(12, y - 3)}\" font-family=\"sans-serif\" font-size=\"12\" font-weight=\"bold\" fill=\"red\" stroke=\"#fff\" stroke-width=\"3\" paint-order=\"stroke\">${index + 1}</text>`;\n })\n .join(\"\");\n const svg = `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${locatorWidth}\" height=\"${locatorHeight}\">${shapes}</svg>`;\n\n const file = path.join(options.outDir, \"locator.png\");\n await sharp(options.diffPath ?? options.actualPath)\n .resize(locatorWidth, locatorHeight, { fit: \"fill\" })\n .composite([{ input: Buffer.from(svg), left: 0, top: 0 }])\n .png()\n .toFile(file);\n\n return file;\n};\n\n/**\n * Write `locator.png` and `regions.png` into `outDir`.\n *\n * Expected and actual must have the same dimensions — region boxes are only\n * meaningful when both images share a coordinate space. Use\n * {@link renderOverview} when they do not.\n */\nexport const renderJudgmentTiles = async (\n options: TileOptions,\n): Promise<TileResult> => {\n const { width, height } = await readSize(options.actualPath);\n\n const [regions, locator] = await Promise.all([\n renderRegions(options, width, height),\n renderLocator(options, width, height),\n ]);\n\n return {\n locator,\n regions: regions?.file,\n renderedRegions: regions?.count ?? 0,\n };\n};\n\n/**\n * Write `overview.png`: expected and actual, scaled down side by side.\n *\n * For screenshots whose dimensions changed, where no region can be located,\n * this is what the judge looks at instead of two full-size images.\n */\nexport const renderOverview = async (options: {\n expectedPath: string;\n actualPath: string;\n outDir: string;\n}): Promise<string> => {\n const [expectedSize, actualSize] = await Promise.all([\n readSize(options.expectedPath),\n readSize(options.actualPath),\n ]);\n\n // One scale for both, so a height difference stays visible as one.\n const scale = Math.min(\n fitScale(\n expectedSize.width,\n expectedSize.height,\n LOCATOR_MAX_WIDTH,\n LOCATOR_MAX_HEIGHT,\n ),\n fitScale(\n actualSize.width,\n actualSize.height,\n LOCATOR_MAX_WIDTH,\n LOCATOR_MAX_HEIGHT,\n ),\n );\n\n const scaled = (size: { width: number; height: number }) => ({\n width: Math.max(1, Math.round(size.width * scale)),\n height: Math.max(1, Math.round(size.height * scale)),\n });\n const expected = scaled(expectedSize);\n const actual = scaled(actualSize);\n\n const [expectedBuffer, actualBuffer] = await Promise.all([\n sharp(options.expectedPath)\n .resize(expected.width, expected.height, { fit: \"fill\" })\n .png()\n .toBuffer(),\n sharp(options.actualPath)\n .resize(actual.width, actual.height, { fit: \"fill\" })\n .png()\n .toBuffer(),\n ]);\n\n const file = path.join(options.outDir, \"overview.png\");\n await sharp({\n create: {\n width: expected.width + GUTTER + actual.width,\n height: LABEL_HEIGHT + Math.max(expected.height, actual.height),\n channels: 3,\n background: BACKGROUND,\n },\n })\n .composite([\n {\n input: label(\n `expected ${expectedSize.width}x${expectedSize.height}`,\n expected.width,\n ),\n left: 0,\n top: 0,\n },\n {\n input: label(\n `actual ${actualSize.width}x${actualSize.height}`,\n actual.width,\n ),\n left: expected.width + GUTTER,\n top: 0,\n },\n { input: expectedBuffer, left: 0, top: LABEL_HEIGHT },\n {\n input: actualBuffer,\n left: expected.width + GUTTER,\n top: LABEL_HEIGHT,\n },\n ])\n .png()\n .toFile(file);\n\n return file;\n};\n","import { createHash } from \"node:crypto\";\nimport fsp from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport {\n type ChangeRegion,\n type InterpretResult,\n interpret,\n} from \"@blazediff/interpret-native\";\nimport sharp from \"sharp\";\nimport { writeCommonCanvas } from \"../features/png/canvas\";\nimport { mapWithConcurrency } from \"../mapWithConcurrency\";\nimport { collectScreenshots } from \"../screenshots/collectScreenshots\";\nimport type { DiffOptions, Screenshot } from \"../types\";\nimport {\n AGENT_REPORT_VERSION,\n agentDir,\n agentReportPath,\n judgmentsRoot,\n} from \"./paths\";\nimport { renderJudgmentTiles, renderOverview } from \"./tiles\";\nimport {\n ACTION_BY_LABEL,\n describeChange,\n isVerdictLabel,\n type Verdict,\n type VerdictLabel,\n} from \"./verdict\";\n\n/**\n * Agent review: turn the screenshots on disk into something a coding agent\n * can judge cheaply, and fold its judgments back in.\n *\n * Every changed screenshot gets a judgment request. Nothing is labelled from\n * diff signals alone — see `VERDICT_LABELS` for why.\n *\n * Nothing here captures. It reads `actual/`, `expected/` and `diff/` as the\n * last `cappa capture` left them, so it is safe to run repeatedly — a re-run\n * is how an agent's verdicts are applied, and a re-capture invalidates them\n * automatically because every judgment is tied to a fingerprint of the two\n * images it was made about.\n *\n * Layout, all inside `<outputDir>/.cappa-agent/` (dot-prefixed, so neither\n * screenshot collection nor the review server's static handler touch it):\n *\n * ```\n * report.json full report of the last check\n * judgments/<name>/request.json what to judge and where the evidence is\n * judgments/<name>/locator.png thumbnail with every region outlined\n * judgments/<name>/regions.png [expected | actual] crop per region\n * judgments/<name>/overview.png both images whole, when their sizes differ\n * judgments/<name>/verdict.json written by the judge\n * ```\n */\nconst REQUEST_FILE = \"request.json\";\nconst VERDICT_FILE = \"verdict.json\";\nconst JUDGMENT_FILES = [\n REQUEST_FILE,\n VERDICT_FILE,\n \"locator.png\",\n \"regions.png\",\n \"overview.png\",\n];\n\nexport type AgentRegion = {\n /** 1-based, matching the numbers in `locator.png` and rows in `regions.png`. */\n index: number;\n bbox: { x: number; y: number; width: number; height: number };\n pixelCount: number;\n percentage: number;\n position: string;\n shape: string;\n};\n\n/** A judge's verdict, as applied to a screenshot. */\nexport type AppliedVerdict = Verdict & {\n confidence?: number;\n};\n\nexport type JudgmentPaths = {\n dir: string;\n request: string;\n verdict: string;\n locator?: string;\n regions?: string;\n overview?: string;\n};\n\nexport type AgentReportEntry = {\n name: string;\n category: \"changed\" | \"new\" | \"deleted\";\n taskId?: string;\n plugin?: string;\n /** Absolute paths to the screenshot files. */\n paths: { expected?: string; actual?: string; diff?: string };\n percentDifference?: number;\n numDiffPixels?: number;\n dimensions?: {\n expected: { width: number; height: number };\n actual: { width: number; height: number };\n };\n /**\n * Where and how much it changed, e.g. `2 regions @ top-left (1.20%)`. The\n * same change on different screenshots reads the same, so it groups them.\n */\n change?: string;\n /** Largest first. */\n regions?: AgentRegion[];\n /** The judge's verdict, once one was written about these images. */\n verdict?: AppliedVerdict;\n /** A changed screenshot without a valid verdict yet. */\n pending: boolean;\n judgment?: JudgmentPaths;\n /** Why a `verdict.json` that exists was ignored. */\n verdictError?: string;\n};\n\nexport type AgentReport = {\n version: number;\n createdAt: string;\n outputDir: string;\n reportPath: string;\n totals: {\n total: number;\n passed: number;\n changed: number;\n new: number;\n deleted: number;\n pendingJudgments: number;\n };\n /** Every non-passing screenshot, changed ones first. */\n entries: AgentReportEntry[];\n};\n\n/**\n * The directory holding a screenshot's judgment.\n *\n * Screenshot names are relative paths (`example/button/primary`), so they map\n * onto nested directories directly; anything that would resolve outside the\n * judgments root is refused rather than written.\n */\nexport const judgmentDir = (outputDir: string, name: string): string => {\n const root = judgmentsRoot(outputDir);\n const dir = path.resolve(root, name);\n const relative = path.relative(root, dir);\n if (!relative || relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n throw new Error(`Invalid screenshot name for a judgment: ${name}`);\n }\n return dir;\n};\n\nconst exists = async (file: string): Promise<boolean> => {\n try {\n await fsp.access(file);\n return true;\n } catch {\n return false;\n }\n};\n\nconst readJson = async (file: string): Promise<unknown> => {\n try {\n return JSON.parse(await fsp.readFile(file, \"utf8\"));\n } catch {\n return undefined;\n }\n};\n\nconst writeJson = async (file: string, value: unknown): Promise<void> => {\n await fsp.mkdir(path.dirname(file), { recursive: true });\n await fsp.writeFile(file, `${JSON.stringify(value, null, 2)}\\n`, \"utf8\");\n};\n\n/** Ties a judgment to the exact pair of images it was made about. */\nexport const fingerprintImages = async (\n expectedPath: string,\n actualPath: string,\n): Promise<string> => {\n const [expected, actual] = await Promise.all([\n fsp.readFile(expectedPath),\n fsp.readFile(actualPath),\n ]);\n return createHash(\"sha256\")\n .update(expected)\n .update(\"\\0\")\n .update(actual)\n .digest(\"hex\");\n};\n\nexport type ParsedAgentVerdict =\n | {\n ok: true;\n label: VerdictLabel;\n headline: string;\n rationale: string[];\n confidence?: number;\n }\n | { ok: false; error: string };\n\n/**\n * Read a judge's verdict, accepting both the nested shape blazediff uses\n * (`{ verdict: { label, headline, rationale }, confidence }`) and a flat one\n * (`{ label, headline, rationale, confidence }`) — a judge that writes either\n * should not have its work thrown away over nesting.\n */\nexport const parseAgentVerdict = (raw: unknown): ParsedAgentVerdict => {\n if (typeof raw !== \"object\" || raw === null) {\n return { ok: false, error: \"verdict.json is not a JSON object\" };\n }\n\n const outer = raw as Record<string, unknown>;\n const inner =\n typeof outer.verdict === \"object\" && outer.verdict !== null\n ? (outer.verdict as Record<string, unknown>)\n : outer;\n\n const label = inner.label;\n if (!isVerdictLabel(label)) {\n return {\n ok: false,\n error: `label must be one of regression-likely, intentional-likely, noise-likely (got ${JSON.stringify(label)})`,\n };\n }\n\n const headline =\n typeof inner.headline === \"string\" && inner.headline.trim()\n ? inner.headline.trim()\n : undefined;\n if (!headline) {\n return { ok: false, error: \"headline must be a non-empty string\" };\n }\n\n const toLines = (value: unknown): string[] =>\n Array.isArray(value)\n ? value.filter((line): line is string => typeof line === \"string\")\n : typeof value === \"string\" && value.trim()\n ? [value.trim()]\n : [];\n const rationale = [...toLines(inner.rationale)];\n if (inner !== outer) rationale.push(...toLines(outer.rationale));\n\n const rawConfidence = outer.confidence ?? inner.confidence;\n const confidence =\n typeof rawConfidence === \"number\" && Number.isFinite(rawConfidence)\n ? Math.min(1, Math.max(0, rawConfidence))\n : undefined;\n\n return {\n ok: true,\n label,\n headline,\n rationale,\n ...(confidence !== undefined ? { confidence } : {}),\n };\n};\n\nconst readSize = async (file: string) => {\n const { width = 0, height = 0 } = await sharp(file).metadata();\n return { width, height };\n};\n\n/**\n * Whether the diff on disk can be outlined in the compared coordinate space.\n *\n * Same-size screenshots always qualify. For a size change, only a diff of the\n * padded canvas does — one left by an older capture (a fixed-size\n * placeholder) would be stretched over the regions and misplace them.\n */\nconst diffMatchesCanvas = async (\n diffPath: string,\n comparedActual: string,\n differentSizes: boolean,\n): Promise<boolean> => {\n if (!differentSizes) return true;\n const [diff, canvas] = await Promise.all([\n readSize(diffPath),\n readSize(comparedActual),\n ]);\n return diff.width === canvas.width && diff.height === canvas.height;\n};\n\nconst toAgentRegions = (regions: readonly ChangeRegion[]): AgentRegion[] =>\n [...regions]\n .sort((a, b) => b.pixelCount - a.pixelCount)\n .map((region, index) => ({\n index: index + 1,\n bbox: {\n x: region.bbox.x,\n y: region.bbox.y,\n width: region.bbox.width,\n height: region.bbox.height,\n },\n pixelCount: region.pixelCount,\n percentage: region.percentage,\n position: region.position,\n shape: region.shape,\n }));\n\n/**\n * The interpretation a capture already persisted, or a fresh one.\n *\n * `diff.interpret` is off by default, so most changed screenshots arrive\n * without one; computing it here means agent review works on any project\n * rather than only on those that opted into interpretation at capture time.\n */\nconst interpretationFor = async (\n screenshot: Extract<Screenshot, { category: \"changed\" }>,\n expectedPath: string,\n actualPath: string,\n diff: DiffOptions | undefined,\n): Promise<InterpretResult | undefined> => {\n if (screenshot.diffMeta?.interpretation) {\n return screenshot.diffMeta.interpretation;\n }\n\n const pixel = diff && diff.type !== \"gmsd\" ? diff : undefined;\n try {\n return await interpret(expectedPath, actualPath, undefined, {\n source: \"pixel\",\n threshold: pixel?.threshold,\n antialiasing: pixel?.includeAA ?? false,\n });\n } catch {\n return undefined;\n }\n};\n\nconst JUDGE_INSTRUCTIONS = [\n \"Every changed screenshot differs beyond the project's diff threshold, so sub-pixel rendering is already filtered out: look at each change before labelling it.\",\n \"Read locator.png and regions.png together. locator.png outlines every region (numbered) on a thumbnail; regions.png stacks one [expected | actual] row per region, in `regions` order.\",\n \"overview.png exists only when the image dimensions changed: it shows both images whole, side by side. Regions are then located on a canvas padded to the larger size, anchored top-left — in a crop, area that only one image covers is empty.\",\n \"Compare sizes, not just content: text that is larger, smaller, bolder or reflowed, and spacing, alignment or wrapping that moved, are regressions unless a code change explains them.\",\n \"Only open paths.expected / paths.actual / paths.diff (full size) when a change clearly continues outside its crop.\",\n \"Write verdict.json next to this file, or run `cappa agent judge <name> --label <label> --headline <text>`.\",\n];\n\nconst VERDICT_SCHEMA = {\n label: \"regression-likely | intentional-likely | noise-likely\",\n headline: \"one line describing what changed\",\n rationale: [\"short reasons\"],\n confidence: \"0..1\",\n};\n\nexport type RunAgentCheckOptions = {\n outputDir: string;\n /** The project's diff config — its threshold is reused for interpretation. */\n diff?: DiffOptions;\n /** Regions rendered into `regions.png` per screenshot. Default 8. */\n maxTileRegions?: number;\n /** Screenshots analysed in parallel. Default 4. */\n concurrency?: number;\n now?: () => Date;\n};\n\nconst analyseChanged = async (\n screenshot: Extract<Screenshot, { category: \"changed\" }>,\n options: Required<Pick<RunAgentCheckOptions, \"outputDir\">> &\n RunAgentCheckOptions,\n createdAt: string,\n): Promise<AgentReportEntry> => {\n const { outputDir } = options;\n const expectedPath = path.resolve(outputDir, screenshot.expectedPath);\n const actualPath = path.resolve(outputDir, screenshot.actualPath);\n const diffPath = path.resolve(outputDir, screenshot.diffPath);\n\n const [expectedSize, actualSize, diffExists] = await Promise.all([\n readSize(expectedPath),\n readSize(actualPath),\n exists(diffPath),\n ]);\n const differentSizes =\n expectedSize.width !== actualSize.width ||\n expectedSize.height !== actualSize.height;\n\n // Regions only mean something in a coordinate space both images share, so\n // a size change is analysed on copies padded to a common canvas — the same\n // canvas the capture's own diff was computed on.\n const canvasDir = differentSizes\n ? await fsp.mkdtemp(path.join(os.tmpdir(), \"cappa-agent-canvas-\"))\n : undefined;\n try {\n const canvas = canvasDir\n ? await writeCommonCanvas(expectedPath, actualPath, canvasDir)\n : undefined;\n return await analyseOnCanvas({\n screenshot,\n options,\n createdAt,\n paths: { expectedPath, actualPath, diffPath, diffExists },\n sizes: { expectedSize, actualSize },\n canvas: canvas\n ? { expectedPath: canvas.expectedPath, actualPath: canvas.actualPath }\n : undefined,\n });\n } finally {\n if (canvasDir) await fsp.rm(canvasDir, { recursive: true, force: true });\n }\n};\n\nconst analyseOnCanvas = async ({\n screenshot,\n options,\n createdAt,\n paths: { expectedPath, actualPath, diffPath, diffExists },\n sizes: { expectedSize, actualSize },\n canvas,\n}: {\n screenshot: Extract<Screenshot, { category: \"changed\" }>;\n options: Required<Pick<RunAgentCheckOptions, \"outputDir\">> &\n RunAgentCheckOptions;\n createdAt: string;\n paths: {\n expectedPath: string;\n actualPath: string;\n diffPath: string;\n diffExists: boolean;\n };\n sizes: {\n expectedSize: { width: number; height: number };\n actualSize: { width: number; height: number };\n };\n /** Padded copies of both images, when their sizes differ. */\n canvas?: { expectedPath: string; actualPath: string };\n}): Promise<AgentReportEntry> => {\n const { outputDir } = options;\n const differentSizes = canvas !== undefined;\n const comparedExpected = canvas?.expectedPath ?? expectedPath;\n const comparedActual = canvas?.actualPath ?? actualPath;\n\n const interpretation = await interpretationFor(\n screenshot,\n comparedExpected,\n comparedActual,\n options.diff,\n );\n\n const percentDifference =\n screenshot.diffMeta?.percentDifference ?? interpretation?.diffPercentage;\n const numDiffPixels =\n screenshot.diffMeta?.numDiffPixels ?? interpretation?.diffCount;\n const regions = toAgentRegions(interpretation?.regions ?? []);\n\n const change = describeChange({\n percentDifference,\n numDiffPixels,\n interpretation,\n differentSizes,\n });\n\n const entry: AgentReportEntry = {\n name: screenshot.name,\n category: \"changed\",\n ...(screenshot.taskId\n ? { taskId: screenshot.taskId, plugin: screenshot.plugin }\n : {}),\n paths: {\n expected: expectedPath,\n actual: actualPath,\n ...(diffExists ? { diff: diffPath } : {}),\n },\n percentDifference,\n numDiffPixels,\n dimensions: { expected: expectedSize, actual: actualSize },\n change,\n regions,\n pending: true,\n };\n\n const dir = judgmentDir(outputDir, screenshot.name);\n const requestPath = path.join(dir, REQUEST_FILE);\n const verdictPath = path.join(dir, VERDICT_FILE);\n\n const fingerprint = await fingerprintImages(expectedPath, actualPath);\n\n // A request made about different images makes its verdict meaningless:\n // drop the whole judgment and start over rather than apply a stale label.\n const previous = (await readJson(requestPath)) as\n | { fingerprint?: unknown }\n | undefined;\n if (previous && previous.fingerprint !== fingerprint) {\n await clearJudgmentFiles(dir);\n }\n\n await fsp.mkdir(dir, { recursive: true });\n\n const judgment: JudgmentPaths = {\n dir,\n request: requestPath,\n verdict: verdictPath,\n };\n if (differentSizes) {\n judgment.overview = await renderOverview({\n expectedPath,\n actualPath,\n outDir: dir,\n });\n }\n if (!differentSizes || regions.length > 0) {\n const tiles = await renderJudgmentTiles({\n expectedPath: comparedExpected,\n actualPath: comparedActual,\n diffPath:\n diffExists &&\n (await diffMatchesCanvas(diffPath, comparedActual, differentSizes))\n ? diffPath\n : undefined,\n regions: regions.map((region) => region.bbox),\n outDir: dir,\n maxRegions: options.maxTileRegions,\n });\n if (tiles.locator) judgment.locator = tiles.locator;\n if (tiles.regions) judgment.regions = tiles.regions;\n }\n entry.judgment = judgment;\n\n await writeJson(requestPath, {\n version: AGENT_REPORT_VERSION,\n name: entry.name,\n taskId: entry.taskId,\n plugin: entry.plugin,\n fingerprint,\n createdAt,\n instructions: JUDGE_INSTRUCTIONS,\n verdictSchema: VERDICT_SCHEMA,\n change,\n percentDifference,\n numDiffPixels,\n dimensions: entry.dimensions,\n regions,\n paths: {\n locator: judgment.locator,\n regions: judgment.regions,\n overview: judgment.overview,\n expected: expectedPath,\n actual: actualPath,\n diff: entry.paths.diff,\n verdict: verdictPath,\n },\n });\n\n if (!(await exists(verdictPath))) return entry;\n\n const parsed = parseAgentVerdict(await readJson(verdictPath));\n if (!parsed.ok) {\n entry.verdictError = parsed.error;\n return entry;\n }\n\n entry.pending = false;\n entry.verdict = {\n label: parsed.label,\n headline: parsed.headline,\n rationale: parsed.rationale,\n action: ACTION_BY_LABEL[parsed.label],\n ...(parsed.confidence !== undefined\n ? { confidence: parsed.confidence }\n : {}),\n };\n return entry;\n};\n\nconst clearJudgmentFiles = async (dir: string): Promise<void> => {\n await Promise.all(\n JUDGMENT_FILES.map((file) => fsp.rm(path.join(dir, file), { force: true })),\n );\n};\n\n/**\n * Remove a screenshot's judgment — after it was approved, or because it is no\n * longer changed. Only the judgment's own files go: a directory can also be\n * the parent of another screenshot's judgment (`button` and `button/primary`).\n */\nexport const clearJudgment = async (\n outputDir: string,\n name: string,\n): Promise<void> => {\n const dir = judgmentDir(outputDir, name);\n await clearJudgmentFiles(dir);\n await removeEmptyDirs(dir, judgmentsRoot(outputDir));\n};\n\n/** Remove `dir` and its parents up to (excluding) `root` while empty. */\nconst removeEmptyDirs = async (dir: string, root: string): Promise<void> => {\n let current = dir;\n while (current !== root && current.startsWith(root)) {\n try {\n await fsp.rmdir(current);\n } catch {\n return;\n }\n current = path.dirname(current);\n }\n};\n\nconst listRequestDirs = async (root: string): Promise<string[]> => {\n if (!(await exists(root))) return [];\n const files = await Array.fromAsync(\n fsp.glob(`**/${REQUEST_FILE}`, { cwd: root }),\n );\n return files.map((file) => path.resolve(root, path.dirname(file)));\n};\n\n/** Drop judgments for screenshots that no longer need one. */\nconst pruneJudgments = async (\n outputDir: string,\n keep: ReadonlySet<string>,\n): Promise<void> => {\n const root = judgmentsRoot(outputDir);\n for (const dir of await listRequestDirs(root)) {\n if (keep.has(dir)) continue;\n await clearJudgmentFiles(dir);\n await removeEmptyDirs(dir, root);\n }\n};\n\n/**\n * Analyse every non-passing screenshot, write a judgment request for every\n * changed one, apply any verdicts already written, and persist the full\n * report to `<outputDir>/.cappa-agent/report.json`.\n */\nexport const runAgentCheck = async (\n options: RunAgentCheckOptions,\n): Promise<AgentReport> => {\n const outputDir = path.resolve(options.outputDir);\n const createdAt = (options.now?.() ?? new Date()).toISOString();\n\n const screenshots = await collectScreenshots(outputDir);\n\n // Never commit agent scratch state: a judgment is only valid for the\n // images on this machine.\n await fsp.mkdir(agentDir(outputDir), { recursive: true });\n await fsp.writeFile(path.join(agentDir(outputDir), \".gitignore\"), \"*\\n\");\n\n const changed = screenshots.filter(\n (s): s is Extract<Screenshot, { category: \"changed\" }> =>\n s.category === \"changed\",\n );\n\n const changedEntries = await mapWithConcurrency(\n options.concurrency ?? 4,\n changed,\n (screenshot) =>\n analyseChanged(screenshot, { ...options, outputDir }, createdAt),\n );\n\n await pruneJudgments(\n outputDir,\n new Set(\n changedEntries.flatMap((entry) =>\n entry.judgment ? [entry.judgment.dir] : [],\n ),\n ),\n );\n\n const otherEntries = screenshots.flatMap((s): AgentReportEntry[] => {\n if (s.category === \"new\") {\n return [\n {\n name: s.name,\n category: \"new\",\n ...(s.taskId ? { taskId: s.taskId, plugin: s.plugin } : {}),\n paths: { actual: path.resolve(outputDir, s.actualPath) },\n pending: false,\n },\n ];\n }\n if (s.category === \"deleted\") {\n return [\n {\n name: s.name,\n category: \"deleted\",\n paths: { expected: path.resolve(outputDir, s.expectedPath) },\n pending: false,\n },\n ];\n }\n return [];\n });\n\n const entries = [...changedEntries, ...otherEntries];\n const count = (category: Screenshot[\"category\"]) =>\n screenshots.filter((s) => s.category === category).length;\n\n const report: AgentReport = {\n version: AGENT_REPORT_VERSION,\n createdAt,\n outputDir,\n reportPath: agentReportPath(outputDir),\n totals: {\n total: screenshots.length,\n passed: count(\"passed\"),\n changed: count(\"changed\"),\n new: count(\"new\"),\n deleted: count(\"deleted\"),\n pendingJudgments: entries.filter((entry) => entry.pending).length,\n },\n entries,\n };\n\n await writeJson(report.reportPath, report);\n\n return report;\n};\n\n/** Read the report the last {@link runAgentCheck} wrote, if any. */\nexport const readAgentReport = async (\n outputDir: string,\n): Promise<AgentReport | undefined> => {\n const raw = (await readJson(agentReportPath(outputDir))) as\n | AgentReport\n | undefined;\n return raw?.version === AGENT_REPORT_VERSION ? raw : undefined;\n};\n\nexport type SlimAgentReport = {\n reportPath: string;\n total: number;\n passed: number;\n changed: number;\n new: number;\n deleted: number;\n pendingJudgments: number;\n results: Array<{\n name: string;\n category: AgentReportEntry[\"category\"];\n change?: string;\n verdict?: Pick<AppliedVerdict, \"label\" | \"headline\" | \"action\">;\n pending?: true;\n /** Judgment directory, present while a verdict is pending. */\n judgment?: string;\n verdictError?: string;\n }>;\n};\n\n/**\n * The report as an agent should first see it: one line of state per\n * screenshot, with the detail left in `report.json` and the judgment\n * requests for when it is actually needed.\n */\nexport const toSlimAgentReport = (report: AgentReport): SlimAgentReport => ({\n reportPath: report.reportPath,\n ...report.totals,\n results: report.entries.map((entry) => ({\n name: entry.name,\n category: entry.category,\n ...(entry.change ? { change: entry.change } : {}),\n ...(entry.verdict\n ? {\n verdict: {\n label: entry.verdict.label,\n headline: entry.verdict.headline,\n action: entry.verdict.action,\n },\n }\n : {}),\n ...(entry.pending ? { pending: true as const } : {}),\n ...(entry.pending && entry.judgment\n ? { judgment: entry.judgment.dir }\n : {}),\n ...(entry.verdictError ? { verdictError: entry.verdictError } : {}),\n })),\n});\n\nexport type AgentVerdictInput = {\n label: VerdictLabel;\n headline: string;\n rationale?: string[];\n confidence?: number;\n};\n\n/**\n * Record a judge's verdict for a screenshot with a pending request — the\n * validated alternative to hand-writing `verdict.json`.\n */\nexport const writeAgentVerdict = async (\n outputDir: string,\n name: string,\n input: AgentVerdictInput,\n): Promise<string> => {\n const dir = judgmentDir(outputDir, name);\n if (!(await exists(path.join(dir, REQUEST_FILE)))) {\n throw new Error(\n `No judgment request for \"${name}\" — run \\`cappa agent check\\` first; only changed screenshots get one.`,\n );\n }\n\n const parsed = parseAgentVerdict(input);\n if (!parsed.ok) throw new Error(parsed.error);\n\n const verdictPath = path.join(dir, VERDICT_FILE);\n await writeJson(verdictPath, {\n name,\n verdict: {\n label: parsed.label,\n headline: parsed.headline,\n rationale: parsed.rationale,\n action: ACTION_BY_LABEL[parsed.label],\n },\n ...(parsed.confidence !== undefined\n ? { confidence: parsed.confidence }\n : {}),\n });\n return verdictPath;\n};\n","import path from \"node:path\";\nimport type { WebServerConfig } from \"../types\";\nimport type { ResolvedWebServerConfig } from \"./WebServerPool\";\n\nexport const DEFAULT_WEB_SERVER_TIMEOUT_MS = 60_000;\n\n// `localhost:6006` parses — as a URL with the scheme `localhost:`.\nconst isHttpUrl = (value: string): boolean =>\n URL.canParse(value) && [\"http:\", \"https:\"].includes(new URL(value).protocol);\n\n/**\n * Normalise `webServer` to a list with every default applied.\n *\n * A relative `cwd` resolves against `configDir` — the directory of\n * `cappa.config.ts` — not the process's working directory, so the same config\n * works whether cappa runs from the repository root or from inside the package\n * (`pnpm -F visual-tests cappa capture`).\n */\nexport function resolveWebServerConfig(\n webServer: WebServerConfig | WebServerConfig[] | undefined,\n configDir: string,\n env: NodeJS.ProcessEnv = process.env,\n): ResolvedWebServerConfig[] {\n if (webServer === undefined) {\n return [];\n }\n\n const entries = Array.isArray(webServer) ? webServer : [webServer];\n\n return entries.map((entry, index) => {\n const where = Array.isArray(webServer)\n ? `webServer[${index}]`\n : \"webServer\";\n\n if (typeof entry?.command !== \"string\" || entry.command.trim() === \"\") {\n throw new Error(`Invalid configuration: ${where}.command is required.`);\n }\n if (typeof entry.url !== \"string\" || !isHttpUrl(entry.url)) {\n throw new Error(\n `Invalid configuration: ${where}.url must be an absolute URL, e.g. \"http://localhost:6006\".`,\n );\n }\n if (\n entry.timeout !== undefined &&\n !(Number.isFinite(entry.timeout) && entry.timeout > 0)\n ) {\n throw new Error(\n `Invalid configuration: ${where}.timeout must be a positive number of milliseconds.`,\n );\n }\n\n return {\n command: entry.command,\n url: entry.url,\n reuseExistingServer: entry.reuseExistingServer ?? !env.CI,\n timeout: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