@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.
Files changed (41) hide show
  1. package/README.md +12 -1
  2. package/package.json +1 -1
  3. package/public/app.js +38 -10
  4. package/public/arrangement-worker.js +11 -0
  5. package/public/arrangement.js +49 -0
  6. package/public/assets.js +16 -4
  7. package/public/layout.js +29 -13
  8. package/src/cli-output.mjs +258 -0
  9. package/src/cli.mjs +120 -45
  10. package/src/http.mjs +1 -0
  11. package/src/hub/auth.mjs +2 -1
  12. package/src/hub/proxy.mjs +5 -3
  13. package/src/hub/registry.mjs +57 -23
  14. package/src/hub.mjs +36 -21
  15. package/src/lifecycle.mjs +109 -0
  16. package/src/link.mjs +10 -9
  17. package/src/open.mjs +58 -54
  18. package/src/perf.mjs +12 -0
  19. package/src/server.mjs +78 -41
  20. package/src/service.mjs +115 -94
  21. package/src/toolkit/arch-git.mjs +142 -10
  22. package/src/toolkit/arch-overlay.mjs +1 -1
  23. package/src/toolkit/arch.mjs +62 -58
  24. package/src/toolkit/browser.mjs +38 -12
  25. package/src/toolkit/build-store.mjs +11 -3
  26. package/src/toolkit/build-worker.mjs +4 -1
  27. package/src/toolkit/build.mjs +26 -2
  28. package/src/toolkit/commands.mjs +158 -86
  29. package/src/toolkit/compare.mjs +93 -46
  30. package/src/toolkit/config.mjs +23 -20
  31. package/src/toolkit/diff-inputs.mjs +239 -0
  32. package/src/toolkit/diff-policy.mjs +28 -0
  33. package/src/toolkit/diff.mjs +258 -0
  34. package/src/toolkit/migrate.mjs +42 -30
  35. package/src/toolkit/part-diff.mjs +118 -0
  36. package/src/toolkit/part-snapshot.mjs +264 -0
  37. package/src/toolkit/pixel-diff.mjs +103 -0
  38. package/src/toolkit/project.mjs +45 -33
  39. package/src/toolkit/results.mjs +44 -0
  40. package/src/toolkit/runtime.d.ts +2 -1
  41. package/src/toolkit/tokens.mjs +5 -4
@@ -2,6 +2,7 @@ import { existsSync, readFileSync, writeFileSync, readdirSync, renameSync, rmSyn
2
2
  import path from 'node:path';
3
3
  import { CONFIG_NAMES, LEGACY_CONFIG_NAMES, loadConfig } from './config.mjs';
4
4
  import { refreshTypes, relative } from './project.mjs';
5
+ import { CliError, classifyError } from '../cli-output.mjs';
5
6
 
6
7
  function files(directory) {
7
8
  if (!existsSync(directory)) return [];
@@ -38,36 +39,47 @@ export async function migrate(project = process.cwd(), log = console.log) {
38
39
  const root = path.resolve(project);
39
40
  const oldConfigs = LEGACY_CONFIG_NAMES.filter(name => existsSync(path.join(root, name)));
40
41
  const newConfigs = CONFIG_NAMES.filter(name => existsSync(path.join(root, name)));
41
- if (oldConfigs.length && newConfigs.length) throw Error(`Both old and new config names exist in ${root}; keep one configuration before running adg migrate.`);
42
- for (const name of oldConfigs) {
43
- const next = name.replace('sdg.', 'adg.');
44
- renameSync(path.join(root, name), path.join(root, next));
45
- log(`Renamed ${name} -> ${next}`);
46
- }
47
- const config = await loadConfig(root, { checkVersion: false });
48
- if (config.root !== root) throw Error(`No project configuration in ${root}; run adg migrate from the project root.`);
49
- const update = (file, next) => {
50
- const original = readFileSync(file, 'utf8');
51
- if (next === original) return;
52
- writeFileSync(file, next);
53
- log(`Updated ${relative(config, file)}`);
54
- };
55
- for (const file of files(config.design)) {
56
- if (/\.[cm]?[jt]sx?$/.test(file)) update(file, rewriteImports(readFileSync(file, 'utf8')));
57
- if (/^tsconfig(?:\.[^.]+)*\.json$/.test(path.basename(file))) {
58
- update(file, readFileSync(file, 'utf8')
59
- .replace(/(["'])sdg(?=["'/:])/g, '$1adg').replace(/\.sdg(?=[/\\])/g, '.adg'));
42
+ if (oldConfigs.length && newConfigs.length) throw new CliError('MIGRATION_CONFLICT', `Both old and new config names exist in ${root}; keep one configuration before running adg migrate.`, { context: { project: root } });
43
+ const data = { project: root, complete: false, changes: [] };
44
+ try {
45
+ for (const name of oldConfigs) {
46
+ const next = name.replace('sdg.', 'adg.');
47
+ renameSync(path.join(root, name), path.join(root, next));
48
+ data.changes.push({ action: 'renamed', path: path.join(root, next), from: path.join(root, name) });
49
+ log(`Renamed ${name} -> ${next}`);
60
50
  }
51
+ const config = await loadConfig(root, { checkVersion: false });
52
+ if (config.root !== root) throw new CliError('PROJECT_NOT_FOUND', `No project configuration in ${root}; run adg migrate from the project root.`);
53
+ const update = (file, next) => {
54
+ const original = readFileSync(file, 'utf8');
55
+ if (next === original) return;
56
+ writeFileSync(file, next);
57
+ data.changes.push({ action: 'updated', path: file, from: null });
58
+ log(`Updated ${relative(config, file)}`);
59
+ };
60
+ for (const file of files(config.design)) {
61
+ if (/\.[cm]?[jt]sx?$/.test(file)) update(file, rewriteImports(readFileSync(file, 'utf8')));
62
+ if (/^tsconfig(?:\.[^.]+)*\.json$/.test(path.basename(file))) {
63
+ update(file, readFileSync(file, 'utf8')
64
+ .replace(/(["'])sdg(?=["'/:])/g, '$1adg').replace(/\.sdg(?=[/\\])/g, '.adg'));
65
+ }
66
+ }
67
+ for (const file of files(root).filter(file => path.basename(file) === '.gitignore')) {
68
+ update(file, readFileSync(file, 'utf8').replace(/^(?!\s*#)(.*)$/gm, line => line.replace(/(^|\/)\.sdg(?=\/|\r?$)/g, '$1.adg')));
69
+ }
70
+ const oldGenerated = path.join(config.design, '.sdg');
71
+ if (existsSync(oldGenerated)) {
72
+ rmSync(oldGenerated, { recursive: true });
73
+ data.changes.push({ action: 'deleted', path: oldGenerated, from: null });
74
+ log(`Deleted ${relative(config, oldGenerated)}/`);
75
+ }
76
+ refreshTypes(config, data.changes);
77
+ log(`Regenerated ${relative(config, path.join(config.design, '.adg'))}/`);
78
+ data.complete = true;
79
+ return data;
80
+ } catch (error) {
81
+ if (!data.changes.length) throw error;
82
+ if (error instanceof CliError) { error.data = data; throw error; }
83
+ throw new CliError(classifyError(error).error.code, error.message, { cause: error, data });
61
84
  }
62
- for (const file of files(root).filter(file => path.basename(file) === '.gitignore')) {
63
- update(file, readFileSync(file, 'utf8').replace(/^(?!\s*#)(.*)$/gm, line => line.replace(/(^|\/)\.sdg(?=\/|\r?$)/g, '$1.adg')));
64
- }
65
- const oldGenerated = path.join(config.design, '.sdg');
66
- if (existsSync(oldGenerated)) {
67
- rmSync(oldGenerated, { recursive: true });
68
- log(`Deleted ${relative(config, oldGenerated)}/`);
69
- }
70
- refreshTypes(config);
71
- log(`Regenerated ${relative(config, path.join(config.design, '.adg'))}/`);
72
- return 0;
73
85
  }
@@ -0,0 +1,118 @@
1
+ import { loadTokens } from './project.mjs';
2
+ import { loadFrame, readyResources } from './browser.mjs';
3
+ import { collectPartSnapshot, normalizeSnapshot, snapshotFindings, settlePart } from './part-snapshot.mjs';
4
+ import { CliError } from '../cli-output.mjs';
5
+ import { cleanup } from './results.mjs';
6
+
7
+ export const frameIdentity = row => JSON.stringify([row.source, row.frame]);
8
+ export const comparisonIdentity = (row, theme) => JSON.stringify([row.source, row.frame, theme]);
9
+
10
+ export function partContext(built, inputs, scale, themes, clock) {
11
+ const parts = built.frames.filter(row => row.parentRow);
12
+ if (!parts.length) return null;
13
+ const targets = new Map();
14
+ for (const row of parts) {
15
+ const key = frameIdentity(row.parentRow), values = targets.get(key) ?? [];
16
+ if (!values.includes(row.after.parent.selector)) values.push(row.after.parent.selector);
17
+ targets.set(key, values);
18
+ }
19
+ const tokens = {};
20
+ for (const [side, config] of [['before', inputs.before.config], ['after', inputs.after.config]]) {
21
+ const parsed = loadTokens(config);
22
+ tokens[side] = Object.fromEntries(themes.map(theme => [theme, [...new Map([...parsed.light, ...(theme === 'dark' ? parsed.dark : [])])].sort(([a], [b]) => a.localeCompare(b))]));
23
+ }
24
+ return { targets, tokens, scale, themes, clock, parents: new Map(), comparisons: new Map(), isolation: new Map() };
25
+ }
26
+
27
+ async function readSnapshot(page, args) {
28
+ const snapshot = await page.evaluate(collectPartSnapshot, args);
29
+ if (snapshot.referenceError) throw new CliError('DIFF_REFERENCE_INVALID', snapshot.referenceError);
30
+ if (snapshot.unsupported.length) {
31
+ const first = snapshot.unsupported[0];
32
+ throw new CliError('DIFF_SNAPSHOT_UNSUPPORTED', `${first.path}: ${first.property}: ${first.value}`);
33
+ }
34
+ return normalizeSnapshot(snapshot);
35
+ }
36
+
37
+ export async function captureEvidence(page, selectors, row, side, theme, context, capture) {
38
+ const read = () => Promise.all(selectors.map(selector => readSnapshot(page, { selector, tokens: context.tokens[side][theme], scale: context.scale, ref: { source: row.source, frame: row.frame }, theme })));
39
+ const { snapshot, png } = await settlePart(read, capture, {
40
+ now: context.clock?.now,
41
+ wait: context.clock?.wait ?? (() => page.evaluate(() => new Promise(requestAnimationFrame))),
42
+ });
43
+ return { png, targets: new Map(selectors.map((selector, index) => [selector, snapshot[index]])) };
44
+ }
45
+
46
+ export async function capturePart(browser, row, theme, context) {
47
+ const parent = context.parents.get(comparisonIdentity(row.parentRow, theme));
48
+ const selector = row.after.parent.selector;
49
+ const beforeSnapshot = parent.before.targets.get(selector), parentCurrentSnapshot = parent.after.targets.get(selector);
50
+ const page = await browser.newPage({ deviceScaleFactor: context.scale, locale: 'en-US', timezoneId: 'UTC' });
51
+ try {
52
+ await loadFrame(page, row.after, theme);
53
+ await page.evaluate(readyResources);
54
+ const after = await captureEvidence(page, [null], row, 'after', theme, context, () => page.locator('[data-adg-frame]').screenshot({ animations: 'disabled', caret: 'hide' }));
55
+ const afterSnapshot = after.targets.get(null), findings = [
56
+ ...snapshotFindings(beforeSnapshot, afterSnapshot),
57
+ ...snapshotFindings(beforeSnapshot, parentCurrentSnapshot, 'parent'),
58
+ ];
59
+ if (!afterSnapshot.frameAligned) findings.push({ code: 'PART_FRAME_GEOMETRY_CHANGED', kind: 'layout', path: 'part', property: 'frameAlignment', before: true, after: false });
60
+ if (beforeSnapshot.frameClipped || parentCurrentSnapshot.frameClipped) findings.push({ code: 'CLIPPING_CHANGED', kind: 'layout', path: 'parent', property: 'frameClipped', before: beforeSnapshot.frameClipped, after: parentCurrentSnapshot.frameClipped });
61
+ const beforeSize = beforeSnapshot.size;
62
+ const afterSize = { width: afterSnapshot.size.width, height: afterSnapshot.size.height, pixelWidth: after.png.readUInt32BE(16), pixelHeight: after.png.readUInt32BE(20) };
63
+ const currentRaster = new Set(afterSnapshot.rasterMask);
64
+ const edgeBoxes = [beforeSnapshot, afterSnapshot].flatMap(snapshot => snapshot.edgeBoxes.map(box => ({
65
+ x: box.x * context.scale + snapshot.fractionalOrigin.x, y: box.y * context.scale + snapshot.fractionalOrigin.y,
66
+ width: box.width * context.scale, height: box.height * context.scale,
67
+ })));
68
+ const supportRows = context.themes.map(theme => context.comparisons.get(comparisonIdentity(row.parentRow, theme)));
69
+ return { row, theme, page,
70
+ before: { png: parent.before.png, size: beforeSize }, after: { png: after.png, size: afterSize },
71
+ crop: beforeSnapshot.deviceCrop,
72
+ parent: { ref: { source: row.after.parent.source, frame: row.after.parent.frame }, selector,
73
+ cssCrop: beforeSnapshot.cssCrop, deviceCrop: beforeSnapshot.deviceCrop, fractionalOrigin: beforeSnapshot.fractionalOrigin,
74
+ clipping: { before: beforeSnapshot.contextEffects.clipping, current: parentCurrentSnapshot.contextEffects.clipping, after: afterSnapshot.contextEffects.clipping },
75
+ supportIds: supportRows.map(row => row.id) },
76
+ snapshots: { elementEqual: !findings.some(item => item.kind === 'element' || item.kind === 'resource'), layoutEqual: !findings.some(item => item.kind === 'layout'), colorEqual: !findings.some(item => item.kind === 'color'), findings },
77
+ snapshotFiles: { beforeSnapshot, afterSnapshot, parentCurrentSnapshot },
78
+ parentChanged: supportRows.some(row => row.verdict !== 'identical'),
79
+ singleTheme: context.themes.length !== 2,
80
+ evidence: { snapshotsMatch: !findings.length, rasterMask: beforeSnapshot.rasterMask.filter(pixel => currentRaster.has(pixel)), edgeBoxes },
81
+ };
82
+ } catch (error) { await cleanup(() => page.close(), error); throw error; }
83
+ }
84
+
85
+ export async function isolateParent(pair, context) {
86
+ const key = JSON.stringify([frameIdentity(pair.row.parentRow), pair.parent.selector, pair.theme]);
87
+ if (!context.isolation.has(key)) context.isolation.set(key, (async () => {
88
+ const page = pair.page, row = pair.row.parentRow;
89
+ await loadFrame(page, row.before, pair.theme);
90
+ await page.evaluate(readyResources);
91
+ const args = { selector: pair.parent.selector, tokens: context.tokens.before[pair.theme], scale: context.scale, ref: pair.parent.ref, theme: pair.theme };
92
+ const before = await readSnapshot(page, args);
93
+ if (snapshotFindings(pair.snapshotFiles.beforeSnapshot, before).length || JSON.stringify(before.deviceCrop) !== JSON.stringify(pair.crop)) throw new CliError('DIFF_UNSETTLED', 'The parent target changed before isolation.');
94
+ await page.evaluate(selector => {
95
+ const frame = document.querySelector('[data-adg-frame]'), target = frame.querySelector(selector);
96
+ window.__adgIsolation = [...frame.querySelectorAll('*')].filter(node => !target.contains(node) && !node.contains(target)).map(node => [node, node.getAttribute('style')]);
97
+ for (const [node] of window.__adgIsolation) node.style.setProperty('visibility', 'hidden', 'important');
98
+ }, pair.parent.selector);
99
+ let primary;
100
+ try {
101
+ const after = await readSnapshot(page, args);
102
+ if (snapshotFindings(before, after).length) throw new CliError('DIFF_UNSETTLED', 'Isolation changed the target snapshots.');
103
+ const png = await page.locator('[data-adg-frame]').screenshot({ animations: 'disabled', caret: 'hide' });
104
+ const captured = await readSnapshot(page, args);
105
+ if (snapshotFindings(after, captured).length) throw new CliError('DIFF_UNSETTLED', 'The target changed during isolation capture.');
106
+ return png;
107
+ } catch (error) { primary = error; throw error; }
108
+ finally {
109
+ await cleanup(() => page.evaluate(() => {
110
+ for (const [node, style] of window.__adgIsolation) {
111
+ if (style === null) node.removeAttribute('style'); else node.setAttribute('style', style);
112
+ }
113
+ delete window.__adgIsolation;
114
+ }), primary);
115
+ }
116
+ })());
117
+ return context.isolation.get(key);
118
+ }
@@ -0,0 +1,264 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { CliError } from '../cli-output.mjs';
3
+
4
+ /** Runs only in pages contributing part evidence. */
5
+ export async function collectPartSnapshot({ selector, tokens, scale, ref, theme }) {
6
+ const frame = document.querySelector('[data-adg-frame]');
7
+ let roots;
8
+ try { roots = selector === null ? [...frame.children] : [...frame.querySelectorAll(selector)]; }
9
+ catch { return { referenceError: `Invalid parent selector ${selector}.` }; }
10
+ if (roots.length !== 1) return { referenceError: `Expected one target for ${selector ?? 'the part root'}, found ${roots.length}.` };
11
+ const root = roots[0], origin = root.getBoundingClientRect(), frameBox = frame.getBoundingClientRect();
12
+ if (!origin.width || !origin.height || getComputedStyle(root).visibility !== 'visible') return { referenceError: 'The parent/part target must be visible.' };
13
+ const clean = number => number === 0 ? 0 : number;
14
+ const box = rect => ({ x: clean(rect.x - origin.x), y: clean(rect.y - origin.y), width: rect.width, height: rect.height });
15
+ const cssCrop = { x: origin.x - frameBox.x, y: origin.y - frameBox.y, width: origin.width, height: origin.height };
16
+ const left = Math.floor(cssCrop.x * scale), top = Math.floor(cssCrop.y * scale);
17
+ const deviceCrop = { x: left, y: top, width: Math.ceil((cssCrop.x + origin.width) * scale) - left, height: Math.ceil((cssCrop.y + origin.height) * scale) - top };
18
+ const fractionalOrigin = { x: cssCrop.x * scale - left, y: cssCrop.y * scale - top };
19
+ const nodes = [root, ...root.querySelectorAll('*')], paths = new Map(nodes.map((node, index) => [node, String(index)]));
20
+ const ids = new Map(nodes.filter(node => node.id).map(node => [node.id, `node-${paths.get(node)}`]));
21
+ const unsupported = [], resources = [], resourceCache = new Map(), decoded = new Map();
22
+ const internalIds = value => value.replace(/url\(["']?#([^)'"\s]+)["']?\)/g, (_, id) => `url(#${ids.get(id) ?? id})`);
23
+ const resource = async url => {
24
+ if (resourceCache.has(url)) return resourceCache.get(url);
25
+ let content = url;
26
+ if (!url.startsWith('data:')) {
27
+ try {
28
+ const response = await fetch(url);
29
+ if (!response.ok) throw Error(`HTTP ${response.status}`);
30
+ const bytes = new Uint8Array(await response.arrayBuffer());
31
+ let binary = '';
32
+ for (let offset = 0; offset < bytes.length; offset += 8192) binary += String.fromCharCode(...bytes.subarray(offset, offset + 8192));
33
+ content = `data:${response.headers.get('content-type') ?? ''};base64,${btoa(binary)}`;
34
+ } catch { unsupported.push({ path: 'resources', property: 'bytes', value: url }); }
35
+ }
36
+ const id = `resource-${resources.length}`;
37
+ const kind = /^data:image\/svg\+xml/i.test(content) ? 'vector' : /^data:(?:image\/|application\/octet-stream)/i.test(content) ? 'raster' : 'font';
38
+ const entry = { id, source: url.startsWith('data:') ? `embedded:${kind}` : url, kind, contentIdentity: content, intrinsicWidth: null, intrinsicHeight: null };
39
+ if (kind === 'raster') {
40
+ const comma = content.indexOf(',');
41
+ const bytes = content.slice(0, comma).includes(';base64') ? atob(content.slice(comma + 1)) : decodeURIComponent(content.slice(comma + 1));
42
+ if (bytes.startsWith('GIF8') && /NETSCAPE2\.0|ANIMEXTS1\.0/.test(bytes) || bytes.startsWith('\x89PNG') && bytes.includes('acTL') || bytes.startsWith('RIFF') && bytes.includes('ANIM')) unsupported.push({ path: 'resources', property: 'paint', value: 'animated raster' });
43
+ }
44
+ resources.push(entry); resourceCache.set(url, entry);
45
+ return entry;
46
+ };
47
+ const normalizeStyle = async style => {
48
+ const values = {};
49
+ for (const property of [...style].sort()) {
50
+ let value = internalIds(style.getPropertyValue(property));
51
+ if (/url\(/.test(value)) {
52
+ for (const match of [...value.matchAll(/url\(["']?([^)'"\s]+)["']?\)/g)]) {
53
+ if (match[1].startsWith('#')) continue;
54
+ const entry = await resource(match[1]);
55
+ value = value.replace(match[0], `url(${entry.id})`);
56
+ }
57
+ }
58
+ values[property] = value;
59
+ }
60
+ return values;
61
+ };
62
+ const inspectPaint = (style, path) => {
63
+ for (const property of ['filter', 'backdrop-filter', 'clip-path', 'mask-image', 'mix-blend-mode', 'perspective']) {
64
+ const value = style.getPropertyValue(property);
65
+ if (value && !['none', 'normal'].includes(value)) unsupported.push({ path, property, value });
66
+ }
67
+ };
68
+ const paintProperty = property => /color|background|fill|stroke|shadow|opacity|filter|blend|mask|clip-path/.test(property);
69
+ const ignored = /^(?:--|animation|transition|cursor$|pointer-events$|user-select$|touch-action$|scroll-behavior$|caret-color$)/;
70
+ const tokenRules = [];
71
+ const visitRules = rules => {
72
+ for (const rule of rules) {
73
+ if (rule instanceof CSSMediaRule && !matchMedia(rule.conditionText).matches || rule instanceof CSSSupportsRule && !CSS.supports(rule.conditionText)) continue;
74
+ if (rule.selectorText && rule.style) tokenRules.push(rule);
75
+ if (rule.cssRules) visitRules(rule.cssRules);
76
+ }
77
+ };
78
+ for (const sheet of document.styleSheets) visitRules(sheet.cssRules);
79
+ const elements = [], texts = [], rasters = [], edgeBoxes = [];
80
+ for (const node of nodes) {
81
+ const path = paths.get(node), style = getComputedStyle(node), rect = node.getBoundingClientRect();
82
+ inspectPaint(style, path);
83
+ if (node.matches('canvas,video,object,embed,foreignObject')) unsupported.push({ path, property: 'paint', value: node.localName });
84
+ const computedStyle = await normalizeStyle(style), layout = {}, paint = {};
85
+ for (const [property, value] of Object.entries(computedStyle)) {
86
+ if (!ignored.test(property)) (paintProperty(property) ? paint : layout)[property] = value;
87
+ }
88
+ const attributes = {};
89
+ for (const attr of [...node.attributes].sort((a, b) => a.name.localeCompare(b.name))) {
90
+ if (['class', 'style', 'id'].includes(attr.name) || attr.name.startsWith('data-')) continue;
91
+ let value = internalIds(attr.value);
92
+ if (['src', 'href', 'xlink:href'].includes(attr.name) && !value.startsWith('#') && node.matches('img,image')) value = (await resource(value)).id;
93
+ if (value.startsWith('#') && ids.has(value.slice(1))) value = `#${ids.get(value.slice(1))}`;
94
+ attributes[attr.name] = value;
95
+ }
96
+ if (node.matches('input,textarea,select')) {
97
+ attributes.value = node.value;
98
+ if ('checked' in node) attributes.checked = String(node.checked);
99
+ }
100
+ for (const property of [...node.style].filter(name => name.startsWith('--'))) layout[property] = node.style.getPropertyValue(property);
101
+ const tokenExpressions = [];
102
+ for (const declaration of [...tokenRules.filter(rule => { try { return node.matches(rule.selectorText); } catch { return false; } }).map(rule => rule.style), node.style]) {
103
+ for (const property of declaration) {
104
+ const expression = declaration.getPropertyValue(property);
105
+ if (property.startsWith('--') || expression.includes('var(')) tokenExpressions.push({ property, expression, resolved: style.getPropertyValue(property) });
106
+ }
107
+ }
108
+ const pseudo = {};
109
+ for (const name of ['before', 'after']) {
110
+ const style = getComputedStyle(node, `::${name}`);
111
+ pseudo[name] = ['none', 'normal'].includes(style.content) ? null : { content: style.content, computedStyle: await normalizeStyle(style) };
112
+ if (pseudo[name]) inspectPaint(style, `${path}::${name}`);
113
+ if (/counter\(|attr\(/.test(style.content)) unsupported.push({ path, property: 'content', value: style.content });
114
+ }
115
+ elements.push({ path, parentPath: node === root ? null : paths.get(node.parentElement), tag: node.localName, namespace: node.namespaceURI,
116
+ attributes, childOrder: [...node.childNodes].filter(child => child.nodeType === 1 || child.nodeType === 3 && child.textContent.trim()).map((child, index) => child.nodeType === 1 ? paths.get(child) : `${path}/text-${index}`),
117
+ box: box(rect), clientRects: [...node.getClientRects()].map(box), layout, paint, computedStyle, pseudo, tokenExpressions,
118
+ owners: JSON.parse(node.getAttribute('data-adg-owners') ?? '[]') });
119
+ for (const [index, child] of [...node.childNodes].entries()) {
120
+ if (child.nodeType !== 3 || !child.textContent.trim()) continue;
121
+ const range = document.createRange(); range.selectNodeContents(child);
122
+ const lines = [...range.getClientRects()].map(rect => ({ text: child.textContent, box: box(rect) }));
123
+ texts.push({ path: `${path}/text-${index}`, parentPath: path, text: child.textContent, lines });
124
+ edgeBoxes.push(...lines.map(line => line.box));
125
+ }
126
+ if (node instanceof SVGElement && /^(path|rect|circle|ellipse|polygon|polyline|line|text)$/.test(node.localName) || parseFloat(style.borderTopWidth) || parseFloat(style.borderRadius)) edgeBoxes.push(box(rect));
127
+ if (!node.matches('img,image')) continue;
128
+ const url = node.currentSrc || node.getAttribute('href') || node.getAttribute('xlink:href') || node.getAttribute('src');
129
+ if (!url) continue;
130
+ const entry = await resource(url);
131
+ let image = decoded.get(url);
132
+ if (!image) {
133
+ image = new Image(); image.src = url;
134
+ await image.decode(); decoded.set(url, image);
135
+ }
136
+ entry.intrinsicWidth = image.naturalWidth; entry.intrinsicHeight = image.naturalHeight;
137
+ if (entry.kind === 'raster' && style.display !== 'none' && style.visibility === 'visible' && Number(style.opacity) > 0) {
138
+ const transform = node instanceof SVGElement ? node.getScreenCTM() : new DOMMatrixReadOnly(style.transform === 'none' ? undefined : style.transform);
139
+ if (transform && (transform.b || transform.c || transform.a <= 0 || transform.d <= 0)) unsupported.push({ path, property: 'raster-transform', value: style.transform });
140
+ rasters.push({ node, path, box: box(rect) });
141
+ }
142
+ }
143
+ for (const sheet of document.styleSheets) for (const rule of sheet.cssRules) {
144
+ if (rule.type !== CSSRule.FONT_FACE_RULE) continue;
145
+ for (const match of rule.style.src.matchAll(/url\(["']?([^)'"\s]+)["']?\)/g)) await resource(match[1]);
146
+ }
147
+ let visible = { left: Math.max(origin.left, frameBox.left), top: Math.max(origin.top, frameBox.top), right: Math.min(origin.right, frameBox.right), bottom: Math.min(origin.bottom, frameBox.bottom) };
148
+ const compositing = {}, backgrounds = [], clipShapes = [];
149
+ for (let parent = root.parentElement; parent; parent = parent.parentElement) {
150
+ const style = getComputedStyle(parent), rect = parent.getBoundingClientRect();
151
+ inspectPaint(style, 'ancestor');
152
+ if (style.transform !== 'none') {
153
+ const matrix = new DOMMatrixReadOnly(style.transform);
154
+ if (!matrix.is2D || matrix.a !== 1 || matrix.b || matrix.c || matrix.d !== 1) unsupported.push({ path: 'ancestor', property: 'transform', value: style.transform });
155
+ }
156
+ if (style.opacity !== '1') compositing.opacity = String(Number(compositing.opacity ?? 1) * Number(style.opacity));
157
+ if (style.backgroundColor !== 'rgba(0, 0, 0, 0)') backgrounds.push(style.backgroundColor);
158
+ if (style.backgroundImage !== 'none') {
159
+ compositing.backgroundImages ??= [];
160
+ compositing.backgroundImages.push({ box: box(rect), value: (await normalizeStyle(style))['background-image'] });
161
+ }
162
+ if (style.boxShadow !== 'none') {
163
+ compositing.shadows ??= [];
164
+ compositing.shadows.push({ box: box(rect), value: style.boxShadow });
165
+ }
166
+ if (/(hidden|clip|auto|scroll)/.test(style.overflowX + style.overflowY)) {
167
+ const radii = ['border-top-left-radius', 'border-top-right-radius', 'border-bottom-left-radius', 'border-bottom-right-radius'].map(name => style.getPropertyValue(name));
168
+ if (radii.some(radius => parseFloat(radius))) clipShapes.push({ box: box(rect), radii });
169
+ }
170
+ if (/(hidden|clip|auto|scroll)/.test(style.overflowX)) { visible.left = Math.max(visible.left, rect.left + parent.clientLeft); visible.right = Math.min(visible.right, rect.left + parent.clientLeft + parent.clientWidth); }
171
+ if (/(hidden|clip|auto|scroll)/.test(style.overflowY)) { visible.top = Math.max(visible.top, rect.top + parent.clientTop); visible.bottom = Math.min(visible.bottom, rect.top + parent.clientTop + parent.clientHeight); }
172
+ }
173
+ const clipped = visible.left > origin.left || visible.top > origin.top || visible.right < origin.right || visible.bottom < origin.bottom;
174
+ const clipping = clipped ? [{ x: visible.left - origin.left, y: visible.top - origin.top, width: Math.max(0, visible.right - visible.left), height: Math.max(0, visible.bottom - visible.top) }] : [];
175
+ const backgroundCanvas = document.createElement('canvas'); backgroundCanvas.width = backgroundCanvas.height = 1;
176
+ const backgroundContext = backgroundCanvas.getContext('2d');
177
+ for (const color of backgrounds.reverse()) { backgroundContext.fillStyle = color; backgroundContext.fillRect(0, 0, 1, 1); }
178
+ const backdrop = [...backgroundContext.getImageData(0, 0, 1, 1).data].join(',');
179
+ const rasterMask = [];
180
+ if (rasters.length) {
181
+ const restored = nodes.map(node => [node, node.getAttribute('style')]);
182
+ const inert = new Map(nodes.filter(node => node.hasAttribute('inert')).map(node => [node, node.getAttribute('inert')]));
183
+ for (let node = root; node; node = node.parentElement) if (node.hasAttribute('inert')) inert.set(node, node.getAttribute('inert'));
184
+ for (const [node] of inert) node.removeAttribute('inert');
185
+ try {
186
+ for (const node of nodes) node.style.setProperty('pointer-events', 'auto', 'important');
187
+ for (const raster of rasters) {
188
+ const r = raster.box;
189
+ const x0 = Math.max(0, Math.floor(r.x * scale + fractionalOrigin.x)), y0 = Math.max(0, Math.floor(r.y * scale + fractionalOrigin.y));
190
+ const x1 = Math.min(deviceCrop.width, Math.ceil((r.x + r.width) * scale + fractionalOrigin.x)), y1 = Math.min(deviceCrop.height, Math.ceil((r.y + r.height) * scale + fractionalOrigin.y));
191
+ for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) {
192
+ const stack = document.elementsFromPoint(frameBox.x + (left + x + 0.5) / scale, frameBox.y + (top + y + 0.5) / scale);
193
+ if (stack[0] === raster.node) rasterMask.push(y * deviceCrop.width + x);
194
+ }
195
+ }
196
+ } finally {
197
+ for (const [node, style] of restored) { node.getAttribute('style'); if (style === null) node.removeAttribute('style'); else node.setAttribute('style', style); }
198
+ for (const [node, value] of inert) node.setAttribute('inert', value);
199
+ }
200
+ }
201
+ return { snapshotVersion: 1, ref, theme, size: { width: origin.width, height: origin.height, pixelWidth: deviceCrop.width, pixelHeight: deviceCrop.height },
202
+ origin: { x: origin.x, y: origin.y }, elements, texts,
203
+ tokens: tokens.map(([name, declaration]) => ({ name, declaration, resolved: getComputedStyle(root).getPropertyValue(name).trim() })), resources,
204
+ contextEffects: { clipping, clipShapes, compositing, backdrop },
205
+ cssCrop, deviceCrop, fractionalOrigin, clipped,
206
+ frameClipped: origin.left < frameBox.left || origin.top < frameBox.top || origin.right > frameBox.right || origin.bottom > frameBox.bottom,
207
+ edgeBoxes, rasterMask, unsupported,
208
+ frameAligned: selector !== null || cssCrop.x === 0 && cssCrop.y === 0 && origin.width === frameBox.width && origin.height === frameBox.height };
209
+ }
210
+
211
+ export function normalizeSnapshot(snapshot) {
212
+ for (const resource of snapshot.resources) {
213
+ let content = resource.contentIdentity;
214
+ if (content.startsWith('data:')) {
215
+ const comma = content.indexOf(',');
216
+ content = content.slice(0, comma).includes(';base64') ? Buffer.from(content.slice(comma + 1), 'base64') : Buffer.from(decodeURIComponent(content.slice(comma + 1)));
217
+ }
218
+ resource.contentIdentity = createHash('sha256').update(content).digest('hex');
219
+ }
220
+ return snapshot;
221
+ }
222
+
223
+ export function snapshotFindings(before, after, context = 'part') {
224
+ const findings = [];
225
+ const compare = (a, b, path, kind, code) => {
226
+ if (JSON.stringify(a) === JSON.stringify(b)) return;
227
+ if (a && b && typeof a === 'object' && typeof b === 'object') {
228
+ for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) compare(a[key], b[key], `${path}.${key}`, kind, code);
229
+ } else findings.push({ code, kind, path: context, property: path, before: a ?? null, after: b ?? null });
230
+ };
231
+ compare(before.tokens, after.tokens, 'tokens', 'color', 'TOKEN_CHANGED');
232
+ compare(before.resources, after.resources, 'resources', 'resource', 'RESOURCE_CHANGED');
233
+ compare(before.contextEffects.clipping, after.contextEffects.clipping, 'clipping', 'layout', 'CLIPPING_CHANGED');
234
+ compare(before.contextEffects.clipShapes, after.contextEffects.clipShapes, 'clipShapes', 'layout', 'CLIPPING_CHANGED');
235
+ compare(before.contextEffects.compositing, after.contextEffects.compositing, 'compositing', 'color', 'COLOR_CHANGED');
236
+ compare(before.contextEffects.backdrop, after.contextEffects.backdrop, 'backdrop', 'color', 'COLOR_CHANGED');
237
+ const count = Math.max(before.elements.length, after.elements.length);
238
+ for (let index = 0; index < count; index++) {
239
+ const a = before.elements[index], b = after.elements[index];
240
+ if (!a || !b) { findings.push({ code: a ? 'ELEMENT_REMOVED' : 'ELEMENT_ADDED', kind: 'element', path: context, property: `elements.${index}`, before: a ?? null, after: b ?? null }); continue; }
241
+ for (const property of ['tag', 'namespace', 'attributes', 'childOrder']) compare(a[property], b[property], `elements.${index}.${property}`, 'element', 'ELEMENT_CHANGED');
242
+ for (const property of ['box', 'clientRects', 'layout']) compare(a[property], b[property], `elements.${index}.${property}`, 'layout', 'LAYOUT_CHANGED');
243
+ compare(a.paint, b.paint, `elements.${index}.paint`, 'color', 'COLOR_CHANGED');
244
+ compare(a.pseudo, b.pseudo, `elements.${index}.pseudo`, 'element', 'ELEMENT_CHANGED');
245
+ }
246
+ compare(before.texts, after.texts, 'texts', 'element', 'TEXT_CHANGED');
247
+ return findings;
248
+ }
249
+
250
+ /** Two equal observations and an unchanged post-capture observation share one deadline. */
251
+ export async function settlePart(read, capture, { now = () => performance.now(), wait = () => new Promise(resolve => setTimeout(resolve, 0)) } = {}) {
252
+ const start = now();
253
+ let previous;
254
+ for (;;) {
255
+ const snapshot = await read(), state = JSON.stringify(snapshot);
256
+ if (state === previous) {
257
+ const png = await capture(), after = await read();
258
+ if (JSON.stringify(after) === state && now() - start < 5000) return { snapshot: after, png };
259
+ previous = JSON.stringify(after);
260
+ } else previous = state;
261
+ if (now() - start >= 5000) throw new CliError('DIFF_UNSETTLED', 'Part snapshots did not settle within five seconds.');
262
+ await wait();
263
+ }
264
+ }
@@ -0,0 +1,103 @@
1
+ /** The same comparator runs in Node tests and as a browser function handle. */
2
+ export function pixelComparator() {
3
+ const color = (image, offset) => image.data[offset + 3] === 0 ? [0, 0, 0, 0] : [...image.data.subarray(offset, offset + 4)];
4
+ const delta = (a, b) => Math.max(...a.map((value, channel) => Math.abs(value - b[channel])));
5
+ const blend = (value, a, b) => {
6
+ let channel = 0;
7
+ for (let index = 1; index < 4; index++) if (Math.abs(b[index] - a[index]) > Math.abs(b[channel] - a[channel])) channel = index;
8
+ const t = (value[channel] - a[channel]) / (b[channel] - a[channel]);
9
+ return t >= 0 && t <= 1 && value.every((number, index) => Math.abs(number - a[index] - t * (b[index] - a[index])) <= 2)
10
+ ? delta(value, a) > 2 && delta(value, b) > 2 : null;
11
+ };
12
+ const antialias = (before, after, x, y, a, b, minimum) => {
13
+ const anchors = new Map();
14
+ for (let dy = Math.max(0, y - 1); dy <= Math.min(before.height - 1, y + 1); dy++) for (let dx = Math.max(0, x - 1); dx <= Math.min(before.width - 1, x + 1); dx++) {
15
+ const offset = (dy * before.width + dx) * 4, old = color(before, offset), current = color(after, offset);
16
+ if (delta(old, current)) continue;
17
+ const key = old.join(','), entry = anchors.get(key) ?? { color: old, count: 0 };
18
+ entry.count++; anchors.set(key, entry);
19
+ }
20
+ const colors = [...anchors.values()].filter(anchor => anchor.count >= 3).map(anchor => anchor.color);
21
+ const luminance = rgba => rgba[0] * 0.2126 + rgba[1] * 0.7152 + rgba[2] * 0.0722;
22
+ for (let i = 0; i < colors.length; i++) for (let j = i + 1; j < colors.length; j++) {
23
+ if (delta(colors[i], colors[j]) <= minimum || luminance(colors[i]) === luminance(colors[j])) continue;
24
+ const old = blend(a, colors[i], colors[j]), current = blend(b, colors[i], colors[j]);
25
+ if (old !== null && current !== null && (old || current)) return true;
26
+ }
27
+ return false;
28
+ };
29
+ return (before, after, evidence = null, isolated = null) => {
30
+ const width = Math.max(before?.width ?? 0, after?.width ?? 0);
31
+ const height = Math.max(before?.height ?? 0, after?.height ?? 0);
32
+ const difference = new Uint8ClampedArray(width * height * 4);
33
+ const bleed = isolated ? new Uint8ClampedArray(width * height * 4) : null;
34
+ const classes = Object.fromEntries(['imperceptible', 'antialiasing', 'boundary_bleed', 'bitmap_resampling', 'other'].map(name => [name, { pixels: 0, ratio: 0, maxChannelDelta: 0, withinThreshold: true }]));
35
+ const palette = { imperceptible: [100, 116, 139], antialiasing: [245, 158, 11], boundary_bleed: [14, 165, 233], bitmap_resampling: [168, 85, 247], other: [255, 0, 255] };
36
+ const raster = new Set(evidence?.rasterMask ?? []), policy = evidence?.thresholds;
37
+ const eligible = evidence?.snapshotsMatch && before?.width === after?.width && before?.height === after?.height;
38
+ let differentPixels = 0, needsIsolation = false;
39
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
40
+ const hasBefore = before && x < before.width && y < before.height;
41
+ const hasAfter = after && x < after.width && y < after.height;
42
+ let delta = 0;
43
+ if (!!hasBefore !== !!hasAfter) delta = 255;
44
+ else if (hasBefore && hasAfter) {
45
+ const a = (y * before.width + x) * 4, b = (y * after.width + x) * 4;
46
+ for (let channel = 0; channel < 4; channel++) {
47
+ const old = channel < 3 && before.data[a + 3] === 0 ? 0 : before.data[a + channel];
48
+ const current = channel < 3 && after.data[b + 3] === 0 ? 0 : after.data[b + channel];
49
+ delta = Math.max(delta, Math.abs(old - current));
50
+ }
51
+ }
52
+ if (!delta) continue;
53
+ differentPixels++;
54
+ const offset = (y * width + x) * 4;
55
+ let name = 'other';
56
+ if (policy && delta <= policy.imperceptible.maxChannelDelta) name = 'imperceptible';
57
+ else if (eligible) {
58
+ const old = color(before, offset), current = color(after, offset), alone = isolated && color(isolated, offset);
59
+ const external = alone && old.some((value, channel) => value !== alone[channel]);
60
+ if (!isolated) needsIsolation = true;
61
+ const edge = policy.boundaryBleed.edgeDevicePixels;
62
+ if (external) {
63
+ if ((x < edge || y < edge || x >= width - edge || y >= height - edge) && current.every((value, channel) => value === alone[channel])) name = 'boundary_bleed';
64
+ } else if (raster.has(y * width + x)) name = 'bitmap_resampling';
65
+ else if (delta <= policy.antialiasing.maxChannelDelta && evidence.edgeBoxes.some(box => x >= box.x && y >= box.y && x < box.x + box.width && y < box.y + box.height) && antialias(before, after, x, y, old, current, policy.imperceptible.maxChannelDelta)) name = 'antialiasing';
66
+ }
67
+ const stat = classes[name]; stat.pixels++; stat.maxChannelDelta = Math.max(stat.maxChannelDelta, delta);
68
+ difference.set(palette[name], offset); difference[offset + 3] = 255;
69
+ if (bleed && name === 'boundary_bleed') { bleed.set([255, 255, 255, 255], offset); }
70
+ }
71
+ const areaPixels = width * height;
72
+ for (const stat of Object.values(classes)) stat.ratio = areaPixels ? stat.pixels / areaPixels : 0;
73
+ classes.other.withinThreshold = classes.other.pixels === 0;
74
+ if (policy) {
75
+ classes.antialiasing.withinThreshold = !classes.antialiasing.pixels || classes.antialiasing.ratio < policy.antialiasing.maxRatioExclusive;
76
+ classes.bitmap_resampling.withinThreshold = !classes.bitmap_resampling.pixels || classes.bitmap_resampling.ratio < policy.bitmapResampling.maxRatioExclusive;
77
+ }
78
+ return { width, height, difference, bleed, needsIsolation, pixels: { areaPixels, equalPixels: areaPixels - differentPixels, differentPixels, classes } };
79
+ };
80
+ }
81
+
82
+ export async function imageDifference({ before, after, compare, crop = null, isolated = null, evidence = null }) {
83
+ const read = async (source, clip = null) => {
84
+ if (source === null) return null;
85
+ const image = new Image(); image.src = source;
86
+ await image.decode();
87
+ const canvas = document.createElement('canvas');
88
+ canvas.width = image.naturalWidth; canvas.height = image.naturalHeight;
89
+ const context = canvas.getContext('2d', { colorSpace: 'srgb', willReadFrequently: true });
90
+ context.drawImage(image, 0, 0);
91
+ return clip ? context.getImageData(clip.x, clip.y, clip.width, clip.height) : context.getImageData(0, 0, canvas.width, canvas.height);
92
+ };
93
+ const first = await read(before, crop), second = await read(after), alone = await read(isolated, crop);
94
+ const result = compare(first, second, evidence, alone);
95
+ const encode = image => {
96
+ const canvas = document.createElement('canvas'); canvas.width = image.width; canvas.height = image.height;
97
+ canvas.getContext('2d').putImageData(image, 0, 0);
98
+ return canvas.toDataURL('image/png').split(',')[1];
99
+ };
100
+ return { pixels: result.pixels, png: encode(new ImageData(result.difference, result.width, result.height)),
101
+ beforePng: crop && encode(first), isolatedPng: alone && encode(alone),
102
+ bleedPng: result.bleed && encode(new ImageData(result.bleed, result.width, result.height)), needsIsolation: result.needsIsolation };
103
+ }