visual-regression-ci 0.0.0-stage → 0.9.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/LICENSE +21 -0
- package/README.md +953 -2
- package/package.json +76 -4
- package/src/ci/actionReport.js +340 -0
- package/src/ci/prComment.js +420 -0
- package/src/cli/capture.js +243 -0
- package/src/cli/compare.js +190 -0
- package/src/cli/config.js +287 -0
- package/src/cli/database.js +69 -0
- package/src/cli/display.js +119 -0
- package/src/cli/errors.js +17 -0
- package/src/cli/index.js +577 -0
- package/src/cli/installBrowsers.js +59 -0
- package/src/cli/invocation.js +66 -0
- package/src/cli/jsonTarget.js +100 -0
- package/src/cli/logger.js +15 -0
- package/src/cli/manifest.js +139 -0
- package/src/cli/naming.js +60 -0
- package/src/cli/reporter.js +172 -0
- package/src/cli/result.js +225 -0
- package/src/cli/serve.js +64 -0
- package/src/server/app.js +135 -0
- package/src/server/db.js +691 -0
- package/src/server/importRuns.js +837 -0
- package/src/server/paths.js +107 -0
- package/src/server/public/css/styles.css +2362 -0
- package/src/server/public/js/common.js +32 -0
- package/src/server/public/js/dashboard.js +140 -0
- package/src/server/public/js/import-upload.js +169 -0
- package/src/server/public/js/review-actions.js +379 -0
- package/src/server/public/js/shortcuts.js +242 -0
- package/src/server/public/js/slider.js +104 -0
- package/src/server/public/js/tabs.js +85 -0
- package/src/server/public/js/theme.js +83 -0
- package/src/server/routes/api.js +141 -0
- package/src/server/routes/views.js +68 -0
- package/src/server/security.js +79 -0
- package/src/server/uploadImport.js +227 -0
- package/src/server/urls.js +31 -0
- package/src/server/viewModels.js +366 -0
- package/src/server/views/history.ejs +111 -0
- package/src/server/views/index.ejs +283 -0
- package/src/server/views/layout.ejs +11 -0
- package/src/server/views/partials/footer.ejs +11 -0
- package/src/server/views/partials/header.ejs +93 -0
- package/src/server/views/run-detail.ejs +295 -0
- package/src/shared/packageSpec.js +49 -0
- package/src/shared/text.js +59 -0
package/src/cli/index.js
ADDED
|
@@ -0,0 +1,577 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { Command } from 'commander';
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { execSync } from 'node:child_process';
|
|
7
|
+
import { loadConfig, readConfiguredStorageDir } from './config.js';
|
|
8
|
+
import { captureScreenshots, getSnapshotFilename, assertValidRunId } from './capture.js';
|
|
9
|
+
import { compareSnapshot, sha256, DEFAULT_PIXELMATCH_THRESHOLD } from './compare.js';
|
|
10
|
+
import { buildRunManifest, writeRunManifest, toSqliteTimestamp, getToolVersion, MANIFEST_FILENAME } from './manifest.js';
|
|
11
|
+
import { sanitizeForDisplay } from '../shared/text.js';
|
|
12
|
+
import { resolveStorageRoot } from '../server/paths.js';
|
|
13
|
+
import { generateSummaryMarkdown, writeSummaryReport } from './reporter.js';
|
|
14
|
+
import { EXIT, STDOUT_TARGET, CliError, buildResult, writeResult, sanitizeMessage, redactUrl, toError } from './result.js';
|
|
15
|
+
import { jsonTargetConflict, jsonTargetShapeProblem } from './jsonTarget.js';
|
|
16
|
+
import { createLogger } from './logger.js';
|
|
17
|
+
import { toDisplayPath } from './display.js';
|
|
18
|
+
import { cliCommand, shellQuote } from './invocation.js';
|
|
19
|
+
import { resolveServeOptions, isLoopbackHost, exposedWarning } from './serve.js';
|
|
20
|
+
import { installBrowsers } from './installBrowsers.js';
|
|
21
|
+
import { loadDatabase, DatabaseDriverError } from './database.js';
|
|
22
|
+
|
|
23
|
+
// The database modules load better-sqlite3 (a native module) and the import code loads
|
|
24
|
+
// yauzl, so they are imported only by the commands that need them (see loadDatabase):
|
|
25
|
+
// capture, install-browsers, --help and --version keep working if better-sqlite3 is
|
|
26
|
+
// broken, and test records its result without the database.
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The --json result still owed if the command ends in an error or a crash: set once
|
|
30
|
+
* the target is accepted, cleared once a result was written. state() returns what is
|
|
31
|
+
* known so far ({ run, results }); conflict() re-checks the target right before writing.
|
|
32
|
+
*/
|
|
33
|
+
let pendingJson = null;
|
|
34
|
+
|
|
35
|
+
/** Writes the pending --json result for an error (synchronously: safe right before process.exit). */
|
|
36
|
+
function writePendingJson(error) {
|
|
37
|
+
const pending = pendingJson;
|
|
38
|
+
pendingJson = null; // at most once
|
|
39
|
+
if (!pending) return;
|
|
40
|
+
try {
|
|
41
|
+
const conflict = pending.conflict();
|
|
42
|
+
if (conflict) {
|
|
43
|
+
console.error(`[ERROR] Not writing the JSON result: ${sanitizeMessage(conflict)}\n`);
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
writeResult(buildResult({ command: pending.command, error: toError(error), ...pending.state() }), pending.target);
|
|
47
|
+
} catch (writeErr) {
|
|
48
|
+
console.error(`[ERROR] Could not write the JSON result to ${sanitizeMessage(pending.target)}: ${sanitizeMessage(String(writeErr?.message ?? writeErr))}\n`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Anything that escapes the command handlers is a crash: exit 2, never 1 (which means
|
|
53
|
+
// "visual differences"), and the --json result (if one is owed) says so too.
|
|
54
|
+
function crash(kind) {
|
|
55
|
+
return (reason) => {
|
|
56
|
+
try {
|
|
57
|
+
console.error(`\n[ERROR] ${kind}: ${sanitizeMessage(String(reason?.stack ?? reason))}\n`);
|
|
58
|
+
writePendingJson(reason);
|
|
59
|
+
} finally {
|
|
60
|
+
process.exit(EXIT.ERROR);
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
process.on('unhandledRejection', crash('Unhandled promise rejection'));
|
|
65
|
+
process.on('uncaughtException', crash('Uncaught exception'));
|
|
66
|
+
|
|
67
|
+
function getGitContext() {
|
|
68
|
+
const envBranch = process.env.GITHUB_HEAD_REF || process.env.GITHUB_REF_NAME;
|
|
69
|
+
const envFullSha = process.env.GITHUB_SHA || null;
|
|
70
|
+
try {
|
|
71
|
+
const branch = envBranch || execSync('git rev-parse --abbrev-ref HEAD', { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
|
72
|
+
const commit_sha = envFullSha || execSync('git rev-parse HEAD', { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
|
73
|
+
return { branch, commit_sha, commit_hash: commit_sha.substring(0, 7) };
|
|
74
|
+
} catch {
|
|
75
|
+
return { branch: envBranch || null, commit_sha: envFullSha, commit_hash: envFullSha ? envFullSha.substring(0, 7) : null };
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const NOT_IDLE_NOTE = ' (page never went network-idle, e.g. analytics or long-polling; captured after the load event)';
|
|
80
|
+
|
|
81
|
+
const program = new Command();
|
|
82
|
+
|
|
83
|
+
// Usage errors (unknown option, missing argument...) exit 2; --help and --version exit 0.
|
|
84
|
+
// Set before the subcommands are added so they inherit it.
|
|
85
|
+
program.exitOverride((err) => process.exit(err.exitCode === 0 ? EXIT.PASS : EXIT.ERROR));
|
|
86
|
+
|
|
87
|
+
program
|
|
88
|
+
.name('visual-ci')
|
|
89
|
+
.description('Visual Regression Testing Engine & CI Tool')
|
|
90
|
+
.version(getToolVersion());
|
|
91
|
+
|
|
92
|
+
program
|
|
93
|
+
.command('capture')
|
|
94
|
+
.description('Capture deterministic full-page screenshots across configured viewports')
|
|
95
|
+
.option('-c, --config <path>', 'Path to visual.config.json')
|
|
96
|
+
.option('-r, --run-id <id>', 'Identifier for the test run')
|
|
97
|
+
.option('-u, --base-url <url>', 'Override target baseUrl')
|
|
98
|
+
.option('-o, --output-dir <path>', 'Custom directory to store output screenshots')
|
|
99
|
+
.action(async (options) => {
|
|
100
|
+
try {
|
|
101
|
+
const overrides = {};
|
|
102
|
+
if (options.baseUrl) {
|
|
103
|
+
overrides.baseUrl = options.baseUrl;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const config = loadConfig(options.config, overrides);
|
|
107
|
+
const runId = options.runId || `run_${Date.now()}`;
|
|
108
|
+
|
|
109
|
+
console.log('──────────────────────────────────────────────────────');
|
|
110
|
+
console.log(' Visual Regression Testing Tool: Headless Capture');
|
|
111
|
+
console.log('──────────────────────────────────────────────────────');
|
|
112
|
+
console.log(` Target Base URL : ${redactUrl(config.baseUrl)}`);
|
|
113
|
+
console.log(` Routes : ${config.routes.join(', ')}`);
|
|
114
|
+
console.log(` Viewports : ${config.viewports.map((v) => `${v.name} (${v.width}x${v.height})`).join(', ')}`);
|
|
115
|
+
console.log(` Mask Selectors : ${config.maskSelectors.length > 0 ? config.maskSelectors.join(', ') : '(none)'}`);
|
|
116
|
+
console.log(` Run ID : ${runId}`);
|
|
117
|
+
console.log('──────────────────────────────────────────────────────\n');
|
|
118
|
+
|
|
119
|
+
const startTime = Date.now();
|
|
120
|
+
|
|
121
|
+
const results = await captureScreenshots(config, {
|
|
122
|
+
runId,
|
|
123
|
+
outputDir: options.outputDir || path.join(resolveStorageRoot(config.storageDir), 'runs'),
|
|
124
|
+
onProgress: (snap) => {
|
|
125
|
+
const relPath = path.relative(process.cwd(), snap.filepath);
|
|
126
|
+
console.log(` [OK] ${snap.route} @ ${snap.viewport} (${snap.width}x${snap.height}) -> ${relPath}`);
|
|
127
|
+
if (!snap.networkIdle) console.log(NOT_IDLE_NOTE);
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
const elapsed = ((Date.now() - startTime) / 1000).toFixed(2);
|
|
132
|
+
console.log('\n──────────────────────────────────────────────────────');
|
|
133
|
+
console.log(` Capture Complete: ${results.length} screenshots saved in ${elapsed}s`);
|
|
134
|
+
console.log('──────────────────────────────────────────────────────\n');
|
|
135
|
+
} catch (err) {
|
|
136
|
+
console.error(`\n[ERROR] Capture failed: ${sanitizeMessage(String(err?.message ?? err))}\n`);
|
|
137
|
+
process.exit(EXIT.ERROR);
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* The run folder as far as it can be known before the config is loaded (for the
|
|
143
|
+
* --json guard): storageDir is read on its own, falling back to the default.
|
|
144
|
+
*/
|
|
145
|
+
function guessRunsDir(options, runId) {
|
|
146
|
+
let storageDir;
|
|
147
|
+
try {
|
|
148
|
+
storageDir = readConfiguredStorageDir(options.config) || undefined;
|
|
149
|
+
} catch {
|
|
150
|
+
storageDir = undefined; // loadConfig reports the problem
|
|
151
|
+
}
|
|
152
|
+
return path.join(resolveStorageRoot(storageDir), 'runs', runId);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
program
|
|
156
|
+
.command('test')
|
|
157
|
+
.description('Capture screenshots and compare against baseline golden masters')
|
|
158
|
+
.option('-c, --config <path>', 'Path to visual.config.json')
|
|
159
|
+
.option('-r, --run-id <id>', 'Identifier for the test run')
|
|
160
|
+
.option('-u, --base-url <url>', 'Override target baseUrl')
|
|
161
|
+
.option('--update-baselines', 'Promote all current screenshots to baseline images')
|
|
162
|
+
.option('-s, --summary-file <path>', 'Custom file name or relative path for markdown summary')
|
|
163
|
+
.option('--strict', 'Fail on missing baselines instead of creating them (default when CI=true)')
|
|
164
|
+
.option('--no-strict', 'Create missing baselines from the current screenshots, even in CI')
|
|
165
|
+
.option('--json <file>', 'Also write a machine-readable result (schema visual-ci-result v1) to <file> (relative to the working directory); "-" writes it to stdout and moves all other output to stderr')
|
|
166
|
+
.action(async (options) => {
|
|
167
|
+
const jsonTarget = options.json;
|
|
168
|
+
const log = createLogger({ stdoutReserved: jsonTarget === STDOUT_TARGET });
|
|
169
|
+
const startTime = Date.now();
|
|
170
|
+
const results = [];
|
|
171
|
+
let run = null; // what the JSON result reports about the run, once it is known
|
|
172
|
+
let runsDir = null; // the run folder: guessed before the config is loaded, then exact
|
|
173
|
+
const checkJsonTarget = () => jsonTargetConflict(jsonTarget, { runsDir, summaryFile: options.summaryFile });
|
|
174
|
+
const refuseJsonTarget = (message) => {
|
|
175
|
+
pendingJson = null; // never write to (or delete) a refused target
|
|
176
|
+
return new CliError('INVALID_ARGUMENT', message);
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
try {
|
|
180
|
+
const shapeProblem = jsonTargetShapeProblem(jsonTarget);
|
|
181
|
+
if (shapeProblem) throw refuseJsonTarget(shapeProblem);
|
|
182
|
+
if (jsonTarget !== undefined) {
|
|
183
|
+
pendingJson = { command: 'test', target: jsonTarget, conflict: checkJsonTarget, state: () => ({ run, results }) };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const runId = options.runId || `run_${startTime}`;
|
|
187
|
+
assertValidRunId(runId);
|
|
188
|
+
runsDir = guessRunsDir(options, runId);
|
|
189
|
+
const earlyConflict = checkJsonTarget();
|
|
190
|
+
if (earlyConflict) throw refuseJsonTarget(earlyConflict);
|
|
191
|
+
// The target is accepted: remove a result left by an earlier run, so a reused
|
|
192
|
+
// path never shows an old outcome (this run writes a new one, error or not).
|
|
193
|
+
if (jsonTarget !== undefined && jsonTarget !== STDOUT_TARGET) {
|
|
194
|
+
fs.rmSync(path.resolve(process.cwd(), jsonTarget), { force: true });
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const overrides = {};
|
|
198
|
+
if (options.baseUrl) {
|
|
199
|
+
overrides.baseUrl = options.baseUrl;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const config = loadConfig(options.config, overrides);
|
|
203
|
+
// The database only feeds the dashboard: run.json and the --json result are the
|
|
204
|
+
// run's record (CI never needs the database). Without a working driver, say so once
|
|
205
|
+
// and carry on.
|
|
206
|
+
let database = null;
|
|
207
|
+
try {
|
|
208
|
+
database = await loadDatabase();
|
|
209
|
+
} catch (dbErr) {
|
|
210
|
+
if (!(dbErr instanceof DatabaseDriverError)) throw dbErr;
|
|
211
|
+
log.warn(` [WARN] This run won't appear in the dashboard (run.json and any --json result are still written): ${sanitizeMessage(dbErr.message)}\n`);
|
|
212
|
+
}
|
|
213
|
+
// Same root the dashboard uses (VISUAL_STORAGE_DIR > storageDir > ./storage),
|
|
214
|
+
// so baselines, screenshots and the database always end up together.
|
|
215
|
+
const storageRoot = resolveStorageRoot(config.storageDir);
|
|
216
|
+
const baselinesDir = path.join(storageRoot, 'baselines');
|
|
217
|
+
runsDir = path.join(storageRoot, 'runs', runId);
|
|
218
|
+
const strict = options.strict ?? process.env.CI === 'true';
|
|
219
|
+
const mode = options.updateBaselines ? 'update-baselines' : 'compare';
|
|
220
|
+
// path.join like writeSummaryReport (path.resolve would let "/run.json" through).
|
|
221
|
+
if (options.summaryFile && path.join(runsDir, options.summaryFile) === path.join(runsDir, MANIFEST_FILENAME)) {
|
|
222
|
+
throw new CliError('INVALID_ARGUMENT', `--summary-file cannot be "${options.summaryFile}": that is the run's ${MANIFEST_FILENAME}`);
|
|
223
|
+
}
|
|
224
|
+
const conflict = checkJsonTarget();
|
|
225
|
+
if (conflict) throw refuseJsonTarget(conflict);
|
|
226
|
+
|
|
227
|
+
const gitInfo = getGitContext();
|
|
228
|
+
run = {
|
|
229
|
+
id: runId,
|
|
230
|
+
mode,
|
|
231
|
+
strict,
|
|
232
|
+
baseUrl: config.baseUrl,
|
|
233
|
+
gitInfo,
|
|
234
|
+
createdAt: new Date(startTime),
|
|
235
|
+
threshold: config.threshold,
|
|
236
|
+
runDir: runsDir,
|
|
237
|
+
manifestPath: null,
|
|
238
|
+
summaryPath: null
|
|
239
|
+
};
|
|
240
|
+
|
|
241
|
+
log.info('──────────────────────────────────────────────────────');
|
|
242
|
+
log.info(' Visual Regression Testing Tool: Compare & Test');
|
|
243
|
+
log.info('──────────────────────────────────────────────────────');
|
|
244
|
+
log.info(` Target Base URL : ${redactUrl(config.baseUrl)}`);
|
|
245
|
+
log.info(` Routes : ${config.routes.join(', ')}`);
|
|
246
|
+
log.info(` Viewports : ${config.viewports.map((v) => `${v.name} (${v.width}x${v.height})`).join(', ')}`);
|
|
247
|
+
log.info(` Threshold : ${config.threshold * 100}%`);
|
|
248
|
+
log.info(` Run ID : ${runId}`);
|
|
249
|
+
log.info(` Storage : ${path.relative(process.cwd(), storageRoot) || '.'}`);
|
|
250
|
+
log.info(` Missing baseline: ${strict ? 'fail (strict)' : 'create from current screenshot'}`);
|
|
251
|
+
log.info('──────────────────────────────────────────────────────\n');
|
|
252
|
+
|
|
253
|
+
log.info(' Step 1: Capturing screenshots...');
|
|
254
|
+
const snapshots = await captureScreenshots(config, {
|
|
255
|
+
runId,
|
|
256
|
+
outputDir: path.join(storageRoot, 'runs'),
|
|
257
|
+
onProgress: (snap) => {
|
|
258
|
+
log.info(` 📸 Captured ${snap.route} @ ${snap.viewport}`);
|
|
259
|
+
if (!snap.networkIdle) log.info(NOT_IDLE_NOTE);
|
|
260
|
+
}
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
log.info('\n Step 2: Comparing against baselines...');
|
|
264
|
+
let passedCount = 0;
|
|
265
|
+
let failedCount = 0;
|
|
266
|
+
let newBaselineCount = 0;
|
|
267
|
+
|
|
268
|
+
for (const snap of snapshots) {
|
|
269
|
+
if (options.updateBaselines) {
|
|
270
|
+
fs.mkdirSync(baselinesDir, { recursive: true });
|
|
271
|
+
const baselineFilename = getSnapshotFilename(snap.route, snap.viewport);
|
|
272
|
+
const baselinePath = path.join(baselinesDir, baselineFilename);
|
|
273
|
+
fs.copyFileSync(snap.filepath, baselinePath);
|
|
274
|
+
log.info(` [UPDATED BASELINE] ${snap.route} @ ${snap.viewport}`);
|
|
275
|
+
newBaselineCount++;
|
|
276
|
+
results.push({
|
|
277
|
+
...snap,
|
|
278
|
+
status: 'NEW_BASELINE',
|
|
279
|
+
mismatchPercentage: 0,
|
|
280
|
+
baselinePath,
|
|
281
|
+
baselineSnapshotPath: snap.filepath,
|
|
282
|
+
baselineSha256: sha256(fs.readFileSync(baselinePath))
|
|
283
|
+
});
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const comp = compareSnapshot(snap, {
|
|
288
|
+
baselinesDir,
|
|
289
|
+
diffDir: runsDir,
|
|
290
|
+
allowedThreshold: config.threshold,
|
|
291
|
+
createMissingBaselines: !strict
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
results.push({ ...comp, width: snap.width, height: snap.height });
|
|
295
|
+
|
|
296
|
+
if (comp.status === 'NEW_BASELINE') {
|
|
297
|
+
newBaselineCount++;
|
|
298
|
+
log.info(` [NEW BASELINE] ${comp.route} @ ${comp.viewport} -> Baseline created`);
|
|
299
|
+
} else if (comp.status === 'MISSING_BASELINE') {
|
|
300
|
+
failedCount++;
|
|
301
|
+
const rel = path.relative(process.cwd(), comp.baselinePath);
|
|
302
|
+
log.info(` [FAIL] ${comp.route} @ ${comp.viewport} -> no baseline at ${rel} (create it with --update-baselines and commit it)`);
|
|
303
|
+
} else if (comp.status === 'MATCH') {
|
|
304
|
+
passedCount++;
|
|
305
|
+
log.info(` [PASS] ${comp.route} @ ${comp.viewport} (${comp.mismatchPercentage.toFixed(2)}% mismatch)`);
|
|
306
|
+
} else {
|
|
307
|
+
failedCount++;
|
|
308
|
+
log.info(` [FAIL] ${comp.route} @ ${comp.viewport} (${comp.mismatchPercentage.toFixed(2)}% mismatch > ${config.threshold * 100}% threshold)`);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
const overallStatus = failedCount > 0 ? 'FAILED' : 'PASSED';
|
|
313
|
+
const createdAt = new Date();
|
|
314
|
+
run.createdAt = createdAt; // same timestamp as run.json and the database row
|
|
315
|
+
|
|
316
|
+
// Machine-readable run record next to the screenshots (travels with CI artifacts).
|
|
317
|
+
// Written before the database so a DB failure can't lose it.
|
|
318
|
+
try {
|
|
319
|
+
run.manifestPath = writeRunManifest(buildRunManifest({
|
|
320
|
+
runId,
|
|
321
|
+
createdAt,
|
|
322
|
+
gitInfo,
|
|
323
|
+
status: overallStatus,
|
|
324
|
+
threshold: config.threshold,
|
|
325
|
+
pixelmatchThreshold: DEFAULT_PIXELMATCH_THRESHOLD,
|
|
326
|
+
strict,
|
|
327
|
+
mode,
|
|
328
|
+
runDir: runsDir,
|
|
329
|
+
baselinesDir,
|
|
330
|
+
results
|
|
331
|
+
}), runsDir);
|
|
332
|
+
} catch (manifestErr) {
|
|
333
|
+
log.warn(` [WARN] Failed to write run.json: ${manifestErr.message}`);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// Record test run & snapshots in SQLite database for web review dashboard
|
|
337
|
+
if (database) {
|
|
338
|
+
try {
|
|
339
|
+
const { createTestRun, createSnapshot, getDb } = database;
|
|
340
|
+
const db = getDb(path.join(storageRoot, 'data.sqlite'));
|
|
341
|
+
createTestRun({
|
|
342
|
+
id: runId,
|
|
343
|
+
commit_hash: gitInfo.commit_hash,
|
|
344
|
+
branch: gitInfo.branch,
|
|
345
|
+
status: overallStatus,
|
|
346
|
+
created_at: toSqliteTimestamp(createdAt)
|
|
347
|
+
}, db);
|
|
348
|
+
|
|
349
|
+
for (const r of results) {
|
|
350
|
+
createSnapshot({
|
|
351
|
+
run_id: runId,
|
|
352
|
+
route: r.route,
|
|
353
|
+
viewport: r.viewport,
|
|
354
|
+
baseline_path: r.baselinePath || null,
|
|
355
|
+
baseline_snapshot_path: r.baselineSnapshotPath || null,
|
|
356
|
+
baseline_sha256: r.baselineSha256 || null,
|
|
357
|
+
current_path: r.currentPath || r.filepath,
|
|
358
|
+
diff_path: r.diffPath || null,
|
|
359
|
+
mismatch_percentage: r.mismatchPercentage || 0,
|
|
360
|
+
status: r.status
|
|
361
|
+
}, db);
|
|
362
|
+
}
|
|
363
|
+
} catch (dbErr) {
|
|
364
|
+
log.warn(` [WARN] Failed to record run in database: ${dbErr.message}`);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
const elapsed = ((Date.now() - startTime) / 1000).toFixed(2);
|
|
369
|
+
|
|
370
|
+
// Generate GitHub-flavored markdown summary report
|
|
371
|
+
const summaryMarkdown = generateSummaryMarkdown({
|
|
372
|
+
runId,
|
|
373
|
+
gitInfo,
|
|
374
|
+
threshold: config.threshold,
|
|
375
|
+
elapsed,
|
|
376
|
+
passedCount,
|
|
377
|
+
failedCount,
|
|
378
|
+
newBaselineCount,
|
|
379
|
+
results
|
|
380
|
+
});
|
|
381
|
+
|
|
382
|
+
const summaryOptions = { runsDir };
|
|
383
|
+
if (options.summaryFile) {
|
|
384
|
+
summaryOptions.summaryFileName = options.summaryFile;
|
|
385
|
+
}
|
|
386
|
+
const { runSummaryPath, stepSummaryWritten } = writeSummaryReport(summaryMarkdown, summaryOptions);
|
|
387
|
+
run.summaryPath = runSummaryPath;
|
|
388
|
+
run.durationMs = Date.now() - startTime;
|
|
389
|
+
|
|
390
|
+
const result = buildResult({ command: 'test', run, results });
|
|
391
|
+
let jsonFile = null;
|
|
392
|
+
if (jsonTarget !== undefined) {
|
|
393
|
+
// Again now that the run folder exists, so symlinks and hard links resolve.
|
|
394
|
+
const lateConflict = checkJsonTarget();
|
|
395
|
+
if (lateConflict) throw refuseJsonTarget(lateConflict);
|
|
396
|
+
try {
|
|
397
|
+
jsonFile = writeResult(result, jsonTarget);
|
|
398
|
+
pendingJson = null;
|
|
399
|
+
} catch (writeErr) {
|
|
400
|
+
pendingJson = null; // it would fail again
|
|
401
|
+
throw new CliError('INTERNAL', `Could not write the JSON result to ${jsonTarget}: ${writeErr.message}`, { cause: writeErr });
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
log.info('\n──────────────────────────────────────────────────────');
|
|
406
|
+
log.info(' Visual Regression Test Summary');
|
|
407
|
+
log.info('──────────────────────────────────────────────────────');
|
|
408
|
+
log.info(` Total Snapshots : ${results.length}`);
|
|
409
|
+
log.info(` Passed (Match) : ${passedCount}`);
|
|
410
|
+
log.info(` Failed (Diff) : ${failedCount}`);
|
|
411
|
+
log.info(` New Baselines : ${newBaselineCount}`);
|
|
412
|
+
log.info(` Execution Time : ${elapsed}s`);
|
|
413
|
+
log.info('──────────────────────────────────────────────────────');
|
|
414
|
+
log.info(` Review Dashboard : http://localhost:4000/runs/${runId}`);
|
|
415
|
+
if (runSummaryPath) {
|
|
416
|
+
const relSummary = path.relative(process.cwd(), runSummaryPath);
|
|
417
|
+
log.info(` Summary Report : ${relSummary}`);
|
|
418
|
+
}
|
|
419
|
+
if (jsonFile && jsonFile !== STDOUT_TARGET) {
|
|
420
|
+
log.info(` JSON Result : ${toDisplayPath(jsonFile)}`); // absolute when outside the working directory
|
|
421
|
+
}
|
|
422
|
+
if (stepSummaryWritten) {
|
|
423
|
+
log.info(' CI Step Summary : Appended to GITHUB_STEP_SUMMARY');
|
|
424
|
+
}
|
|
425
|
+
log.info('──────────────────────────────────────────────────────\n');
|
|
426
|
+
|
|
427
|
+
if (result.exit_code === EXIT.DIFF) {
|
|
428
|
+
log.error(`[FAILURE] Visual regressions detected in ${failedCount} snapshot(s).\n`);
|
|
429
|
+
} else {
|
|
430
|
+
log.info('[SUCCESS] All snapshots passed without visual regressions!\n');
|
|
431
|
+
}
|
|
432
|
+
process.exit(result.exit_code);
|
|
433
|
+
} catch (err) {
|
|
434
|
+
// If anything here throws, the crash handler still writes the pending JSON and exits 2.
|
|
435
|
+
log.error(`\n[ERROR] Test run failed: ${sanitizeMessage(String(err?.message ?? err))}\n`);
|
|
436
|
+
if (run) run.durationMs = Date.now() - startTime;
|
|
437
|
+
writePendingJson(err);
|
|
438
|
+
process.exit(EXIT.ERROR);
|
|
439
|
+
}
|
|
440
|
+
});
|
|
441
|
+
|
|
442
|
+
/** Zip (by magic bytes or extension) or folder; a run.json file means its folder. */
|
|
443
|
+
function detectImportSource(input) {
|
|
444
|
+
const abs = path.resolve(process.cwd(), input);
|
|
445
|
+
let st;
|
|
446
|
+
try {
|
|
447
|
+
st = fs.statSync(abs);
|
|
448
|
+
} catch {
|
|
449
|
+
throw new Error(`Not found: ${input}`);
|
|
450
|
+
}
|
|
451
|
+
if (st.isDirectory()) return { kind: 'dir', path: abs };
|
|
452
|
+
if (!st.isFile()) throw new Error(`${input} is not a zip file or a folder`);
|
|
453
|
+
if (path.basename(abs) === MANIFEST_FILENAME) return { kind: 'dir', path: path.dirname(abs) };
|
|
454
|
+
|
|
455
|
+
const head = Buffer.alloc(4);
|
|
456
|
+
const fd = fs.openSync(abs, 'r');
|
|
457
|
+
try {
|
|
458
|
+
fs.readSync(fd, head, 0, 4, 0);
|
|
459
|
+
} finally {
|
|
460
|
+
fs.closeSync(fd);
|
|
461
|
+
}
|
|
462
|
+
const magic = head.toString('latin1');
|
|
463
|
+
if (magic === 'PK\x03\x04' || magic === 'PK\x05\x06' || path.extname(abs).toLowerCase() === '.zip') {
|
|
464
|
+
return { kind: 'zip', file: abs };
|
|
465
|
+
}
|
|
466
|
+
throw new Error(`${input} is not a zip file or a folder`);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
program
|
|
470
|
+
.command('import')
|
|
471
|
+
.description('Import CI run(s) (the visual-regression-diffs artifact zip, or a run folder) into the local dashboard')
|
|
472
|
+
.argument('<path>', 'Artifact .zip, a folder holding <run-id>/run.json, or a run folder')
|
|
473
|
+
.option('-c, --config <path>', 'Path to visual.config.json (only storageDir is used)')
|
|
474
|
+
.option('-r, --run-id <id>', 'Local id for the imported run (only when importing a single run)')
|
|
475
|
+
.action(async (input, options) => {
|
|
476
|
+
let db;
|
|
477
|
+
let closeDb;
|
|
478
|
+
try {
|
|
479
|
+
const storageRoot = resolveStorageRoot(readConfiguredStorageDir(options.config) || undefined);
|
|
480
|
+
const source = detectImportSource(input);
|
|
481
|
+
const dbModule = await loadDatabase();
|
|
482
|
+
const { importRuns } = await import('../server/importRuns.js');
|
|
483
|
+
closeDb = dbModule.closeDb;
|
|
484
|
+
db = dbModule.getDb(path.join(storageRoot, 'data.sqlite'));
|
|
485
|
+
const { runs } = await importRuns(source, { storageRoot, db, runId: options.runId });
|
|
486
|
+
|
|
487
|
+
const dashboardPort = process.env.PORT || 4000; // the port `visual-ci serve` uses by default
|
|
488
|
+
const fresh = runs.filter((r) => !r.alreadyImported).length;
|
|
489
|
+
const where = path.relative(process.cwd(), storageRoot) || '.';
|
|
490
|
+
console.log(fresh === 0
|
|
491
|
+
? `\n Nothing new to import into ${where}: already imported`
|
|
492
|
+
: `\n Imported ${fresh} run${fresh === 1 ? '' : 's'} into ${where}`);
|
|
493
|
+
for (const run of runs) {
|
|
494
|
+
const notes = [];
|
|
495
|
+
if (run.renamedFrom) notes.push(`renamed from ${run.renamedFrom}: that id was already taken`);
|
|
496
|
+
if (run.alreadyImported) notes.push('already imported, nothing changed');
|
|
497
|
+
const plural = run.snapshots === 1 ? '' : 's';
|
|
498
|
+
console.log(` ${run.id} ${run.status}, ${run.snapshots} snapshot${plural}${notes.length ? ` (${notes.join('; ')})` : ''}`);
|
|
499
|
+
console.log(` http://localhost:${dashboardPort}${run.url}`);
|
|
500
|
+
}
|
|
501
|
+
// With the same -c, so the dashboard shows the storage the runs went into.
|
|
502
|
+
const serveArgs = options.config ? ` -c ${shellQuote(options.config)}` : '';
|
|
503
|
+
console.log(`\n Open the dashboard with \`${cliCommand()} serve${serveArgs}\` to review them.\n`);
|
|
504
|
+
} catch (err) {
|
|
505
|
+
// Backstop: messages can quote names from the archive (importRuns already escapes them).
|
|
506
|
+
console.error(`\n[ERROR] Import failed: ${sanitizeForDisplay(String(err?.message ?? err))}\n`);
|
|
507
|
+
process.exitCode = EXIT.ERROR;
|
|
508
|
+
} finally {
|
|
509
|
+
if (db) closeDb?.();
|
|
510
|
+
}
|
|
511
|
+
});
|
|
512
|
+
|
|
513
|
+
program
|
|
514
|
+
.command('serve')
|
|
515
|
+
.description('Start the web review dashboard (and its REST API)')
|
|
516
|
+
.option('-p, --port <n>', 'Port to listen on, 0 for any free port (default: $PORT, else 4000)')
|
|
517
|
+
.option('--host <host>', 'Interface to listen on (default: $VISUAL_CI_HOST, else 127.0.0.1; 0.0.0.0 exposes the dashboard, which has no login, on your network)')
|
|
518
|
+
.option('-c, --config <path>', 'Path to visual.config.json (only storageDir is used)')
|
|
519
|
+
.action(async (options) => {
|
|
520
|
+
try {
|
|
521
|
+
const { port, host } = resolveServeOptions(options);
|
|
522
|
+
// Same storage root as `test` and `import` with the same config. The dashboard
|
|
523
|
+
// reads it from VISUAL_STORAGE_DIR, which still wins when it is already set.
|
|
524
|
+
if (options.config) {
|
|
525
|
+
process.env.VISUAL_STORAGE_DIR = resolveStorageRoot(readConfiguredStorageDir(options.config) || undefined);
|
|
526
|
+
}
|
|
527
|
+
await loadDatabase(); // fail here, with the fix, rather than on the first request
|
|
528
|
+
const { startServer } = await import('../server/app.js');
|
|
529
|
+
const { closeDb } = await import('../server/db.js');
|
|
530
|
+
const server = startServer({ port, host });
|
|
531
|
+
// Installed before the URL is printed, so a signal right after it is handled too.
|
|
532
|
+
const stop = (signal) => {
|
|
533
|
+
console.log(`\n ${signal} received: stopping the dashboard.`);
|
|
534
|
+
server.close(() => {
|
|
535
|
+
closeDb();
|
|
536
|
+
process.exit(EXIT.PASS);
|
|
537
|
+
});
|
|
538
|
+
server.closeAllConnections(); // keep-alive connections would hold close() open
|
|
539
|
+
};
|
|
540
|
+
process.once('SIGINT', stop);
|
|
541
|
+
process.once('SIGTERM', stop);
|
|
542
|
+
await new Promise((resolve, reject) => {
|
|
543
|
+
server.once('listening', resolve);
|
|
544
|
+
server.once('error', reject);
|
|
545
|
+
});
|
|
546
|
+
server.on('error', crash('Dashboard server error'));
|
|
547
|
+
if (!isLoopbackHost(host)) console.warn(`\n${exposedWarning(host)}\n`);
|
|
548
|
+
} catch (err) {
|
|
549
|
+
const reason = err?.code === 'EADDRINUSE' ? `port ${err.port} on ${err.address} is already in use`
|
|
550
|
+
: err?.code === 'EACCES' ? `no permission to listen on ${err.address}:${err.port}`
|
|
551
|
+
: String(err?.message ?? err);
|
|
552
|
+
console.error(`\n[ERROR] Could not start the dashboard: ${sanitizeMessage(reason)}\n`);
|
|
553
|
+
process.exit(EXIT.ERROR);
|
|
554
|
+
}
|
|
555
|
+
});
|
|
556
|
+
|
|
557
|
+
program
|
|
558
|
+
.command('install-browsers')
|
|
559
|
+
.description("Download the Chromium build that this version of visual-ci's Playwright needs")
|
|
560
|
+
.option('--with-deps', 'Also install the system libraries Chromium needs (Linux; runs the package manager, with sudo when not root)')
|
|
561
|
+
.option('--dry-run', 'Only print what would be installed, and where')
|
|
562
|
+
.action(async (options) => {
|
|
563
|
+
const { exitCode, code, signal, error } = await installBrowsers({ withDeps: options.withDeps, dryRun: options.dryRun });
|
|
564
|
+
if (error) {
|
|
565
|
+
console.error(`\n[ERROR] Could not run the Playwright installer: ${sanitizeMessage(String(error?.message ?? error))}\n`);
|
|
566
|
+
} else if (exitCode !== EXIT.PASS) {
|
|
567
|
+
console.error(`\n[ERROR] The Playwright installer failed (${signal ? `signal ${signal}` : `exit code ${code}`}).\n`);
|
|
568
|
+
}
|
|
569
|
+
process.exit(exitCode);
|
|
570
|
+
});
|
|
571
|
+
|
|
572
|
+
// Fallback / default action
|
|
573
|
+
if (process.argv.length <= 2) {
|
|
574
|
+
program.help();
|
|
575
|
+
} else {
|
|
576
|
+
program.parseAsync(process.argv).catch(crash('Command failed'));
|
|
577
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { spawn as nodeSpawn } from 'node:child_process';
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { EXIT } from './result.js';
|
|
5
|
+
|
|
6
|
+
const require = createRequire(import.meta.url);
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The Playwright CLI of the Playwright this package depends on (its "bin" entry), so
|
|
10
|
+
* the browser that gets installed is the build our pinned Playwright launches.
|
|
11
|
+
* (`npx playwright` could run a different Playwright, e.g. one of the project's own.)
|
|
12
|
+
*
|
|
13
|
+
* @param {(id: string) => string} [resolve=require.resolve]
|
|
14
|
+
* @returns {string} Absolute path of playwright's cli.js
|
|
15
|
+
*/
|
|
16
|
+
export function playwrightCliPath(resolve = require.resolve) {
|
|
17
|
+
const pkgFile = resolve('playwright/package.json');
|
|
18
|
+
const pkg = require(pkgFile);
|
|
19
|
+
const bin = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.playwright;
|
|
20
|
+
if (!bin) throw new Error(`No "playwright" bin in ${pkgFile}`);
|
|
21
|
+
return path.resolve(path.dirname(pkgFile), bin);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Arguments for the Playwright CLI: `install [--with-deps] [--dry-run] chromium`.
|
|
26
|
+
*
|
|
27
|
+
* @param {{ withDeps?: boolean, dryRun?: boolean }} [options]
|
|
28
|
+
* @returns {string[]}
|
|
29
|
+
*/
|
|
30
|
+
export function installArgs({ withDeps = false, dryRun = false } = {}) {
|
|
31
|
+
return ['install', ...(withDeps ? ['--with-deps'] : []), ...(dryRun ? ['--dry-run'] : []), 'chromium'];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Runs our Playwright's `install chromium` with this Node.js, its output going
|
|
36
|
+
* straight to the terminal.
|
|
37
|
+
*
|
|
38
|
+
* @param {object} [options]
|
|
39
|
+
* @param {boolean} [options.withDeps] - Also install the system libraries (Linux; uses sudo when not root)
|
|
40
|
+
* @param {boolean} [options.dryRun] - Only print what would be installed
|
|
41
|
+
* @param {typeof nodeSpawn} [options.spawn] - For tests
|
|
42
|
+
* @param {string} [options.cliPath] - Defaults to playwrightCliPath()
|
|
43
|
+
* @returns {Promise<{ exitCode: number, code?: number|null, signal?: string|null, error?: Error }>}
|
|
44
|
+
* exitCode is EXIT.PASS when Playwright succeeded, otherwise EXIT.ERROR
|
|
45
|
+
*/
|
|
46
|
+
export function installBrowsers({ withDeps = false, dryRun = false, spawn = nodeSpawn, cliPath } = {}) {
|
|
47
|
+
return new Promise((resolve) => {
|
|
48
|
+
let child;
|
|
49
|
+
try {
|
|
50
|
+
const cli = cliPath ?? playwrightCliPath();
|
|
51
|
+
child = spawn(process.execPath, [cli, ...installArgs({ withDeps, dryRun })], { stdio: 'inherit' });
|
|
52
|
+
} catch (error) {
|
|
53
|
+
resolve({ exitCode: EXIT.ERROR, error });
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
child.once('error', (error) => resolve({ exitCode: EXIT.ERROR, error }));
|
|
57
|
+
child.once('exit', (code, signal) => resolve({ exitCode: code === 0 ? EXIT.PASS : EXIT.ERROR, code, signal }));
|
|
58
|
+
});
|
|
59
|
+
}
|