@whzxc/agent-design-gallery 0.7.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 CHANGED
@@ -25,7 +25,7 @@ adg service migrate
25
25
  updates design editor paths and `.sdg/` entries in the project's `.gitignore` files, deletes the old generated
26
26
  `design/.sdg/` directory and regenerates `design/.adg/` (using the configured design directory). It prints each
27
27
  change and is safe to repeat. When both config names exist, it refuses before changing files. Normal commands
28
- finding only an old config stop with guidance to run `adg migrate`.
28
+ finding only an old current-project config stop with guidance to run `adg migrate`. `diff` migrates a legacy base inside its disposable historical tree and reports the change.
29
29
 
30
30
  On macOS, `adg service migrate` stops `org.svg-design-gallery.hub`, moves its entire state directory from
31
31
  `svg-design-gallery` to `agent-design-gallery`, and replaces the LaunchAgent with `org.agent-design-gallery.hub`
@@ -103,12 +103,21 @@ adg init
103
103
  adg check
104
104
  adg render surfaces/example --frame=default --scale=2
105
105
  adg check --read-only
106
+ adg diff --base=HEAD --json
106
107
  ```
107
108
 
108
109
  `init` creates tokens, components/modules/surfaces, fixtures/art, editor configuration and ignore entries. A fresh library gets one `example.tsx` per production layer, composed downward with shared fixture data; existing libraries receive no demo sources. Existing authored files are preserved, declarations are refreshed, and missing ignore entries are appended. Starter configuration requires ADG 0.5.0 or newer. `check --read-only` skips declarations and build files for an audit. Projects do not install ADG as a dependency.
109
110
 
110
111
  Builds produce standalone HTML and renders produce `<frame>-light.png` and `<frame>-dark.png` under `output/design/<source>/`. After configuring an implementation adapter and frame fixture/capture, use `adg compare <source> --frame=<name>` or `adg compare --all`. Flags override Frame capture props; `--all` writes a linked HTML index and `summary.json` under `output/design/compare/`. `sync` and `measure` have been removed.
111
112
 
113
+ `adg diff --base=<rev>` writes per-frame/theme before, after and difference PNGs plus
114
+ `report.json` for Git and working-tree sources, including added/removed frames. Existing
115
+ frames require exact pixels and size. New part Frames can declare `parent` and use
116
+ consumer `diff.thresholds`; a `structural` batch requires full existing-frame coverage
117
+ in both themes. Exit 0 is `identical`/`structural`, 1 is completed `changed`, and 2 is
118
+ incomplete execution. See [parts and classifier limits](docs/design-toolkit.md#git-frame-diff)
119
+ and the [JSON contract](docs/agent-interface.md#diff).
120
+
112
121
  See the [toolkit contract](docs/design-toolkit.md) for source format and compare adapters, and the [changelog](CHANGELOG.md) for version changes. Node.js executes design modules at build time; open sources you trust.
113
122
 
114
123
  ## Architecture sources
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whzxc/agent-design-gallery",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Local TSX design toolkit and SVG viewer",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -27,6 +27,11 @@ export const errorCatalog = {
27
27
  SOURCE_BUILD_FAILED: [2, 'check', 'Read source diagnostics after repairing the source.'],
28
28
  GIT_UNAVAILABLE: [2, 'git-version', 'Verify Git after installing it.'],
29
29
  GIT_BASE_INVALID: [2, 'git', 'Inspect the project repository and base revision.'],
30
+ DIFF_BASE_DEPENDENCIES_UNAVAILABLE: [2, 'diff', 'Restore the reported historical import or its installed dependency before retrying.'],
31
+ DIFF_FAILED: [1, 'diff', 'Review the reported artifacts, then repeat the comparison after resolving the differences.'],
32
+ DIFF_REFERENCE_INVALID: [2, 'diff', 'Repair the Frame parent reference or selector, then repeat the comparison.'],
33
+ DIFF_UNSETTLED: [2, 'diff', 'Stabilize the reported part or parent target, then repeat the comparison.'],
34
+ DIFF_SNAPSHOT_UNSUPPORTED: [2, 'diff', 'Supply a static presentation with attributable paint, then repeat the comparison.'],
30
35
  CHECK_FAILED: [1, 'check', 'Recheck after fixing findings.'],
31
36
  COMPARE_FAILED: [1, 'compare', 'Compare again after reviewing the reports.'],
32
37
  PLAYWRIGHT_UNAVAILABLE: [2, 'install', 'Restore the packaged browser dependency.'],
@@ -64,7 +69,7 @@ export class CliError extends Error {
64
69
  }
65
70
 
66
71
  const canonicalCommands = new Set([
67
- 'open', 'link', 'serve', 'root', 'service', 'migrate', 'init', 'check', 'render', 'compare',
72
+ 'open', 'link', 'serve', 'root', 'service', 'migrate', 'init', 'check', 'render', 'compare', 'diff',
68
73
  'root add', 'root remove', 'root list', 'root scan',
69
74
  'service install', 'service uninstall', 'service status', 'service logs', 'service migrate',
70
75
  'help', 'version', 'adg',
@@ -112,6 +117,17 @@ export function nextActions(code, context = {}) {
112
117
  break;
113
118
  }
114
119
  case 'chromium': argv = ['npx', `playwright@${playwrightVersion}`, 'install', 'chromium']; break;
120
+ case 'diff': {
121
+ const values = context.values ?? {};
122
+ if (context.command !== 'diff' || typeof values.base !== 'string' || !values.base.trim()) { argv = helpArgv('diff'); break; }
123
+ argv = ['adg', 'diff'];
124
+ for (const key of ['base', 'frame', 'theme', 'scale', 'out-dir']) {
125
+ if (typeof values[key] === 'string') argv.push(`--${key}=${values[key]}`);
126
+ }
127
+ argv.push('--json');
128
+ if (context.positionals?.length) argv.push('--', ...context.positionals);
129
+ break;
130
+ }
115
131
  case 'compare': {
116
132
  const values = context.values ?? {}, sources = context.positionals ?? [];
117
133
  if (context.command !== 'compare' || (!values.all && (sources.length !== 1 || typeof values.frame !== 'string' || !values.frame))) {
@@ -205,6 +221,12 @@ export async function withHumanOutput(work, stderr) {
205
221
  finally { [process.stdout.write, process.stderr.write] = originals; }
206
222
  }
207
223
 
224
+ /** Preserve the active output sink while translating revision-local diagnostics. */
225
+ export async function withHumanOutputMapping(work, transform) {
226
+ const sink = humanOutput.getStore() ?? process.stderr.write.bind(process.stderr);
227
+ return withHumanOutput(work, text => sink(transform(text)));
228
+ }
229
+
208
230
  /** @param {OutputOptions} options */
209
231
  export function createOutput({ json, command, revealKey = false, stdout = text => { process.stdout.write(text); }, stderr = text => { process.stderr.write(text); } }) {
210
232
  /** @param {Envelope} envelope */
package/src/cli.mjs CHANGED
@@ -6,7 +6,7 @@ import { realpathSync } from 'node:fs';
6
6
  import { VERSION, loadConfig } from './toolkit/config.mjs';
7
7
  import { CliError, createOutput, withHumanOutput } from './cli-output.mjs';
8
8
 
9
- export const commands = ['open', 'link', 'serve', 'root', 'service', 'migrate', 'init', 'check', 'render', 'compare'];
9
+ export const commands = ['open', 'link', 'serve', 'root', 'service', 'migrate', 'init', 'check', 'render', 'compare', 'diff'];
10
10
  const targetOptions = '[--asset=<path> [--frame=<name>] | --group=<name> | --layer=<name> | --tokens] [--mode=query|path] [--base=<rev>]';
11
11
  const usage = {
12
12
  open: `[directory] [--port=<n>] [--no-open] [--state-dir=<path>] ${targetOptions}`,
@@ -16,6 +16,7 @@ const usage = {
16
16
  root: 'add <dir> [--depth=2] | remove <dir> | list | scan [dir] [--state-dir=<path>]',
17
17
  migrate: '[project]', init: '', check: '[source...] [--read-only]', render: '[source...] [--frame=<name>] [--theme=both|light|dark] [--scale=2] [--out-dir=<path>] [--json] [--base=<rev>]',
18
18
  compare: '<source> --frame=<name> [--fixture=<name>] [--region=<name> | --selector=<css> | --page] [--origin="<x> <y>"] [--click=<name>...] [--viewport=<w>x<h>] | --all',
19
+ diff: '[source...] --base=<rev> [--frame=<name>] [--theme=both|light|dark] [--scale=2] [--out-dir=<path>] [--json]',
19
20
  };
20
21
  const details = {
21
22
  migrate: 'Rename a project configuration and runtime imports, update editor paths and ignore entries, remove old generated files and regenerate declarations. Refuses mixed config names; safe to run again.',
@@ -26,9 +27,10 @@ const details = {
26
27
  link: 'Print a clean ADG preview URL. Query mode isolates a target. Path mode locates it in the design hierarchy.',
27
28
  check: 'Check import direction and every selected frame in both themes. --read-only skips generated types and build files.', render: 'Render selected frames as PNG. Defaults to both themes at 2×. --json prints a versioned result with capture geometry and absolute paths.',
28
29
  compare: 'Compare fixture text positions. Flags override Frame fixture and capture. --all writes a summary for every fixture frame.',
30
+ diff: 'Compare the Git base and working-tree source/frame union. Existing frames require exact pixels and CSS/device size; added Frame parent declarations enable structural part evidence under diff.thresholds. Defaults to both themes at 2× and <configured output>/diff. Writes before, after and difference PNGs plus report.json. A structural batch requires all existing frames in both themes; source/frame/theme restrictions report partial coverage. Exit 0 identical/structural, 1 changed, 2 incomplete.',
29
31
  };
30
32
  export function help(command) {
31
- if (command) return `Usage: adg ${command} ${usage[command]}\n\n${details[command]}\n\n-h, --help Show help\nExit codes: 0 success, 1 check/compare problems, 2 usage/configuration/environment error.`;
33
+ if (command) return `Usage: adg ${command} ${usage[command]}\n\n${details[command]}\n\n-h, --help Show help\nExit codes: 0 success, 1 check/compare/diff problems, 2 usage/configuration/environment error.`;
32
34
  return `Usage: adg [open] [directory] [options]\n\n${commands.map(name => ` adg ${name} ${usage[name]}`).join('\n')}\n\nAny first argument that is not a command opens a directory. Use adg open check for a directory named check.\nRun adg <command> --help for details. -v, --version prints the installed version.`;
33
35
  }
34
36
  export function parseCli(args) {
@@ -37,7 +39,7 @@ export function parseCli(args) {
37
39
  const explicit = commands.includes(args[0]), command = explicit ? args[0] : 'open';
38
40
  const options = { help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' }, json: { type: 'boolean' } };
39
41
  const locators = ['asset', 'frame', 'group', 'layer', 'mode', 'base'];
40
- const strings = { open: ['port', 'state-dir', ...locators], link: locators, serve: ['port', 'state-dir'], root: ['depth', 'state-dir'], service: ['port', 'state-dir'], render: ['scale', 'frame', 'theme', 'out-dir', 'base'], compare: ['frame', 'fixture', 'region', 'selector', 'viewport', 'origin'] };
42
+ const strings = { open: ['port', 'state-dir', ...locators], link: locators, serve: ['port', 'state-dir'], root: ['depth', 'state-dir'], service: ['port', 'state-dir'], render: ['scale', 'frame', 'theme', 'out-dir', 'base'], diff: ['base', 'frame', 'theme', 'scale', 'out-dir'], compare: ['frame', 'fixture', 'region', 'selector', 'viewport', 'origin'] };
41
43
  for (const name of strings[command] ?? []) options[name] = { type: 'string' };
42
44
  if (command === 'serve') for (const name of ['print-key', 'rotate-key']) options[name] = { type: 'boolean' };
43
45
  if (command === 'open') options['no-open'] = { type: 'boolean' };
@@ -51,6 +53,7 @@ export function parseCli(args) {
51
53
  const { values, positionals } = parsed;
52
54
  if (globalJson) values.json = true;
53
55
  if (!values.help && !values.version) {
56
+ if (command === 'diff' && (typeof values.base !== 'string' || !values.base.trim())) throw new CliError('USAGE_INVALID', 'Set --base to a Git revision; run adg diff --help.');
54
57
  if ((command === 'init' && positionals.length) || (['open', 'migrate'].includes(command) && positionals.length > 1) || (command === 'compare' && (values.all ? positionals.length || values.frame : positionals.length !== 1 || !values.frame))) throw new CliError('USAGE_INVALID', `Invalid arguments; run adg ${command} --help`);
55
58
  if (command === 'link' && positionals.length !== 1) throw new CliError('USAGE_INVALID', 'Expected one viewer URL. Run adg link --help.');
56
59
  if (command === 'service' && (positionals.length !== 1 || !serviceActions.includes(positionals[0]) || (values.port !== undefined && positionals[0] !== 'install'))) throw new CliError('USAGE_INVALID', 'Invalid arguments; run adg service --help');
@@ -119,6 +122,7 @@ async function dispatch({ command, values, positionals }, cwd, output, serviceOp
119
122
  const config = await loadConfig(cwd);
120
123
  if (command === 'init') return { data: (await import('./toolkit/project.mjs')).init(config, output.log) };
121
124
  if (command === 'compare') return (await import('./toolkit/compare.mjs')).compare(config, positionals, values, {log:output.log});
125
+ if (command === 'diff') return (await import('./toolkit/diff.mjs')).diff(config, positionals, values, { log: output.log });
122
126
  const toolkit = await import('./toolkit/commands.mjs');
123
127
  return command === 'check' ? toolkit.check(config, positionals, values, output.log, output.progress) : toolkit.render(config, positionals, values, output.log);
124
128
  }
@@ -1,9 +1,28 @@
1
- import { execFile } from 'node:child_process';
1
+ import { execFile, spawn } from 'node:child_process';
2
2
  import { promisify } from 'node:util';
3
3
  import path from 'node:path';
4
- import { realpath } from 'node:fs/promises';
5
- import { CliError } from '../cli-output.mjs';
4
+ import { realpath, mkdtemp, mkdir, open, symlink, rm } from 'node:fs/promises';
5
+ import { tmpdir } from 'node:os';
6
+ import { pathToFileURL } from 'node:url';
7
+ import { CliError, asCliError } from '../cli-output.mjs';
8
+ import { cleanup } from './results.mjs';
6
9
  const exec = promisify(execFile);
10
+
11
+ export function revisionValue(value, directory, root) {
12
+ if (typeof value === 'string') return value.replaceAll(pathToFileURL(directory).href, pathToFileURL(root).href).replaceAll(directory, root);
13
+ if (Array.isArray(value)) return value.map(item => revisionValue(item, directory, root));
14
+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, revisionValue(item, directory, root)]));
15
+ return value;
16
+ }
17
+
18
+ export function revisionError(error, directory, base) {
19
+ const failure = asCliError(error);
20
+ failure.message = `Base ${base.sha.slice(0, 7)}: ${revisionValue(failure.message, directory, base.root)}`;
21
+ failure.context = revisionValue(failure.context, directory, base.root);
22
+ failure.warnings = revisionValue(failure.warnings, directory, base.root);
23
+ failure.data = null;
24
+ return failure;
25
+ }
7
26
  async function physicalPath(file) {
8
27
  try { return await realpath(file); }
9
28
  catch(error) {
@@ -13,12 +32,124 @@ async function physicalPath(file) {
13
32
  }
14
33
  }
15
34
  async function git(root, args) {
16
- try { return (await exec('git',['-C',root,...args],{maxBuffer:16*1024*1024})).stdout; }
35
+ try {
36
+ const task = exec('git', ['-C', root, ...args], { maxBuffer: 16 * 1024 * 1024 });
37
+ task.child.stdin.end();
38
+ return (await task).stdout;
39
+ }
17
40
  catch(error) {
18
41
  if(error.code==='ENOENT')throw new CliError('GIT_UNAVAILABLE', 'Git is unavailable; install Git and retry --base.', { cause: error });
19
42
  throw new CliError('GIT_BASE_INVALID', error.message, { cause: error, context: { project: root, gitCause: 'read' } });
20
43
  }
21
44
  }
45
+
46
+ async function writeBaseBlobs(base, directory, entries) {
47
+ const child = spawn('git', ['-C', base.root, 'cat-file', '--batch']);
48
+ let stderr = '', spawnError;
49
+ child.stderr.setEncoding('utf8');
50
+ child.stderr.on('data', text => { stderr = (stderr + text).slice(-16384); });
51
+ child.stdin.on('error', () => {});
52
+ const done = new Promise((resolve, reject) => {
53
+ child.once('error', error => { spawnError = error; reject(error); });
54
+ child.once('close', code => code === 0 ? resolve() : reject(new Error(stderr || `Git cat-file exited ${code}.`)));
55
+ });
56
+ done.catch(() => {});
57
+ const chunks = child.stdout[Symbol.asyncIterator]();
58
+ let pending = Buffer.alloc(0);
59
+ const refill = async () => {
60
+ const next = await chunks.next();
61
+ if (next.done) throw new Error(stderr || 'Git blob stream ended early.');
62
+ pending = next.value;
63
+ };
64
+ try {
65
+ for (const entry of entries) {
66
+ if (entry.type !== 'blob') continue;
67
+ const target = path.join(directory, entry.name);
68
+ await mkdir(path.dirname(target), { recursive: true });
69
+ child.stdin.write(`${entry.blob}\n`);
70
+ let header = '';
71
+ for (;;) {
72
+ if (!pending.length) await refill();
73
+ const end = pending.indexOf(10);
74
+ if (end >= 0) {
75
+ header += pending.subarray(0, end).toString('ascii');
76
+ pending = pending.subarray(end + 1);
77
+ break;
78
+ }
79
+ header += pending.toString('ascii'); pending = Buffer.alloc(0);
80
+ }
81
+ const [id, type, length] = header.split(' ');
82
+ if (id !== entry.blob || type !== 'blob' || !/^\d+$/.test(length)) throw new Error(`Cannot read Git blob ${entry.blob}.`);
83
+ const linkChunks = [];
84
+ const file = entry.mode === '120000' ? null : await open(target, 'w', entry.mode === '100755' ? 0o755 : 0o644);
85
+ try {
86
+ let remaining = Number(length);
87
+ while (remaining > 0) {
88
+ if (!pending.length) await refill();
89
+ const count = Math.min(remaining, pending.length), bytes = pending.subarray(0, count);
90
+ if (file) await file.writeFile(bytes);
91
+ else linkChunks.push(bytes);
92
+ pending = pending.subarray(count); remaining -= count;
93
+ }
94
+ } finally { await file?.close(); }
95
+ if (!pending.length) await refill();
96
+ if (pending[0] !== 10) throw new Error('Invalid Git blob separator.');
97
+ pending = pending.subarray(1);
98
+ if (!file) {
99
+ const link = Buffer.concat(linkChunks).toString('utf8');
100
+ const relative = path.relative(directory, path.resolve(path.dirname(target), link));
101
+ if (!path.isAbsolute(link) && relative !== '..' && !relative.startsWith(`..${path.sep}`)) await symlink(link, target);
102
+ }
103
+ }
104
+ child.stdin.end();
105
+ await done;
106
+ } catch (error) {
107
+ if (spawnError?.code === 'ENOENT') throw new CliError('GIT_UNAVAILABLE', 'Git is unavailable; install Git and retry --base.', { cause: spawnError });
108
+ if (error.code) throw error;
109
+ throw new CliError('GIT_BASE_INVALID', error.message, { cause: error, context: { project: base.root, gitCause: 'read' } });
110
+ } finally {
111
+ if (child.exitCode === null) child.kill();
112
+ await done.catch(() => {});
113
+ }
114
+ }
115
+
116
+ /** Materialize tracked bytes without export attributes or a Git worktree. */
117
+ export async function materializeBase(base) {
118
+ const directory = await realpath(await mkdtemp(path.join(tmpdir(), 'adg-diff-')));
119
+ const close = async () => {
120
+ try { await cleanup(() => rm(directory, { recursive: true, force: true })); }
121
+ catch (error) { throw revisionError(error, directory, base); }
122
+ };
123
+ try {
124
+ const tree = await git(base.root, ['ls-tree', '-r', '-z', base.sha]);
125
+ const entries = tree.split('\0').filter(Boolean).map(entry => {
126
+ const [, mode, type, blob, name] = /^(\d{6}) (blob|commit) ([a-f0-9]+)\t([\s\S]+)$/.exec(entry);
127
+ return { mode, type, blob, name };
128
+ });
129
+ await writeBaseBlobs(base, directory, entries);
130
+ return { directory, close };
131
+ } catch (error) {
132
+ const failure = revisionError(error, directory, base);
133
+ await cleanup(() => rm(directory, { recursive: true, force: true }), failure);
134
+ failure.warnings = revisionValue(failure.warnings, directory, base.root);
135
+ throw failure;
136
+ }
137
+ }
138
+
139
+ export async function currentHead(base) {
140
+ try { return (await git(base.root, ['rev-parse', '--verify', 'HEAD'])).trim(); }
141
+ catch (error) { if (error.code === 'GIT_UNAVAILABLE') throw error; return null; }
142
+ }
143
+
144
+ /** Rename hints include staged and unstaged tracked changes against the base. */
145
+ export async function sourceRenames(base) {
146
+ const fields = (await git(base.root, ['diff', '--name-status', '-z', '--find-renames', '--diff-filter=R', base.sha, '--'])).split('\0');
147
+ const renames = [];
148
+ for (let index = 0; index < fields.length - 1; index += 3) {
149
+ renames.push({ before: fields[index + 1], after: fields[index + 2] });
150
+ }
151
+ return renames;
152
+ }
22
153
  export async function resolveBase(config, rev) {
23
154
  if(typeof rev!=='string'||!rev.trim())throw new CliError('USAGE_INVALID', 'Set --base to a Git revision, for example HEAD.');
24
155
  let root;
@@ -23,6 +23,20 @@ export async function loadFrame(page, frame, theme = 'light') {
23
23
  });
24
24
  }
25
25
 
26
+ export async function readyResources() {
27
+ await document.fonts.ready;
28
+ await Promise.all([...document.images].map(image => image.decode()));
29
+ const urls = new Set();
30
+ for (const element of document.querySelectorAll('*')) {
31
+ for (const match of getComputedStyle(element).backgroundImage.matchAll(/url\(["']?(.+?)["']?\)/g)) urls.add(match[1]);
32
+ }
33
+ for (const element of document.querySelectorAll('svg image')) {
34
+ const href = element.getAttribute('href') ?? element.getAttribute('xlink:href');
35
+ if (href) urls.add(href);
36
+ }
37
+ await Promise.all([...urls].map(async url => { const image = new Image(); image.src = url; await image.decode(); }));
38
+ }
39
+
26
40
  /** Classify Playwright execution failures where the browser's connection is observable. */
27
41
  export async function browserTask(browser, work) {
28
42
  try { return await work(); }
@@ -61,6 +61,16 @@ function trimTransforms() {
61
61
  export function validateFrame(frame) {
62
62
  if (!frame?.frame || typeof frame.name !== 'string' || !frame.name.trim()) throw Error('Default export must return named Frames');
63
63
  for (const key of ['width', 'height']) if (frame[key] !== undefined && !(Number.isFinite(frame[key]) && frame[key] > 0)) throw Error(`Invalid Frame ${key}; use positive CSS pixels`);
64
+ const parent = frame.parent;
65
+ if (parent !== undefined) {
66
+ if (!parent || typeof parent !== 'object' || Array.isArray(parent) ||
67
+ Object.keys(parent).some(key => !['source', 'frame', 'selector'].includes(key)) ||
68
+ ['source', 'frame', 'selector'].some(key => typeof parent[key] !== 'string' || !parent[key].trim()) ||
69
+ !/\.(tsx|mmd)$/.test(parent.source) || /[\\:]|^\//.test(parent.source) ||
70
+ parent.source.split('/').some(part => ['', '.', '..'].includes(part))) {
71
+ throw Error('Invalid Frame parent; use project-relative source, frame and selector strings');
72
+ }
73
+ }
64
74
  const c = frame.capture;
65
75
  if (c !== undefined) {
66
76
  if (!c || typeof c !== 'object' || ['region','selector','page'].filter(k => c[k] !== undefined).length !== 1 || (c.page !== undefined && c.page !== true) || ['region','selector'].some(k => c[k] !== undefined && (typeof c[k] !== 'string' || !c[k].trim())) || (c.viewport !== undefined && !/^[1-9]\d*x[1-9]\d*$/.test(c.viewport)) || (c.origin !== undefined && (!c.page || !/^\d+(?:\.\d+)? \d+(?:\.\d+)?$/.test(c.origin))) || (c.clicks !== undefined && (!Array.isArray(c.clicks) || c.clicks.some(v => typeof v !== 'string' || !v)))) throw Error('Invalid capture; use region, selector or page with viewport, origin and clicks');
@@ -5,6 +5,7 @@ import { pathToFileURL } from 'node:url';
5
5
  import { createRequire } from 'node:module';
6
6
  import { build } from 'esbuild';
7
7
  import { sourceDirectories, archFiles } from './project.mjs';
8
+ import { resolveDiffPolicy } from './diff-policy.mjs';
8
9
 
9
10
  export const VERSION = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url))).version;
10
11
  export const UPDATE = 'npm install -g @whzxc/agent-design-gallery';
@@ -109,8 +110,9 @@ async function importConfig(file) {
109
110
  }}] });
110
111
  return (await import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}`)).default;
111
112
  }
112
- export async function loadConfig(cwd = process.cwd(), { checkVersion = true } = {}) {
113
- 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);
114
116
  let config = {};
115
117
  if (file) {
116
118
  try { config = await importConfig(file); }
@@ -132,5 +134,5 @@ export async function loadConfig(cwd = process.cwd(), { checkVersion = true } =
132
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');
133
135
  const arch = config.arch === false ? false : path.resolve(root,config.arch ?? 'arch');
134
136
  const design=path.resolve(root,config.design??'design');
135
- 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) };
136
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
+ }