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
package/package.json CHANGED
@@ -1,6 +1,78 @@
1
1
  {
2
2
  "name": "visual-regression-ci",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.9.0",
4
+ "description": "Self-hosted visual regression testing for CI: Playwright screenshots, pixel diffs, a review dashboard and a GitHub Action",
5
+ "keywords": [
6
+ "visual-regression",
7
+ "visual-testing",
8
+ "screenshot-testing",
9
+ "regression-testing",
10
+ "playwright",
11
+ "pixelmatch",
12
+ "screenshot",
13
+ "ci",
14
+ "github-actions",
15
+ "cli",
16
+ "dashboard"
17
+ ],
18
+ "homepage": "https://github.com/abhishek-k-33/Visual_Regression_Testing#readme",
19
+ "bugs": {
20
+ "url": "https://github.com/abhishek-k-33/Visual_Regression_Testing/issues"
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/abhishek-k-33/Visual_Regression_Testing.git"
25
+ },
26
+ "license": "MIT",
27
+ "author": "",
28
+ "type": "module",
29
+ "bin": {
30
+ "visual-ci": "src/cli/index.js"
31
+ },
32
+ "exports": {
33
+ "./package.json": "./package.json"
34
+ },
35
+ "files": [
36
+ "src/**/*.js",
37
+ "src/**/*.ejs",
38
+ "src/**/*.css",
39
+ "!src/**/*.test.js",
40
+ "README.md",
41
+ "LICENSE"
42
+ ],
43
+ "engines": {
44
+ "node": ">=22"
45
+ },
46
+ "scripts": {
47
+ "start": "node src/server/app.js",
48
+ "server": "node src/server/app.js",
49
+ "capture": "node src/cli/index.js capture",
50
+ "test:visual": "node src/cli/index.js test",
51
+ "demo": "node scripts/demo.js",
52
+ "demo:serve": "node scripts/serve-demo.js",
53
+ "demo:pages": "node scripts/build-static-demo.js --out _site --base /Visual_Regression_Testing",
54
+ "docker:build": "docker compose build",
55
+ "docker:dashboard": "docker compose up dashboard",
56
+ "docker:test": "docker compose run --rm runner",
57
+ "docker:update-baselines": "docker compose run --rm runner node src/cli/index.js test --update-baselines",
58
+ "test": "vitest run",
59
+ "check:package": "node scripts/check-package.js",
60
+ "prepublishOnly": "node scripts/check-package.js",
61
+ "version": "node scripts/sync-readme-version.js"
62
+ },
63
+ "dependencies": {
64
+ "better-sqlite3": "^13.2.0",
65
+ "commander": "^13.1.0",
66
+ "ejs": "^3.1.10",
67
+ "express": "^4.21.2",
68
+ "pixelmatch": "^7.1.0",
69
+ "playwright": "1.64.1",
70
+ "pngjs": "^7.0.0",
71
+ "yauzl": "^3.4.0"
72
+ },
73
+ "devDependencies": {
74
+ "@axe-core/playwright": "4.14.0",
75
+ "vitest": "^3.0.7",
76
+ "yaml": "^2.9.1"
77
+ }
78
+ }
@@ -0,0 +1,340 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ /**
5
+ * Turns the `visual-ci test --json` result that the GitHub Action's container wrote into
6
+ * the action's outputs (action.yml, step "parse", run through actions/github-script).
7
+ *
8
+ * The container sees the runner's workspace at /github/workspace and its own folder
9
+ * $RUNNER_TEMP/visual-ci at /visual-ci-temp (never all of $RUNNER_TEMP: that holds the
10
+ * runner's command files, GITHUB_ENV among them), and runs in
11
+ * /github/workspace/<working-directory>. The CLI records
12
+ * paths relative to that working directory (or absolute when they lie outside it), so a
13
+ * path is mapped back to the runner by joining it onto $GITHUB_WORKSPACE/<working-directory>,
14
+ * or by swapping the container mount prefix for the host one.
15
+ *
16
+ * Only node: builtins, so it runs inside github-script without `npm ci` in the action
17
+ * folder. Nothing here throws for a bad report: the action reports status "error" and
18
+ * fails at its last step instead, after the artifact upload had its chance.
19
+ */
20
+
21
+ export const CONTAINER_WORKSPACE = '/github/workspace';
22
+ export const CONTAINER_TEMP = '/visual-ci-temp';
23
+ /** The folder in $RUNNER_TEMP that is mounted at CONTAINER_TEMP (and holds the JSON result). */
24
+ export const TEMP_SUBDIR = 'visual-ci';
25
+ export const RESULT_SCHEMA = 'visual-ci-result';
26
+ export const RESULT_VERSION = 1;
27
+ export const UPLOAD_MODES = Object.freeze(['on-failure', 'always', 'never']);
28
+
29
+ /** Same rule as the CLI (capture.js) plus the length cap of `visual-ci import`. */
30
+ export const RUN_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
31
+
32
+ /** Every output the parse step sets (action.yml maps its outputs onto these). */
33
+ export const OUTPUT_NAMES = Object.freeze([
34
+ 'status',
35
+ 'exit-code',
36
+ 'total',
37
+ 'changed',
38
+ 'new-baselines',
39
+ 'run-id',
40
+ 'report-path',
41
+ 'summary-path',
42
+ 'run-dir',
43
+ 'upload',
44
+ 'upload-path'
45
+ ]);
46
+
47
+ /** Name of the JSON result the action asks the CLI for, in $RUNNER_TEMP/visual-ci. */
48
+ export function reportFileName(runId) {
49
+ return `visual-ci-${runId}.json`;
50
+ }
51
+
52
+ /** $RUNNER_TEMP/visual-ci: the only part of RUNNER_TEMP the container can see. */
53
+ export function hostTempDir(runnerTemp) {
54
+ return path.posix.join(path.posix.resolve(runnerTemp), TEMP_SUBDIR);
55
+ }
56
+
57
+ const isInsideOrSame = (child, parent) => {
58
+ const rel = path.posix.relative(parent, child);
59
+ return rel === '' || (rel !== '..' && !rel.startsWith('../') && !path.posix.isAbsolute(rel));
60
+ };
61
+
62
+ /** <storage>/runs/<runId>, strictly inside the workspace (by name): the only folder the action uploads. */
63
+ function isRunFolderPath(p, runId, workspace) {
64
+ const root = path.posix.resolve(workspace);
65
+ return path.posix.basename(p) === runId &&
66
+ path.posix.basename(path.posix.dirname(p)) === 'runs' &&
67
+ p !== root && isInsideOrSame(p, root);
68
+ }
69
+
70
+ /**
71
+ * What an upload of `dir` would contain: the number of regular files, and any entry that
72
+ * is a symlink (upload-artifact follows them, so one could pull files from anywhere on
73
+ * the runner into the artifact) or something other than a file or folder.
74
+ *
75
+ * @param {string} dir
76
+ * @param {typeof fs} [fsImpl]
77
+ * @returns {{ files: number, unsafe: string[] }}
78
+ */
79
+ export function inspectRunFolder(dir, fsImpl = fs) {
80
+ let files = 0;
81
+ const unsafe = [];
82
+ const walk = (current, rel) => {
83
+ for (const entry of fsImpl.readdirSync(current, { withFileTypes: true })) {
84
+ const relPath = rel ? `${rel}/${entry.name}` : entry.name;
85
+ if (entry.isSymbolicLink()) unsafe.push(relPath);
86
+ else if (entry.isDirectory()) walk(path.join(current, entry.name), relPath);
87
+ else if (entry.isFile()) files++;
88
+ else unsafe.push(relPath);
89
+ }
90
+ };
91
+ walk(dir, '');
92
+ return { files, unsafe };
93
+ }
94
+
95
+ /**
96
+ * Whether `dir` is really inside `root` once every symlink on the way is resolved (a
97
+ * textual check alone is fooled by e.g. workspace/storage -> /elsewhere).
98
+ */
99
+ function isReallyInside(dir, root, fsImpl) {
100
+ try {
101
+ const realDir = fsImpl.realpathSync(dir);
102
+ const realRoot = fsImpl.realpathSync(root);
103
+ return realDir !== realRoot && isInsideOrSame(realDir, realRoot);
104
+ } catch {
105
+ return false;
106
+ }
107
+ }
108
+
109
+ /** A relative working-directory input as a clean POSIX path ("." for the workspace root). */
110
+ export function normalizeWorkingDirectory(dir) {
111
+ const normalized = path.posix.normalize(String(dir ?? '.').trim() || '.').replace(/\/+$/, '');
112
+ return normalized === '' ? '.' : normalized;
113
+ }
114
+
115
+ /**
116
+ * A path from the result (container view) as a path on the runner, or null when it
117
+ * does not lie in a mounted folder (then it only ever existed inside the container).
118
+ *
119
+ * @param {unknown} p - As recorded in the result: relative to the working directory, or absolute
120
+ * @param {{ workspace: string, workingDirectory?: string, tempDir?: string }} hosts - tempDir:
121
+ * the host folder mounted at CONTAINER_TEMP ($RUNNER_TEMP/visual-ci)
122
+ * @returns {string|null}
123
+ */
124
+ export function toHostPath(p, { workspace, workingDirectory = '.', tempDir } = {}) {
125
+ if (typeof p !== 'string' || p === '' || p.includes('\0') || !workspace) return null;
126
+ const hostWorkspace = path.posix.resolve(workspace);
127
+ const mounts = [[CONTAINER_WORKSPACE, hostWorkspace]];
128
+ if (tempDir) mounts.push([CONTAINER_TEMP, path.posix.resolve(tempDir)]);
129
+
130
+ if (!path.posix.isAbsolute(p)) {
131
+ const containerCwd = path.posix.join(CONTAINER_WORKSPACE, normalizeWorkingDirectory(workingDirectory));
132
+ return toHostPath(path.posix.resolve(containerCwd, p), { workspace, tempDir });
133
+ }
134
+ const resolved = path.posix.resolve(p);
135
+ for (const [inContainer, onHost] of mounts) {
136
+ if (isInsideOrSame(resolved, inContainer)) {
137
+ return path.posix.join(onHost, path.posix.relative(inContainer, resolved));
138
+ }
139
+ }
140
+ return null;
141
+ }
142
+
143
+ /**
144
+ * Whether the run folder should be uploaded as an artifact.
145
+ *
146
+ * @param {string} mode - on-failure | always | never
147
+ * @param {number} exitCode - The action's exit code (0 pass, 1 diffs, 2 error)
148
+ * @param {boolean} hasFiles - The run folder exists and holds at least one file (an error
149
+ * before the first screenshot leaves it empty: nothing worth an artifact)
150
+ * @returns {boolean}
151
+ */
152
+ export function shouldUpload(mode, exitCode, hasFiles) {
153
+ if (!hasFiles) return false;
154
+ if (mode === 'always') return true;
155
+ if (mode === 'on-failure') return exitCode !== 0;
156
+ return false; // never (or an unknown mode, which the validate step already refuses)
157
+ }
158
+
159
+ export function readReport(file, fsImpl = fs) {
160
+ let text;
161
+ try {
162
+ text = fsImpl.readFileSync(file, 'utf8');
163
+ } catch (err) {
164
+ return { problem: err.code === 'ENOENT' ? 'visual-ci wrote no JSON result' : `the JSON result could not be read (${err.code || err.message})` };
165
+ }
166
+ let report;
167
+ try {
168
+ report = JSON.parse(text);
169
+ } catch {
170
+ return { problem: 'the JSON result is not valid JSON' };
171
+ }
172
+ if (!report || typeof report !== 'object' || Array.isArray(report)) return { problem: 'the JSON result is not an object' };
173
+ if (report.schema !== RESULT_SCHEMA || report.version !== RESULT_VERSION) {
174
+ return { problem: `the JSON result is not schema ${RESULT_SCHEMA} v${RESULT_VERSION}` };
175
+ }
176
+ if (!['passed', 'failed', 'error'].includes(report.status) || ![0, 1, 2].includes(report.exit_code)) {
177
+ return { problem: 'the JSON result has an invalid status or exit_code' };
178
+ }
179
+ return { report };
180
+ }
181
+
182
+ const count = (value) => (Number.isInteger(value) && value >= 0 ? value : 0);
183
+ const isDirectory = (p, fsImpl) => {
184
+ try {
185
+ return fsImpl.lstatSync(p).isDirectory(); // lstat: a symlinked run folder is never used
186
+ } catch {
187
+ return false;
188
+ }
189
+ };
190
+ const isFile = (p, fsImpl) => {
191
+ try {
192
+ return fsImpl.statSync(p).isFile();
193
+ } catch {
194
+ return false;
195
+ }
196
+ };
197
+
198
+ /**
199
+ * Computes the action outputs.
200
+ *
201
+ * @param {object} options
202
+ * @param {string} options.exitCode - The container's exit code, as the run step recorded it ('' if it never ran)
203
+ * @param {string} options.runId - The validated run id
204
+ * @param {string} options.workspace - $GITHUB_WORKSPACE
205
+ * @param {string} options.workingDirectory - The validated working-directory input
206
+ * @param {string} options.runnerTemp - $RUNNER_TEMP (the result is in its visual-ci folder)
207
+ * @param {string} options.uploadMode - on-failure | always | never
208
+ * @param {typeof fs} [options.fs]
209
+ * @returns {{ outputs: Record<string, string>, errors: string[], warnings: string[] }}
210
+ */
211
+ export function buildActionOutputs({ exitCode, runId, workspace, workingDirectory = '.', runnerTemp, uploadMode, fs: fsImpl = fs }) {
212
+ const errors = [];
213
+ const warnings = [];
214
+ const tempDir = runnerTemp ? hostTempDir(runnerTemp) : undefined;
215
+ const hosts = { workspace, workingDirectory, tempDir };
216
+ const reportFile = tempDir ? path.posix.join(tempDir, reportFileName(runId)) : '';
217
+
218
+ const rawCode = String(exitCode ?? '').trim();
219
+ const containerCode = /^\d{1,3}$/.test(rawCode) ? Number(rawCode) : null;
220
+
221
+ let report = null;
222
+ if (containerCode === null) {
223
+ errors.push('visual-ci did not run (no exit code was recorded; see the earlier steps).');
224
+ } else {
225
+ const read = reportFile ? readReport(reportFile, fsImpl) : { problem: 'RUNNER_TEMP is not set' };
226
+ if (read.problem) {
227
+ errors.push(`visual-ci exited with code ${containerCode}, but ${read.problem} (${reportFile || 'no report path'}). See the log above.`);
228
+ } else if (read.report.exit_code !== containerCode) {
229
+ errors.push(`visual-ci exited with code ${containerCode}, but its JSON result says ${read.report.exit_code}: the run did not finish normally (killed or out of memory?).`);
230
+ } else {
231
+ report = read.report;
232
+ }
233
+ }
234
+
235
+ const status = report ? report.status : 'error';
236
+ const actionExitCode = report ? report.exit_code : 2;
237
+ if (report?.status === 'error' && report.error) {
238
+ errors.push(`visual-ci failed: ${report.error.code}: ${report.error.message}`);
239
+ }
240
+
241
+ // The run folder: only this run's own folder (named after the run id) is ever uploaded.
242
+ let runDir = null;
243
+ if (report?.run) {
244
+ const id = report.run.id;
245
+ const mapped = toHostPath(report.run.run_dir, hosts);
246
+ if (id !== runId) {
247
+ warnings.push(`The JSON result is for run "${String(id)}", not "${runId}"; its folder is not used.`);
248
+ } else if (!mapped) {
249
+ warnings.push(`The run folder (${String(report.run.run_dir)}) is outside the workspace, so it cannot be uploaded.`);
250
+ } else if (!isRunFolderPath(mapped, runId, workspace)) {
251
+ warnings.push(`The run folder (${String(report.run.run_dir)}) is not a run folder inside the workspace, so it is not uploaded.`);
252
+ } else if (isDirectory(mapped, fsImpl) && !isReallyInside(mapped, workspace, fsImpl)) {
253
+ warnings.push(`The run folder (${String(report.run.run_dir)}) resolves outside the workspace (through a symlink), so it is not uploaded.`);
254
+ } else {
255
+ runDir = mapped;
256
+ }
257
+ }
258
+ const runDirExists = runDir !== null && isDirectory(runDir, fsImpl);
259
+ let hasFiles = false;
260
+ if (runDirExists) {
261
+ const { files, unsafe } = inspectRunFolder(runDir, fsImpl);
262
+ if (unsafe.length > 0) {
263
+ warnings.push(`The run folder contains ${unsafe.length} symlink(s) or special file(s) (e.g. ${unsafe[0]}), so it is not uploaded.`);
264
+ } else if (files === 0) {
265
+ warnings.push('The run folder is empty (visual-ci stopped before the first screenshot), so there is nothing to upload.');
266
+ } else {
267
+ hasFiles = true;
268
+ }
269
+ }
270
+ const summaryPath = report?.run ? toHostPath(report.run.summary, hosts) : null;
271
+ const upload = shouldUpload(uploadMode, actionExitCode, hasFiles);
272
+
273
+ const outputs = {
274
+ status,
275
+ 'exit-code': String(actionExitCode),
276
+ total: String(count(report?.counts?.total)),
277
+ changed: String(count(report?.counts?.changed)),
278
+ 'new-baselines': String(count(report?.counts?.new_baseline)),
279
+ 'run-id': runId || '',
280
+ 'report-path': reportFile && isFile(reportFile, fsImpl) ? reportFile : '',
281
+ 'summary-path': summaryPath && isFile(summaryPath, fsImpl) ? summaryPath : '',
282
+ 'run-dir': runDirExists ? runDir : '',
283
+ upload: upload ? 'true' : 'false',
284
+ 'upload-path': upload ? runDir : ''
285
+ };
286
+ return { outputs, errors, warnings };
287
+ }
288
+
289
+ /**
290
+ * Whether an artifact named `name` already exists in this workflow run (upload-artifact
291
+ * would then fail: names must be unique per run, e.g. across matrix legs). Best effort:
292
+ * listing needs `actions: read`, which the token may not have; then the answer is null.
293
+ *
294
+ * @param {{ github?: object, context?: object, name: string }} options
295
+ * @returns {Promise<boolean|null>}
296
+ */
297
+ export async function artifactNameTaken({ github, context, name }) {
298
+ const list = github?.rest?.actions?.listWorkflowRunArtifacts;
299
+ if (typeof list !== 'function' || !context?.repo || !context.runId || !name) return null;
300
+ try {
301
+ const { data } = await list({ owner: context.repo.owner, repo: context.repo.repo, run_id: context.runId, name, per_page: 100 });
302
+ return (data?.artifacts || []).some((a) => a.name === name && !a.expired);
303
+ } catch {
304
+ return null; // e.g. 403 without actions: read
305
+ }
306
+ }
307
+
308
+ /**
309
+ * Entry point for the action's github-script step: reads the step's env, sets the
310
+ * outputs and reports problems as annotations. Never fails the step.
311
+ *
312
+ * @param {{ core: { setOutput: Function, error: Function, warning: Function, info: Function },
313
+ * github?: object, context?: object }} ctx - github-script's core, github and context
314
+ * @param {NodeJS.ProcessEnv} [env]
315
+ * @returns {Promise<ReturnType<typeof buildActionOutputs>>}
316
+ */
317
+ export async function run({ core, github, context }, env = process.env) {
318
+ const result = buildActionOutputs({
319
+ exitCode: env.VISUAL_CI_EXIT_CODE,
320
+ runId: env.VISUAL_CI_RUN_ID,
321
+ workspace: env.GITHUB_WORKSPACE,
322
+ workingDirectory: env.VISUAL_CI_WORKING_DIRECTORY,
323
+ runnerTemp: env.RUNNER_TEMP,
324
+ uploadMode: env.VISUAL_CI_UPLOAD_ARTIFACT
325
+ });
326
+ if (result.outputs.upload === 'true') {
327
+ const name = env.VISUAL_CI_ARTIFACT_NAME;
328
+ const taken = await artifactNameTaken({ github, context, name });
329
+ if (taken) {
330
+ result.warnings.push(`An artifact named "${name}" already exists in this workflow run, so the upload will fail. ` +
331
+ 'In a matrix, or when this action runs more than once in a job, give each use its own artifact-name (and run-id).');
332
+ }
333
+ }
334
+ for (const message of result.errors) core.error(message);
335
+ for (const message of result.warnings) core.warning(message);
336
+ for (const name of OUTPUT_NAMES) core.setOutput(name, result.outputs[name]);
337
+ core.info(`visual-ci: status=${result.outputs.status}, exit code ${result.outputs['exit-code']}, ` +
338
+ `${result.outputs.total} snapshot(s), ${result.outputs.changed} changed, ${result.outputs['new-baselines']} new baseline(s)`);
339
+ return result;
340
+ }