@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.cjs CHANGED
@@ -47,6 +47,7 @@ let _blazediff_core_native = require("@blazediff/core-native");
47
47
  let _blazediff_interpret_native = require("@blazediff/interpret-native");
48
48
  let node_crypto = require("node:crypto");
49
49
  let playwright_core = require("playwright-core");
50
+ let node_child_process = require("node:child_process");
50
51
  //#region src/features/png/util.ts
51
52
  const pngSignature = Buffer.from([
52
53
  137,
@@ -1001,6 +1002,91 @@ const recordCaptureOrigins = async (outputDir, origins, knownNames) => {
1001
1002
  }
1002
1003
  };
1003
1004
  //#endregion
1005
+ //#region src/webServer/unreachable.ts
1006
+ /** The advice for a refused connection when the config has no `webServer`. */
1007
+ const NO_WEB_SERVER_HINT = "Start it before capturing, or add a `webServer` entry to cappa.config.ts so cappa starts it for you.";
1008
+ /**
1009
+ * How a refused connection reads, across the places one surfaces: Node's
1010
+ * sockets and `fetch` (`ECONNREFUSED`), Chromium (`net::ERR_CONNECTION_REFUSED`),
1011
+ * Firefox (`NS_ERROR_CONNECTION_REFUSED`) and WebKit.
1012
+ */
1013
+ const REFUSED_PATTERN = /\bECONNREFUSED\b|\bERR_CONNECTION_REFUSED\b|\bNS_ERROR_CONNECTION_REFUSED\b|Could not connect to (?:the )?server|Connection refused/i;
1014
+ const URL_PATTERN = /\bhttps?:\/\/[^\s"'`<>)\]]+/i;
1015
+ const toOrigin = (url) => {
1016
+ try {
1017
+ return new URL(url.replace(/[.,;:!?]+$/, "")).origin;
1018
+ } catch {
1019
+ return;
1020
+ }
1021
+ };
1022
+ /**
1023
+ * Whether `error` — an `Error`, a plain object, or just a message string, as
1024
+ * plugins report task failures — is a refused connection.
1025
+ *
1026
+ * Walks `cause` and `AggregateError.errors`: Node's `fetch` says only
1027
+ * "fetch failed" and puts `ECONNREFUSED` on its cause, and a plugin that wraps
1028
+ * the error in a friendlier one keeps it there too.
1029
+ *
1030
+ * Works on any plugin's errors, third-party included, because it reads the
1031
+ * error rather than asking the plugin.
1032
+ */
1033
+ function findRefusedConnection(error) {
1034
+ let refused = false;
1035
+ let origin;
1036
+ let socketOrigin;
1037
+ const seen = /* @__PURE__ */ new Set();
1038
+ const visit = (value, depth) => {
1039
+ if (value === null || value === void 0 || depth > 8 || seen.has(value)) return;
1040
+ seen.add(value);
1041
+ if (typeof value === "string") {
1042
+ if (REFUSED_PATTERN.test(value)) refused = true;
1043
+ const url = value.match(URL_PATTERN)?.[0];
1044
+ origin ??= url ? toOrigin(url) : void 0;
1045
+ return;
1046
+ }
1047
+ if (typeof value !== "object") return;
1048
+ const record = value;
1049
+ if (record.code === "ECONNREFUSED") {
1050
+ refused = true;
1051
+ if (typeof record.address === "string" && record.port !== void 0) {
1052
+ const host = record.address.includes(":") ? `[${record.address}]` : record.address;
1053
+ socketOrigin ??= `http://${host}:${record.port}`;
1054
+ }
1055
+ }
1056
+ visit(record.message, depth + 1);
1057
+ visit(record.cause, depth + 1);
1058
+ if (Array.isArray(record.errors)) for (const inner of record.errors) visit(inner, depth + 1);
1059
+ };
1060
+ visit(error, 0);
1061
+ if (!refused) return;
1062
+ const resolved = origin ?? socketOrigin;
1063
+ return resolved ? { origin: resolved } : {};
1064
+ }
1065
+ const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
1066
+ "localhost",
1067
+ "127.0.0.1",
1068
+ "[::1]",
1069
+ "0.0.0.0"
1070
+ ]);
1071
+ /**
1072
+ * Whether two origins name the same server.
1073
+ *
1074
+ * Loopback spellings are interchangeable: a plugin configured with
1075
+ * `localhost:6006` and a socket error reporting `127.0.0.1:6006` are the same
1076
+ * Storybook.
1077
+ */
1078
+ function sameServer(a, b) {
1079
+ try {
1080
+ const left = new URL(a);
1081
+ const right = new URL(b);
1082
+ const port = (url) => url.port || (url.protocol === "https:" ? "443" : "80");
1083
+ if (port(left) !== port(right)) return false;
1084
+ return left.hostname === right.hostname || LOOPBACK_HOSTS.has(left.hostname) && LOOPBACK_HOSTS.has(right.hostname);
1085
+ } catch {
1086
+ return false;
1087
+ }
1088
+ }
1089
+ //#endregion
1004
1090
  //#region src/runner/tasks.ts
1005
1091
  const isObject = (value) => typeof value === "object" && value !== null;
1006
1092
  /**
@@ -1092,6 +1178,8 @@ var CaptureRunner = class {
1092
1178
  outputDir;
1093
1179
  fileSystem;
1094
1180
  now;
1181
+ prepare;
1182
+ explainUnreachable;
1095
1183
  listeners = /* @__PURE__ */ new Set();
1096
1184
  controller = new AbortController();
1097
1185
  seq = 0;
@@ -1121,6 +1209,8 @@ var CaptureRunner = class {
1121
1209
  this.fileSystem = options.fileSystem ?? options.screenshotTool.filesystem ?? new ScreenshotFileSystem(this.outputDir);
1122
1210
  this.id = options.id ?? (0, node_crypto.randomUUID)();
1123
1211
  this.now = options.now ?? (() => Date.now());
1212
+ this.prepare = options.prepare;
1213
+ this.explainUnreachable = options.explainUnreachable ?? (() => "Start it before capturing, or add a `webServer` entry to cappa.config.ts so cappa starts it for you.");
1124
1214
  }
1125
1215
  /** Subscribe to run events. Returns an unsubscribe function. */
1126
1216
  on(listener) {
@@ -1209,6 +1299,10 @@ var CaptureRunner = class {
1209
1299
  this.attachToolCaptureSink();
1210
1300
  try {
1211
1301
  try {
1302
+ if (this.prepare) {
1303
+ this.state = "discovering";
1304
+ await this.prepare((level, message) => this.log(level, message));
1305
+ }
1212
1306
  if (request.clearActual ?? true) {
1213
1307
  this.log("debug", `Cleaning output directory: ${this.outputDir}`);
1214
1308
  this.fileSystem.clearActual();
@@ -1216,7 +1310,8 @@ var CaptureRunner = class {
1216
1310
  }
1217
1311
  const pluginTasks = await this.discover(request);
1218
1312
  if (!this.controller.signal.aborted) await this.execute(pluginTasks);
1219
- } catch (error) {
1313
+ } catch (thrown) {
1314
+ const error = this.toUnreachableError(thrown) ?? thrown;
1220
1315
  this.error = error;
1221
1316
  this.state = "failed";
1222
1317
  this.finishedAt = this.now();
@@ -1394,6 +1489,7 @@ var CaptureRunner = class {
1394
1489
  }
1395
1490
  const durationMs = this.now() - taskStart;
1396
1491
  completedTasks++;
1492
+ result = this.explainTaskError(result);
1397
1493
  const failed = didScreenshotFail(result);
1398
1494
  const status = toTaskStatus(result);
1399
1495
  const typedResult = result;
@@ -1432,6 +1528,36 @@ var CaptureRunner = class {
1432
1528
  });
1433
1529
  }
1434
1530
  }
1531
+ /**
1532
+ * The message for a refused connection: where, and what to do about it.
1533
+ *
1534
+ * Identical for every task that hit the same server — no task id, no path —
1535
+ * so a report can collapse 300 of them into one line.
1536
+ */
1537
+ unreachableMessage(origin) {
1538
+ return `Cannot reach ${origin ?? "the app under test"}: connection refused. ${this.explainUnreachable(origin)}`;
1539
+ }
1540
+ toUnreachableError(error) {
1541
+ const refused = findRefusedConnection(error);
1542
+ if (!refused) return;
1543
+ return new Error(this.unreachableMessage(refused.origin), { cause: error });
1544
+ }
1545
+ /**
1546
+ * Replace a plugin's refused-connection error with the explained one.
1547
+ *
1548
+ * Reads the result rather than asking the plugin, so third-party plugins get
1549
+ * the same message without an API change.
1550
+ */
1551
+ explainTaskError(result) {
1552
+ const error = result?.error;
1553
+ if (error === void 0 || error === null) return result;
1554
+ const refused = findRefusedConnection(error);
1555
+ if (!refused) return result;
1556
+ return {
1557
+ ...result,
1558
+ error: this.unreachableMessage(refused.origin)
1559
+ };
1560
+ }
1435
1561
  async collectDeleted() {
1436
1562
  if (!this.anyTasksRan) return;
1437
1563
  try {
@@ -2364,6 +2490,404 @@ const collectScreenshots = async (outputDir) => {
2364
2490
  }));
2365
2491
  };
2366
2492
  //#endregion
2493
+ //#region src/webServer/process.ts
2494
+ /** Grace period between SIGTERM and SIGKILL. */
2495
+ const DEFAULT_KILL_GRACE_MS = 5e3;
2496
+ /** How long to wait for the kernel to reap a SIGKILLed group. */
2497
+ const SIGKILL_WAIT_MS = 2e3;
2498
+ const isWindows = process.platform === "win32";
2499
+ /**
2500
+ * The last part of a process's output, kept in memory.
2501
+ *
2502
+ * Bounded by bytes rather than lines: a dev server that prints one enormous
2503
+ * line is no reason to hold on to all of it, and the tail exists to explain a
2504
+ * failure, not to be a log.
2505
+ */
2506
+ var OutputTail = class {
2507
+ maxBytes;
2508
+ chunks = [];
2509
+ size = 0;
2510
+ constructor(maxBytes = 65536) {
2511
+ this.maxBytes = maxBytes;
2512
+ }
2513
+ push(chunk) {
2514
+ this.chunks.push(chunk);
2515
+ this.size += chunk.length;
2516
+ while (this.size > this.maxBytes && this.chunks.length > 1) this.size -= this.chunks.shift()?.length ?? 0;
2517
+ }
2518
+ /** The last `maxLines` non-empty lines. */
2519
+ lines(maxLines = 30) {
2520
+ return this.chunks.join("").split(/\r?\n/).filter((line) => line.trim() !== "").slice(-maxLines);
2521
+ }
2522
+ };
2523
+ /**
2524
+ * Process groups this process started and has not stopped yet.
2525
+ *
2526
+ * Exists for the one exit no `close()` covers: the process leaving without
2527
+ * shutting down. A server left running holds its port, and the next run would
2528
+ * silently *reuse* it — a stale build answering for the current one.
2529
+ */
2530
+ const liveProcesses = /* @__PURE__ */ new Set();
2531
+ let exitHookInstalled = false;
2532
+ const installExitHook = () => {
2533
+ if (exitHookInstalled) return;
2534
+ exitHookInstalled = true;
2535
+ process.on("exit", () => {
2536
+ for (const child of liveProcesses) killTreeNow(child);
2537
+ liveProcesses.clear();
2538
+ });
2539
+ };
2540
+ const killTreeNow = (child) => {
2541
+ if (child.pid === void 0) return;
2542
+ try {
2543
+ if (isWindows) (0, node_child_process.execFileSync)("taskkill", [
2544
+ "/pid",
2545
+ String(child.pid),
2546
+ "/T",
2547
+ "/F"
2548
+ ], { stdio: "ignore" });
2549
+ else process.kill(-child.pid, "SIGKILL");
2550
+ } catch {}
2551
+ };
2552
+ /**
2553
+ * Start `command` through a shell, as the leader of its own process group.
2554
+ *
2555
+ * A group, because the command is rarely the server itself: `pnpm storybook`
2556
+ * is pnpm, running a shell, running storybook, running workers. Killing only
2557
+ * the direct child would leave the rest holding the port.
2558
+ *
2559
+ * Output is buffered, never written anywhere unless `onOutput` asks for it —
2560
+ * `cappa capture --json` must stay a single clean document on stdout.
2561
+ */
2562
+ function spawnServerProcess(command, options) {
2563
+ const child = (0, node_child_process.spawn)(command, {
2564
+ cwd: options.cwd,
2565
+ env: {
2566
+ ...process.env,
2567
+ ...options.env
2568
+ },
2569
+ shell: true,
2570
+ detached: !isWindows,
2571
+ stdio: [
2572
+ "ignore",
2573
+ "pipe",
2574
+ "pipe"
2575
+ ],
2576
+ windowsHide: true
2577
+ });
2578
+ const output = new OutputTail();
2579
+ const onData = (data) => {
2580
+ const chunk = data.toString();
2581
+ output.push(chunk);
2582
+ options.onOutput?.(chunk);
2583
+ };
2584
+ child.stdout?.on("data", onData);
2585
+ child.stderr?.on("data", onData);
2586
+ liveProcesses.add(child);
2587
+ installExitHook();
2588
+ let exit;
2589
+ const exited = new Promise((resolve) => {
2590
+ const settle = (value) => {
2591
+ if (exit) return;
2592
+ exit = value;
2593
+ resolve(value);
2594
+ };
2595
+ child.once("exit", (code, signal) => settle({
2596
+ code,
2597
+ signal
2598
+ }));
2599
+ child.once("error", (error) => {
2600
+ output.push(`${error.message}\n`);
2601
+ settle({
2602
+ code: null,
2603
+ signal: null
2604
+ });
2605
+ });
2606
+ });
2607
+ let killing;
2608
+ return {
2609
+ get pid() {
2610
+ return child.pid;
2611
+ },
2612
+ exited,
2613
+ get exit() {
2614
+ return exit;
2615
+ },
2616
+ output,
2617
+ kill(graceMs = DEFAULT_KILL_GRACE_MS) {
2618
+ killing ??= killProcessTree(child, exited, graceMs).finally(() => {
2619
+ liveProcesses.delete(child);
2620
+ });
2621
+ return killing;
2622
+ }
2623
+ };
2624
+ }
2625
+ /** True while any process in the group led by `pid` is alive. */
2626
+ const groupAlive = (pid) => {
2627
+ try {
2628
+ process.kill(-pid, 0);
2629
+ return true;
2630
+ } catch (error) {
2631
+ return error.code === "EPERM";
2632
+ }
2633
+ };
2634
+ const delay = (ms) => new Promise((resolve) => {
2635
+ setTimeout(resolve, ms);
2636
+ });
2637
+ /**
2638
+ * SIGTERM the whole group, then SIGKILL whatever is left after `graceMs`.
2639
+ *
2640
+ * Waits on the group, not the child: the shell can exit at once while the
2641
+ * server it started is still shutting down — and still holding the port.
2642
+ */
2643
+ async function killProcessTree(child, exited, graceMs) {
2644
+ const pid = child.pid;
2645
+ if (pid === void 0) return;
2646
+ if (isWindows) {
2647
+ await new Promise((resolve) => {
2648
+ (0, node_child_process.execFile)("taskkill", [
2649
+ "/pid",
2650
+ String(pid),
2651
+ "/T",
2652
+ "/F"
2653
+ ], () => resolve());
2654
+ });
2655
+ await exited;
2656
+ return;
2657
+ }
2658
+ if (!groupAlive(pid)) return;
2659
+ try {
2660
+ process.kill(-pid, "SIGTERM");
2661
+ } catch {
2662
+ return;
2663
+ }
2664
+ const deadline = Date.now() + graceMs;
2665
+ while (groupAlive(pid) && Date.now() < deadline) await delay(50);
2666
+ if (groupAlive(pid)) {
2667
+ try {
2668
+ process.kill(-pid, "SIGKILL");
2669
+ } catch {}
2670
+ const killDeadline = Date.now() + SIGKILL_WAIT_MS;
2671
+ while (groupAlive(pid) && Date.now() < killDeadline) await delay(20);
2672
+ }
2673
+ await exited;
2674
+ }
2675
+ //#endregion
2676
+ //#region src/webServer/readiness.ts
2677
+ const PROBE_TIMEOUT_MS = 5e3;
2678
+ /** Delays between probes; the last one repeats. */
2679
+ const POLL_DELAYS_MS = [
2680
+ 100,
2681
+ 250,
2682
+ 500,
2683
+ 1e3
2684
+ ];
2685
+ /**
2686
+ * Whether `url` answers with a 2xx or 3xx status.
2687
+ *
2688
+ * Redirects are not followed: a dev server that redirects `/` to `/login` is
2689
+ * up, and following it would make readiness depend on a page cappa never asked
2690
+ * about.
2691
+ */
2692
+ async function isUrlReady(url, timeoutMs = PROBE_TIMEOUT_MS) {
2693
+ try {
2694
+ const response = await fetch(url, {
2695
+ redirect: "manual",
2696
+ signal: AbortSignal.timeout(Math.max(1, timeoutMs))
2697
+ });
2698
+ await response.body?.cancel().catch(() => {});
2699
+ return response.status >= 200 && response.status < 400;
2700
+ } catch {
2701
+ return false;
2702
+ }
2703
+ }
2704
+ /** Poll `url` until it is ready, the deadline passes, or `abort` settles. */
2705
+ async function waitForUrl(url, options) {
2706
+ const probe = options.probe ?? isUrlReady;
2707
+ const deadline = Date.now() + options.timeoutMs;
2708
+ let aborted = false;
2709
+ const abort = (options.abort ?? new Promise(() => {})).then(() => {
2710
+ aborted = true;
2711
+ }, () => {
2712
+ aborted = true;
2713
+ });
2714
+ for (let attempt = 0;; attempt++) {
2715
+ const remaining = deadline - Date.now();
2716
+ if (aborted) return "aborted";
2717
+ if (remaining <= 0) return "timeout";
2718
+ if (await probe(url, Math.min(remaining, PROBE_TIMEOUT_MS))) return "ready";
2719
+ const wait = Math.min(POLL_DELAYS_MS[Math.min(attempt, POLL_DELAYS_MS.length - 1)] ?? 1e3, Math.max(0, deadline - Date.now()));
2720
+ let timer;
2721
+ await Promise.race([new Promise((resolve) => {
2722
+ timer = setTimeout(resolve, wait);
2723
+ }), abort]);
2724
+ clearTimeout(timer);
2725
+ }
2726
+ }
2727
+ //#endregion
2728
+ //#region src/webServer/WebServerPool.ts
2729
+ /** A web server could not be started, or would not become ready. */
2730
+ var WebServerError = class extends Error {
2731
+ constructor(message) {
2732
+ super(message);
2733
+ this.name = "WebServerError";
2734
+ }
2735
+ };
2736
+ const describeExit = (exit) => exit.signal ? `signal ${exit.signal}` : exit.code === null ? "an error" : `code ${exit.code}`;
2737
+ const formatTail = (command, lines) => lines.length === 0 ? `\`${command}\` printed nothing.` : `Last output of \`${command}\`:\n${lines.map((line) => ` ${line}`).join("\n")}`;
2738
+ const seconds = (ms) => `${Math.round(ms / 100) / 10}s`;
2739
+ /**
2740
+ * The servers a config's `webServer` describes, started on demand.
2741
+ *
2742
+ * Lazy and restartable rather than started once: the owning engine calls
2743
+ * `ensure` before every run and `stop` when the browser goes idle, so a review
2744
+ * session that sits unused gives the port back, and the next capture starts —
2745
+ * and rebuilds — the app again, picking up whatever changed in between.
2746
+ *
2747
+ * Every `ensure` says which way it went, because "reusing a server" and
2748
+ * "started one" look identical in screenshots, and a stale build, another
2749
+ * branch or another project on the same port is otherwise very hard to spot.
2750
+ */
2751
+ var WebServerPool = class {
2752
+ entries;
2753
+ options;
2754
+ probe;
2755
+ /** Bumped by `stop`, so a start in flight knows it was cancelled. */
2756
+ generation = 0;
2757
+ constructor(options) {
2758
+ this.options = options;
2759
+ this.probe = options.probe ?? isUrlReady;
2760
+ this.entries = options.servers.map((config) => ({
2761
+ config,
2762
+ state: { kind: "idle" },
2763
+ starting: null
2764
+ }));
2765
+ }
2766
+ /** Whether the config has any `webServer` entry at all. */
2767
+ get configured() {
2768
+ return this.entries.length > 0;
2769
+ }
2770
+ /** Number of processes cappa started that are still running. */
2771
+ get running() {
2772
+ return this.entries.filter((entry) => entry.state.kind === "running" && !entry.state.process.exit).length;
2773
+ }
2774
+ /**
2775
+ * Make every server ready, in parallel, starting the ones that are not.
2776
+ *
2777
+ * All of them, even for a run that only captures one plugin's tasks: nothing
2778
+ * maps a plugin to a server, and guessing would start the wrong one.
2779
+ */
2780
+ async ensure(log = this.defaultLog) {
2781
+ if (this.entries.length === 0) return;
2782
+ const errors = (await Promise.allSettled(this.entries.map((entry) => this.ensureEntry(entry, log)))).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
2783
+ if (errors.length === 1) throw errors[0];
2784
+ if (errors.length > 1) throw new WebServerError(errors.map((error) => error instanceof Error ? error.message : error).join("\n\n"));
2785
+ }
2786
+ /**
2787
+ * Stop every server cappa started. A reused server is left alone — cappa did
2788
+ * not start it, so it is not cappa's to stop.
2789
+ */
2790
+ async stop() {
2791
+ this.generation += 1;
2792
+ await Promise.all(this.entries.map(async (entry) => {
2793
+ const state = entry.state;
2794
+ entry.state = { kind: "idle" };
2795
+ if (state.kind === "running") await state.process.kill(this.options.killGraceMs);
2796
+ }));
2797
+ }
2798
+ /**
2799
+ * What to tell the user about a connection refused at `origin`.
2800
+ *
2801
+ * Always an actionable sentence: the bare "ECONNREFUSED" it replaces is the
2802
+ * single most common capture failure, and says nothing about what to do.
2803
+ */
2804
+ explainUnreachable(origin) {
2805
+ if (this.entries.length === 0) return NO_WEB_SERVER_HINT;
2806
+ const matching = origin ? this.entries.find((entry) => sameServer(entry.config.url, origin)) : void 0;
2807
+ const crashed = matching?.state.kind === "exited" ? matching : this.entries.find((entry) => entry.state.kind === "exited");
2808
+ if (crashed && crashed.state.kind === "exited") 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)}`;
2809
+ if (origin && !matching) return `No \`webServer\` entry serves ${origin} (configured: ${this.entries.map((entry) => entry.config.url).join(", ")}). Check that the plugin's URL matches \`webServer.url\`.`;
2810
+ return "The configured `webServer` was ready, but stopped accepting connections.";
2811
+ }
2812
+ defaultLog = (level, message) => {
2813
+ this.options.log?.(level, message);
2814
+ };
2815
+ ensureEntry(entry, log) {
2816
+ entry.starting ??= this.startEntry(entry, log).finally(() => {
2817
+ entry.starting = null;
2818
+ });
2819
+ return entry.starting;
2820
+ }
2821
+ async startEntry(entry, log) {
2822
+ const { command, url, timeout, cwd, env, reuseExistingServer } = entry.config;
2823
+ const previous = entry.state;
2824
+ if (previous.kind === "running" && !previous.process.exit) {
2825
+ log("info", `Using \`${command}\` at ${url}, started earlier by cappa`);
2826
+ return;
2827
+ }
2828
+ if (previous.kind === "exited") log("warn", `\`${command}\` exited with ${describeExit(previous.exit)} after the last run; starting it again`);
2829
+ if (await this.probe(url, Math.min(timeout, 5e3))) {
2830
+ if (reuseExistingServer) {
2831
+ entry.state = { kind: "reused" };
2832
+ log("info", `Reusing server at ${url} — \`${command}\` was not run`);
2833
+ return;
2834
+ }
2835
+ throw new WebServerError(`${url} is already in use, and \`webServer.reuseExistingServer\` is false. Stop whatever is serving it, or allow reusing it.`);
2836
+ }
2837
+ const generation = this.generation;
2838
+ const startedAt = Date.now();
2839
+ log("info", `Starting \`${command}\` — waiting up to ${seconds(timeout)} for ${url}`);
2840
+ const child = (this.options.spawn ?? spawnServerProcess)(command, {
2841
+ cwd,
2842
+ env,
2843
+ onOutput: this.options.onOutput ? (chunk) => this.options.onOutput?.(entry.config, chunk) : void 0
2844
+ });
2845
+ entry.state = {
2846
+ kind: "running",
2847
+ process: child
2848
+ };
2849
+ const result = await waitForUrl(url, {
2850
+ timeoutMs: timeout,
2851
+ abort: child.exited,
2852
+ probe: this.probe
2853
+ });
2854
+ if (generation !== this.generation) {
2855
+ await child.kill(this.options.killGraceMs);
2856
+ throw new WebServerError(`\`${command}\` was stopped before ${url} was ready.`);
2857
+ }
2858
+ if (result === "ready") {
2859
+ this.watchForCrash(entry, child);
2860
+ log("success", `Started \`${command}\` — ${url} ready in ${seconds(Date.now() - startedAt)}`);
2861
+ return;
2862
+ }
2863
+ entry.state = { kind: "idle" };
2864
+ if (result === "aborted") {
2865
+ const exit = await child.exited;
2866
+ throw new WebServerError(`\`${command}\` exited with ${describeExit(exit)} before ${url} was ready.\n${formatTail(command, child.output.lines())}`);
2867
+ }
2868
+ await child.kill(this.options.killGraceMs);
2869
+ throw new WebServerError(`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())}`);
2870
+ }
2871
+ /**
2872
+ * Record a server that exits on its own, so the failures it causes can say
2873
+ * why and the next run starts it again. Deliberately no restart loop: a
2874
+ * server that keeps crashing should fail loudly, not flap.
2875
+ */
2876
+ watchForCrash(entry, child) {
2877
+ child.exited.then((exit) => {
2878
+ const state = entry.state;
2879
+ if (state.kind !== "running" || state.process !== child) return;
2880
+ entry.state = {
2881
+ kind: "exited",
2882
+ exit,
2883
+ tail: child.output.lines()
2884
+ };
2885
+ child.kill(this.options.killGraceMs);
2886
+ this.defaultLog("error", `\`${entry.config.command}\` exited with ${describeExit(exit)} while cappa was using it.`);
2887
+ });
2888
+ }
2889
+ };
2890
+ //#endregion
2367
2891
  //#region src/engine/RunStore.ts
2368
2892
  /**
2369
2893
  * In-memory registry of capture runs and their event history.
@@ -2529,6 +3053,7 @@ const isWatchInProgressError = (error) => hasCode(error, ENGINE_ERROR_CODES.watc
2529
3053
  var WarmBrowser = class {
2530
3054
  createTool;
2531
3055
  idleTimeoutMs;
3056
+ onShutdown;
2532
3057
  tool = null;
2533
3058
  idleTimer = null;
2534
3059
  inUse = false;
@@ -2540,6 +3065,7 @@ var WarmBrowser = class {
2540
3065
  constructor(options) {
2541
3066
  this.createTool = options.create;
2542
3067
  this.idleTimeoutMs = options.idleTimeoutMs ?? 3e5;
3068
+ this.onShutdown = options.onShutdown;
2543
3069
  }
2544
3070
  /** True while a browser process is alive. */
2545
3071
  get isWarm() {
@@ -2611,7 +3137,11 @@ var WarmBrowser = class {
2611
3137
  const tool = this.tool;
2612
3138
  this.tool = null;
2613
3139
  this.inUse = false;
2614
- if (tool) await tool.close();
3140
+ try {
3141
+ if (tool) await tool.close();
3142
+ } finally {
3143
+ await this.onShutdown?.();
3144
+ }
2615
3145
  });
2616
3146
  }
2617
3147
  startIdleTimer() {
@@ -2636,7 +3166,11 @@ var WarmBrowser = class {
2636
3166
  if (this.inUse || this.closed || this.holds > 0) return;
2637
3167
  const tool = this.tool;
2638
3168
  this.tool = null;
2639
- if (tool) await tool.close();
3169
+ try {
3170
+ if (tool) await tool.close();
3171
+ } finally {
3172
+ await this.onShutdown?.();
3173
+ }
2640
3174
  });
2641
3175
  }
2642
3176
  serialize(work) {
@@ -3000,6 +3534,28 @@ const toRelative = (cwd, changedPath) => {
3000
3534
  };
3001
3535
  //#endregion
3002
3536
  //#region src/engine/LocalEngine.ts
3537
+ const defaultLog = (level, message) => {
3538
+ try {
3539
+ (0, _cappa_logger.getLogger)()[level](message);
3540
+ } catch {}
3541
+ };
3542
+ /**
3543
+ * Stream a web server's output live at debug level. Buffered regardless: the
3544
+ * tail is what explains a server that failed to start.
3545
+ *
3546
+ * To stderr, never stdout — `capture --json` owns stdout.
3547
+ */
3548
+ const streamOutputAtDebug = (server, chunk) => {
3549
+ let level = 0;
3550
+ try {
3551
+ level = (0, _cappa_logger.getLogger)().level;
3552
+ } catch {
3553
+ return;
3554
+ }
3555
+ if (level < 4) return;
3556
+ const prefix = `[webServer ${server.url}] `;
3557
+ process.stderr.write(chunk.split(/(?<=\n)/).map((line) => prefix + line).join(""));
3558
+ };
3003
3559
  /**
3004
3560
  * `CaptureEngine` backed by an in-process Playwright browser.
3005
3561
  *
@@ -3017,6 +3573,7 @@ var LocalEngine = class {
3017
3573
  fileSystem;
3018
3574
  browser;
3019
3575
  runs;
3576
+ webServers;
3020
3577
  /**
3021
3578
  * Set synchronously the moment a run is claimed, before any `await`, so two
3022
3579
  * concurrent `startRun` calls cannot both pass the check and then fight over
@@ -3044,9 +3601,16 @@ var LocalEngine = class {
3044
3601
  this.plugins = options.plugins;
3045
3602
  this.fileSystem = new ScreenshotFileSystem(options.outputDir);
3046
3603
  this.runs = new RunStore(options.runStore);
3604
+ this.webServers = new WebServerPool({
3605
+ servers: options.webServer ?? [],
3606
+ log: defaultLog,
3607
+ onOutput: streamOutputAtDebug,
3608
+ ...options.webServerPool
3609
+ });
3047
3610
  this.browser = new WarmBrowser({
3048
3611
  create: options.createScreenshotTool ?? (() => this.buildTool()),
3049
- idleTimeoutMs: options.browserIdleTimeoutMs
3612
+ idleTimeoutMs: options.browserIdleTimeoutMs,
3613
+ onShutdown: () => this.webServers.stop()
3050
3614
  });
3051
3615
  }
3052
3616
  buildTool() {
@@ -3096,7 +3660,9 @@ var LocalEngine = class {
3096
3660
  screenshotTool: await this.browser.acquire(),
3097
3661
  plugins: this.plugins,
3098
3662
  outputDir: this.options.outputDir,
3099
- fileSystem: this.fileSystem
3663
+ fileSystem: this.fileSystem,
3664
+ prepare: (log) => this.webServers.ensure(log),
3665
+ explainUnreachable: (origin) => this.webServers.explainUnreachable(origin)
3100
3666
  });
3101
3667
  const finish = () => {
3102
3668
  if (this.activeRunId !== runner.id) return;
@@ -3234,7 +3800,11 @@ var LocalEngine = class {
3234
3800
  this.closed = true;
3235
3801
  await this.endWatch("engine-closed");
3236
3802
  (this.activeRunId ? this.runs.getRunner(this.activeRunId) : void 0)?.abort();
3237
- await this.browser.close();
3803
+ try {
3804
+ await this.browser.close();
3805
+ } finally {
3806
+ await this.webServers.stop();
3807
+ }
3238
3808
  }
3239
3809
  async endWatch(reason) {
3240
3810
  const session = this.watchSession;
@@ -3307,6 +3877,7 @@ var LocalEngine = class {
3307
3877
  async discoverTargets() {
3308
3878
  const tool = await this.browser.acquire();
3309
3879
  try {
3880
+ await this.webServers.ensure();
3310
3881
  const discovered = await Promise.all(this.plugins.map(async (plugin) => {
3311
3882
  const tasks = await plugin.discover(tool);
3312
3883
  return {
@@ -4035,6 +4606,35 @@ const writeAgentVerdict = async (outputDir, name, input) => {
4035
4606
  return verdictPath;
4036
4607
  };
4037
4608
  //#endregion
4609
+ //#region src/webServer/resolve.ts
4610
+ const DEFAULT_WEB_SERVER_TIMEOUT_MS = 6e4;
4611
+ const isHttpUrl = (value) => URL.canParse(value) && ["http:", "https:"].includes(new URL(value).protocol);
4612
+ /**
4613
+ * Normalise `webServer` to a list with every default applied.
4614
+ *
4615
+ * A relative `cwd` resolves against `configDir` — the directory of
4616
+ * `cappa.config.ts` — not the process's working directory, so the same config
4617
+ * works whether cappa runs from the repository root or from inside the package
4618
+ * (`pnpm -F visual-tests cappa capture`).
4619
+ */
4620
+ function resolveWebServerConfig(webServer, configDir, env = process.env) {
4621
+ if (webServer === void 0) return [];
4622
+ return (Array.isArray(webServer) ? webServer : [webServer]).map((entry, index) => {
4623
+ const where = Array.isArray(webServer) ? `webServer[${index}]` : "webServer";
4624
+ if (typeof entry?.command !== "string" || entry.command.trim() === "") throw new Error(`Invalid configuration: ${where}.command is required.`);
4625
+ if (typeof entry.url !== "string" || !isHttpUrl(entry.url)) throw new Error(`Invalid configuration: ${where}.url must be an absolute URL, e.g. "http://localhost:6006".`);
4626
+ if (entry.timeout !== void 0 && !(Number.isFinite(entry.timeout) && entry.timeout > 0)) throw new Error(`Invalid configuration: ${where}.timeout must be a positive number of milliseconds.`);
4627
+ return {
4628
+ command: entry.command,
4629
+ url: entry.url,
4630
+ reuseExistingServer: entry.reuseExistingServer ?? !env.CI,
4631
+ timeout: entry.timeout ?? 6e4,
4632
+ cwd: node_path.default.resolve(configDir, entry.cwd ?? "."),
4633
+ env: entry.env ?? {}
4634
+ };
4635
+ });
4636
+ }
4637
+ //#endregion
4038
4638
  exports.ACTION_BY_LABEL = ACTION_BY_LABEL;
4039
4639
  exports.AGENT_DIRNAME = AGENT_DIRNAME;
4040
4640
  exports.AGENT_REPORT_VERSION = AGENT_REPORT_VERSION;
@@ -4042,7 +4642,9 @@ exports.CONSOLE_LOG_LEVELS = CONSOLE_LOG_LEVELS;
4042
4642
  exports.CaptureRunner = CaptureRunner;
4043
4643
  exports.DEFAULT_DEBOUNCE_MS = DEFAULT_DEBOUNCE_MS;
4044
4644
  exports.DEFAULT_IGNORED_DIRS = DEFAULT_IGNORED_DIRS;
4645
+ exports.DEFAULT_KILL_GRACE_MS = DEFAULT_KILL_GRACE_MS;
4045
4646
  exports.DEFAULT_MAX_TASKS = DEFAULT_MAX_TASKS;
4647
+ exports.DEFAULT_WEB_SERVER_TIMEOUT_MS = DEFAULT_WEB_SERVER_TIMEOUT_MS;
4046
4648
  exports.ENGINE_ERROR_CODES = ENGINE_ERROR_CODES;
4047
4649
  exports.FsScreenshotStore = FsScreenshotStore;
4048
4650
  exports.JUDGED_LABELS = JUDGED_LABELS;
@@ -4050,6 +4652,8 @@ exports.JUDGE_MODES = JUDGE_MODES;
4050
4652
  exports.LocalEngine = LocalEngine;
4051
4653
  exports.MANIFEST_FILENAME = MANIFEST_FILENAME;
4052
4654
  exports.MANIFEST_VERSION = MANIFEST_VERSION;
4655
+ exports.NO_WEB_SERVER_HINT = NO_WEB_SERVER_HINT;
4656
+ exports.OutputTail = OutputTail;
4053
4657
  exports.RunInProgressError = RunInProgressError;
4054
4658
  exports.RunStore = RunStore;
4055
4659
  exports.SUB_PERCEPTUAL_PERCENT = SUB_PERCEPTUAL_PERCENT;
@@ -4060,6 +4664,8 @@ exports.VERDICT_LABELS = VERDICT_LABELS;
4060
4664
  exports.WarmBrowser = WarmBrowser;
4061
4665
  exports.WatchInProgressError = WatchInProgressError;
4062
4666
  exports.WatchSession = WatchSession;
4667
+ exports.WebServerError = WebServerError;
4668
+ exports.WebServerPool = WebServerPool;
4063
4669
  exports.agentDir = agentDir;
4064
4670
  exports.agentReportPath = agentReportPath;
4065
4671
  exports.attachConsoleLogging = attachConsoleLogging;
@@ -4073,6 +4679,7 @@ exports.defineConfig = defineConfig;
4073
4679
  exports.deriveVerdict = deriveVerdict;
4074
4680
  exports.didScreenshotFail = didScreenshotFail;
4075
4681
  exports.filterTasks = filterTasks;
4682
+ exports.findRefusedConnection = findRefusedConnection;
4076
4683
  exports.fingerprintImages = fingerprintImages;
4077
4684
  exports.getDeletedScreenshots = getDeletedScreenshots;
4078
4685
  exports.groupScreenshots = groupScreenshots;
@@ -4081,6 +4688,7 @@ exports.imagesMatchGMSD = imagesMatchGMSD;
4081
4688
  exports.isJudgedLabel = isJudgedLabel;
4082
4689
  exports.isRunInProgressError = isRunInProgressError;
4083
4690
  exports.isUnknownTargetsError = isUnknownTargetsError;
4691
+ exports.isUrlReady = isUrlReady;
4084
4692
  exports.isVerdictLabel = isVerdictLabel;
4085
4693
  exports.isWatchInProgressError = isWatchInProgressError;
4086
4694
  exports.judgmentDir = judgmentDir;
@@ -4095,15 +4703,19 @@ exports.readDiffMeta = readDiffMeta;
4095
4703
  exports.recordCaptureOrigins = recordCaptureOrigins;
4096
4704
  exports.renderJudgmentTiles = renderJudgmentTiles;
4097
4705
  exports.renderOverview = renderOverview;
4706
+ exports.resolveWebServerConfig = resolveWebServerConfig;
4098
4707
  exports.runAgentCheck = runAgentCheck;
4708
+ exports.sameServer = sameServer;
4099
4709
  exports.sanitizeScreenshotFilename = sanitizeScreenshotFilename;
4100
4710
  exports.selectTasks = selectTasks;
4711
+ exports.spawnServerProcess = spawnServerProcess;
4101
4712
  exports.toConsoleLogLevel = toConsoleLogLevel;
4102
4713
  exports.toDiffMetaPath = toDiffMetaPath;
4103
4714
  exports.toManifestKey = toManifestKey;
4104
4715
  exports.toSerializedError = toSerializedError;
4105
4716
  exports.toSlimAgentReport = toSlimAgentReport;
4106
4717
  exports.toTaskStatus = toTaskStatus;
4718
+ exports.waitForUrl = waitForUrl;
4107
4719
  exports.writeAgentVerdict = writeAgentVerdict;
4108
4720
 
4109
4721
  //# sourceMappingURL=index.cjs.map