@cappa/cli 0.11.1 → 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 +670 -380
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -2
- package/dist/index.d.mts +1 -2
- package/dist/index.mjs +665 -375
- package/dist/index.mjs.map +1 -1
- package/package.json +13 -12
package/dist/index.cjs
CHANGED
|
@@ -16,191 +16,32 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
16
16
|
}
|
|
17
17
|
return to;
|
|
18
18
|
};
|
|
19
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
20
20
|
value: mod,
|
|
21
21
|
enumerable: true
|
|
22
22
|
}) : target, mod));
|
|
23
23
|
//#endregion
|
|
24
24
|
let _cappa_logger = require("@cappa/logger");
|
|
25
25
|
let commander = require("commander");
|
|
26
|
+
let _cappa_config = require("@cappa/config");
|
|
26
27
|
let _cappa_core = require("@cappa/core");
|
|
27
|
-
let node_fs = require("node:fs");
|
|
28
|
-
node_fs = __toESM(node_fs);
|
|
29
28
|
let node_path = require("node:path");
|
|
30
29
|
node_path = __toESM(node_path);
|
|
31
|
-
let jiti = require("jiti");
|
|
32
|
-
let node_crypto = require("node:crypto");
|
|
33
|
-
let node_fs_promises = require("node:fs/promises");
|
|
34
30
|
let chalk = require("chalk");
|
|
35
31
|
chalk = __toESM(chalk);
|
|
32
|
+
let zod = require("zod");
|
|
33
|
+
let _cappa_client = require("@cappa/client");
|
|
36
34
|
let _cappa_server = require("@cappa/server");
|
|
35
|
+
let node_fs = require("node:fs");
|
|
36
|
+
node_fs = __toESM(node_fs);
|
|
37
|
+
let node_crypto = require("node:crypto");
|
|
37
38
|
//#region package.json
|
|
38
|
-
var version = "0.
|
|
39
|
-
//#endregion
|
|
40
|
-
//#region src/features/config/getPlugins.ts
|
|
41
|
-
async function getPlugins(plugins) {
|
|
42
|
-
if (!plugins) return [];
|
|
43
|
-
const loadedPlugins = [];
|
|
44
|
-
for (const plugin of plugins) if (typeof plugin === "function") {
|
|
45
|
-
const pluginDef = plugin();
|
|
46
|
-
loadedPlugins.push(pluginDef);
|
|
47
|
-
} else loadedPlugins.push(plugin);
|
|
48
|
-
return loadedPlugins;
|
|
49
|
-
}
|
|
50
|
-
function isPromise(value) {
|
|
51
|
-
return value !== null && typeof value === "object" && "then" in value && typeof value.then === "function";
|
|
52
|
-
}
|
|
53
|
-
//#endregion
|
|
54
|
-
//#region src/features/config/loadConfig.ts
|
|
55
|
-
const tsLoader = async (configFile) => {
|
|
56
|
-
return await (0, jiti.createJiti)(require("url").pathToFileURL(__filename).href, {
|
|
57
|
-
jsx: {
|
|
58
|
-
runtime: "automatic",
|
|
59
|
-
importSource: "@cappa/core"
|
|
60
|
-
},
|
|
61
|
-
sourceMaps: true
|
|
62
|
-
}).import(configFile, { default: true });
|
|
63
|
-
};
|
|
64
|
-
async function loadConfig() {
|
|
65
|
-
const configPath = node_path.default.resolve(process.cwd(), "cappa.config.ts");
|
|
66
|
-
if (!node_fs.default.existsSync(configPath)) throw new Error("Config not found. Please create a cappa.config.ts file in the current directory.");
|
|
67
|
-
try {
|
|
68
|
-
const config = await tsLoader(configPath);
|
|
69
|
-
if (!config) throw new Error("Config file is empty or does not export a valid configuration.");
|
|
70
|
-
return {
|
|
71
|
-
filepath: configPath,
|
|
72
|
-
config
|
|
73
|
-
};
|
|
74
|
-
} catch (error) {
|
|
75
|
-
throw new Error(`Failed to load config from ${configPath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
//#endregion
|
|
79
|
-
//#region src/features/config/getConfig.ts
|
|
80
|
-
/**
|
|
81
|
-
* Converting UserConfig to Config without a change in the object beside the JSON convert.
|
|
82
|
-
*/
|
|
83
|
-
async function getConfig(loadResult) {
|
|
84
|
-
const configData = (loadResult ?? await loadConfig())?.config;
|
|
85
|
-
let cappaUserConfig = Promise.resolve(configData);
|
|
86
|
-
const configEnv = {
|
|
87
|
-
command: process.argv[2],
|
|
88
|
-
mode: process.env.NODE_ENV || "development",
|
|
89
|
-
env: process.env
|
|
90
|
-
};
|
|
91
|
-
if (typeof configData === "function") {
|
|
92
|
-
const possiblePromise = configData(configEnv);
|
|
93
|
-
if (isPromise(possiblePromise)) cappaUserConfig = possiblePromise;
|
|
94
|
-
else cappaUserConfig = Promise.resolve(possiblePromise);
|
|
95
|
-
}
|
|
96
|
-
const userConfig = await cappaUserConfig;
|
|
97
|
-
if (!userConfig || typeof userConfig === "function") throw new Error("Invalid configuration: no valid config found");
|
|
98
|
-
const diffConfig = (() => {
|
|
99
|
-
if (userConfig.diff?.type !== "gmsd") return {
|
|
100
|
-
type: "pixel",
|
|
101
|
-
threshold: userConfig.diff?.threshold ?? .1,
|
|
102
|
-
includeAA: userConfig.diff?.includeAA ?? false,
|
|
103
|
-
fastBufferCheck: userConfig.diff?.fastBufferCheck ?? true,
|
|
104
|
-
maxDiffPixels: userConfig.diff?.maxDiffPixels ?? 0,
|
|
105
|
-
maxDiffPercentage: userConfig.diff?.maxDiffPercentage ?? 0,
|
|
106
|
-
interpret: userConfig.diff?.interpret ?? false
|
|
107
|
-
};
|
|
108
|
-
return {
|
|
109
|
-
type: "gmsd",
|
|
110
|
-
threshold: userConfig.diff.threshold ?? .1,
|
|
111
|
-
downsample: userConfig.diff.downsample ?? 0,
|
|
112
|
-
c: userConfig.diff.c ?? 170
|
|
113
|
-
};
|
|
114
|
-
})();
|
|
115
|
-
const configWithDefaults = {
|
|
116
|
-
outputDir: userConfig.outputDir || "./screenshots",
|
|
117
|
-
retries: userConfig.retries || 2,
|
|
118
|
-
concurrency: userConfig.concurrency || 1,
|
|
119
|
-
logConsoleEvents: userConfig.logConsoleEvents ?? true,
|
|
120
|
-
diff: diffConfig,
|
|
121
|
-
plugins: userConfig.plugins ? await getPlugins(userConfig.plugins) : [],
|
|
122
|
-
onFail: userConfig.onFail,
|
|
123
|
-
screenshot: {
|
|
124
|
-
fullPage: userConfig.screenshot?.fullPage ?? true,
|
|
125
|
-
viewport: userConfig.screenshot?.viewport ?? {
|
|
126
|
-
width: 1920,
|
|
127
|
-
height: 1080
|
|
128
|
-
}
|
|
129
|
-
},
|
|
130
|
-
review: {
|
|
131
|
-
theme: userConfig.review?.theme ?? "light",
|
|
132
|
-
port: userConfig.review?.port ?? 3e3
|
|
133
|
-
},
|
|
134
|
-
connectionTimeout: userConfig.connectionTimeout ?? 2e4
|
|
135
|
-
};
|
|
136
|
-
(0, _cappa_logger.getLogger)().debug("Configuration loaded:", JSON.stringify(configWithDefaults, null, 2));
|
|
137
|
-
return configWithDefaults;
|
|
138
|
-
}
|
|
139
|
-
//#endregion
|
|
140
|
-
//#region src/utils/groupScreenshots.ts
|
|
141
|
-
const groupScreenshots = async (actualScreenshots, expectedScreenshots, diffScreenshots, outputDir) => {
|
|
142
|
-
const screenshotRepresentations = [];
|
|
143
|
-
const expectedByRelativePath = /* @__PURE__ */ new Map();
|
|
144
|
-
for (const screenshot of expectedScreenshots) {
|
|
145
|
-
const relativePath = node_path.default.relative(`${outputDir}/expected`, screenshot);
|
|
146
|
-
expectedByRelativePath.set(relativePath, screenshot);
|
|
147
|
-
}
|
|
148
|
-
const diffByRelativePath = /* @__PURE__ */ new Map();
|
|
149
|
-
for (const screenshot of diffScreenshots) {
|
|
150
|
-
const relativePath = node_path.default.relative(`${outputDir}/diff`, screenshot);
|
|
151
|
-
diffByRelativePath.set(relativePath, screenshot);
|
|
152
|
-
}
|
|
153
|
-
const actualRelativePaths = /* @__PURE__ */ new Set();
|
|
154
|
-
for (const screenshot of actualScreenshots) {
|
|
155
|
-
const relativePath = node_path.default.relative(`${outputDir}/actual`, screenshot);
|
|
156
|
-
actualRelativePaths.add(relativePath);
|
|
157
|
-
const name = relativePath.replace(".png", "");
|
|
158
|
-
const id = (0, node_crypto.createHash)("sha256").update(relativePath).digest("hex");
|
|
159
|
-
const expectedScreenshot = expectedByRelativePath.get(relativePath);
|
|
160
|
-
const diffScreenshot = diffByRelativePath.get(relativePath);
|
|
161
|
-
const diffMeta = diffScreenshot ? await (0, _cappa_core.readDiffMeta)(diffScreenshot) : void 0;
|
|
162
|
-
screenshotRepresentations.push({
|
|
163
|
-
id,
|
|
164
|
-
name,
|
|
165
|
-
category: buildCategory(expectedScreenshot, diffScreenshot),
|
|
166
|
-
expectedPath: expectedScreenshot ? node_path.default.relative(outputDir, expectedScreenshot) : void 0,
|
|
167
|
-
diffPath: diffScreenshot ? node_path.default.relative(outputDir, diffScreenshot) : void 0,
|
|
168
|
-
actualPath: node_path.default.relative(outputDir, screenshot),
|
|
169
|
-
...diffMeta ? { diffMeta } : {}
|
|
170
|
-
});
|
|
171
|
-
}
|
|
172
|
-
for (const expectedScreenshot of expectedScreenshots) {
|
|
173
|
-
const relativePath = node_path.default.relative(`${outputDir}/expected`, expectedScreenshot);
|
|
174
|
-
if (actualRelativePaths.has(relativePath)) continue;
|
|
175
|
-
const name = relativePath.replace(".png", "");
|
|
176
|
-
const id = (0, node_crypto.createHash)("sha256").update(relativePath).digest("hex");
|
|
177
|
-
screenshotRepresentations.push({
|
|
178
|
-
id,
|
|
179
|
-
name,
|
|
180
|
-
category: "deleted",
|
|
181
|
-
expectedPath: node_path.default.relative(outputDir, expectedScreenshot)
|
|
182
|
-
});
|
|
183
|
-
}
|
|
184
|
-
return screenshotRepresentations.sort((a, b) => {
|
|
185
|
-
return CATEGORY_ORDER[a.category] - CATEGORY_ORDER[b.category];
|
|
186
|
-
});
|
|
187
|
-
};
|
|
188
|
-
const buildCategory = (expectedScreenshot, diffScreenshot) => {
|
|
189
|
-
if (expectedScreenshot && diffScreenshot) return "changed";
|
|
190
|
-
if (expectedScreenshot) return "passed";
|
|
191
|
-
return "new";
|
|
192
|
-
};
|
|
193
|
-
const CATEGORY_ORDER = {
|
|
194
|
-
new: 0,
|
|
195
|
-
deleted: 1,
|
|
196
|
-
changed: 2,
|
|
197
|
-
passed: 3
|
|
198
|
-
};
|
|
39
|
+
var version = "0.13.0";
|
|
199
40
|
//#endregion
|
|
200
41
|
//#region src/commands/approve.ts
|
|
201
42
|
const approve = async (options) => {
|
|
202
43
|
const logger = (0, _cappa_logger.getLogger)();
|
|
203
|
-
const config = await getConfig();
|
|
44
|
+
const config = await (0, _cappa_config.getConfig)();
|
|
204
45
|
logger.start("Approving screenshots...");
|
|
205
46
|
const fileSystem = new _cappa_core.ScreenshotFileSystem(config.outputDir);
|
|
206
47
|
const [actualScreenshots, diffScreenshots, expectedScreenshots] = await Promise.all([
|
|
@@ -208,7 +49,7 @@ const approve = async (options) => {
|
|
|
208
49
|
fileSystem.getDiffScreenshots(),
|
|
209
50
|
fileSystem.getExpectedScreenshots()
|
|
210
51
|
]);
|
|
211
|
-
let screenshotsToApprove = await groupScreenshots(actualScreenshots, expectedScreenshots, diffScreenshots, config.outputDir);
|
|
52
|
+
let screenshotsToApprove = await (0, _cappa_core.groupScreenshots)(actualScreenshots, expectedScreenshots, diffScreenshots, config.outputDir);
|
|
212
53
|
const filters = options.filter?.map((filter) => filter.toLowerCase()) ?? [];
|
|
213
54
|
if (filters.length > 0) {
|
|
214
55
|
logger.debug(`Filtering actual screenshots by filter: ${filters.join(", ")}`);
|
|
@@ -232,37 +73,278 @@ const filterScreenshots = (screenshots, filters) => {
|
|
|
232
73
|
});
|
|
233
74
|
};
|
|
234
75
|
//#endregion
|
|
235
|
-
//#region src/
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
76
|
+
//#region src/utils/describeChanges.ts
|
|
77
|
+
/**
|
|
78
|
+
* The interpretation fields this reporter actually reads.
|
|
79
|
+
*
|
|
80
|
+
* The protocol carries `diffMeta.interpretation` opaquely — its shape belongs
|
|
81
|
+
* to `@blazediff/core-native` and pinning it in a versioned wire contract would
|
|
82
|
+
* make every diff-engine upgrade a breaking protocol change. So a remote engine
|
|
83
|
+
* hands this an `unknown`, and it narrows rather than trusts.
|
|
84
|
+
*
|
|
85
|
+
* Deliberately not the full `InterpretResult`: matching only what is rendered
|
|
86
|
+
* means a diff engine that adds or reshapes a field the reporter ignores does
|
|
87
|
+
* not silently cost the user their diff report.
|
|
88
|
+
*/
|
|
89
|
+
const regionSchema = zod.z.object({
|
|
90
|
+
bbox: zod.z.object({
|
|
91
|
+
x: zod.z.number(),
|
|
92
|
+
y: zod.z.number(),
|
|
93
|
+
width: zod.z.number(),
|
|
94
|
+
height: zod.z.number()
|
|
95
|
+
}),
|
|
96
|
+
percentage: zod.z.number(),
|
|
97
|
+
position: zod.z.string(),
|
|
98
|
+
changeType: zod.z.string()
|
|
99
|
+
});
|
|
100
|
+
const interpretationSchema = zod.z.object({
|
|
101
|
+
severity: zod.z.string(),
|
|
102
|
+
totalRegions: zod.z.number(),
|
|
103
|
+
summary: zod.z.string().optional(),
|
|
104
|
+
regions: zod.z.array(regionSchema).catch([]).optional()
|
|
105
|
+
});
|
|
106
|
+
const severityColor = (severity) => {
|
|
107
|
+
switch (severity) {
|
|
108
|
+
case "High": return chalk.default.red;
|
|
109
|
+
case "Medium": return chalk.default.yellow;
|
|
110
|
+
case "Low": return chalk.default.green;
|
|
111
|
+
default: return chalk.default.gray;
|
|
243
112
|
}
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
113
|
+
};
|
|
114
|
+
/** Human-readable labels for the `changeType` values reported by blazediff. */
|
|
115
|
+
const CHANGE_TYPE_LABELS = {
|
|
116
|
+
Addition: "added",
|
|
117
|
+
Deletion: "removed",
|
|
118
|
+
ColorChange: "color",
|
|
119
|
+
ContentChange: "content",
|
|
120
|
+
Shift: "shifted",
|
|
121
|
+
RenderingNoise: "noise"
|
|
122
|
+
};
|
|
123
|
+
const changeTypeLabel = (changeType) => CHANGE_TYPE_LABELS[changeType] ?? changeType;
|
|
124
|
+
/** `content at center · 0.90% · 360x200 at (420, 300)` */
|
|
125
|
+
const describeRegion = (region) => {
|
|
126
|
+
const { bbox } = region;
|
|
127
|
+
return [
|
|
128
|
+
chalk.default.cyan(changeTypeLabel(region.changeType)),
|
|
129
|
+
`at ${region.position}`,
|
|
130
|
+
chalk.default.dim("·"),
|
|
131
|
+
`${region.percentage.toFixed(2)}%`,
|
|
132
|
+
chalk.default.dim("·"),
|
|
133
|
+
chalk.default.dim(`${bbox.width}x${bbox.height} at (${bbox.x}, ${bbox.y})`)
|
|
134
|
+
].join(" ");
|
|
135
|
+
};
|
|
136
|
+
/**
|
|
137
|
+
* Build human-readable lines describing the changed screenshots, surfacing the
|
|
138
|
+
* pixel-diff percentage and (when `diff.interpret` is enabled) the structured
|
|
139
|
+
* interpretation: severity, region count, summary and the individual regions
|
|
140
|
+
* with their position and bounding box.
|
|
141
|
+
*
|
|
142
|
+
* Returns an empty array when there are no changed screenshots.
|
|
143
|
+
*/
|
|
144
|
+
const describeChanges = (screenshots, options = {}) => {
|
|
145
|
+
const { maxRegions = 5 } = options;
|
|
146
|
+
const changed = screenshots.filter((screenshot) => screenshot.category === "changed");
|
|
147
|
+
if (changed.length === 0) return [];
|
|
148
|
+
const lines = [];
|
|
149
|
+
for (const screenshot of changed) {
|
|
150
|
+
const meta = screenshot.diffMeta;
|
|
151
|
+
const parsed = interpretationSchema.safeParse(meta?.interpretation);
|
|
152
|
+
const interpretation = parsed.success ? parsed.data : void 0;
|
|
153
|
+
const parts = [];
|
|
154
|
+
if (interpretation) parts.push(severityColor(interpretation.severity)(interpretation.severity.toUpperCase()));
|
|
155
|
+
if (meta?.percentDifference !== void 0) parts.push(`${meta.percentDifference.toFixed(2)}%`);
|
|
156
|
+
if (interpretation) {
|
|
157
|
+
const { totalRegions } = interpretation;
|
|
158
|
+
parts.push(`${totalRegions} ${totalRegions === 1 ? "region" : "regions"}`);
|
|
159
|
+
}
|
|
160
|
+
const suffix = parts.length > 0 ? ` ${chalk.default.dim("·")} ${parts.join(chalk.default.dim(" · "))}` : "";
|
|
161
|
+
lines.push(`${chalk.default.bold(screenshot.name)}${suffix}`);
|
|
162
|
+
if (interpretation?.summary) lines.push(` ${chalk.default.dim(interpretation.summary)}`);
|
|
163
|
+
const regions = [...interpretation?.regions ?? []].sort((a, b) => b.percentage - a.percentage);
|
|
164
|
+
if (maxRegions > 0 && regions.length > 0) {
|
|
165
|
+
for (const region of regions.slice(0, maxRegions)) lines.push(` ${chalk.default.dim("→")} ${describeRegion(region)}`);
|
|
166
|
+
const remaining = regions.length - maxRegions;
|
|
167
|
+
if (remaining > 0) lines.push(chalk.default.dim(` … and ${remaining} more ${remaining === 1 ? "region" : "regions"}`));
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return lines;
|
|
171
|
+
};
|
|
172
|
+
//#endregion
|
|
173
|
+
//#region src/utils/parseMaxRegions.ts
|
|
174
|
+
/**
|
|
175
|
+
* Parse the `--max-regions` option: a non-negative integer, where `0` disables
|
|
176
|
+
* the per-region breakdown. Falls back to the default when omitted.
|
|
177
|
+
*/
|
|
178
|
+
const parseMaxRegions = (value) => {
|
|
179
|
+
if (value === void 0) return 5;
|
|
180
|
+
if (!/^\d+$/.test(value.trim())) throw new commander.InvalidArgumentError("Expected a non-negative integer (0 disables the region breakdown).");
|
|
181
|
+
return Number(value.trim());
|
|
182
|
+
};
|
|
183
|
+
//#endregion
|
|
184
|
+
//#region src/utils/remoteEngine.ts
|
|
185
|
+
/** A pre-flight failure, already phrased for the user. */
|
|
186
|
+
var RemoteServerError = class extends Error {
|
|
187
|
+
constructor(message) {
|
|
188
|
+
super(message);
|
|
189
|
+
this.name = "RemoteServerError";
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
/**
|
|
193
|
+
* The host already has a run in flight.
|
|
194
|
+
*
|
|
195
|
+
* Duck-typed rather than `instanceof`: `@cappa/client` ships dual ESM/CJS
|
|
196
|
+
* builds, so the CLI can hold a different copy of the class than the one that
|
|
197
|
+
* threw — the same hazard the client documents for its own 404 check.
|
|
198
|
+
*/
|
|
199
|
+
const isRunInProgress = (error) => typeof error === "object" && error !== null && error.status === 409;
|
|
200
|
+
const isAuthFailure = (error) => typeof error === "object" && error !== null && error.status === 401;
|
|
201
|
+
const isProtocolMismatch = (error) => error instanceof _cappa_client.ProtocolMismatchError || typeof error === "object" && error !== null && error.name === "ProtocolMismatchError";
|
|
202
|
+
/**
|
|
203
|
+
* Build a remote engine and prove the host is usable before capturing anything.
|
|
204
|
+
*
|
|
205
|
+
* One request to `/api/health` turns four different failures — unreachable
|
|
206
|
+
* host, wrong token, protocol skew, and a host that cannot capture — into four
|
|
207
|
+
* distinct messages, up front. The client performs the version handshake on its
|
|
208
|
+
* first call anyway; doing it here is what makes the failure legible rather
|
|
209
|
+
* than arriving mid-run with half a report already printed.
|
|
210
|
+
*/
|
|
211
|
+
async function connectToServer(options) {
|
|
212
|
+
const engine = (0, _cappa_client.createClient)({
|
|
213
|
+
baseUrl: options.server,
|
|
214
|
+
token: options.token
|
|
215
|
+
});
|
|
216
|
+
let health;
|
|
217
|
+
try {
|
|
218
|
+
health = await engine.health();
|
|
219
|
+
} catch (error) {
|
|
220
|
+
await engine.close();
|
|
221
|
+
if (isAuthFailure(error)) throw new RemoteServerError(`${options.server} rejected the access token. Pass --token <token>, or set CAPPA_TOKEN.`);
|
|
222
|
+
if (isProtocolMismatch(error)) throw new RemoteServerError(`${options.server} speaks protocol version ${error.actual}, this CLI expects ${error.expected}. Upgrade whichever is older.`);
|
|
223
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
224
|
+
throw new RemoteServerError(`Could not reach a cappa server at ${options.server}: ${reason}`);
|
|
225
|
+
}
|
|
226
|
+
if (!health.capabilities.capture) {
|
|
227
|
+
await engine.close();
|
|
228
|
+
throw new RemoteServerError(`${options.server} is running read-only and cannot capture. Restart it without --read-only.`);
|
|
229
|
+
}
|
|
230
|
+
return engine;
|
|
231
|
+
}
|
|
232
|
+
//#endregion
|
|
233
|
+
//#region src/utils/server.ts
|
|
234
|
+
const closeQuietly = async (name, closeable) => {
|
|
235
|
+
try {
|
|
236
|
+
await closeable.close();
|
|
237
|
+
} catch (error) {
|
|
238
|
+
(0, _cappa_logger.getLogger)().debug(`Error closing ${name} during shutdown:`, error);
|
|
247
239
|
}
|
|
248
|
-
return false;
|
|
249
240
|
};
|
|
250
|
-
|
|
241
|
+
/**
|
|
242
|
+
* Shut a running server down cleanly on Ctrl-C or SIGTERM.
|
|
243
|
+
*
|
|
244
|
+
* Order matters: the HTTP server closes first so no new run can be started
|
|
245
|
+
* mid-teardown, then the engine, which aborts an active run and closes the
|
|
246
|
+
* browser. Without that last step a killed server can leave an orphaned
|
|
247
|
+
* Chromium behind.
|
|
248
|
+
*
|
|
249
|
+
* The second signal exits immediately — if the first shutdown is wedged on a
|
|
250
|
+
* capture that will not stop, the user should not have to reach for `kill -9`.
|
|
251
|
+
*/
|
|
252
|
+
function registerShutdownHandlers(server, engine, exitFn = process.exit) {
|
|
253
|
+
let shuttingDown = false;
|
|
254
|
+
const handleSignal = async () => {
|
|
255
|
+
if (shuttingDown) {
|
|
256
|
+
exitFn(130);
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
shuttingDown = true;
|
|
260
|
+
(0, _cappa_logger.getLogger)().info("Shutting down…");
|
|
261
|
+
await closeQuietly("server", server);
|
|
262
|
+
await closeQuietly("engine", engine);
|
|
263
|
+
exitFn(130);
|
|
264
|
+
};
|
|
265
|
+
process.on("SIGINT", handleSignal);
|
|
266
|
+
process.on("SIGTERM", handleSignal);
|
|
267
|
+
return () => {
|
|
268
|
+
process.off("SIGINT", handleSignal);
|
|
269
|
+
process.off("SIGTERM", handleSignal);
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Read the access token from the flag, falling back to `CAPPA_TOKEN`.
|
|
274
|
+
*
|
|
275
|
+
* The environment fallback exists so a CI job does not have to put the token in
|
|
276
|
+
* its process list, where anything on the box can read it.
|
|
277
|
+
*/
|
|
278
|
+
const resolveToken = (token) => token ?? process.env.CAPPA_TOKEN ?? void 0;
|
|
279
|
+
/** Wildcard binds: addresses to listen on, never addresses to open. */
|
|
280
|
+
const WILDCARD_HOSTS = /* @__PURE__ */ new Set([
|
|
281
|
+
"0.0.0.0",
|
|
282
|
+
"::",
|
|
283
|
+
"[::]"
|
|
284
|
+
]);
|
|
285
|
+
/**
|
|
286
|
+
* The host to put in the URL a person is expected to click.
|
|
287
|
+
*
|
|
288
|
+
* A wildcard bind is the common way to expose the UI, and printing it verbatim
|
|
289
|
+
* produced `http://0.0.0.0:4801?token=…` — an address no browser will open,
|
|
290
|
+
* handed to a user who then cannot reach their own review UI. `localhost` is
|
|
291
|
+
* reachable on every interface the wildcard covers, so it is the right thing to
|
|
292
|
+
* show; a specific host is printed as given, because that one is meaningful.
|
|
293
|
+
*/
|
|
294
|
+
const toDisplayHost = (host) => (0, _cappa_server.isLoopbackHost)(host) || WILDCARD_HOSTS.has(host) ? "localhost" : host;
|
|
295
|
+
/**
|
|
296
|
+
* Build an engine, wrap it in a server, and start listening.
|
|
297
|
+
*
|
|
298
|
+
* Shared by `review` and `serve`, which differ only in how they resolve a token
|
|
299
|
+
* and what they print afterwards — everything from the engine to the bound
|
|
300
|
+
* socket is the same, and was duplicated before `serve` existed.
|
|
301
|
+
*
|
|
302
|
+
* The token is taken as already-resolved: the two commands have deliberately
|
|
303
|
+
* different policies (`review` generates one off loopback for the human reading
|
|
304
|
+
* the URL it prints, `serve` refuses to start without one), and folding that
|
|
305
|
+
* decision in here would hide it.
|
|
306
|
+
*/
|
|
307
|
+
async function startServer(options) {
|
|
308
|
+
const logger = (0, _cappa_logger.getLogger)();
|
|
309
|
+
const { config, host, port, readOnly, token, ui } = options;
|
|
310
|
+
const engine = new _cappa_core.LocalEngine({
|
|
311
|
+
...(0, _cappa_config.configToEngineOptions)(config),
|
|
312
|
+
browserIdleTimeoutMs: config.review.browserIdleTimeout
|
|
313
|
+
});
|
|
314
|
+
const server = await (0, _cappa_server.createServer)({
|
|
315
|
+
engine,
|
|
316
|
+
isProd: true,
|
|
317
|
+
ui,
|
|
318
|
+
outputDir: node_path.default.resolve(config.outputDir),
|
|
319
|
+
logger: logger.level >= 4,
|
|
320
|
+
theme: config.review.theme,
|
|
321
|
+
readOnly,
|
|
322
|
+
token
|
|
323
|
+
});
|
|
324
|
+
const unregisterShutdownHandlers = registerShutdownHandlers(server, engine);
|
|
325
|
+
await server.listen({
|
|
326
|
+
port,
|
|
327
|
+
host
|
|
328
|
+
});
|
|
329
|
+
return {
|
|
330
|
+
server,
|
|
331
|
+
engine,
|
|
332
|
+
url: `http://${toDisplayHost(host)}:${port}${token ? `?token=${token}` : ""}`,
|
|
333
|
+
unregisterShutdownHandlers
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
//#endregion
|
|
337
|
+
//#region src/commands/capture.ts
|
|
338
|
+
async function executeOnFailCallback(config, groupedScreenshots, { remote = false } = {}) {
|
|
251
339
|
const logger = (0, _cappa_logger.getLogger)();
|
|
252
340
|
if (!config.onFail) return;
|
|
253
|
-
|
|
254
|
-
const
|
|
255
|
-
const
|
|
256
|
-
const [actualScreenshots, expectedScreenshots, diffScreenshots] = await Promise.all([
|
|
257
|
-
actualScreenshotsPromise,
|
|
258
|
-
expectedScreenshotsPromise,
|
|
259
|
-
diffScreenshotsPromise
|
|
260
|
-
]);
|
|
261
|
-
const failingScreenshots = (await groupScreenshots(await Array.fromAsync(actualScreenshots), await Array.fromAsync(expectedScreenshots), await Array.fromAsync(diffScreenshots), config.outputDir)).filter((screenshot) => screenshot.category !== "passed").map((screenshot) => ({
|
|
341
|
+
if (remote && groupedScreenshots.length > 0) logger.warn("Capturing against a remote server: onFail receives relative paths only, because the screenshot files live on the host rather than this machine.");
|
|
342
|
+
const resolveLocal = (relative) => !remote && relative ? node_path.default.resolve(config.outputDir, relative) : void 0;
|
|
343
|
+
const failingScreenshots = groupedScreenshots.filter((screenshot) => screenshot.category !== "passed").map((screenshot) => ({
|
|
262
344
|
...screenshot,
|
|
263
|
-
absoluteActualPath: "actualPath" in screenshot
|
|
264
|
-
absoluteExpectedPath: "expectedPath" in screenshot
|
|
265
|
-
absoluteDiffPath: "diffPath" in screenshot
|
|
345
|
+
absoluteActualPath: resolveLocal("actualPath" in screenshot ? screenshot.actualPath : void 0),
|
|
346
|
+
absoluteExpectedPath: resolveLocal("expectedPath" in screenshot ? screenshot.expectedPath : void 0),
|
|
347
|
+
absoluteDiffPath: resolveLocal("diffPath" in screenshot ? screenshot.diffPath : void 0)
|
|
266
348
|
}));
|
|
267
349
|
if (failingScreenshots.length > 0) {
|
|
268
350
|
logger.debug(`Executing onFail callback with ${failingScreenshots.length} failing screenshot(s)`);
|
|
@@ -304,8 +386,10 @@ function generateFailureReportMessage(failedScreenshots, deletedScreenshots) {
|
|
|
304
386
|
const errorMsg = typeof result.error === "string" ? result.error : result.error instanceof Error ? result.error.message : String(result.error);
|
|
305
387
|
lines.push(` ${chalk.default.red("Error:")} ${errorMsg}`);
|
|
306
388
|
}
|
|
307
|
-
if (result.success === false)
|
|
308
|
-
|
|
389
|
+
if (result.success === false) {
|
|
390
|
+
if (result.isNew) lines.push(` ${chalk.default.yellow("Status:")} New screenshot (no baseline — run 'cappa approve' to accept)`);
|
|
391
|
+
else lines.push(` ${chalk.default.red("Status:")} Failed (comparison failed)`);
|
|
392
|
+
}
|
|
309
393
|
if (!result.filepath && result.skipped !== true) lines.push(` ${chalk.default.red("Status:")} Failed (no filepath generated)`);
|
|
310
394
|
}
|
|
311
395
|
}
|
|
@@ -315,158 +399,370 @@ function generateFailureReportMessage(failedScreenshots, deletedScreenshots) {
|
|
|
315
399
|
}
|
|
316
400
|
return lines.join("\n");
|
|
317
401
|
}
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
function registerSignalHandlers(screenshotTool, exitFn = process.exit) {
|
|
402
|
+
const supportsWatch = (engine) => typeof engine.startWatch === "function" && typeof engine.stopWatch === "function" && typeof engine.subscribeWatch === "function";
|
|
403
|
+
/**
|
|
404
|
+
* Close `closeable` and exit 130 on SIGINT/SIGTERM.
|
|
405
|
+
*
|
|
406
|
+
* Typed structurally rather than against a concrete class so it can be handed
|
|
407
|
+
* whatever owns the browser — that is the engine now, and a remote engine
|
|
408
|
+
* later, neither of which the CLI should have to special-case here.
|
|
409
|
+
*/
|
|
410
|
+
function registerSignalHandlers(closeable, exitFn = process.exit, onSignal) {
|
|
411
|
+
let handling = false;
|
|
329
412
|
const handleSignal = async () => {
|
|
330
|
-
|
|
413
|
+
if (handling) {
|
|
414
|
+
(0, _cappa_logger.getLogger)().warn("Interrupted again — exiting now. The remote run may still be going.");
|
|
415
|
+
exitFn(130);
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
handling = true;
|
|
419
|
+
try {
|
|
420
|
+
await onSignal?.();
|
|
421
|
+
await closeable.close();
|
|
422
|
+
} catch (error) {
|
|
423
|
+
(0, _cappa_logger.getLogger)().debug("Error during shutdown:", error);
|
|
424
|
+
}
|
|
331
425
|
exitFn(130);
|
|
332
426
|
};
|
|
333
|
-
process.
|
|
334
|
-
process.
|
|
427
|
+
process.on("SIGINT", handleSignal);
|
|
428
|
+
process.on("SIGTERM", handleSignal);
|
|
335
429
|
return () => {
|
|
336
430
|
process.off("SIGINT", handleSignal);
|
|
337
431
|
process.off("SIGTERM", handleSignal);
|
|
338
432
|
};
|
|
339
433
|
}
|
|
340
|
-
|
|
434
|
+
/**
|
|
435
|
+
* Render a runner event to the terminal.
|
|
436
|
+
*
|
|
437
|
+
* All terminal presentation lives here — the runner itself is silent — so the
|
|
438
|
+
* server can consume the exact same event stream without inheriting CLI output.
|
|
439
|
+
*/
|
|
440
|
+
function renderRunEvent(event) {
|
|
341
441
|
const logger = (0, _cappa_logger.getLogger)();
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
retries: config.retries,
|
|
352
|
-
concurrency: config.concurrency,
|
|
353
|
-
logConsoleEvents: config.logConsoleEvents,
|
|
354
|
-
fullPage: config.screenshot?.fullPage ?? true,
|
|
355
|
-
viewport: config.screenshot?.viewport ?? {
|
|
356
|
-
width: 1920,
|
|
357
|
-
height: 1080
|
|
358
|
-
},
|
|
359
|
-
connectionTimeout: config.connectionTimeout
|
|
360
|
-
});
|
|
361
|
-
const unregisterSignalHandlers = registerSignalHandlers(screenshotTool);
|
|
362
|
-
let captureError;
|
|
363
|
-
let hasScreenshotFailure = false;
|
|
364
|
-
let anyTasksRan = false;
|
|
365
|
-
const failedScreenshots = [];
|
|
366
|
-
try {
|
|
367
|
-
await screenshotTool.init();
|
|
368
|
-
const plugins = config.plugins || [];
|
|
369
|
-
const pluginTasks = await Promise.all(plugins.map(async (plugin) => {
|
|
370
|
-
logger.debug(`Discovering tasks for plugin: ${plugin.name}`);
|
|
371
|
-
const tasks = await plugin.discover(screenshotTool);
|
|
372
|
-
logger.info(`Found ${tasks.length} tasks for ${plugin.name}`);
|
|
373
|
-
return {
|
|
374
|
-
plugin,
|
|
375
|
-
tasks
|
|
376
|
-
};
|
|
377
|
-
}));
|
|
378
|
-
if (options.filter) {
|
|
442
|
+
switch (event.type) {
|
|
443
|
+
case "log":
|
|
444
|
+
logger[event.level](event.message, ...event.args);
|
|
445
|
+
break;
|
|
446
|
+
case "discover:plugin":
|
|
447
|
+
logger.info(`Found ${event.taskCount} tasks for ${event.plugin}`);
|
|
448
|
+
break;
|
|
449
|
+
case "filter:applied":
|
|
450
|
+
if (event.filter === void 0) break;
|
|
379
451
|
logger.box({
|
|
380
452
|
title: "Filter Active",
|
|
381
|
-
message: `Only capturing tasks matching: ${chalk.default.cyan(
|
|
453
|
+
message: `Only capturing tasks matching: ${chalk.default.cyan(event.filter)}`
|
|
382
454
|
});
|
|
383
|
-
for (const entry of
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
455
|
+
for (const entry of event.plugins) logger.info(`${entry.plugin}: ${entry.after}/${entry.before} tasks match filter`);
|
|
456
|
+
break;
|
|
457
|
+
case "task:start":
|
|
458
|
+
logger.debug(`Executing task: ${event.taskId}`);
|
|
459
|
+
break;
|
|
460
|
+
case "task:complete":
|
|
461
|
+
logger.info(formatProgress(event.completed, event.total, event.taskId));
|
|
462
|
+
break;
|
|
463
|
+
case "plugin:complete":
|
|
464
|
+
if (event.failed) logger.error(`Plugin ${event.plugin} completed with failures: ${event.resultCount} results`);
|
|
465
|
+
else logger.success(`Plugin ${event.plugin} completed: ${event.resultCount} results`);
|
|
466
|
+
break;
|
|
467
|
+
case "run:error": logger.error("Error during plugin execution:", event.error.message);
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* One line for a settled batch of changes.
|
|
472
|
+
*
|
|
473
|
+
* Terse on purpose: this is the inner loop of somebody fixing a regression, and
|
|
474
|
+
* a paragraph per save is noise. It still says *why* the iteration is the size
|
|
475
|
+
* it is, because "3 tasks" and "everything" have very different causes.
|
|
476
|
+
*/
|
|
477
|
+
function describeWatchChange(event) {
|
|
478
|
+
const files = event.files.length === 1 ? event.files[0] ?? "" : `${event.files.length} files`;
|
|
479
|
+
const what = (() => {
|
|
480
|
+
switch (event.scope) {
|
|
481
|
+
case "tasks": {
|
|
482
|
+
const count = event.taskIds?.length ?? 0;
|
|
483
|
+
return `${count} task${count === 1 ? "" : "s"}`;
|
|
387
484
|
}
|
|
485
|
+
case "plugins": return "every task of the affected plugin(s)";
|
|
486
|
+
case "all": return "everything";
|
|
487
|
+
default: return "nothing";
|
|
488
|
+
}
|
|
489
|
+
})();
|
|
490
|
+
return `${chalk.default.cyan("↻")} ${what} · ${files} changed`;
|
|
491
|
+
}
|
|
492
|
+
/** The one-line result of a watch iteration. */
|
|
493
|
+
function summarizeRunDetail(detail, duration) {
|
|
494
|
+
if (!detail) return `Run finished in ${duration}`;
|
|
495
|
+
const failures = detail.failures.length + detail.deletedScreenshots.length;
|
|
496
|
+
const captured = `${detail.completedTasks}/${detail.totalTasks} captured`;
|
|
497
|
+
if (failures > 0) return chalk.default.yellow(`${captured}, ${failures} to review — ${duration}`);
|
|
498
|
+
return chalk.default.green(`${captured}, all passing — ${duration}`);
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* A watch iteration's run output.
|
|
502
|
+
*
|
|
503
|
+
* Only what changed: a passing task in watch mode is the absence of news, and
|
|
504
|
+
* printing every one of them buries the two lines that matter.
|
|
505
|
+
*/
|
|
506
|
+
function renderWatchRunEvent(event) {
|
|
507
|
+
const logger = (0, _cappa_logger.getLogger)();
|
|
508
|
+
switch (event.type) {
|
|
509
|
+
case "log":
|
|
510
|
+
if (event.level === "warn" || event.level === "error") logger[event.level](event.message, ...event.args);
|
|
511
|
+
break;
|
|
512
|
+
case "task:complete":
|
|
513
|
+
if (event.status !== "passed" && event.status !== "skipped") logger.info(` ${chalk.default.dim(event.status)} ${event.taskId}`);
|
|
514
|
+
break;
|
|
515
|
+
case "run:error": logger.error("Error during plugin execution:", event.error.message);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* Stop watching and exit 0 on SIGINT/SIGTERM.
|
|
520
|
+
*
|
|
521
|
+
* Zero, not 130: quitting a watch session is how it is meant to end, and a
|
|
522
|
+
* non-zero exit would make `cappa capture --watch` fail every shell script and
|
|
523
|
+
* task runner that wraps it.
|
|
524
|
+
*/
|
|
525
|
+
function registerWatchSignalHandlers(stop, exitFn = process.exit) {
|
|
526
|
+
let handling = false;
|
|
527
|
+
const handleSignal = async () => {
|
|
528
|
+
if (handling) {
|
|
529
|
+
exitFn(0);
|
|
530
|
+
return;
|
|
388
531
|
}
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
532
|
+
handling = true;
|
|
533
|
+
(0, _cappa_logger.getLogger)().info("Stopping watch…");
|
|
534
|
+
await stop();
|
|
535
|
+
exitFn(0);
|
|
536
|
+
};
|
|
537
|
+
process.on("SIGINT", handleSignal);
|
|
538
|
+
process.on("SIGTERM", handleSignal);
|
|
539
|
+
return () => {
|
|
540
|
+
process.off("SIGINT", handleSignal);
|
|
541
|
+
process.off("SIGTERM", handleSignal);
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
/**
|
|
545
|
+
* Watch for changes and re-capture, until interrupted.
|
|
546
|
+
*
|
|
547
|
+
* Resolves only when a signal stops the session, so the caller keeps the
|
|
548
|
+
* process — and the warm browser — alive for as long as the user is editing.
|
|
549
|
+
*/
|
|
550
|
+
async function watchCapture(engine, options = {}, exitFn = process.exit) {
|
|
551
|
+
const logger = (0, _cappa_logger.getLogger)();
|
|
552
|
+
let release;
|
|
553
|
+
const finished = new Promise((resolve) => {
|
|
554
|
+
release = resolve;
|
|
555
|
+
});
|
|
556
|
+
const stop = async () => {
|
|
557
|
+
try {
|
|
558
|
+
await engine.stopWatch();
|
|
559
|
+
await engine.close();
|
|
560
|
+
} catch (error) {
|
|
561
|
+
logger.debug("Error stopping the watch session:", error);
|
|
562
|
+
} finally {
|
|
563
|
+
release?.();
|
|
564
|
+
}
|
|
565
|
+
};
|
|
566
|
+
const unregisterSignalHandlers = registerWatchSignalHandlers(stop, exitFn);
|
|
567
|
+
let rendering = Promise.resolve();
|
|
568
|
+
const unsubscribe = engine.subscribeWatch((event) => {
|
|
569
|
+
switch (event.type) {
|
|
570
|
+
case "watch:start":
|
|
571
|
+
logger.info(`Watching ${event.paths.join(", ")}${event.filter ? ` (filter: ${event.filter})` : ""} — press Ctrl-C to stop.`);
|
|
572
|
+
break;
|
|
573
|
+
case "watch:change": {
|
|
574
|
+
logger.info(describeWatchChange(event));
|
|
575
|
+
if (event.error) {
|
|
576
|
+
logger.warn(`Could not start a run: ${event.error}`);
|
|
577
|
+
break;
|
|
413
578
|
}
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
579
|
+
const runId = event.runId;
|
|
580
|
+
if (runId) rendering = rendering.then(() => renderWatchIteration(engine, runId).catch((error) => {
|
|
581
|
+
logger.error("Error rendering the run:", error);
|
|
582
|
+
}));
|
|
583
|
+
break;
|
|
584
|
+
}
|
|
418
585
|
}
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
586
|
+
});
|
|
587
|
+
try {
|
|
588
|
+
await engine.startWatch({ filter: options.filter });
|
|
589
|
+
await finished;
|
|
423
590
|
} finally {
|
|
591
|
+
unsubscribe();
|
|
424
592
|
unregisterSignalHandlers();
|
|
425
|
-
await screenshotTool.close();
|
|
426
593
|
}
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
594
|
+
}
|
|
595
|
+
async function renderWatchIteration(engine, runId) {
|
|
596
|
+
const logger = (0, _cappa_logger.getLogger)();
|
|
597
|
+
const start = performance.now();
|
|
598
|
+
await renderRunToCompletion(engine, runId, renderWatchRunEvent);
|
|
599
|
+
const detail = await engine.getRun(runId);
|
|
600
|
+
const duration = formatDuration(performance.now() - start);
|
|
601
|
+
logger.info(summarizeRunDetail(detail, duration));
|
|
602
|
+
}
|
|
603
|
+
/**
|
|
604
|
+
* Rebuild a throwable error from the run's serialized one.
|
|
605
|
+
*
|
|
606
|
+
* The engine flattens the error a plugin threw so it can cross a network
|
|
607
|
+
* boundary, but `capture` has always failed by letting that error escape — the
|
|
608
|
+
* stack is the only debugging signal for a plugin that blew up. Reinstating
|
|
609
|
+
* name, message and stack keeps that output intact.
|
|
610
|
+
*/
|
|
611
|
+
function toThrowable(error) {
|
|
612
|
+
const rebuilt = new Error(error.message);
|
|
613
|
+
rebuilt.name = error.name;
|
|
614
|
+
if (error.stack) rebuilt.stack = error.stack;
|
|
615
|
+
return rebuilt;
|
|
616
|
+
}
|
|
617
|
+
/**
|
|
618
|
+
* Subscribe to a run, render every event, and resolve when it terminates.
|
|
619
|
+
*
|
|
620
|
+
* Events buffered between `startRun` and this subscription are replayed
|
|
621
|
+
* synchronously, so nothing emitted during start-up is lost.
|
|
622
|
+
*/
|
|
623
|
+
async function renderRunToCompletion(engine, runId, onEvent) {
|
|
624
|
+
let unsubscribe;
|
|
625
|
+
try {
|
|
626
|
+
await new Promise((resolve) => {
|
|
627
|
+
unsubscribe = engine.subscribeRun(runId, (event) => {
|
|
628
|
+
onEvent(event);
|
|
629
|
+
if (event.type === "run:complete" || event.type === "run:error") resolve();
|
|
630
|
+
});
|
|
631
|
+
});
|
|
632
|
+
} finally {
|
|
633
|
+
unsubscribe?.();
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
/** How long a `SIGINT` waits for a remote host to acknowledge cancellation. */
|
|
637
|
+
const REMOTE_CANCEL_TIMEOUT_MS = 5e3;
|
|
638
|
+
const runCapture = async (options = {}) => {
|
|
639
|
+
const logger = (0, _cappa_logger.getLogger)();
|
|
640
|
+
const captureStart = performance.now();
|
|
641
|
+
if (options.watch && options.server) {
|
|
642
|
+
logger.error("--watch cannot be combined with --server: a remote host cannot see the files on this machine.");
|
|
643
|
+
process.exit(1);
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
if (options.watch && options.ci) {
|
|
647
|
+
logger.error("--watch cannot be combined with --ci: CI captures once and exits.");
|
|
648
|
+
process.exit(1);
|
|
649
|
+
return;
|
|
650
|
+
}
|
|
651
|
+
const config = await (0, _cappa_config.getConfig)();
|
|
652
|
+
const remote = options.server !== void 0;
|
|
653
|
+
let engine;
|
|
654
|
+
if (options.token && !options.server) {
|
|
655
|
+
logger.error("--token only applies with --server.");
|
|
656
|
+
process.exit(1);
|
|
657
|
+
return;
|
|
433
658
|
}
|
|
659
|
+
if (options.server) {
|
|
660
|
+
logger.info(`Capturing on ${options.server}, which uses its own cappa.config.ts. Local capture settings do not apply.`);
|
|
661
|
+
try {
|
|
662
|
+
engine = await connectToServer({
|
|
663
|
+
server: options.server,
|
|
664
|
+
token: resolveToken(options.token)
|
|
665
|
+
});
|
|
666
|
+
} catch (error) {
|
|
667
|
+
if (error instanceof RemoteServerError) {
|
|
668
|
+
logger.error(error.message);
|
|
669
|
+
process.exit(1);
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
throw error;
|
|
673
|
+
}
|
|
674
|
+
} else engine = new _cappa_core.LocalEngine({
|
|
675
|
+
...(0, _cappa_config.configToEngineOptions)(config),
|
|
676
|
+
browserIdleTimeoutMs: options.watch ? config.review?.browserIdleTimeout : 0
|
|
677
|
+
});
|
|
434
678
|
const isCi = options.ci || process.env.CI === "true";
|
|
435
|
-
|
|
679
|
+
let detail;
|
|
680
|
+
let groupedScreenshots = [];
|
|
681
|
+
let activeRunId;
|
|
682
|
+
let runCompleted;
|
|
683
|
+
const cancelRemoteRun = async () => {
|
|
684
|
+
if (!remote || !activeRunId) return;
|
|
685
|
+
logger.info("Cancelling the remote run…");
|
|
686
|
+
try {
|
|
687
|
+
await engine.cancelRun(activeRunId);
|
|
688
|
+
await Promise.race([runCompleted?.catch(() => void 0) ?? Promise.resolve(), new Promise((resolve) => {
|
|
689
|
+
setTimeout(resolve, REMOTE_CANCEL_TIMEOUT_MS).unref?.();
|
|
690
|
+
})]);
|
|
691
|
+
} catch (error) {
|
|
692
|
+
logger.debug("Error cancelling the remote run:", error);
|
|
693
|
+
}
|
|
694
|
+
};
|
|
695
|
+
const unregisterSignalHandlers = registerSignalHandlers(engine, process.exit, cancelRemoteRun);
|
|
696
|
+
try {
|
|
697
|
+
let run;
|
|
698
|
+
try {
|
|
699
|
+
run = await engine.startRun({
|
|
700
|
+
filter: options.filter,
|
|
701
|
+
clearActual: true
|
|
702
|
+
});
|
|
703
|
+
} catch (error) {
|
|
704
|
+
if (isRunInProgress(error)) {
|
|
705
|
+
const active = error.activeRunId ? ` (run ${error.activeRunId})` : "";
|
|
706
|
+
logger.error(`${options.server} is already running a capture${active}. Wait for it to finish, or cancel it, and try again.`);
|
|
707
|
+
process.exit(1);
|
|
708
|
+
return;
|
|
709
|
+
}
|
|
710
|
+
throw error;
|
|
711
|
+
}
|
|
712
|
+
activeRunId = run.id;
|
|
713
|
+
runCompleted = renderRunToCompletion(engine, run.id, renderRunEvent);
|
|
714
|
+
await runCompleted;
|
|
715
|
+
detail = await engine.getRun(run.id);
|
|
716
|
+
const failedDuringRun = detail?.error !== void 0;
|
|
717
|
+
const hasFailure = (detail?.failures.length ?? 0) > 0 || (detail?.deletedScreenshots.length ?? 0) > 0;
|
|
718
|
+
if (!failedDuringRun && (isCi || hasFailure)) try {
|
|
719
|
+
groupedScreenshots = await engine.listScreenshots();
|
|
720
|
+
} catch (err) {
|
|
721
|
+
logger.warn("Could not collect screenshot results:", err);
|
|
722
|
+
}
|
|
723
|
+
} finally {
|
|
724
|
+
unregisterSignalHandlers();
|
|
725
|
+
if (!options.watch) await engine.close();
|
|
726
|
+
}
|
|
727
|
+
if (detail?.error) throw toThrowable(detail.error);
|
|
728
|
+
const failures = detail?.failures ?? [];
|
|
729
|
+
const deletedScreenshots = detail?.deletedScreenshots ?? [];
|
|
730
|
+
const hasScreenshotFailure = failures.length > 0 || deletedScreenshots.length > 0;
|
|
731
|
+
if (isCi) await executeOnFailCallback(config, groupedScreenshots, { remote });
|
|
436
732
|
const duration = formatDuration(performance.now() - captureStart);
|
|
437
733
|
if (hasScreenshotFailure) {
|
|
438
|
-
const reportMessage = generateFailureReportMessage(
|
|
734
|
+
const reportMessage = generateFailureReportMessage(failures, deletedScreenshots);
|
|
439
735
|
logger.box({
|
|
440
736
|
title: "Failed Screenshots",
|
|
441
737
|
message: reportMessage
|
|
442
738
|
});
|
|
443
|
-
|
|
444
|
-
|
|
739
|
+
const changeLines = describeChanges(groupedScreenshots, { maxRegions: options.maxRegions });
|
|
740
|
+
if (changeLines.length > 0) logger.box({
|
|
741
|
+
title: "Changed Screenshots",
|
|
742
|
+
message: changeLines.join("\n")
|
|
743
|
+
});
|
|
744
|
+
if (options.watch) logger.warn(`One or more screenshots failed in ${duration}.`);
|
|
745
|
+
else {
|
|
746
|
+
logger.error(`One or more screenshots failed in ${duration}. See report above for details.`);
|
|
747
|
+
process.exit(1);
|
|
748
|
+
}
|
|
445
749
|
} else logger.success(`All plugins completed successfully in ${duration}`);
|
|
750
|
+
if (options.watch) {
|
|
751
|
+
if (!supportsWatch(engine)) {
|
|
752
|
+
logger.error("This engine cannot watch files.");
|
|
753
|
+
await engine.close();
|
|
754
|
+
process.exit(1);
|
|
755
|
+
return;
|
|
756
|
+
}
|
|
757
|
+
await watchCapture(engine, { filter: options.filter });
|
|
758
|
+
}
|
|
446
759
|
};
|
|
447
760
|
const registerCaptureCommand = (program) => {
|
|
448
|
-
program.command("capture").description("Capture screenshots").option("--ci", "run capture in CI mode and execute onFail callback").option("-f, --filter <pattern>", "only capture tasks whose id matches the given glob pattern").action(async (options) => {
|
|
761
|
+
program.command("capture").description("Capture screenshots").option("--ci", "run capture in CI mode and execute onFail callback").option("-f, --filter <pattern>", "only capture tasks whose id matches the given glob pattern").option("--max-regions <count>", "maximum number of interpreted diff regions listed per changed screenshot (0 to disable)", parseMaxRegions, 5).option("--server <url>", "capture against a `cappa serve` host instead of a local browser").option("--token <token>", "access token for --server (falls back to CAPPA_TOKEN)").option("-w, --watch", "capture once, then re-capture affected tasks whenever files change").action(async (options) => {
|
|
449
762
|
await runCapture(options);
|
|
450
763
|
});
|
|
451
764
|
};
|
|
452
765
|
//#endregion
|
|
453
|
-
//#region src/features/config/default.ts
|
|
454
|
-
const defaultConfig = `import { defineConfig } from "@cappa/core";
|
|
455
|
-
|
|
456
|
-
export default defineConfig({
|
|
457
|
-
outputDir: "./screenshots",
|
|
458
|
-
retries: 3,
|
|
459
|
-
diff: {
|
|
460
|
-
threshold: 0.1,
|
|
461
|
-
includeAA: false,
|
|
462
|
-
fastBufferCheck: true,
|
|
463
|
-
maxDiffPixels: 0,
|
|
464
|
-
maxDiffPercentage: 0,
|
|
465
|
-
},
|
|
466
|
-
plugins: [],
|
|
467
|
-
});
|
|
468
|
-
`;
|
|
469
|
-
//#endregion
|
|
470
766
|
//#region src/commands/init.ts
|
|
471
767
|
const init = async () => {
|
|
472
768
|
const logger = (0, _cappa_logger.getLogger)();
|
|
@@ -474,7 +770,7 @@ const init = async () => {
|
|
|
474
770
|
const packageJsonPath = node_path.default.resolve(process.cwd(), "package.json");
|
|
475
771
|
if (node_fs.default.existsSync(configPath)) logger.warn("cappa.config.ts already exists, skipping...");
|
|
476
772
|
else {
|
|
477
|
-
node_fs.default.writeFileSync(configPath, defaultConfig);
|
|
773
|
+
node_fs.default.writeFileSync(configPath, _cappa_config.defaultConfig);
|
|
478
774
|
logger.success("Created cappa.config.ts");
|
|
479
775
|
}
|
|
480
776
|
if (node_fs.default.existsSync(packageJsonPath)) try {
|
|
@@ -495,86 +791,79 @@ const init = async () => {
|
|
|
495
791
|
};
|
|
496
792
|
//#endregion
|
|
497
793
|
//#region src/commands/review.ts
|
|
498
|
-
const review = async () => {
|
|
794
|
+
const review = async (options = {}) => {
|
|
499
795
|
const logger = (0, _cappa_logger.getLogger)();
|
|
500
|
-
const config = await getConfig();
|
|
501
|
-
const
|
|
502
|
-
const
|
|
503
|
-
const
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
796
|
+
const config = await (0, _cappa_config.getConfig)();
|
|
797
|
+
const host = options.host ?? "127.0.0.1";
|
|
798
|
+
const port = options.port ?? config.review.port;
|
|
799
|
+
const readOnly = options.readOnly ?? false;
|
|
800
|
+
let token = resolveToken(options.token);
|
|
801
|
+
let tokenWasGenerated = false;
|
|
802
|
+
if (!token && !(0, _cappa_server.isLoopbackHost)(host) && !readOnly) {
|
|
803
|
+
token = (0, node_crypto.randomBytes)(24).toString("base64url");
|
|
804
|
+
tokenWasGenerated = true;
|
|
805
|
+
logger.warn(`Binding to ${host} exposes capture control beyond this machine; requiring an access token.`);
|
|
806
|
+
}
|
|
807
|
+
const { url } = await startServer({
|
|
808
|
+
config,
|
|
809
|
+
host,
|
|
810
|
+
port,
|
|
811
|
+
readOnly,
|
|
812
|
+
token,
|
|
813
|
+
ui: true
|
|
517
814
|
});
|
|
518
|
-
logger.success(`Review UI available at
|
|
519
|
-
|
|
815
|
+
logger.success(`Review UI available at ${url}`);
|
|
816
|
+
if (tokenWasGenerated && logger.level < 3) logger.warn(`Review UI available at ${url}`);
|
|
817
|
+
if (readOnly) logger.info("Running read-only: capture and approval are disabled.");
|
|
520
818
|
};
|
|
521
819
|
//#endregion
|
|
522
|
-
//#region src/
|
|
523
|
-
const severityColor = (severity) => {
|
|
524
|
-
switch (severity) {
|
|
525
|
-
case "High": return chalk.default.red;
|
|
526
|
-
case "Medium": return chalk.default.yellow;
|
|
527
|
-
case "Low": return chalk.default.green;
|
|
528
|
-
default: return chalk.default.gray;
|
|
529
|
-
}
|
|
530
|
-
};
|
|
820
|
+
//#region src/commands/serve.ts
|
|
531
821
|
/**
|
|
532
|
-
*
|
|
533
|
-
* pixel-diff percentage and (when `diff.interpret` is enabled) the structured
|
|
534
|
-
* interpretation: severity, region count and summary.
|
|
822
|
+
* Host a capture engine for a remote `cappa capture --server`.
|
|
535
823
|
*
|
|
536
|
-
*
|
|
824
|
+
* `review` minus the assumption that a person is about to open a browser. The
|
|
825
|
+
* one deliberate divergence is the token: `review` generates one off loopback
|
|
826
|
+
* because a human is reading the URL it prints, and `serve` has no such reader —
|
|
827
|
+
* generating one here would produce a daemon nobody can authenticate against.
|
|
828
|
+
* So off loopback it is required, and the command refuses to start without one.
|
|
537
829
|
*/
|
|
538
|
-
const
|
|
539
|
-
const
|
|
540
|
-
|
|
541
|
-
const
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
parts.push(`${totalRegions} ${totalRegions === 1 ? "region" : "regions"}`);
|
|
551
|
-
}
|
|
552
|
-
const suffix = parts.length > 0 ? ` ${chalk.default.dim("·")} ${parts.join(chalk.default.dim(" · "))}` : "";
|
|
553
|
-
lines.push(`${chalk.default.bold(screenshot.name)}${suffix}`);
|
|
554
|
-
if (interpretation?.summary) lines.push(` ${chalk.default.dim(interpretation.summary)}`);
|
|
830
|
+
const serve = async (options = {}) => {
|
|
831
|
+
const logger = (0, _cappa_logger.getLogger)();
|
|
832
|
+
const config = await (0, _cappa_config.getConfig)();
|
|
833
|
+
const host = options.host ?? "127.0.0.1";
|
|
834
|
+
const port = options.port ?? config.review.port;
|
|
835
|
+
const readOnly = options.readOnly ?? false;
|
|
836
|
+
const ui = options.ui ?? true;
|
|
837
|
+
const token = resolveToken(options.token);
|
|
838
|
+
if (!token && !(0, _cappa_server.isLoopbackHost)(host) && !readOnly) {
|
|
839
|
+
logger.error(`Binding to ${host} exposes capture control beyond this machine, so an access token is required. Pass --token <token>, or set CAPPA_TOKEN to keep it out of the process list.`);
|
|
840
|
+
process.exit(1);
|
|
841
|
+
return;
|
|
555
842
|
}
|
|
556
|
-
|
|
843
|
+
const { url } = await startServer({
|
|
844
|
+
config,
|
|
845
|
+
host,
|
|
846
|
+
port,
|
|
847
|
+
readOnly,
|
|
848
|
+
token,
|
|
849
|
+
ui
|
|
850
|
+
});
|
|
851
|
+
logger.log(`cappa serve listening host=${host} port=${port} ui=${ui} read-only=${readOnly} token=${token ? "yes" : "no"}`);
|
|
852
|
+
if (ui) logger.info(`Review UI available at ${url}`);
|
|
853
|
+
if (readOnly) logger.info("Running read-only: capture and approval are disabled.");
|
|
557
854
|
};
|
|
558
855
|
//#endregion
|
|
559
856
|
//#region src/commands/status.ts
|
|
560
|
-
const status = async () => {
|
|
857
|
+
const status = async (options = {}) => {
|
|
561
858
|
const logger = (0, _cappa_logger.getLogger)();
|
|
562
|
-
const config = await getConfig();
|
|
563
|
-
const
|
|
564
|
-
const expectedScreenshotsPromise = (0, node_fs_promises.glob)(node_path.default.resolve(config.outputDir, "expected", "**/*.png"));
|
|
565
|
-
const diffScreenshotsPromise = (0, node_fs_promises.glob)(node_path.default.resolve(config.outputDir, "diff", "**/*.png"));
|
|
566
|
-
const [actualScreenshots, expectedScreenshots, diffScreenshots] = await Promise.all([
|
|
567
|
-
actualScreenshotsPromise,
|
|
568
|
-
expectedScreenshotsPromise,
|
|
569
|
-
diffScreenshotsPromise
|
|
570
|
-
]);
|
|
571
|
-
const groupedScreenshots = await groupScreenshots(await Array.fromAsync(actualScreenshots), await Array.fromAsync(expectedScreenshots), await Array.fromAsync(diffScreenshots), config.outputDir);
|
|
859
|
+
const config = await (0, _cappa_config.getConfig)();
|
|
860
|
+
const groupedScreenshots = await (0, _cappa_core.collectScreenshots)(config.outputDir);
|
|
572
861
|
logger.debug("All screenshot information:", JSON.stringify(groupedScreenshots, null, 2));
|
|
573
862
|
logger.box({
|
|
574
863
|
title: "Screenshot Status",
|
|
575
864
|
message: `${chalk.default.yellow("New screenshots:")} ${groupedScreenshots.filter((r) => r.category === "new").length}\n${chalk.default.red("Deleted screenshots:")} ${groupedScreenshots.filter((r) => r.category === "deleted").length}\n${chalk.default.green("Changed screenshots:")} ${groupedScreenshots.filter((r) => r.category === "changed").length}\n${chalk.default.blue("Passed screenshots:")} ${groupedScreenshots.filter((r) => r.category === "passed").length}`
|
|
576
865
|
});
|
|
577
|
-
const changeLines = describeChanges(groupedScreenshots);
|
|
866
|
+
const changeLines = describeChanges(groupedScreenshots, { maxRegions: options.maxRegions });
|
|
578
867
|
if (changeLines.length > 0) logger.box({
|
|
579
868
|
title: "Changed Screenshots",
|
|
580
869
|
message: changeLines.join("\n")
|
|
@@ -593,9 +882,10 @@ program.name("cappa").description("Cappa CLI").version(version).option("-l, --lo
|
|
|
593
882
|
(0, _cappa_logger.initLogger)(logLevel)?.debug(`Log level set to: ${logLevel}`);
|
|
594
883
|
});
|
|
595
884
|
registerCaptureCommand(program);
|
|
596
|
-
program.command("review").description("
|
|
885
|
+
program.command("review").description("Open the review and capture UI").option("-p, --port <port>", "port to listen on", (v) => Number.parseInt(v, 10)).option("--host <host>", "host to bind to (a non-loopback host requires an access token)").option("--read-only", "serve the UI without capture, approval or any other mutation").option("--token <token>", "require this access token on every API request (falls back to CAPPA_TOKEN)").action(review);
|
|
886
|
+
program.command("serve").description("Host a capture engine for a remote `cappa capture --server`").option("-p, --port <port>", "port to listen on", (v) => Number.parseInt(v, 10)).option("--host <host>", "host to bind to (a non-loopback host requires an access token)").option("--read-only", "serve without capture, approval or any other mutation").option("--token <token>", "require this access token on every API request (falls back to CAPPA_TOKEN)").option("--no-ui", "serve the API only, without the review UI").action(serve);
|
|
597
887
|
program.command("approve").description("Approve screenshots").option("-f, --filter <filter...>", "only approve screenshots whose name includes the provided filter value(s)").action(approve);
|
|
598
|
-
program.command("status").description("Get status of screenshots").action(status);
|
|
888
|
+
program.command("status").description("Get status of screenshots").option("--max-regions <count>", "maximum number of interpreted diff regions listed per changed screenshot (0 to disable)", parseMaxRegions, 5).action(status);
|
|
599
889
|
program.command("init").description("Initialize Cappa in the current directory").action(init);
|
|
600
890
|
async function run() {
|
|
601
891
|
await program.parseAsync();
|