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.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +953 -2
  3. package/package.json +76 -4
  4. package/src/ci/actionReport.js +340 -0
  5. package/src/ci/prComment.js +420 -0
  6. package/src/cli/capture.js +243 -0
  7. package/src/cli/compare.js +190 -0
  8. package/src/cli/config.js +287 -0
  9. package/src/cli/database.js +69 -0
  10. package/src/cli/display.js +119 -0
  11. package/src/cli/errors.js +17 -0
  12. package/src/cli/index.js +577 -0
  13. package/src/cli/installBrowsers.js +59 -0
  14. package/src/cli/invocation.js +66 -0
  15. package/src/cli/jsonTarget.js +100 -0
  16. package/src/cli/logger.js +15 -0
  17. package/src/cli/manifest.js +139 -0
  18. package/src/cli/naming.js +60 -0
  19. package/src/cli/reporter.js +172 -0
  20. package/src/cli/result.js +225 -0
  21. package/src/cli/serve.js +64 -0
  22. package/src/server/app.js +135 -0
  23. package/src/server/db.js +691 -0
  24. package/src/server/importRuns.js +837 -0
  25. package/src/server/paths.js +107 -0
  26. package/src/server/public/css/styles.css +2362 -0
  27. package/src/server/public/js/common.js +32 -0
  28. package/src/server/public/js/dashboard.js +140 -0
  29. package/src/server/public/js/import-upload.js +169 -0
  30. package/src/server/public/js/review-actions.js +379 -0
  31. package/src/server/public/js/shortcuts.js +242 -0
  32. package/src/server/public/js/slider.js +104 -0
  33. package/src/server/public/js/tabs.js +85 -0
  34. package/src/server/public/js/theme.js +83 -0
  35. package/src/server/routes/api.js +141 -0
  36. package/src/server/routes/views.js +68 -0
  37. package/src/server/security.js +79 -0
  38. package/src/server/uploadImport.js +227 -0
  39. package/src/server/urls.js +31 -0
  40. package/src/server/viewModels.js +366 -0
  41. package/src/server/views/history.ejs +111 -0
  42. package/src/server/views/index.ejs +283 -0
  43. package/src/server/views/layout.ejs +11 -0
  44. package/src/server/views/partials/footer.ejs +11 -0
  45. package/src/server/views/partials/header.ejs +93 -0
  46. package/src/server/views/run-detail.ejs +295 -0
  47. package/src/shared/packageSpec.js +49 -0
  48. package/src/shared/text.js +59 -0
@@ -0,0 +1,691 @@
1
+ import crypto from 'node:crypto';
2
+ import Database from 'better-sqlite3';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { getStorageRoot, resolvePngInside } from './paths.js';
6
+
7
+ /**
8
+ * Default database path: data.sqlite inside the storage root (see getStorageRoot).
9
+ *
10
+ * @returns {string}
11
+ */
12
+ export function getDefaultDbPath() {
13
+ return path.join(getStorageRoot(), 'data.sqlite');
14
+ }
15
+
16
+ /**
17
+ * Throws if better-sqlite3 cannot load its native binary. It does that on the first
18
+ * `new Database()`, not when it is imported, so this opens (and closes) an in-memory one.
19
+ */
20
+ export function assertDriverLoads() {
21
+ new Database(':memory:').close();
22
+ }
23
+
24
+ let dbInstance = null;
25
+
26
+ /**
27
+ * Initializes and returns the SQLite database instance.
28
+ * Sets WAL mode for high concurrency and executes schema creation.
29
+ *
30
+ * @param {string} [customDbPath] - Optional custom path for the SQLite file
31
+ * @returns {Database.Database} SQLite database connection
32
+ */
33
+ export function initDb(customDbPath) {
34
+ const dbPath = customDbPath || getDefaultDbPath();
35
+
36
+ // Ensure parent directory exists
37
+ fs.mkdirSync(path.dirname(dbPath), { recursive: true });
38
+
39
+ if (dbInstance) {
40
+ try {
41
+ dbInstance.close();
42
+ } catch (_) {}
43
+ dbInstance = null;
44
+ }
45
+
46
+ const db = new Database(dbPath);
47
+
48
+ // Enable WAL mode for optimal concurrent performance
49
+ db.pragma('journal_mode = WAL');
50
+ db.pragma('foreign_keys = ON');
51
+
52
+ // Schema creation
53
+ db.exec(`
54
+ CREATE TABLE IF NOT EXISTS test_runs (
55
+ id TEXT PRIMARY KEY,
56
+ commit_hash TEXT,
57
+ branch TEXT,
58
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
59
+ status TEXT NOT NULL, -- 'PASSED', 'FAILED', 'APPROVED', 'REJECTED'
60
+ imported_at DATETIME -- set when the run was imported (visual-ci import), else NULL
61
+ );
62
+
63
+ CREATE TABLE IF NOT EXISTS snapshots (
64
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
65
+ run_id TEXT NOT NULL,
66
+ route TEXT NOT NULL,
67
+ viewport TEXT NOT NULL,
68
+ baseline_path TEXT, -- shared baseline that approval promotes into
69
+ baseline_snapshot_path TEXT, -- per-run copy of the baseline actually compared
70
+ baseline_sha256 TEXT, -- hash of that baseline ('none' if there was none), to refuse stale approvals
71
+ current_path TEXT NOT NULL,
72
+ diff_path TEXT,
73
+ mismatch_percentage REAL DEFAULT 0,
74
+ status TEXT NOT NULL, -- 'MATCH', 'DIFF', 'NEW_BASELINE', 'MISSING_BASELINE', 'APPROVED', 'REJECTED'
75
+ FOREIGN KEY (run_id) REFERENCES test_runs(id) ON DELETE CASCADE
76
+ );
77
+
78
+ CREATE INDEX IF NOT EXISTS idx_snapshots_run_id ON snapshots(run_id);
79
+ `);
80
+
81
+ // Migrate databases created before per-run baselines (and imports) existed. IMMEDIATE
82
+ // locking so a dashboard and CLI opening the same old database at once don't both add
83
+ // the columns.
84
+ db.transaction(() => {
85
+ const columns = new Set(db.prepare('PRAGMA table_info(snapshots)').all().map((c) => c.name));
86
+ for (const column of ['baseline_snapshot_path', 'baseline_sha256']) {
87
+ if (!columns.has(column)) db.exec(`ALTER TABLE snapshots ADD COLUMN ${column} TEXT`);
88
+ }
89
+ const runColumns = new Set(db.prepare('PRAGMA table_info(test_runs)').all().map((c) => c.name));
90
+ if (!runColumns.has('imported_at')) db.exec('ALTER TABLE test_runs ADD COLUMN imported_at DATETIME');
91
+ }).immediate();
92
+
93
+ // History page lookups (route + viewport across runs). IF NOT EXISTS keeps it
94
+ // safe for existing databases.
95
+ db.exec('CREATE INDEX IF NOT EXISTS idx_snapshots_viewport_route ON snapshots(viewport, route)');
96
+
97
+ dbInstance = db;
98
+ return db;
99
+ }
100
+
101
+ /**
102
+ * Returns the singleton or active database instance.
103
+ *
104
+ * @param {string} [dbPath] - Optional path
105
+ * @returns {Database.Database}
106
+ */
107
+ export function getDb(dbPath) {
108
+ if (!dbInstance || (dbPath && dbInstance.name !== dbPath)) {
109
+ dbInstance = initDb(dbPath);
110
+ }
111
+ return dbInstance;
112
+ }
113
+
114
+ /**
115
+ * Closes the active database connection (useful for testing and graceful shutdowns).
116
+ */
117
+ export function closeDb() {
118
+ if (dbInstance) {
119
+ dbInstance.close();
120
+ dbInstance = null;
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Inserts a new test run record.
126
+ *
127
+ * @param {object} run - Test run metadata
128
+ * @param {string} run.id - Unique run ID
129
+ * @param {string} [run.commit_hash] - Git commit hash
130
+ * @param {string} [run.branch] - Git branch
131
+ * @param {string} run.status - 'PASSED', 'FAILED', 'APPROVED', 'REJECTED'
132
+ * @param {string} [run.created_at] - 'YYYY-MM-DD HH:MM:SS' UTC (defaults to now)
133
+ * @param {string} [run.imported_at] - Same format; only for runs imported from elsewhere
134
+ * @param {Database.Database} [db] - Optional DB instance
135
+ * @returns {object} The created run
136
+ */
137
+ export function createTestRun(run, db = getDb()) {
138
+ // created_at defaults to SQLite's CURRENT_TIMESTAMP ('YYYY-MM-DD HH:MM:SS', UTC);
139
+ // callers may pass the same format so the row matches the run's run.json.
140
+ const stmt = db.prepare(`
141
+ INSERT INTO test_runs (id, commit_hash, branch, status, created_at, imported_at)
142
+ VALUES (?, ?, ?, ?, COALESCE(?, CURRENT_TIMESTAMP), ?)
143
+ `);
144
+
145
+ stmt.run(
146
+ run.id,
147
+ run.commit_hash || null,
148
+ run.branch || null,
149
+ run.status || 'PASSED',
150
+ run.created_at || null,
151
+ run.imported_at || null
152
+ );
153
+
154
+ return getTestRunById(run.id, db);
155
+ }
156
+
157
+ /**
158
+ * Inserts a snapshot record associated with a test run.
159
+ *
160
+ * @param {object} snap - Snapshot metadata
161
+ * @param {Database.Database} [db] - Optional DB instance
162
+ * @returns {object} The created snapshot with its ID
163
+ */
164
+ export function createSnapshot(snap, db = getDb()) {
165
+ const stmt = db.prepare(`
166
+ INSERT INTO snapshots (
167
+ run_id, route, viewport, baseline_path, baseline_snapshot_path, baseline_sha256,
168
+ current_path, diff_path, mismatch_percentage, status
169
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
170
+ `);
171
+
172
+ const info = stmt.run(
173
+ snap.run_id,
174
+ snap.route,
175
+ snap.viewport,
176
+ snap.baseline_path || null,
177
+ snap.baseline_snapshot_path || null,
178
+ snap.baseline_sha256 || null,
179
+ snap.current_path,
180
+ snap.diff_path || null,
181
+ snap.mismatch_percentage !== undefined ? snap.mismatch_percentage : 0,
182
+ snap.status || 'MATCH'
183
+ );
184
+
185
+ return getSnapshotById(info.lastInsertRowid, db);
186
+ }
187
+
188
+ /**
189
+ * Fetches all test runs ordered by creation date descending (newest insert first
190
+ * when several share the same second),
191
+ * augmented with snapshot counts (total, diffs, matches).
192
+ *
193
+ * @param {Database.Database} [db] - Optional DB instance
194
+ * @returns {Array<object>}
195
+ */
196
+ export function getAllTestRuns(db = getDb()) {
197
+ const stmt = db.prepare(`
198
+ SELECT
199
+ r.*,
200
+ COUNT(s.id) as total_snapshots,
201
+ SUM(CASE WHEN s.status IN ('DIFF', 'MISSING_BASELINE') THEN 1 ELSE 0 END) as diff_count,
202
+ SUM(CASE WHEN s.status = 'MATCH' THEN 1 ELSE 0 END) as match_count,
203
+ SUM(CASE WHEN s.status = 'NEW_BASELINE' THEN 1 ELSE 0 END) as new_baseline_count,
204
+ SUM(CASE WHEN s.status = 'APPROVED' THEN 1 ELSE 0 END) as approved_count,
205
+ SUM(CASE WHEN s.status = 'REJECTED' THEN 1 ELSE 0 END) as rejected_count
206
+ FROM test_runs r
207
+ LEFT JOIN snapshots s ON s.run_id = r.id
208
+ GROUP BY r.id
209
+ ORDER BY r.created_at DESC, r.rowid DESC
210
+ `);
211
+ return stmt.all();
212
+ }
213
+
214
+ /**
215
+ * Fetches a single test run by its ID.
216
+ *
217
+ * @param {string} id - Run ID
218
+ * @param {Database.Database} [db] - Optional DB instance
219
+ * @returns {object|null}
220
+ */
221
+ export function getTestRunById(id, db = getDb()) {
222
+ const stmt = db.prepare(`
223
+ SELECT
224
+ r.*,
225
+ COUNT(s.id) as total_snapshots,
226
+ SUM(CASE WHEN s.status IN ('DIFF', 'MISSING_BASELINE') THEN 1 ELSE 0 END) as diff_count,
227
+ SUM(CASE WHEN s.status = 'MATCH' THEN 1 ELSE 0 END) as match_count,
228
+ SUM(CASE WHEN s.status = 'NEW_BASELINE' THEN 1 ELSE 0 END) as new_baseline_count,
229
+ SUM(CASE WHEN s.status = 'APPROVED' THEN 1 ELSE 0 END) as approved_count,
230
+ SUM(CASE WHEN s.status = 'REJECTED' THEN 1 ELSE 0 END) as rejected_count
231
+ FROM test_runs r
232
+ LEFT JOIN snapshots s ON s.run_id = r.id
233
+ WHERE r.id = ?
234
+ GROUP BY r.id
235
+ `);
236
+ return stmt.get(id) || null;
237
+ }
238
+
239
+ /**
240
+ * Fetches all snapshots belonging to a given run ID.
241
+ *
242
+ * @param {string} runId - Run ID
243
+ * @param {Database.Database} [db] - Optional DB instance
244
+ * @returns {Array<object>}
245
+ */
246
+ export function getSnapshotsByRunId(runId, db = getDb()) {
247
+ const stmt = db.prepare(`
248
+ SELECT * FROM snapshots
249
+ WHERE run_id = ?
250
+ ORDER BY id ASC
251
+ `);
252
+ return stmt.all(runId);
253
+ }
254
+
255
+ /**
256
+ * Fetches a single snapshot by its primary key ID.
257
+ *
258
+ * @param {number|string} id - Snapshot ID
259
+ * @param {Database.Database} [db] - Optional DB instance
260
+ * @returns {object|null}
261
+ */
262
+ export function getSnapshotById(id, db = getDb()) {
263
+ const stmt = db.prepare('SELECT * FROM snapshots WHERE id = ?');
264
+ return stmt.get(id) || null;
265
+ }
266
+
267
+ // ─── History (one route + viewport across runs) ─────────────────────────────
268
+
269
+ /**
270
+ * Distinct routes recorded for a viewport (the history page maps them to slugs).
271
+ *
272
+ * @param {string} viewport
273
+ * @param {Database.Database} [db] - Optional DB instance
274
+ * @returns {string[]}
275
+ */
276
+ export function getRoutesForViewport(viewport, db = getDb()) {
277
+ return db.prepare('SELECT DISTINCT route FROM snapshots WHERE viewport = ?').pluck().all(viewport);
278
+ }
279
+
280
+ /**
281
+ * Every distinct route/viewport pair in the database (e.g. to pre-render history pages).
282
+ *
283
+ * @param {Database.Database} [db] - Optional DB instance
284
+ * @returns {Array<{ route: string, viewport: string }>}
285
+ */
286
+ export function getRouteViewportPairs(db = getDb()) {
287
+ return db.prepare('SELECT DISTINCT route, viewport FROM snapshots ORDER BY route, viewport').all();
288
+ }
289
+
290
+ /**
291
+ * Snapshots of the given routes at one viewport, joined with their run, newest run
292
+ * first (insertion order breaks ties within the same second, like getAllTestRuns).
293
+ *
294
+ * @param {object} options
295
+ * @param {string[]} options.routes - Route spellings to include (empty -> [])
296
+ * @param {string} options.viewport
297
+ * @param {number} [options.limit=100]
298
+ * @param {Database.Database} [db] - Optional DB instance
299
+ * @returns {Array<object>} snapshot columns plus created_at, branch, commit_hash, run_status
300
+ */
301
+ export function getSnapshotHistory({ routes, viewport, limit = 100 }, db = getDb()) {
302
+ if (!routes || routes.length === 0) return [];
303
+ const placeholders = routes.map(() => '?').join(', ');
304
+ return db.prepare(`
305
+ SELECT s.*, r.created_at, r.branch, r.commit_hash, r.status AS run_status
306
+ FROM snapshots s
307
+ JOIN test_runs r ON r.id = s.run_id
308
+ WHERE s.viewport = ? AND s.route IN (${placeholders})
309
+ ORDER BY r.created_at DESC, r.rowid DESC, s.id DESC
310
+ LIMIT ?
311
+ `).all(viewport, ...routes, limit);
312
+ }
313
+
314
+ /**
315
+ * Recalculates and updates the parent test_run status based on all its child snapshots:
316
+ * - If any snapshot is 'DIFF' or 'MISSING_BASELINE', run is 'FAILED'
317
+ * - If any snapshot is 'REJECTED', run is 'REJECTED'
318
+ * - If all snapshots are 'APPROVED', 'MATCH', or 'NEW_BASELINE':
319
+ * - If at least one was 'APPROVED', run is 'APPROVED'
320
+ * - Else, run is 'PASSED'
321
+ *
322
+ * @param {string} runId - Parent run ID
323
+ * @param {Database.Database} [db] - Optional DB instance
324
+ * @returns {string} New run status
325
+ */
326
+ export function recalculateRunStatus(runId, db = getDb()) {
327
+ const snapshots = getSnapshotsByRunId(runId, db);
328
+ if (!snapshots || snapshots.length === 0) {
329
+ return 'PASSED';
330
+ }
331
+
332
+ let hasDiff = false;
333
+ let hasRejected = false;
334
+ let hasApproved = false;
335
+
336
+ for (const s of snapshots) {
337
+ if (s.status === 'DIFF' || s.status === 'MISSING_BASELINE') hasDiff = true;
338
+ if (s.status === 'REJECTED') hasRejected = true;
339
+ if (s.status === 'APPROVED') hasApproved = true;
340
+ }
341
+
342
+ let newStatus = 'PASSED';
343
+ if (hasRejected) {
344
+ newStatus = 'REJECTED';
345
+ } else if (hasDiff) {
346
+ newStatus = 'FAILED';
347
+ } else if (hasApproved) {
348
+ newStatus = 'APPROVED';
349
+ }
350
+
351
+ db.prepare('UPDATE test_runs SET status = ? WHERE id = ?').run(newStatus, runId);
352
+ return newStatus;
353
+ }
354
+
355
+ const hashFile = (file) => crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
356
+
357
+ /** Snapshot statuses that still need a review decision. */
358
+ export const PENDING_STATUSES = Object.freeze(['DIFF', 'MISSING_BASELINE']);
359
+
360
+ const STALE_BASELINE_MESSAGE =
361
+ 'Conflict: the baseline has changed since this run (a newer run was probably approved). ' +
362
+ 'Re-run the visual tests and review the new result instead.';
363
+
364
+ /**
365
+ * Refuses to approve a run whose baseline has since been replaced (e.g. a newer run was
366
+ * approved), which would otherwise silently revert the newer baseline.
367
+ * - baseline_sha256 'none': the run found no baseline, so there must still be none.
368
+ * - any other hash: the baseline must still have that hash.
369
+ * - NULL (rows recorded before hashes existed): unchecked, except legacy
370
+ * MISSING_BASELINE rows, which must still have no baseline.
371
+ * Approving is always allowed when the baseline already equals this run's screenshot,
372
+ * since the copy then changes nothing.
373
+ */
374
+ function assertBaselineUnchanged(snapshot, source, target) {
375
+ if (isBaselineStale(snapshot, { source, target })) throw new Error(STALE_BASELINE_MESSAGE);
376
+ }
377
+
378
+ /**
379
+ * The rule behind assertBaselineUnchanged, without throwing: true when approving would be
380
+ * refused because the baseline at `target` is no longer the one the run compared against.
381
+ *
382
+ * @param {object} snapshot - Snapshot row (baseline_sha256, status)
383
+ * @param {object} files
384
+ * @param {string} files.source - This run's screenshot
385
+ * @param {string} files.target - The shared baseline approval would replace
386
+ * @param {(file: string) => string} [files.hash] - SHA-256 hex of a file (e.g. cached)
387
+ * @returns {boolean}
388
+ */
389
+ export function isBaselineStale(snapshot, { source, target, hash = hashFile }) {
390
+ const recorded = snapshot.baseline_sha256 ||
391
+ (snapshot.status === 'MISSING_BASELINE' ? 'none' : null);
392
+ if (!recorded) return false;
393
+
394
+ const exists = fs.existsSync(target);
395
+ const actual = exists ? hash(target) : 'none';
396
+ if (actual === recorded) return false;
397
+ if (exists && fs.existsSync(source) && actual === hash(source)) return false; // already this screenshot: no-op
398
+ return true;
399
+ }
400
+
401
+ function conflictError(message, conflicts) {
402
+ const err = new Error(message);
403
+ err.status = 409;
404
+ err.conflicts = conflicts;
405
+ return err;
406
+ }
407
+
408
+ const conflictEntry = (s) => ({ id: s.id, route: s.route, viewport: s.viewport });
409
+
410
+ /**
411
+ * Works out what approving one snapshot would do, without changing anything.
412
+ * Allowlist: the source must be a .png in <storage>/runs/ and the target a .png in
413
+ * <storage>/baselines/ (symlinks resolved). Also runs the stale-baseline check.
414
+ * (Like before, resolving a not-yet-existing target may create its parent folder.)
415
+ *
416
+ * @param {object} snapshot - Snapshot row
417
+ * @param {string} [storageRoot] - Defaults to getStorageRoot()
418
+ * @returns {{ snapshot: object, source: string|null, target: string|null }}
419
+ * source/target are null when the row has no files to promote (status-only approval)
420
+ * @throws {Error} "Access denied: ..." or "Conflict: ..." (with err.conflicts)
421
+ */
422
+ export function planApproval(snapshot, storageRoot = getStorageRoot()) {
423
+ if (!snapshot.baseline_path || !snapshot.current_path) {
424
+ return { snapshot, source: null, target: null };
425
+ }
426
+ const source = resolvePngInside(snapshot.current_path, path.join(storageRoot, 'runs'));
427
+ const target = resolvePngInside(snapshot.baseline_path, path.join(storageRoot, 'baselines'), { mustExist: false });
428
+ try {
429
+ assertBaselineUnchanged(snapshot, source, target);
430
+ } catch (err) {
431
+ throw conflictError(err.message, [conflictEntry(snapshot)]);
432
+ }
433
+ // What the baseline looked like when it was checked; re-checked just before writing.
434
+ return { snapshot, source, target, seen: baselineState(target) };
435
+ }
436
+
437
+ /** Hash of a baseline file, or 'none' when it doesn't exist. */
438
+ function baselineState(target) {
439
+ return fs.existsSync(target) ? hashFile(target) : 'none';
440
+ }
441
+
442
+ /** Hidden sibling path used for temp copies and backups (never served: not a ".png"). */
443
+ function siblingPath(target, kind) {
444
+ return path.join(path.dirname(target), `.${path.basename(target)}.${crypto.randomBytes(8).toString('hex')}.${kind}`);
445
+ }
446
+
447
+ /**
448
+ * Puts baselines back after a failed batch: each backup (a hard link or copy of the
449
+ * old file) is renamed back over its target, which is atomic and copies nothing;
450
+ * targets that didn't exist before are removed. Never throws: returns the targets it
451
+ * could not restore (their backups are kept on disk so nothing is lost).
452
+ */
453
+ function restoreBaselines(written) {
454
+ const failed = [];
455
+ for (const { target, backup } of [...written].reverse()) {
456
+ try {
457
+ if (backup && isSameFile(backup, target)) {
458
+ // The swap never happened: the target is still the old file (the backup is a
459
+ // hard link to it), and rename() between two links to one file is a no-op.
460
+ fs.rmSync(backup, { force: true });
461
+ } else if (backup) {
462
+ fs.renameSync(backup, target);
463
+ } else {
464
+ fs.rmSync(target, { force: true });
465
+ }
466
+ } catch (restoreErr) {
467
+ console.error(`[ERROR] Could not restore baseline ${target}: ${restoreErr.message}`);
468
+ failed.push(backup ? `${target} (backup kept at ${backup})` : target);
469
+ }
470
+ }
471
+ return failed;
472
+ }
473
+
474
+ function isSameFile(a, b) {
475
+ try {
476
+ const sa = fs.statSync(a);
477
+ const sb = fs.statSync(b);
478
+ return sa.ino === sb.ino && sa.dev === sb.dev;
479
+ } catch {
480
+ return false;
481
+ }
482
+ }
483
+
484
+ /** Keeps the current baseline under a hidden name: a hard link if possible, else a copy. */
485
+ function backUpBaseline(target) {
486
+ const backup = siblingPath(target, 'bak');
487
+ try {
488
+ fs.linkSync(target, backup);
489
+ } catch {
490
+ fs.copyFileSync(target, backup, fs.constants.COPYFILE_EXCL);
491
+ }
492
+ return backup;
493
+ }
494
+
495
+ /**
496
+ * Promotes every planned screenshot and records the approvals, all or nothing. For each
497
+ * file: re-check that the baseline is still what planning saw (else 409 Conflict),
498
+ * copy the screenshot to a hidden temp file, keep the old baseline as a hidden backup,
499
+ * then rename the temp file over the target. All status changes happen in one
500
+ * transaction. On any failure, backups are renamed back, new baselines removed, and the
501
+ * error rethrown (mentioning any baseline that could not be restored).
502
+ */
503
+ function executeApprovalPlans(plans, db) {
504
+ const writes = plans.filter((p) => p.target);
505
+ const written = []; // { target, backup } for every target that may have changed
506
+ let tmp = null;
507
+ try {
508
+ for (const plan of writes) {
509
+ const { snapshot, source, target, seen } = plan;
510
+ if (baselineState(target) !== seen) {
511
+ throw conflictError(
512
+ 'Conflict: a baseline changed while the batch was being approved. Re-run the visual tests and review the new result instead.',
513
+ [conflictEntry(snapshot)]
514
+ );
515
+ }
516
+ tmp = siblingPath(target, 'tmp');
517
+ fs.copyFileSync(source, tmp, fs.constants.COPYFILE_EXCL);
518
+ const backup = seen === 'none' ? null : backUpBaseline(target);
519
+ written.push({ target, backup }); // before the rename, so a half-done step is still rolled back
520
+ fs.renameSync(tmp, target);
521
+ tmp = null;
522
+ }
523
+
524
+ const runIds = [...new Set(plans.map((p) => p.snapshot.run_id))];
525
+ const runStatuses = db.transaction(() => {
526
+ const update = db.prepare('UPDATE snapshots SET status = ? WHERE id = ?');
527
+ for (const { snapshot } of plans) update.run('APPROVED', snapshot.id);
528
+ return Object.fromEntries(runIds.map((runId) => [runId, recalculateRunStatus(runId, db)]));
529
+ })();
530
+
531
+ for (const { backup } of written) {
532
+ if (!backup) continue;
533
+ try {
534
+ fs.rmSync(backup, { force: true });
535
+ } catch (cleanupErr) {
536
+ console.error(`[WARN] Could not remove baseline backup ${backup}: ${cleanupErr.message}`);
537
+ }
538
+ }
539
+ return runStatuses;
540
+ } catch (err) {
541
+ if (tmp) {
542
+ try {
543
+ fs.rmSync(tmp, { force: true });
544
+ } catch (cleanupErr) {
545
+ console.error(`[WARN] Could not remove temp file ${tmp}: ${cleanupErr.message}`);
546
+ }
547
+ }
548
+ const notRestored = restoreBaselines(written);
549
+ if (notRestored.length) {
550
+ err.message += ` Additionally, these baselines could not be restored: ${notRestored.join('; ')}.`;
551
+ }
552
+ throw err;
553
+ }
554
+ }
555
+
556
+ /**
557
+ * Approves several snapshots at once, all or nothing:
558
+ * 1. Plans every snapshot first (path allowlist + stale-baseline check). Any conflicts
559
+ * are collected and reported together in one "Conflict" error (err.status 409,
560
+ * err.conflicts [{ id, route, viewport }]) before anything is changed. An
561
+ * "Access denied" or "not found" error is thrown as for a single approval.
562
+ * 2. Refuses (as a Conflict) when two snapshots would write the same baseline file.
563
+ * 3. Copies every screenshot over its baseline and marks the snapshots APPROVED,
564
+ * recalculating each affected run once; on any failure, everything is rolled back.
565
+ *
566
+ * @param {Array<number|string>} snapshotIds
567
+ * @param {Database.Database} [db]
568
+ * @param {object} [options]
569
+ * @param {string} [options.storageRoot] - Storage root (defaults to getStorageRoot())
570
+ * @returns {{ approved: number[], snapshots: object[], runStatuses: Record<string, string> }}
571
+ */
572
+ export function approveSnapshots(snapshotIds, db = getDb(), options = {}) {
573
+ const storageRoot = options.storageRoot || getStorageRoot();
574
+ // Approving the same snapshot twice in one call is the same as approving it once.
575
+ const ids = [...new Map(snapshotIds.map((id) => [String(id), id])).values()];
576
+ const snapshots = ids.map((id) => {
577
+ const snapshot = getSnapshotById(id, db);
578
+ if (!snapshot) throw new Error(`Snapshot with id ${id} not found.`);
579
+ return snapshot;
580
+ });
581
+
582
+ const plans = [];
583
+ const conflicts = [];
584
+ for (const snapshot of snapshots) {
585
+ try {
586
+ plans.push(planApproval(snapshot, storageRoot));
587
+ } catch (err) {
588
+ if (!err.conflicts) throw err;
589
+ conflicts.push(...err.conflicts);
590
+ }
591
+ }
592
+ if (conflicts.length) {
593
+ if (snapshots.length === 1) throw conflictError(STALE_BASELINE_MESSAGE, conflicts);
594
+ const list = conflicts.map((c) => `${c.route} @ ${c.viewport}`).join(', ');
595
+ throw conflictError(
596
+ `Conflict: the baseline has changed since this run for ${conflicts.length} of ${snapshots.length} ` +
597
+ `snapshot(s) (${list}); a newer run was probably approved. Nothing was approved. ` +
598
+ 'Re-run the visual tests and review the new result instead.',
599
+ conflicts
600
+ );
601
+ }
602
+
603
+ const byTarget = new Map();
604
+ for (const plan of plans.filter((p) => p.target)) {
605
+ const other = byTarget.get(plan.target);
606
+ if (other) {
607
+ throw conflictError(
608
+ `Conflict: ${other.snapshot.route} @ ${other.snapshot.viewport} and ${plan.snapshot.route} @ ` +
609
+ `${plan.snapshot.viewport} would both write the baseline ${path.basename(plan.target)}. ` +
610
+ 'Nothing was approved; approve them one at a time.',
611
+ [conflictEntry(other.snapshot), conflictEntry(plan.snapshot)]
612
+ );
613
+ }
614
+ byTarget.set(plan.target, plan);
615
+ }
616
+
617
+ const runStatuses = executeApprovalPlans(plans, db);
618
+ return {
619
+ approved: snapshots.map((s) => s.id),
620
+ snapshots: snapshots.map((s) => getSnapshotById(s.id, db)),
621
+ runStatuses
622
+ };
623
+ }
624
+
625
+ /**
626
+ * Approves a snapshot:
627
+ * 1. Copies current_path screenshot over baseline_path on disk
628
+ * 2. Updates snapshot status in SQLite to 'APPROVED'
629
+ * 3. Recalculates parent test_run status
630
+ *
631
+ * @param {number|string} snapshotId - Snapshot ID
632
+ * @param {Database.Database} [db] - Optional DB instance
633
+ * @param {object} [options]
634
+ * @param {string} [options.storageRoot] - Storage root (defaults to getStorageRoot())
635
+ * @returns {object} Updated snapshot and new parent run status
636
+ */
637
+ export function approveSnapshot(snapshotId, db = getDb(), options = {}) {
638
+ const result = approveSnapshots([snapshotId], db, options);
639
+ const snapshot = result.snapshots[0];
640
+ return {
641
+ snapshot,
642
+ runStatus: result.runStatuses[snapshot.run_id]
643
+ };
644
+ }
645
+
646
+ /**
647
+ * Approves every snapshot of a run that still needs review (DIFF or MISSING_BASELINE),
648
+ * all or nothing (see approveSnapshots).
649
+ *
650
+ * @param {string} runId
651
+ * @param {Database.Database} [db]
652
+ * @param {object} [options]
653
+ * @param {string} [options.storageRoot] - Storage root (defaults to getStorageRoot())
654
+ * @returns {{ approved: number[], runStatus: string, snapshots: object[] }}
655
+ * With nothing pending, approved is [] and no file or row is touched.
656
+ * @throws {Error} "Run with id ... not found.", "Access denied: ..." or "Conflict: ..."
657
+ */
658
+ export function approveAllPending(runId, db = getDb(), options = {}) {
659
+ const run = getTestRunById(runId, db);
660
+ if (!run) throw new Error(`Run with id ${runId} not found.`);
661
+
662
+ const pending = getSnapshotsByRunId(runId, db).filter((s) => PENDING_STATUSES.includes(s.status));
663
+ if (pending.length === 0) return { approved: [], runStatus: run.status, snapshots: [] };
664
+
665
+ const result = approveSnapshots(pending.map((s) => s.id), db, options);
666
+ return { approved: result.approved, runStatus: result.runStatuses[runId], snapshots: result.snapshots };
667
+ }
668
+
669
+ /**
670
+ * Rejects a snapshot:
671
+ * 1. Updates snapshot status in SQLite to 'REJECTED'
672
+ * 2. Updates parent run status to 'REJECTED'
673
+ *
674
+ * @param {number|string} snapshotId - Snapshot ID
675
+ * @param {Database.Database} [db] - Optional DB instance
676
+ * @returns {object} Updated snapshot and new parent run status
677
+ */
678
+ export function rejectSnapshot(snapshotId, db = getDb()) {
679
+ const snapshot = getSnapshotById(snapshotId, db);
680
+ if (!snapshot) {
681
+ throw new Error(`Snapshot with id ${snapshotId} not found.`);
682
+ }
683
+
684
+ db.prepare('UPDATE snapshots SET status = ? WHERE id = ?').run('REJECTED', snapshotId);
685
+ const runStatus = recalculateRunStatus(snapshot.run_id, db);
686
+
687
+ return {
688
+ snapshot: getSnapshotById(snapshotId, db),
689
+ runStatus
690
+ };
691
+ }