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,837 @@
|
|
|
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 yauzl from 'yauzl';
|
|
7
|
+
import { getSnapshotFilename } from '../cli/naming.js';
|
|
8
|
+
import { MANIFEST_FILENAME, MANIFEST_SCHEMA, MANIFEST_VERSION, toSqliteTimestamp } from '../cli/manifest.js';
|
|
9
|
+
import { createSnapshot, createTestRun, getTestRunById, recalculateRunStatus } from './db.js';
|
|
10
|
+
import { isInside } from './paths.js';
|
|
11
|
+
import { UNSAFE_CHARS, sanitizeForDisplay } from '../shared/text.js';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Imports test runs recorded elsewhere (typically the `visual-regression-diffs` artifact
|
|
15
|
+
* a failed CI job uploads: a zip of storage/runs/) into a local storage root, so they
|
|
16
|
+
* show up in the dashboard and can be reviewed there.
|
|
17
|
+
*
|
|
18
|
+
* Used by `visual-ci import` and meant to back a dashboard upload as well, so it takes
|
|
19
|
+
* everything it needs as arguments and reports failures as ImportError with an HTTP-ish
|
|
20
|
+
* `status`:
|
|
21
|
+
* 400 unreadable or unsafe input (not a zip, path traversal, duplicate entries, bad option)
|
|
22
|
+
* 409 the requested run id is taken
|
|
23
|
+
* 413 an input limit was exceeded (see IMPORT_LIMITS)
|
|
24
|
+
* 422 the input is readable but holds no valid run (no run.json, invalid manifest,
|
|
25
|
+
* missing/forged images, hashes that don't match)
|
|
26
|
+
* Anything else (disk full, database error) is rethrown unchanged.
|
|
27
|
+
*
|
|
28
|
+
* Trust model: the archive is untrusted. Only run.json and *.png files are extracted,
|
|
29
|
+
* into a private staging folder, never following symlinks; sizes are counted while
|
|
30
|
+
* streaming, not taken from headers. File names are re-derived from each snapshot's
|
|
31
|
+
* route and viewport (never taken from the manifest), every referenced image must be a
|
|
32
|
+
* PNG of bounded size whose SHA-256 matches the manifest, and nothing is ever written
|
|
33
|
+
* to baselines/. The CI-recorded baseline hash is kept verbatim, so approving an
|
|
34
|
+
* imported snapshot only works while the local baseline is exactly the one CI compared
|
|
35
|
+
* against (see approveSnapshots in db.js).
|
|
36
|
+
*
|
|
37
|
+
* All or nothing per call: if any run in the input is invalid, nothing is imported.
|
|
38
|
+
*
|
|
39
|
+
* Keeps a server responsive (it also backs POST /api/imports): every file's size,
|
|
40
|
+
* SHA-256 and PNG header are computed while it is streamed into staging, so validation
|
|
41
|
+
* never reads whole files synchronously; the remaining synchronous work is metadata
|
|
42
|
+
* (lstat, rename, mkdir) and the short commit step (id choice -> rename -> one DB
|
|
43
|
+
* transaction), which must stay synchronous so concurrent imports can't pick the same id.
|
|
44
|
+
* One-import-at-a-time and disk-space limits for uploads live in uploadImport.js.
|
|
45
|
+
*/
|
|
46
|
+
|
|
47
|
+
export const IMPORT_LIMITS = Object.freeze({
|
|
48
|
+
maxEntries: 2000, // archive entries / directory entries visited
|
|
49
|
+
maxFileBytes: 50 * 1024 * 1024, // per extracted image
|
|
50
|
+
maxTotalBytes: 500 * 1024 * 1024, // all extracted files together
|
|
51
|
+
maxManifestBytes: 1024 * 1024, // per run.json
|
|
52
|
+
maxSnapshots: 1000, // per run
|
|
53
|
+
maxImageWidth: 16384,
|
|
54
|
+
maxImageHeight: 65536
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
/** Same rule as capture.js plus a length cap (it becomes a folder name and a URL). */
|
|
58
|
+
export const RUN_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
|
|
59
|
+
const VIEWPORT_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
|
|
60
|
+
const HEX_SHA256 = /^[0-9a-f]{64}$/;
|
|
61
|
+
const COMMIT_PATTERN = /^[0-9A-Fa-f]{1,64}$/;
|
|
62
|
+
const ISO_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?(Z|[+-]\d{2}:\d{2})$/;
|
|
63
|
+
// UNSAFE_CHARS (controls, bidi/format characters, surrogates, separators, see
|
|
64
|
+
// src/shared/text.js) are refused in every manifest string and archive entry name.
|
|
65
|
+
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
|
66
|
+
const MAX_MANIFEST_DEPTH = 3; // run.json, <id>/run.json, runs/<id>/run.json
|
|
67
|
+
const MAX_FILE_DEPTH = MAX_MANIFEST_DEPTH + 1; // + baselines/<file>.png
|
|
68
|
+
const MAX_ENTRY_NAME = 1024;
|
|
69
|
+
const MAX_ID_SUFFIX = 1000;
|
|
70
|
+
const RUN_STATUSES = ['PASSED', 'FAILED'];
|
|
71
|
+
const SNAPSHOT_STATUSES = ['MATCH', 'DIFF', 'NEW_BASELINE', 'MISSING_BASELINE'];
|
|
72
|
+
const MODES = ['compare', 'update-baselines'];
|
|
73
|
+
|
|
74
|
+
export class ImportError extends Error {
|
|
75
|
+
/**
|
|
76
|
+
* @param {number} status - 400, 409, 413 or 422 (see the module comment)
|
|
77
|
+
* @param {string} message
|
|
78
|
+
*/
|
|
79
|
+
constructor(status, message) {
|
|
80
|
+
super(message);
|
|
81
|
+
this.name = 'ImportError';
|
|
82
|
+
this.status = status;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const badInput = (message) => new ImportError(400, message);
|
|
87
|
+
const tooLarge = (message) => new ImportError(413, message);
|
|
88
|
+
const invalid = (message) => new ImportError(422, message);
|
|
89
|
+
|
|
90
|
+
// Moved to src/shared/text.js; still exported here for existing callers.
|
|
91
|
+
export { sanitizeForDisplay };
|
|
92
|
+
|
|
93
|
+
/** Untrusted value for an error message: quoted, escaped and shortened. */
|
|
94
|
+
function show(value) {
|
|
95
|
+
// JSON.stringify escapes C0 only; sanitizeForDisplay handles C1, bidi and the rest.
|
|
96
|
+
const text = sanitizeForDisplay(JSON.stringify(value) ?? String(value));
|
|
97
|
+
return text.length > 120 ? `${text.slice(0, 117)}...` : text;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const mb = (bytes) => `${Math.round(bytes / (1024 * 1024))} MB`;
|
|
101
|
+
const PNG_HEADER_BYTES = 24; // signature + IHDR length/type + width + height
|
|
102
|
+
|
|
103
|
+
function pathExists(p) {
|
|
104
|
+
try {
|
|
105
|
+
fs.lstatSync(p);
|
|
106
|
+
return true;
|
|
107
|
+
} catch (err) {
|
|
108
|
+
if (err.code === 'ENOENT') return false;
|
|
109
|
+
throw err;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// ─── Staging: extract / copy only what an import can use ─────────────────────
|
|
114
|
+
|
|
115
|
+
/** 'manifest' for run.json, 'png' for images, null for anything the import ignores. */
|
|
116
|
+
function classify(parts) {
|
|
117
|
+
const name = parts[parts.length - 1];
|
|
118
|
+
if (name === MANIFEST_FILENAME && parts.length <= MAX_MANIFEST_DEPTH) return 'manifest';
|
|
119
|
+
if (name.endsWith('.png') && parts.length <= MAX_FILE_DEPTH) return 'png';
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Splits an archive entry name into path segments, refusing anything that could escape
|
|
125
|
+
* or confuse the staging folder (yauzl already rejects absolute paths, ".." and
|
|
126
|
+
* backslashes; this adds empty and "." segments and control characters).
|
|
127
|
+
*/
|
|
128
|
+
function entrySegments(name) {
|
|
129
|
+
const trimmed = name.endsWith('/') ? name.slice(0, -1) : name;
|
|
130
|
+
const parts = trimmed.split('/');
|
|
131
|
+
if (
|
|
132
|
+
trimmed.length === 0 || trimmed.length > MAX_ENTRY_NAME || UNSAFE_CHARS.test(trimmed) ||
|
|
133
|
+
parts.some((p) => p === '' || p === '.' || p === '..' || p.length > 255)
|
|
134
|
+
) {
|
|
135
|
+
throw badInput(`Unsafe file name in the archive: ${show(name)}. Nothing was imported.`);
|
|
136
|
+
}
|
|
137
|
+
return parts;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Streams `source` into a new file at staging/<parts>, counting the bytes that actually
|
|
142
|
+
* arrive (the per-file and the overall limit), and records it in `state`.
|
|
143
|
+
*/
|
|
144
|
+
async function stageFile(source, parts, kind, state) {
|
|
145
|
+
const dest = path.join(state.filesDir, ...parts);
|
|
146
|
+
if (!isInside(dest, state.filesDir)) throw badInput(`Unsafe file name: ${show(parts.join('/'))}.`);
|
|
147
|
+
const maxBytes = kind === 'manifest' ? state.limits.maxManifestBytes : state.limits.maxFileBytes;
|
|
148
|
+
const label = parts.join('/');
|
|
149
|
+
let written = 0;
|
|
150
|
+
// Hash and keep the first bytes while streaming, so validation never re-reads the file.
|
|
151
|
+
const hash = crypto.createHash('sha256');
|
|
152
|
+
let header = Buffer.alloc(0);
|
|
153
|
+
const counter = new Transform({
|
|
154
|
+
transform(chunk, _encoding, callback) {
|
|
155
|
+
written += chunk.length;
|
|
156
|
+
hash.update(chunk);
|
|
157
|
+
if (header.length < PNG_HEADER_BYTES) {
|
|
158
|
+
header = Buffer.concat([header, chunk.subarray(0, PNG_HEADER_BYTES - header.length)]);
|
|
159
|
+
}
|
|
160
|
+
state.totalBytes += chunk.length;
|
|
161
|
+
if (written > maxBytes) {
|
|
162
|
+
return callback(tooLarge(`${show(label)} is larger than the ${mb(maxBytes)} limit for ${kind === 'manifest' ? 'run.json' : 'an image'}.`));
|
|
163
|
+
}
|
|
164
|
+
if (state.totalBytes > state.limits.maxTotalBytes) {
|
|
165
|
+
return callback(tooLarge(`The import is larger than the ${mb(state.limits.maxTotalBytes)} limit.`));
|
|
166
|
+
}
|
|
167
|
+
return callback(null, chunk);
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
try {
|
|
172
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
173
|
+
// 'wx': a second entry with the same name must not silently replace the first.
|
|
174
|
+
await pipeline(source, counter, fs.createWriteStream(dest, { flags: 'wx' }));
|
|
175
|
+
} catch (err) {
|
|
176
|
+
if (['EEXIST', 'ENOTDIR', 'EISDIR'].includes(err.code)) {
|
|
177
|
+
throw badInput(`The input contains ${show(label)} more than once (or as both a file and a folder). Nothing was imported.`);
|
|
178
|
+
}
|
|
179
|
+
throw err;
|
|
180
|
+
}
|
|
181
|
+
state.files.set(label, { sha256: hash.digest('hex'), header });
|
|
182
|
+
if (kind === 'manifest') state.manifests.push(parts);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function countEntry(state) {
|
|
186
|
+
state.entries += 1;
|
|
187
|
+
if (state.entries > state.limits.maxEntries) {
|
|
188
|
+
throw tooLarge(`The input has more than ${state.limits.maxEntries} files and folders.`);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** ENOSPC, EACCES, ... (not yauzl's format errors, not Node's ERR_* stream errors). */
|
|
193
|
+
const isSystemError = (err) => typeof err.code === 'string' && /^E[A-Z]+$/.test(err.code);
|
|
194
|
+
|
|
195
|
+
// yauzl's own file name checks put the raw entry name into the message.
|
|
196
|
+
const YAUZL_NAME_ERRORS = ['invalid characters in fileName: ', 'absolute path: ', 'invalid relative path: '];
|
|
197
|
+
|
|
198
|
+
/** Our own message for a yauzl error; never its raw text (it can carry an entry name). */
|
|
199
|
+
function zipFormatError(err) {
|
|
200
|
+
const message = String(err?.message ?? err);
|
|
201
|
+
const prefix = YAUZL_NAME_ERRORS.find((p) => message.startsWith(p));
|
|
202
|
+
if (prefix) {
|
|
203
|
+
return badInput(`Unsafe file name in the archive: ${show(message.slice(prefix.length))}. Nothing was imported.`);
|
|
204
|
+
}
|
|
205
|
+
return badInput(`Invalid zip archive: ${sanitizeForDisplay(message).slice(0, 300)}`);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const S_IFMT = 0o170000;
|
|
209
|
+
const S_IFREG = 0o100000;
|
|
210
|
+
|
|
211
|
+
async function stageZip(file, state) {
|
|
212
|
+
let zip;
|
|
213
|
+
try {
|
|
214
|
+
// strictFileNames: a backslash is an error instead of being turned into "/".
|
|
215
|
+
zip = await yauzl.openPromise(file, { strictFileNames: true, validateEntrySizes: true });
|
|
216
|
+
} catch (err) {
|
|
217
|
+
if (err.code === 'ENOENT' || err.code === 'EACCES' || err.code === 'EISDIR') {
|
|
218
|
+
throw badInput(`Cannot read ${show(file)}: ${err.code}.`);
|
|
219
|
+
}
|
|
220
|
+
throw badInput(`Not a valid zip archive: ${sanitizeForDisplay(err.message)}`);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
try {
|
|
224
|
+
if (zip.entryCount > state.limits.maxEntries) {
|
|
225
|
+
throw tooLarge(`The archive has ${zip.entryCount} entries; the limit is ${state.limits.maxEntries}.`);
|
|
226
|
+
}
|
|
227
|
+
for await (const entry of zip.eachEntry()) {
|
|
228
|
+
countEntry(state);
|
|
229
|
+
const parts = entrySegments(entry.fileName);
|
|
230
|
+
if (entry.fileName.endsWith('/')) continue; // folders are created as needed
|
|
231
|
+
|
|
232
|
+
// Unix file type in the high 16 bits: skip symlinks, devices etc. (0 = not recorded).
|
|
233
|
+
const type = (entry.externalFileAttributes >>> 16) & S_IFMT;
|
|
234
|
+
if (type !== 0 && type !== S_IFREG) continue;
|
|
235
|
+
|
|
236
|
+
const kind = classify(parts);
|
|
237
|
+
if (!kind) continue;
|
|
238
|
+
if (entry.isEncrypted()) throw badInput(`${show(entry.fileName)} is encrypted; encrypted archives are not supported.`);
|
|
239
|
+
|
|
240
|
+
// Quick refusal from the header; the real limit is enforced while streaming.
|
|
241
|
+
const max = kind === 'manifest' ? state.limits.maxManifestBytes : state.limits.maxFileBytes;
|
|
242
|
+
if (entry.uncompressedSize > max) {
|
|
243
|
+
throw tooLarge(`${show(entry.fileName)} is larger than the ${mb(max)} limit.`);
|
|
244
|
+
}
|
|
245
|
+
const stream = await zip.openReadStreamPromise(entry);
|
|
246
|
+
try {
|
|
247
|
+
await stageFile(stream, parts, kind, state);
|
|
248
|
+
} finally {
|
|
249
|
+
stream.destroy();
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
} catch (err) {
|
|
253
|
+
if (err instanceof ImportError || isSystemError(err)) throw err; // ours, or e.g. a full disk
|
|
254
|
+
throw zipFormatError(err);
|
|
255
|
+
} finally {
|
|
256
|
+
zip.close();
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const OPEN_FLAGS = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) | (fs.constants.O_NONBLOCK || 0);
|
|
261
|
+
const isAtOrInside = (child, parent) => child === parent || isInside(child, parent);
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Opens a file found while walking `root` for reading, or returns null when it must be
|
|
265
|
+
* skipped. Defends against the tree changing under us:
|
|
266
|
+
* - O_NOFOLLOW: the file itself can't be a symlink; O_NONBLOCK: a FIFO swapped in can't
|
|
267
|
+
* block the open (and is then skipped as not a regular file).
|
|
268
|
+
* - After opening, the parent folder's real path must still be inside root and the
|
|
269
|
+
* file at <real parent>/<name> must be the very file we opened (same dev/inode), so a
|
|
270
|
+
* parent folder swapped for a symlink (before or after the open) is caught.
|
|
271
|
+
*/
|
|
272
|
+
function openInsideRoot(root, parentAbs, name) {
|
|
273
|
+
let fd;
|
|
274
|
+
try {
|
|
275
|
+
fd = fs.openSync(path.join(parentAbs, name), OPEN_FLAGS);
|
|
276
|
+
} catch (err) {
|
|
277
|
+
if (['ELOOP', 'ENOENT', 'ENXIO', 'EMLINK'].includes(err.code)) return null; // link, vanished, FIFO/socket
|
|
278
|
+
throw err;
|
|
279
|
+
}
|
|
280
|
+
let keep = false;
|
|
281
|
+
try {
|
|
282
|
+
keep = isOpenedFileInsideRoot(fd, root, parentAbs, name);
|
|
283
|
+
} catch (err) {
|
|
284
|
+
if (err.code !== 'ENOENT') {
|
|
285
|
+
fs.closeSync(fd);
|
|
286
|
+
throw err;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
if (!keep) {
|
|
290
|
+
fs.closeSync(fd);
|
|
291
|
+
return null;
|
|
292
|
+
}
|
|
293
|
+
return fd;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function isOpenedFileInsideRoot(fd, root, parentAbs, name) {
|
|
297
|
+
const opened = fs.fstatSync(fd);
|
|
298
|
+
if (!opened.isFile()) return false;
|
|
299
|
+
const realParent = fs.realpathSync(parentAbs);
|
|
300
|
+
if (!isAtOrInside(realParent, root)) return false;
|
|
301
|
+
const there = fs.lstatSync(path.join(realParent, name));
|
|
302
|
+
return there.isFile() && there.dev === opened.dev && there.ino === opened.ino;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Copies a folder's run.json / *.png files. Symlinks are never followed below the
|
|
307
|
+
* folder given (that folder itself may be a symlink: it is what the user asked for):
|
|
308
|
+
* entries are checked with lstat, folders are only entered when their real path is
|
|
309
|
+
* still inside the root, and files are opened with openInsideRoot. Listings are read
|
|
310
|
+
* lazily so the entry limit applies before a huge folder is loaded.
|
|
311
|
+
*/
|
|
312
|
+
async function stageDir(dir, state) {
|
|
313
|
+
let root;
|
|
314
|
+
try {
|
|
315
|
+
root = fs.realpathSync(dir);
|
|
316
|
+
if (!fs.statSync(root).isDirectory()) throw badInput(`${show(dir)} is not a folder.`);
|
|
317
|
+
} catch (err) {
|
|
318
|
+
if (err instanceof ImportError) throw err;
|
|
319
|
+
throw badInput(`Cannot read the folder ${show(dir)}: ${sanitizeForDisplay(err.code || err.message)}.`);
|
|
320
|
+
}
|
|
321
|
+
const staging = fs.statSync(state.stagingDir);
|
|
322
|
+
|
|
323
|
+
async function walk(abs, relParts) {
|
|
324
|
+
const handle = fs.opendirSync(abs);
|
|
325
|
+
try {
|
|
326
|
+
for (let dirent = handle.readSync(); dirent !== null; dirent = handle.readSync()) {
|
|
327
|
+
countEntry(state);
|
|
328
|
+
const name = dirent.name;
|
|
329
|
+
// Names we could never reference (or print safely) are skipped, not staged.
|
|
330
|
+
if (name.length > 255 || UNSAFE_CHARS.test(name)) continue;
|
|
331
|
+
const parts = [...relParts, name];
|
|
332
|
+
const child = path.join(abs, name);
|
|
333
|
+
let st;
|
|
334
|
+
try {
|
|
335
|
+
st = fs.lstatSync(child);
|
|
336
|
+
} catch (err) {
|
|
337
|
+
if (err.code === 'ENOENT') continue;
|
|
338
|
+
throw err;
|
|
339
|
+
}
|
|
340
|
+
if (st.isSymbolicLink()) continue;
|
|
341
|
+
if (st.isDirectory()) {
|
|
342
|
+
if (parts.length >= MAX_FILE_DEPTH) continue;
|
|
343
|
+
// Importing the storage folder itself must not walk into this import's staging copy.
|
|
344
|
+
if (st.ino === staging.ino && st.dev === staging.dev) continue;
|
|
345
|
+
if (!isAtOrInside(fs.realpathSync(child), root)) continue;
|
|
346
|
+
await walk(child, parts);
|
|
347
|
+
continue;
|
|
348
|
+
}
|
|
349
|
+
if (!st.isFile()) continue;
|
|
350
|
+
const kind = classify(parts);
|
|
351
|
+
if (!kind) continue;
|
|
352
|
+
const fd = openInsideRoot(root, abs, name);
|
|
353
|
+
if (fd === null) continue;
|
|
354
|
+
const stream = fs.createReadStream(null, { fd }); // closes fd when destroyed
|
|
355
|
+
try {
|
|
356
|
+
await stageFile(stream, parts, kind, state);
|
|
357
|
+
} finally {
|
|
358
|
+
stream.destroy();
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
} finally {
|
|
362
|
+
handle.closeSync();
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
await walk(root, []);
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// ─── Manifest validation ─────────────────────────────────────────────────────
|
|
370
|
+
|
|
371
|
+
function isPlainObject(v) {
|
|
372
|
+
return v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function checkString(v, where, { max, nullable = false, pattern, allowEmpty = false } = {}) {
|
|
376
|
+
if (v === null || v === undefined) {
|
|
377
|
+
if (nullable) return null;
|
|
378
|
+
throw invalid(`${where} is required.`);
|
|
379
|
+
}
|
|
380
|
+
if (typeof v !== 'string') throw invalid(`${where} must be a string, got ${show(v)}.`);
|
|
381
|
+
if ((!allowEmpty && v.length === 0) || (max && v.length > max) || UNSAFE_CHARS.test(v)) {
|
|
382
|
+
throw invalid(`${where} is not a valid value: ${show(v)}.`);
|
|
383
|
+
}
|
|
384
|
+
if (pattern && !pattern.test(v)) throw invalid(`${where} is not valid: ${show(v)}.`);
|
|
385
|
+
return v;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function checkEnum(v, allowed, where) {
|
|
389
|
+
if (!allowed.includes(v)) throw invalid(`${where} must be one of ${allowed.join(', ')}, got ${show(v)}.`);
|
|
390
|
+
return v;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
function checkNumber(v, where, { min, max, integer = false, nullable = false }) {
|
|
394
|
+
if (v === null && nullable) return null;
|
|
395
|
+
if (typeof v !== 'number' || !Number.isFinite(v) || v < min || v > max || (integer && !Number.isSafeInteger(v))) {
|
|
396
|
+
throw invalid(`${where} must be ${integer ? 'an integer' : 'a number'} from ${min} to ${max}, got ${show(v)}.`);
|
|
397
|
+
}
|
|
398
|
+
return v;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function checkBoolean(v, where) {
|
|
402
|
+
if (typeof v !== 'boolean') throw invalid(`${where} must be true or false, got ${show(v)}.`);
|
|
403
|
+
return v;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** Checks a staged file's first bytes (recorded while staging) for a sane PNG. */
|
|
407
|
+
function checkPng(header, rel, where, limits) {
|
|
408
|
+
if (header.length < PNG_HEADER_BYTES || !header.subarray(0, 8).equals(PNG_SIGNATURE)) {
|
|
409
|
+
throw invalid(`${where}: ${show(rel)} is not a PNG image.`);
|
|
410
|
+
}
|
|
411
|
+
if (header.readUInt32BE(8) !== 13 || header.toString('latin1', 12, 16) !== 'IHDR') {
|
|
412
|
+
throw invalid(`${where}: ${show(rel)} is not a valid PNG image (no IHDR header).`);
|
|
413
|
+
}
|
|
414
|
+
const width = header.readUInt32BE(16);
|
|
415
|
+
const height = header.readUInt32BE(20);
|
|
416
|
+
if (width < 1 || height < 1 || width > limits.maxImageWidth || height > limits.maxImageHeight) {
|
|
417
|
+
throw invalid(`${where}: ${show(rel)} is ${width}x${height} pixels; images may be at most ` +
|
|
418
|
+
`${limits.maxImageWidth}x${limits.maxImageHeight}.`);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Validates one parsed run.json against the files staged next to it.
|
|
424
|
+
*
|
|
425
|
+
* @param {unknown} manifest - Parsed JSON
|
|
426
|
+
* @param {(rel: string) => ({ sha256: string, header: Buffer } | undefined)} stagedFile
|
|
427
|
+
* What staging recorded for a path relative to the run.json's folder (undefined if
|
|
428
|
+
* nothing was staged there)
|
|
429
|
+
* @param {string} label - Where the manifest came from, for messages
|
|
430
|
+
* @param {object} limits
|
|
431
|
+
* @returns {{ run: object, createdAtSql: string, snapshots: object[] }}
|
|
432
|
+
*/
|
|
433
|
+
export function validateManifest(manifest, stagedFile, label, limits = IMPORT_LIMITS) {
|
|
434
|
+
const fail = (message) => invalid(`${label}: ${message}`);
|
|
435
|
+
if (!isPlainObject(manifest)) throw fail('run.json must be a JSON object.');
|
|
436
|
+
if (manifest.schema !== MANIFEST_SCHEMA) throw fail(`not a visual-ci run record (schema ${show(manifest.schema)}).`);
|
|
437
|
+
if (manifest.version !== MANIFEST_VERSION) {
|
|
438
|
+
throw fail(`unsupported run.json version ${show(manifest.version)}; this visual-ci understands version ${MANIFEST_VERSION}.`);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
const wrap = (fn) => {
|
|
442
|
+
try {
|
|
443
|
+
return fn();
|
|
444
|
+
} catch (err) {
|
|
445
|
+
if (err instanceof ImportError) throw fail(err.message);
|
|
446
|
+
throw err;
|
|
447
|
+
}
|
|
448
|
+
};
|
|
449
|
+
|
|
450
|
+
const r = manifest.run;
|
|
451
|
+
if (!isPlainObject(r)) throw fail('"run" must be an object.');
|
|
452
|
+
const run = wrap(() => ({
|
|
453
|
+
id: checkString(r.id, 'run.id', { pattern: RUN_ID_PATTERN }),
|
|
454
|
+
commit_hash: checkString(r.commit_hash, 'run.commit_hash', { nullable: true, pattern: COMMIT_PATTERN }),
|
|
455
|
+
commit_sha: checkString(r.commit_sha, 'run.commit_sha', { nullable: true, pattern: COMMIT_PATTERN }),
|
|
456
|
+
branch: checkString(r.branch, 'run.branch', { nullable: true, max: 255 }),
|
|
457
|
+
status: checkEnum(r.status, RUN_STATUSES, 'run.status'),
|
|
458
|
+
created_at: checkString(r.created_at, 'run.created_at', { pattern: ISO_TIMESTAMP }),
|
|
459
|
+
mode: checkEnum(r.mode, MODES, 'run.mode'),
|
|
460
|
+
strict: checkBoolean(r.strict, 'run.strict'),
|
|
461
|
+
threshold_percentage: checkNumber(r.threshold_percentage, 'run.threshold_percentage', { min: 0, max: 100 }),
|
|
462
|
+
pixelmatch_threshold: checkNumber(r.pixelmatch_threshold, 'run.pixelmatch_threshold', { min: 0, max: 1 })
|
|
463
|
+
}));
|
|
464
|
+
const createdAt = new Date(run.created_at);
|
|
465
|
+
if (Number.isNaN(createdAt.getTime())) throw fail(`run.created_at is not a valid date: ${show(run.created_at)}.`);
|
|
466
|
+
|
|
467
|
+
if (!Array.isArray(manifest.snapshots) || manifest.snapshots.length === 0) {
|
|
468
|
+
throw fail('"snapshots" must be a non-empty array.');
|
|
469
|
+
}
|
|
470
|
+
if (manifest.snapshots.length > limits.maxSnapshots) {
|
|
471
|
+
throw fail(`too many snapshots (${manifest.snapshots.length}; the limit is ${limits.maxSnapshots}).`);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
const pairs = new Set();
|
|
475
|
+
const fileOwners = new Map();
|
|
476
|
+
const snapshots = manifest.snapshots.map((s, i) => wrap(() => {
|
|
477
|
+
const at = `snapshots[${i}]`;
|
|
478
|
+
if (!isPlainObject(s)) throw invalid(`${at} must be an object.`);
|
|
479
|
+
const route = checkString(s.route, `${at}.route`, { max: 2048 });
|
|
480
|
+
const viewport = checkString(s.viewport, `${at}.viewport`, { pattern: VIEWPORT_PATTERN });
|
|
481
|
+
const status = checkEnum(s.status, SNAPSHOT_STATUSES, `${at}.status`);
|
|
482
|
+
if (s.viewport_size !== null && s.viewport_size !== undefined) {
|
|
483
|
+
if (!isPlainObject(s.viewport_size)) throw invalid(`${at}.viewport_size must be an object or null.`);
|
|
484
|
+
checkNumber(s.viewport_size.width, `${at}.viewport_size.width`, { min: 1, max: 100000, integer: true });
|
|
485
|
+
checkNumber(s.viewport_size.height, `${at}.viewport_size.height`, { min: 1, max: 100000, integer: true });
|
|
486
|
+
}
|
|
487
|
+
const mismatch = checkNumber(s.mismatch_percentage, `${at}.mismatch_percentage`, { min: 0, max: 100 });
|
|
488
|
+
const mismatched = checkNumber(s.mismatched_pixels ?? null, `${at}.mismatched_pixels`, { min: 0, max: Number.MAX_SAFE_INTEGER, integer: true, nullable: true });
|
|
489
|
+
const total = checkNumber(s.total_pixels ?? null, `${at}.total_pixels`, { min: 0, max: Number.MAX_SAFE_INTEGER, integer: true, nullable: true });
|
|
490
|
+
if (mismatched !== null && total !== null && mismatched > total) {
|
|
491
|
+
throw invalid(`${at}.mismatched_pixels is larger than total_pixels.`);
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
const pair = `${route}\u0000${viewport}`;
|
|
495
|
+
if (pairs.has(pair)) throw invalid(`${at}: route ${show(route)} at viewport ${show(viewport)} is listed twice.`);
|
|
496
|
+
pairs.add(pair);
|
|
497
|
+
|
|
498
|
+
// File names are derived, never trusted: the manifest must agree with them.
|
|
499
|
+
const file = getSnapshotFilename(route, viewport);
|
|
500
|
+
const diffFile = `${file.slice(0, -'.png'.length)}-diff.png`;
|
|
501
|
+
if (diffFile.length > 255) throw invalid(`${at}: the route is too long to make a file name.`);
|
|
502
|
+
for (const name of [file, diffFile]) {
|
|
503
|
+
const owner = fileOwners.get(name);
|
|
504
|
+
if (owner !== undefined) throw invalid(`${at} and snapshots[${owner}] would both use the file ${show(name)}.`);
|
|
505
|
+
fileOwners.set(name, i);
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
const expect = (key, expected) => {
|
|
509
|
+
if (s[key] !== expected) {
|
|
510
|
+
throw invalid(`${at}.${key} must be ${show(expected)} (derived from its route, viewport and status), got ${show(s[key])}.`);
|
|
511
|
+
}
|
|
512
|
+
};
|
|
513
|
+
const compared = status === 'MATCH' || status === 'DIFF';
|
|
514
|
+
expect('current', file);
|
|
515
|
+
expect('baseline', file);
|
|
516
|
+
expect('baseline_snapshot', compared ? `baselines/${file}` : status === 'NEW_BASELINE' ? file : null);
|
|
517
|
+
if (compared) {
|
|
518
|
+
if (s.diff !== null) expect('diff', diffFile);
|
|
519
|
+
} else {
|
|
520
|
+
expect('diff', null);
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
checkString(s.current_sha256, `${at}.current_sha256`, { pattern: HEX_SHA256 });
|
|
524
|
+
if (s.diff === null) expect('diff_sha256', null);
|
|
525
|
+
else checkString(s.diff_sha256, `${at}.diff_sha256`, { pattern: HEX_SHA256 });
|
|
526
|
+
|
|
527
|
+
// null would mean "unknown" locally and skip the stale-baseline check on approval.
|
|
528
|
+
const baselineSha = s.baseline_sha256;
|
|
529
|
+
if (status === 'MISSING_BASELINE') {
|
|
530
|
+
if (baselineSha !== 'none') throw invalid(`${at}.baseline_sha256 must be "none" for a missing baseline, got ${show(baselineSha)}.`);
|
|
531
|
+
} else if (typeof baselineSha !== 'string' || !HEX_SHA256.test(baselineSha)) {
|
|
532
|
+
throw invalid(`${at}.baseline_sha256 must be a SHA-256 hex digest, got ${show(baselineSha)}.`);
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
// The images themselves: present, real PNGs of sane size, hashes as recorded.
|
|
536
|
+
const files = { current: s.current, diff: s.diff, baselineCopy: compared ? s.baseline_snapshot : null };
|
|
537
|
+
for (const rel of Object.values(files)) {
|
|
538
|
+
if (rel === null) continue;
|
|
539
|
+
const info = stagedFile(rel);
|
|
540
|
+
if (!info) throw invalid(`${at}: ${show(rel)} is missing from the input.`);
|
|
541
|
+
checkPng(info.header, rel, at, limits);
|
|
542
|
+
}
|
|
543
|
+
const hashOf = (rel) => stagedFile(rel).sha256;
|
|
544
|
+
const currentHash = hashOf(s.current);
|
|
545
|
+
if (currentHash !== s.current_sha256) throw invalid(`${at}: ${show(s.current)} does not match current_sha256.`);
|
|
546
|
+
if (s.diff !== null && hashOf(s.diff) !== s.diff_sha256) throw invalid(`${at}: ${show(s.diff)} does not match diff_sha256.`);
|
|
547
|
+
if (status === 'NEW_BASELINE' && baselineSha !== currentHash) {
|
|
548
|
+
throw invalid(`${at}.baseline_sha256 must equal the screenshot's hash for a new baseline.`);
|
|
549
|
+
}
|
|
550
|
+
if (compared && hashOf(s.baseline_snapshot) !== baselineSha) {
|
|
551
|
+
throw invalid(`${at}: ${show(s.baseline_snapshot)} does not match baseline_sha256.`);
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
return { route, viewport, status, mismatch_percentage: mismatch, baseline_sha256: baselineSha, file, files };
|
|
555
|
+
}));
|
|
556
|
+
|
|
557
|
+
return { run, createdAtSql: toSqliteTimestamp(createdAt), snapshots };
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
// ─── Run ids ─────────────────────────────────────────────────────────────────
|
|
561
|
+
|
|
562
|
+
/** True when an existing row is this same run (an earlier import of the same artifact). */
|
|
563
|
+
function isSameRun(row, parsed) {
|
|
564
|
+
const commit = parsed.run.commit_hash ?? (parsed.run.commit_sha ? parsed.run.commit_sha.slice(0, 7) : null);
|
|
565
|
+
return (row.commit_hash ?? null) === commit &&
|
|
566
|
+
row.created_at === parsed.createdAtSql &&
|
|
567
|
+
Number(row.total_snapshots) === parsed.snapshots.length;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/**
|
|
571
|
+
* Picks the local id for a run: its own id, or "<id>-imp2", "-imp3", ... when that is
|
|
572
|
+
* taken by a different run (a DB row or a leftover runs/<id>/ folder). An existing row
|
|
573
|
+
* for the same run means it was imported before.
|
|
574
|
+
*
|
|
575
|
+
* Ids are compared case-insensitively ("Run_A" and "run_a" are the same folder on
|
|
576
|
+
* macOS and Windows), so a run is never given an id that differs from an existing one
|
|
577
|
+
* only in case.
|
|
578
|
+
*
|
|
579
|
+
* @param {object} ctx
|
|
580
|
+
* @param {Set<string>} ctx.reserved - Lower-cased ids already picked in this import
|
|
581
|
+
* @param {Set<string>} ctx.folders - Lower-cased names in runs/
|
|
582
|
+
*/
|
|
583
|
+
function chooseRunId(parsed, { db, reserved, folders, requestedId }) {
|
|
584
|
+
const likeRows = db.prepare('SELECT id FROM test_runs WHERE id = ? COLLATE NOCASE');
|
|
585
|
+
const taken = (id) => {
|
|
586
|
+
const key = id.toLowerCase();
|
|
587
|
+
return reserved.has(key) || folders.has(key) || likeRows.all(id).length > 0;
|
|
588
|
+
};
|
|
589
|
+
if (requestedId) {
|
|
590
|
+
if (taken(requestedId)) {
|
|
591
|
+
throw new ImportError(409, `A run with id "${requestedId}" already exists (ids are compared ignoring case); choose another run id.`);
|
|
592
|
+
}
|
|
593
|
+
return { id: requestedId };
|
|
594
|
+
}
|
|
595
|
+
const base = parsed.run.id;
|
|
596
|
+
for (let n = 1; n <= MAX_ID_SUFFIX; n++) {
|
|
597
|
+
const id = n === 1 ? base : `${base}-imp${n}`;
|
|
598
|
+
if (!RUN_ID_PATTERN.test(id)) break;
|
|
599
|
+
if (reserved.has(id.toLowerCase())) continue;
|
|
600
|
+
const row = getTestRunById(id, db);
|
|
601
|
+
if (row && isSameRun(row, parsed)) return { id, alreadyImported: true };
|
|
602
|
+
if (taken(id)) continue;
|
|
603
|
+
return { id };
|
|
604
|
+
}
|
|
605
|
+
throw new ImportError(409, `Could not find a free id for run "${base}"; pass a run id explicitly.`);
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
// ─── Staging folders ─────────────────────────────────────────────────────────
|
|
609
|
+
|
|
610
|
+
/** Staging folders older than this are leftovers of a crashed import. */
|
|
611
|
+
export const STALE_STAGING_MS = 60 * 60 * 1000;
|
|
612
|
+
const STAGING_PREFIX = '.import-';
|
|
613
|
+
|
|
614
|
+
/**
|
|
615
|
+
* Removes `.import-*` folders older than STALE_STAGING_MS from the given folders (left
|
|
616
|
+
* behind if a process died mid-import). Only real directories (lstat, links are never
|
|
617
|
+
* followed); failures are only logged, since they must not block a new import.
|
|
618
|
+
*/
|
|
619
|
+
async function removeStaleStaging(dirs, now = Date.now()) {
|
|
620
|
+
for (const dir of dirs) {
|
|
621
|
+
let names;
|
|
622
|
+
try {
|
|
623
|
+
names = await fs.promises.readdir(dir);
|
|
624
|
+
} catch {
|
|
625
|
+
continue;
|
|
626
|
+
}
|
|
627
|
+
for (const name of names) {
|
|
628
|
+
if (!name.startsWith(STAGING_PREFIX)) continue;
|
|
629
|
+
const p = path.join(dir, name);
|
|
630
|
+
try {
|
|
631
|
+
const st = await fs.promises.lstat(p);
|
|
632
|
+
if (st.isDirectory() && now - st.mtimeMs > STALE_STAGING_MS) await fs.promises.rm(p, { recursive: true, force: true });
|
|
633
|
+
} catch (err) {
|
|
634
|
+
console.warn(`[WARN] Could not remove the old import folder ${sanitizeForDisplay(p)}: ${sanitizeForDisplay(err.message)}`);
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* Renames a finished run folder into runs/. When runs/ is on another filesystem (e.g.
|
|
642
|
+
* a symlink to another disk) the rename fails with EXDEV: then the folder is copied to
|
|
643
|
+
* a hidden temp folder inside runs/ first, so the run still appears in one rename.
|
|
644
|
+
*/
|
|
645
|
+
function moveIntoRuns(out, finalDir, runsDir) {
|
|
646
|
+
try {
|
|
647
|
+
fs.renameSync(out, finalDir);
|
|
648
|
+
return;
|
|
649
|
+
} catch (err) {
|
|
650
|
+
if (err.code !== 'EXDEV') throw err;
|
|
651
|
+
}
|
|
652
|
+
const tmp = fs.mkdtempSync(path.join(runsDir, STAGING_PREFIX));
|
|
653
|
+
try {
|
|
654
|
+
fs.cpSync(out, tmp, { recursive: true, errorOnExist: true, force: false });
|
|
655
|
+
fs.renameSync(tmp, finalDir);
|
|
656
|
+
} catch (err) {
|
|
657
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
658
|
+
throw err;
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
// ─── Entry point ─────────────────────────────────────────────────────────────
|
|
663
|
+
|
|
664
|
+
/**
|
|
665
|
+
* @param {{ kind: 'zip', file: string } | { kind: 'dir', path: string }} source
|
|
666
|
+
* @param {object} options
|
|
667
|
+
* @param {string} options.storageRoot - Storage root (holds runs/, baselines/, the DB)
|
|
668
|
+
* @param {import('better-sqlite3').Database} options.db - Database of that storage root
|
|
669
|
+
* @param {string} [options.runId] - Local id to use (only when the input holds one run)
|
|
670
|
+
* @param {Partial<typeof IMPORT_LIMITS>} [options.limits] - Lower limits (tests)
|
|
671
|
+
* @returns {Promise<{ runs: Array<{ id: string, url: string, status: string,
|
|
672
|
+
* snapshots: number, renamedFrom?: string, alreadyImported?: true }> }>}
|
|
673
|
+
* @throws {ImportError} See the module comment for the statuses
|
|
674
|
+
*/
|
|
675
|
+
export async function importRuns(source, { storageRoot, db, runId, limits: limitOverrides } = {}) {
|
|
676
|
+
if (!storageRoot || typeof storageRoot !== 'string') throw new TypeError('importRuns: storageRoot is required');
|
|
677
|
+
if (!db) throw new TypeError('importRuns: db is required');
|
|
678
|
+
if (runId !== undefined && runId !== null && (typeof runId !== 'string' || !RUN_ID_PATTERN.test(runId))) {
|
|
679
|
+
throw badInput(`Invalid run id ${show(runId)}: use 1-128 letters, digits, "-" or "_".`);
|
|
680
|
+
}
|
|
681
|
+
const limits = { ...IMPORT_LIMITS, ...limitOverrides };
|
|
682
|
+
const root = path.resolve(storageRoot);
|
|
683
|
+
const runsDir = path.join(root, 'runs');
|
|
684
|
+
await fs.promises.mkdir(runsDir, { recursive: true });
|
|
685
|
+
await removeStaleStaging([root, runsDir]);
|
|
686
|
+
|
|
687
|
+
// On the same filesystem as runs/, so the final move is a rename: next to runs/
|
|
688
|
+
// normally, inside it when runs/ is another filesystem (e.g. a symlink to another
|
|
689
|
+
// disk). Never served either way: /storage refuses dot-named path segments.
|
|
690
|
+
const [rootStat, runsStat] = await Promise.all([fs.promises.stat(root), fs.promises.stat(runsDir)]);
|
|
691
|
+
const stagingParent = rootStat.dev === runsStat.dev ? root : runsDir;
|
|
692
|
+
const stagingDir = await fs.promises.mkdtemp(path.join(stagingParent, STAGING_PREFIX));
|
|
693
|
+
const state = {
|
|
694
|
+
stagingDir,
|
|
695
|
+
filesDir: path.join(stagingDir, 'files'),
|
|
696
|
+
limits,
|
|
697
|
+
entries: 0,
|
|
698
|
+
totalBytes: 0,
|
|
699
|
+
manifests: [],
|
|
700
|
+
files: new Map() // staged path -> { sha256, header }
|
|
701
|
+
};
|
|
702
|
+
await fs.promises.mkdir(state.filesDir);
|
|
703
|
+
|
|
704
|
+
try {
|
|
705
|
+
if (source?.kind === 'zip' && typeof source.file === 'string') await stageZip(source.file, state);
|
|
706
|
+
else if (source?.kind === 'dir' && typeof source.path === 'string') await stageDir(source.path, state);
|
|
707
|
+
else throw badInput('Nothing to import: expected a zip file or a folder.');
|
|
708
|
+
|
|
709
|
+
if (state.manifests.length === 0) {
|
|
710
|
+
throw invalid("No run.json found (artifacts from before run.json existed can't be imported; re-run CI).");
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
const runDirs = state.manifests.map((parts) => parts.slice(0, -1).join('/'));
|
|
714
|
+
for (const a of runDirs) {
|
|
715
|
+
for (const b of runDirs) {
|
|
716
|
+
if (a !== b && (a === '' || b.startsWith(`${a}/`))) {
|
|
717
|
+
throw invalid(`The run in ${show(b || '.')} is inside the run in ${show(a || '.')}; import them separately.`);
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
if (runId && state.manifests.length > 1) {
|
|
722
|
+
throw badInput(`The input holds ${state.manifests.length} runs; a run id can only be given when importing one.`);
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
// Validate everything before changing anything.
|
|
726
|
+
const parsedRuns = [];
|
|
727
|
+
for (const [i, parts] of state.manifests.entries()) {
|
|
728
|
+
const label = parts.join('/');
|
|
729
|
+
let json;
|
|
730
|
+
try {
|
|
731
|
+
json = JSON.parse(await fs.promises.readFile(path.join(state.filesDir, ...parts), 'utf8'));
|
|
732
|
+
} catch (err) {
|
|
733
|
+
// V8's message quotes part of the input, so it is sanitised like any other text.
|
|
734
|
+
throw invalid(`${label}: not valid JSON (${sanitizeForDisplay(err.message).slice(0, 200)}).`);
|
|
735
|
+
}
|
|
736
|
+
const prefix = runDirs[i] ? `${runDirs[i]}/` : '';
|
|
737
|
+
const stagedFile = (rel) => state.files.get(prefix + rel);
|
|
738
|
+
parsedRuns.push({ ...validateManifest(json, stagedFile, label, limits), runDir: runDirs[i] });
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
// From here on everything is synchronous, so a concurrent import in this process
|
|
742
|
+
// can't pick the same id between the check and the rename.
|
|
743
|
+
const reserved = new Set();
|
|
744
|
+
const folders = new Set(fs.readdirSync(runsDir).map((name) => name.toLowerCase()));
|
|
745
|
+
const plans = parsedRuns.map((parsed) => {
|
|
746
|
+
const choice = chooseRunId(parsed, { db, reserved, folders, requestedId: runId });
|
|
747
|
+
reserved.add(choice.id.toLowerCase());
|
|
748
|
+
return { parsed, ...choice };
|
|
749
|
+
});
|
|
750
|
+
|
|
751
|
+
commitRuns(plans.filter((p) => !p.alreadyImported), { root, runsDir, db, state });
|
|
752
|
+
|
|
753
|
+
return {
|
|
754
|
+
runs: plans.map(({ parsed, id, alreadyImported }) => {
|
|
755
|
+
const entry = {
|
|
756
|
+
id,
|
|
757
|
+
url: `/runs/${encodeURIComponent(id)}`,
|
|
758
|
+
status: getTestRunById(id, db).status,
|
|
759
|
+
snapshots: parsed.snapshots.length
|
|
760
|
+
};
|
|
761
|
+
if (id !== parsed.run.id) entry.renamedFrom = parsed.run.id;
|
|
762
|
+
if (alreadyImported) entry.alreadyImported = true;
|
|
763
|
+
return entry;
|
|
764
|
+
})
|
|
765
|
+
};
|
|
766
|
+
} finally {
|
|
767
|
+
await fs.promises.rm(stagingDir, { recursive: true, force: true });
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
/**
|
|
772
|
+
* Moves each run's validated images into runs/<id>/ (current + diff at the top,
|
|
773
|
+
* compared baselines under baselines/, like the CLI writes them) and records all runs
|
|
774
|
+
* in one transaction. If anything fails, the folders moved so far are removed again.
|
|
775
|
+
*/
|
|
776
|
+
function commitRuns(plans, { root, runsDir, db, state }) {
|
|
777
|
+
const moved = [];
|
|
778
|
+
try {
|
|
779
|
+
plans.forEach((plan, i) => {
|
|
780
|
+
const { parsed, id } = plan;
|
|
781
|
+
const from = path.join(state.filesDir, ...(parsed.runDir ? parsed.runDir.split('/') : []));
|
|
782
|
+
const out = path.join(state.stagingDir, 'out', String(i));
|
|
783
|
+
fs.mkdirSync(path.join(out, 'baselines'), { recursive: true });
|
|
784
|
+
for (const s of parsed.snapshots) {
|
|
785
|
+
for (const rel of Object.values(s.files)) {
|
|
786
|
+
if (rel) fs.renameSync(path.join(from, ...rel.split('/')), path.join(out, ...rel.split('/')));
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
const finalDir = path.join(runsDir, id);
|
|
790
|
+
if (pathExists(finalDir)) throw new ImportError(409, `runs/${id} appeared while importing; try again.`);
|
|
791
|
+
moveIntoRuns(out, finalDir, runsDir);
|
|
792
|
+
moved.push(finalDir);
|
|
793
|
+
});
|
|
794
|
+
|
|
795
|
+
const importedAt = toSqliteTimestamp(new Date());
|
|
796
|
+
db.transaction(() => {
|
|
797
|
+
for (const { parsed, id } of plans) {
|
|
798
|
+
const runDir = path.join(runsDir, id);
|
|
799
|
+
createTestRun({
|
|
800
|
+
id,
|
|
801
|
+
commit_hash: parsed.run.commit_hash ?? (parsed.run.commit_sha ? parsed.run.commit_sha.slice(0, 7) : null),
|
|
802
|
+
branch: parsed.run.branch,
|
|
803
|
+
status: parsed.run.status,
|
|
804
|
+
created_at: parsed.createdAtSql,
|
|
805
|
+
imported_at: importedAt
|
|
806
|
+
}, db);
|
|
807
|
+
for (const s of parsed.snapshots) {
|
|
808
|
+
const currentPath = path.join(runDir, s.file);
|
|
809
|
+
createSnapshot({
|
|
810
|
+
run_id: id,
|
|
811
|
+
route: s.route,
|
|
812
|
+
viewport: s.viewport,
|
|
813
|
+
baseline_path: path.join(root, 'baselines', s.file),
|
|
814
|
+
baseline_snapshot_path: s.status === 'NEW_BASELINE'
|
|
815
|
+
? currentPath
|
|
816
|
+
: s.files.baselineCopy ? path.join(runDir, 'baselines', s.file) : null,
|
|
817
|
+
baseline_sha256: s.baseline_sha256,
|
|
818
|
+
current_path: currentPath,
|
|
819
|
+
diff_path: s.files.diff ? path.join(runDir, s.file.replace(/\.png$/, '-diff.png')) : null,
|
|
820
|
+
mismatch_percentage: s.mismatch_percentage,
|
|
821
|
+
status: s.status
|
|
822
|
+
}, db);
|
|
823
|
+
}
|
|
824
|
+
recalculateRunStatus(id, db);
|
|
825
|
+
}
|
|
826
|
+
})();
|
|
827
|
+
} catch (err) {
|
|
828
|
+
for (const dir of moved) {
|
|
829
|
+
try {
|
|
830
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
831
|
+
} catch (cleanupErr) {
|
|
832
|
+
console.error(`[WARN] Could not remove ${dir} after a failed import: ${sanitizeForDisplay(cleanupErr.message)}`);
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
throw err;
|
|
836
|
+
}
|
|
837
|
+
}
|