visual-regression-ci 0.0.0-stage → 0.9.1
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 +839 -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,66 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { GITHUB_PACKAGE_SPEC, npxCommand } from '../shared/packageSpec.js';
|
|
4
|
+
import { toDisplayPath } from './display.js';
|
|
5
|
+
import { getToolVersion } from './manifest.js';
|
|
6
|
+
|
|
7
|
+
/** This package's CLI entry point (src/cli/index.js). */
|
|
8
|
+
export const CLI_FILE = fileURLToPath(new URL('./index.js', import.meta.url));
|
|
9
|
+
|
|
10
|
+
/** Where the Docker image (and so the GitHub Action's container) keeps visual-ci. */
|
|
11
|
+
const IMAGE_APP_DIR = '/app';
|
|
12
|
+
|
|
13
|
+
const SHELL_SAFE = /^[\w@%+=:,./-]+$/;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Text as one shell word: unchanged when it only has safe characters, otherwise in
|
|
17
|
+
* single quotes (a ' inside becomes '\'').
|
|
18
|
+
*
|
|
19
|
+
* @param {string} text
|
|
20
|
+
* @returns {string}
|
|
21
|
+
*/
|
|
22
|
+
export function shellQuote(text) {
|
|
23
|
+
const value = String(text);
|
|
24
|
+
return SHELL_SAFE.test(value) ? value : `'${value.replace(/'/g, "'\\''")}'`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The command a user should type to run visual-ci again, for hints such as
|
|
29
|
+
* "Install it with: <command> install-browsers". It depends on where this copy runs
|
|
30
|
+
* from, and never is a bare, unpinned `npx visual-ci` where visual-ci is not installed
|
|
31
|
+
* (npx would then run whatever version is latest on npm):
|
|
32
|
+
*
|
|
33
|
+
* - inside the GitHub Action's container (GITHUB_ACTIONS=true, visual-ci in /app): the
|
|
34
|
+
* reader is on their own machine, so `npx -y visual-regression-ci@<this version>`;
|
|
35
|
+
* - installed in the current project (node_modules above or at cwd): `npx visual-ci`,
|
|
36
|
+
* which npx resolves to that local copy;
|
|
37
|
+
* - from npx's cache (`npx visual-regression-ci@<version> ...`): the same `npx -y visual-regression-ci@<this version>`;
|
|
38
|
+
* - any other node_modules (a global install): `visual-ci`;
|
|
39
|
+
* - a checkout of this repository: `node <path to src/cli/index.js>`. (The Docker
|
|
40
|
+
* dashboard is such a checkout, in /app: its hints read `node src/cli/index.js`.)
|
|
41
|
+
*
|
|
42
|
+
* The version is this copy's own (package.json). If that can't be read, the npx cases
|
|
43
|
+
* fetch visual-ci from this repository instead: `npx -y -p github:... visual-ci`.
|
|
44
|
+
*
|
|
45
|
+
* @param {object} [options]
|
|
46
|
+
* @param {string} [options.file=CLI_FILE] - Absolute path of the running src/cli/index.js
|
|
47
|
+
* @param {string} [options.cwd=process.cwd()]
|
|
48
|
+
* @param {NodeJS.ProcessEnv} [options.env=process.env]
|
|
49
|
+
* @param {string} [options.version=getToolVersion()] - This copy's version
|
|
50
|
+
* @returns {string}
|
|
51
|
+
*/
|
|
52
|
+
export function cliCommand({ file = CLI_FILE, cwd = process.cwd(), env = process.env, version = getToolVersion() } = {}) {
|
|
53
|
+
const viaNpm = npxCommand(version) ?? `npx -y -p ${GITHUB_PACKAGE_SPEC} visual-ci`;
|
|
54
|
+
if (env.GITHUB_ACTIONS === 'true' && file.startsWith(`${IMAGE_APP_DIR}/`)) return viaNpm;
|
|
55
|
+
const parts = file.split(path.sep);
|
|
56
|
+
const nodeModules = parts.indexOf('node_modules');
|
|
57
|
+
if (nodeModules === -1) {
|
|
58
|
+
const shown = toDisplayPath(file, cwd);
|
|
59
|
+
return `node ${SHELL_SAFE.test(shown) ? shown : shellQuote(file)}`;
|
|
60
|
+
}
|
|
61
|
+
if (parts.includes('_npx')) return viaNpm;
|
|
62
|
+
const projectRoot = parts.slice(0, nodeModules).join(path.sep) || path.sep;
|
|
63
|
+
const rel = path.relative(projectRoot, cwd);
|
|
64
|
+
const cwdInProject = rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
|
|
65
|
+
return cwdInProject ? 'npx visual-ci' : 'visual-ci';
|
|
66
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { MANIFEST_FILENAME } from './manifest.js';
|
|
4
|
+
import { STDOUT_TARGET } from './result.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Checks for the `test --json <file>` target. The JSON must never replace the run's
|
|
8
|
+
* own run.json or markdown summary (that would make the run impossible to import),
|
|
9
|
+
* however the path is spelled: through a symlinked folder, a symlinked
|
|
10
|
+
* VISUAL_STORAGE_DIR, a hard link, or a different letter case on macOS/Windows.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const caseInsensitive = (platform) => platform === 'darwin' || platform === 'win32';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Like fs.realpathSync, but for a path that may not exist yet: the deepest existing
|
|
17
|
+
* ancestor is resolved and the rest appended.
|
|
18
|
+
*
|
|
19
|
+
* @param {string} p - Absolute path
|
|
20
|
+
* @returns {string}
|
|
21
|
+
*/
|
|
22
|
+
export function realpathLoose(p) {
|
|
23
|
+
const tail = [];
|
|
24
|
+
let current = p;
|
|
25
|
+
for (;;) {
|
|
26
|
+
try {
|
|
27
|
+
return path.join(fs.realpathSync.native(current), ...tail);
|
|
28
|
+
} catch {
|
|
29
|
+
const parent = path.dirname(current);
|
|
30
|
+
if (parent === current) return p;
|
|
31
|
+
tail.unshift(path.basename(current));
|
|
32
|
+
current = parent;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function sameFile(a, b) {
|
|
38
|
+
try {
|
|
39
|
+
const sa = fs.statSync(a);
|
|
40
|
+
const sb = fs.statSync(b);
|
|
41
|
+
return sa.dev === sb.dev && sa.ino === sb.ino;
|
|
42
|
+
} catch {
|
|
43
|
+
return false; // one of them does not exist (yet)
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The run files a --json target may not be. Paths built with path.join, like their writers do. */
|
|
48
|
+
export function protectedRunFiles(runsDir, summaryFile) {
|
|
49
|
+
return [
|
|
50
|
+
{ file: path.join(runsDir, MANIFEST_FILENAME), label: `run's ${MANIFEST_FILENAME}` },
|
|
51
|
+
{ file: path.join(runsDir, summaryFile || 'summary.md'), label: "run's markdown summary" }
|
|
52
|
+
];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Why a --json target can't be used, or null. Compares, for the run's run.json and
|
|
57
|
+
* summary: the resolved paths; the real paths of their folders plus the file name
|
|
58
|
+
* (case-folded on macOS/Windows); and, when both exist, device + inode. Call it up
|
|
59
|
+
* front (cheap, catches most mistakes) and again right before writing, when the run
|
|
60
|
+
* folder exists and symlinks resolve.
|
|
61
|
+
*
|
|
62
|
+
* @param {string|undefined} target - The --json value (relative to cwd)
|
|
63
|
+
* @param {{ runsDir?: string|null, summaryFile?: string, cwd?: string, platform?: string }} options
|
|
64
|
+
* @returns {string|null}
|
|
65
|
+
*/
|
|
66
|
+
export function jsonTargetConflict(target, { runsDir, summaryFile, cwd = process.cwd(), platform = process.platform } = {}) {
|
|
67
|
+
if (!target || target === STDOUT_TARGET || !runsDir) return null;
|
|
68
|
+
const file = path.resolve(cwd, target);
|
|
69
|
+
const fold = (p) => (caseInsensitive(platform) ? p.toLowerCase() : p);
|
|
70
|
+
const real = (p) => fold(path.join(realpathLoose(path.dirname(p)), path.basename(p)));
|
|
71
|
+
const realTarget = real(file);
|
|
72
|
+
|
|
73
|
+
for (const { file: runFile, label } of protectedRunFiles(runsDir, summaryFile)) {
|
|
74
|
+
if (fold(file) === fold(runFile) || realTarget === real(runFile) || sameFile(file, runFile)) {
|
|
75
|
+
return `--json cannot be "${target}": that is the ${label}`;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Why a --json target is not a file name, or null: empty, an existing directory, or a
|
|
83
|
+
* path ending in a separator ("out/").
|
|
84
|
+
*
|
|
85
|
+
* @param {string|undefined} target
|
|
86
|
+
* @param {{ cwd?: string }} [options]
|
|
87
|
+
* @returns {string|null}
|
|
88
|
+
*/
|
|
89
|
+
export function jsonTargetShapeProblem(target, { cwd = process.cwd() } = {}) {
|
|
90
|
+
if (target === undefined || target === STDOUT_TARGET) return null;
|
|
91
|
+
if (target.trim() === '') return '--json needs a file name, or "-" for stdout';
|
|
92
|
+
const isDir = /[\\/]$/.test(target) || (() => {
|
|
93
|
+
try {
|
|
94
|
+
return fs.statSync(path.resolve(cwd, target)).isDirectory();
|
|
95
|
+
} catch {
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
})();
|
|
99
|
+
return isDir ? `--json cannot be "${target}": that is a directory; give a file name such as result.json` : null;
|
|
100
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Human-readable CLI output. Normally progress goes to stdout and warnings/errors to
|
|
3
|
+
* stderr; with `--json -` stdout is reserved for the JSON result, so everything goes
|
|
4
|
+
* to stderr.
|
|
5
|
+
*
|
|
6
|
+
* @param {{ stdoutReserved?: boolean }} [options]
|
|
7
|
+
* @returns {{ info: (...args: unknown[]) => void, warn: (...args: unknown[]) => void, error: (...args: unknown[]) => void }}
|
|
8
|
+
*/
|
|
9
|
+
export function createLogger({ stdoutReserved = false } = {}) {
|
|
10
|
+
return {
|
|
11
|
+
info: (...args) => (stdoutReserved ? console.error(...args) : console.log(...args)),
|
|
12
|
+
warn: (...args) => console.warn(...args),
|
|
13
|
+
error: (...args) => console.error(...args)
|
|
14
|
+
};
|
|
15
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* run.json: a self-contained, machine-readable record of one test run, written into
|
|
7
|
+
* the run's folder (runs/<id>/run.json). CI uploads storage/runs/ as an artifact, so
|
|
8
|
+
* the record travels with the screenshots and a run can be re-created elsewhere
|
|
9
|
+
* (e.g. imported into a local dashboard) without the SQLite database.
|
|
10
|
+
*
|
|
11
|
+
* Paths are relative and use "/": current, diff and baseline_snapshot are relative to
|
|
12
|
+
* the run folder; baseline is relative to the shared baselines/ folder.
|
|
13
|
+
* Units: threshold_percentage and mismatch_percentage are both percentages (1 = 1%).
|
|
14
|
+
* baseline_sha256 is the hash of the baseline that was compared, or 'none' if there
|
|
15
|
+
* was no baseline; current_sha256/diff_sha256 let an importer verify the images.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
export const MANIFEST_SCHEMA = 'visual-ci-run';
|
|
19
|
+
export const MANIFEST_VERSION = 1;
|
|
20
|
+
export const MANIFEST_FILENAME = 'run.json';
|
|
21
|
+
|
|
22
|
+
let toolVersion;
|
|
23
|
+
|
|
24
|
+
/** The tool's version from package.json, read on first use ('unknown' if unreadable). */
|
|
25
|
+
export function getToolVersion() {
|
|
26
|
+
if (toolVersion === undefined) {
|
|
27
|
+
try {
|
|
28
|
+
toolVersion = JSON.parse(fs.readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version;
|
|
29
|
+
} catch {
|
|
30
|
+
toolVersion = 'unknown';
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return toolVersion;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const hashFile = (file) => (file ? crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex') : null);
|
|
37
|
+
|
|
38
|
+
/** SQLite's CURRENT_TIMESTAMP format (UTC), so DB rows and manifests sort alike. */
|
|
39
|
+
export function toSqliteTimestamp(date) {
|
|
40
|
+
return date.toISOString().replace('T', ' ').slice(0, 19);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function relativeInside(dir, file, label) {
|
|
44
|
+
if (!file) return null;
|
|
45
|
+
const rel = path.relative(dir, file);
|
|
46
|
+
if (!rel || rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) {
|
|
47
|
+
throw new Error(`Cannot record ${label} "${file}": it is not inside ${dir}`);
|
|
48
|
+
}
|
|
49
|
+
return rel.split(path.sep).join('/');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* @param {object} options
|
|
54
|
+
* @param {string} options.runId
|
|
55
|
+
* @param {Date} options.createdAt
|
|
56
|
+
* @param {{ branch?: string|null, commit_hash?: string|null, commit_sha?: string|null }} [options.gitInfo]
|
|
57
|
+
* @param {'PASSED'|'FAILED'} options.status
|
|
58
|
+
* @param {number} options.threshold - Allowed mismatch ratio from the config (0.01 = 1%)
|
|
59
|
+
* @param {number} options.pixelmatchThreshold - Per-pixel colour sensitivity used
|
|
60
|
+
* @param {boolean} options.strict - Whether missing baselines failed instead of being created
|
|
61
|
+
* @param {'compare'|'update-baselines'} options.mode
|
|
62
|
+
* @param {string} options.runDir - Absolute path of runs/<id>
|
|
63
|
+
* @param {string} options.baselinesDir - Absolute path of the shared baselines folder
|
|
64
|
+
* @param {object[]} options.results - Comparison results as produced by the CLI
|
|
65
|
+
* @returns {object} The manifest
|
|
66
|
+
*/
|
|
67
|
+
export function buildRunManifest({
|
|
68
|
+
runId, createdAt, gitInfo = {}, status, threshold, pixelmatchThreshold, strict, mode,
|
|
69
|
+
runDir, baselinesDir, results
|
|
70
|
+
}) {
|
|
71
|
+
const snapshots = results.map((r) => {
|
|
72
|
+
const currentPath = r.currentPath || r.filepath;
|
|
73
|
+
return {
|
|
74
|
+
route: r.route,
|
|
75
|
+
viewport: r.viewport,
|
|
76
|
+
viewport_size: r.width && r.height ? { width: r.width, height: r.height } : null,
|
|
77
|
+
status: r.status,
|
|
78
|
+
mismatch_percentage: r.mismatchPercentage || 0,
|
|
79
|
+
mismatched_pixels: r.mismatchedPixels ?? null,
|
|
80
|
+
total_pixels: r.totalPixels ?? null,
|
|
81
|
+
current: relativeInside(runDir, currentPath, 'screenshot'),
|
|
82
|
+
current_sha256: hashFile(currentPath),
|
|
83
|
+
diff: relativeInside(runDir, r.diffPath, 'diff image'),
|
|
84
|
+
diff_sha256: hashFile(r.diffPath),
|
|
85
|
+
baseline_snapshot: relativeInside(runDir, r.baselineSnapshotPath, 'baseline copy'),
|
|
86
|
+
baseline: relativeInside(baselinesDir, r.baselinePath, 'baseline'),
|
|
87
|
+
baseline_sha256: r.baselineSha256 || 'none'
|
|
88
|
+
};
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
// Backstop for colliding file names (config validation should already prevent them)
|
|
92
|
+
for (const key of ['current', 'diff', 'baseline']) {
|
|
93
|
+
const seen = new Set();
|
|
94
|
+
for (const s of snapshots) {
|
|
95
|
+
if (s[key] === null) continue;
|
|
96
|
+
if (seen.has(s[key])) throw new Error(`Two snapshots share the ${key} file "${s[key]}"`);
|
|
97
|
+
seen.add(s[key]);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return {
|
|
102
|
+
schema: MANIFEST_SCHEMA,
|
|
103
|
+
version: MANIFEST_VERSION,
|
|
104
|
+
tool: { name: 'visual-ci', version: getToolVersion() },
|
|
105
|
+
run: {
|
|
106
|
+
id: runId,
|
|
107
|
+
commit_hash: gitInfo.commit_hash || null,
|
|
108
|
+
commit_sha: gitInfo.commit_sha || null,
|
|
109
|
+
branch: gitInfo.branch || null,
|
|
110
|
+
status,
|
|
111
|
+
created_at: createdAt.toISOString(),
|
|
112
|
+
mode,
|
|
113
|
+
strict,
|
|
114
|
+
threshold_percentage: Math.round(threshold * 100 * 1e6) / 1e6, // 0.07 * 100 is 7.000000000000001
|
|
115
|
+
pixelmatch_threshold: pixelmatchThreshold
|
|
116
|
+
},
|
|
117
|
+
snapshots
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Writes run.json into the run folder (via a temp file + rename, so a reader never
|
|
123
|
+
* sees a half-written file).
|
|
124
|
+
*
|
|
125
|
+
* @returns {string} Path of the written manifest
|
|
126
|
+
*/
|
|
127
|
+
export function writeRunManifest(manifest, runDir) {
|
|
128
|
+
fs.mkdirSync(runDir, { recursive: true });
|
|
129
|
+
const target = path.join(runDir, MANIFEST_FILENAME);
|
|
130
|
+
const temp = `${target}.tmp-${process.pid}`;
|
|
131
|
+
try {
|
|
132
|
+
fs.writeFileSync(temp, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
|
|
133
|
+
fs.renameSync(temp, target);
|
|
134
|
+
} catch (err) {
|
|
135
|
+
fs.rmSync(temp, { force: true });
|
|
136
|
+
throw err;
|
|
137
|
+
}
|
|
138
|
+
return target;
|
|
139
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// File naming for screenshots, shared by capture, compare, config validation and
|
|
2
|
+
// run.json. Kept free of Playwright so lightweight modules can import it.
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Creates a clean filesystem-friendly slug from a URL route.
|
|
6
|
+
*
|
|
7
|
+
* @param {string} route - The route path (e.g. "/" or "/blog/post-1")
|
|
8
|
+
* @returns {string} Clean file slug
|
|
9
|
+
*/
|
|
10
|
+
export function getRouteSlug(route) {// converts a web address into a safe legal framework on our computer
|
|
11
|
+
// what this function does is that if removes / from page names so that it can be saved as a file
|
|
12
|
+
if (!route || route === '/') {
|
|
13
|
+
return 'index'; // returns the name of the homepage which is generally named index.html
|
|
14
|
+
}
|
|
15
|
+
return route
|
|
16
|
+
.replace(/^\/+/, '')// replaces the slashes at the very front of the address. ^ means at the beginning
|
|
17
|
+
.replace(/\/+$/, '')// replaces the slashes at the very last of the address ,$ means attthe end
|
|
18
|
+
.replace(/[^a-zA-Z0-9_-]/g, '_');// ^ means anything except. replaces anything except atoz and 0to9 ,_,-with _
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Generates standard screenshot filename.
|
|
23
|
+
*
|
|
24
|
+
* @param {string} route - URL route
|
|
25
|
+
* @param {string} viewportName - Viewport identifier
|
|
26
|
+
* @returns {string} Filename (e.g. "index-desktop.png")
|
|
27
|
+
*/
|
|
28
|
+
export function getSnapshotFilename(route, viewportName) {
|
|
29
|
+
const slug = getRouteSlug(route); // saves the slug of the address to slug variable
|
|
30
|
+
return `${slug}-${viewportName}.png`; // combines the slug the viewport name and the .png extension to form a clean organized filename
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Throws if two route/viewport pairs would write the same screenshot or diff file
|
|
35
|
+
* (e.g. "/a-b" @ "c" and "/a" @ "b-c" are both a-b-c.png, and a viewport named
|
|
36
|
+
* "m-diff" collides with the diff image of viewport "m"). Such runs silently
|
|
37
|
+
* overwrite each other's images.
|
|
38
|
+
*
|
|
39
|
+
* @param {string[]} routes
|
|
40
|
+
* @param {{ name: string }[]} viewports
|
|
41
|
+
*/
|
|
42
|
+
export function assertUniqueSnapshotFiles(routes, viewports) {
|
|
43
|
+
const owners = new Map();
|
|
44
|
+
for (const route of routes) {
|
|
45
|
+
for (const viewport of viewports) {
|
|
46
|
+
const owner = `route "${route}" @ viewport "${viewport.name}"`;
|
|
47
|
+
const file = getSnapshotFilename(route, viewport.name);
|
|
48
|
+
for (const name of [file, file.replace(/\.png$/, '-diff.png')]) {
|
|
49
|
+
const existing = owners.get(name);
|
|
50
|
+
if (existing) {
|
|
51
|
+
throw new Error(
|
|
52
|
+
`Invalid configuration: ${existing} and ${owner} would both write "${name}". ` +
|
|
53
|
+
'Rename a route or viewport so every screenshot gets its own file.'
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
owners.set(name, owner);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { mdCode } from '../shared/text.js';
|
|
4
|
+
import { cliCommand as defaultCliCommand } from './invocation.js';
|
|
5
|
+
|
|
6
|
+
/** The README section on creating baselines (same Docker image as CI). */
|
|
7
|
+
export const BASELINES_DOCS_URL = 'https://github.com/abhishek-k-33/Visual_Regression_Testing#baselines-in-your-repo';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Format a status string with an emoji badge for Markdown display.
|
|
11
|
+
* @param {string} status
|
|
12
|
+
* @returns {string}
|
|
13
|
+
*/
|
|
14
|
+
export function formatStatusBadge(status) {
|
|
15
|
+
switch (status) {
|
|
16
|
+
case 'MATCH':
|
|
17
|
+
return '🟢 **PASSED**';
|
|
18
|
+
case 'DIFF':
|
|
19
|
+
return '🔴 **FAILED**';
|
|
20
|
+
case 'NEW_BASELINE':
|
|
21
|
+
return '🟡 **NEW BASELINE**';
|
|
22
|
+
case 'MISSING_BASELINE':
|
|
23
|
+
return '🔴 **MISSING BASELINE**';
|
|
24
|
+
default:
|
|
25
|
+
return status;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Generate a GitHub Flavored Markdown summary report for a visual regression test run.
|
|
31
|
+
* @param {Object} options
|
|
32
|
+
* @param {string} options.runId
|
|
33
|
+
* @param {Object} [options.gitInfo]
|
|
34
|
+
* @param {string} [options.gitInfo.branch]
|
|
35
|
+
* @param {string} [options.gitInfo.commit_hash]
|
|
36
|
+
* @param {number} [options.threshold=0.01]
|
|
37
|
+
* @param {string|number} [options.elapsed='0']
|
|
38
|
+
* @param {number} options.passedCount
|
|
39
|
+
* @param {number} options.failedCount
|
|
40
|
+
* @param {number} options.newBaselineCount
|
|
41
|
+
* @param {Array<Object>} options.results
|
|
42
|
+
* @param {boolean} [options.githubActions] - Running in GitHub Actions (default: GITHUB_ACTIONS=true)
|
|
43
|
+
* @param {string} [options.cliCommand] - How to run visual-ci here (default: cliCommand())
|
|
44
|
+
* @returns {string}
|
|
45
|
+
*/
|
|
46
|
+
export function generateSummaryMarkdown(options) {
|
|
47
|
+
const {
|
|
48
|
+
runId,
|
|
49
|
+
gitInfo = {},
|
|
50
|
+
threshold = 0.01,
|
|
51
|
+
elapsed = '0',
|
|
52
|
+
passedCount = 0,
|
|
53
|
+
failedCount = 0,
|
|
54
|
+
newBaselineCount = 0,
|
|
55
|
+
results = [],
|
|
56
|
+
githubActions = process.env.GITHUB_ACTIONS === 'true'
|
|
57
|
+
} = options;
|
|
58
|
+
|
|
59
|
+
const totalSnapshots = results.length;
|
|
60
|
+
const isPassed = failedCount === 0;
|
|
61
|
+
const overallBadge = isPassed
|
|
62
|
+
? '✅ **PASSED**'
|
|
63
|
+
: `❌ **FAILED (${failedCount} regression${failedCount === 1 ? '' : 's'})**`;
|
|
64
|
+
|
|
65
|
+
const thresholdPercent = (threshold * 100).toFixed(2);
|
|
66
|
+
const branchName = gitInfo.branch ? mdCode(gitInfo.branch) : '_N/A_';
|
|
67
|
+
const commitHash = gitInfo.commit_hash ? mdCode(gitInfo.commit_hash) : '_N/A_';
|
|
68
|
+
|
|
69
|
+
const lines = [
|
|
70
|
+
'# 📸 Visual CI Test Report',
|
|
71
|
+
'',
|
|
72
|
+
'| Metric | Value |',
|
|
73
|
+
'| :--- | :--- |',
|
|
74
|
+
`| **Run ID** | ${mdCode(runId)} |`,
|
|
75
|
+
`| **Branch** | ${branchName} |`,
|
|
76
|
+
`| **Commit** | ${commitHash} |`,
|
|
77
|
+
`| **Overall Status** | ${overallBadge} |`,
|
|
78
|
+
`| **Total Snapshots** | ${totalSnapshots} |`,
|
|
79
|
+
`| **Passed (Match)** | ${passedCount} |`,
|
|
80
|
+
`| **Failed (Diff)** | ${failedCount} |`,
|
|
81
|
+
`| **New Baselines** | ${newBaselineCount} |`,
|
|
82
|
+
`| **Execution Time** | ${elapsed}s |`,
|
|
83
|
+
`| **Allowed Threshold** | ${thresholdPercent}% |`,
|
|
84
|
+
'',
|
|
85
|
+
'### Snapshot Breakdown',
|
|
86
|
+
'',
|
|
87
|
+
'| Status | Route | Viewport | Mismatch | Details |',
|
|
88
|
+
'| :--- | :--- | :--- | :--- | :--- |'
|
|
89
|
+
];
|
|
90
|
+
|
|
91
|
+
for (const r of results) {
|
|
92
|
+
const statusCol = formatStatusBadge(r.status);
|
|
93
|
+
// Routes and viewports come from the config: a backtick or | must not break the table.
|
|
94
|
+
const routeCol = mdCode(r.route);
|
|
95
|
+
const viewportCol = mdCode(r.viewport);
|
|
96
|
+
const mismatchCol = r.mismatchPercentage !== undefined
|
|
97
|
+
? `\`${r.mismatchPercentage.toFixed(2)}%\``
|
|
98
|
+
: '`0.00%`';
|
|
99
|
+
|
|
100
|
+
let detailsCol = 'Baseline matched';
|
|
101
|
+
if (r.status === 'DIFF') {
|
|
102
|
+
detailsCol = `Exceeded threshold (${thresholdPercent}%)`;
|
|
103
|
+
} else if (r.status === 'NEW_BASELINE') {
|
|
104
|
+
detailsCol = 'New baseline master initialized';
|
|
105
|
+
} else if (r.status === 'MISSING_BASELINE') {
|
|
106
|
+
detailsCol = 'No committed baseline (run with --update-baselines and commit it)';
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
lines.push(`| ${statusCol} | ${routeCol} | ${viewportCol} | ${mismatchCol} | ${detailsCol} |`);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
lines.push('');
|
|
113
|
+
|
|
114
|
+
if (!isPassed) {
|
|
115
|
+
lines.push('> ⚠️ **Action Required:** Visual differences were detected.');
|
|
116
|
+
lines.push('> - Review diff screenshots uploaded in the **`visual-regression-diffs`** workflow artifact.');
|
|
117
|
+
lines.push('> - Or inspect interactively on the local dashboard: `http://localhost:4000/runs/' + runId + '`.');
|
|
118
|
+
if (githubActions) {
|
|
119
|
+
// Most readers don't have visual-ci installed, and baselines must come from the same
|
|
120
|
+
// Docker image CI uses: point at the action's input, never at a bare `npx visual-ci`.
|
|
121
|
+
lines.push(`> - If changes are intended, create new baselines with the action's \`update-baselines: true\` input (they are rendered in the same Docker image as this check) and commit them: see [Baselines in your repo](${BASELINES_DOCS_URL}).`);
|
|
122
|
+
} else {
|
|
123
|
+
const command = `${options.cliCommand ?? defaultCliCommand()} test --update-baselines`;
|
|
124
|
+
lines.push(`> - If changes are intended, update the baselines with ${mdCode(command, { table: false })} and commit them.`);
|
|
125
|
+
}
|
|
126
|
+
lines.push('');
|
|
127
|
+
} else {
|
|
128
|
+
lines.push('> ✨ **All snapshots passed!** No unexpected visual regressions detected.');
|
|
129
|
+
lines.push('');
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
return lines.join('\n');
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Write summary markdown to disk and append to GITHUB_STEP_SUMMARY if available.
|
|
137
|
+
* @param {string} markdown
|
|
138
|
+
* @param {Object} options
|
|
139
|
+
* @param {string} options.runsDir
|
|
140
|
+
* @param {string} [options.summaryFileName='summary.md']
|
|
141
|
+
* @returns {{ runSummaryPath: string|null, stepSummaryWritten: boolean }} runSummaryPath is
|
|
142
|
+
* null when the summary could not be written
|
|
143
|
+
*/
|
|
144
|
+
export function writeSummaryReport(markdown, options = {}) {
|
|
145
|
+
const { runsDir, summaryFileName = 'summary.md' } = options;
|
|
146
|
+
let runSummaryPath = null;
|
|
147
|
+
let stepSummaryWritten = false;
|
|
148
|
+
|
|
149
|
+
if (runsDir) {
|
|
150
|
+
const target = path.join(runsDir, summaryFileName);
|
|
151
|
+
try {
|
|
152
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
153
|
+
fs.writeFileSync(target, markdown, 'utf8');
|
|
154
|
+
runSummaryPath = target; // only once it exists
|
|
155
|
+
} catch (err) {
|
|
156
|
+
console.warn(` [WARN] Failed to write summary to ${target}: ${err.message}`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// Also write to GitHub Actions step summary if running in CI
|
|
161
|
+
const githubStepSummary = process.env.GITHUB_STEP_SUMMARY;
|
|
162
|
+
if (githubStepSummary) {
|
|
163
|
+
try {
|
|
164
|
+
fs.appendFileSync(githubStepSummary, `\n${markdown}\n`, 'utf8');
|
|
165
|
+
stepSummaryWritten = true;
|
|
166
|
+
} catch (err) {
|
|
167
|
+
console.warn(` [WARN] Failed to write to GITHUB_STEP_SUMMARY: ${err.message}`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return { runSummaryPath, stepSummaryWritten };
|
|
172
|
+
}
|