@whzxc/agent-design-gallery 0.9.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +19 -3
  2. package/package.json +4 -1
  3. package/public/annotations.js +816 -0
  4. package/public/app.js +245 -12
  5. package/public/assets.js +4 -13
  6. package/public/frame-identity.js +223 -0
  7. package/public/icons.js +1 -0
  8. package/public/index.html +3 -0
  9. package/public/selection.js +1 -1
  10. package/public/style.css +72 -2
  11. package/src/annotations.mjs +238 -0
  12. package/src/cli-output.mjs +49 -2
  13. package/src/cli.mjs +83 -12
  14. package/src/http.mjs +2 -1
  15. package/src/hub/instances.mjs +1 -1
  16. package/src/hub/registry.mjs +1 -1
  17. package/src/hub.mjs +2 -2
  18. package/src/server.mjs +59 -11
  19. package/src/service.mjs +1 -1
  20. package/src/toolkit/arch-git.mjs +19 -0
  21. package/src/toolkit/arch-overlay.mjs +1 -1
  22. package/src/toolkit/asset-rules.mjs +42 -3
  23. package/src/toolkit/build-store.mjs +5 -3
  24. package/src/toolkit/build-worker.mjs +5 -2
  25. package/src/toolkit/build.mjs +36 -14
  26. package/src/toolkit/commands.mjs +85 -22
  27. package/src/toolkit/config.mjs +8 -6
  28. package/src/toolkit/diff-inputs.mjs +5 -5
  29. package/src/toolkit/diff.mjs +18 -11
  30. package/src/toolkit/document.mjs +6 -6
  31. package/src/toolkit/frame-document.mjs +6 -0
  32. package/src/toolkit/frame-facets.mjs +167 -0
  33. package/src/toolkit/frame-identity.mjs +100 -0
  34. package/src/toolkit/frame-observation.mjs +147 -0
  35. package/src/toolkit/frame-primitives.mjs +85 -0
  36. package/src/toolkit/html.mjs +1 -0
  37. package/src/toolkit/impact-eligibility.mjs +136 -0
  38. package/src/toolkit/impact-inputs.mjs +52 -0
  39. package/src/toolkit/impact-output.mjs +46 -0
  40. package/src/toolkit/impact-proof.mjs +67 -0
  41. package/src/toolkit/impact-selection.mjs +96 -0
  42. package/src/toolkit/impact.mjs +382 -0
  43. package/src/toolkit/implementation-query.mjs +53 -0
  44. package/src/toolkit/input-generation.mjs +51 -0
  45. package/src/toolkit/inspect-encoding.mjs +459 -0
  46. package/src/toolkit/inspect-observation.mjs +56 -0
  47. package/src/toolkit/inspect-output.mjs +169 -0
  48. package/src/toolkit/inspect-styles.mjs +34 -0
  49. package/src/toolkit/inspect.d.ts +118 -0
  50. package/src/toolkit/inspect.mjs +125 -0
  51. package/src/toolkit/owner-observation.mjs +23 -189
  52. package/src/toolkit/owner-search.mjs +2 -2
  53. package/src/toolkit/owner.mjs +37 -45
  54. package/src/toolkit/part-diff.mjs +2 -0
  55. package/src/toolkit/part-snapshot.mjs +15 -23
  56. package/src/toolkit/project-index.mjs +100 -22
  57. package/src/toolkit/project.mjs +52 -6
  58. package/src/toolkit/results.mjs +2 -2
  59. package/src/toolkit/runtime.d.ts +7 -5
  60. package/src/toolkit/runtime.mjs +20 -7
  61. package/src/toolkit/token-reachability.mjs +71 -0
@@ -2,13 +2,31 @@ import { mkdirSync, readFileSync, existsSync } from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { availableParallelism } from 'node:os';
4
4
  import { buildSource } from './build.mjs';
5
- import { selectSources, relative, loadTokens, sourceDirectories, archFiles } from './project.mjs';
6
- import { importDirectionViolations } from './asset-rules.mjs';
5
+ import { selectSources, relative, loadTokens, sourceDirectories, archFiles, featureFolderProblems } from './project.mjs';
6
+ import { importDirectionViolations, singleConsumerComponents } from './asset-rules.mjs';
7
7
  import { launch, loadFrame, browserTask } from './browser.mjs';
8
8
  import { CliError, classifyError } from '../cli-output.mjs';
9
9
  import { commandFailure, cleanup, emptySelection } from './results.mjs';
10
10
  import { loadImplementationMap, validateImplementationMap } from './implementation-map.mjs';
11
- import { mappingFacts } from './source-facts.mjs';
11
+ import { withImpacted } from './impact-selection.mjs';
12
+ import { mappingFacts, frameOwners } from './source-facts.mjs';
13
+
14
+ function frameStructure(frame) {
15
+ return frame.html
16
+ .replace(/>[^<]*</g, '><')
17
+ .replace(/\s(?:aria-label|aria-description|title|placeholder|value)="[^"]*"/g, '')
18
+ .replace(/\sdata-adg-keys="[^"]*"/g, '')
19
+ .replace(/\s+/g, ' ')
20
+ .trim();
21
+ }
22
+
23
+ function frameOwnsPart(frame, source, part, config) {
24
+ return (frame.owners ?? frameOwners(frame.html)).some(owner => owner.source === source && owner.export === part);
25
+ }
26
+
27
+ function proposedFrame(source, frame) {
28
+ return frame.proposed ? { source, frame: frame.name, scope: frame.proposed } : null;
29
+ }
12
30
  export function inspectFrame(tokenNames) {
13
31
  const frame = document.querySelector('[data-adg-frame]'), box = frame.getBoundingClientRect(), problems = new Map();
14
32
  const add = (code, message) => problems.set(message, {code, message, line:null, column:null});
@@ -181,10 +199,12 @@ export function inspectFrame(tokenNames) {
181
199
  }
182
200
  return [...problems.values()];
183
201
  }
184
- export async function check(config, args = [], options = {}, log = console.log, error = console.error, { launchBrowser = launch } = {}) {
202
+ export async function check(config, args = [], options = {}, log = console.log, error = console.error, { launchBrowser = launch, session } = {}) {
203
+ if (options.impacted && !session) return withImpacted(config, args, options, 'check', selected =>
204
+ check(config, args, options, log, error, { launchBrowser, session: selected }));
185
205
  const write = !options['read-only'];
186
206
  /** @type {import('./results.mjs').CheckData} */
187
- const data = { project: config.root, readOnly: !write, complete: false, sources: [], summary: { sources: 0, frames: 0, evaluations: 0, problems: 0 }, findings: [] };
207
+ const data = { project: config.root, readOnly: !write, complete: false, impact: session?.selection ?? null, sources: [], summary: { sources: 0, frames: 0, evaluations: 0, problems: 0 }, findings: [], proposed: [] };
188
208
  const warnings = [], humanProblems = new Set(), findingKeys = new Set(), graph = {};
189
209
  let browser, primary;
190
210
  const add = (problem, file, frame = null, theme = null, source = relative(config, file)) => {
@@ -201,13 +221,14 @@ export async function check(config, args = [], options = {}, log = console.log,
201
221
  };
202
222
  try {
203
223
  const mapping = await loadImplementationMap(config);
204
- const files = selectSources(config, args, { write });
224
+ const files = session ? session.sources.map(source => path.join(config.root, source)).filter(existsSync) : selectSources(config, args, { write });
205
225
  data.sources = files.map(file => relative(config, file));
206
226
  data.summary.sources = files.length;
227
+ if (config.check?.strictLayers === true) for (const problem of featureFolderProblems(config.design, sourceDirectories(config))) add({ code: problem.code, message: problem.message, line: null, column: null }, problem.file);
207
228
  const tokens = files.length ? loadTokens(config) : null;
208
229
  const arch = files.some(file => file.endsWith('.mmd')) ? await import('./arch.mjs') : null;
209
230
  let page;
210
- const builtSources = new Map(), failedSources = new Map();
231
+ const builtSources = new Map(), allBuilt = new Map(), failedSources = new Map();
211
232
  for (const file of files) {
212
233
  const architecture = file.endsWith('.mmd');
213
234
  if (architecture) {
@@ -222,8 +243,9 @@ export async function check(config, args = [], options = {}, log = console.log,
222
243
  let built;
223
244
  try {
224
245
  // Static architecture rejection is a completed rule evaluation and needs no browser.
225
- browser ??= await launchBrowser();
226
- built = await buildSource(config, file, { allowLegacy: false, write, browser });
246
+ if (session && !architecture) built = session.views[1].built.get(relative(config, file));
247
+ else if (session && !session.chosen.some(row => row.source === relative(config, file) && session.themes.some(theme => session.scheduled(row, theme)))) continue;
248
+ else { browser ??= await launchBrowser(); built = await buildSource(config, file, { allowLegacy: false, write: session ? false : write, browser }); }
227
249
  } catch (cause) {
228
250
  const legacy = cause.errors?.find(item => item.detail?.code === 'LEGACY_SOURCE');
229
251
  if (legacy) throw legacy.detail;
@@ -234,9 +256,13 @@ export async function check(config, args = [], options = {}, log = console.log,
234
256
  continue;
235
257
  }
236
258
  data.summary.frames += built.frames.length;
259
+ allBuilt.set(relative(config, file), built);
260
+ for (const frame of built.frames) if (frame.proposed) data.proposed.push(proposedFrame(relative(config, file), frame));
237
261
  if (mapping.present && !architecture) builtSources.set(relative(config, file), mappingFacts(built));
238
262
  graph[path.relative(config.design, file).split(path.sep).join('/')] = { uses: built.imports };
239
- for (const frame of built.frames) for (const theme of ['light', 'dark']) {
263
+ for (const frame of built.frames) for (const theme of session?.themes ?? ['light', 'dark']) {
264
+ if (session && !session.scheduled({ source: relative(config, file), frame: frame.name }, theme)) continue;
265
+ browser ??= await launchBrowser();
240
266
  try {
241
267
  page ??= await browserTask(browser, () => browser.newPage());
242
268
  await loadFrame(page, frame, theme);
@@ -249,14 +275,15 @@ export async function check(config, args = [], options = {}, log = console.log,
249
275
  }
250
276
  }
251
277
  }
278
+ let validatedMap = null;
252
279
  if (mapping.present) {
253
280
  const { listSources } = await import('./project.mjs');
254
- await validateImplementationMap(config, mapping, {
281
+ validatedMap = await validateImplementationMap(config, mapping, {
255
282
  sources: listSources(config.design, sourceDirectories(config)).map(file => relative(config, file)),
256
283
  selected: args.length ? data.sources : undefined,
257
284
  getBuild: source => {
258
285
  if (failedSources.has(source)) throw failedSources.get(source);
259
- if (!builtSources.has(source)) builtSources.set(source, buildSource(config, path.join(config.root, source), { write: false, allowLegacy: false }));
286
+ if (!builtSources.has(source)) builtSources.set(source, session?.views[1].built.get(source) ?? buildSource(config, path.join(config.root, source), { write: false, allowLegacy: false }));
260
287
  return builtSources.get(source);
261
288
  },
262
289
  onFinding: ({ code, message, line, column, frame }) => add({ code, message, line, column }, mapping.file, frame),
@@ -264,11 +291,42 @@ export async function check(config, args = [], options = {}, log = console.log,
264
291
  }
265
292
  await cleanup(() => browser?.close(), primary);
266
293
  browser = null;
267
- if (config.check?.importDirection !== false) for (const { source, target, from, to } of importDirectionViolations(graph, sourceDirectories(config))) {
268
- add({ code: 'IMPORT_DIRECTION', message: `import ${target} violates import direction (${from} -> ${to}); import from the same or a lower layer in sources`, line: null, column: null }, path.join(config.design, source));
294
+ if (config.check?.importDirection !== false) for (const { source, target, from, to, sameLayer, featureBoundary } of importDirectionViolations(graph, sourceDirectories(config), { strictLayers: config.check?.strictLayers === true })) {
295
+ add({ code: 'IMPORT_DIRECTION', message: `import ${target} violates import direction (${from} -> ${to}); ${featureBoundary ? (sameLayer ? 'module files may import only within their own feature folder' : 'surfaces must import a module feature through its index.tsx') : sameLayer ? 'same-layer imports are allowed only in the lowest layer' : 'import from the same or a lower layer in sources'}`, line: null, column: null }, path.join(config.design, source));
296
+ }
297
+ if (config.check?.lifecycle === true && mapping.present && validatedMap) {
298
+ const production = sourceDirectories(config).filter(name => name !== 'studies');
299
+ const top = production.at(-1);
300
+ const active = validatedMap.bindings.filter(binding => binding.active);
301
+ const hasBinding = (source, part = null) => active.some(binding => binding.design.source === source && (part === null ? binding.design.part === undefined : binding.design.part === part));
302
+ for (const [source, built] of allBuilt) {
303
+ const layer = source.split('/')[0];
304
+ if (!production.includes(layer)) continue;
305
+ for (const part of built.parts ?? []) {
306
+ const frames = built.frames.filter(frame => frameOwnsPart(frame, source.replace(/^design\//, ''), part, config));
307
+ if (layer !== top && !hasBinding(source, part) && !frames.some(frame => frame.proposed)) add({ code: 'OWNER_PART_UNBOUND', message: `Exported part ${part} has no implementation binding or proposed frame; add a binding or mark a review frame with proposed`, line: null, column: null }, path.join(config.root, source));
308
+ }
309
+ if (layer === top && !hasBinding(source)) add({ code: 'OWNER_SURFACE_UNBOUND', message: `Surface source has no whole-source implementation binding; add a binding without part`, line: null, column: null }, path.join(config.root, source));
310
+ if (layer === top) for (const frame of built.frames) if (!frame.proposed && (!frame.fixture || !frame.capture)) add({ code: 'OWNER_SURFACE_FRAME_UNCAPTURED', message: `Surface frame ${frame.name} needs fixture and capture or a proposed review scope; add both metadata fields or proposed`, line: null, column: null }, path.join(config.root, source), frame.name);
311
+ }
312
+ }
313
+ if (config.check?.singleConsumer !== false) {
314
+ for (const warning of singleConsumerComponents(graph, sourceDirectories(config), Object.fromEntries([...allBuilt].map(([source, built]) => [source.replace(/^design\//, ''), built.parts ?? []])))) {
315
+ warnings.push({ code: warning.code, message: warning.message, next: [] });
316
+ if (!options.json) log(`WARNING ${warning.message}`);
317
+ }
318
+ }
319
+ if (config.check?.redundantFrames !== false) {
320
+ for (const [source, built] of allBuilt) {
321
+ const byStructure = new Map();
322
+ for (const frame of built.frames) { const key = frameStructure(frame); const list = byStructure.get(key) ?? []; list.push(frame.name); byStructure.set(key, list); }
323
+ for (const frames of byStructure.values()) if (frames.length > 1) warnings.push({ code: 'REDUNDANT_FRAME', message: `${source}: frames ${frames.join(', ')} have identical structure apart from text, locale and geometry.`, next: [] });
324
+ }
269
325
  }
270
326
  for (const problem of humanProblems) error(problem);
271
327
  const message = `Design check ${humanProblems.size ? 'failed' : 'passed'} for ${files.length} sources${humanProblems.size ? `: ${humanProblems.size} problems` : ''}.`;
328
+ for (const item of data.proposed) log(`PROPOSED ${item.source}#${item.frame} (${item.scope})`);
329
+ for (const warning of warnings.filter(warning => warning.code === 'REDUNDANT_FRAME')) log(`WARNING ${warning.message}`);
272
330
  log(message);
273
331
  if (!files.length) emptySelection(warnings);
274
332
  if (primary) { primary.humanReported = true; throw primary; }
@@ -281,10 +339,12 @@ export async function check(config, args = [], options = {}, log = console.log,
281
339
  } finally { if (browser) await cleanup(() => browser.close(), primary); }
282
340
  }
283
341
 
284
- export async function render(config, args = [], options = {}, log = console.log, { launchBrowser = launch } = {}) {
342
+ export async function render(config, args = [], options = {}, log = console.log, { launchBrowser = launch, session } = {}) {
343
+ if (options.impacted && !session) return withImpacted(config, args, options, 'render', selected =>
344
+ render(config, args, options, log, { launchBrowser, session: selected }));
285
345
  const output = options['out-dir'] ? path.resolve(config.root, options['out-dir']) : config.output;
286
346
  /** @type {import('./results.mjs').RenderData} */
287
- const data = { project: config.root, outputDirectory: output, complete: false, base: null, captures: [], deleted: [] };
347
+ const data = { project: config.root, outputDirectory: output, complete: false, impact: session?.selection ?? null, base: null, captures: [], deleted: [] };
288
348
  const warnings = [], completed = [], failures = [];
289
349
  let browser, primary;
290
350
  try {
@@ -295,30 +355,33 @@ export async function render(config, args = [], options = {}, log = console.log,
295
355
  if (options['out-dir'] === '') throw new CliError('USAGE_INVALID', 'Set --out-dir to a directory.');
296
356
  const themes = themeOption === 'both' ? ['light', 'dark'] : [themeOption];
297
357
  let base, additional = [];
298
- if (options.base !== undefined && (!args.length || args.some(arg => arg.endsWith('.mmd')))) {
358
+ if (!session && options.base !== undefined && (!args.length || args.some(arg => arg.endsWith('.mmd')))) {
299
359
  const git = await import('./arch-git.mjs');
300
360
  base = await git.resolveBase(config, options.base);
301
361
  additional = await git.baseArchFiles(config, base);
302
362
  data.base = { rev: base.rev, sha: base.sha };
303
- } else if (options.base !== undefined) warnings.push({ code: 'USAGE_INVALID', message: '--base applies only to architecture sources.', next: [] });
304
- const selected = selectSources(config, args, { additional });
363
+ } else if (!session && options.base !== undefined) warnings.push({ code: 'USAGE_INVALID', message: '--base applies only to architecture sources.', next: [] });
364
+ if (session) data.base = { rev: session.selection.query.base.rev, sha: session.selection.query.base.sha };
365
+ if (session) data.deleted = [...new Set(session.chosen.filter(row => row.status === 'removed').map(row => row.source))];
366
+ const selected = session ? [...new Set(session.chosen.filter(row => row.after && themes.some(theme => session.scheduled(row, theme))).map(row => path.join(config.root, row.source)))] : selectSources(config, args, { additional });
305
367
  const currentArchitecture = base ? new Set(archFiles(config.arch)) : null;
306
368
  const files = selected.filter(file => {
307
369
  if (!existsSync(file) || (base && file.endsWith('.mmd') && !currentArchitecture.has(file))) { data.deleted.push(relative(config, file)); return false; }
308
370
  return true;
309
371
  });
310
- if (!selected.length) emptySelection(warnings);
372
+ if (!selected.length && (!session || !session.selection.coverage.expectedRows)) emptySelection(warnings);
311
373
  if (files.length) browser = await launchBrowser();
312
374
  const captures = [];
313
375
  for (const file of files) {
314
- const built = base && file.endsWith('.mmd') ? await (await import('./arch-overlay.mjs')).buildOverlay(config, file, { base, browser }) : await buildSource(config, file, { allowLegacy: false, browser });
376
+ const built = session?.views[1].built.get(relative(config, file)) ?? (base && file.endsWith('.mmd') ? await (await import('./arch-overlay.mjs')).buildOverlay(config, file, { base, browser }) : await buildSource(config, file, { allowLegacy: false, write: !session, browser }));
315
377
  for (const frame of built.frames.filter(frame => !options.frame || frame.name === options.frame)) for (const theme of themes) {
378
+ if (session && !session.scheduled({ source: relative(config, file), frame: frame.name }, theme)) continue;
316
379
  const outputSource = file.endsWith('.mmd') ? relative(config, file) : path.relative(config.design, file);
317
380
  const target = path.join(output, outputSource.replace(/\.(?:tsx|mmd)$/, ''), `${encodeURIComponent(frame.name)}-${theme}.png`);
318
381
  captures.push({ source: relative(config, file), frame, theme, target });
319
382
  }
320
383
  }
321
- if (options.frame && !captures.length && !data.deleted.length) throw new CliError('FRAME_NOT_FOUND', `Unknown frame ${options.frame}; choose a declared frame`);
384
+ if (!session && options.frame && !captures.length && !data.deleted.length) throw new CliError('FRAME_NOT_FOUND', `Unknown frame ${options.frame}; choose a declared frame`);
322
385
  let next = 0;
323
386
  await Promise.allSettled(Array.from({ length: Math.min(4, availableParallelism(), captures.length) }, async () => {
324
387
  while (next < captures.length) {
@@ -87,10 +87,11 @@ export function viewport(value) {
87
87
  if (!match) throw new CliError('CONFIG_INVALID', `Invalid viewport ${value}; use <width>x<height>, for example 1280x800`);
88
88
  return { width: Number(match[1]), height: Number(match[2]) };
89
89
  }
90
- async function importConfig(file) {
90
+ let configEvaluation = 0;
91
+ async function importConfig(file, fresh) {
91
92
  if (!file.endsWith('.ts')) {
92
93
  const info = statSync(file), url = pathToFileURL(file);
93
- url.searchParams.set('revision', `${info.mtimeMs}-${info.size}`);
94
+ url.searchParams.set('revision', `${info.mtimeMs}-${info.size}${fresh ? `-${++configEvaluation}` : ''}`);
94
95
  return (await import(url.href)).default;
95
96
  }
96
97
  const require = createRequire(pathToFileURL(file));
@@ -108,14 +109,14 @@ async function importConfig(file) {
108
109
  }
109
110
  });
110
111
  }}] });
111
- return (await import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}`)).default;
112
+ return (await import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}${fresh ? `#${++configEvaluation}` : ''}`)).default;
112
113
  }
113
- export async function loadConfig(cwd = process.cwd(), { checkVersion = true, discover = true } = {}) {
114
+ export async function loadConfig(cwd = process.cwd(), { checkVersion = true, discover = true, fresh = false } = {}) {
114
115
  const root = discover ? discoverRoot(cwd) : path.resolve(cwd), file = configFile(root);
115
116
  if (!discover) requireMigration(root);
116
117
  let config = {};
117
118
  if (file) {
118
- try { config = await importConfig(file); }
119
+ try { config = await importConfig(file, fresh); }
119
120
  catch (error) { throw new CliError('CONFIG_INVALID', `Cannot load ${file}: ${error.message}; fix ${path.basename(file)}`, { cause: error }); }
120
121
  }
121
122
  if (!config || typeof config !== 'object' || Array.isArray(config)) throw new CliError('CONFIG_INVALID', 'Export a default object from adg.config.mjs');
@@ -125,6 +126,7 @@ export async function loadConfig(cwd = process.cwd(), { checkVersion = true, dis
125
126
  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
127
  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
128
  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');
129
+ for (const key of ['strictLayers', 'lifecycle', 'singleConsumer']) if (config.check?.[key] !== undefined && typeof config.check[key] !== 'boolean') throw new CliError('CONFIG_INVALID', `Set check.${key} to true or false in adg.config.mjs`);
128
130
  const compare = { port: 5188, viewport: '1280x800', ...config.compare };
129
131
  viewport(compare.viewport);
130
132
  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');
@@ -134,5 +136,5 @@ export async function loadConfig(cwd = process.cwd(), { checkVersion = true, dis
134
136
  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');
135
137
  const arch = config.arch === false ? false : path.resolve(root,config.arch ?? 'arch');
136
138
  const design=path.resolve(root,config.design??'design');
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) };
139
+ 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,strictLayers:false,lifecycle:false,singleConsumer:true,...config.check}, compare, diff: resolveDiffPolicy(config.diff) };
138
140
  }
@@ -64,7 +64,7 @@ function inventory(config, repository) {
64
64
  }));
65
65
  }
66
66
 
67
- async function selectedSources(config, beforeConfig, root, union, args) {
67
+ export async function selectedSources(config, beforeConfig, root, union, args) {
68
68
  if (!args.length) return [...union].sort();
69
69
  const previousDesign = path.resolve(root, path.relative(beforeConfig.root, beforeConfig.design));
70
70
  const selected = [];
@@ -183,9 +183,9 @@ export async function prepareDiffInputs(config, args = [], options = {}) {
183
183
  let closed = false;
184
184
  return {
185
185
  base, before, after, sources, warnings, translateDiagnostic: translate, environment: { configDependencies, baseMigration },
186
- async buildFrames({ browser } = {}) {
186
+ async buildFrames({ browser, materialized, sources: requestedSources = sources, frame: requestedFrame = options.frame } = {}) {
187
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()];
188
+ const built = materialized ? materialized.map(values => new Map(values)) : [new Map(), new Map()], snapshots = [new Map(), new Map()];
189
189
  const build = async (side, index, source) => {
190
190
  if (built[index].has(source) || !side.sources.has(source)) return;
191
191
  try {
@@ -197,11 +197,11 @@ export async function prepareDiffInputs(config, args = [], options = {}) {
197
197
  throw failure;
198
198
  }
199
199
  };
200
- for (const source of sources) {
200
+ for (const source of requestedSources) {
201
201
  await build(before, 0, source);
202
202
  await build(after, 1, source);
203
203
  }
204
- const frames = matchDiffFrames(sources, built[0], built[1], renames, options.frame);
204
+ const frames = matchDiffFrames(requestedSources, built[0], built[1], renames, requestedFrame);
205
205
  const support = [], parents = new Map();
206
206
  const selected = new Map(frames.map(row => [frameKey(row), row]));
207
207
  for (const row of frames.filter(row => row.status === 'added' && row.after.parent)) {
@@ -9,6 +9,7 @@ import { pixelComparator, imageDifference } from './pixel-diff.mjs';
9
9
  import { partContext, captureEvidence, capturePart, isolateParent, frameIdentity, comparisonIdentity } from './part-diff.mjs';
10
10
  import { commandFailure, cleanup, emptySelection } from './results.mjs';
11
11
  import { CliError, classifyError, asCliError, nextActions } from '../cli-output.mjs';
12
+ import { withImpacted } from './impact-selection.mjs';
12
13
  import { resolveDiffPolicy } from './diff-policy.mjs';
13
14
 
14
15
  const metadata = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
@@ -110,7 +111,10 @@ async function writePair(output, pair, thresholds) {
110
111
  relation: pair.parent ? 'parent_crop' : 'revision', before: pair.parent?.ref ?? (pair.before ? ref : null), after: pair.after ? ref : null,
111
112
  beforeSize, afterSize, parent: pair.parent ?? null, snapshots: pair.snapshots ?? null, pixels: pair.pixels,
112
113
  verdict: reasons.length ? 'changed' : pair.parent ? 'structural' : 'identical', reasons,
113
- note: { before: row.before?.note ?? null, after: row.after?.note ?? null }, paths,
114
+ note: { before: row.before?.note ?? null, after: row.after?.note ?? null },
115
+ proposed: row.after?.proposed ?? row.before?.proposed ?? null,
116
+ metadata: { before: row.before ? { locale: row.before.locale ?? null, proposed: row.before.proposed ?? null, fixture: row.before.fixture ?? null, capture: row.before.capture ?? null } : null,
117
+ after: row.after ? { locale: row.after.locale ?? null, proposed: row.after.proposed ?? null, fixture: row.after.fixture ?? null, capture: row.after.capture ?? null } : null }, paths,
114
118
  };
115
119
  await Promise.all([
116
120
  pair.before && writeFile(paths.before, pair.before.png),
@@ -125,7 +129,9 @@ async function writePair(output, pair, thresholds) {
125
129
  }
126
130
 
127
131
  /** 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 } = {}) {
132
+ export async function diff(config, args = [], options = {}, { launchBrowser = launch, prepareInputs = prepareDiffInputs, log = console.log, clock, session } = {}) {
133
+ if (options.impacted && !session) return withImpacted(config, args, options, 'diff', selected =>
134
+ diff(config, args, options, { launchBrowser, prepareInputs, log, clock, session: selected }));
129
135
  const started = performance.now(), scale = Number(options.scale ?? 2), themeOption = options.theme ?? 'both';
130
136
  if (!Number.isFinite(scale) || scale <= 0) throw new CliError('USAGE_INVALID', 'Invalid --scale; use a positive number.');
131
137
  if (!['both', 'light', 'dark'].includes(themeOption)) throw new CliError('USAGE_INVALID', 'Choose --theme=both, light, or dark.');
@@ -143,7 +149,7 @@ export async function diff(config, args = [], options = {}, { launchBrowser = la
143
149
  };
144
150
  try {
145
151
  const head = await timed('prepareMs', async () => {
146
- inputs = await prepareInputs(config, args, options);
152
+ inputs = session ? session.diffInputs : await prepareInputs(config, args, options);
147
153
  return currentHead(inputs.base);
148
154
  });
149
155
  warnings.push(...inputs.warnings);
@@ -154,26 +160,27 @@ export async function diff(config, args = [], options = {}, { launchBrowser = la
154
160
  existingCoverage: !inputs.sources.length ? 'empty' : args.length || options.frame !== undefined || themes.length !== 2 ? 'partial' : 'full' },
155
161
  environment: { adg: metadata.version, node: process.version, platform: process.platform, arch: process.arch, chromium: null,
156
162
  ...metadata.dependencies, locale: 'en-US', timezone: 'UTC', ...inputs.environment, baseThresholds: inputs.before.config.diff.thresholds },
157
- classifierVersion: 1, thresholds, comparisons: [], support: [], verdict: null, reasons: [],
163
+ impact: session?.selection ?? null, classifierVersion: 1, thresholds, comparisons: [], support: [], verdict: null, reasons: [],
158
164
  summary: { sources: inputs.sources.length, frames: 0, comparisons: 0, supportComparisons: 0, isolationCaptures: 0,
159
165
  added: 0, removed: 0, matched: 0, identical: 0, structural: 0, changed: 0,
160
166
  classPixels: Object.fromEntries(classNames.map(name => [name, 0])) },
161
167
  differencePalette: { equal: '#00000000', imperceptible: '#64748b', antialiasing: '#f59e0b', boundary_bleed: '#0ea5e9', bitmap_resampling: '#a855f7', other: '#ff00ff' }, reportPath: null, timings,
162
168
  };
163
- if (inputs.sources.length) browser = await launchBrowser();
169
+ if (session ? session.chosen.some(row => row.source.endsWith('.mmd') && session.themes.some(theme => session.scheduled(row, theme))) : inputs.sources.length) browser = await launchBrowser();
164
170
  const built = await timed('buildMs', () => inputs.buildFrames({ browser }));
171
+ if (session) built.frames = built.frames.filter(row => themes.some(theme => session.scheduled(row, theme)));
165
172
  context = partContext(built, inputs, scale, themes, clock);
166
173
  for (const warning of inputs.warnings) if (!warnings.includes(warning)) warnings.push(warning);
167
174
  data.summary.frames = built.frames.length;
168
175
  for (const row of built.frames) data.summary[row.status]++;
169
- if (!built.frames.length) emptySelection(warnings);
170
- else browser ??= await launchBrowser();
176
+ if (!built.frames.length && (!session || !session.selection.coverage.expectedRows)) emptySelection(warnings);
177
+ else if (built.frames.length) browser ??= await launchBrowser();
171
178
  if (browser) data.environment.chromium = browser.version();
172
179
  const selectedOrder = new Map(built.frames.flatMap(row => themes.map(theme => comparisonIdentity(row, theme))).map((key, index) => [key, index]));
173
180
  const supportKeys = new Set(built.support.map(frameIdentity));
174
181
  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 })));
182
+ const ordinaryJobs = ordinary.flatMap(row => themes.filter(theme => !session || row.support || session.scheduled(row, theme)).map(theme => ({ row, theme })));
183
+ const partJobs = built.frames.filter(row => row.parentRow).flatMap(row => themes.filter(theme => !session || session.scheduled(row, theme)).map(theme => ({ row, theme })));
177
184
  const concurrency = Math.min(4, availableParallelism());
178
185
  for (const jobs of [ordinaryJobs, partJobs]) for (let start = 0; start < jobs.length; start += concurrency) {
179
186
  const failures = [], openPairs = [];
@@ -244,8 +251,8 @@ export async function diff(config, args = [], options = {}, { launchBrowser = la
244
251
  timings.totalMs = performance.now() - started;
245
252
  data.reportPath = path.join(output, 'report.json');
246
253
  try {
247
- await mkdir(output, { recursive: true });
248
- await writeFile(data.reportPath, JSON.stringify(data, null, 2) + '\n');
254
+ if (!session) await mkdir(output, { recursive: true });
255
+ if (!session) await writeFile(data.reportPath, JSON.stringify(data, null, 2) + '\n');
249
256
  } catch (error) {
250
257
  data.reportPath = null; data.complete = false; data.verdict = null;
251
258
  if (primary) primary.warnings.push(classifyError(error).error);
@@ -20,10 +20,10 @@ export function implementationTexts(root, clip) {
20
20
  }
21
21
  return box.left >= left - 0.5 && box.right <= right + 0.5 && (box.top + box.bottom) / 2 >= top && (box.top + box.bottom) / 2 <= bottom;
22
22
  };
23
- const push = (text, box, owner, style = getComputedStyle(owner)) => {
23
+ const push = (text, box, owner, style = getComputedStyle(owner), leadingSpace = false) => {
24
24
  if (!inside(box, owner)) return;
25
25
  texts.push({ text, x: box.left - origin.left, y: box.top - origin.top, width: box.right - box.left, height: box.bottom - box.top,
26
- space: (measure.font = `${style.fontWeight} ${style.fontSize} ${style.fontFamily}`, measure.measureText(' ').width), anchor: style.textAlign === 'center' ? 'middle' : style.textAlign === 'right' ? 'end' : 'start', fill: style.color, size: style.fontSize, weight: style.fontWeight, family: style.fontFamily });
26
+ space: (measure.font = `${style.fontWeight} ${style.fontSize} ${style.fontFamily}`, measure.measureText(' ').width), leadingSpace, anchor: style.textAlign === 'center' ? 'middle' : style.textAlign === 'right' ? 'end' : 'start', fill: style.color, size: style.fontSize, weight: style.fontWeight, family: style.fontFamily });
27
27
  };
28
28
  const linesFor = node => {
29
29
  const result=[];
@@ -34,7 +34,7 @@ export function implementationTexts(root, clip) {
34
34
  if (!rect) continue;
35
35
  let line = lines.at(-1);
36
36
  if (!line || Math.abs(line.top - rect.top) >= rect.height / 2) {
37
- line = { text: '', top: rect.top, bottom: rect.bottom, chars: [] }; lines.push(line);
37
+ line = { text: '', top: rect.top, bottom: rect.bottom, chars: [], leadingSpace: /^\s/.test(node.data) }; lines.push(line);
38
38
  }
39
39
  line.text += node.data[index]; line.chars.push({ index, rect }); line.bottom = Math.max(line.bottom, rect.bottom);
40
40
  }
@@ -43,7 +43,7 @@ export function implementationTexts(root, clip) {
43
43
  if (!content) continue;
44
44
  const chars = line.chars.filter(({ index }) => !/\s/.test(node.data[index]));
45
45
  const box = { left: Math.min(...chars.map(c => c.rect.left)), right: Math.max(...chars.map(c => c.rect.right)), top: line.top, bottom: line.bottom };
46
- result.push({content,box});
46
+ result.push({content,box,leadingSpace:line.leadingSpace});
47
47
  }
48
48
  return result;
49
49
  };
@@ -51,7 +51,7 @@ export function implementationTexts(root, clip) {
51
51
  for (let node = walker.nextNode(); node; node = walker.nextNode()) {
52
52
  const owner=node.parentElement;
53
53
  if (!node.textContent.trim() || !owner || owner.closest('input,textarea') || !visible(owner)) continue;
54
- for (const {content,box} of linesFor(node)) push(content,box,owner);
54
+ for (const {content,box,leadingSpace} of linesFor(node)) push(content,box,owner,undefined,leadingSpace);
55
55
  }
56
56
  const canvas = document.createElement('canvas').getContext('2d');
57
57
  const fields='input:not([type]), input[type=text], input[type=search], input[type=email], input[type=url], input[type=tel], input[type=number], textarea';
@@ -77,7 +77,7 @@ export function implementationTexts(root, clip) {
77
77
  }
78
78
  const merged = [];
79
79
  for (const item of texts.sort((a,b) => a.y - b.y || a.x - b.x)) {
80
- const previous = merged.findLast(p => Math.abs(p.y + p.height/2 - item.y - item.height/2) < 1 && item.x >= p.x + p.width - .5 && item.x - p.x - p.width < Math.max(p.space, item.space) - .1);
80
+ const previous = merged.findLast(p => Math.abs(p.y + p.height/2 - item.y - item.height/2) < 1 && item.x >= p.x + p.width - .5 && item.x - p.x - p.width <= Math.max(p.space, item.space, item.leadingSpace ? 6 : 0) + .1);
81
81
  if (previous) { const gap = item.x - previous.x - previous.width; previous.text += (gap > .5 ? ' ' : '') + item.text; previous.width = item.x + item.width - previous.x; }
82
82
  else merged.push({...item});
83
83
  }
@@ -0,0 +1,6 @@
1
+ import { escape } from './html.mjs';
2
+
3
+ /** The builder and operation-local proof use the same exact document construction. */
4
+ export function frameDocument(frame, theme, css) {
5
+ return `<!doctype html><html data-theme="${theme}"><head><meta charset="utf-8"><style>${css.replace(/<\/style/gi, '<\\/style')}</style></head><body><div data-adg-frame="${escape(frame.name)}" style="${frame.width ? `width:${frame.width}px;` : 'width:max-content;'}${frame.height ? `height:${frame.height}px;` : ''}">${frame.html}</div></body></html>`;
6
+ }
@@ -0,0 +1,167 @@
1
+ /** Rich facets attach to the existing frame walk; they never discover or walk a second DOM tree. */
2
+ export function installInspectFacets() {
3
+ if (globalThis.__adgInspectFacets) return;
4
+ globalThis.__adgInspectFacets = {
5
+ create({ elements, paths, style, rect, origin, declarationsFor, tokens, theme, properties }) {
6
+ const p = globalThis.__adgFramePrimitives, facts = [], runs = [], limitations = [], orderKeys=new Map();
7
+ const customCache = new Map(), variableDeclarations = new Map(),referenceCache=new Map(),customKeys=new Map();
8
+ const valueFacts=[],valueKeys=new Map();
9
+ const projectDeclarations=new Map(tokens.map(t=>[t.name,new Set(t.values.map(v=>v.declaration))]));
10
+ const definitions = new Map(tokens.map(t => [t.name, t.values.find(v => v.theme === theme)?.declaration]));
11
+ const round = n => Math.round(n * 100) / 100 || 0;
12
+ const box = r => Object.fromEntries(Object.entries(p.relativeBox(r, origin)).map(([k,v]) => [k,round(v)]));
13
+ const limit = (code, path, accuracy='unavailable', property) => limitations.push({code,path,accuracy,...(property?{property}:{})});
14
+ const inherited = /^(?:color|font(?:-.+)?|line-height|letter-spacing|word-spacing|text-align|text-indent|text-transform|visibility|direction|writing-mode|white-space|word-break|overflow-wrap|fill|stroke(?:-.+)?)$/;
15
+ const relevant = (decl, prop) => decl === prop || ['font','background','border','margin','padding','gap','grid-row','grid-column','outline','text-decoration'].some(short => decl === short && (prop.startsWith(short+'-') || short === 'font' && prop === 'line-height' || short === 'gap' && /^(row|column)-gap$/.test(prop)));
16
+ function variableDeclarationsFor(node,pseudo=''){
17
+ let byPseudo=variableDeclarations.get(node);if(!byPseudo){byPseudo=new Map();variableDeclarations.set(node,byPseudo);}
18
+ if(!byPseudo.has(pseudo))byPseudo.set(pseudo,declarationsFor(node,pseudo).filter(d=>!d.property.startsWith('--')&&d.declaration.includes('var(')));
19
+ return byPseudo.get(pseudo);
20
+ }
21
+ function references(node, property, pseudo='') {
22
+ const candidates = [];
23
+ for (let parent=node; parent; parent=parent.parentElement) {
24
+ if (parent!==node && !inherited.test(property)) break;
25
+ for (const d of [...variableDeclarationsFor(parent, parent===node ? pseudo : ''), ...(pseudo&&parent===node&&inherited.test(property)?variableDeclarationsFor(parent):[])]) if (relevant(d.property,property)) {
26
+ candidates.push({...d,inherited:parent!==node});
27
+ }
28
+ }
29
+ if(!candidates.length)return {refs:[],unresolved:[]};
30
+ if(!customCache.has(node)){
31
+ const custom=new Map();
32
+ for(let parent=node;parent;parent=parent.parentElement)for(const d of declarationsFor(parent)){
33
+ if(parent===document.documentElement&&projectDeclarations.get(d.property)?.has(d.declaration))continue;
34
+ if(d.property.startsWith('--')&&!custom.has(d.property))custom.set(d.property,d.declaration);
35
+ }
36
+ customCache.set(node,custom);customKeys.set(node,JSON.stringify([...custom].sort(([a],[b])=>a.localeCompare(b))));
37
+ }
38
+ const custom=customCache.get(node),cacheKey=JSON.stringify([candidates,customKeys.get(node)]);
39
+ if(referenceCache.has(cacheKey))return referenceCache.get(cacheKey);
40
+ const refs=[], unresolved=[];
41
+ for (const d of candidates) {
42
+ function expand(name, via=[], fallback=false) {
43
+ if (via.includes(name)) { unresolved.push('token_cycle:'+name);return; }
44
+ const project=definitions.has(name), local=custom.has(name)&&custom.get(name)!==definitions.get(name);
45
+ if (project) refs.push({token:name,kind:fallback?'fallback':via.length?'alias':'direct',expression:d.declaration,via,inherited:d.inherited,basis:'authored_reference',
46
+ ...(d.property!==property?{shorthand:d.property}:{}),
47
+ ...(via.some(n=>custom.has(n)&&custom.get(n)!==definitions.get(n)) || local ? {localOverrides:[...new Set([...via,name])].filter(n=>custom.has(n)&&custom.get(n)!==definitions.get(n)).map(name=>({name,declaration:custom.get(name)}))}: {})});
48
+ const expression = local ? custom.get(name) : definitions.get(name);
49
+ if (expression===undefined) { unresolved.push('missing_variable:'+name);return; }
50
+ for (const v of p.variables(expression)) expand(v.name,[...via,name],fallback||v.fallback);
51
+ }
52
+ for (const v of p.variables(d.declaration)) expand(v.name,[],v.fallback);
53
+ }
54
+ const result={refs:[...new Map(refs.map(r=>[JSON.stringify(r),r])).values()],unresolved:[...new Set(unresolved)]};referenceCache.set(cacheKey,result);return result;
55
+ }
56
+ function styles(node, pseudo='') {
57
+ const s=pseudo?getComputedStyle(node,pseudo):style(node);
58
+ return properties.map(property=>{
59
+ const value={css:s.getPropertyValue(property),...references(node,property,pseudo)},key=JSON.stringify(value);
60
+ if(valueKeys.has(key))return valueKeys.get(key);
61
+ const index=valueFacts.length;valueFacts.push(value);valueKeys.set(key,index);return index;
62
+ });
63
+ }
64
+ const ancestors=new Map(),frameNode=document.querySelector('[data-adg-frame]');
65
+ function ancestry(node){
66
+ if(ancestors.has(node))return ancestors.get(node);
67
+ const parent=node===frameNode?null:node.parentElement,above=parent?ancestry(parent):null,s=style(node),r=rect(node);
68
+ const clip={...(above?.childClip??{left:origin.left,top:origin.top,right:origin.right,bottom:origin.bottom})},childClip={...clip};
69
+ if(s.display!=='inline'){
70
+ const sx=r.width/(node.offsetWidth||r.width||1),sy=r.height/(node.offsetHeight||r.height||1);
71
+ if(/hidden|clip|scroll|auto/.test(s.overflowX)){childClip.left=Math.max(childClip.left,r.left+(node.clientLeft||0)*sx);childClip.right=Math.min(childClip.right,r.left+((node.clientLeft||0)+node.clientWidth)*sx);}
72
+ if(/hidden|clip|scroll|auto/.test(s.overflowY)){childClip.top=Math.max(childClip.top,r.top+(node.clientTop||0)*sy);childClip.bottom=Math.min(childClip.bottom,r.top+((node.clientTop||0)+node.clientHeight)*sy);}
73
+ }
74
+ const rounded=(above?.rounded??0)+Number(s.display!=='inline'&&/hidden|clip|scroll|auto/.test(s.overflowX+s.overflowY)&&!!parseFloat(s.borderRadius));
75
+ const masks=(above?.masks??0)+Number(s.clipPath!=='none'||s.maskImage!=='none');
76
+ const result={clip,childClip,rounded,masks,ancestorRounded:above?.rounded??0,hidden:(above?.hidden??false)||s.display==='none'||Number(s.opacity)===0};ancestors.set(node,result);return result;
77
+ }
78
+ function geometry(node) {
79
+ const s=style(node), r=rect(node);
80
+ const laidOut=s.display!=='none' && s.display!=='contents' && node.getClientRects().length>0;
81
+ const g={box:laidOut?box(r):null,visibility:laidOut?'visible':'not_laid_out'};
82
+ if (!laidOut) return g;
83
+ const rects=[...node.getClientRects()].map(box);
84
+ if(rects.length>1)g.clientRects=rects;
85
+ if(node instanceof HTMLElement)g.layoutSize={width:node.offsetWidth,height:node.offsetHeight};
86
+ const inherited=ancestry(node),clip=inherited.clip,hidden=s.visibility!=='visible'||inherited.hidden;
87
+ for(let i=0;i<inherited.ancestorRounded;i++)limit('CLIP_SHAPE_APPROXIMATE',paths.get(node),'bounds','border-radius');
88
+ for(let i=0;i<inherited.masks;i++)limit('CLIP_SHAPE_APPROXIMATE',paths.get(node),'bounds','clip-path');
89
+ if(inherited.masks)g.clipAccuracy='bounds';
90
+ g.clip={x:round(clip.left-origin.left),y:round(clip.top-origin.top),width:round(Math.max(0,clip.right-clip.left)),height:round(Math.max(0,clip.bottom-clip.top))};
91
+ const visible={left:Math.max(r.left,clip.left),top:Math.max(r.top,clip.top),right:Math.min(r.right,clip.right),bottom:Math.min(r.bottom,clip.bottom)};
92
+ g.visibleBox=visible.right>visible.left&&visible.bottom>visible.top?box({...visible,width:visible.right-visible.left,height:visible.bottom-visible.top}):null;
93
+ g.visibility=hidden?'hidden':!g.visibleBox?'clipped':visible.left>r.left||visible.top>r.top||visible.right<r.right||visible.bottom<r.bottom?'partial':'visible';
94
+ g.clipAccuracy??='rect';
95
+ if(node.scrollWidth>node.clientWidth||node.scrollHeight>node.clientHeight||node.scrollTop||node.scrollLeft)g.scroll={x:node.scrollLeft||0,y:node.scrollTop||0,width:node.scrollWidth||0,height:node.scrollHeight||0,clientWidth:node.clientWidth||0,clientHeight:node.clientHeight||0};
96
+ if(s.transform!=='none'||s.rotate!=='none'||s.scale!=='none'||s.translate!=='none')limit('TRANSFORM_QUAD_UNAVAILABLE',paths.get(node),'bounds','transform');
97
+ return g;
98
+ }
99
+ function attributes(node) {
100
+ const attrs={};
101
+ for(const a of node.attributes) if (/^(?:id|data-part|data-adg-id|role|aria-.+|title|lang|dir|alt|for|type|placeholder|disabled|readonly|checked|selected|required|multiple|tabindex|href|target|rel)$/.test(a.name) && !/^data:/.test(a.value))attrs[a.name]=a.value;
102
+ if(node.matches('input,textarea,select')){
103
+ if(node.type==='password')attrs.valueRedacted=true;
104
+ else {attrs.value=node.value; if('checked'in node)attrs.checked=node.checked;}
105
+ }
106
+ return attrs;
107
+ }
108
+ function addRun(node, raw, kind, slot, boxes, accuracy='range', pseudo) {
109
+ const path=paths.get(node);
110
+ const run={path,slot,kind,raw,normalized:p.normalizeText(raw),boxes,accuracy,...(pseudo?{pseudo}:{})};
111
+ let group=node;for(;group&&group.parentElement;group=group.parentElement)if(group.matches('button,a,label,input,textarea,select,text')||!['inline','contents'].includes(style(group).display))break;
112
+ run.group=paths.get(group)??path;
113
+ const indices=[];let anchor=kind==='dom'?node.childNodes[slot]:node;
114
+ for(let current=anchor;current&&current!==document.querySelector('[data-adg-frame]');current=current.parentNode)indices.unshift([...current.parentNode.childNodes].indexOf(current));
115
+ if(kind!=='dom')indices.push(pseudo==='after'?Number.MAX_SAFE_INTEGER:-2);
116
+ orderKeys.set(run,indices);runs.push(run);
117
+ }
118
+ return {
119
+ node(node) {
120
+ const path=paths.get(node),s=style(node),g=geometry(node),attrs=attributes(node);
121
+ const fact={path,tag:node.localName,namespace:node.namespaceURI,attributes:attrs,geometry:g,values:styles(node),effects:{},pseudo:[]};
122
+ for(const property of ['filter','backdrop-filter','mix-blend-mode','isolation','contain','clip-path','mask-image','perspective']){
123
+ const value=s.getPropertyValue(property);
124
+ if(value && !['none','normal','auto'].includes(value)){fact.effects[property]=value;limit(property.includes('clip')||property.includes('mask')?'CLIP_SHAPE_APPROXIMATE':'INK_BOUNDS_UNAVAILABLE',path,'bounds',property);}
125
+ }
126
+ if(s.boxShadow!=='none'||s.textShadow!=='none')limit('INK_BOUNDS_UNAVAILABLE',path,'unavailable','shadow');
127
+ if(node.matches('canvas,video,object,embed,foreignObject')){limit('OPAQUE_RESOURCE',path);limit('DYNAMIC_PAINT',path);}
128
+ if(node.matches('animate,animateTransform,set'))limit('DYNAMIC_PAINT',path);
129
+ for(const kind of ['before','after','marker','placeholder']){
130
+ if(kind==='placeholder' && (!node.matches('input,textarea')||node.value||!node.placeholder))continue;
131
+ if(kind==='marker' && s.display!=='list-item')continue;
132
+ const ps=getComputedStyle(node,'::'+kind);
133
+ const content=kind==='placeholder'?node.placeholder:ps.content;
134
+ if(!['placeholder','marker'].includes(kind)&&['none','normal',''].includes(content))continue;
135
+ if(ps.display==='none')continue;
136
+ const pseudo={kind,content,values:styles(node,'::'+kind),geometry:{box:null,visibility:g.visibility}};
137
+ fact.pseudo.push(pseudo);limit('PSEUDO_BOX_UNAVAILABLE',path,'unavailable',kind);
138
+ let raw=kind==='placeholder'?content:[...content.matchAll(/"((?:\\.|[^"\\])*)"|'((?:\\.|[^'\\])*)'/g)].map(m=>(m[1]??m[2]).replace(/\\([\da-f]{1,6})\s?|\\(.)/gi,(_,hex,char)=>hex?String.fromCodePoint(parseInt(hex,16)||0xfffd):char)).join('');
139
+ if(kind==='marker'&&content==='normal'||/\b(?:attr|counter|counters|url)\(/.test(content)){raw=content;limit('GENERATED_TEXT_UNRESOLVED',path,'unavailable',kind);}
140
+ if(raw)addRun(node,raw,'pseudo',kind,[],'owner_box',kind);
141
+ }
142
+ if(!node.matches('script,style,defs,title,metadata') && !node.closest('defs')){
143
+ for(const [slot,child]of [...node.childNodes].entries())if(child.nodeType===3 && child.data.length){
144
+ const {rects}=p.textRects(child);addRun(node,child.data,'dom',slot,rects.map(box));
145
+ }
146
+ if(node.matches('input,textarea,select')&&node.type!=='password'){
147
+ const value=node.matches('select')?[...node.selectedOptions].map(o=>o.text).join(' '):node.value;
148
+ if(value)addRun(node,value,'control','value',g.box?[g.box]:[],'control_box');
149
+ }
150
+ }
151
+ const svg=node instanceof SVGElement;
152
+ if(svg){fact.svgAttributes={};for(const a of node.attributes)if(/^(?:d|points|x|y|width|height|cx|cy|r|rx|ry|viewBox|transform|href|xlink:href|gradientUnits|gradientTransform|offset|clipPathUnits|maskUnits|maskContentUnits|preserveAspectRatio|id)$/.test(a.name))fact.svgAttributes[a.name]=a.value;}
153
+ if(node.matches('svg,img,image,canvas,video')){
154
+ const url=node.currentSrc||node.getAttribute('src')||node.getAttribute('href')||node.getAttribute('xlink:href');
155
+ fact.resource={kind:node.matches('svg')?(node.hasAttribute('data-adg-icon')?'icon':'svg'):node.matches('img,image')?'raster':'opaque',source:node.getAttribute('data-adg-art'),url,
156
+ intrinsic:node instanceof HTMLImageElement?{width:node.naturalWidth,height:node.naturalHeight}:svg?{width:node.width?.baseVal?.value||g.box?.width||0,height:node.height?.baseVal?.value||g.box?.height||0}:null,
157
+ viewBox:node.getAttribute('viewBox'),icon:node.getAttribute('data-adg-icon')};
158
+ }
159
+ const urls=[...s.backgroundImage.matchAll(/url\(["']?([^)'"\s]+)["']?\)/g)].map(m=>m[1]);
160
+ if(urls.length)fact.backgrounds=urls;
161
+ facts.push(fact);
162
+ },
163
+ finish(){runs.sort((a,b)=>{const x=orderKeys.get(a),y=orderKeys.get(b);for(let i=0;i<Math.min(x.length,y.length);i++)if(x[i]!==y[i])return x[i]-y[i];return x.length-y.length;});return {properties,valueFacts,nodes:facts,runs,limitations,size:{width:round(origin.width),height:round(origin.height)},palette:Object.fromEntries(tokens.map(t=>[t.name,getComputedStyle(document.documentElement).getPropertyValue(t.name).trim()||null]))};},
164
+ };
165
+ },
166
+ };
167
+ }