@cappa/core 0.12.3 → 0.13.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
@@ -6,6 +6,15 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __exportAll = (all, no_symbols) => {
10
+ let target = {};
11
+ for (var name in all) __defProp(target, name, {
12
+ get: all[name],
13
+ enumerable: true
14
+ });
15
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
16
+ return target;
17
+ };
9
18
  var __copyProps = (to, from, except, desc) => {
10
19
  if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
20
  key = keys[i];
@@ -16,7 +25,7 @@ var __copyProps = (to, from, except, desc) => {
16
25
  }
17
26
  return to;
18
27
  };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
20
29
  value: mod,
21
30
  enumerable: true
22
31
  }) : target, mod));
@@ -35,6 +44,8 @@ node_os = __toESM(node_os);
35
44
  let node_path = require("node:path");
36
45
  node_path = __toESM(node_path);
37
46
  let _blazediff_core_native = require("@blazediff/core-native");
47
+ let _blazediff_interpret_native = require("@blazediff/interpret-native");
48
+ let node_crypto = require("node:crypto");
38
49
  let playwright_core = require("playwright-core");
39
50
  //#region src/features/png/util.ts
40
51
  const pngSignature = Buffer.from([
@@ -400,7 +411,8 @@ async function compareImages(image1, image2, withDiff = false, options = {}) {
400
411
  const percentDifference = nativeResult.diffPercentage;
401
412
  let interpretation;
402
413
  if (wantInterpret && !nativeResult.match) try {
403
- interpretation = await (0, _blazediff_core_native.interpret)(p1, p2, {
414
+ interpretation = await (0, _blazediff_interpret_native.interpret)(p1, p2, void 0, {
415
+ source: "pixel",
404
416
  threshold: options.threshold,
405
417
  antialiasing: options.includeAA ?? false
406
418
  });
@@ -493,6 +505,11 @@ async function mapWithConcurrency(concurrency, items, fn) {
493
505
  }
494
506
  //#endregion
495
507
  //#region src/filesystem.ts
508
+ var filesystem_exports = /* @__PURE__ */ __exportAll({
509
+ ScreenshotFileSystem: () => ScreenshotFileSystem,
510
+ readDiffMeta: () => readDiffMeta,
511
+ toDiffMetaPath: () => toDiffMetaPath
512
+ });
496
513
  const APPROVE_SCREENSHOTS_CONCURRENCY = 8;
497
514
  /**
498
515
  * Map a diff image path to its sidecar metadata path (`.png` -> `.json`).
@@ -774,6 +791,542 @@ var ScreenshotFileSystem = class {
774
791
  }
775
792
  };
776
793
  //#endregion
794
+ //#region src/screenshots/manifest.ts
795
+ /**
796
+ * Maps a screenshot back to the capture task that produced it.
797
+ *
798
+ * Nothing on disk carries this. A screenshot's name comes from the filename a
799
+ * plugin chose (`example/button/primary`), while the task id comes from the
800
+ * plugin's own addressing scheme (`example-button--primary` for Storybook) —
801
+ * and there is no rule connecting the two. Without a record written at capture
802
+ * time, "re-capture this one screenshot" has no task to ask for, which is
803
+ * exactly how the review UI's re-capture button came to send a name the engine
804
+ * had never heard of.
805
+ *
806
+ * Kept beside `actual/` and `expected/` rather than inside them so it is never
807
+ * mistaken for a screenshot, and dot-prefixed so `@fastify/static` (which is
808
+ * configured with `serveDotFiles: false`) will not serve it.
809
+ */
810
+ const MANIFEST_FILENAME = ".cappa-manifest.json";
811
+ /** Bumped only if the on-disk shape changes incompatibly. */
812
+ const MANIFEST_VERSION = 1;
813
+ const emptyManifest = () => ({
814
+ version: 1,
815
+ screenshots: {}
816
+ });
817
+ const manifestPath = (outputDir) => node_path.default.resolve(outputDir, MANIFEST_FILENAME);
818
+ /**
819
+ * The key a capture filename is recorded under.
820
+ *
821
+ * Must match the `name` `groupScreenshots` derives, or a lookup silently
822
+ * misses: the relative path with its `.png` dropped, and separators normalised
823
+ * so a manifest written on Windows is readable on Linux.
824
+ */
825
+ const toManifestKey = (filename) => filename.split(node_path.default.sep).join("/").replace(/\.png$/i, "");
826
+ const isOrigin = (value) => typeof value === "object" && value !== null && typeof value.taskId === "string" && typeof value.plugin === "string";
827
+ /**
828
+ * Read the manifest, or an empty one.
829
+ *
830
+ * Never throws: the manifest is an optimisation, and a missing, truncated or
831
+ * hand-edited file must degrade to "we do not know where this came from"
832
+ * rather than break the screenshot index every command depends on.
833
+ */
834
+ const readCaptureManifest = async (outputDir) => {
835
+ try {
836
+ const raw = await node_fs_promises.default.readFile(manifestPath(outputDir), "utf8");
837
+ const parsed = JSON.parse(raw);
838
+ if (typeof parsed !== "object" || parsed === null || parsed.version !== 1) return emptyManifest();
839
+ const screenshots = parsed.screenshots;
840
+ if (typeof screenshots !== "object" || screenshots === null) return emptyManifest();
841
+ const entries = Object.entries(screenshots).filter(([, origin]) => isOrigin(origin));
842
+ return {
843
+ version: 1,
844
+ screenshots: Object.fromEntries(entries)
845
+ };
846
+ } catch {
847
+ return emptyManifest();
848
+ }
849
+ };
850
+ /**
851
+ * Merge freshly captured origins into whatever the manifest already holds.
852
+ *
853
+ * A run only captures the tasks it was asked for, so existing entries have to
854
+ * survive — otherwise re-capturing one screenshot would strip every other
855
+ * screenshot's origin and disable the button that started it.
856
+ *
857
+ * `knownNames`, when given, is the set of screenshots that currently exist;
858
+ * entries outside it are dropped so renames and deletions do not accumulate
859
+ * forever. New origins are always kept, whether or not they appear in it.
860
+ */
861
+ const mergeCaptureManifest = (existing, origins, knownNames) => {
862
+ const keep = knownNames ? new Set(knownNames) : void 0;
863
+ const merged = {};
864
+ for (const [name, origin] of Object.entries(existing.screenshots)) if (!keep || keep.has(name)) merged[name] = origin;
865
+ for (const [name, origin] of Object.entries(origins)) merged[name] = origin;
866
+ return {
867
+ version: 1,
868
+ screenshots: merged
869
+ };
870
+ };
871
+ /**
872
+ * Persist `origins`, merged over what is already recorded.
873
+ *
874
+ * Best-effort by design: a read-only or full disk must not turn a successful
875
+ * capture run into a failed one, so a write failure is reported to the caller
876
+ * as `false` rather than thrown.
877
+ */
878
+ const recordCaptureOrigins = async (outputDir, origins, knownNames) => {
879
+ try {
880
+ const merged = mergeCaptureManifest(await readCaptureManifest(outputDir), origins, knownNames);
881
+ await node_fs_promises.default.mkdir(node_path.default.resolve(outputDir), { recursive: true });
882
+ await node_fs_promises.default.writeFile(manifestPath(outputDir), `${JSON.stringify(merged, null, 2)}\n`, "utf8");
883
+ return true;
884
+ } catch {
885
+ return false;
886
+ }
887
+ };
888
+ //#endregion
889
+ //#region src/runner/tasks.ts
890
+ const isObject = (value) => typeof value === "object" && value !== null;
891
+ /**
892
+ * Decide whether a plugin's `execute` result represents a failed screenshot.
893
+ *
894
+ * Plugins return loosely-shaped objects, so this inspects the three signals that
895
+ * matter: an explicit `error`, an explicit `success: false`, or a missing
896
+ * `filepath` on a task that was not skipped.
897
+ */
898
+ const didScreenshotFail = (result) => {
899
+ if (!isObject(result)) return false;
900
+ if ("error" in result && result.error != null) return true;
901
+ if ("success" in result) {
902
+ const { success } = result;
903
+ if (success === false) return true;
904
+ }
905
+ if ("filepath" in result) {
906
+ const { filepath, skipped } = result;
907
+ if (!filepath && skipped !== true) return true;
908
+ }
909
+ return false;
910
+ };
911
+ /**
912
+ * Map a plugin result onto the status shown in the UI.
913
+ *
914
+ * Mirrors the screenshot categories: a capture with no baseline is `new`, a
915
+ * failing comparison is `changed`, and anything `didScreenshotFail` flags for
916
+ * another reason is `failed`.
917
+ */
918
+ const toTaskStatus = (result) => {
919
+ if (!isObject(result)) return "passed";
920
+ const typed = result;
921
+ if (typed.skipped === true) return "skipped";
922
+ if ("error" in typed && typed.error != null) return "failed";
923
+ if (typed.isNew === true) return "new";
924
+ if (typed.success === false) return "changed";
925
+ if (didScreenshotFail(typed)) return "failed";
926
+ return "passed";
927
+ };
928
+ /** Restrict `tasks` to those whose id matches the glob `filter`. */
929
+ function filterTasks(tasks, filter) {
930
+ return tasks.filter((task) => node_path.default.matchesGlob(task.id, filter));
931
+ }
932
+ /** Restrict `tasks` to an explicit set of ids. */
933
+ function selectTasks(tasks, taskIds) {
934
+ const wanted = new Set(taskIds);
935
+ return tasks.filter((task) => wanted.has(task.id));
936
+ }
937
+ /**
938
+ * Baselines in `expected/` that have no counterpart in `actual/` — screenshots
939
+ * that existed when the baseline was approved but were not captured this run.
940
+ */
941
+ async function getDeletedScreenshots(outputDir) {
942
+ const actualDir = node_path.default.resolve(outputDir, "actual");
943
+ const expectedDir = node_path.default.resolve(outputDir, "expected");
944
+ const [actualFiles, expectedFiles] = await Promise.all([Array.fromAsync((0, node_fs_promises.glob)(node_path.default.join(actualDir, "**/*.png"))), Array.fromAsync((0, node_fs_promises.glob)(node_path.default.join(expectedDir, "**/*.png")))]);
945
+ const actualRelative = new Set(actualFiles.map((p) => node_path.default.relative(actualDir, p)));
946
+ return expectedFiles.map((p) => node_path.default.relative(expectedDir, p)).filter((rel) => !actualRelative.has(rel));
947
+ }
948
+ //#endregion
949
+ //#region src/runner/types.ts
950
+ const toSerializedError = (error) => {
951
+ if (error instanceof Error) return {
952
+ name: error.name,
953
+ message: error.message,
954
+ stack: error.stack
955
+ };
956
+ return {
957
+ name: "Error",
958
+ message: String(error)
959
+ };
960
+ };
961
+ //#endregion
962
+ //#region src/runner/CaptureRunner.ts
963
+ /**
964
+ * Orchestrates a single capture run: discover → filter → execute, emitting
965
+ * typed events as it goes.
966
+ *
967
+ * Deliberately free of any presentation or process concerns — no logger calls,
968
+ * no `chalk`, no `process.exit`. Consumers render the events however they like:
969
+ * the CLI writes them to the terminal, the server streams them over SSE.
970
+ *
971
+ * One instance represents one run. Create a new one per run.
972
+ */
973
+ var CaptureRunner = class {
974
+ id;
975
+ screenshotTool;
976
+ plugins;
977
+ outputDir;
978
+ fileSystem;
979
+ now;
980
+ listeners = /* @__PURE__ */ new Set();
981
+ controller = new AbortController();
982
+ seq = 0;
983
+ state = "idle";
984
+ request = {};
985
+ startedAt = 0;
986
+ finishedAt;
987
+ error;
988
+ anyTasksRan = false;
989
+ deletedScreenshots = [];
990
+ taskRecords = /* @__PURE__ */ new Map();
991
+ failures = [];
992
+ started = false;
993
+ /**
994
+ * Which task currently owns each pooled page.
995
+ *
996
+ * Tasks run concurrently, one per page, so the page is what disambiguates
997
+ * the capture sink's reports. Populated only while a task is executing.
998
+ */
999
+ taskByPage = /* @__PURE__ */ new Map();
1000
+ /** Screenshot name → the task that captured it, for the capture manifest. */
1001
+ capturedOrigins = /* @__PURE__ */ new Map();
1002
+ constructor(options) {
1003
+ this.screenshotTool = options.screenshotTool;
1004
+ this.plugins = options.plugins;
1005
+ this.outputDir = options.outputDir ?? options.screenshotTool.outputDir;
1006
+ this.fileSystem = options.fileSystem ?? options.screenshotTool.filesystem ?? new ScreenshotFileSystem(this.outputDir);
1007
+ this.id = options.id ?? (0, node_crypto.randomUUID)();
1008
+ this.now = options.now ?? (() => Date.now());
1009
+ }
1010
+ /** Subscribe to run events. Returns an unsubscribe function. */
1011
+ on(listener) {
1012
+ this.listeners.add(listener);
1013
+ return () => {
1014
+ this.listeners.delete(listener);
1015
+ };
1016
+ }
1017
+ get signal() {
1018
+ return this.controller.signal;
1019
+ }
1020
+ /**
1021
+ * Request cancellation. In-flight tasks finish (Playwright gives us no safe
1022
+ * mid-screenshot abort), but no further tasks are started.
1023
+ */
1024
+ abort() {
1025
+ if (this.state === "completed" || this.state === "failed") return;
1026
+ this.controller.abort();
1027
+ }
1028
+ getSummary() {
1029
+ const tasks = [...this.taskRecords.values()];
1030
+ const completedTasks = tasks.filter((task) => task.status !== "pending" && task.status !== "running").length;
1031
+ return {
1032
+ id: this.id,
1033
+ state: this.state,
1034
+ request: this.request,
1035
+ startedAt: this.startedAt,
1036
+ finishedAt: this.finishedAt,
1037
+ durationMs: this.finishedAt === void 0 ? void 0 : this.finishedAt - this.startedAt,
1038
+ totalTasks: tasks.length,
1039
+ completedTasks,
1040
+ failedTasks: this.failures.length,
1041
+ deletedScreenshots: this.deletedScreenshots,
1042
+ anyTasksRan: this.anyTasksRan,
1043
+ error: this.error === void 0 ? void 0 : toSerializedError(this.error)
1044
+ };
1045
+ }
1046
+ getDetail() {
1047
+ return {
1048
+ ...this.getSummary(),
1049
+ tasks: [...this.taskRecords.values()],
1050
+ failures: [...this.failures]
1051
+ };
1052
+ }
1053
+ /**
1054
+ * Whether the run produced at least one failing screenshot or detected a
1055
+ * deleted baseline — the condition the CLI exits non-zero on.
1056
+ */
1057
+ get hasScreenshotFailure() {
1058
+ return this.failures.length > 0 || this.deletedScreenshots.length > 0;
1059
+ }
1060
+ emit(event) {
1061
+ this.seq += 1;
1062
+ const full = {
1063
+ ...event,
1064
+ seq: this.seq,
1065
+ runId: this.id,
1066
+ at: this.now()
1067
+ };
1068
+ for (const listener of this.listeners) try {
1069
+ listener(full);
1070
+ } catch {}
1071
+ }
1072
+ log(level, message, ...args) {
1073
+ this.emit({
1074
+ type: "log",
1075
+ level,
1076
+ message,
1077
+ args
1078
+ });
1079
+ }
1080
+ /**
1081
+ * Run the capture. Resolves with the final detail; rejects if a plugin threw,
1082
+ * after emitting `run:error`.
1083
+ */
1084
+ async run(request = {}) {
1085
+ if (this.started) throw new Error(`Run ${this.id} has already been started`);
1086
+ this.started = true;
1087
+ this.request = request;
1088
+ this.startedAt = this.now();
1089
+ this.emit({
1090
+ type: "run:start",
1091
+ request
1092
+ });
1093
+ this.attachToolLogSink();
1094
+ this.attachToolCaptureSink();
1095
+ try {
1096
+ try {
1097
+ if (request.clearActual ?? true) {
1098
+ this.log("debug", `Cleaning output directory: ${this.outputDir}`);
1099
+ this.fileSystem.clearActual();
1100
+ this.fileSystem.clearDiff();
1101
+ }
1102
+ const pluginTasks = await this.discover(request);
1103
+ if (!this.controller.signal.aborted) await this.execute(pluginTasks);
1104
+ } catch (error) {
1105
+ this.error = error;
1106
+ this.state = "failed";
1107
+ this.finishedAt = this.now();
1108
+ this.emit({
1109
+ type: "run:error",
1110
+ error: toSerializedError(error)
1111
+ });
1112
+ throw error;
1113
+ }
1114
+ await this.collectDeleted();
1115
+ await this.persistCaptureOrigins();
1116
+ this.finishedAt = this.now();
1117
+ this.state = this.controller.signal.aborted ? "cancelled" : "completed";
1118
+ if (this.state === "cancelled") this.emit({ type: "run:cancelled" });
1119
+ const summary = this.getSummary();
1120
+ this.emit({
1121
+ type: "run:complete",
1122
+ summary
1123
+ });
1124
+ return this.getDetail();
1125
+ } finally {
1126
+ this.detachToolLogSink();
1127
+ this.detachToolCaptureSink();
1128
+ await this.persistCaptureOrigins();
1129
+ }
1130
+ }
1131
+ /**
1132
+ * Route `ScreenshotTool`'s log output through this run's events.
1133
+ *
1134
+ * Guarded rather than called outright: tests inject minimal stand-ins for the
1135
+ * tool, and a fake without the method should not fail a run.
1136
+ */
1137
+ attachToolLogSink() {
1138
+ this.screenshotTool.setLogSink?.((level, message, ...args) => {
1139
+ this.log(level, message, ...args);
1140
+ });
1141
+ }
1142
+ detachToolLogSink() {
1143
+ this.screenshotTool.setLogSink?.(null);
1144
+ }
1145
+ /**
1146
+ * Record which task produces which screenshot file.
1147
+ *
1148
+ * Guarded like the log sink: tests inject minimal tool stand-ins, and one
1149
+ * without the method must not fail a run — it only loses the manifest.
1150
+ */
1151
+ attachToolCaptureSink() {
1152
+ this.screenshotTool.setCaptureSink?.((page, filename) => {
1153
+ const origin = this.taskByPage.get(page);
1154
+ if (origin) this.capturedOrigins.set(toManifestKey(filename), origin);
1155
+ });
1156
+ }
1157
+ detachToolCaptureSink() {
1158
+ this.screenshotTool.setCaptureSink?.(null);
1159
+ this.taskByPage.clear();
1160
+ }
1161
+ /**
1162
+ * Write what this run learned about screenshot origins.
1163
+ *
1164
+ * Idempotent, because it is called once on the happy path and again from
1165
+ * `run`'s `finally` for the paths that never reach it. Existing entries are
1166
+ * preserved and only names that no longer exist on disk are dropped, so a
1167
+ * run of one task does not erase every other screenshot's origin.
1168
+ */
1169
+ async persistCaptureOrigins() {
1170
+ if (this.capturedOrigins.size === 0) return;
1171
+ const origins = Object.fromEntries(this.capturedOrigins);
1172
+ this.capturedOrigins.clear();
1173
+ let knownNames;
1174
+ try {
1175
+ const [actual, expected] = await Promise.all([this.fileSystem.getActualScreenshots(), this.fileSystem.getExpectedScreenshots()]);
1176
+ knownNames = [...actual.map((file) => toManifestKey((0, node_path.relative)(this.fileSystem.getActualDir(), file))), ...expected.map((file) => toManifestKey((0, node_path.relative)(this.fileSystem.getExpectedDir(), file)))];
1177
+ } catch {
1178
+ knownNames = void 0;
1179
+ }
1180
+ if (!await recordCaptureOrigins(this.outputDir, origins, knownNames)) this.log("debug", "Could not write the capture manifest; re-capturing a single screenshot may be unavailable.");
1181
+ }
1182
+ async discover(request) {
1183
+ this.state = "discovering";
1184
+ const wanted = request.plugins ? new Set(request.plugins) : void 0;
1185
+ const plugins = wanted ? this.plugins.filter((plugin) => wanted.has(plugin.name)) : this.plugins;
1186
+ this.emit({
1187
+ type: "discover:start",
1188
+ plugins: plugins.map((plugin) => plugin.name)
1189
+ });
1190
+ const pluginTasks = await Promise.all(plugins.map(async (plugin) => {
1191
+ this.log("debug", `Discovering tasks for plugin: ${plugin.name}`);
1192
+ const tasks = await plugin.discover(this.screenshotTool);
1193
+ this.emit({
1194
+ type: "discover:plugin",
1195
+ plugin: plugin.name,
1196
+ taskCount: tasks.length
1197
+ });
1198
+ return {
1199
+ plugin,
1200
+ tasks
1201
+ };
1202
+ }));
1203
+ const targets = pluginTasks.flatMap(({ plugin, tasks }) => tasks.map((task) => ({
1204
+ id: task.id,
1205
+ url: task.url,
1206
+ plugin: plugin.name
1207
+ })));
1208
+ this.emit({
1209
+ type: "discover:complete",
1210
+ targets,
1211
+ totalTasks: targets.length
1212
+ });
1213
+ if (request.filter === void 0 && request.taskIds === void 0) return pluginTasks;
1214
+ const applied = [];
1215
+ for (const entry of pluginTasks) {
1216
+ const before = entry.tasks.length;
1217
+ let tasks = entry.tasks;
1218
+ if (request.filter !== void 0) tasks = filterTasks(tasks, request.filter);
1219
+ if (request.taskIds !== void 0) tasks = selectTasks(tasks, request.taskIds);
1220
+ entry.tasks = tasks;
1221
+ applied.push({
1222
+ plugin: entry.plugin.name,
1223
+ before,
1224
+ after: tasks.length
1225
+ });
1226
+ }
1227
+ this.emit({
1228
+ type: "filter:applied",
1229
+ filter: request.filter,
1230
+ taskIds: request.taskIds,
1231
+ plugins: applied
1232
+ });
1233
+ return pluginTasks;
1234
+ }
1235
+ async execute(pluginTasks) {
1236
+ this.state = "running";
1237
+ for (const { plugin, tasks } of pluginTasks) {
1238
+ if (tasks.length === 0) continue;
1239
+ if (this.controller.signal.aborted) return;
1240
+ this.anyTasksRan = true;
1241
+ let pluginHasFailure = false;
1242
+ for (const task of tasks) this.taskRecords.set(task.id, {
1243
+ id: task.id,
1244
+ url: task.url,
1245
+ plugin: plugin.name,
1246
+ status: "pending"
1247
+ });
1248
+ this.emit({
1249
+ type: "plugin:start",
1250
+ plugin: plugin.name,
1251
+ taskCount: tasks.length
1252
+ });
1253
+ this.log("debug", `Processing ${tasks.length} tasks with concurrency ${this.screenshotTool.concurrency}`);
1254
+ let completedTasks = 0;
1255
+ const pageContexts = /* @__PURE__ */ new Map();
1256
+ const results = await mapWithConcurrency(this.screenshotTool.concurrency, tasks, async (task, workerIndex) => {
1257
+ if (this.controller.signal.aborted) return;
1258
+ const page = this.screenshotTool.getPageFromPool(workerIndex);
1259
+ if (!pageContexts.has(workerIndex) && plugin.initPage) pageContexts.set(workerIndex, await plugin.initPage(page, this.screenshotTool));
1260
+ const context = pageContexts.get(workerIndex);
1261
+ const record = this.taskRecords.get(task.id);
1262
+ if (record) record.status = "running";
1263
+ this.emit({
1264
+ type: "task:start",
1265
+ plugin: plugin.name,
1266
+ taskId: task.id,
1267
+ url: task.url
1268
+ });
1269
+ const taskStart = this.now();
1270
+ this.taskByPage.set(page, {
1271
+ taskId: task.id,
1272
+ plugin: plugin.name
1273
+ });
1274
+ let result;
1275
+ try {
1276
+ result = await plugin.execute(task, page, this.screenshotTool, context);
1277
+ } finally {
1278
+ this.taskByPage.delete(page);
1279
+ }
1280
+ const durationMs = this.now() - taskStart;
1281
+ completedTasks++;
1282
+ const failed = didScreenshotFail(result);
1283
+ const status = toTaskStatus(result);
1284
+ const typedResult = result;
1285
+ if (record) {
1286
+ record.status = status;
1287
+ record.durationMs = durationMs;
1288
+ record.result = typedResult;
1289
+ }
1290
+ if (failed) {
1291
+ pluginHasFailure = true;
1292
+ this.failures.push({
1293
+ taskId: task.id,
1294
+ taskUrl: task.url,
1295
+ result: typedResult ?? {},
1296
+ pluginName: plugin.name
1297
+ });
1298
+ }
1299
+ this.emit({
1300
+ type: "task:complete",
1301
+ plugin: plugin.name,
1302
+ taskId: task.id,
1303
+ url: task.url,
1304
+ status,
1305
+ completed: completedTasks,
1306
+ total: tasks.length,
1307
+ durationMs,
1308
+ result: typedResult
1309
+ });
1310
+ return result;
1311
+ });
1312
+ this.emit({
1313
+ type: "plugin:complete",
1314
+ plugin: plugin.name,
1315
+ resultCount: results.length,
1316
+ failed: pluginHasFailure
1317
+ });
1318
+ }
1319
+ }
1320
+ async collectDeleted() {
1321
+ if (!this.anyTasksRan) return;
1322
+ try {
1323
+ this.deletedScreenshots = await getDeletedScreenshots(this.outputDir);
1324
+ } catch (error) {
1325
+ this.log("warn", "Could not check for deleted screenshots:", error);
1326
+ }
1327
+ }
1328
+ };
1329
+ //#endregion
777
1330
  //#region src/screenshot.ts
778
1331
  const defaultPixelDiffConfig = {
779
1332
  type: "pixel",
@@ -789,6 +1342,15 @@ const defaultGMSDDiffConfig = {
789
1342
  downsample: 0,
790
1343
  c: 170
791
1344
  };
1345
+ const LOG_SINK_LEVELS = [
1346
+ "debug",
1347
+ "info",
1348
+ "warn",
1349
+ "error",
1350
+ "success"
1351
+ ];
1352
+ /** A logger-shaped object that forwards every call to `sink`. */
1353
+ const toSinkLogger = (sink) => Object.fromEntries(LOG_SINK_LEVELS.map((level) => [level, (message, ...args) => sink(level, String(message), ...args)]));
792
1354
  var ScreenshotTool = class {
793
1355
  browserType;
794
1356
  headless;
@@ -802,11 +1364,23 @@ var ScreenshotTool = class {
802
1364
  contexts = [];
803
1365
  pages = [];
804
1366
  diff;
1367
+ /**
1368
+ * Where this tool's own output goes.
1369
+ *
1370
+ * Normally the global logger. While a `CaptureRunner` owns the tool it is
1371
+ * swapped for a shim that forwards into the run's event stream instead — see
1372
+ * `setLogSink`.
1373
+ */
805
1374
  logger;
806
1375
  retries;
807
1376
  filesystem;
808
1377
  logConsoleEvents;
809
1378
  connectionTimeout;
1379
+ defaultUserAgent = "";
1380
+ /** The real logger, kept so `setLogSink(null)` restores the same instance. */
1381
+ baseLogger;
1382
+ /** Set while a `CaptureRunner` owns this tool — see `setCaptureSink`. */
1383
+ captureSink = null;
810
1384
  constructor(options) {
811
1385
  this.browserType = options.browserType || "chromium";
812
1386
  this.headless = options.headless !== false;
@@ -820,10 +1394,40 @@ var ScreenshotTool = class {
820
1394
  this.concurrency = Math.max(1, options.concurrency || 1);
821
1395
  this.logConsoleEvents = options.logConsoleEvents ?? true;
822
1396
  this.connectionTimeout = options.connectionTimeout ?? 2e4;
823
- this.logger = (0, _cappa_logger.getLogger)();
1397
+ this.baseLogger = (0, _cappa_logger.getLogger)();
1398
+ this.logger = this.baseLogger;
824
1399
  this.retries = options.retries || 2;
825
1400
  this.filesystem = new ScreenshotFileSystem(this.outputDir);
826
1401
  }
1402
+ /**
1403
+ * Send this tool's own log output to `sink` instead of the global logger.
1404
+ *
1405
+ * `ScreenshotTool` writes lines a user expects to see — "Screenshot saved",
1406
+ * "Screenshot passed visual comparison", the retry warnings — straight to the
1407
+ * logger. That is fine in-process and useless over a network: with the
1408
+ * browser on another machine those lines would stay in the *host's* terminal
1409
+ * while the client showed a run with no commentary. A `CaptureRunner` installs
1410
+ * a sink for the duration of a run so they travel as `log` events instead.
1411
+ *
1412
+ * Pass `null` to restore the real logger.
1413
+ */
1414
+ setLogSink(sink) {
1415
+ this.logger = sink ? toSinkLogger(sink) : this.baseLogger;
1416
+ }
1417
+ /**
1418
+ * Report every screenshot this tool writes to `sink`.
1419
+ *
1420
+ * A `CaptureRunner` installs one for the duration of a run so it can record
1421
+ * which task produced which file. Nothing else can know: a plugin picks the
1422
+ * filename inside `execute` and is free to derive it from the task however
1423
+ * it likes, so the only reliable observation point is the write itself —
1424
+ * which also catches variants, whose filenames the plugin never states.
1425
+ *
1426
+ * Pass `null` to stop reporting.
1427
+ */
1428
+ setCaptureSink(sink) {
1429
+ this.captureSink = sink;
1430
+ }
827
1431
  resolveDiffOptions(diff) {
828
1432
  if (diff?.type === "gmsd") return {
829
1433
  ...defaultGMSDDiffConfig,
@@ -863,13 +1467,22 @@ var ScreenshotTool = class {
863
1467
  if (!browser) throw new Error("Something went wrong with starting the browser.");
864
1468
  this.browser = browser;
865
1469
  const tempCtx = await browser.newContext();
866
- const defaultUserAgent = await (await tempCtx.newPage()).evaluate(() => navigator.userAgent);
1470
+ const tempPage = await tempCtx.newPage();
1471
+ this.defaultUserAgent = await tempPage.evaluate(() => navigator.userAgent);
867
1472
  await tempCtx.close();
1473
+ await this.createContexts();
1474
+ }
1475
+ /**
1476
+ * Create the pool of browser contexts and pages.
1477
+ */
1478
+ async createContexts() {
1479
+ const browser = this.browser;
1480
+ if (!browser) throw new Error("Browser not initialized");
868
1481
  const results = await Promise.all(Array.from({ length: this.concurrency }, async () => {
869
1482
  const context = await browser.newContext({
870
1483
  reducedMotion: "reduce",
871
1484
  deviceScaleFactor: 2,
872
- userAgent: `${defaultUserAgent} CappaStorybook`,
1485
+ userAgent: `${this.defaultUserAgent} CappaStorybook`,
873
1486
  viewport: this.viewport
874
1487
  });
875
1488
  return {
@@ -883,12 +1496,57 @@ var ScreenshotTool = class {
883
1496
  this.page = this.pages[0] ?? null;
884
1497
  }
885
1498
  /**
1499
+ * Closes every context and page, leaving the browser process running.
1500
+ */
1501
+ async closeContexts() {
1502
+ for (const context of this.contexts) await context.close();
1503
+ this.contexts = [];
1504
+ this.pages = [];
1505
+ this.context = null;
1506
+ this.page = null;
1507
+ }
1508
+ /**
1509
+ * Throw away the current contexts and build a fresh pool on the same browser.
1510
+ *
1511
+ * A long-lived process that keeps the browser warm between capture runs must
1512
+ * call this first: contexts accumulate cookies, storage and scroll position,
1513
+ * and a screenshot taken against leaked state is not the screenshot the CLI
1514
+ * would have taken with a fresh browser.
1515
+ */
1516
+ async recycleContexts() {
1517
+ if (!this.browser) throw new Error("Browser not initialized");
1518
+ await this.closeContexts();
1519
+ await this.createContexts();
1520
+ }
1521
+ /**
886
1522
  * Closes browser
887
1523
  * If not closed, the process will not exit
1524
+ *
1525
+ * Tolerant of a browser that is already gone. A Ctrl-C in a terminal is
1526
+ * delivered to the whole foreground process group, Chromium included, so by
1527
+ * the time a signal handler gets here every context can already be dead and
1528
+ * closing one throws `Failed to find context with id …`. Letting that escape
1529
+ * turns a clean shutdown into an uncaught exception, which is the one thing
1530
+ * teardown must never do.
888
1531
  */
889
1532
  async close() {
890
- for (const context of this.contexts) await context.close();
891
- if (this.browser) await this.browser.close();
1533
+ try {
1534
+ await this.closeContexts();
1535
+ } catch (error) {
1536
+ (0, _cappa_logger.getLogger)().debug("Error closing browser contexts:", error);
1537
+ this.contexts = [];
1538
+ this.pages = [];
1539
+ this.context = null;
1540
+ this.page = null;
1541
+ }
1542
+ if (this.browser) {
1543
+ try {
1544
+ await this.browser.close();
1545
+ } catch (error) {
1546
+ (0, _cappa_logger.getLogger)().debug("Error closing the browser:", error);
1547
+ }
1548
+ this.browser = null;
1549
+ }
892
1550
  }
893
1551
  /**
894
1552
  * Navigates to a URL with "domcontentloaded" waitUntil
@@ -1097,6 +1755,9 @@ var ScreenshotTool = class {
1097
1755
  }
1098
1756
  const duration = Math.round(performance.now() - start);
1099
1757
  this.logger.debug(`${filename} captured in ${duration}ms`);
1758
+ try {
1759
+ this.captureSink?.(page, filename);
1760
+ } catch {}
1100
1761
  return result;
1101
1762
  }
1102
1763
  async capture(page, filename, options, extras = {}) {
@@ -1278,15 +1939,1171 @@ var ScreenshotTool = class {
1278
1939
  }
1279
1940
  };
1280
1941
  //#endregion
1942
+ //#region src/screenshots/groupScreenshots.ts
1943
+ const groupScreenshots = async (actualScreenshots, expectedScreenshots, diffScreenshots, outputDir) => {
1944
+ const screenshotRepresentations = [];
1945
+ const expectedByRelativePath = /* @__PURE__ */ new Map();
1946
+ for (const screenshot of expectedScreenshots) {
1947
+ const relativePath = node_path.default.relative(`${outputDir}/expected`, screenshot);
1948
+ expectedByRelativePath.set(relativePath, screenshot);
1949
+ }
1950
+ const diffByRelativePath = /* @__PURE__ */ new Map();
1951
+ for (const screenshot of diffScreenshots) {
1952
+ const relativePath = node_path.default.relative(`${outputDir}/diff`, screenshot);
1953
+ diffByRelativePath.set(relativePath, screenshot);
1954
+ }
1955
+ const actualRelativePaths = /* @__PURE__ */ new Set();
1956
+ for (const screenshot of actualScreenshots) {
1957
+ const relativePath = node_path.default.relative(`${outputDir}/actual`, screenshot);
1958
+ actualRelativePaths.add(relativePath);
1959
+ const name = relativePath.replace(".png", "");
1960
+ const id = (0, node_crypto.createHash)("sha256").update(relativePath).digest("hex");
1961
+ const expectedScreenshot = expectedByRelativePath.get(relativePath);
1962
+ const diffScreenshot = diffByRelativePath.get(relativePath);
1963
+ const diffMeta = diffScreenshot ? await readDiffMeta(diffScreenshot) : void 0;
1964
+ screenshotRepresentations.push({
1965
+ id,
1966
+ name,
1967
+ category: buildCategory(expectedScreenshot, diffScreenshot),
1968
+ expectedPath: expectedScreenshot ? node_path.default.relative(outputDir, expectedScreenshot) : void 0,
1969
+ diffPath: diffScreenshot ? node_path.default.relative(outputDir, diffScreenshot) : void 0,
1970
+ actualPath: node_path.default.relative(outputDir, screenshot),
1971
+ ...diffMeta ? { diffMeta } : {}
1972
+ });
1973
+ }
1974
+ for (const expectedScreenshot of expectedScreenshots) {
1975
+ const relativePath = node_path.default.relative(`${outputDir}/expected`, expectedScreenshot);
1976
+ if (actualRelativePaths.has(relativePath)) continue;
1977
+ const name = relativePath.replace(".png", "");
1978
+ const id = (0, node_crypto.createHash)("sha256").update(relativePath).digest("hex");
1979
+ screenshotRepresentations.push({
1980
+ id,
1981
+ name,
1982
+ category: "deleted",
1983
+ expectedPath: node_path.default.relative(outputDir, expectedScreenshot)
1984
+ });
1985
+ }
1986
+ return screenshotRepresentations.sort((a, b) => {
1987
+ return CATEGORY_ORDER[a.category] - CATEGORY_ORDER[b.category];
1988
+ });
1989
+ };
1990
+ const buildCategory = (expectedScreenshot, diffScreenshot) => {
1991
+ if (expectedScreenshot && diffScreenshot) return "changed";
1992
+ if (expectedScreenshot) return "passed";
1993
+ return "new";
1994
+ };
1995
+ const CATEGORY_ORDER = {
1996
+ new: 0,
1997
+ deleted: 1,
1998
+ changed: 2,
1999
+ passed: 3
2000
+ };
2001
+ //#endregion
2002
+ //#region src/screenshots/collectScreenshots.ts
2003
+ const listPngs = async (dir) => Array.fromAsync(await (0, node_fs_promises.glob)(node_path.default.resolve(dir, "**/*.png")));
2004
+ /**
2005
+ * Read the `actual/`, `expected/` and `diff/` directories of `outputDir` and
2006
+ * group them into the screenshot representations used by the CLI commands
2007
+ * (including the diff metadata sidecar with the optional interpretation).
2008
+ *
2009
+ * The capture manifest is folded in here so every consumer — the CLI, the
2010
+ * server, the review UI — sees the same `taskId`, and so a screenshot captured
2011
+ * before manifests existed simply has none rather than a wrong one.
2012
+ */
2013
+ const collectScreenshots = async (outputDir) => {
2014
+ const [actualScreenshots, expectedScreenshots, diffScreenshots, manifest] = await Promise.all([
2015
+ listPngs(node_path.default.resolve(outputDir, "actual")),
2016
+ listPngs(node_path.default.resolve(outputDir, "expected")),
2017
+ listPngs(node_path.default.resolve(outputDir, "diff")),
2018
+ readCaptureManifest(outputDir)
2019
+ ]);
2020
+ return (await groupScreenshots(actualScreenshots, expectedScreenshots, diffScreenshots, outputDir)).map((screenshot) => {
2021
+ const origin = manifest.screenshots[screenshot.name];
2022
+ return origin ? {
2023
+ ...screenshot,
2024
+ taskId: origin.taskId,
2025
+ plugin: origin.plugin
2026
+ } : screenshot;
2027
+ });
2028
+ };
2029
+ //#endregion
2030
+ //#region src/engine/RunStore.ts
2031
+ /**
2032
+ * In-memory registry of capture runs and their event history.
2033
+ *
2034
+ * The event buffer is what lets an SSE client reconnect without losing
2035
+ * anything: subscribers replay from the last `seq` they saw before live
2036
+ * delivery starts.
2037
+ */
2038
+ var RunStore = class {
2039
+ maxEventsPerRun;
2040
+ maxRuns;
2041
+ runs = /* @__PURE__ */ new Map();
2042
+ /** Insertion order, oldest first — the eviction queue. */
2043
+ order = [];
2044
+ constructor(options = {}) {
2045
+ this.maxEventsPerRun = options.maxEventsPerRun ?? 5e3;
2046
+ this.maxRuns = options.maxRuns ?? 20;
2047
+ }
2048
+ /** Register a runner and start buffering its events. */
2049
+ add(runner) {
2050
+ const entry = {
2051
+ id: runner.id,
2052
+ runner,
2053
+ events: [],
2054
+ dropped: 0,
2055
+ listeners: /* @__PURE__ */ new Set()
2056
+ };
2057
+ this.runs.set(runner.id, entry);
2058
+ this.order.push(runner.id);
2059
+ this.evictOldRuns();
2060
+ runner.on((event) => {
2061
+ entry.events.push(event);
2062
+ if (entry.events.length > this.maxEventsPerRun) {
2063
+ entry.dropped += entry.events.length - this.maxEventsPerRun;
2064
+ entry.events.splice(0, entry.events.length - this.maxEventsPerRun);
2065
+ }
2066
+ for (const listener of entry.listeners) try {
2067
+ listener(event);
2068
+ } catch {}
2069
+ });
2070
+ }
2071
+ /**
2072
+ * Freeze the final detail of a finished run so it stays queryable after the
2073
+ * runner is discarded.
2074
+ */
2075
+ finalize(runId) {
2076
+ const entry = this.runs.get(runId);
2077
+ if (entry) entry.finalDetail = entry.runner.getDetail();
2078
+ }
2079
+ get(runId) {
2080
+ const entry = this.runs.get(runId);
2081
+ if (!entry) return;
2082
+ return entry.finalDetail ?? entry.runner.getDetail();
2083
+ }
2084
+ getRunner(runId) {
2085
+ return this.runs.get(runId)?.runner;
2086
+ }
2087
+ /** Newest first. */
2088
+ list() {
2089
+ return [...this.order].reverse().map((id) => {
2090
+ const entry = this.runs.get(id);
2091
+ if (!entry) return;
2092
+ return entry.finalDetail ?? entry.runner.getSummary();
2093
+ }).filter((summary) => summary !== void 0);
2094
+ }
2095
+ /**
2096
+ * Subscribe to a run, replaying buffered events first.
2097
+ *
2098
+ * Replay is synchronous, so a subscriber cannot miss events that arrive
2099
+ * between the buffer read and the listener being registered.
2100
+ */
2101
+ subscribe(runId, onEvent, options = {}) {
2102
+ const entry = this.runs.get(runId);
2103
+ if (!entry) return () => {};
2104
+ const sinceSeq = options.sinceSeq ?? 0;
2105
+ for (const event of entry.events) if (event.seq > sinceSeq) onEvent(event);
2106
+ entry.listeners.add(onEvent);
2107
+ return () => {
2108
+ entry.listeners.delete(onEvent);
2109
+ };
2110
+ }
2111
+ /** How many events were dropped from a run's buffer (0 when none were). */
2112
+ droppedEvents(runId) {
2113
+ return this.runs.get(runId)?.dropped ?? 0;
2114
+ }
2115
+ evictOldRuns() {
2116
+ while (this.order.length > this.maxRuns) {
2117
+ const oldest = this.order.shift();
2118
+ if (oldest !== void 0) this.runs.delete(oldest);
2119
+ }
2120
+ }
2121
+ };
2122
+ //#endregion
2123
+ //#region src/engine/types.ts
2124
+ /**
2125
+ * Stable discriminators for engine errors.
2126
+ *
2127
+ * These exist because `instanceof` is not reliable across the package
2128
+ * boundary. `@cappa/core` ships dual ESM/CJS builds, so a CJS consumer (the
2129
+ * CLI binary) and an ESM one (the server) each load their own copy of these
2130
+ * classes: an error thrown by one is not an `instanceof` the other's class,
2131
+ * and the check silently fails — turning a 409 into a 500. Callers must use
2132
+ * the guards below rather than `instanceof`.
2133
+ */
2134
+ const ENGINE_ERROR_CODES = {
2135
+ runInProgress: "CAPPA_RUN_IN_PROGRESS",
2136
+ unknownTargets: "CAPPA_UNKNOWN_TARGETS",
2137
+ watchInProgress: "CAPPA_WATCH_IN_PROGRESS"
2138
+ };
2139
+ /** Thrown by `startRun` when the engine is already running something. */
2140
+ var RunInProgressError = class extends Error {
2141
+ code = ENGINE_ERROR_CODES.runInProgress;
2142
+ activeRunId;
2143
+ constructor(activeRunId) {
2144
+ super(`A capture run is already in progress (${activeRunId})`);
2145
+ this.name = "RunInProgressError";
2146
+ this.activeRunId = activeRunId;
2147
+ }
2148
+ };
2149
+ /** Thrown by `startRun` when `taskIds` names tasks that were never discovered. */
2150
+ var UnknownTargetsError = class extends Error {
2151
+ code = ENGINE_ERROR_CODES.unknownTargets;
2152
+ taskIds;
2153
+ constructor(taskIds) {
2154
+ super(`Unknown task ids: ${taskIds.join(", ")}`);
2155
+ this.name = "UnknownTargetsError";
2156
+ this.taskIds = taskIds;
2157
+ }
2158
+ };
2159
+ /** Thrown by `startWatch` when a watch session is already running. */
2160
+ var WatchInProgressError = class extends Error {
2161
+ code = ENGINE_ERROR_CODES.watchInProgress;
2162
+ constructor() {
2163
+ super("A watch session is already running");
2164
+ this.name = "WatchInProgressError";
2165
+ }
2166
+ };
2167
+ const hasCode = (error, code) => error instanceof Error && error.code === code;
2168
+ /**
2169
+ * Identity-independent check for `RunInProgressError`.
2170
+ *
2171
+ * Prefer this over `instanceof` — see `ENGINE_ERROR_CODES`.
2172
+ */
2173
+ const isRunInProgressError = (error) => hasCode(error, ENGINE_ERROR_CODES.runInProgress);
2174
+ /** Identity-independent check for `UnknownTargetsError`. */
2175
+ const isUnknownTargetsError = (error) => hasCode(error, ENGINE_ERROR_CODES.unknownTargets);
2176
+ /** Identity-independent check for `WatchInProgressError`. */
2177
+ const isWatchInProgressError = (error) => hasCode(error, ENGINE_ERROR_CODES.watchInProgress);
2178
+ //#endregion
2179
+ //#region src/engine/WarmBrowser.ts
2180
+ /**
2181
+ * Keeps a Playwright browser alive between capture runs.
2182
+ *
2183
+ * Interactively, a cold Chromium start on every "Capture" click is the
2184
+ * difference between a snappy tool and a sluggish one — but a browser left
2185
+ * running forever is a memory leak, so it is evicted after an idle period.
2186
+ *
2187
+ * Contexts are recycled on every acquire after the first, because a warm
2188
+ * browser's pages carry cookies, storage and scroll position from the previous
2189
+ * run and a screenshot taken against leaked state is not the screenshot the CLI
2190
+ * would have taken.
2191
+ */
2192
+ var WarmBrowser = class {
2193
+ createTool;
2194
+ idleTimeoutMs;
2195
+ tool = null;
2196
+ idleTimer = null;
2197
+ inUse = false;
2198
+ closed = false;
2199
+ /** Outstanding `hold()` leases. While any is held, eviction is suspended. */
2200
+ holds = 0;
2201
+ /** Serializes acquire/close so concurrent callers cannot race the browser. */
2202
+ pending = Promise.resolve();
2203
+ constructor(options) {
2204
+ this.createTool = options.create;
2205
+ this.idleTimeoutMs = options.idleTimeoutMs ?? 3e5;
2206
+ }
2207
+ /** True while a browser process is alive. */
2208
+ get isWarm() {
2209
+ return this.tool !== null;
2210
+ }
2211
+ /**
2212
+ * Get a ready-to-use `ScreenshotTool`, starting or reusing the browser.
2213
+ * Always pair with `release()`.
2214
+ */
2215
+ async acquire() {
2216
+ return this.serialize(async () => {
2217
+ if (this.closed) throw new Error("WarmBrowser has been closed");
2218
+ this.cancelIdleTimer();
2219
+ this.inUse = true;
2220
+ if (this.tool) {
2221
+ await this.tool.recycleContexts();
2222
+ return this.tool;
2223
+ }
2224
+ const tool = this.createTool();
2225
+ await tool.init();
2226
+ this.tool = tool;
2227
+ return tool;
2228
+ });
2229
+ }
2230
+ /**
2231
+ * Hand the browser back. It stays warm until the idle timeout elapses.
2232
+ */
2233
+ release() {
2234
+ this.inUse = false;
2235
+ if (this.closed || !this.tool) return;
2236
+ if (this.holds > 0) {
2237
+ this.cancelIdleTimer();
2238
+ return;
2239
+ }
2240
+ if (this.idleTimeoutMs <= 0) {
2241
+ this.close();
2242
+ return;
2243
+ }
2244
+ this.startIdleTimer();
2245
+ }
2246
+ /**
2247
+ * Suspend idle eviction until the returned function is called.
2248
+ *
2249
+ * Held by an active watch session. Without it, `WarmBrowser` closes the
2250
+ * browser between saves during a coffee break and the next save pays full
2251
+ * start-up — which is the entire premise of watch mode, defeated by its own
2252
+ * idle handling.
2253
+ */
2254
+ hold() {
2255
+ this.holds += 1;
2256
+ this.cancelIdleTimer();
2257
+ let released = false;
2258
+ return () => {
2259
+ if (released) return;
2260
+ released = true;
2261
+ this.holds -= 1;
2262
+ if (this.holds === 0 && !this.inUse) this.release();
2263
+ };
2264
+ }
2265
+ /** True while at least one lease suspends idle eviction. */
2266
+ get isHeld() {
2267
+ return this.holds > 0;
2268
+ }
2269
+ /** Shut the browser down now. Safe to call repeatedly. */
2270
+ async close() {
2271
+ this.closed = true;
2272
+ this.cancelIdleTimer();
2273
+ await this.serialize(async () => {
2274
+ const tool = this.tool;
2275
+ this.tool = null;
2276
+ this.inUse = false;
2277
+ if (tool) await tool.close();
2278
+ });
2279
+ }
2280
+ startIdleTimer() {
2281
+ this.cancelIdleTimer();
2282
+ const timer = setTimeout(() => {
2283
+ this.idleTimer = null;
2284
+ if (this.inUse || this.closed || this.holds > 0 || !this.tool) return;
2285
+ this.evict();
2286
+ }, this.idleTimeoutMs);
2287
+ if (typeof timer.unref === "function") timer.unref();
2288
+ this.idleTimer = timer;
2289
+ }
2290
+ cancelIdleTimer() {
2291
+ if (this.idleTimer !== null) {
2292
+ clearTimeout(this.idleTimer);
2293
+ this.idleTimer = null;
2294
+ }
2295
+ }
2296
+ /** Shut the browser down but stay usable — the next acquire starts cold. */
2297
+ async evict() {
2298
+ await this.serialize(async () => {
2299
+ if (this.inUse || this.closed || this.holds > 0) return;
2300
+ const tool = this.tool;
2301
+ this.tool = null;
2302
+ if (tool) await tool.close();
2303
+ });
2304
+ }
2305
+ serialize(work) {
2306
+ const next = this.pending.then(work, work);
2307
+ this.pending = next.then(() => void 0, () => void 0);
2308
+ return next;
2309
+ }
2310
+ };
2311
+ //#endregion
2312
+ //#region src/engine/WatchSession.ts
2313
+ /**
2314
+ * Directories no watch should ever descend into.
2315
+ *
2316
+ * `outputDir` is not here because it is not a fixed name — the engine passes it
2317
+ * in. Missing it would be fatal rather than merely noisy: a capture writes PNGs
2318
+ * into it, every write is a change, and the session would trigger itself
2319
+ * forever.
2320
+ */
2321
+ const DEFAULT_IGNORED_DIRS = /* @__PURE__ */ new Set([
2322
+ ".git",
2323
+ ".cache",
2324
+ ".next",
2325
+ ".nuxt",
2326
+ ".output",
2327
+ ".parcel-cache",
2328
+ ".svelte-kit",
2329
+ ".turbo",
2330
+ ".vercel",
2331
+ "build",
2332
+ "coverage",
2333
+ "dist",
2334
+ "node_modules",
2335
+ "storybook-static"
2336
+ ]);
2337
+ /** Watch-mode defaults, exported so the CLI and docs can quote one source. */
2338
+ const DEFAULT_DEBOUNCE_MS = 300;
2339
+ const DEFAULT_MAX_TASKS = 200;
2340
+ /** How long `start()` waits for the initial filesystem scan before giving up on it. */
2341
+ const READY_TIMEOUT_MS = 1e4;
2342
+ /**
2343
+ * chokidar, loaded on first use.
2344
+ *
2345
+ * Imported lazily so that requiring `@cappa/core` — which the CLI does for
2346
+ * every command, and a plugin does just to get types — never starts a file
2347
+ * watcher's dependency tree for a process that will not watch anything.
2348
+ */
2349
+ const defaultCreateWatcher = async (roots, options) => {
2350
+ const { watch } = await import("chokidar");
2351
+ return watch(roots, {
2352
+ cwd: options.cwd,
2353
+ ignoreInitial: true,
2354
+ ignored: (candidate) => options.ignored(candidate)
2355
+ });
2356
+ };
2357
+ /**
2358
+ * Re-captures affected tasks when files change.
2359
+ *
2360
+ * A scheduler for runs, deliberately not a second orchestrator: every iteration
2361
+ * goes through the engine's ordinary `startRun`, so watch-triggered captures
2362
+ * emit the same events, land in the same run store and honour the same
2363
+ * one-run-at-a-time rule as a capture somebody clicked.
2364
+ *
2365
+ * Two behaviours matter more than they look:
2366
+ *
2367
+ * - **`clearActual` is always false.** Clearing on every save would delete the
2368
+ * diffs the user is looking at for tasks they did not touch.
2369
+ * - **Changes during a run are queued, never rejected.** The engine's single-run
2370
+ * rule stays intact, and the user gets the run they expect rather than a
2371
+ * conflict error they did not cause.
2372
+ */
2373
+ var WatchSession = class {
2374
+ options;
2375
+ cwd;
2376
+ roots;
2377
+ ignoredRoots;
2378
+ debounceMs;
2379
+ maxTasks;
2380
+ now;
2381
+ watcher = null;
2382
+ pending = /* @__PURE__ */ new Set();
2383
+ timer = null;
2384
+ draining = false;
2385
+ stopped = false;
2386
+ startedAt;
2387
+ lastChange;
2388
+ constructor(options) {
2389
+ this.options = options;
2390
+ this.cwd = options.cwd ?? process.cwd();
2391
+ this.debounceMs = options.debounceMs ?? 300;
2392
+ this.maxTasks = options.maxTasks ?? 200;
2393
+ this.now = options.now ?? (() => Date.now());
2394
+ this.roots = resolveRoots(options.paths, options.plugins);
2395
+ this.ignoredRoots = (options.ignoredPaths ?? []).map((entry) => node_path.default.resolve(this.cwd, entry));
2396
+ }
2397
+ /** Begin watching. Resolves once the initial scan has settled. */
2398
+ async start() {
2399
+ if (this.watcher) return this.getStatus();
2400
+ const watcher = await (this.options.createWatcher ?? defaultCreateWatcher)(this.roots, {
2401
+ cwd: this.cwd,
2402
+ ignored: (candidate) => this.isIgnored(candidate)
2403
+ });
2404
+ if (this.stopped) {
2405
+ await watcher.close();
2406
+ return this.getStatus();
2407
+ }
2408
+ this.watcher = watcher;
2409
+ watcher.on("all", (event, changedPath) => {
2410
+ if (event !== "add" && event !== "change" && event !== "unlink") return;
2411
+ this.onFileChanged(changedPath);
2412
+ });
2413
+ watcher.on("error", () => {});
2414
+ await this.waitForReady(watcher);
2415
+ this.startedAt = this.now();
2416
+ this.emit({
2417
+ type: "watch:start",
2418
+ paths: this.roots,
2419
+ filter: this.options.filter,
2420
+ debounceMs: this.debounceMs
2421
+ });
2422
+ return this.getStatus();
2423
+ }
2424
+ /**
2425
+ * Stop watching.
2426
+ *
2427
+ * Deliberately does not cancel a run already in flight: that run is the
2428
+ * answer to a save the user made, and killing it half-way leaves `actual/`
2429
+ * holding a partial capture.
2430
+ */
2431
+ async stop(reason = "requested") {
2432
+ if (this.stopped) return;
2433
+ this.stopped = true;
2434
+ if (this.timer) {
2435
+ clearTimeout(this.timer);
2436
+ this.timer = null;
2437
+ }
2438
+ this.pending.clear();
2439
+ const watcher = this.watcher;
2440
+ this.watcher = null;
2441
+ try {
2442
+ await watcher?.close();
2443
+ } finally {
2444
+ this.emit({
2445
+ type: "watch:stop",
2446
+ reason
2447
+ });
2448
+ }
2449
+ }
2450
+ getStatus() {
2451
+ return {
2452
+ active: this.watcher !== null && !this.stopped,
2453
+ paths: this.roots,
2454
+ filter: this.options.filter,
2455
+ debounceMs: this.debounceMs,
2456
+ startedAt: this.startedAt,
2457
+ lastChange: this.lastChange
2458
+ };
2459
+ }
2460
+ emit(event) {
2461
+ this.options.emit?.(event);
2462
+ }
2463
+ async waitForReady(watcher) {
2464
+ await new Promise((resolve) => {
2465
+ let settled = false;
2466
+ const finish = () => {
2467
+ if (settled) return;
2468
+ settled = true;
2469
+ clearTimeout(timer);
2470
+ resolve();
2471
+ };
2472
+ const timer = setTimeout(finish, READY_TIMEOUT_MS);
2473
+ timer.unref?.();
2474
+ watcher.on("ready", finish);
2475
+ watcher.on("error", finish);
2476
+ });
2477
+ }
2478
+ onFileChanged(changedPath) {
2479
+ if (this.stopped) return;
2480
+ this.pending.add(toRelative(this.cwd, changedPath));
2481
+ if (this.timer) clearTimeout(this.timer);
2482
+ const timer = setTimeout(() => {
2483
+ this.timer = null;
2484
+ this.drain();
2485
+ }, this.debounceMs);
2486
+ timer.unref?.();
2487
+ this.timer = timer;
2488
+ }
2489
+ /**
2490
+ * Capture for everything pending, one batch at a time.
2491
+ *
2492
+ * The loop re-reads `pending` after each iteration, which is what turns a
2493
+ * save arriving mid-run into the next iteration rather than into a `409`.
2494
+ */
2495
+ async drain() {
2496
+ if (this.draining) return;
2497
+ this.draining = true;
2498
+ try {
2499
+ while (this.pending.size > 0 && !this.stopped) {
2500
+ const files = [...this.pending].sort();
2501
+ this.pending.clear();
2502
+ await this.captureFor(files);
2503
+ }
2504
+ } finally {
2505
+ this.draining = false;
2506
+ }
2507
+ }
2508
+ async captureFor(files) {
2509
+ const resolution = await this.resolveFiles(files);
2510
+ if (resolution.scope === "none") {
2511
+ this.record({
2512
+ files,
2513
+ scope: "none",
2514
+ taskIds: [],
2515
+ at: this.now()
2516
+ });
2517
+ return;
2518
+ }
2519
+ let runId;
2520
+ let error;
2521
+ try {
2522
+ runId = (await this.options.startRun(resolution.request)).id;
2523
+ } catch (cause) {
2524
+ error = cause instanceof Error ? cause.message : String(cause);
2525
+ }
2526
+ this.record({
2527
+ files,
2528
+ scope: resolution.scope,
2529
+ taskIds: resolution.taskIds,
2530
+ runId,
2531
+ error,
2532
+ at: this.now()
2533
+ });
2534
+ if (runId) await this.options.waitForRun(runId);
2535
+ }
2536
+ record(change) {
2537
+ this.lastChange = change;
2538
+ const { at: _at, ...rest } = change;
2539
+ this.emit({
2540
+ type: "watch:change",
2541
+ ...rest
2542
+ });
2543
+ }
2544
+ /**
2545
+ * Ask every plugin what the changed files affect, and turn the answers into
2546
+ * one run request.
2547
+ */
2548
+ async resolveFiles(files) {
2549
+ const trigger = {
2550
+ source: "watch",
2551
+ files
2552
+ };
2553
+ const everything = {
2554
+ scope: "all",
2555
+ request: {
2556
+ filter: this.options.filter,
2557
+ clearActual: false,
2558
+ trigger
2559
+ }
2560
+ };
2561
+ let tasksByPlugin;
2562
+ try {
2563
+ tasksByPlugin = await this.options.discover();
2564
+ } catch {
2565
+ return everything;
2566
+ }
2567
+ const fullPlugins = /* @__PURE__ */ new Set();
2568
+ const taskIds = /* @__PURE__ */ new Set();
2569
+ for (const plugin of this.options.plugins) {
2570
+ const tasks = tasksByPlugin.get(plugin.name) ?? [];
2571
+ if (!plugin.watch) {
2572
+ fullPlugins.add(plugin.name);
2573
+ continue;
2574
+ }
2575
+ for (const file of files) {
2576
+ let resolved;
2577
+ try {
2578
+ resolved = plugin.watch.resolve(file, tasks);
2579
+ } catch {
2580
+ resolved = null;
2581
+ }
2582
+ if (resolved === null) {
2583
+ fullPlugins.add(plugin.name);
2584
+ break;
2585
+ }
2586
+ for (const id of resolved) taskIds.add(id);
2587
+ }
2588
+ }
2589
+ if (fullPlugins.size === 0) {
2590
+ if (taskIds.size === 0) return {
2591
+ scope: "none",
2592
+ request: {}
2593
+ };
2594
+ return this.byTaskIds([...taskIds], trigger, everything);
2595
+ }
2596
+ if (taskIds.size === 0) return {
2597
+ scope: "plugins",
2598
+ request: {
2599
+ plugins: [...fullPlugins],
2600
+ filter: this.options.filter,
2601
+ clearActual: false,
2602
+ trigger
2603
+ }
2604
+ };
2605
+ const expanded = new Set(taskIds);
2606
+ for (const name of fullPlugins) for (const task of tasksByPlugin.get(name) ?? []) expanded.add(task.id);
2607
+ return this.byTaskIds([...expanded], trigger, everything);
2608
+ }
2609
+ /**
2610
+ * A run of explicit ids, unless there are so many that naming them is
2611
+ * pointless — a branch switch or a formatter pass resolves half the project,
2612
+ * and a filtered full run is both cheaper to express and easier to read.
2613
+ */
2614
+ byTaskIds(taskIds, trigger, everything) {
2615
+ if (taskIds.length > this.maxTasks) return everything;
2616
+ return {
2617
+ scope: "tasks",
2618
+ taskIds,
2619
+ request: {
2620
+ taskIds,
2621
+ filter: this.options.filter,
2622
+ clearActual: false,
2623
+ trigger
2624
+ }
2625
+ };
2626
+ }
2627
+ isIgnored(candidate) {
2628
+ const absolute = node_path.default.resolve(this.cwd, candidate);
2629
+ const relative = node_path.default.relative(this.cwd, absolute);
2630
+ if (relative.startsWith("..") || node_path.default.isAbsolute(relative)) return true;
2631
+ for (const ignored of this.ignoredRoots) if (absolute === ignored || absolute.startsWith(`${ignored}${node_path.default.sep}`)) return true;
2632
+ return relative.split(node_path.default.sep).some((segment) => DEFAULT_IGNORED_DIRS.has(segment));
2633
+ }
2634
+ };
2635
+ /** The part of a glob before its first magic character — the directory to watch. */
2636
+ const globRoot = (pattern) => {
2637
+ const segments = pattern.split("/");
2638
+ const staticSegments = [];
2639
+ for (const segment of segments) {
2640
+ if (/[*?[\]{}!+@(]/.test(segment)) break;
2641
+ staticSegments.push(segment);
2642
+ }
2643
+ const root = staticSegments.join("/");
2644
+ return root === "" ? "." : root;
2645
+ };
2646
+ /**
2647
+ * What to hand the watcher.
2648
+ *
2649
+ * The project root by default, plus the roots of whatever globs the plugins
2650
+ * declared. Plugin globs can only widen the set: a plugin that maps story files
2651
+ * precisely still has to be told about the component those stories render, and
2652
+ * that component is not in its globs.
2653
+ */
2654
+ const resolveRoots = (paths, plugins) => {
2655
+ const roots = new Set(paths && paths.length > 0 ? paths : ["."]);
2656
+ for (const plugin of plugins) for (const pattern of plugin.watch?.paths ?? []) roots.add(globRoot(pattern));
2657
+ if (roots.has(".")) return ["."];
2658
+ return [...roots];
2659
+ };
2660
+ const toRelative = (cwd, changedPath) => {
2661
+ if (!node_path.default.isAbsolute(changedPath)) return changedPath.split(node_path.default.sep).join("/");
2662
+ return node_path.default.relative(cwd, changedPath).split(node_path.default.sep).join("/");
2663
+ };
2664
+ //#endregion
2665
+ //#region src/engine/LocalEngine.ts
2666
+ /**
2667
+ * `CaptureEngine` backed by an in-process Playwright browser.
2668
+ *
2669
+ * Holds the config's live plugin objects, so it must live in the process that
2670
+ * loaded `cappa.config.ts`. The server takes one of these by injection rather
2671
+ * than building it, which is what keeps `@cappa/server` free of config loading
2672
+ * and makes a remote engine a drop-in alternative.
2673
+ *
2674
+ * One run at a time. Queuing is deliberately not implemented: the browser pool
2675
+ * is the real constraint, and a second concurrent run would fight it.
2676
+ */
2677
+ var LocalEngine = class {
2678
+ options;
2679
+ plugins;
2680
+ fileSystem;
2681
+ browser;
2682
+ runs;
2683
+ /**
2684
+ * Set synchronously the moment a run is claimed, before any `await`, so two
2685
+ * concurrent `startRun` calls cannot both pass the check and then fight over
2686
+ * the browser. Covers the window between claiming and the run finishing.
2687
+ */
2688
+ busy = false;
2689
+ activeRunId = null;
2690
+ targetsCache = null;
2691
+ /**
2692
+ * The tasks behind `targetsCache`, kept whole.
2693
+ *
2694
+ * A `Target` is what crosses the wire; a plugin's `watch.resolve` needs the
2695
+ * task it came from, `data` included — that is where a story's `importPath`
2696
+ * lives. Same discovery, two shapes, one cache lifetime.
2697
+ */
2698
+ taskCache = null;
2699
+ closed = false;
2700
+ watchSession = null;
2701
+ releaseBrowserHold = null;
2702
+ watchListeners = /* @__PURE__ */ new Set();
2703
+ watchEvents = [];
2704
+ watchSeq = 0;
2705
+ constructor(options) {
2706
+ this.options = options;
2707
+ this.plugins = options.plugins;
2708
+ this.fileSystem = new ScreenshotFileSystem(options.outputDir);
2709
+ this.runs = new RunStore(options.runStore);
2710
+ this.browser = new WarmBrowser({
2711
+ create: options.createScreenshotTool ?? (() => this.buildTool()),
2712
+ idleTimeoutMs: options.browserIdleTimeoutMs
2713
+ });
2714
+ }
2715
+ buildTool() {
2716
+ return new ScreenshotTool({
2717
+ outputDir: this.options.outputDir,
2718
+ diff: this.options.diff,
2719
+ retries: this.options.retries,
2720
+ concurrency: this.options.concurrency,
2721
+ logConsoleEvents: this.options.logConsoleEvents,
2722
+ fullPage: this.options.fullPage ?? true,
2723
+ viewport: this.options.viewport ?? {
2724
+ width: 1920,
2725
+ height: 1080
2726
+ },
2727
+ connectionTimeout: this.options.connectionTimeout
2728
+ });
2729
+ }
2730
+ async listPlugins() {
2731
+ return this.plugins.map((plugin) => ({
2732
+ name: plugin.name,
2733
+ description: plugin.description
2734
+ }));
2735
+ }
2736
+ /**
2737
+ * Discovery needs a browser (plugins query the app under test through it), so
2738
+ * this warms the browser on a cache miss.
2739
+ *
2740
+ * While a run holds the browser, only the cache can be served: discovering
2741
+ * would recycle the very contexts the run is capturing with.
2742
+ */
2743
+ async listTargets(options = {}) {
2744
+ this.assertOpen();
2745
+ if (this.targetsCache && !options.refresh) return this.targetsCache;
2746
+ if (this.busy) {
2747
+ if (this.targetsCache) return this.targetsCache;
2748
+ throw new RunInProgressError(this.activeRunId ?? "starting");
2749
+ }
2750
+ return this.discoverTargets();
2751
+ }
2752
+ async startRun(request = {}) {
2753
+ this.assertOpen();
2754
+ if (this.busy) throw new RunInProgressError(this.activeRunId ?? "starting");
2755
+ this.busy = true;
2756
+ try {
2757
+ await this.validateTaskIds(request);
2758
+ const runner = new CaptureRunner({
2759
+ screenshotTool: await this.browser.acquire(),
2760
+ plugins: this.plugins,
2761
+ outputDir: this.options.outputDir,
2762
+ fileSystem: this.fileSystem
2763
+ });
2764
+ const finish = () => {
2765
+ if (this.activeRunId !== runner.id) return;
2766
+ this.targetsCache = null;
2767
+ this.taskCache = null;
2768
+ this.runs.finalize(runner.id);
2769
+ this.activeRunId = null;
2770
+ this.busy = false;
2771
+ this.browser.release();
2772
+ };
2773
+ runner.on((event) => {
2774
+ if (event.type === "run:complete" || event.type === "run:error") finish();
2775
+ });
2776
+ this.runs.add(runner);
2777
+ this.activeRunId = runner.id;
2778
+ runner.run(request).catch(() => {}).finally(finish);
2779
+ return runner.getSummary();
2780
+ } catch (error) {
2781
+ this.busy = false;
2782
+ this.activeRunId = null;
2783
+ throw error;
2784
+ }
2785
+ }
2786
+ async getRun(id) {
2787
+ return this.runs.get(id);
2788
+ }
2789
+ async listRuns() {
2790
+ return this.runs.list();
2791
+ }
2792
+ async cancelRun(id) {
2793
+ this.runs.getRunner(id)?.abort();
2794
+ }
2795
+ subscribeRun(id, onEvent, options = {}) {
2796
+ return this.runs.subscribe(id, onEvent, options);
2797
+ }
2798
+ /**
2799
+ * Read the screenshot index from disk.
2800
+ *
2801
+ * Always a fresh read rather than a cached snapshot — anything can write to
2802
+ * `outputDir` while the server is up, including a CLI run in another terminal.
2803
+ */
2804
+ async listScreenshots(query = {}) {
2805
+ let screenshots = await collectScreenshots(this.options.outputDir);
2806
+ if (query.category) screenshots = screenshots.filter((screenshot) => screenshot.category === query.category);
2807
+ if (query.search) {
2808
+ const term = query.search.toLowerCase();
2809
+ screenshots = screenshots.filter((screenshot) => screenshot.name.toLowerCase().includes(term));
2810
+ }
2811
+ return screenshots;
2812
+ }
2813
+ async approve(names) {
2814
+ const screenshots = await this.listScreenshots();
2815
+ const approved = [];
2816
+ const errors = [];
2817
+ for (const name of names) {
2818
+ const screenshot = screenshots.find((entry) => entry.name === name);
2819
+ if (!screenshot) {
2820
+ errors.push({
2821
+ name,
2822
+ error: "Screenshot not found"
2823
+ });
2824
+ continue;
2825
+ }
2826
+ try {
2827
+ await this.fileSystem.approveScreenshots([screenshot], this.options.diff ?? { type: "pixel" });
2828
+ approved.push(name);
2829
+ } catch (error) {
2830
+ errors.push({
2831
+ name,
2832
+ error: error instanceof Error ? error.message : "Approval failed"
2833
+ });
2834
+ }
2835
+ }
2836
+ return {
2837
+ approved,
2838
+ errors
2839
+ };
2840
+ }
2841
+ /**
2842
+ * Re-capture affected tasks on file change until `stopWatch`.
2843
+ *
2844
+ * Every iteration goes through `startRun`, so a watch-triggered capture is an
2845
+ * ordinary run: same events, same run store, same single-run rule, visible in
2846
+ * `listRuns` and in the UI. Watch is a scheduler, not a second orchestrator.
2847
+ */
2848
+ async startWatch(request = {}) {
2849
+ this.assertOpen();
2850
+ if (this.watchSession) throw new WatchInProgressError();
2851
+ const release = this.browser.hold();
2852
+ const session = new WatchSession({
2853
+ plugins: this.plugins,
2854
+ cwd: this.options.cwd,
2855
+ paths: request.paths,
2856
+ ignoredPaths: [this.options.outputDir],
2857
+ filter: request.filter,
2858
+ debounceMs: request.debounceMs,
2859
+ maxTasks: request.maxTasks,
2860
+ createWatcher: this.options.createWatcher,
2861
+ discover: () => this.discoverTasks(),
2862
+ startRun: (runRequest) => this.startRun(runRequest),
2863
+ waitForRun: (runId) => this.waitForRun(runId),
2864
+ emit: (event) => this.emitWatchEvent(event)
2865
+ });
2866
+ this.watchSession = session;
2867
+ this.releaseBrowserHold = release;
2868
+ try {
2869
+ return await session.start();
2870
+ } catch (error) {
2871
+ this.watchSession = null;
2872
+ this.releaseBrowserHold = null;
2873
+ release();
2874
+ throw error;
2875
+ }
2876
+ }
2877
+ async stopWatch() {
2878
+ await this.endWatch("requested");
2879
+ return this.getWatchStatus();
2880
+ }
2881
+ async getWatchStatus() {
2882
+ return this.watchSession?.getStatus() ?? {
2883
+ active: false,
2884
+ paths: [],
2885
+ debounceMs: 300
2886
+ };
2887
+ }
2888
+ subscribeWatch(onEvent, options = {}) {
2889
+ const sinceSeq = options.sinceSeq ?? 0;
2890
+ for (const event of this.watchEvents) if (event.seq > sinceSeq) onEvent(event);
2891
+ this.watchListeners.add(onEvent);
2892
+ return () => {
2893
+ this.watchListeners.delete(onEvent);
2894
+ };
2895
+ }
2896
+ async close() {
2897
+ this.closed = true;
2898
+ await this.endWatch("engine-closed");
2899
+ (this.activeRunId ? this.runs.getRunner(this.activeRunId) : void 0)?.abort();
2900
+ await this.browser.close();
2901
+ }
2902
+ async endWatch(reason) {
2903
+ const session = this.watchSession;
2904
+ const release = this.releaseBrowserHold;
2905
+ this.watchSession = null;
2906
+ this.releaseBrowserHold = null;
2907
+ try {
2908
+ await session?.stop(reason);
2909
+ } finally {
2910
+ release?.();
2911
+ }
2912
+ }
2913
+ emitWatchEvent(event) {
2914
+ this.watchSeq += 1;
2915
+ const full = {
2916
+ ...event,
2917
+ seq: this.watchSeq,
2918
+ at: Date.now()
2919
+ };
2920
+ this.watchEvents.push(full);
2921
+ const max = this.options.maxWatchEvents ?? 200;
2922
+ if (this.watchEvents.length > max) this.watchEvents = this.watchEvents.slice(-max);
2923
+ for (const listener of this.watchListeners) try {
2924
+ listener(full);
2925
+ } catch {}
2926
+ }
2927
+ /** Resolve once a run reaches a terminal event. */
2928
+ waitForRun(id) {
2929
+ return new Promise((resolve) => {
2930
+ let unsubscribe;
2931
+ let finished = false;
2932
+ const finish = () => {
2933
+ if (finished) return;
2934
+ finished = true;
2935
+ unsubscribe?.();
2936
+ resolve();
2937
+ };
2938
+ unsubscribe = this.runs.subscribe(id, (event) => {
2939
+ if (event.type === "run:complete" || event.type === "run:error") finish();
2940
+ });
2941
+ if (finished) unsubscribe();
2942
+ });
2943
+ }
2944
+ /** True while a browser process is alive. Exposed for tests and diagnostics. */
2945
+ get isWarm() {
2946
+ return this.browser.isWarm;
2947
+ }
2948
+ assertOpen() {
2949
+ if (this.closed) throw new Error("Engine has been closed");
2950
+ }
2951
+ /**
2952
+ * A client may only ask for tasks that discovery produced.
2953
+ *
2954
+ * This is a security boundary as much as a correctness one: it is what stops
2955
+ * a request from steering the browser to an arbitrary URL.
2956
+ */
2957
+ async validateTaskIds(request) {
2958
+ if (!request.taskIds || request.taskIds.length === 0) return;
2959
+ const targets = this.targetsCache ?? await this.discoverTargets();
2960
+ const known = new Set(targets.map((target) => target.id));
2961
+ const unknown = request.taskIds.filter((id) => !known.has(id));
2962
+ if (unknown.length > 0) throw new UnknownTargetsError(unknown);
2963
+ }
2964
+ /** Discovered tasks per plugin, whole. Cached with `targetsCache`. */
2965
+ async discoverTasks() {
2966
+ if (this.taskCache) return this.taskCache;
2967
+ await this.discoverTargets();
2968
+ return this.taskCache ?? /* @__PURE__ */ new Map();
2969
+ }
2970
+ async discoverTargets() {
2971
+ const tool = await this.browser.acquire();
2972
+ try {
2973
+ const discovered = await Promise.all(this.plugins.map(async (plugin) => {
2974
+ const tasks = await plugin.discover(tool);
2975
+ return {
2976
+ plugin: plugin.name,
2977
+ tasks
2978
+ };
2979
+ }));
2980
+ this.taskCache = new Map(discovered.map(({ plugin, tasks }) => [plugin, tasks]));
2981
+ this.targetsCache = discovered.flatMap(({ plugin, tasks }) => tasks.map((task) => ({
2982
+ id: task.id,
2983
+ url: task.url,
2984
+ plugin
2985
+ })));
2986
+ return this.targetsCache;
2987
+ } finally {
2988
+ this.browser.release();
2989
+ }
2990
+ }
2991
+ };
2992
+ //#endregion
2993
+ //#region src/store.ts
2994
+ /**
2995
+ * `ScreenshotStore` over the local filesystem, delegating to
2996
+ * `ScreenshotFileSystem` so both views stay consistent.
2997
+ */
2998
+ var FsScreenshotStore = class {
2999
+ fs;
3000
+ constructor(outputDirOrFs) {
3001
+ this.fs = typeof outputDirOrFs === "string" ? new ScreenshotFileSystem(outputDirOrFs) : outputDirOrFs;
3002
+ }
3003
+ dirFor(bucket) {
3004
+ if (bucket === "actual") return this.fs.getActualDir();
3005
+ if (bucket === "expected") return this.fs.getExpectedDir();
3006
+ return this.fs.getDiffDir();
3007
+ }
3008
+ pathFor(bucket, key) {
3009
+ if (bucket === "actual") return this.fs.getActualFilePath(key);
3010
+ if (bucket === "expected") return this.fs.getExpectedFilePath(key);
3011
+ return this.fs.getDiffFilePath(key);
3012
+ }
3013
+ async has(bucket, key) {
3014
+ if (bucket === "expected") return this.fs.hasExpectedFile(key);
3015
+ const fsp = await import("node:fs/promises");
3016
+ try {
3017
+ await fsp.access(this.pathFor(bucket, key));
3018
+ return true;
3019
+ } catch {
3020
+ return false;
3021
+ }
3022
+ }
3023
+ async read(bucket, key) {
3024
+ if (bucket === "expected") return this.fs.readExpectedFile(key);
3025
+ return (await import("node:fs/promises")).readFile(this.pathFor(bucket, key));
3026
+ }
3027
+ async write(bucket, key, data) {
3028
+ if (bucket === "actual") {
3029
+ await this.fs.writeActualFile(key, data);
3030
+ return;
3031
+ }
3032
+ if (bucket === "diff") {
3033
+ await this.fs.writeDiffFile(key, data);
3034
+ return;
3035
+ }
3036
+ const filePath = this.pathFor(bucket, key);
3037
+ await this.fs.ensureParentDir(filePath);
3038
+ await (await import("node:fs/promises")).writeFile(filePath, data);
3039
+ }
3040
+ async list(bucket) {
3041
+ const files = bucket === "actual" ? await this.fs.getActualScreenshots() : bucket === "expected" ? await this.fs.getExpectedScreenshots() : await this.fs.getDiffScreenshots();
3042
+ const dir = this.dirFor(bucket);
3043
+ return files.map((file) => node_path.default.relative(dir, file));
3044
+ }
3045
+ async remove(bucket, key) {
3046
+ await (await import("node:fs/promises")).rm(this.pathFor(bucket, key), { force: true });
3047
+ }
3048
+ async clear(bucket) {
3049
+ if (bucket === "actual") {
3050
+ this.fs.clearActual();
3051
+ return;
3052
+ }
3053
+ if (bucket === "diff") {
3054
+ this.fs.clearDiff();
3055
+ return;
3056
+ }
3057
+ throw new Error("Refusing to clear the expected/ bucket: it holds the approved baselines");
3058
+ }
3059
+ async readMeta(key) {
3060
+ const { readDiffMeta } = await Promise.resolve().then(() => filesystem_exports);
3061
+ return readDiffMeta(this.fs.getDiffFilePath(key));
3062
+ }
3063
+ async writeMeta(key, meta) {
3064
+ await this.fs.writeDiffMetaFile(key, meta);
3065
+ }
3066
+ };
3067
+ //#endregion
3068
+ exports.CaptureRunner = CaptureRunner;
3069
+ exports.DEFAULT_DEBOUNCE_MS = DEFAULT_DEBOUNCE_MS;
3070
+ exports.DEFAULT_IGNORED_DIRS = DEFAULT_IGNORED_DIRS;
3071
+ exports.DEFAULT_MAX_TASKS = DEFAULT_MAX_TASKS;
3072
+ exports.ENGINE_ERROR_CODES = ENGINE_ERROR_CODES;
3073
+ exports.FsScreenshotStore = FsScreenshotStore;
3074
+ exports.LocalEngine = LocalEngine;
3075
+ exports.MANIFEST_FILENAME = MANIFEST_FILENAME;
3076
+ exports.MANIFEST_VERSION = MANIFEST_VERSION;
3077
+ exports.RunInProgressError = RunInProgressError;
3078
+ exports.RunStore = RunStore;
1281
3079
  exports.ScreenshotFileSystem = ScreenshotFileSystem;
1282
3080
  exports.ScreenshotTool = ScreenshotTool;
3081
+ exports.UnknownTargetsError = UnknownTargetsError;
3082
+ exports.WarmBrowser = WarmBrowser;
3083
+ exports.WatchInProgressError = WatchInProgressError;
3084
+ exports.WatchSession = WatchSession;
3085
+ exports.collectScreenshots = collectScreenshots;
1283
3086
  exports.compareImages = compareImages;
1284
3087
  exports.compareImagesGMSD = compareImagesGMSD;
1285
3088
  exports.defineConfig = defineConfig;
3089
+ exports.didScreenshotFail = didScreenshotFail;
3090
+ exports.filterTasks = filterTasks;
3091
+ exports.getDeletedScreenshots = getDeletedScreenshots;
3092
+ exports.groupScreenshots = groupScreenshots;
1286
3093
  exports.imagesMatch = imagesMatch;
1287
3094
  exports.imagesMatchGMSD = imagesMatchGMSD;
3095
+ exports.isRunInProgressError = isRunInProgressError;
3096
+ exports.isUnknownTargetsError = isUnknownTargetsError;
3097
+ exports.isWatchInProgressError = isWatchInProgressError;
1288
3098
  exports.mapWithConcurrency = mapWithConcurrency;
3099
+ exports.mergeCaptureManifest = mergeCaptureManifest;
3100
+ exports.readCaptureManifest = readCaptureManifest;
1289
3101
  exports.readDiffMeta = readDiffMeta;
3102
+ exports.recordCaptureOrigins = recordCaptureOrigins;
3103
+ exports.selectTasks = selectTasks;
1290
3104
  exports.toDiffMetaPath = toDiffMetaPath;
3105
+ exports.toManifestKey = toManifestKey;
3106
+ exports.toSerializedError = toSerializedError;
3107
+ exports.toTaskStatus = toTaskStatus;
1291
3108
 
1292
3109
  //# sourceMappingURL=index.cjs.map