@cappa/core 0.14.0 → 0.16.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.
package/dist/index.d.mts CHANGED
@@ -1,8 +1,69 @@
1
1
  import "@blazediff/gmsd";
2
2
  import { Logger } from "@cappa/logger";
3
3
  import "@blazediff/core-native";
4
- import { ChangeRegion, InterpretResult, InterpretResult as InterpretResult$1 } from "@blazediff/interpret-native";
4
+ import { BoundingBox, ChangeRegion, InterpretResult, InterpretResult as InterpretResult$1 } from "@blazediff/interpret-native";
5
5
  import { Browser, BrowserContext, ConsoleMessage, Locator, Page } from "playwright-core";
6
+ //#region src/agent/verdict.d.ts
7
+ /**
8
+ * What a reviewer — heuristic or agent — believes a changed screenshot is.
9
+ *
10
+ * `ambiguous` is only ever produced by the heuristic: it is the signal that
11
+ * the change has to be looked at, and an agent's verdict must resolve it into
12
+ * one of the other three.
13
+ */
14
+ export declare const VERDICT_LABELS: readonly ["regression-likely", "intentional-likely", "noise-likely", "ambiguous"];
15
+ type VerdictLabel = (typeof VERDICT_LABELS)[number];
16
+ /** The labels a judge may hand back — everything but `ambiguous`. */
17
+ export declare const JUDGED_LABELS: readonly ["regression-likely", "intentional-likely", "noise-likely"];
18
+ type JudgedLabel = (typeof JUDGED_LABELS)[number];
19
+ /** What to do next with a screenshot carrying a label. */
20
+ type VerdictAction = "investigate" | "approve-if-intended" | "mask-or-approve";
21
+ export declare const ACTION_BY_LABEL: Record<VerdictLabel, VerdictAction>;
22
+ type Verdict = {
23
+ label: VerdictLabel;
24
+ /** One line, e.g. `2 regions: 1 addition, 1 color-change @ top-left (1.20%, medium)`. */
25
+ headline: string;
26
+ rationale: string[];
27
+ action: VerdictAction;
28
+ };
29
+ export declare const isVerdictLabel: (value: unknown) => value is VerdictLabel;
30
+ export declare const isJudgedLabel: (value: unknown) => value is JudgedLabel;
31
+ /**
32
+ * Change types are normalised to kebab-case before they are compared.
33
+ *
34
+ * `@blazediff/interpret-native` reports `color-change` today but earlier
35
+ * releases reported `ColorChange`; normalising keeps the heuristic working
36
+ * across a diff-engine upgrade instead of silently degrading every screenshot
37
+ * to `ambiguous`.
38
+ */
39
+ export declare const normalizeChangeType: (changeType: string) => string;
40
+ /** Below this share of the image, a low-severity change is not perceptible. */
41
+ export declare const SUB_PERCEPTUAL_PERCENT = 0.01;
42
+ type VerdictInput = {
43
+ /** Percentage of differing pixels (0-100), from the pixel diff. */
44
+ percentDifference?: number;
45
+ numDiffPixels?: number;
46
+ interpretation?: InterpretResult$1;
47
+ /** Expected and actual have different dimensions. */
48
+ differentSizes?: boolean;
49
+ };
50
+ /**
51
+ * A one-line description of a change, shaped so that the same kind of change
52
+ * on different screenshots produces the same headline — which is what lets an
53
+ * agent spot one shared cause (a footer timestamp, a theme toggle) across
54
+ * dozens of screenshots without opening any of them.
55
+ */
56
+ export declare const buildHeadline: (input: VerdictInput) => string;
57
+ /**
58
+ * Classify a changed screenshot from its diff interpretation alone.
59
+ *
60
+ * Deliberately conservative: only the cases the signals settle are labelled,
61
+ * and everything else is `ambiguous` so that it reaches a judge who can look
62
+ * at the pixels. A wrong `noise-likely` hides a regression; a wrong
63
+ * `ambiguous` costs one look.
64
+ */
65
+ export declare const deriveVerdict: (input: VerdictInput) => Verdict;
66
+ //#endregion
6
67
  //#region src/consoleEvents.d.ts
7
68
  /**
8
69
  * Minimum severity of browser console output to forward, ordered from most
@@ -169,6 +230,14 @@ export declare class ScreenshotFileSystem {
169
230
  * Write a file to the diff directory
170
231
  */
171
232
  writeDiffFile(filename: string, data: Buffer): Promise<void>;
233
+ /**
234
+ * Remove a screenshot's diff image and metadata sidecar, if any.
235
+ *
236
+ * A run that does not clear `diff/` — a filtered or single-screenshot
237
+ * re-capture — would otherwise leave the previous run's diff behind for a
238
+ * screenshot that now passes, and a screenshot with a diff is `changed`.
239
+ */
240
+ removeDiffFiles(filename: string): Promise<void>;
172
241
  /**
173
242
  * Get the path to a diff metadata sidecar file (`<name>.json`)
174
243
  */
@@ -810,6 +879,51 @@ type DiffOptionsGMSD = {
810
879
  type: "gmsd";
811
880
  } & DiffConfigGMSD;
812
881
  type DiffOptions = DiffOptionsPixel | DiffOptionsGMSD;
882
+ /**
883
+ * A server cappa starts before capturing — the app under test, such as a
884
+ * Storybook or a preview build — and stops again when it is done.
885
+ *
886
+ * Not to be confused with cappa's own review server (`cappa review`,
887
+ * `cappa serve`, `review.port`): this is what the plugins point at.
888
+ */
889
+ type WebServerConfig = {
890
+ /**
891
+ * Shell command that starts the server, e.g. `pnpm storybook --ci`.
892
+ *
893
+ * Run through a shell, so `pnpm build && pnpm preview` works — including on
894
+ * Windows. The whole process tree is stopped when cappa is done.
895
+ */
896
+ command: string;
897
+ /**
898
+ * URL that answers with a 2xx or 3xx status once the server is ready.
899
+ * Usually the same URL a plugin is configured with.
900
+ */
901
+ url: string;
902
+ /**
903
+ * Use a server that is already answering at `url` instead of starting one.
904
+ *
905
+ * A reused server skips `command` entirely — build step included — and is
906
+ * never stopped, because cappa did not start it. When `false`, an answering
907
+ * `url` is an error.
908
+ *
909
+ * @default !process.env.CI
910
+ */
911
+ reuseExistingServer?: boolean;
912
+ /**
913
+ * How long `url` may take to become ready, in milliseconds, measured from
914
+ * the moment `command` is spawned — so it covers any build step in it.
915
+ * @default 60000
916
+ */
917
+ timeout?: number;
918
+ /**
919
+ * Directory `command` runs in. A relative path resolves against the
920
+ * directory of `cappa.config.ts`, not the current working directory.
921
+ * @default the directory of `cappa.config.ts`
922
+ */
923
+ cwd?: string;
924
+ /** Environment variables for `command`, merged over the inherited ones. */
925
+ env?: Record<string, string>;
926
+ };
813
927
  /**
814
928
  * Config used in `cappa.config.ts`
815
929
  *
@@ -860,6 +974,18 @@ type UserConfig = {
860
974
  * Each plugin may have additional configurable options (defined within the plugin itself).
861
975
  */
862
976
  plugins?: Array<Plugin | PluginDef>;
977
+ /**
978
+ * Server(s) cappa starts before capturing and stops when it is done — the
979
+ * app the plugins point at. Several entries start in parallel, and all must
980
+ * be ready before anything is captured.
981
+ *
982
+ * @example
983
+ * webServer: {
984
+ * command: "pnpm storybook --ci",
985
+ * url: "http://localhost:6006",
986
+ * }
987
+ */
988
+ webServer?: WebServerConfig | WebServerConfig[];
863
989
  /**
864
990
  * Callback executed when screenshots fail comparison.
865
991
  * Receives the failing screenshots so they can be uploaded or processed.
@@ -959,6 +1085,24 @@ interface DiffMetadata {
959
1085
  /** Structured interpretation, present only when `diff.interpret` is enabled. */
960
1086
  interpretation?: InterpretResult$1;
961
1087
  }
1088
+ /**
1089
+ * The verdict `cappa agent check` reached for a changed screenshot, as the
1090
+ * review UI shows it.
1091
+ */
1092
+ interface AgentReview {
1093
+ label: VerdictLabel;
1094
+ headline: string;
1095
+ rationale: string[];
1096
+ action: VerdictAction;
1097
+ /** `heuristic` from the diff signals; `agent` from a judge's verdict. */
1098
+ source: "heuristic" | "agent";
1099
+ /** 0-1, when the judge gave one. */
1100
+ confidence?: number;
1101
+ /** A judgment was requested and no verdict had been written yet. */
1102
+ pending: boolean;
1103
+ /** When the check that produced this ran (ISO 8601). */
1104
+ reviewedAt: string;
1105
+ }
962
1106
  type ChangedScreenshot = {
963
1107
  category: "changed";
964
1108
  diffPath: string;
@@ -969,6 +1113,12 @@ type ChangedScreenshot = {
969
1113
  * `diff/<name>.json` sidecar. Absent if the sidecar was not written.
970
1114
  */
971
1115
  diffMeta?: DiffMetadata;
1116
+ /**
1117
+ * The last `cappa agent check` verdict. Absent when no check has run, or
1118
+ * when either image changed since — a verdict about other pixels is not one
1119
+ * worth showing.
1120
+ */
1121
+ review?: AgentReview;
972
1122
  };
973
1123
  type PassedScreenshot = {
974
1124
  category: "passed";
@@ -1041,6 +1191,132 @@ export declare function imagesMatchGMSD(image1: string | Buffer, image2: string
1041
1191
  */
1042
1192
  export declare function defineConfig(options: PossiblePromise<UserConfig> | ((env: ConfigEnv) => PossiblePromise<UserConfig>)): typeof options;
1043
1193
  //#endregion
1194
+ //#region src/webServer/process.d.ts
1195
+ /** Grace period between SIGTERM and SIGKILL. */
1196
+ export declare const DEFAULT_KILL_GRACE_MS = 5000;
1197
+ /**
1198
+ * The last part of a process's output, kept in memory.
1199
+ *
1200
+ * Bounded by bytes rather than lines: a dev server that prints one enormous
1201
+ * line is no reason to hold on to all of it, and the tail exists to explain a
1202
+ * failure, not to be a log.
1203
+ */
1204
+ export declare class OutputTail {
1205
+ private readonly maxBytes;
1206
+ private chunks;
1207
+ private size;
1208
+ constructor(maxBytes?: number);
1209
+ push(chunk: string): void;
1210
+ /** The last `maxLines` non-empty lines. */
1211
+ lines(maxLines?: number): string[];
1212
+ }
1213
+ type ProcessExit = {
1214
+ code: number | null;
1215
+ signal: NodeJS.Signals | null;
1216
+ };
1217
+ type ServerProcess = {
1218
+ readonly pid: number | undefined;
1219
+ /** Settles once the direct child has exited. Never rejects. */
1220
+ readonly exited: Promise<ProcessExit>;
1221
+ /** The exit, once there is one. */
1222
+ readonly exit: ProcessExit | undefined;
1223
+ readonly output: OutputTail;
1224
+ /** Stop the whole process tree. Safe to call repeatedly. */
1225
+ kill(graceMs?: number): Promise<void>;
1226
+ };
1227
+ type SpawnServerOptions = {
1228
+ cwd: string;
1229
+ env?: Record<string, string>;
1230
+ /** Called with every chunk of output as it arrives. */
1231
+ onOutput?: (chunk: string) => void;
1232
+ };
1233
+ /**
1234
+ * Start `command` through a shell, as the leader of its own process group.
1235
+ *
1236
+ * A group, because the command is rarely the server itself: `pnpm storybook`
1237
+ * is pnpm, running a shell, running storybook, running workers. Killing only
1238
+ * the direct child would leave the rest holding the port.
1239
+ *
1240
+ * Output is buffered, never written anywhere unless `onOutput` asks for it —
1241
+ * `cappa capture --json` must stay a single clean document on stdout.
1242
+ */
1243
+ export declare function spawnServerProcess(command: string, options: SpawnServerOptions): ServerProcess;
1244
+ //#endregion
1245
+ //#region src/webServer/WebServerPool.d.ts
1246
+ /** A `webServer` entry with every default applied. */
1247
+ type ResolvedWebServerConfig = Required<WebServerConfig>;
1248
+ type WebServerLogLevel = "debug" | "info" | "warn" | "error" | "success";
1249
+ type WebServerLog = (level: WebServerLogLevel, message: string) => void;
1250
+ type WebServerPoolOptions = {
1251
+ servers: ResolvedWebServerConfig[];
1252
+ /** Where lifecycle messages go when `ensure` is not handed a log. */
1253
+ log?: WebServerLog;
1254
+ /** Live output, for `--log-level 4`. Output is buffered either way. */
1255
+ onOutput?: (server: ResolvedWebServerConfig, chunk: string) => void;
1256
+ /** Overrides process spawning. Tests use this. */
1257
+ spawn?: (command: string, options: SpawnServerOptions) => ServerProcess;
1258
+ /** Overrides the readiness probe. Tests use this. */
1259
+ probe?: (url: string, timeoutMs: number) => Promise<boolean>;
1260
+ /** Grace period between SIGTERM and SIGKILL. @default 5000 */
1261
+ killGraceMs?: number;
1262
+ };
1263
+ /** A web server could not be started, or would not become ready. */
1264
+ export declare class WebServerError extends Error {
1265
+ constructor(message: string);
1266
+ }
1267
+ /**
1268
+ * The servers a config's `webServer` describes, started on demand.
1269
+ *
1270
+ * Lazy and restartable rather than started once: the owning engine calls
1271
+ * `ensure` before every run and `stop` when the browser goes idle, so a review
1272
+ * session that sits unused gives the port back, and the next capture starts —
1273
+ * and rebuilds — the app again, picking up whatever changed in between.
1274
+ *
1275
+ * Every `ensure` says which way it went, because "reusing a server" and
1276
+ * "started one" look identical in screenshots, and a stale build, another
1277
+ * branch or another project on the same port is otherwise very hard to spot.
1278
+ */
1279
+ export declare class WebServerPool {
1280
+ private readonly entries;
1281
+ private readonly options;
1282
+ private readonly probe;
1283
+ /** Bumped by `stop`, so a start in flight knows it was cancelled. */
1284
+ private generation;
1285
+ constructor(options: WebServerPoolOptions);
1286
+ /** Whether the config has any `webServer` entry at all. */
1287
+ get configured(): boolean;
1288
+ /** Number of processes cappa started that are still running. */
1289
+ get running(): number;
1290
+ /**
1291
+ * Make every server ready, in parallel, starting the ones that are not.
1292
+ *
1293
+ * All of them, even for a run that only captures one plugin's tasks: nothing
1294
+ * maps a plugin to a server, and guessing would start the wrong one.
1295
+ */
1296
+ ensure(log?: WebServerLog): Promise<void>;
1297
+ /**
1298
+ * Stop every server cappa started. A reused server is left alone — cappa did
1299
+ * not start it, so it is not cappa's to stop.
1300
+ */
1301
+ stop(): Promise<void>;
1302
+ /**
1303
+ * What to tell the user about a connection refused at `origin`.
1304
+ *
1305
+ * Always an actionable sentence: the bare "ECONNREFUSED" it replaces is the
1306
+ * single most common capture failure, and says nothing about what to do.
1307
+ */
1308
+ explainUnreachable(origin?: string): string;
1309
+ private readonly defaultLog;
1310
+ private ensureEntry;
1311
+ private startEntry;
1312
+ /**
1313
+ * Record a server that exits on its own, so the failures it causes can say
1314
+ * why and the next run starts it again. Deliberately no restart loop: a
1315
+ * server that keeps crashing should fail loudly, not flap.
1316
+ */
1317
+ private watchForCrash;
1318
+ }
1319
+ //#endregion
1044
1320
  //#region src/runner/CaptureRunner.d.ts
1045
1321
  type CaptureRunnerOptions = {
1046
1322
  /**
@@ -1062,6 +1338,17 @@ type CaptureRunnerOptions = {
1062
1338
  id?: string;
1063
1339
  /** Injectable clock, for deterministic tests. */
1064
1340
  now?: () => number;
1341
+ /**
1342
+ * Runs after `run:start` and before anything is cleared or discovered —
1343
+ * the engine starts its web servers here. Its log lines become run events,
1344
+ * and a rejection fails the run with `actual/` still intact.
1345
+ */
1346
+ prepare?: (log: (level: RunLogLevel, message: string) => void) => Promise<void>;
1347
+ /**
1348
+ * The advice appended to a refused connection, given the origin that
1349
+ * refused when the error names one. Defaults to suggesting a `webServer`.
1350
+ */
1351
+ explainUnreachable?: (origin: string | undefined) => string;
1065
1352
  };
1066
1353
  /**
1067
1354
  * Orchestrates a single capture run: discover → filter → execute, emitting
@@ -1080,6 +1367,8 @@ export declare class CaptureRunner {
1080
1367
  private readonly outputDir;
1081
1368
  private readonly fileSystem;
1082
1369
  private readonly now;
1370
+ private readonly prepare;
1371
+ private readonly explainUnreachable;
1083
1372
  private readonly listeners;
1084
1373
  private readonly controller;
1085
1374
  private seq;
@@ -1152,6 +1441,21 @@ export declare class CaptureRunner {
1152
1441
  private persistCaptureOrigins;
1153
1442
  private discover;
1154
1443
  private execute;
1444
+ /**
1445
+ * The message for a refused connection: where, and what to do about it.
1446
+ *
1447
+ * Identical for every task that hit the same server — no task id, no path —
1448
+ * so a report can collapse 300 of them into one line.
1449
+ */
1450
+ private unreachableMessage;
1451
+ private toUnreachableError;
1452
+ /**
1453
+ * Replace a plugin's refused-connection error with the explained one.
1454
+ *
1455
+ * Reads the result rather than asking the plugin, so third-party plugins get
1456
+ * the same message without an API change.
1457
+ */
1458
+ private explainTaskError;
1155
1459
  private collectDeleted;
1156
1460
  }
1157
1461
  //#endregion
@@ -1572,6 +1876,13 @@ type LocalEngineOptions = {
1572
1876
  createWatcher?: CreateFileWatcher;
1573
1877
  /** Watch events buffered for replay to a (re)connecting subscriber. @default 200 */
1574
1878
  maxWatchEvents?: number;
1879
+ /**
1880
+ * The app under test, started before the first run and stopped with the
1881
+ * browser — on `close()` and when it goes idle.
1882
+ */
1883
+ webServer?: ResolvedWebServerConfig[];
1884
+ /** Overrides the web server pool's process and probe hooks. Tests use this. */
1885
+ webServerPool?: Pick<WebServerPoolOptions, "spawn" | "probe" | "killGraceMs">;
1575
1886
  };
1576
1887
  /**
1577
1888
  * `CaptureEngine` backed by an in-process Playwright browser.
@@ -1590,6 +1901,7 @@ export declare class LocalEngine implements CaptureEngine {
1590
1901
  private readonly fileSystem;
1591
1902
  private readonly browser;
1592
1903
  private readonly runs;
1904
+ private readonly webServers;
1593
1905
  /**
1594
1906
  * Set synchronously the moment a run is claimed, before any `await`, so two
1595
1907
  * concurrent `startRun` calls cannot both pass the check and then fight over
@@ -1677,6 +1989,12 @@ type WarmBrowserOptions = {
1677
1989
  * @default 300_000 (5 minutes)
1678
1990
  */
1679
1991
  idleTimeoutMs?: number;
1992
+ /**
1993
+ * Called whenever the browser shuts down — idle eviction and `close()`
1994
+ * alike. Whatever only makes sense while a browser is warm (the app under
1995
+ * test, started for it) goes down with it.
1996
+ */
1997
+ onShutdown?: () => Promise<void>;
1680
1998
  };
1681
1999
  /**
1682
2000
  * Keeps a Playwright browser alive between capture runs.
@@ -1693,6 +2011,7 @@ type WarmBrowserOptions = {
1693
2011
  export declare class WarmBrowser {
1694
2012
  private readonly createTool;
1695
2013
  private readonly idleTimeoutMs;
2014
+ private readonly onShutdown;
1696
2015
  private tool;
1697
2016
  private idleTimer;
1698
2017
  private inUse;
@@ -1787,7 +2106,9 @@ export declare function getDeletedScreenshots(outputDir: string): Promise<string
1787
2106
  *
1788
2107
  * The capture manifest is folded in here so every consumer — the CLI, the
1789
2108
  * server, the review UI — sees the same `taskId`, and so a screenshot captured
1790
- * before manifests existed simply has none rather than a wrong one.
2109
+ * before manifests existed simply has none rather than a wrong one. The last
2110
+ * `cappa agent check` verdict is folded in the same way, as `review`, while it
2111
+ * still describes the images on disk.
1791
2112
  */
1792
2113
  export declare const collectScreenshots: (outputDir: string) => Promise<Screenshot[]>;
1793
2114
  //#endregion
@@ -1908,5 +2229,332 @@ export declare class FsScreenshotStore implements ScreenshotStore {
1908
2229
  writeMeta(key: string, meta: DiffMetadata): Promise<void>;
1909
2230
  }
1910
2231
  //#endregion
1911
- export { type ApproveResult, type CaptureEngine, type CaptureManifest, type CaptureRunnerOptions, type ChangeRegion, type ChangedScreenshot, type ConfigEnv, type ConsoleLogLevel, type CreateFileWatcher, type DeletedScreenshot, type DiffConfig, type DiffConfigGMSD, type DiffMetadata, type DiffOptions, type DiffOptionsGMSD, type DiffOptionsPixel, type EmittableWatchEvent, type FailedScreenshot, type FileWatcher, type InterpretResult, type ListTargetsOptions, type LocalEngineOptions, type LogConsoleEvents, type NewScreenshot, type PassedScreenshot, type Plugin, type PluginCaptureResult, type PluginDef, type PluginFunction, type PluginInfo, type PluginTask, type PluginWatch, type PluginWatchResolve, type RunDetail, type RunEvent, type RunEventListener, type RunEventType, type RunLogLevel, type RunState, type RunStoreOptions, type RunSummary, type RunTrigger, type RunnablePlugin, type Screenshot, type ScreenshotBucket, type ScreenshotCaptureDetails, type ScreenshotCaptureExtras, type ScreenshotCaptureResult, type ScreenshotCaptureSink, type ScreenshotOptions, type ScreenshotOrigin, type ScreenshotQuery, type ScreenshotSettings, type ScreenshotStore, ScreenshotTool, type ScreenshotVariant, type ScreenshotVariantCaptureDetails, type ScreenshotVariantWithUrl, type SerializedError, type StartRunRequest, type StartWatchRequest, type SubscribeOptions, type Target, type TaskFailure, type TaskRecord, type TaskStatus, type UserConfig, type Viewport, type WarmBrowserOptions, type WatchChange, type WatchEvent, type WatchEventType, type WatchScope, type WatchSessionOptions, type WatchStatus };
2232
+ //#region src/agent/paths.d.ts
2233
+ /**
2234
+ * Where agent review keeps its state, inside `outputDir`.
2235
+ *
2236
+ * Its own module so screenshot collection can read the report without
2237
+ * importing the review pipeline, which itself collects screenshots.
2238
+ */
2239
+ export declare const AGENT_DIRNAME = ".cappa-agent";
2240
+ /** Bumped only if `request.json` or `report.json` change incompatibly. */
2241
+ export declare const AGENT_REPORT_VERSION = 1;
2242
+ export declare const agentDir: (outputDir: string) => string;
2243
+ export declare const agentReportPath: (outputDir: string) => string;
2244
+ //#endregion
2245
+ //#region src/agent/review.d.ts
2246
+ /**
2247
+ * Which changed screenshots get a judgment request.
2248
+ *
2249
+ * - `ambiguous`: only those the heuristic could not label (default)
2250
+ * - `all`: every changed screenshot, for a full second opinion
2251
+ * - `none`: heuristic labels only, no new requests
2252
+ *
2253
+ * Judgments that already exist are kept and applied in every mode.
2254
+ */
2255
+ type JudgeMode = "ambiguous" | "all" | "none";
2256
+ export declare const JUDGE_MODES: readonly JudgeMode[];
2257
+ type AgentRegion = {
2258
+ /** 1-based, matching the numbers in `locator.png` and rows in `regions.png`. */
2259
+ index: number;
2260
+ bbox: {
2261
+ x: number;
2262
+ y: number;
2263
+ width: number;
2264
+ height: number;
2265
+ };
2266
+ pixelCount: number;
2267
+ percentage: number;
2268
+ position: string;
2269
+ shape: string;
2270
+ changeType: string;
2271
+ confidence: number;
2272
+ };
2273
+ type AppliedVerdict = Verdict & {
2274
+ /** Whether the label came from the heuristic or from a judge. */
2275
+ source: "heuristic" | "agent";
2276
+ confidence?: number;
2277
+ };
2278
+ type JudgmentPaths = {
2279
+ dir: string;
2280
+ request: string;
2281
+ verdict: string;
2282
+ locator?: string;
2283
+ regions?: string;
2284
+ overview?: string;
2285
+ };
2286
+ type AgentReportEntry = {
2287
+ name: string;
2288
+ category: "changed" | "new" | "deleted";
2289
+ taskId?: string;
2290
+ plugin?: string;
2291
+ /** Absolute paths to the screenshot files. */
2292
+ paths: {
2293
+ expected?: string;
2294
+ actual?: string;
2295
+ diff?: string;
2296
+ };
2297
+ percentDifference?: number;
2298
+ numDiffPixels?: number;
2299
+ dimensions?: {
2300
+ expected: {
2301
+ width: number;
2302
+ height: number;
2303
+ };
2304
+ actual: {
2305
+ width: number;
2306
+ height: number;
2307
+ };
2308
+ };
2309
+ severity?: string;
2310
+ summary?: string;
2311
+ /** Largest first. */
2312
+ regions?: AgentRegion[];
2313
+ heuristic?: Verdict;
2314
+ /** The judge's verdict when there is a current one, else the heuristic's. */
2315
+ verdict?: AppliedVerdict;
2316
+ /** A judgment was requested and no valid verdict has been written yet. */
2317
+ pending: boolean;
2318
+ judgment?: JudgmentPaths;
2319
+ /** Why a `verdict.json` that exists was ignored. */
2320
+ verdictError?: string;
2321
+ };
2322
+ type AgentReport = {
2323
+ version: number;
2324
+ createdAt: string;
2325
+ outputDir: string;
2326
+ reportPath: string;
2327
+ judge: JudgeMode;
2328
+ totals: {
2329
+ total: number;
2330
+ passed: number;
2331
+ changed: number;
2332
+ new: number;
2333
+ deleted: number;
2334
+ pendingJudgments: number;
2335
+ };
2336
+ /** Every non-passing screenshot, changed ones first. */
2337
+ entries: AgentReportEntry[];
2338
+ };
2339
+ /**
2340
+ * The directory holding a screenshot's judgment.
2341
+ *
2342
+ * Screenshot names are relative paths (`example/button/primary`), so they map
2343
+ * onto nested directories directly; anything that would resolve outside the
2344
+ * judgments root is refused rather than written.
2345
+ */
2346
+ export declare const judgmentDir: (outputDir: string, name: string) => string;
2347
+ /** Ties a judgment to the exact pair of images it was made about. */
2348
+ export declare const fingerprintImages: (expectedPath: string, actualPath: string) => Promise<string>;
2349
+ type ParsedAgentVerdict = {
2350
+ ok: true;
2351
+ label: JudgedLabel;
2352
+ headline: string;
2353
+ rationale: string[];
2354
+ confidence?: number;
2355
+ } | {
2356
+ ok: false;
2357
+ error: string;
2358
+ };
2359
+ /**
2360
+ * Read a judge's verdict, accepting both the nested shape blazediff uses
2361
+ * (`{ verdict: { label, headline, rationale }, confidence }`) and a flat one
2362
+ * (`{ label, headline, rationale, confidence }`) — a judge that writes either
2363
+ * should not have its work thrown away over nesting.
2364
+ */
2365
+ export declare const parseAgentVerdict: (raw: unknown) => ParsedAgentVerdict;
2366
+ type RunAgentCheckOptions = {
2367
+ outputDir: string;
2368
+ /** The project's diff config — its threshold is reused for interpretation. */
2369
+ diff?: DiffOptions;
2370
+ judge?: JudgeMode;
2371
+ /** Regions rendered into `regions.png` per screenshot. Default 8. */
2372
+ maxTileRegions?: number;
2373
+ /** Screenshots analysed in parallel. Default 4. */
2374
+ concurrency?: number;
2375
+ now?: () => Date;
2376
+ };
2377
+ /**
2378
+ * Remove a screenshot's judgment — after it was approved, or because it is no
2379
+ * longer changed. Only the judgment's own files go: a directory can also be
2380
+ * the parent of another screenshot's judgment (`button` and `button/primary`).
2381
+ */
2382
+ export declare const clearJudgment: (outputDir: string, name: string) => Promise<void>;
2383
+ /**
2384
+ * Analyse every non-passing screenshot, write judgment requests for the ones
2385
+ * that need a judge, apply any verdicts already written, and persist the
2386
+ * full report to `<outputDir>/.cappa-agent/report.json`.
2387
+ */
2388
+ export declare const runAgentCheck: (options: RunAgentCheckOptions) => Promise<AgentReport>;
2389
+ /** Read the report the last {@link runAgentCheck} wrote, if any. */
2390
+ export declare const readAgentReport: (outputDir: string) => Promise<AgentReport | undefined>;
2391
+ type SlimAgentReport = {
2392
+ reportPath: string;
2393
+ total: number;
2394
+ passed: number;
2395
+ changed: number;
2396
+ new: number;
2397
+ deleted: number;
2398
+ pendingJudgments: number;
2399
+ results: Array<{
2400
+ name: string;
2401
+ category: AgentReportEntry["category"];
2402
+ verdict?: Pick<AppliedVerdict, "label" | "headline" | "action" | "source">;
2403
+ pending?: true;
2404
+ /** Judgment directory, present while a verdict is pending. */
2405
+ judgment?: string;
2406
+ verdictError?: string;
2407
+ }>;
2408
+ };
2409
+ /**
2410
+ * The report as an agent should first see it: one line of state per
2411
+ * screenshot, with the detail left in `report.json` and the judgment
2412
+ * requests for when it is actually needed.
2413
+ */
2414
+ export declare const toSlimAgentReport: (report: AgentReport) => SlimAgentReport;
2415
+ type AgentVerdictInput = {
2416
+ label: JudgedLabel;
2417
+ headline: string;
2418
+ rationale?: string[];
2419
+ confidence?: number;
2420
+ };
2421
+ /**
2422
+ * Record a judge's verdict for a screenshot with a pending request — the
2423
+ * validated alternative to hand-writing `verdict.json`.
2424
+ */
2425
+ export declare const writeAgentVerdict: (outputDir: string, name: string, input: AgentVerdictInput) => Promise<string>;
2426
+ //#endregion
2427
+ //#region src/agent/tiles.d.ts
2428
+ /**
2429
+ * Evidence images for a judge, sized for a model's context window rather than
2430
+ * for a human's screen.
2431
+ *
2432
+ * A full-page screenshot is easily 1920x8000 — expensive to read and mostly
2433
+ * unchanged. A judge needs two things instead: where the changes are
2434
+ * (`locator.png`, a small outlined thumbnail) and what each one looks like
2435
+ * before and after (`regions.png`, tight crops side by side). Together they
2436
+ * are typically one to two orders of magnitude smaller than the full images.
2437
+ */
2438
+ type TileOptions = {
2439
+ expectedPath: string;
2440
+ actualPath: string;
2441
+ /** Diff image to outline the regions on; falls back to the actual image. */
2442
+ diffPath?: string;
2443
+ /** Regions, largest first — row order in `regions.png` follows this. */
2444
+ regions: readonly BoundingBox[];
2445
+ outDir: string;
2446
+ /** Regions rendered into `regions.png`. Default 8. */
2447
+ maxRegions?: number;
2448
+ /**
2449
+ * Minimum context kept around each region, in pixels; grows with the
2450
+ * region's size. Default 24.
2451
+ */
2452
+ padding?: number;
2453
+ /** Largest width a single crop is rendered at. Default 640. */
2454
+ maxCropWidth?: number;
2455
+ };
2456
+ type TileResult = {
2457
+ /** Absolute path, or undefined when nothing could be drawn. */
2458
+ locator?: string;
2459
+ /** Absolute path, or undefined when there were no regions. */
2460
+ regions?: string;
2461
+ /** How many regions `regions.png` holds (≤ `maxRegions`). */
2462
+ renderedRegions: number;
2463
+ };
2464
+ export declare const padAndClamp: (bbox: BoundingBox, padding: number | {
2465
+ x: number;
2466
+ y: number;
2467
+ }, width: number, height: number) => BoundingBox;
2468
+ /**
2469
+ * Context kept around a region: proportional to its size, within bounds.
2470
+ *
2471
+ * A fixed margin is too tight for small regions — a changed letter cropped
2472
+ * with 24px around it says nothing about whether a button label got
2473
+ * truncated — and wasteful for large ones.
2474
+ */
2475
+ export declare const contextPadding: (bbox: BoundingBox, minimum: number) => {
2476
+ x: number;
2477
+ y: number;
2478
+ };
2479
+ /**
2480
+ * Write `locator.png` and `regions.png` into `outDir`.
2481
+ *
2482
+ * Expected and actual must have the same dimensions — region boxes are only
2483
+ * meaningful when both images share a coordinate space. Use
2484
+ * {@link renderOverview} when they do not.
2485
+ */
2486
+ export declare const renderJudgmentTiles: (options: TileOptions) => Promise<TileResult>;
2487
+ /**
2488
+ * Write `overview.png`: expected and actual, scaled down side by side.
2489
+ *
2490
+ * For screenshots whose dimensions changed, where no region can be located,
2491
+ * this is what the judge looks at instead of two full-size images.
2492
+ */
2493
+ export declare const renderOverview: (options: {
2494
+ expectedPath: string;
2495
+ actualPath: string;
2496
+ outDir: string;
2497
+ }) => Promise<string>;
2498
+ //#endregion
2499
+ //#region src/webServer/readiness.d.ts
2500
+ /**
2501
+ * Whether `url` answers with a 2xx or 3xx status.
2502
+ *
2503
+ * Redirects are not followed: a dev server that redirects `/` to `/login` is
2504
+ * up, and following it would make readiness depend on a page cappa never asked
2505
+ * about.
2506
+ */
2507
+ export declare function isUrlReady(url: string, timeoutMs?: number): Promise<boolean>;
2508
+ type WaitForUrlOptions = {
2509
+ timeoutMs: number;
2510
+ /** Stop waiting as soon as this settles — the server process exited. */
2511
+ abort?: Promise<unknown>;
2512
+ /** Injectable for tests. */
2513
+ probe?: (url: string, timeoutMs: number) => Promise<boolean>;
2514
+ };
2515
+ type WaitForUrlResult = "ready" | "timeout" | "aborted";
2516
+ /** Poll `url` until it is ready, the deadline passes, or `abort` settles. */
2517
+ export declare function waitForUrl(url: string, options: WaitForUrlOptions): Promise<WaitForUrlResult>;
2518
+ //#endregion
2519
+ //#region src/webServer/resolve.d.ts
2520
+ export declare const DEFAULT_WEB_SERVER_TIMEOUT_MS = 60000;
2521
+ /**
2522
+ * Normalise `webServer` to a list with every default applied.
2523
+ *
2524
+ * A relative `cwd` resolves against `configDir` — the directory of
2525
+ * `cappa.config.ts` — not the process's working directory, so the same config
2526
+ * works whether cappa runs from the repository root or from inside the package
2527
+ * (`pnpm -F visual-tests cappa capture`).
2528
+ */
2529
+ export declare function resolveWebServerConfig(webServer: WebServerConfig | WebServerConfig[] | undefined, configDir: string, env?: NodeJS.ProcessEnv): ResolvedWebServerConfig[];
2530
+ //#endregion
2531
+ //#region src/webServer/unreachable.d.ts
2532
+ /** The advice for a refused connection when the config has no `webServer`. */
2533
+ export declare const NO_WEB_SERVER_HINT = "Start it before capturing, or add a `webServer` entry to cappa.config.ts so cappa starts it for you.";
2534
+ type RefusedConnection = {
2535
+ /** Origin of the URL that refused, when the error names one. */
2536
+ origin?: string;
2537
+ };
2538
+ /**
2539
+ * Whether `error` — an `Error`, a plain object, or just a message string, as
2540
+ * plugins report task failures — is a refused connection.
2541
+ *
2542
+ * Walks `cause` and `AggregateError.errors`: Node's `fetch` says only
2543
+ * "fetch failed" and puts `ECONNREFUSED` on its cause, and a plugin that wraps
2544
+ * the error in a friendlier one keeps it there too.
2545
+ *
2546
+ * Works on any plugin's errors, third-party included, because it reads the
2547
+ * error rather than asking the plugin.
2548
+ */
2549
+ export declare function findRefusedConnection(error: unknown): RefusedConnection | undefined;
2550
+ /**
2551
+ * Whether two origins name the same server.
2552
+ *
2553
+ * Loopback spellings are interchangeable: a plugin configured with
2554
+ * `localhost:6006` and a socket error reporting `127.0.0.1:6006` are the same
2555
+ * Storybook.
2556
+ */
2557
+ export declare function sameServer(a: string, b: string): boolean;
2558
+ //#endregion
2559
+ export { type AgentRegion, type AgentReport, type AgentReportEntry, type AgentReview, type AgentVerdictInput, type AppliedVerdict, type ApproveResult, type CaptureEngine, type CaptureManifest, type CaptureRunnerOptions, type ChangeRegion, type ChangedScreenshot, type ConfigEnv, type ConsoleLogLevel, type CreateFileWatcher, type DeletedScreenshot, type DiffConfig, type DiffConfigGMSD, type DiffMetadata, type DiffOptions, type DiffOptionsGMSD, type DiffOptionsPixel, type EmittableWatchEvent, type FailedScreenshot, type FileWatcher, type InterpretResult, type JudgeMode, type JudgedLabel, type JudgmentPaths, type ListTargetsOptions, type LocalEngineOptions, type LogConsoleEvents, type NewScreenshot, type ParsedAgentVerdict, type PassedScreenshot, type Plugin, type PluginCaptureResult, type PluginDef, type PluginFunction, type PluginInfo, type PluginTask, type PluginWatch, type PluginWatchResolve, type ProcessExit, type RefusedConnection, type ResolvedWebServerConfig, type RunAgentCheckOptions, type RunDetail, type RunEvent, type RunEventListener, type RunEventType, type RunLogLevel, type RunState, type RunStoreOptions, type RunSummary, type RunTrigger, type RunnablePlugin, type Screenshot, type ScreenshotBucket, type ScreenshotCaptureDetails, type ScreenshotCaptureExtras, type ScreenshotCaptureResult, type ScreenshotCaptureSink, type ScreenshotOptions, type ScreenshotOrigin, type ScreenshotQuery, type ScreenshotSettings, type ScreenshotStore, ScreenshotTool, type ScreenshotVariant, type ScreenshotVariantCaptureDetails, type ScreenshotVariantWithUrl, type SerializedError, type ServerProcess, type SlimAgentReport, type SpawnServerOptions, type StartRunRequest, type StartWatchRequest, type SubscribeOptions, type Target, type TaskFailure, type TaskRecord, type TaskStatus, type TileOptions, type TileResult, type UserConfig, type Verdict, type VerdictAction, type VerdictInput, type VerdictLabel, type Viewport, type WaitForUrlOptions, type WaitForUrlResult, type WarmBrowserOptions, type WatchChange, type WatchEvent, type WatchEventType, type WatchScope, type WatchSessionOptions, type WatchStatus, type WebServerConfig, type WebServerLog, type WebServerLogLevel, type WebServerPoolOptions };
1912
2560
  //# sourceMappingURL=index.d.mts.map