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
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { Transform } from 'node:stream';
|
|
5
|
+
import { pipeline } from 'node:stream/promises';
|
|
6
|
+
import { importRuns, ImportError } from './importRuns.js';
|
|
7
|
+
import { sanitizeForDisplay } from '../shared/text.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* POST /api/imports: a CI artifact zip uploaded from the dashboard, imported with the
|
|
11
|
+
* same importRuns() the CLI uses.
|
|
12
|
+
*
|
|
13
|
+
* The body is the raw zip (no multipart), streamed to a dot-named temp file inside the
|
|
14
|
+
* storage root (never served: /storage refuses dot-named segments) and removed again
|
|
15
|
+
* whatever happens. Guards, in order:
|
|
16
|
+
* 415 Content-Type is not a zip / octet-stream
|
|
17
|
+
* 503 another import is running in this process (with Retry-After; no queue)
|
|
18
|
+
* 413 Content-Length, or the bytes actually received, exceed the upload cap
|
|
19
|
+
* 507 not enough free disk space (when the platform can tell)
|
|
20
|
+
* then importRuns' own 400/409/413/422. Messages are always sanitised.
|
|
21
|
+
*
|
|
22
|
+
* Who may call it is decided earlier, by the same Host allowlist and CSRF checks as
|
|
23
|
+
* approving a snapshot (see security.js).
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
export const DEFAULT_MAX_UPLOAD_BYTES = 200 * 1024 * 1024;
|
|
27
|
+
export const UPLOAD_CONTENT_TYPES = Object.freeze(['application/zip', 'application/x-zip-compressed', 'application/octet-stream']);
|
|
28
|
+
export const RETRY_AFTER_SECONDS = 15;
|
|
29
|
+
export const DEFAULT_IDLE_TIMEOUT_MS = 30 * 1000;
|
|
30
|
+
const MIN_FREE_BYTES = 1024 * 1024 * 1024;
|
|
31
|
+
const UPLOAD_PREFIX = '.upload-';
|
|
32
|
+
const STALE_UPLOAD_MS = 60 * 60 * 1000;
|
|
33
|
+
|
|
34
|
+
/** "200 MB", "512 KB", "900 bytes" */
|
|
35
|
+
export function formatBytes(bytes) {
|
|
36
|
+
if (bytes >= 1024 * 1024) return `${Math.round(bytes / (1024 * 1024))} MB`;
|
|
37
|
+
if (bytes >= 1024) return `${Math.round(bytes / 1024)} KB`;
|
|
38
|
+
return `${bytes} bytes`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The upload cap: VISUAL_IMPORT_MAX_UPLOAD_BYTES (a positive integer) or 200 MB.
|
|
43
|
+
* Read on every request so it can be changed without a restart (and by tests).
|
|
44
|
+
*/
|
|
45
|
+
export function maxUploadBytes() {
|
|
46
|
+
const raw = process.env.VISUAL_IMPORT_MAX_UPLOAD_BYTES;
|
|
47
|
+
if (raw === undefined || raw.trim() === '') return DEFAULT_MAX_UPLOAD_BYTES;
|
|
48
|
+
const n = Number(raw);
|
|
49
|
+
return Number.isSafeInteger(n) && n > 0 ? n : DEFAULT_MAX_UPLOAD_BYTES;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* How long an upload may go without receiving a byte before it is dropped (so a stalled
|
|
54
|
+
* client can't hold the one-import lock): VISUAL_IMPORT_IDLE_TIMEOUT_MS or 30 s.
|
|
55
|
+
*/
|
|
56
|
+
export function idleTimeoutMs() {
|
|
57
|
+
const raw = process.env.VISUAL_IMPORT_IDLE_TIMEOUT_MS;
|
|
58
|
+
if (raw === undefined || raw.trim() === '') return DEFAULT_IDLE_TIMEOUT_MS;
|
|
59
|
+
const n = Number(raw);
|
|
60
|
+
return Number.isSafeInteger(n) && n > 0 ? n : DEFAULT_IDLE_TIMEOUT_MS;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Free space the disk must have before an upload is accepted: max(2 x cap, 1 GB). */
|
|
64
|
+
export const requiredFreeBytes = (cap) => Math.max(2 * cap, MIN_FREE_BYTES);
|
|
65
|
+
|
|
66
|
+
let busy = false;
|
|
67
|
+
|
|
68
|
+
/** True while an upload is being received or imported (one at a time per process). */
|
|
69
|
+
export function isImportBusy() {
|
|
70
|
+
return busy;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Refuses with 507 when any of `dirs` is on a disk with less than `needed` bytes free.
|
|
75
|
+
* Each folder is checked on its own: the upload lands in the storage root, but the
|
|
76
|
+
* archive is unpacked next to runs/ or inside it when runs/ is another filesystem.
|
|
77
|
+
* Skipped where fs.statfs is missing or fails (e.g. unsupported filesystems).
|
|
78
|
+
*/
|
|
79
|
+
async function assertFreeSpace(dirs, needed) {
|
|
80
|
+
if (typeof fs.promises.statfs !== 'function') return;
|
|
81
|
+
for (const dir of dirs) {
|
|
82
|
+
let stats;
|
|
83
|
+
try {
|
|
84
|
+
stats = await fs.promises.statfs(dir);
|
|
85
|
+
} catch {
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
const free = Number(stats.bavail) * Number(stats.bsize);
|
|
89
|
+
if (!Number.isFinite(free)) continue;
|
|
90
|
+
if (free < needed) {
|
|
91
|
+
throw new ImportError(507, `Not enough free disk space to import: ${formatBytes(free)} free, at least ${formatBytes(needed)} needed.`);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** A stack trace for the log: every line sanitised, the line breaks kept. */
|
|
97
|
+
const loggableStack = (err) => String(err?.stack || err?.message || err).split('\n').map(sanitizeForDisplay).join('\n');
|
|
98
|
+
|
|
99
|
+
/** Removes .upload-* temp files over an hour old (left by a crash). Never follows links. */
|
|
100
|
+
async function removeStaleUploads(storageRoot, now = Date.now()) {
|
|
101
|
+
let names;
|
|
102
|
+
try {
|
|
103
|
+
names = await fs.promises.readdir(storageRoot);
|
|
104
|
+
} catch {
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
for (const name of names) {
|
|
108
|
+
if (!name.startsWith(UPLOAD_PREFIX)) continue;
|
|
109
|
+
const file = path.join(storageRoot, name);
|
|
110
|
+
try {
|
|
111
|
+
const st = await fs.promises.lstat(file);
|
|
112
|
+
if (st.isFile() && now - st.mtimeMs > STALE_UPLOAD_MS) await fs.promises.rm(file, { force: true });
|
|
113
|
+
} catch { /* not worth failing an upload over */ }
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function mediaType(req) {
|
|
118
|
+
return String(req.headers['content-type'] || '').split(';')[0].trim().toLowerCase();
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Sends an error. When the request body was not (fully) read, the connection is closed
|
|
123
|
+
* after the response and the rest of the body is discarded rather than stored.
|
|
124
|
+
*/
|
|
125
|
+
function sendError(req, res, status, message, { bodyUnread = false, headers = {} } = {}) {
|
|
126
|
+
if (res.headersSent || res.destroyed) return;
|
|
127
|
+
if (bodyUnread) res.set('Connection', 'close');
|
|
128
|
+
res.set(headers);
|
|
129
|
+
res.status(status).json({ success: false, error: sanitizeForDisplay(message) });
|
|
130
|
+
if (bodyUnread) {
|
|
131
|
+
req.unpipe();
|
|
132
|
+
req.resume();
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Express handler body for POST /api/imports. Never rejects: every outcome is a response
|
|
138
|
+
* (or nothing, when the client went away).
|
|
139
|
+
*
|
|
140
|
+
* @param {import('express').Request} req
|
|
141
|
+
* @param {import('express').Response} res
|
|
142
|
+
* @param {object} options
|
|
143
|
+
* @param {string} options.storageRoot
|
|
144
|
+
* @param {import('better-sqlite3').Database} options.db
|
|
145
|
+
* @param {number} [options.maxBytes] - Upload cap (defaults to maxUploadBytes())
|
|
146
|
+
* @param {number} [options.idleMs] - Drop the upload after this long without data (defaults to idleTimeoutMs())
|
|
147
|
+
*/
|
|
148
|
+
export async function handleImportUpload(req, res, { storageRoot, db, maxBytes = maxUploadBytes(), idleMs = idleTimeoutMs() }) {
|
|
149
|
+
const type = mediaType(req);
|
|
150
|
+
if (!UPLOAD_CONTENT_TYPES.includes(type)) {
|
|
151
|
+
return sendError(req, res, 415,
|
|
152
|
+
`Upload the artifact as a raw .zip body (Content-Type ${UPLOAD_CONTENT_TYPES.join(', ')}), got "${type || 'none'}".`,
|
|
153
|
+
{ bodyUnread: true });
|
|
154
|
+
}
|
|
155
|
+
if (busy) {
|
|
156
|
+
return sendError(req, res, 503, 'Another import is in progress. Try again when it has finished.',
|
|
157
|
+
{ bodyUnread: true, headers: { 'Retry-After': String(RETRY_AFTER_SECONDS) } });
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
busy = true;
|
|
161
|
+
// pipeline() destroys `req` on ANY error (e.g. the temp file can't be created), so
|
|
162
|
+
// only a destroyed socket means the client went away.
|
|
163
|
+
const { socket } = req;
|
|
164
|
+
let tempFile = null;
|
|
165
|
+
let bodyDone = false;
|
|
166
|
+
let idleTimer = null;
|
|
167
|
+
let reply; // sent only after the temp file is gone and the lock is free
|
|
168
|
+
try {
|
|
169
|
+
const declared = req.headers['content-length'];
|
|
170
|
+
if (declared !== undefined && Number(declared) > maxBytes) {
|
|
171
|
+
throw new ImportError(413, `The upload is larger than the ${formatBytes(maxBytes)} limit.`);
|
|
172
|
+
}
|
|
173
|
+
const runsDir = path.join(storageRoot, 'runs');
|
|
174
|
+
await fs.promises.mkdir(runsDir, { recursive: true });
|
|
175
|
+
await assertFreeSpace([storageRoot, runsDir], requiredFreeBytes(maxBytes));
|
|
176
|
+
await removeStaleUploads(storageRoot);
|
|
177
|
+
|
|
178
|
+
tempFile = path.join(storageRoot, `${UPLOAD_PREFIX}${crypto.randomBytes(12).toString('hex')}.zip`);
|
|
179
|
+
// A client that stops sending is disconnected; that takes the client-abort path below.
|
|
180
|
+
idleTimer = setTimeout(() => socket.destroy(), idleMs);
|
|
181
|
+
let received = 0;
|
|
182
|
+
const cap = new Transform({
|
|
183
|
+
transform(chunk, _encoding, callback) {
|
|
184
|
+
idleTimer.refresh();
|
|
185
|
+
received += chunk.length;
|
|
186
|
+
if (received > maxBytes) return callback(new ImportError(413, `The upload is larger than the ${formatBytes(maxBytes)} limit.`));
|
|
187
|
+
return callback(null, chunk);
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
await pipeline(req, cap, fs.createWriteStream(tempFile, { flags: 'wx', mode: 0o600 }));
|
|
191
|
+
clearTimeout(idleTimer);
|
|
192
|
+
bodyDone = true;
|
|
193
|
+
if (received === 0) throw new ImportError(400, 'The upload was empty: send the artifact .zip as the request body.');
|
|
194
|
+
|
|
195
|
+
const { runs } = await importRuns({ kind: 'zip', file: tempFile }, { storageRoot, db });
|
|
196
|
+
// 201 when at least one run was created; 200 when everything was already imported.
|
|
197
|
+
reply = {
|
|
198
|
+
status: runs.some((r) => !r.alreadyImported) ? 201 : 200,
|
|
199
|
+
body: {
|
|
200
|
+
success: true,
|
|
201
|
+
runs: runs.map(({ id, url, status, snapshots, renamedFrom, alreadyImported }) => ({
|
|
202
|
+
id, url, status, snapshots,
|
|
203
|
+
...(renamedFrom ? { renamedFrom } : {}),
|
|
204
|
+
...(alreadyImported ? { alreadyImported } : {})
|
|
205
|
+
}))
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
} catch (err) {
|
|
209
|
+
if (socket.destroyed && !(err instanceof ImportError)) {
|
|
210
|
+
reply = null; // the client aborted (or stalled and was dropped): nobody to answer
|
|
211
|
+
} else if (err instanceof ImportError) {
|
|
212
|
+
reply = { status: err.status, error: err.message };
|
|
213
|
+
} else {
|
|
214
|
+
// Details (paths, stack) go to the server log only, never to the client.
|
|
215
|
+
console.error(`[ERROR] Import upload failed:\n${loggableStack(err)}`);
|
|
216
|
+
reply = { status: 500, error: `Import failed because of a server error (${err.code ?? 'see the server log'}).` };
|
|
217
|
+
}
|
|
218
|
+
} finally {
|
|
219
|
+
clearTimeout(idleTimer);
|
|
220
|
+
if (tempFile) await fs.promises.rm(tempFile, { force: true }).catch(() => {});
|
|
221
|
+
busy = false;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
if (!reply || res.destroyed) return;
|
|
225
|
+
if (reply.error !== undefined) sendError(req, res, reply.status, reply.error, { bodyUnread: !bodyDone });
|
|
226
|
+
else res.status(reply.status).json(reply.body);
|
|
227
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Base-path handling for the dashboard's templates.
|
|
3
|
+
*
|
|
4
|
+
* Every local URL in the views goes through url(), so the same templates render at
|
|
5
|
+
* the site root (live server) or under a sub-path (static GitHub Pages build).
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** '' for the site root, otherwise '/segment' with a leading slash and no trailing one. */
|
|
9
|
+
export function normalizeBase(base) {
|
|
10
|
+
let normalized = String(base || '').trim().replace(/\/+$/, '');
|
|
11
|
+
if (normalized && !normalized.startsWith('/')) normalized = `/${normalized}`;
|
|
12
|
+
return normalized;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** url() for a given base: prefixes local paths; a missing path stays '' (e.g. no screenshot). */
|
|
16
|
+
export function makeUrl(base) {
|
|
17
|
+
const prefix = normalizeBase(base);
|
|
18
|
+
return (p) => (p ? `${prefix}${p}` : '');
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Render locals for a base path and mode, always supplied together so `url()`,
|
|
23
|
+
* `data-base` and `data-mode` can never disagree. Pass these as render options
|
|
24
|
+
* instead of mutating app.locals (which live requests share).
|
|
25
|
+
*
|
|
26
|
+
* @param {{ base?: string, mode?: 'live' | 'static' }} [options]
|
|
27
|
+
*/
|
|
28
|
+
export function pageLocals({ base = '', mode = 'live' } = {}) {
|
|
29
|
+
if (mode !== 'live' && mode !== 'static') throw new Error(`Unknown page mode "${mode}"`);
|
|
30
|
+
return { base: normalizeBase(base), mode, url: makeUrl(base) };
|
|
31
|
+
}
|
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {
|
|
5
|
+
isBaselineStale,
|
|
6
|
+
getAllTestRuns,
|
|
7
|
+
getTestRunById,
|
|
8
|
+
getSnapshotsByRunId,
|
|
9
|
+
getRoutesForViewport,
|
|
10
|
+
getSnapshotHistory,
|
|
11
|
+
PENDING_STATUSES
|
|
12
|
+
} from './db.js';
|
|
13
|
+
import { getStorageRoot, isInside } from './paths.js';
|
|
14
|
+
import { getRouteSlug, getSnapshotFilename } from '../cli/naming.js';
|
|
15
|
+
|
|
16
|
+
// Data shaping for the server-rendered views, kept out of the routes so the same
|
|
17
|
+
// models can feed other renderers (e.g. a static build). Image URLs are app-relative
|
|
18
|
+
// ("/storage/..."); templates prefix them with url() for the configured base path.
|
|
19
|
+
|
|
20
|
+
// runs/<id>/<file>, runs/<id>/baselines/<file> or baselines/<file>, taken from the end
|
|
21
|
+
export function knownStorageTail(parts) {
|
|
22
|
+
const n = parts.length;
|
|
23
|
+
if (n >= 4 && parts[n - 4] === 'runs' && parts[n - 2] === 'baselines') return parts.slice(n - 4);
|
|
24
|
+
if (n >= 3 && parts[n - 3] === 'runs') return parts.slice(n - 3);
|
|
25
|
+
if (n >= 2 && parts[n - 2] === 'baselines') return parts.slice(n - 2);
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Maps a stored file path to its "/storage/..." URL, relative to the storage root.
|
|
31
|
+
* (Searching the path for "/storage/" broke with a custom storageDir, or when the
|
|
32
|
+
* project itself lives under a folder named "storage".)
|
|
33
|
+
*
|
|
34
|
+
* @param {string|null} filePath - Path recorded in the database
|
|
35
|
+
* @param {string} [storageRoot] - Absolute storage root (defaults to getStorageRoot())
|
|
36
|
+
* @returns {string|null} "/storage/<encoded segments>", or null when it can't be served
|
|
37
|
+
*/
|
|
38
|
+
export function toWebUrl(filePath, storageRoot = getStorageRoot()) {
|
|
39
|
+
if (!filePath) return null;
|
|
40
|
+
let segments;
|
|
41
|
+
const rel = path.relative(storageRoot, path.resolve(filePath));
|
|
42
|
+
if (rel && rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel)) {
|
|
43
|
+
segments = rel.split(path.sep);
|
|
44
|
+
} else {
|
|
45
|
+
// Recorded under another root (e.g. /app/storage inside Docker, viewed on the
|
|
46
|
+
// host): keep the trailing runs/... or baselines/... part. The /storage
|
|
47
|
+
// middleware still allowlists whatever this produces.
|
|
48
|
+
segments = knownStorageTail(filePath.split(/[\\/]/));
|
|
49
|
+
}
|
|
50
|
+
return segments ? `/storage/${segments.map(encodeURIComponent).join('/')}` : null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Adds baselineUrl / currentUrl / diffUrl to a snapshot row.
|
|
55
|
+
*/
|
|
56
|
+
export function snapshotViewModel(s, storageRoot = getStorageRoot()) {
|
|
57
|
+
return {
|
|
58
|
+
...s,
|
|
59
|
+
// Show the baseline this run was compared against (its own copy), not today's
|
|
60
|
+
// shared file. Older rows have no copy and fall back to the shared baseline.
|
|
61
|
+
// Runs that found no baseline ('none', or legacy MISSING_BASELINE rows) have none to show,
|
|
62
|
+
// even after being approved or rejected.
|
|
63
|
+
baselineUrl: s.baseline_sha256 === 'none' || s.status === 'MISSING_BASELINE'
|
|
64
|
+
? null
|
|
65
|
+
: toWebUrl(s.baseline_snapshot_path || s.baseline_path, storageRoot),
|
|
66
|
+
currentUrl: toWebUrl(s.current_path, storageRoot),
|
|
67
|
+
diffUrl: toWebUrl(s.diff_path, storageRoot)
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Snapshot status counts shown in the dashboard's Snapshots column, in display order.
|
|
72
|
+
const SNAPSHOT_COUNT_PARTS = [
|
|
73
|
+
{ key: 'diff_count', label: 'diff', cls: 'diff-count' }, // DIFF + MISSING_BASELINE (pending review)
|
|
74
|
+
{ key: 'rejected_count', label: 'rejected', cls: 'rejected-count' },
|
|
75
|
+
{ key: 'new_baseline_count', label: 'new baseline', cls: 'new-count' },
|
|
76
|
+
{ key: 'approved_count', label: 'approved', cls: 'approved-count' },
|
|
77
|
+
{ key: 'match_count', label: 'match', cls: 'match-count' }
|
|
78
|
+
];
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Non-zero snapshot counts of a run row from getAllTestRuns(), e.g.
|
|
82
|
+
* [{ count: 2, label: 'new baseline', cls: 'new-count' }]. A baseline-only run reads
|
|
83
|
+
* "2 new baseline" rather than "0 match"; an approved run "2 approved".
|
|
84
|
+
*
|
|
85
|
+
* @param {object} run
|
|
86
|
+
* @returns {{ count: number, label: string, cls: string }[]}
|
|
87
|
+
*/
|
|
88
|
+
export function snapshotCounts(run) {
|
|
89
|
+
return SNAPSHOT_COUNT_PARTS
|
|
90
|
+
.map(({ key, label, cls }) => ({ count: Number(run[key]) || 0, label, cls }))
|
|
91
|
+
.filter((part) => part.count > 0);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** 'YYYY-MM-DD HH:MM:SS' (SQLite UTC) -> ISO 8601 with Z, or null for anything else. */
|
|
95
|
+
export function sqliteUtcToIso(value) {
|
|
96
|
+
const m = /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})$/.exec(String(value ?? ''));
|
|
97
|
+
return m ? `${m[1]}T${m[2]}Z` : null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Dashboard homepage model: all runs (newest first) plus the KPI / filter-tab counts.
|
|
102
|
+
* Each run also gets `snapshotCounts` and `createdAtIso` (for <time datetime>).
|
|
103
|
+
*
|
|
104
|
+
* @param {object} [options]
|
|
105
|
+
* @param {import('better-sqlite3').Database} [options.db] - Defaults to the shared DB
|
|
106
|
+
*/
|
|
107
|
+
export function indexModel({ db } = {}) {
|
|
108
|
+
const runs = getAllTestRuns(db).map((run) => ({
|
|
109
|
+
...run,
|
|
110
|
+
snapshotCounts: snapshotCounts(run),
|
|
111
|
+
createdAtIso: sqliteUtcToIso(run.created_at),
|
|
112
|
+
importedAtIso: sqliteUtcToIso(run.imported_at)
|
|
113
|
+
}));
|
|
114
|
+
const count = (...statuses) => runs.filter((r) => statuses.includes(r.status)).length;
|
|
115
|
+
return {
|
|
116
|
+
title: 'Visual Regression Test Runs',
|
|
117
|
+
runs,
|
|
118
|
+
stats: {
|
|
119
|
+
total: runs.length,
|
|
120
|
+
passed: count('PASSED'),
|
|
121
|
+
approved: count('APPROVED'),
|
|
122
|
+
passedOrApproved: count('PASSED', 'APPROVED'),
|
|
123
|
+
failed: count('FAILED', 'REJECTED')
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Run detail model, or null when the run doesn't exist.
|
|
130
|
+
*
|
|
131
|
+
* @param {object} options
|
|
132
|
+
* @param {import('better-sqlite3').Database} [options.db] - Defaults to the shared DB
|
|
133
|
+
* @param {string} options.runId
|
|
134
|
+
* @param {string} [options.storageRoot] - Defaults to getStorageRoot()
|
|
135
|
+
*/
|
|
136
|
+
export function runDetailModel({ db, runId, storageRoot = getStorageRoot() }) {
|
|
137
|
+
const run = getTestRunById(runId, db);
|
|
138
|
+
if (!run) return null;
|
|
139
|
+
const imported = Boolean(run.imported_at);
|
|
140
|
+
const snapshots = getSnapshotsByRunId(runId, db).map((s) => ({
|
|
141
|
+
...snapshotViewModel(s, storageRoot),
|
|
142
|
+
historyUrl: historyPath(s.route, s.viewport),
|
|
143
|
+
// Imported runs were compared against CI's baseline; approval is refused unless the
|
|
144
|
+
// local one is still identical, so say so up front instead of failing on click.
|
|
145
|
+
baselineStale: imported && PENDING_STATUSES.includes(s.status) && localBaselineIsStale(s, storageRoot)
|
|
146
|
+
}));
|
|
147
|
+
return {
|
|
148
|
+
title: `Run Details: ${run.id}`,
|
|
149
|
+
run: { ...run, createdAtIso: sqliteUtcToIso(run.created_at), importedAtIso: sqliteUtcToIso(run.imported_at) },
|
|
150
|
+
snapshots,
|
|
151
|
+
// Snapshots still awaiting review: the "Approve all pending (N)" button
|
|
152
|
+
pendingCount: snapshots.filter((s) => PENDING_STATUSES.includes(s.status)).length,
|
|
153
|
+
// Pending snapshots that can't be approved here (see baselineStale)
|
|
154
|
+
stalePendingCount: snapshots.filter((s) => s.baselineStale).length
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Baseline/screenshot hashes for the run page, keyed by path and invalidated by
|
|
159
|
+
// dev/inode/size/mtime/ctime, so viewing an imported run doesn't re-hash unchanged files
|
|
160
|
+
// on every request. Least recently used entries are evicted first. This is only a hint
|
|
161
|
+
// for the page: approval always re-hashes (see approveSnapshots in db.js).
|
|
162
|
+
const hashCache = new Map();
|
|
163
|
+
export const HASH_CACHE_MAX = 4096;
|
|
164
|
+
|
|
165
|
+
export function cachedHash(file) {
|
|
166
|
+
const st = fs.statSync(file);
|
|
167
|
+
const key = `${st.dev}:${st.ino}:${st.size}:${st.mtimeMs}:${st.ctimeMs}`;
|
|
168
|
+
const hit = hashCache.get(file);
|
|
169
|
+
if (hit && hit.key === key) {
|
|
170
|
+
hashCache.delete(file); // re-insert: Map order is insertion order, oldest first
|
|
171
|
+
hashCache.set(file, hit);
|
|
172
|
+
return hit.hash;
|
|
173
|
+
}
|
|
174
|
+
const hash = crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
|
175
|
+
hashCache.delete(file);
|
|
176
|
+
while (hashCache.size >= HASH_CACHE_MAX) hashCache.delete(hashCache.keys().next().value);
|
|
177
|
+
hashCache.set(file, { key, hash });
|
|
178
|
+
return hash;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** For tests: how many hashes are cached, and whether `file` is one of them. */
|
|
182
|
+
export function hashCacheInfo(file) {
|
|
183
|
+
return { size: hashCache.size, has: file ? hashCache.has(file) : undefined };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Whether approving this snapshot would be refused because the local shared baseline
|
|
188
|
+
* is not the one the run compared against (same rule as approval, see isBaselineStale).
|
|
189
|
+
* Rows whose files lie outside this storage root are left to approval to report.
|
|
190
|
+
*/
|
|
191
|
+
export function localBaselineIsStale(snapshot, storageRoot = getStorageRoot()) {
|
|
192
|
+
if (!snapshot.baseline_path || !snapshot.current_path) return false;
|
|
193
|
+
const target = path.resolve(snapshot.baseline_path);
|
|
194
|
+
const source = path.resolve(snapshot.current_path);
|
|
195
|
+
if (!isInside(target, path.join(storageRoot, 'baselines')) || !isInside(source, path.join(storageRoot, 'runs'))) {
|
|
196
|
+
return false;
|
|
197
|
+
}
|
|
198
|
+
try {
|
|
199
|
+
return isBaselineStale(snapshot, { source, target, hash: cachedHash });
|
|
200
|
+
} catch {
|
|
201
|
+
return false; // unreadable file: approval will report the real error
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// ─── History page (one route + viewport across runs) ────────────────────────
|
|
206
|
+
|
|
207
|
+
/** Viewport names the history page accepts (also keeps "/history/<slug>/<viewport>" file-safe). */
|
|
208
|
+
export const VIEWPORT_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
|
|
209
|
+
// getRouteSlug() only ever produces these characters; the length cap matches file names.
|
|
210
|
+
const SLUG_PATTERN = /^[A-Za-z0-9_-]{1,255}$/;
|
|
211
|
+
export const HISTORY_LIMIT = 100;
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* App-relative URL of a route's history page at one viewport, or null when the pair
|
|
215
|
+
* can't have one (e.g. a viewport name outside VIEWPORT_PATTERN). Routes are identified
|
|
216
|
+
* by getRouteSlug(), the same identity as their shared baseline file, so "/a/b" and
|
|
217
|
+
* "/a_b" share one history.
|
|
218
|
+
*
|
|
219
|
+
* @param {string} route
|
|
220
|
+
* @param {string} viewport
|
|
221
|
+
* @returns {string|null}
|
|
222
|
+
*/
|
|
223
|
+
export function historyPath(route, viewport) {
|
|
224
|
+
const slug = getRouteSlug(route);
|
|
225
|
+
if (!SLUG_PATTERN.test(slug) || !VIEWPORT_PATTERN.test(String(viewport))) return null;
|
|
226
|
+
return `/history/${slug}/${viewport}`;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const STATUS_PILLS = {
|
|
230
|
+
MATCH: { cls: 'status-pill-passed', label: 'MATCH' },
|
|
231
|
+
DIFF: { cls: 'status-pill-failed', label: 'DIFF' },
|
|
232
|
+
MISSING_BASELINE: { cls: 'status-pill-failed', label: 'MISSING BASELINE' },
|
|
233
|
+
NEW_BASELINE: { cls: 'status-pill-new', label: 'NEW BASELINE' },
|
|
234
|
+
APPROVED: { cls: 'status-pill-approved', label: 'APPROVED' },
|
|
235
|
+
REJECTED: { cls: 'status-pill-rejected', label: 'REJECTED' }
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* The baseline a row was compared against: its hash, 'none' when there was no baseline,
|
|
240
|
+
* or null when unknown (rows recorded before hashes existed, except MISSING_BASELINE).
|
|
241
|
+
*/
|
|
242
|
+
function comparedBaseline(row) {
|
|
243
|
+
if (row.baseline_sha256) return row.baseline_sha256;
|
|
244
|
+
return row.status === 'MISSING_BASELINE' ? 'none' : null;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* How the baseline changed between an older row and the next newer one:
|
|
249
|
+
* 'created' (none -> baseline), 'removed' (baseline -> none), 'changed' (different
|
|
250
|
+
* hash), or null (same, or unknown for either row).
|
|
251
|
+
*/
|
|
252
|
+
export function baselineChange(newer, older) {
|
|
253
|
+
const before = older ? comparedBaseline(older) : null;
|
|
254
|
+
const after = comparedBaseline(newer);
|
|
255
|
+
if (!before || !after || before === after) return null;
|
|
256
|
+
if (before === 'none') return 'created';
|
|
257
|
+
if (after === 'none') return 'removed';
|
|
258
|
+
return 'changed';
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const BASELINE_CHANGE_LABELS = {
|
|
262
|
+
created: 'Baseline created',
|
|
263
|
+
removed: 'Baseline removed',
|
|
264
|
+
changed: 'Baseline changed'
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
const pct = (n) => `${n.toFixed(2)}%`;
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Geometry for a server-rendered SVG sparkline of mismatch percentages (oldest first).
|
|
271
|
+
* The y axis starts at 0%, so an all-zero history is a flat line along the bottom.
|
|
272
|
+
*
|
|
273
|
+
* @param {number[]} values
|
|
274
|
+
* @param {{ width?: number, height?: number, pad?: number }} [size]
|
|
275
|
+
*/
|
|
276
|
+
export function buildSparkline(values, { width = 600, height = 72, pad = 8 } = {}) {
|
|
277
|
+
const n = values.length;
|
|
278
|
+
if (n === 0) {
|
|
279
|
+
return { width, height, points: [], path: '', label: 'Mismatch: no runs recorded' };
|
|
280
|
+
}
|
|
281
|
+
const min = Math.min(...values);
|
|
282
|
+
const max = Math.max(...values);
|
|
283
|
+
const latest = values[n - 1];
|
|
284
|
+
const top = max > 0 ? max : 1;
|
|
285
|
+
const round = (v) => Math.round(v * 10) / 10;
|
|
286
|
+
const points = values.map((value, i) => ({
|
|
287
|
+
value,
|
|
288
|
+
x: round(n === 1 ? width / 2 : pad + (i * (width - 2 * pad)) / (n - 1)),
|
|
289
|
+
y: round(height - pad - (value / top) * (height - 2 * pad))
|
|
290
|
+
}));
|
|
291
|
+
const label = n === 1
|
|
292
|
+
? `Mismatch for 1 run: ${pct(latest)}`
|
|
293
|
+
: `Mismatch over ${n} runs, oldest to newest: min ${pct(min)}, max ${pct(max)}, latest ${pct(latest)}`;
|
|
294
|
+
return {
|
|
295
|
+
width,
|
|
296
|
+
height,
|
|
297
|
+
points,
|
|
298
|
+
path: points.map((p, i) => `${i ? 'L' : 'M'}${p.x} ${p.y}`).join(' '),
|
|
299
|
+
min,
|
|
300
|
+
max,
|
|
301
|
+
latest,
|
|
302
|
+
label
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* History page model: every recorded snapshot of one route (by slug) at one viewport,
|
|
308
|
+
* newest run first, or null when the slug/viewport is invalid or has no snapshots.
|
|
309
|
+
*
|
|
310
|
+
* @param {object} options
|
|
311
|
+
* @param {import('better-sqlite3').Database} [options.db] - Defaults to the shared DB
|
|
312
|
+
* @param {string} options.slug - getRouteSlug(route)
|
|
313
|
+
* @param {string} options.viewport
|
|
314
|
+
* @param {string} [options.storageRoot] - Defaults to getStorageRoot()
|
|
315
|
+
*/
|
|
316
|
+
export function historyModel({ db, slug, viewport, storageRoot = getStorageRoot() }) {
|
|
317
|
+
if (typeof slug !== 'string' || typeof viewport !== 'string') return null;
|
|
318
|
+
if (!SLUG_PATTERN.test(slug) || !VIEWPORT_PATTERN.test(viewport)) return null;
|
|
319
|
+
|
|
320
|
+
const routes = getRoutesForViewport(viewport, db).filter((r) => getRouteSlug(r) === slug);
|
|
321
|
+
if (routes.length === 0) return null;
|
|
322
|
+
// One extra row so the oldest row shown can still be compared with the run before it,
|
|
323
|
+
// and so "truncated" is only claimed when there really are more runs.
|
|
324
|
+
const fetched = getSnapshotHistory({ routes, viewport, limit: HISTORY_LIMIT + 1 }, db);
|
|
325
|
+
if (fetched.length === 0) return null;
|
|
326
|
+
const truncated = fetched.length > HISTORY_LIMIT;
|
|
327
|
+
const rows = fetched.slice(0, HISTORY_LIMIT);
|
|
328
|
+
|
|
329
|
+
const entries = rows.map((row, i) => {
|
|
330
|
+
const change = baselineChange(row, fetched[i + 1]);
|
|
331
|
+
return {
|
|
332
|
+
...snapshotViewModel(row, storageRoot),
|
|
333
|
+
mismatch: Number(row.mismatch_percentage) || 0,
|
|
334
|
+
runUrl: `/runs/${encodeURIComponent(row.run_id)}#snapshot-${row.id}`,
|
|
335
|
+
createdAtIso: sqliteUtcToIso(row.created_at),
|
|
336
|
+
statusPill: STATUS_PILLS[row.status] || { cls: 'status-pill-new', label: String(row.status) },
|
|
337
|
+
baselineChange: change,
|
|
338
|
+
baselineChanged: change !== null,
|
|
339
|
+
baselineChangeLabel: change ? BASELINE_CHANGE_LABELS[change] : null
|
|
340
|
+
};
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
// Oldest -> newest for the chart; baseline changes become vertical markers.
|
|
344
|
+
const chronological = [...entries].reverse();
|
|
345
|
+
const sparkline = buildSparkline(chronological.map((e) => e.mismatch));
|
|
346
|
+
sparkline.changes = chronological
|
|
347
|
+
.map((e, i) => (e.baselineChanged ? { x: sparkline.points[i].x, label: e.baselineChangeLabel, runId: e.run_id } : null))
|
|
348
|
+
.filter(Boolean);
|
|
349
|
+
|
|
350
|
+
const route = rows[0].route;
|
|
351
|
+
// Today's shared baseline (what the next run compares against), if there is one.
|
|
352
|
+
const sharedBaseline = path.join(storageRoot, 'baselines', getSnapshotFilename(route, viewport));
|
|
353
|
+
|
|
354
|
+
return {
|
|
355
|
+
title: `History: ${route} @ ${viewport}`,
|
|
356
|
+
slug,
|
|
357
|
+
viewport,
|
|
358
|
+
route,
|
|
359
|
+
routes,
|
|
360
|
+
entries,
|
|
361
|
+
sparkline,
|
|
362
|
+
baselineUrl: fs.existsSync(sharedBaseline) ? toWebUrl(sharedBaseline, storageRoot) : null,
|
|
363
|
+
limit: HISTORY_LIMIT,
|
|
364
|
+
truncated
|
|
365
|
+
};
|
|
366
|
+
}
|