@cappa/core 0.15.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.cts CHANGED
@@ -879,6 +879,51 @@ type DiffOptionsGMSD = {
879
879
  type: "gmsd";
880
880
  } & DiffConfigGMSD;
881
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
+ };
882
927
  /**
883
928
  * Config used in `cappa.config.ts`
884
929
  *
@@ -929,6 +974,18 @@ type UserConfig = {
929
974
  * Each plugin may have additional configurable options (defined within the plugin itself).
930
975
  */
931
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[];
932
989
  /**
933
990
  * Callback executed when screenshots fail comparison.
934
991
  * Receives the failing screenshots so they can be uploaded or processed.
@@ -1134,6 +1191,132 @@ export declare function imagesMatchGMSD(image1: string | Buffer, image2: string
1134
1191
  */
1135
1192
  export declare function defineConfig(options: PossiblePromise<UserConfig> | ((env: ConfigEnv) => PossiblePromise<UserConfig>)): typeof options;
1136
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
1137
1320
  //#region src/runner/CaptureRunner.d.ts
1138
1321
  type CaptureRunnerOptions = {
1139
1322
  /**
@@ -1155,6 +1338,17 @@ type CaptureRunnerOptions = {
1155
1338
  id?: string;
1156
1339
  /** Injectable clock, for deterministic tests. */
1157
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;
1158
1352
  };
1159
1353
  /**
1160
1354
  * Orchestrates a single capture run: discover → filter → execute, emitting
@@ -1173,6 +1367,8 @@ export declare class CaptureRunner {
1173
1367
  private readonly outputDir;
1174
1368
  private readonly fileSystem;
1175
1369
  private readonly now;
1370
+ private readonly prepare;
1371
+ private readonly explainUnreachable;
1176
1372
  private readonly listeners;
1177
1373
  private readonly controller;
1178
1374
  private seq;
@@ -1245,6 +1441,21 @@ export declare class CaptureRunner {
1245
1441
  private persistCaptureOrigins;
1246
1442
  private discover;
1247
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;
1248
1459
  private collectDeleted;
1249
1460
  }
1250
1461
  //#endregion
@@ -1665,6 +1876,13 @@ type LocalEngineOptions = {
1665
1876
  createWatcher?: CreateFileWatcher;
1666
1877
  /** Watch events buffered for replay to a (re)connecting subscriber. @default 200 */
1667
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">;
1668
1886
  };
1669
1887
  /**
1670
1888
  * `CaptureEngine` backed by an in-process Playwright browser.
@@ -1683,6 +1901,7 @@ export declare class LocalEngine implements CaptureEngine {
1683
1901
  private readonly fileSystem;
1684
1902
  private readonly browser;
1685
1903
  private readonly runs;
1904
+ private readonly webServers;
1686
1905
  /**
1687
1906
  * Set synchronously the moment a run is claimed, before any `await`, so two
1688
1907
  * concurrent `startRun` calls cannot both pass the check and then fight over
@@ -1770,6 +1989,12 @@ type WarmBrowserOptions = {
1770
1989
  * @default 300_000 (5 minutes)
1771
1990
  */
1772
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>;
1773
1998
  };
1774
1999
  /**
1775
2000
  * Keeps a Playwright browser alive between capture runs.
@@ -1786,6 +2011,7 @@ type WarmBrowserOptions = {
1786
2011
  export declare class WarmBrowser {
1787
2012
  private readonly createTool;
1788
2013
  private readonly idleTimeoutMs;
2014
+ private readonly onShutdown;
1789
2015
  private tool;
1790
2016
  private idleTimer;
1791
2017
  private inUse;
@@ -2270,5 +2496,65 @@ export declare const renderOverview: (options: {
2270
2496
  outDir: string;
2271
2497
  }) => Promise<string>;
2272
2498
  //#endregion
2273
- 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 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 SlimAgentReport, 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 WarmBrowserOptions, type WatchChange, type WatchEvent, type WatchEventType, type WatchScope, type WatchSessionOptions, type WatchStatus };
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 };
2274
2560
  //# sourceMappingURL=index.d.cts.map