@whzxc/agent-design-gallery 0.6.0 → 0.8.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/README.md +12 -1
- package/package.json +1 -1
- package/public/app.js +38 -10
- package/public/arrangement-worker.js +11 -0
- package/public/arrangement.js +49 -0
- package/public/assets.js +16 -4
- package/public/layout.js +29 -13
- package/src/cli-output.mjs +258 -0
- package/src/cli.mjs +120 -45
- package/src/http.mjs +1 -0
- package/src/hub/auth.mjs +2 -1
- package/src/hub/proxy.mjs +5 -3
- package/src/hub/registry.mjs +57 -23
- package/src/hub.mjs +36 -21
- package/src/lifecycle.mjs +109 -0
- package/src/link.mjs +10 -9
- package/src/open.mjs +58 -54
- package/src/perf.mjs +12 -0
- package/src/server.mjs +78 -41
- package/src/service.mjs +115 -94
- package/src/toolkit/arch-git.mjs +142 -10
- package/src/toolkit/arch-overlay.mjs +1 -1
- package/src/toolkit/arch.mjs +62 -58
- package/src/toolkit/browser.mjs +38 -12
- package/src/toolkit/build-store.mjs +11 -3
- package/src/toolkit/build-worker.mjs +4 -1
- package/src/toolkit/build.mjs +26 -2
- package/src/toolkit/commands.mjs +158 -86
- package/src/toolkit/compare.mjs +93 -46
- package/src/toolkit/config.mjs +23 -20
- package/src/toolkit/diff-inputs.mjs +239 -0
- package/src/toolkit/diff-policy.mjs +28 -0
- package/src/toolkit/diff.mjs +258 -0
- package/src/toolkit/migrate.mjs +42 -30
- package/src/toolkit/part-diff.mjs +118 -0
- package/src/toolkit/part-snapshot.mjs +264 -0
- package/src/toolkit/pixel-diff.mjs +103 -0
- package/src/toolkit/project.mjs +45 -33
- package/src/toolkit/results.mjs +44 -0
- package/src/toolkit/runtime.d.ts +2 -1
- package/src/toolkit/tokens.mjs +5 -4
package/src/toolkit/config.mjs
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
+
import { CliError } from '../cli-output.mjs';
|
|
3
4
|
import { pathToFileURL } from 'node:url';
|
|
4
5
|
import { createRequire } from 'node:module';
|
|
5
6
|
import { build } from 'esbuild';
|
|
6
7
|
import { sourceDirectories, archFiles } from './project.mjs';
|
|
8
|
+
import { resolveDiffPolicy } from './diff-policy.mjs';
|
|
7
9
|
|
|
8
10
|
export const VERSION = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url))).version;
|
|
9
11
|
export const UPDATE = 'npm install -g @whzxc/agent-design-gallery';
|
|
@@ -18,7 +20,7 @@ export function legacyConfigFile(directory) {
|
|
|
18
20
|
export function requireMigration(directory) {
|
|
19
21
|
const old = legacyConfigFile(directory);
|
|
20
22
|
if (old && !CONFIG_NAMES.some(name => existsSync(path.join(directory, name)))) {
|
|
21
|
-
throw
|
|
23
|
+
throw new CliError('MIGRATION_REQUIRED', `Found ${old}; run adg migrate ${JSON.stringify(directory)} before using this project.`, { context: { project: directory } });
|
|
22
24
|
}
|
|
23
25
|
}
|
|
24
26
|
|
|
@@ -36,7 +38,7 @@ export function discoverRoot(cwd = process.cwd()) {
|
|
|
36
38
|
|
|
37
39
|
function versionParts(value) {
|
|
38
40
|
const match = value.match(/^(\d+)\.(\d+)\.(\d+)(?:-([\w.-]+))?(?:\+[\w.-]+)?$/);
|
|
39
|
-
if (!match) throw new
|
|
41
|
+
if (!match) throw new CliError('CONFIG_INVALID', `Invalid version ${value}; use major.minor.patch in requires`);
|
|
40
42
|
return [...match.slice(1, 4).map(Number), match[4]];
|
|
41
43
|
}
|
|
42
44
|
function order(a, b) {
|
|
@@ -59,13 +61,13 @@ function order(a, b) {
|
|
|
59
61
|
// Unsupported syntax fails explicitly instead of silently accepting a version.
|
|
60
62
|
export function satisfies(version, range) {
|
|
61
63
|
const actual = versionParts(version);
|
|
62
|
-
if (typeof range !== 'string' || !range.trim()) throw new
|
|
64
|
+
if (typeof range !== 'string' || !range.trim()) throw new CliError('CONFIG_INVALID', 'Invalid requires; use a range such as >=0.3.0');
|
|
63
65
|
const alternatives = range.split('||').map(branch => {
|
|
64
66
|
const terms = branch.trim().replace(/(>=|<=|>|<|=|\^|~)\s+/g, '$1').split(/\s+/);
|
|
65
67
|
return terms.map(term => {
|
|
66
68
|
if (term === '*') return !actual[3];
|
|
67
69
|
const match = term.match(/^(>=|<=|>|<|=|\^|~)?(\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?)$/);
|
|
68
|
-
if (!match) throw new
|
|
70
|
+
if (!match) throw new CliError('CONFIG_INVALID', `Unsupported requires ${range}; use comparisons with full versions, such as >=0.3.0`);
|
|
69
71
|
const target = versionParts(match[2]), delta = order(actual, target), op = match[1] ?? '=';
|
|
70
72
|
if (actual[3] && (!target[3] || actual.slice(0, 3).some((v, i) => v !== target[i]))) return false;
|
|
71
73
|
if (op === '^' || op === '~') {
|
|
@@ -82,7 +84,7 @@ export function satisfies(version, range) {
|
|
|
82
84
|
|
|
83
85
|
export function viewport(value) {
|
|
84
86
|
const match = typeof value === 'string' && value.match(/^([1-9]\d*)x([1-9]\d*)$/);
|
|
85
|
-
if (!match) throw new
|
|
87
|
+
if (!match) throw new CliError('CONFIG_INVALID', `Invalid viewport ${value}; use <width>x<height>, for example 1280x800`);
|
|
86
88
|
return { width: Number(match[1]), height: Number(match[2]) };
|
|
87
89
|
}
|
|
88
90
|
async function importConfig(file) {
|
|
@@ -108,28 +110,29 @@ async function importConfig(file) {
|
|
|
108
110
|
}}] });
|
|
109
111
|
return (await import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}`)).default;
|
|
110
112
|
}
|
|
111
|
-
export async function loadConfig(cwd = process.cwd(), { checkVersion = true } = {}) {
|
|
112
|
-
const root = discoverRoot(cwd), file = configFile(root);
|
|
113
|
+
export async function loadConfig(cwd = process.cwd(), { checkVersion = true, discover = true } = {}) {
|
|
114
|
+
const root = discover ? discoverRoot(cwd) : path.resolve(cwd), file = configFile(root);
|
|
115
|
+
if (!discover) requireMigration(root);
|
|
113
116
|
let config = {};
|
|
114
117
|
if (file) {
|
|
115
118
|
try { config = await importConfig(file); }
|
|
116
|
-
catch (error) { throw new
|
|
119
|
+
catch (error) { throw new CliError('CONFIG_INVALID', `Cannot load ${file}: ${error.message}; fix ${path.basename(file)}`, { cause: error }); }
|
|
117
120
|
}
|
|
118
|
-
if (!config || typeof config !== 'object' || Array.isArray(config)) throw new
|
|
119
|
-
if (config.name !== undefined && (typeof config.name !== 'string' || !config.name.trim())) throw new
|
|
121
|
+
if (!config || typeof config !== 'object' || Array.isArray(config)) throw new CliError('CONFIG_INVALID', 'Export a default object from adg.config.mjs');
|
|
122
|
+
if (config.name !== undefined && (typeof config.name !== 'string' || !config.name.trim())) throw new CliError('CONFIG_INVALID', 'Set name to a non-empty project name in the ADG config');
|
|
120
123
|
const compatible = config.requires === undefined || satisfies(VERSION, config.requires);
|
|
121
|
-
if (checkVersion && !compatible) throw new
|
|
122
|
-
for (const key of ['design', 'output', 'arch']) if (config[key] !== undefined && !(key === 'arch' && config[key] === false) && (typeof config[key] !== 'string' || !config[key].trim())) throw new
|
|
123
|
-
if (config.check !== undefined && (!config.check || typeof config.check!=='object' || Array.isArray(config.check))) throw new
|
|
124
|
-
if (config.check?.importDirection !== undefined && typeof config.check.importDirection!=='boolean') throw new
|
|
124
|
+
if (checkVersion && !compatible) throw new CliError('VERSION_UNSATISFIED', `ADG ${VERSION} does not satisfy requires ${config.requires}; run ${UPDATE}`);
|
|
125
|
+
for (const key of ['design', 'output', 'arch']) if (config[key] !== undefined && !(key === 'arch' && config[key] === false) && (typeof config[key] !== 'string' || !config[key].trim())) throw new CliError('CONFIG_INVALID', `Set ${key} to a directory path in adg.config.mjs`);
|
|
126
|
+
if (config.check !== undefined && (!config.check || typeof config.check!=='object' || Array.isArray(config.check))) throw new CliError('CONFIG_INVALID', 'Set check to an object in adg.config.mjs');
|
|
127
|
+
if (config.check?.importDirection !== undefined && typeof config.check.importDirection!=='boolean') throw new CliError('CONFIG_INVALID', 'Set check.importDirection to true or false in adg.config.mjs');
|
|
125
128
|
const compare = { port: 5188, viewport: '1280x800', ...config.compare };
|
|
126
129
|
viewport(compare.viewport);
|
|
127
|
-
if (!Number.isInteger(compare.port) || compare.port < 1 || compare.port > 65535) throw new
|
|
128
|
-
for (const key of ['start', 'fixture', 'ready', 'texts']) if (compare[key] !== undefined && typeof compare[key] !== 'function') throw new
|
|
129
|
-
if (compare.block !== undefined && (!Array.isArray(compare.block) || compare.block.some(value => typeof value !== 'string'))) throw new
|
|
130
|
-
if (config.check?.archMaxEdges !== undefined && (!Number.isInteger(config.check.archMaxEdges) || config.check.archMaxEdges < 0)) throw
|
|
131
|
-
if (typeof config.arch === 'string' && (path.isAbsolute(config.arch) || path.relative(root,path.resolve(root,config.arch)).startsWith('..'))) throw
|
|
130
|
+
if (!Number.isInteger(compare.port) || compare.port < 1 || compare.port > 65535) throw new CliError('CONFIG_INVALID', 'Set compare.port to an integer from 1 to 65535 in adg.config.mjs');
|
|
131
|
+
for (const key of ['start', 'fixture', 'ready', 'texts']) if (compare[key] !== undefined && typeof compare[key] !== 'function') throw new CliError('CONFIG_INVALID', `Set compare.${key} to a function in adg.config.mjs`);
|
|
132
|
+
if (compare.block !== undefined && (!Array.isArray(compare.block) || compare.block.some(value => typeof value !== 'string'))) throw new CliError('CONFIG_INVALID', 'Set compare.block to an array of request patterns in adg.config.mjs');
|
|
133
|
+
if (config.check?.archMaxEdges !== undefined && (!Number.isInteger(config.check.archMaxEdges) || config.check.archMaxEdges < 0)) throw new CliError('CONFIG_INVALID', 'Set check.archMaxEdges to a non-negative integer in adg.config.mjs');
|
|
134
|
+
if (typeof config.arch === 'string' && (path.isAbsolute(config.arch) || path.relative(root,path.resolve(root,config.arch)).startsWith('..'))) throw new CliError('CONFIG_INVALID', 'Set arch to a project-root-relative directory in adg.config.mjs');
|
|
132
135
|
const arch = config.arch === false ? false : path.resolve(root,config.arch ?? 'arch');
|
|
133
136
|
const design=path.resolve(root,config.design??'design');
|
|
134
|
-
return { root, name: config.name ?? path.basename(root), requires: config.requires ?? null, compatible, archDirectory: arch, arch: arch && (config.arch !== undefined || archFiles(arch).length) ? arch : false, sources: sourceDirectories({...config,design}), design, output: path.resolve(root, config.output ?? 'output/design'), check:{archMaxEdges:30,importDirection:true,...config.check}, compare };
|
|
137
|
+
return { root, name: config.name ?? path.basename(root), requires: config.requires ?? null, compatible, archDirectory: arch, arch: arch && (config.arch !== undefined || archFiles(arch).length) ? arch : false, sources: sourceDirectories({...config,design}), design, output: path.resolve(root, config.output ?? 'output/design'), check:{archMaxEdges:30,importDirection:true,...config.check}, compare, diff: resolveDiffPolicy(config.diff) };
|
|
135
138
|
}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { mkdir, readFile, realpath, rm, symlink } from 'node:fs/promises';
|
|
4
|
+
import { resolveBase, materializeBase, sourceRenames, revisionValue, revisionError } from './arch-git.mjs';
|
|
5
|
+
import { loadConfig, legacyConfigFile } from './config.mjs';
|
|
6
|
+
import { selectSources, relative } from './project.mjs';
|
|
7
|
+
import { buildSource } from './build.mjs';
|
|
8
|
+
import { cleanup } from './results.mjs';
|
|
9
|
+
import { CliError, withHumanOutputMapping } from '../cli-output.mjs';
|
|
10
|
+
|
|
11
|
+
const environmentFiles = ['package.json', 'package-lock.json', 'npm-shrinkwrap.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lock', 'bun.lockb'];
|
|
12
|
+
const slash = value => value.split(path.sep).join('/');
|
|
13
|
+
const outside = value => value === '..' || value.startsWith(`..${path.sep}`) || path.isAbsolute(value);
|
|
14
|
+
const frameKey = ({ source, frame }) => JSON.stringify([source, frame]);
|
|
15
|
+
|
|
16
|
+
async function optionalBytes(file) {
|
|
17
|
+
try { return await readFile(file); }
|
|
18
|
+
catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function reuseEnvironment(base, tree, root) {
|
|
22
|
+
const changedFiles = [];
|
|
23
|
+
for (let directory = root; ; directory = path.dirname(directory)) {
|
|
24
|
+
const repositoryPath = path.relative(base.root, directory);
|
|
25
|
+
const destination = path.join(tree.directory, repositoryPath);
|
|
26
|
+
const modules = path.join(directory, 'node_modules');
|
|
27
|
+
if (existsSync(modules)) {
|
|
28
|
+
await mkdir(destination, { recursive: true });
|
|
29
|
+
const link = path.join(destination, 'node_modules');
|
|
30
|
+
await rm(link, { recursive: true, force: true });
|
|
31
|
+
await symlink(await realpath(modules), link, 'junction');
|
|
32
|
+
}
|
|
33
|
+
for (const name of environmentFiles) {
|
|
34
|
+
const [before, after] = await Promise.all([
|
|
35
|
+
optionalBytes(path.join(destination, name)), optionalBytes(path.join(directory, name)),
|
|
36
|
+
]);
|
|
37
|
+
if (before === null && after === null) continue;
|
|
38
|
+
if (!before || !after || !before.equals(after)) changedFiles.push(slash(path.join(repositoryPath, name)));
|
|
39
|
+
}
|
|
40
|
+
if (directory === base.root) break;
|
|
41
|
+
}
|
|
42
|
+
return { reused: true, changedFiles: changedFiles.sort() };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function importFailure(error) {
|
|
46
|
+
if (!error) return false;
|
|
47
|
+
if (['ERR_MODULE_NOT_FOUND', 'MODULE_NOT_FOUND', 'ERR_PACKAGE_PATH_NOT_EXPORTED', 'ERR_UNSUPPORTED_DIR_IMPORT'].includes(error.code)) return true;
|
|
48
|
+
const diagnostics = error.errors ?? [];
|
|
49
|
+
return diagnostics.some(item => /(?:Could not|Cannot) resolve|Could not read from file/.test(item.text)) || importFailure(error.cause);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function historicalFailure(error) {
|
|
53
|
+
if (!importFailure(error)) return error;
|
|
54
|
+
return new CliError('DIFF_BASE_DEPENDENCIES_UNAVAILABLE', `Historical import failed: ${error.message}`, { cause: error });
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function inventory(config, repository) {
|
|
58
|
+
return new Map(selectSources(config, [], { write: false }).map(file => {
|
|
59
|
+
const source = relative(config, file);
|
|
60
|
+
if (outside(path.relative(repository, file))) {
|
|
61
|
+
throw new CliError('CONFIG_INVALID', `Source ${file} is outside the revision tree.`);
|
|
62
|
+
}
|
|
63
|
+
return [source, file];
|
|
64
|
+
}));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function selectedSources(config, beforeConfig, root, union, args) {
|
|
68
|
+
if (!args.length) return [...union].sort();
|
|
69
|
+
const previousDesign = path.resolve(root, path.relative(beforeConfig.root, beforeConfig.design));
|
|
70
|
+
const selected = [];
|
|
71
|
+
for (const arg of args) {
|
|
72
|
+
let candidates;
|
|
73
|
+
if (path.isAbsolute(arg)) {
|
|
74
|
+
const absolute = existsSync(arg) ? await realpath(arg) : path.resolve(arg);
|
|
75
|
+
if (outside(path.relative(root, absolute))) throw new CliError('SOURCE_NOT_FOUND', `Source ${arg} is outside the project root.`);
|
|
76
|
+
candidates = [absolute];
|
|
77
|
+
} else candidates = [path.resolve(root, arg), path.resolve(config.design, arg), path.resolve(previousDesign, arg)];
|
|
78
|
+
const sources = candidates.map(file => {
|
|
79
|
+
if (!/\.(?:tsx|mmd)$/.test(file)) file += '.tsx';
|
|
80
|
+
return slash(path.relative(root, file));
|
|
81
|
+
});
|
|
82
|
+
const found = sources.find(source => union.has(source));
|
|
83
|
+
if (!found) throw new CliError('SOURCE_NOT_FOUND', `Unknown source ${arg}; choose a source present at the base or in the working files.`);
|
|
84
|
+
selected.push(found);
|
|
85
|
+
}
|
|
86
|
+
return [...new Set(selected)];
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Match exact source/name identities and retain unmatched rename candidates. */
|
|
90
|
+
export function matchDiffFrames(sources, before, after, renames = [], frame = undefined) {
|
|
91
|
+
const rows = [];
|
|
92
|
+
for (const source of sources) {
|
|
93
|
+
const oldFrames = new Map((before.get(source)?.frames ?? []).map(value => [value.name, value]));
|
|
94
|
+
const newFrames = new Map((after.get(source)?.frames ?? []).map(value => [value.name, value]));
|
|
95
|
+
const names = new Set([...newFrames.keys(), ...oldFrames.keys()]);
|
|
96
|
+
for (const name of names) {
|
|
97
|
+
if (frame !== undefined && name !== frame) continue;
|
|
98
|
+
const old = oldFrames.get(name) ?? null, current = newFrames.get(name) ?? null;
|
|
99
|
+
rows.push({
|
|
100
|
+
source, frame: name, before: old, after: current,
|
|
101
|
+
status: old && current ? 'matched' : old ? 'removed' : 'added',
|
|
102
|
+
matchKind: old && current ? 'exact' : 'unmatched', matchCandidates: [],
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
if (frame !== undefined && !rows.length) throw new CliError('FRAME_NOT_FOUND', `Unknown frame ${frame}; choose a frame present on either side.`);
|
|
107
|
+
const removed = rows.filter(row => row.status === 'removed');
|
|
108
|
+
const added = rows.filter(row => row.status === 'added');
|
|
109
|
+
const addedBySource = groupFrames(added, 'source'), addedByName = groupFrames(added, 'frame');
|
|
110
|
+
const removedByName = groupFrames(removed, 'frame');
|
|
111
|
+
const movedSources = new Map(renames.map(rename => [rename.before, rename.after]));
|
|
112
|
+
for (const old of removed) {
|
|
113
|
+
const candidates = new Set([
|
|
114
|
+
...(addedBySource.get(old.source) ?? []),
|
|
115
|
+
...(addedBySource.get(movedSources.get(old.source)) ?? []),
|
|
116
|
+
]);
|
|
117
|
+
const sameName = addedByName.get(old.frame) ?? [];
|
|
118
|
+
if (removedByName.get(old.frame).length === 1 && sameName.length === 1) candidates.add(sameName[0]);
|
|
119
|
+
for (const current of candidates) {
|
|
120
|
+
old.matchKind = current.matchKind = 'renamed_or_unknown';
|
|
121
|
+
old.matchCandidates.push({ source: current.source, frame: current.frame });
|
|
122
|
+
current.matchCandidates.push({ source: old.source, frame: old.frame });
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return rows;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function groupFrames(rows, field) {
|
|
129
|
+
const groups = new Map();
|
|
130
|
+
for (const row of rows) {
|
|
131
|
+
const values = groups.get(row[field]) ?? [];
|
|
132
|
+
values.push(row);
|
|
133
|
+
groups.set(row[field], values);
|
|
134
|
+
}
|
|
135
|
+
return groups;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Prepare revision inputs. The caller closes the session and owns any supplied browser. */
|
|
139
|
+
export async function prepareDiffInputs(config, args = [], options = {}) {
|
|
140
|
+
const base = await resolveBase(config, options.base);
|
|
141
|
+
const root = await realpath(config.root);
|
|
142
|
+
const tree = await materializeBase(base);
|
|
143
|
+
const warnings = [];
|
|
144
|
+
try {
|
|
145
|
+
const configDependencies = await reuseEnvironment(base, tree, root);
|
|
146
|
+
if (configDependencies.changedFiles.length) warnings.push({
|
|
147
|
+
code: 'DIFF_BASE_ENVIRONMENT_REUSED',
|
|
148
|
+
message: `Base config uses current node_modules; environment files differ: ${configDependencies.changedFiles.join(', ')}.`, next: [],
|
|
149
|
+
});
|
|
150
|
+
const beforeRoot = path.join(tree.directory, path.relative(base.root, root));
|
|
151
|
+
const baseMigration = { applied: false, changes: [] };
|
|
152
|
+
const translate = value => revisionValue(value, tree.directory, base.root);
|
|
153
|
+
let beforeConfig;
|
|
154
|
+
try {
|
|
155
|
+
beforeConfig = await withHumanOutputMapping(async () => {
|
|
156
|
+
if (legacyConfigFile(beforeRoot)) {
|
|
157
|
+
const { migrate } = await import('./migrate.mjs');
|
|
158
|
+
const migrated = await migrate(beforeRoot, () => {});
|
|
159
|
+
baseMigration.applied = true;
|
|
160
|
+
baseMigration.changes = migrated.changes.map(change => ({
|
|
161
|
+
...change, path: relative({ root: beforeRoot }, change.path),
|
|
162
|
+
from: change.from === null ? null : relative({ root: beforeRoot }, change.from),
|
|
163
|
+
}));
|
|
164
|
+
warnings.push({ code: 'DIFF_BASE_MIGRATED', message: `Migrated the disposable base ${base.sha.slice(0, 7)} to ADG.`, next: [] });
|
|
165
|
+
}
|
|
166
|
+
return loadConfig(beforeRoot, { discover: false });
|
|
167
|
+
}, translate);
|
|
168
|
+
} catch (error) { throw revisionError(historicalFailure(error), tree.directory, base); }
|
|
169
|
+
const before = { config: beforeConfig, sources: inventory(beforeConfig, tree.directory) };
|
|
170
|
+
// Resolve symlinked project roots consistently with the Git base identity.
|
|
171
|
+
const currentConfig = { ...config, root };
|
|
172
|
+
for (const key of ['design', 'arch', 'archDirectory', 'output']) {
|
|
173
|
+
if (config[key]) currentConfig[key] = path.resolve(root, path.relative(config.root, config[key]));
|
|
174
|
+
}
|
|
175
|
+
const after = { config: currentConfig, sources: inventory(currentConfig, base.root) };
|
|
176
|
+
const union = new Set([...before.sources.keys(), ...after.sources.keys()]);
|
|
177
|
+
const sources = await selectedSources(currentConfig, beforeConfig, root, union, args);
|
|
178
|
+
const renames = (await sourceRenames(base)).flatMap(rename => {
|
|
179
|
+
const old = path.relative(root, path.join(base.root, rename.before));
|
|
180
|
+
const current = path.relative(root, path.join(base.root, rename.after));
|
|
181
|
+
return outside(old) || outside(current) ? [] : [{ before: slash(old), after: slash(current) }];
|
|
182
|
+
});
|
|
183
|
+
let closed = false;
|
|
184
|
+
return {
|
|
185
|
+
base, before, after, sources, warnings, translateDiagnostic: translate, environment: { configDependencies, baseMigration },
|
|
186
|
+
async buildFrames({ browser } = {}) {
|
|
187
|
+
if (closed) throw new CliError('SOURCE_BUILD_FAILED', 'Diff inputs are closed; prepare a new comparison.');
|
|
188
|
+
const built = [new Map(), new Map()], snapshots = [new Map(), new Map()];
|
|
189
|
+
const build = async (side, index, source) => {
|
|
190
|
+
if (built[index].has(source) || !side.sources.has(source)) return;
|
|
191
|
+
try {
|
|
192
|
+
const work = () => buildSource(side.config, side.sources.get(source), { write: false, allowLegacy: false, snapshot: snapshots[index], browser });
|
|
193
|
+
built[index].set(source, await (side === before ? withHumanOutputMapping(work, translate) : work()));
|
|
194
|
+
} catch (error) {
|
|
195
|
+
const failure = side === before ? revisionError(historicalFailure(error), tree.directory, base) : error;
|
|
196
|
+
if (failure instanceof CliError) failure.warnings.push(...warnings);
|
|
197
|
+
throw failure;
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
for (const source of sources) {
|
|
201
|
+
await build(before, 0, source);
|
|
202
|
+
await build(after, 1, source);
|
|
203
|
+
}
|
|
204
|
+
const frames = matchDiffFrames(sources, built[0], built[1], renames, options.frame);
|
|
205
|
+
const support = [], parents = new Map();
|
|
206
|
+
const selected = new Map(frames.map(row => [frameKey(row), row]));
|
|
207
|
+
for (const row of frames.filter(row => row.status === 'added' && row.after.parent)) {
|
|
208
|
+
const ref = row.after.parent, key = frameKey({ source: ref.source, frame: ref.frame });
|
|
209
|
+
if (!parents.has(key)) {
|
|
210
|
+
await build(before, 0, ref.source);
|
|
211
|
+
await build(after, 1, ref.source);
|
|
212
|
+
const old = built[0].get(ref.source)?.frames.find(frame => frame.name === ref.frame);
|
|
213
|
+
const current = built[1].get(ref.source)?.frames.find(frame => frame.name === ref.frame);
|
|
214
|
+
if (!old || !current) throw new CliError('DIFF_REFERENCE_INVALID', `${row.source}: ${row.frame}: parent ${ref.source}: ${ref.frame} must exist at both revisions.`);
|
|
215
|
+
const parent = selected.get(key) ?? { source: ref.source, frame: ref.frame, before: old, after: current, status: 'matched', matchKind: 'exact', matchCandidates: [] };
|
|
216
|
+
parents.set(key, parent);
|
|
217
|
+
if (!selected.has(key)) support.push(parent);
|
|
218
|
+
}
|
|
219
|
+
row.parentRow = parents.get(key);
|
|
220
|
+
}
|
|
221
|
+
const candidates = frames.filter(row => row.matchKind === 'renamed_or_unknown');
|
|
222
|
+
if (candidates.length) warnings.push({
|
|
223
|
+
code: 'DIFF_RENAMED_OR_UNKNOWN',
|
|
224
|
+
message: `Unmatched frames have rename candidates: ${candidates.map(row => frameKey(row)).join(', ')}.`, next: [],
|
|
225
|
+
});
|
|
226
|
+
return { frames, before: built[0], after: built[1], support };
|
|
227
|
+
},
|
|
228
|
+
async close() { closed = true; await tree.close(); },
|
|
229
|
+
};
|
|
230
|
+
} catch (error) {
|
|
231
|
+
const failure = error instanceof CliError ? error : revisionError(error, tree.directory, base);
|
|
232
|
+
failure.message = revisionValue(failure.message, tree.directory, base.root);
|
|
233
|
+
failure.context = revisionValue(failure.context, tree.directory, base.root);
|
|
234
|
+
failure.warnings.push(...warnings);
|
|
235
|
+
await cleanup(tree.close, failure);
|
|
236
|
+
failure.warnings = revisionValue(failure.warnings, tree.directory, base.root);
|
|
237
|
+
throw failure;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { CliError } from '../cli-output.mjs';
|
|
2
|
+
|
|
3
|
+
const defaults = {
|
|
4
|
+
imperceptible: { maxChannelDelta: 2 },
|
|
5
|
+
antialiasing: { maxChannelDelta: 48, maxRatioExclusive: 0.005 },
|
|
6
|
+
boundaryBleed: { edgeDevicePixels: 2 },
|
|
7
|
+
bitmapResampling: { maxRatioExclusive: 0.001 },
|
|
8
|
+
};
|
|
9
|
+
const object = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
10
|
+
|
|
11
|
+
export function resolveDiffPolicy(value = {}) {
|
|
12
|
+
const invalid = () => { throw new CliError('CONFIG_INVALID', 'Set diff.thresholds to class-specific channel, ratio and edge limits in adg.config.mjs.'); };
|
|
13
|
+
if (!object(value) || Object.keys(value).some(key => key !== 'thresholds')) invalid();
|
|
14
|
+
const supplied = value.thresholds === undefined ? {} : value.thresholds;
|
|
15
|
+
if (!object(supplied) || Object.keys(supplied).some(key => !Object.hasOwn(defaults, key))) invalid();
|
|
16
|
+
const thresholds = {};
|
|
17
|
+
for (const [name, fields] of Object.entries(defaults)) {
|
|
18
|
+
const overrides = supplied[name] === undefined ? {} : supplied[name];
|
|
19
|
+
if (!object(overrides) || Object.keys(overrides).some(key => !Object.hasOwn(fields, key))) invalid();
|
|
20
|
+
thresholds[name] = { ...fields, ...overrides };
|
|
21
|
+
for (const [key, limit] of Object.entries(thresholds[name])) {
|
|
22
|
+
if (!Number.isFinite(limit) || limit < 0) invalid();
|
|
23
|
+
if (key === 'maxRatioExclusive' ? limit > 1 : !Number.isInteger(limit)) invalid();
|
|
24
|
+
if (key === 'maxChannelDelta' && limit > 255) invalid();
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return { thresholds };
|
|
28
|
+
}
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { availableParallelism } from 'node:os';
|
|
5
|
+
import { launch, loadFrame, browserTask, readyResources } from './browser.mjs';
|
|
6
|
+
import { prepareDiffInputs } from './diff-inputs.mjs';
|
|
7
|
+
import { currentHead } from './arch-git.mjs';
|
|
8
|
+
import { pixelComparator, imageDifference } from './pixel-diff.mjs';
|
|
9
|
+
import { partContext, captureEvidence, capturePart, isolateParent, frameIdentity, comparisonIdentity } from './part-diff.mjs';
|
|
10
|
+
import { commandFailure, cleanup, emptySelection } from './results.mjs';
|
|
11
|
+
import { CliError, classifyError, asCliError, nextActions } from '../cli-output.mjs';
|
|
12
|
+
import { resolveDiffPolicy } from './diff-policy.mjs';
|
|
13
|
+
|
|
14
|
+
const metadata = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
|
|
15
|
+
const safeName = name => encodeURIComponent(name).replace(/\./g, '%2E');
|
|
16
|
+
const classNames = ['imperceptible', 'antialiasing', 'boundary_bleed', 'bitmap_resampling', 'other'];
|
|
17
|
+
|
|
18
|
+
function frameFailure(error, row, theme) {
|
|
19
|
+
const failure = asCliError(error, 'RENDER_FAILED');
|
|
20
|
+
failure.message = `${row.source}: ${row.frame}: ${theme}: ${failure.message}`;
|
|
21
|
+
return failure;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async function capturePair(browser, row, theme, scale, context) {
|
|
25
|
+
const captures = { before: null, after: null };
|
|
26
|
+
let page;
|
|
27
|
+
try {
|
|
28
|
+
for (const side of ['before', 'after']) {
|
|
29
|
+
if (!row[side]) continue;
|
|
30
|
+
page ??= await browserTask(browser, () => browser.newPage({ deviceScaleFactor: scale, locale: 'en-US', timezoneId: 'UTC' }));
|
|
31
|
+
await loadFrame(page, row[side], theme);
|
|
32
|
+
captures[side] = await browserTask(browser, async () => {
|
|
33
|
+
await page.evaluate(readyResources);
|
|
34
|
+
const element = page.locator('[data-adg-frame]');
|
|
35
|
+
const box = await element.boundingBox();
|
|
36
|
+
if (!box || box.width <= 0 || box.height <= 0) throw new Error('Frame has no visible bounds.');
|
|
37
|
+
const capture = () => element.screenshot({ animations: 'disabled', caret: 'hide' });
|
|
38
|
+
const targets = context?.targets.get(frameIdentity(row));
|
|
39
|
+
const evidence = targets ? await captureEvidence(page, targets, row, side, theme, context, capture) : { png: await capture() };
|
|
40
|
+
const png = evidence.png;
|
|
41
|
+
return { ...evidence, size: { width: box.width, height: box.height, pixelWidth: png.readUInt32BE(16), pixelHeight: png.readUInt32BE(20) } };
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
if (context?.targets.has(frameIdentity(row))) context.parents.set(comparisonIdentity(row, theme), captures);
|
|
45
|
+
return { row, theme, page, ...captures };
|
|
46
|
+
} catch (error) {
|
|
47
|
+
const failure = frameFailure(error, row, theme);
|
|
48
|
+
await cleanup(() => page?.close(), failure);
|
|
49
|
+
throw failure;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function comparePair(browser, pair, thresholds, context) {
|
|
54
|
+
try {
|
|
55
|
+
return await browserTask(browser, async () => {
|
|
56
|
+
const compare = await pair.page.evaluateHandle(pixelComparator);
|
|
57
|
+
try {
|
|
58
|
+
const encoded = side => pair[side] ? `data:image/png;base64,${pair[side].png.toString('base64')}` : null;
|
|
59
|
+
const args = { before: encoded('before'), after: encoded('after'), compare, crop: pair.crop ?? null,
|
|
60
|
+
evidence: pair.evidence ? { ...pair.evidence, thresholds } : null };
|
|
61
|
+
let result = await pair.page.evaluate(imageDifference, args);
|
|
62
|
+
if (result.needsIsolation) {
|
|
63
|
+
await compare.dispose();
|
|
64
|
+
const isolated = await isolateParent(pair, context);
|
|
65
|
+
// Reloading the parent replaces the document and its function handle.
|
|
66
|
+
const isolatedCompare = await pair.page.evaluateHandle(pixelComparator);
|
|
67
|
+
try { result = await pair.page.evaluate(imageDifference, { ...args, compare: isolatedCompare, isolated: `data:image/png;base64,${isolated.toString('base64')}` }); }
|
|
68
|
+
finally { await isolatedCompare.dispose(); }
|
|
69
|
+
}
|
|
70
|
+
return { ...pair, ...result,
|
|
71
|
+
before: result.beforePng ? { ...pair.before, png: Buffer.from(result.beforePng, 'base64') } : pair.before,
|
|
72
|
+
isolated: result.isolatedPng ? Buffer.from(result.isolatedPng, 'base64') : null,
|
|
73
|
+
bleedMask: result.bleedPng ? Buffer.from(result.bleedPng, 'base64') : null,
|
|
74
|
+
difference: Buffer.from(result.png, 'base64') };
|
|
75
|
+
} finally { await compare.dispose(); }
|
|
76
|
+
});
|
|
77
|
+
} catch (error) { throw frameFailure(error, pair.row, pair.theme); }
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function writePair(output, pair, thresholds) {
|
|
81
|
+
const { row, theme } = pair;
|
|
82
|
+
const directory = path.join(output, row.support ? 'support' : 'frames', ...row.source.split('/').map(safeName), safeName(row.frame), theme);
|
|
83
|
+
await mkdir(directory, { recursive: true });
|
|
84
|
+
const paths = {
|
|
85
|
+
before: pair.before ? path.join(directory, 'before.png') : null,
|
|
86
|
+
after: pair.after ? path.join(directory, 'after.png') : null,
|
|
87
|
+
difference: path.join(directory, 'difference.png'),
|
|
88
|
+
beforeSnapshot: pair.snapshots ? path.join(directory, 'before.snapshot.json') : null,
|
|
89
|
+
afterSnapshot: pair.snapshots ? path.join(directory, 'after.snapshot.json') : null,
|
|
90
|
+
parentCurrentSnapshot: pair.snapshots ? path.join(directory, 'parent-current.snapshot.json') : null,
|
|
91
|
+
report: path.join(directory, 'comparison.json'), parentIsolated: pair.isolated ? path.join(directory, 'parent-isolated.png') : null,
|
|
92
|
+
bleedMask: pair.bleedMask ? path.join(directory, 'bleed-mask.png') : null,
|
|
93
|
+
};
|
|
94
|
+
const beforeSize = pair.before?.size ?? null, afterSize = pair.after?.size ?? null;
|
|
95
|
+
const reasons = [];
|
|
96
|
+
if (!pair.parent && row.status !== 'matched') reasons.push(row.status);
|
|
97
|
+
if (row.matchKind === 'renamed_or_unknown') reasons.push('renamed_or_unknown');
|
|
98
|
+
if (beforeSize && afterSize && Object.keys(beforeSize).some(key => beforeSize[key] !== afterSize[key])) reasons.push('size_changed');
|
|
99
|
+
if (pair.parent) {
|
|
100
|
+
if (pair.snapshots.findings.length) reasons.push('snapshot_mismatch');
|
|
101
|
+
if (pair.parentChanged) reasons.push('parent_changed');
|
|
102
|
+
if (pair.singleTheme) reasons.push('theme_coverage_incomplete');
|
|
103
|
+
if (pair.pixels.classes.other.pixels) reasons.push('other_pixels');
|
|
104
|
+
if (!pair.pixels.classes.antialiasing.withinThreshold || !pair.pixels.classes.bitmap_resampling.withinThreshold) reasons.push('threshold_exceeded');
|
|
105
|
+
} else if (pair.pixels.differentPixels) reasons.push('pixels_changed');
|
|
106
|
+
const ref = { source: row.source, frame: row.frame };
|
|
107
|
+
const comparison = {
|
|
108
|
+
id: JSON.stringify([row.source, row.frame, theme, ...(row.support ? ['support'] : [])]), ...ref, theme,
|
|
109
|
+
status: row.status, matchKind: row.matchKind, matchCandidates: row.matchCandidates,
|
|
110
|
+
relation: pair.parent ? 'parent_crop' : 'revision', before: pair.parent?.ref ?? (pair.before ? ref : null), after: pair.after ? ref : null,
|
|
111
|
+
beforeSize, afterSize, parent: pair.parent ?? null, snapshots: pair.snapshots ?? null, pixels: pair.pixels,
|
|
112
|
+
verdict: reasons.length ? 'changed' : pair.parent ? 'structural' : 'identical', reasons,
|
|
113
|
+
note: { before: row.before?.note ?? null, after: row.after?.note ?? null }, paths,
|
|
114
|
+
};
|
|
115
|
+
await Promise.all([
|
|
116
|
+
pair.before && writeFile(paths.before, pair.before.png),
|
|
117
|
+
pair.after && writeFile(paths.after, pair.after.png),
|
|
118
|
+
writeFile(paths.difference, pair.difference),
|
|
119
|
+
]);
|
|
120
|
+
if (pair.snapshotFiles) await Promise.all(Object.entries(pair.snapshotFiles).map(([name, value]) => writeFile(paths[name], JSON.stringify(value, null, 2) + '\n')));
|
|
121
|
+
if (pair.isolated) await writeFile(paths.parentIsolated, pair.isolated);
|
|
122
|
+
if (pair.bleedMask) await writeFile(paths.bleedMask, pair.bleedMask);
|
|
123
|
+
await writeFile(paths.report, JSON.stringify({ classifierVersion: 1, thresholds, comparison }, null, 2) + '\n');
|
|
124
|
+
return comparison;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Exact ordinary frames and evidence-backed structural part comparisons. */
|
|
128
|
+
export async function diff(config, args = [], options = {}, { launchBrowser = launch, prepareInputs = prepareDiffInputs, log = console.log, clock } = {}) {
|
|
129
|
+
const started = performance.now(), scale = Number(options.scale ?? 2), themeOption = options.theme ?? 'both';
|
|
130
|
+
if (!Number.isFinite(scale) || scale <= 0) throw new CliError('USAGE_INVALID', 'Invalid --scale; use a positive number.');
|
|
131
|
+
if (!['both', 'light', 'dark'].includes(themeOption)) throw new CliError('USAGE_INVALID', 'Choose --theme=both, light, or dark.');
|
|
132
|
+
if (options['out-dir'] === '') throw new CliError('USAGE_INVALID', 'Set --out-dir to a directory.');
|
|
133
|
+
const themes = themeOption === 'both' ? ['light', 'dark'] : [themeOption];
|
|
134
|
+
const output = options['out-dir'] === undefined ? path.join(config.output, 'diff') : path.resolve(config.root, options['out-dir']);
|
|
135
|
+
const timings = { prepareMs: 0, buildMs: 0, captureMs: 0, compareMs: 0, writeMs: 0, totalMs: 0 };
|
|
136
|
+
const warnings = [], completed = [];
|
|
137
|
+
const thresholds = config.diff?.thresholds ?? resolveDiffPolicy().thresholds;
|
|
138
|
+
let inputs, browser, data, primary, context;
|
|
139
|
+
const timed = async (name, work) => {
|
|
140
|
+
const start = performance.now();
|
|
141
|
+
try { return await work(); }
|
|
142
|
+
finally { timings[name] += performance.now() - start; }
|
|
143
|
+
};
|
|
144
|
+
try {
|
|
145
|
+
const head = await timed('prepareMs', async () => {
|
|
146
|
+
inputs = await prepareInputs(config, args, options);
|
|
147
|
+
return currentHead(inputs.base);
|
|
148
|
+
});
|
|
149
|
+
warnings.push(...inputs.warnings);
|
|
150
|
+
data = {
|
|
151
|
+
project: config.root, outputDirectory: output, complete: false,
|
|
152
|
+
base: { rev: inputs.base.rev, sha: inputs.base.sha }, current: { kind: 'working_tree', head },
|
|
153
|
+
selection: { sources: inputs.sources, frame: options.frame ?? null, themes, scale,
|
|
154
|
+
existingCoverage: !inputs.sources.length ? 'empty' : args.length || options.frame !== undefined || themes.length !== 2 ? 'partial' : 'full' },
|
|
155
|
+
environment: { adg: metadata.version, node: process.version, platform: process.platform, arch: process.arch, chromium: null,
|
|
156
|
+
...metadata.dependencies, locale: 'en-US', timezone: 'UTC', ...inputs.environment, baseThresholds: inputs.before.config.diff.thresholds },
|
|
157
|
+
classifierVersion: 1, thresholds, comparisons: [], support: [], verdict: null, reasons: [],
|
|
158
|
+
summary: { sources: inputs.sources.length, frames: 0, comparisons: 0, supportComparisons: 0, isolationCaptures: 0,
|
|
159
|
+
added: 0, removed: 0, matched: 0, identical: 0, structural: 0, changed: 0,
|
|
160
|
+
classPixels: Object.fromEntries(classNames.map(name => [name, 0])) },
|
|
161
|
+
differencePalette: { equal: '#00000000', imperceptible: '#64748b', antialiasing: '#f59e0b', boundary_bleed: '#0ea5e9', bitmap_resampling: '#a855f7', other: '#ff00ff' }, reportPath: null, timings,
|
|
162
|
+
};
|
|
163
|
+
if (inputs.sources.length) browser = await launchBrowser();
|
|
164
|
+
const built = await timed('buildMs', () => inputs.buildFrames({ browser }));
|
|
165
|
+
context = partContext(built, inputs, scale, themes, clock);
|
|
166
|
+
for (const warning of inputs.warnings) if (!warnings.includes(warning)) warnings.push(warning);
|
|
167
|
+
data.summary.frames = built.frames.length;
|
|
168
|
+
for (const row of built.frames) data.summary[row.status]++;
|
|
169
|
+
if (!built.frames.length) emptySelection(warnings);
|
|
170
|
+
else browser ??= await launchBrowser();
|
|
171
|
+
if (browser) data.environment.chromium = browser.version();
|
|
172
|
+
const selectedOrder = new Map(built.frames.flatMap(row => themes.map(theme => comparisonIdentity(row, theme))).map((key, index) => [key, index]));
|
|
173
|
+
const supportKeys = new Set(built.support.map(frameIdentity));
|
|
174
|
+
const ordinary = [...built.frames.filter(row => !row.parentRow), ...built.support.map(row => ({ ...row, support: true }))];
|
|
175
|
+
const ordinaryJobs = ordinary.flatMap(row => themes.map(theme => ({ row, theme })));
|
|
176
|
+
const partJobs = built.frames.filter(row => row.parentRow).flatMap(row => themes.map(theme => ({ row, theme })));
|
|
177
|
+
const concurrency = Math.min(4, availableParallelism());
|
|
178
|
+
for (const jobs of [ordinaryJobs, partJobs]) for (let start = 0; start < jobs.length; start += concurrency) {
|
|
179
|
+
const failures = [], openPairs = [];
|
|
180
|
+
const phase = async (name, items, work) => {
|
|
181
|
+
const settled = await timed(name, () => Promise.allSettled(items.map(work)));
|
|
182
|
+
return settled.flatMap((result, index) => {
|
|
183
|
+
if (result.status === 'fulfilled') return [result.value];
|
|
184
|
+
failures.push({ index, error: result.reason });
|
|
185
|
+
return [];
|
|
186
|
+
});
|
|
187
|
+
};
|
|
188
|
+
try {
|
|
189
|
+
const batch = jobs.slice(start, start + concurrency);
|
|
190
|
+
openPairs.push(...await phase('captureMs', batch, job => job.row.parentRow
|
|
191
|
+
? browserTask(browser, () => capturePart(browser, job.row, job.theme, context)).catch(error => { throw frameFailure(error, job.row, job.theme); })
|
|
192
|
+
: capturePair(browser, job.row, job.theme, scale, context)));
|
|
193
|
+
const compared = await phase('compareMs', openPairs, pair => comparePair(browser, pair, thresholds, context));
|
|
194
|
+
const rows = await phase('writeMs', compared, pair => writePair(output, pair, thresholds));
|
|
195
|
+
for (const row of rows) {
|
|
196
|
+
context?.comparisons.set(comparisonIdentity(row, row.theme), row);
|
|
197
|
+
if (supportKeys.has(frameIdentity(row))) { data.support.push(row); data.summary.supportComparisons++; }
|
|
198
|
+
else {
|
|
199
|
+
completed.push(row); data.summary.comparisons++; data.summary[row.verdict]++;
|
|
200
|
+
for (const name of classNames) data.summary.classPixels[name] += row.pixels.classes[name].pixels;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
} finally {
|
|
204
|
+
for (const pair of openPairs) {
|
|
205
|
+
try { await cleanup(() => pair.page.close()); }
|
|
206
|
+
catch (error) { failures.push({ index: jobs.length, error }); }
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
data.comparisons = completed;
|
|
210
|
+
completed.sort((a, b) => selectedOrder.get(comparisonIdentity(a, a.theme)) - selectedOrder.get(comparisonIdentity(b, b.theme)));
|
|
211
|
+
data.summary.isolationCaptures = context?.isolation.size ?? 0;
|
|
212
|
+
if (failures.length) {
|
|
213
|
+
failures.sort((a, b) => a.index - b.index);
|
|
214
|
+
for (const item of failures.slice(1)) warnings.push(classifyError(item.error).error);
|
|
215
|
+
throw failures[0].error;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
} catch (error) {
|
|
219
|
+
if (inputs) {
|
|
220
|
+
if (error.message) error.message = inputs.translateDiagnostic(error.message);
|
|
221
|
+
if (error.context) error.context = inputs.translateDiagnostic(error.context);
|
|
222
|
+
if (error.warnings) error.warnings = inputs.translateDiagnostic(error.warnings);
|
|
223
|
+
}
|
|
224
|
+
primary = data ? commandFailure(error, data, warnings) : error;
|
|
225
|
+
} finally {
|
|
226
|
+
for (const close of [() => browser?.close(), () => inputs?.close()]) {
|
|
227
|
+
try { await cleanup(close, primary); }
|
|
228
|
+
catch (error) { primary = data ? commandFailure(error, data, warnings) : error; }
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
if (!data) throw primary;
|
|
232
|
+
data.complete = !primary;
|
|
233
|
+
if (!primary) {
|
|
234
|
+
data.verdict = data.summary.changed || data.support.some(row => row.verdict === 'changed') ? 'changed' : data.summary.structural ? 'structural' : 'identical';
|
|
235
|
+
data.reasons = [...new Set([...completed, ...data.support].flatMap(row => row.reasons))];
|
|
236
|
+
if (data.summary.structural && data.selection.existingCoverage !== 'full') {
|
|
237
|
+
data.verdict = 'changed'; data.reasons.push('existing_coverage_incomplete');
|
|
238
|
+
}
|
|
239
|
+
if (data.reasons.includes('existing_coverage_incomplete') || data.reasons.includes('theme_coverage_incomplete')) {
|
|
240
|
+
const next = nextActions('DIFF_FAILED', { command: 'diff', values: { ...options, frame: undefined, theme: 'both' }, positionals: [] }).map(action => ({ ...action, reason: 'Compare all existing frames in both themes before a structural batch verdict.' }));
|
|
241
|
+
warnings.push({ code: 'DIFF_COVERAGE_INCOMPLETE', message: 'A structural batch requires every existing frame in both themes.', next });
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
timings.totalMs = performance.now() - started;
|
|
245
|
+
data.reportPath = path.join(output, 'report.json');
|
|
246
|
+
try {
|
|
247
|
+
await mkdir(output, { recursive: true });
|
|
248
|
+
await writeFile(data.reportPath, JSON.stringify(data, null, 2) + '\n');
|
|
249
|
+
} catch (error) {
|
|
250
|
+
data.reportPath = null; data.complete = false; data.verdict = null;
|
|
251
|
+
if (primary) primary.warnings.push(classifyError(error).error);
|
|
252
|
+
else primary = commandFailure(error, data, warnings);
|
|
253
|
+
}
|
|
254
|
+
if (primary) throw primary;
|
|
255
|
+
if (!options.json) log(`${data.verdict}: ${data.summary.frames} frames. ${data.reportPath}`);
|
|
256
|
+
if (data.verdict === 'changed') throw new CliError('DIFF_FAILED', 'Design differences require review.', { data, warnings });
|
|
257
|
+
return { data, warnings };
|
|
258
|
+
}
|