@whzxc/agent-design-gallery 0.8.0 → 0.10.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 (36) hide show
  1. package/README.md +27 -1
  2. package/package.json +4 -1
  3. package/src/cli-output.mjs +40 -1
  4. package/src/cli.mjs +57 -8
  5. package/src/toolkit/arch-git.mjs +19 -0
  6. package/src/toolkit/build-store.mjs +6 -4
  7. package/src/toolkit/build-worker.mjs +5 -2
  8. package/src/toolkit/build.mjs +20 -5
  9. package/src/toolkit/commands.mjs +44 -14
  10. package/src/toolkit/config.mjs +6 -5
  11. package/src/toolkit/diff-inputs.mjs +5 -5
  12. package/src/toolkit/diff.mjs +14 -10
  13. package/src/toolkit/frame-document.mjs +6 -0
  14. package/src/toolkit/impact-eligibility.mjs +136 -0
  15. package/src/toolkit/impact-inputs.mjs +71 -0
  16. package/src/toolkit/impact-output.mjs +46 -0
  17. package/src/toolkit/impact-proof.mjs +67 -0
  18. package/src/toolkit/impact-selection.mjs +96 -0
  19. package/src/toolkit/impact.mjs +403 -0
  20. package/src/toolkit/implementation-map.mjs +129 -0
  21. package/src/toolkit/implementation-query.mjs +53 -0
  22. package/src/toolkit/index-store.mjs +99 -0
  23. package/src/toolkit/json-locations.mjs +28 -0
  24. package/src/toolkit/owner-authoring.mjs +39 -0
  25. package/src/toolkit/owner-colors.mjs +70 -0
  26. package/src/toolkit/owner-locators.mjs +73 -0
  27. package/src/toolkit/owner-observation.mjs +271 -0
  28. package/src/toolkit/owner-search.mjs +156 -0
  29. package/src/toolkit/owner.mjs +159 -0
  30. package/src/toolkit/project-index.mjs +188 -0
  31. package/src/toolkit/results.mjs +2 -2
  32. package/src/toolkit/runtime.d.ts +1 -1
  33. package/src/toolkit/runtime.mjs +1 -0
  34. package/src/toolkit/source-facts.mjs +25 -0
  35. package/src/toolkit/token-reachability.mjs +71 -0
  36. package/src/toolkit/tokens.mjs +9 -0
@@ -0,0 +1,403 @@
1
+ import path from 'node:path';
2
+ import { readFile, realpath, stat } from 'node:fs/promises';
3
+ import { CliError, nextActions } from '../cli-output.mjs';
4
+ import { openProjectIndex } from './project-index.mjs';
5
+ import { prepareImpactInputs, configInputFiles } from './impact-inputs.mjs';
6
+ import { matchDiffFrames } from './diff-inputs.mjs';
7
+ import { selectSources, relative } from './project.mjs';
8
+ import { loadImplementationMap, implementationFiles } from './implementation-map.mjs';
9
+ import { normalizeFileQuery, implementationScope } from './implementation-query.mjs';
10
+ import { selectorMatches } from './owner-locators.mjs';
11
+ import { relatedSources } from '../../public/relationships.js';
12
+ import { commandFailure, cleanup } from './results.mjs';
13
+ import { indexDigest } from './index-store.mjs';
14
+ import { groupImpactFrames, impactFrameCount } from './impact-output.mjs';
15
+ import { loadConfig } from './config.mjs';
16
+ import { canonicalBytes, capturePolicy, entryProjection, equalEntryProof, architectureProjection, equalProof } from './impact-proof.mjs';
17
+ import { createEligibilityChecker } from './impact-eligibility.mjs';
18
+
19
+ const slash = name => name.split(path.sep).join('/');
20
+ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
21
+ const outside = name => name === '..' || name.startsWith('../') || path.isAbsolute(name);
22
+ const array = value => value === undefined ? [] : Array.isArray(value) ? value : [value];
23
+ const themesFor = values => values.theme && values.theme !== 'both' ? [values.theme] : ['light', 'dark'];
24
+ const trackedHash = contents => indexDigest(contents === null ? 'missing\0' : Buffer.concat([Buffer.from('present\0'), contents]));
25
+ async function bytes(file) {
26
+ try { return await readFile(file); } catch (error) { if (['ENOENT', 'ENOTDIR'].includes(error.code)) return null; throw error; }
27
+ }
28
+
29
+ async function sourceInput(config, input, inventory) {
30
+ try { return relative(config, selectSources(config, [input], { write: false })[0]); }
31
+ catch (error) { if (error.code !== 'SOURCE_NOT_FOUND') throw error; }
32
+ for (const candidate of [path.resolve(config.root, input), path.resolve(config.design, input)]) {
33
+ let file, info;
34
+ try { file = await realpath(candidate); info = await stat(file); }
35
+ catch (error) { if (['ENOENT', 'ENOTDIR'].includes(error.code)) continue; throw error; }
36
+ const name = slash(path.relative(await realpath(config.root), file));
37
+ if (outside(name) || outside(slash(path.relative(await realpath(config.design), file)))) continue;
38
+ if (info.isFile() && !inventory.includes(name)) return name;
39
+ }
40
+ throw new CliError('SOURCE_NOT_FOUND', `Unknown design source/input ${input}; choose an existing source or design dependency.`);
41
+ }
42
+
43
+ function mappingBuild(facts) {
44
+ return { parts: facts.parts, frames: facts.frames.map(frame => ({ name: frame.name,
45
+ owners: frame.parts.map(part => ({ source: part.source, export: part.part })) })) };
46
+ }
47
+
48
+ /** Candidate queries and operation-local fresh-input proofs for exact Git endpoints. */
49
+ export async function impact(config, values, { log = console.log, openIndex = openProjectIndex, prepareInputs = prepareImpactInputs, consume } = {}) {
50
+ const started = performance.now(), themes = themesFor(values);
51
+ const timings = { prepareMs: 0, indexMs: 0, materializeMs: 0, proofMs: 0, queryMs: 0, totalMs: 0 };
52
+ const timed = async (name, work) => { const start = performance.now(); try { return await work(); } finally { timings[name] += performance.now() - start; } };
53
+ let inputs, data, primary;
54
+ const views = [], warnings = [], tracked = new Map();
55
+ async function track(file) { if (!tracked.has(file)) tracked.set(file, trackedHash(await bytes(file))); }
56
+ const warn = (code, message, next = []) => { if (!warnings.some(warning => warning.code === code)) warnings.push({ code, message, next }); };
57
+ const checkNext = reason => [{ argv: ['adg', 'check', '--read-only', '--json'], reason }];
58
+ async function verifyGeneration() {
59
+ // Detect edits before re-evaluating potentially broken configuration, then
60
+ // check again after evaluation so a config hook cannot mutate a tracked input.
61
+ for (const [file, expected] of tracked) if (trackedHash(await bytes(file)) !== expected) throw new CliError('IMPACT_INPUT_CHANGED', `Input changed during impact query: ${file}.`);
62
+ for (const view of views) {
63
+ await view.index.verifyInputs();
64
+ if (inputs) {
65
+ let resolved;
66
+ try { resolved = await loadConfig(view.config.root, { discover: false, fresh: true }); }
67
+ catch (cause) { throw new CliError('IMPACT_INPUT_CHANGED', `Configuration could not be revalidated: ${view.config.root}. ${cause.message}`, { cause }); }
68
+ if (canonicalBytes(resolved) !== view.resolved) throw new CliError('IMPACT_INPUT_CHANGED', `Resolved configuration changed during query: ${view.config.root}.`);
69
+ const files = await configInputFiles(resolved);
70
+ const names = files.map(file => slash(path.relative(resolved.root, file))).sort(compare);
71
+ if (canonicalBytes(names) !== canonicalBytes([...view.configInputs].sort(compare))) throw new CliError('IMPACT_INPUT_CHANGED', 'Configuration dependency inventory changed during query.');
72
+ }
73
+ }
74
+ for (const [file, expected] of tracked) if (trackedHash(await bytes(file)) !== expected) throw new CliError('IMPACT_INPUT_CHANGED', `Input changed during impact query: ${file}.`);
75
+ await inputs?.verifyChanges();
76
+ }
77
+ try {
78
+ let query, fileInput;
79
+ await timed('prepareMs', async () => {
80
+ if (values.base !== undefined) { inputs = await prepareInputs(config, values); query = inputs.query; warnings.push(...inputs.warnings); }
81
+ else if (values.file !== undefined) {
82
+ fileInput = await normalizeFileQuery(config, values);
83
+ const { kind, input, normalized, pathKind, line, symbol } = fileInput.query;
84
+ query = { kind, input, normalized, pathKind, line, symbol };
85
+ } else if (values.token !== undefined) query = { kind: 'token', tokens: [...new Set(array(values.token))] };
86
+ else query = { kind: 'source', sources: [], part: values.part ?? null };
87
+ });
88
+ data = { project: config.root, complete: false, query,
89
+ before: inputs ? { kind: 'revision', sha: query.base.sha } : null,
90
+ after: { kind: inputs?.after.revision ? 'revision' : 'working_tree', sha: inputs?.head ?? null },
91
+ selection: { themes, explain: !!values.explain }, changes: [], facts: [], frames: [], mappingFindings: [], unresolvedInputs: [],
92
+ coverage: { inventory: 'incomplete', mapping: 'not_requested', expectedRows: 0, candidateRows: 0, directRows: 0, transitiveRows: 0,
93
+ renderRows: 0, provenRows: 0, unassessedRows: 0, proofComplete: false,
94
+ tokenScan: { reachableRows: 0, fullSheetRows: 0, fallbackReasons: [] } }, timings };
95
+
96
+ if (inputs && !inputs.after.revision) for (const change of inputs.changes) {
97
+ for (const name of [change.before, change.after].filter(Boolean)) await track(path.join(inputs.repository, name));
98
+ }
99
+ for (const [side, endpoint] of inputs ? [['before', inputs.before], ['after', inputs.after]] : [['after', { config, revision: null }]]) {
100
+ const view = await timed('indexMs', async () => {
101
+ const current = endpoint.config;
102
+ const index = await openIndex(current, { stateDirectory: values['state-dir'], persist: !inputs && !endpoint.revision, fresh: !!inputs,
103
+ artifactDirectory: side === 'after' && values['out-dir'] !== undefined ? path.resolve(current.root, values['out-dir']) : undefined });
104
+ const view = { side, config: current, index, facts: new Map(), built: new Map(), architecture: new Map(),
105
+ graph: null, routes: new Map(), tokens: null, map: null, configInputs: new Set(), resolved: canonicalBytes(current) };
106
+ views.push(view);
107
+ for (const file of await configInputFiles(current)) { await track(file); view.configInputs.add(slash(path.relative(await realpath(current.root), file))); }
108
+ for (const name of ['adg.config.mjs', 'adg.config.js', 'adg.config.ts']) await track(path.join(current.root, name));
109
+ view.tokenFile = path.join(current.design, 'tokens.css');
110
+ await track(view.tokenFile); view.tokenBytes = await bytes(view.tokenFile);
111
+ if (inputs) for (const source of index.inventory.tsx) await track(path.join(current.root, source));
112
+ return view;
113
+ });
114
+ const { index, config: current } = view;
115
+ if (inputs) await timed('materializeMs', async () => {
116
+ const settled = await Promise.allSettled(index.inventory.tsx.map(async source => [source, await index.materialize(source)]));
117
+ for (const result of settled) { if (result.status === 'rejected') throw result.reason; view.built.set(...result.value); }
118
+ });
119
+ await timed('indexMs', async () => {
120
+ for (const source of index.inventory.tsx) {
121
+ const facts = await index.source(source, { tokens: query.kind === 'token' || query.kind === 'git', fresh: !!inputs });
122
+ view.facts.set(source, facts);
123
+ for (const frame of facts.tokenDependencies ?? []) for (const row of frame.themes) if (themes.includes(row.theme)) {
124
+ const scan = data.coverage.tokenScan;
125
+ if (row.mode === 'reachable_declarations') scan.reachableRows++;
126
+ else scan.fullSheetRows++;
127
+ for (const reason of row.fallbackReasons) if (!scan.fallbackReasons.includes(reason)) scan.fallbackReasons.push(reason);
128
+ }
129
+ }
130
+ for (const source of index.inventory.architecture) {
131
+ const metadata = await index.architecture(source), file = path.join(current.root, source), sidecar = path.join(current.root, metadata.sidecar);
132
+ await track(file); await track(sidecar);
133
+ view.architecture.set(source, { source: await bytes(file), sidecar: await bytes(sidecar), tokens: view.tokenBytes, config: current });
134
+ view.facts.set(source, { source, parts: [], imports: [], dependencies: [source, metadata.sidecar, relative(current, view.tokenFile)], frames: [{ name: 'default', parts: [] }] });
135
+ }
136
+ view.graph = await index.relationships({ facts: view.facts, projectPaths: true });
137
+ view.tokens = view.facts.size || query.kind === 'token' ? index.tokens() : [];
138
+ if (query.kind === 'file' || query.kind === 'git') { view.map = await loadImplementationMap(current); await track(view.map.file); }
139
+ });
140
+ }
141
+ const scan = data.coverage.tokenScan;
142
+ scan.fallbackReasons.sort(compare);
143
+ if (scan.fullSheetRows) warn('IMPACT_TOKEN_FALLBACK', `Token scan used the full sheet for ${scan.fullSheetRows} frame/theme inputs: ${scan.fallbackReasons.join(', ')}.`,
144
+ checkNext('Repair the reported token syntax or unbalanced var() declaration, then repeat the impact query.'));
145
+ const current = views.at(-1), previous = inputs ? views[0] : null;
146
+ const allSources = [...new Set(views.flatMap(view => [...view.facts.keys()]))].sort(compare);
147
+ let rows;
148
+ if (inputs) {
149
+ const renames = inputs.changes.filter(change => change.status === 'renamed').map(change => ({
150
+ before: slash(path.relative(inputs.projectPrefix || '.', change.before)), after: slash(path.relative(inputs.projectPrefix || '.', change.after)) }));
151
+ rows = matchDiffFrames(allSources, previous.facts, current.facts, renames);
152
+ } else rows = allSources.flatMap(source => current.facts.get(source).frames.map(frame => ({ source, frame: frame.name, status: 'current', matchKind: null, matchCandidates: [], before: null, after: frame })));
153
+ data.coverage.expectedRows = rows.length * themes.length;
154
+ const eligibility = createEligibilityChecker();
155
+ const entryChecks = new Map(), projections = new Map();
156
+ const projection = (view, built, frame, theme, reach) => {
157
+ if (!projections.has(built)) projections.set(built, entryProjection(built, capturePolicy(view.config)));
158
+ return projections.get(built)(frame, theme, reach);
159
+ };
160
+ const eligible = (built, frame, theme) => {
161
+ if (!entryChecks.has(built)) entryChecks.set(built, eligibility.withCss(built.css.replace(/<\/style/gi, '<\\/style')));
162
+ return entryChecks.get(built)(frame.html);
163
+ };
164
+ const assessments = new Map();
165
+ const requiredParents = new Set(rows.filter(row => row.status === 'added' && row.after.parent).map(row => JSON.stringify([row.after.parent.source, row.after.parent.frame])));
166
+ const seeds = [], factKeys = new Map();
167
+ function seed(view, kind, source, { part = null, token = null, selectedThemes = themes, pathIndexes = [], pointer = null, frames = null } = {}) {
168
+ const key = JSON.stringify([kind, source, part, token, selectedThemes, pointer, pathIndexes]);
169
+ let fact = factKeys.get(key);
170
+ if (!fact) { fact = { id: `f${factKeys.size + 1}`, kind, source, part, token, themes: selectedThemes, sides: [], pathIndexes }; factKeys.set(key, fact); data.facts.push(fact); }
171
+ if (!fact.sides.includes(view.side)) fact.sides.push(view.side);
172
+ seeds.push({ view, fact, pointer, frames });
173
+ }
174
+ function unresolved(name, reason) { if (!data.unresolvedInputs.some(input => input.path === name && input.reason === reason)) data.unresolvedInputs.push({ path: name, reason, fallback: 'none' }); }
175
+ async function mappings(view, indices, pathIndexes = []) {
176
+ if (!view.map.present) { data.coverage.mapping = data.coverage.mapping === 'stale' ? 'stale' : 'absent'; unresolved(view.map.source, 'mapping_absent'); return; }
177
+ if (data.coverage.mapping === 'not_requested') data.coverage.mapping = 'valid';
178
+ const validated = await view.index.mappings({ map: view.map, mappingIndices: indices,
179
+ getBuild: source => {
180
+ const facts = view.facts.get(source);
181
+ // Mapping validators expect design-relative marker provenance.
182
+ const built = mappingBuild(facts);
183
+ for (const frame of built.frames) for (const owner of frame.owners) owner.source = slash(path.relative(view.config.design, path.join(view.config.root, owner.source)));
184
+ return built;
185
+ } });
186
+ for (const finding of validated.findings) {
187
+ const existing = data.mappingFindings.find(item => JSON.stringify({ ...item, sides: undefined }) === JSON.stringify(finding));
188
+ if (existing) { if (!existing.sides.includes(view.side)) existing.sides.push(view.side); }
189
+ else data.mappingFindings.push({ ...finding, sides: [view.side] });
190
+ }
191
+ if (validated.findings.length) data.coverage.mapping = 'stale';
192
+ for (const [file, hash] of Object.entries(validated.implementationHashes)) {
193
+ const name = path.join(view.config.root, file);
194
+ const contents = await bytes(name), fingerprint = trackedHash(contents);
195
+ if (contents === null || indexDigest(contents) !== hash || tracked.has(name) && tracked.get(name) !== fingerprint) throw new CliError('IMPACT_INPUT_CHANGED', `Implementation input changed during query: ${name}.`);
196
+ tracked.set(name, fingerprint);
197
+ }
198
+ for (const binding of validated.bindings) {
199
+ const target = binding.design, facts = view.facts.get(target.source);
200
+ if (!facts) continue;
201
+ // A stale locator does not erase the resolvable declared source/part scope.
202
+ const part = target.part && facts.parts.includes(target.part) ? target.part : null;
203
+ const boundFrames = (target.frames ?? binding.frames).filter(name => facts.frames.some(frame => frame.name === name));
204
+ seed(view, 'mapping', target.source, { part, frames: boundFrames, pointer: binding.pointer, pathIndexes });
205
+ }
206
+ }
207
+
208
+ const proofBeforeQuery = timings.proofMs;
209
+ await timed('queryMs', async () => {
210
+ if (query.kind === 'source') {
211
+ for (const input of array(values.source)) {
212
+ const source = await sourceInput(config, input, allSources); if (!query.sources.includes(source)) query.sources.push(source);
213
+ }
214
+ if (query.part && (query.sources.length !== 1 || !current.facts.get(query.sources[0])?.parts.includes(query.part))) throw new CliError('IMPACT_INPUT_NOT_FOUND', `Unknown design part ${query.part}; choose a registered export in one TSX source.`);
215
+ for (const source of query.sources) { await track(path.join(config.root, source)); seed(current, query.part ? 'part' : 'source', source, { part: query.part }); }
216
+ } else if (query.kind === 'token') {
217
+ for (const token of query.tokens) {
218
+ if (!current.tokens.some(item => item.name === token)) throw new CliError('IMPACT_INPUT_NOT_FOUND', `Unknown token ${token}; choose a name declared in tokens.css.`);
219
+ seed(current, 'token', relative(config, path.join(config.design, 'tokens.css')), { token });
220
+ }
221
+ } else if (query.kind === 'file') {
222
+ const selector = { [query.pathKind === 'directory' ? 'directory' : query.pathKind === 'glob' ? 'glob' : 'file']: query.normalized };
223
+ const files = await implementationFiles(config, selector);
224
+ const { mappingIndices } = implementationScope(current.map, query, fileInput.text, files, { includeStale: true });
225
+ for (const file of files) { await track(path.join(config.root, file)); seed(current, 'implementation', file); }
226
+ await mappings(current, mappingIndices);
227
+ if (!mappingIndices.size) unresolved(query.normalized, 'mapping_unmatched');
228
+ } else {
229
+ const knownDependencies = new Set(views.flatMap(view => [...view.facts.values()].flatMap(facts => facts.dependencies)));
230
+ const mapMatches = name => views.some(view => view.map.mappings.some(mapping => selectorMatches(mapping.implementation, name)));
231
+ for (const change of inputs.changes) {
232
+ const names = [change.before, change.after].filter(Boolean).map(name => slash(path.relative(inputs.projectPrefix || '.', name)));
233
+ const is = predicate => names.some(predicate);
234
+ let role;
235
+ if (is(name => views.some(view => relative(view.config, path.join(view.config.design, 'tokens.css')) === name))) role = 'token';
236
+ else if (is(name => views.some(view => view.map.source === name))) role = 'mapping';
237
+ else if (is(name => views.some(view => view.configInputs.has(name)))) role = 'config';
238
+ else if (is(name => /(?:^|\/)(?:package\.json|package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?)$/.test(name))) role = 'environment';
239
+ else if (names.every(outside)) role = 'outside_design_inputs';
240
+ else if (is(name => views.some(view => view.index.inventory.architecture.includes(name) || view.index.inventory.architecture.includes(name.replace(/\.md$/, '.mmd'))))) role = 'architecture';
241
+ else if (is(name => knownDependencies.has(name) && name.endsWith('.css'))) role = 'global_css';
242
+ else if (is(name => allSources.includes(name) || knownDependencies.has(name) || views.some(view => name.startsWith(relative(view.config, view.config.design) + '/')))) role = 'design';
243
+ else if (is(name => mapMatches(name) || /\.(?:[cm]?[jt]sx?|css|vue|svelte|rs|go|py|swift|c|h|cpp)$/.test(name))) role = 'implementation';
244
+ else if (is(name => /\.(?:md|txt|png|jpe?g|svg|webp)$/.test(name))) role = 'outside_design_inputs';
245
+ else role = 'unknown';
246
+ const pathIndex = data.changes.length; data.changes.push({ ...change, role });
247
+ if (!inputs.after.revision) for (const name of [change.before, change.after].filter(Boolean)) await track(path.join(inputs.repository, name));
248
+ for (const view of views) {
249
+ const repositoryName = view.side === 'before' ? change.before : change.after ?? (['implementation', 'mapping'].includes(role) ? change.before : null);
250
+ if (!repositoryName) continue;
251
+ const name = slash(path.relative(inputs.projectPrefix || '.', repositoryName)), options = { pathIndexes: [pathIndex] };
252
+ if (role === 'token') {
253
+ const other = view === current ? previous : current;
254
+ for (const item of view.tokens) {
255
+ const selectedThemes = themes.filter(theme => item.values.find(value => value.theme === theme)?.declaration !== other.tokens.find(token => token.name === item.name)?.values.find(value => value.theme === theme)?.declaration);
256
+ if (selectedThemes.length) seed(view, 'token', name, { ...options, token: item.name, selectedThemes });
257
+ }
258
+ } else if (role === 'mapping') {
259
+ if (!current.map.present) { data.coverage.mapping = 'absent'; unresolved(current.map.source, 'mapping_absent'); }
260
+ const otherMap = (view === current ? previous : current).map;
261
+ const indices = new Set(view.map.mappings.flatMap((mapping, i) => otherMap.mappings.some(other => JSON.stringify(other) === JSON.stringify(mapping)) ? [] : [i]));
262
+ await mappings(view, indices, [pathIndex]);
263
+ } else if (role === 'implementation') {
264
+ seed(view, 'implementation', name, options);
265
+ const indices = new Set(view.map.mappings.flatMap((mapping, i) => names.some(candidate => selectorMatches(mapping.implementation, candidate)) ? [i] : []));
266
+ await mappings(view, indices, [pathIndex]);
267
+ if (!indices.size) unresolved(name, 'mapping_unmatched');
268
+ } else if (role === 'architecture') seed(view, 'architecture', name.endsWith('.md') ? name.replace(/\.md$/, '.mmd') : name, options);
269
+ else if (role !== 'outside_design_inputs') seed(view, role === 'design' ? 'source' : role, outside(name) ? null : name, options);
270
+ }
271
+ }
272
+ }
273
+
274
+ for (const row of rows) {
275
+ const frame = { ref: { source: row.source, frame: row.frame }, status: row.status, matchKind: row.matchKind, matchCandidates: row.matchCandidates, themes: [] };
276
+ for (const theme of themes) {
277
+ const reasons = new Map();
278
+ function add(seed, kind, scope, witness, count = 1) {
279
+ const key = JSON.stringify([seed.fact.id, kind, scope]);
280
+ let reason = reasons.get(key);
281
+ if (!reason) { reason = { fact: seed.fact.id, class: kind, scope, sides: [], count: 0, ...(values.explain ? { witness } : {}) }; reasons.set(key, reason); }
282
+ if (!reason.sides.includes(seed.view.side)) { reason.sides.push(seed.view.side); reason.count += count; }
283
+ }
284
+ for (const item of seeds) {
285
+ if (!item.fact.themes.includes(theme)) continue;
286
+ const facts = item.view.facts.get(row.source), declared = facts?.frames.find(frame => frame.name === row.frame);
287
+ if (!declared) continue;
288
+ const { kind, source, part, token } = item.fact;
289
+ const witness = { origin: 'build', source, part, token, via: [], mappingPointer: item.pointer };
290
+ if (['config', 'global_css', 'environment', 'unknown'].includes(kind)) { add(item, kind === 'unknown' ? 'unknown' : 'global', 'global', witness); continue; }
291
+ if (kind === 'token') {
292
+ const reach = facts.tokenDependencies?.find(value => value.frame === row.frame)?.themes.find(value => value.theme === theme);
293
+ if (reach?.names.includes(token)) add(item, 'token_dependency', 'transitive', { ...witness, origin: 'lexical', via: reach.via[token] ?? [] });
294
+ else if (facts.source.endsWith('.mmd')) add(item, 'dependency', 'transitive', witness);
295
+ continue;
296
+ }
297
+ const direct = row.source === source;
298
+ if (direct || facts.dependencies.includes(source)) {
299
+ if (values.explain && !direct && !item.view.routes.has(source)) item.view.routes.set(source, new Map(relatedSources(item.view.graph, source, 'usedBy').map(value => [value.path, value.via])));
300
+ const route = values.explain && !direct ? item.view.routes.get(source)?.get(row.source) ?? [] : [];
301
+ add(item, 'dependency', direct ? 'direct' : 'transitive', { ...witness, via: route });
302
+ }
303
+ const occurrences = declared.parts.filter(owner => owner.source === source && (!part || owner.part === part));
304
+ if (occurrences.length) add(item, 'part_occurrence', direct ? 'direct' : 'transitive', { ...witness, origin: 'emitted', part: occurrences[0].part }, occurrences.length);
305
+ if (kind === 'mapping' && direct && item.frames.includes(row.frame)) add(item, 'mapping', 'declared', { ...witness, origin: 'declaration' });
306
+ }
307
+ if (inputs && ['added', 'removed'].includes(row.status)) {
308
+ const view = row.status === 'added' ? current : previous;
309
+ let lifecycle = seeds.find(seed => seed.view === view && seed.fact.source === row.source);
310
+ if (!lifecycle) { seed(view, row.source.endsWith('.mmd') ? 'architecture' : 'source', row.source); lifecycle = seeds.at(-1); }
311
+ add(lifecycle, 'lifecycle', 'direct', { origin: 'build', source: row.source, part: null, token: null, via: [], mappingPointer: null });
312
+ }
313
+ if (inputs && requiredParents.has(JSON.stringify([row.source, row.frame]))) {
314
+ const child = rows.find(child => child.status === 'added' && child.after.parent?.source === row.source && child.after.parent.frame === row.frame);
315
+ let support = seeds.find(seed => seed.view === current && seed.fact.source === child.source);
316
+ if (!support) { seed(current, 'source', child.source); support = seeds.at(-1); }
317
+ add(support, 'dependency', 'support', { origin: 'build', source: child.source, part: null, token: null, via: [], mappingPointer: null });
318
+ }
319
+ const ordered = [...reasons.values()].sort((a, b) => compare(a.fact, b.fact) || compare(a.class, b.class) || compare(a.scope, b.scope));
320
+ if (reasons.size) {
321
+ data.coverage.candidateRows++;
322
+ if (ordered.some(reason => reason.scope === 'direct')) data.coverage.directRows++;
323
+ if (ordered.some(reason => reason.scope === 'transitive')) data.coverage.transitiveRows++;
324
+ }
325
+ const result = { theme, candidate: !!reasons.size, disposition: 'render', reasons: ordered, proof: null, unassessedReasons: [] };
326
+ if (inputs) await timed('proofMs', async () => {
327
+ if (row.status !== 'matched' || row.matchKind !== 'exact') result.unassessedReasons = ['missing_side'];
328
+ else if (row.source.endsWith('.mmd')) {
329
+ const before = architectureProjection(previous.architecture.get(row.source)), after = architectureProjection(current.architecture.get(row.source));
330
+ result.proof = equalProof(before, after, 'architecture_inputs_equal', 'full_sheet', values.explain);
331
+ } else {
332
+ const builtBefore = previous.built.get(row.source), builtAfter = current.built.get(row.source);
333
+ const before = builtBefore.frames.find(frame => frame.name === row.frame), after = builtAfter.frames.find(frame => frame.name === row.frame);
334
+ result.unassessedReasons = [...new Set([...eligible(builtBefore, before, theme), ...eligible(builtAfter, after, theme)])].sort(compare);
335
+ if (!result.unassessedReasons.length) {
336
+ const reach = (view, frame) => view.facts.get(row.source).tokenDependencies.find(item => item.frame === frame.name).themes.find(item => item.theme === theme);
337
+ const left = projection(previous, builtBefore, before, theme, reach(previous, before));
338
+ const right = projection(current, builtAfter, after, theme, reach(current, after));
339
+ result.proof = equalEntryProof(left, right, values.explain);
340
+ }
341
+ }
342
+ if (result.proof && !requiredParents.has(JSON.stringify([row.source, row.frame]))) result.disposition = 'proven_unaffected';
343
+ else result.proof = null;
344
+ });
345
+ if (inputs) {
346
+ if (result.disposition === 'proven_unaffected') data.coverage.provenRows++;
347
+ else data.coverage.renderRows++;
348
+ } else if (reasons.size) data.coverage.renderRows++;
349
+ else { result.disposition = 'unassessed'; data.coverage.unassessedRows++; }
350
+ assessments.set(JSON.stringify([row.source, row.frame, theme]), result);
351
+ if (result.candidate || result.disposition === 'render') frame.themes.push(result);
352
+ }
353
+ if (frame.themes.length) data.frames.push(frame);
354
+ }
355
+ });
356
+ timings.queryMs = Math.max(0, timings.queryMs - (timings.proofMs - proofBeforeQuery));
357
+ data.coverage.inventory = 'complete';
358
+ if (data.unresolvedInputs.length || data.mappingFindings.length) warn('IMPACT_MAPPING_INCOMPLETE', 'Some implementation mappings are absent, unmatched or stale; inspect the resolvable targets and findings.', checkNext('Repair implementation.json and its reported locators before repeating the query.'));
359
+ if (!data.frames.length) {
360
+ const observed = query.kind === 'token' ? { token: query.tokens[0], theme: values.theme } : query.kind === 'file' ? { file: query.input, theme: values.theme } : null;
361
+ warn(query.kind === 'git' ? 'IMPACT_NO_CHANGES' : 'IMPACT_NO_MATCH', 'No frame candidates matched the changed design facts.',
362
+ query.kind === 'git' ? [] : observed ? nextActions('OWNER_UNSETTLED', { command: 'owner', values: observed }) : checkNext('Inspect design inputs and emitted part coverage.'));
363
+ }
364
+
365
+ if (consume) await consume({ views, rows, assessments, inputs, data });
366
+ } catch (cause) {
367
+ if (inputs) { try { await verifyGeneration(); } catch (changed) { cause = changed; } }
368
+ if (cause.code === 'OWNER_INDEX_CHANGED') cause = new CliError('IMPACT_INPUT_CHANGED', cause.message, { cause });
369
+ if (inputs) { cause.message = inputs.translate(cause.message); if (cause.context) cause.context = inputs.translate(cause.context); }
370
+ primary = data ? commandFailure(cause, data, warnings) : cause;
371
+ } finally {
372
+ for (const view of [...views].reverse()) {
373
+ try { await cleanup(() => view.index.close(), primary); } catch (cause) { primary = data ? commandFailure(cause, data, warnings) : cause; }
374
+ }
375
+ if (!primary) {
376
+ try { await verifyGeneration(); data.coverage.proofComplete = !!inputs; }
377
+ catch (cause) {
378
+ if (cause.code === 'OWNER_INDEX_CHANGED') cause = new CliError('IMPACT_INPUT_CHANGED', cause.message, { cause });
379
+ if (inputs) cause.message = inputs.translate(cause.message);
380
+ primary = data ? commandFailure(cause, data, warnings) : cause;
381
+ }
382
+ }
383
+ try { await cleanup(() => inputs?.close(), primary); } catch (cause) { primary = data ? commandFailure(cause, data, warnings) : cause; }
384
+ }
385
+
386
+ timings.totalMs = performance.now() - started;
387
+ if (primary && data) {
388
+ data.coverage.proofComplete = false;
389
+ data.coverage.unassessedRows += data.coverage.provenRows; data.coverage.provenRows = 0;
390
+ for (const frame of data.frames) for (const row of frame.themes) if (row.proof) {
391
+ row.proof = null; row.disposition = 'unassessed'; row.unassessedReasons = ['incomplete_identity'];
392
+ }
393
+ }
394
+ if (data) data.frames = groupImpactFrames(data.frames, { explain: !!values.explain });
395
+ if (primary) throw primary;
396
+ data.complete = true;
397
+ if (!values.json) {
398
+ log(`${impactFrameCount(data.frames)} listed frames; ${data.coverage.candidateRows} theme rows; ${data.coverage.unassessedRows} unassessed. ${data.coverage.provenRows} proven.`);
399
+ for (const group of data.frames) log(`${group.source}#${group.frames.join(', ')} [${group.rows.flatMap(row => row.themes).join(',')}] ${[...new Set(group.rows.flatMap(row => (row.reasons ?? []).map(reason => reason.class)))].join(', ')}`);
400
+ for (const warning of warnings) log(`${warning.code}: ${warning.message}`);
401
+ }
402
+ return { data, warnings };
403
+ }
@@ -0,0 +1,129 @@
1
+ import { readFile, realpath, stat, readdir } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { CliError } from '../cli-output.mjs';
4
+ import { portablePath, globPattern, resolveLocator, symbolRegions, selectorMatches } from './owner-locators.mjs';
5
+ import { indexDigest } from './index-store.mjs';
6
+ import { mappingFacts } from './source-facts.mjs';
7
+ import { jsonLocations } from './json-locations.mjs';
8
+
9
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
10
+ const keys = (value, allowed) => object(value) && Object.keys(value).every(key => allowed.includes(key));
11
+ const nonempty = value => typeof value === 'string' && !!value.trim();
12
+ const missing = error => ['ENOENT', 'ENOTDIR'].includes(error.code);
13
+ const inside = (root, file) => { const rel = path.relative(root, file); return rel !== '..' && !rel.startsWith('..' + path.sep) && !path.isAbsolute(rel); };
14
+ const rel = (config, file) => path.relative(config.root, file).split(path.sep).join('/');
15
+ const invalid = message => { throw new CliError('OWNER_MAP_INVALID', message); };
16
+
17
+ export function parseImplementationMap(text) {
18
+ let value;
19
+ try { value = JSON.parse(text); } catch { invalid('Invalid implementation.json JSON; repair the mapping file.'); }
20
+ if (!keys(value, ['version', 'mappings']) || value.version !== 1 || !Array.isArray(value.mappings)) invalid('implementation.json needs version 1 and a mappings array.');
21
+ value.mappings.forEach((mapping, index) => {
22
+ const pointer = `/mappings/${index}`, fail = reason => invalid(`${pointer}: ${reason}`);
23
+ if (!keys(mapping, ['implementation', 'design']) || !Array.isArray(mapping.design) || !mapping.design.length) fail('use an implementation selector and nonempty design bindings.');
24
+ const s = mapping.implementation;
25
+ if (!object(s) || ['file', 'directory', 'glob'].filter(key => Object.hasOwn(s, key)).length !== 1) fail('choose exactly one file, directory or glob selector.');
26
+ const kind = ['file', 'directory', 'glob'].find(key => Object.hasOwn(s, key));
27
+ if (!keys(s, kind === 'file' ? ['file', 'symbol', 'anchor'] : [kind]) || !portablePath(s[kind], { directory: kind === 'directory', glob: kind === 'glob' })) fail('use a portable project-relative selector; glob supports *, ? and whole-segment **.');
28
+ if (s.symbol !== undefined && !nonempty(s.symbol)) fail('symbol must be a nonempty exact label.');
29
+ if (s.anchor !== undefined && (!nonempty(s.anchor) || !s.symbol)) fail('a nonempty anchor requires a symbol.');
30
+ if (s.symbol && !/\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(s.file) && s.anchor === undefined) fail('this file type requires an explicit symbol anchor.');
31
+ for (const target of mapping.design) {
32
+ if (!keys(target, ['source', 'part', 'frames']) || !portablePath(target.source) || !target.source.endsWith('.tsx') ||
33
+ target.part !== undefined && !nonempty(target.part) || target.frames !== undefined && (!Array.isArray(target.frames) || !target.frames.length || target.frames.some(frame => !nonempty(frame)))) fail('use a TSX source, optional part and nonempty exact frame list.');
34
+ }
35
+ });
36
+ return value;
37
+ }
38
+
39
+ export async function loadImplementationMap(config) {
40
+ const file = path.join(config.design, 'implementation.json');
41
+ let text;
42
+ try { text = await readFile(file, 'utf8'); } catch (error) { if (error.code === 'ENOENT') return { file, source: rel(config, file), present: false, mappings: [] }; throw error; }
43
+ if (!inside(await realpath(config.root), await realpath(file))) invalid('implementation.json resolves outside the project.');
44
+ return { ...parseImplementationMap(text), file, source: rel(config, file), present: true, inputHash: indexDigest(text), locations: jsonLocations(text) };
45
+ }
46
+
47
+ /** Expands only the selector prefix; escaping symlinks are rejected, not followed. */
48
+ export async function implementationFiles(config, selector) {
49
+ const root = await realpath(config.root);
50
+ const output = path.resolve(root, path.relative(config.root, config.output ?? path.join(config.root, 'output/design')));
51
+ const excluded = file => path.relative(root, file).split(path.sep).some(p => ['.git', 'node_modules', '.adg'].includes(p)) || inside(output, file);
52
+ const check = async file => {
53
+ if (!inside(root, await realpath(file))) invalid(`Implementation selector resolves outside the project: ${rel(config, file)}.`);
54
+ return stat(file);
55
+ };
56
+ if (selector.file) {
57
+ const file = path.join(root, selector.file);
58
+ try { return (await check(file)).isFile() ? [selector.file] : []; } catch (error) { if (missing(error)) return []; throw error; }
59
+ }
60
+ const pattern = selector.glob && globPattern(selector.glob);
61
+ const segments = selector.glob?.split('/') ?? [];
62
+ const wildcard = segments.findIndex(segment => /[?*]/.test(segment));
63
+ const prefix = selector.directory ?? segments.slice(0, wildcard < 0 ? -1 : wildcard).join('/');
64
+ const base = path.join(root, prefix), files = [], seen = new Set();
65
+ async function visit(file) {
66
+ if (excluded(file)) return;
67
+ const physical = await realpath(file), info = await check(file);
68
+ if (info.isDirectory()) {
69
+ if (seen.has(physical)) return;
70
+ seen.add(physical);
71
+ for (const entry of await readdir(file)) await visit(path.join(file, entry));
72
+ } else if (info.isFile()) {
73
+ const name = path.relative(root, file).split(path.sep).join('/');
74
+ if (!pattern || pattern.test(name)) files.push(name);
75
+ }
76
+ }
77
+ try {
78
+ if (selector.directory && !(await check(base)).isDirectory()) return [];
79
+ await visit(base);
80
+ } catch (error) { if (!missing(error)) throw error; }
81
+ return files.sort();
82
+ }
83
+
84
+ export async function validateImplementationMap(config, map, { sources, selected, getBuild, onFinding = () => {}, mappingIndices, implementationSelection }) {
85
+ const findings = [], bindings = [], regions = {}, seen = new Set(), builds = new Map(), contents = new Map();
86
+ const sourceSet = new Set(sources), scope = selected && new Set(selected);
87
+ const report = (code, pointer, selector, target, message, candidates = [], frame = null) => {
88
+ const finding = { code, source: map.source, pointer, implementation: selector.file ?? selector.directory ?? selector.glob,
89
+ target, line: map.locations?.[pointer]?.line ?? null, column: map.locations?.[pointer]?.column ?? null, frame, theme: null, message: `${pointer}: ${message}`, observedAnchorLines: candidates };
90
+ findings.push(finding); onFinding(finding);
91
+ };
92
+ for (const [index, mapping] of map.mappings.entries()) {
93
+ if (mappingIndices && !mappingIndices.has(index)) continue;
94
+ const targets = mapping.design.map((target, i) => ({ target, pointer: `/mappings/${index}/design/${i}` })).filter(({ target }) => !scope || scope.has(target.source));
95
+ if (!targets.length) continue;
96
+ const selector = mapping.implementation, pointer = `/mappings/${index}/implementation`;
97
+ const files = implementationSelection ? implementationSelection.filter(file => selectorMatches(selector, file)) : await implementationFiles(config, selector);
98
+ if (implementationSelection && !files.length) continue;
99
+ let locator = { line: null, candidates: [], stale: false };
100
+ if (!files.length) report('OWNER_IMPLEMENTATION_MISSING', pointer, selector, null, 'Selector matches no current implementation file.');
101
+ else if (selector.symbol) {
102
+ if (!contents.has(selector.file)) contents.set(selector.file, await readFile(path.join(config.root, selector.file), 'utf8'));
103
+ locator = resolveLocator(contents.get(selector.file), selector);
104
+ if (locator.stale) report('OWNER_LOCATOR_STALE', pointer, selector, null, 'Symbol must resolve exactly once; add or repair an explicit anchor.', locator.candidates);
105
+ }
106
+ for (const { target, pointer: targetPointer } of targets) {
107
+ let valid = files.length > 0 && !locator.stale, frames = [];
108
+ const duplicate = JSON.stringify([Object.fromEntries(Object.entries(selector).sort()), { source: target.source, part: target.part ?? null, frames: target.frames ? [...target.frames].sort() : null }]);
109
+ if (seen.has(duplicate)) { report('OWNER_MAPPING_DUPLICATE', targetPointer, selector, target, 'Duplicate implementation/design binding.'); continue; }
110
+ seen.add(duplicate);
111
+ if (!sourceSet.has(target.source)) { report('OWNER_SOURCE_MISSING', targetPointer, selector, target, `Undiscovered source ${target.source}.`); valid = false; }
112
+ else if (!implementationSelection || valid) {
113
+ if (!builds.has(target.source)) builds.set(target.source, Promise.resolve(getBuild(target.source)).then(mappingFacts));
114
+ const built = await builds.get(target.source);
115
+ if (target.part && !(built.parts ?? []).includes(target.part)) { report('OWNER_PART_MISSING', targetPointer, selector, target, `Missing design component ${target.part}.`); valid = false; }
116
+ frames = built.frames.filter(frame => !target.frames || target.frames.includes(frame.name));
117
+ for (const name of target.frames ?? []) if (!built.frames.some(frame => frame.name === name)) { report('OWNER_FRAME_MISSING', targetPointer, selector, target, `Missing frame ${name}.`, [], name); valid = false; }
118
+ if (target.part && (built.parts ?? []).includes(target.part)) {
119
+ const matches = frame => frame.owners.some(owner => rel(config, path.join(config.design, owner.source)) === target.source && owner.export === target.part);
120
+ if (target.frames) for (const frame of frames) if (!matches(frame)) { report('OWNER_PART_FRAME_MISMATCH', targetPointer, selector, target, `Explicit frame ${frame.name} does not contain ${target.part}.`, [], frame.name); valid = false; }
121
+ frames = frames.filter(matches);
122
+ }
123
+ }
124
+ bindings.push({ pointer: targetPointer, implementation: selector, design: target, files, anchorLine: locator.line, frames: frames.map(frame => frame.name), active: valid });
125
+ }
126
+ }
127
+ for (const [file, text] of contents) regions[file] = symbolRegions(text, file, map.mappings.map(m => m.implementation).filter(s => s.file === file));
128
+ return { findings, bindings, regions, implementationHashes: Object.fromEntries([...contents].map(([file, text]) => [file, indexDigest(text)])) };
129
+ }
@@ -0,0 +1,53 @@
1
+ import { readFile, realpath, stat } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { CliError } from '../cli-output.mjs';
4
+ import { portablePath, selectorMatches, resolveLocator, symbolRegions, regionAt, sourceLineCount } from './owner-locators.mjs';
5
+
6
+ export async function normalizeFileQuery(config, values) {
7
+ const root = await realpath(config.root), input = values.file;
8
+ if (typeof input !== 'string' || !input.trim()) throw new CliError('USAGE_INVALID', 'Set one nonempty --file input.');
9
+ let absolute = path.resolve(root, input);
10
+ if (path.isAbsolute(input) && !/[?*]/.test(input)) {
11
+ try { absolute = await realpath(input); } catch (error) { if (!['ENOENT', 'ENOTDIR'].includes(error.code)) throw error; throw new CliError('OWNER_INPUT_NOT_FOUND', 'Ownership input does not name an existing file or directory.'); }
12
+ }
13
+ const relative = path.relative(root, absolute).split(path.sep).join('/');
14
+ if (relative === '..' || relative.startsWith('../') || path.isAbsolute(relative)) throw new CliError('USAGE_INVALID', 'Ownership input must stay inside the project root.');
15
+ let pathKind, normalized = relative;
16
+ if (/[?*]/.test(relative)) {
17
+ if (!portablePath(relative, { glob: true })) throw new CliError('USAGE_INVALID', 'Use a POSIX glob with *, ? and whole-segment **.');
18
+ pathKind = 'glob';
19
+ } else {
20
+ let info;
21
+ try { info = await stat(absolute); } catch (error) { if (!['ENOENT', 'ENOTDIR'].includes(error.code)) throw error; throw new CliError('OWNER_INPUT_NOT_FOUND', 'Ownership input does not name an existing file or directory.'); }
22
+ const physical = path.relative(root, await realpath(absolute));
23
+ if (physical === '..' || physical.startsWith('..' + path.sep) || path.isAbsolute(physical)) throw new CliError('USAGE_INVALID', 'Ownership input resolves outside the project root.');
24
+ if (!info.isFile() && !info.isDirectory()) throw new CliError('USAGE_INVALID', 'Choose a regular implementation file or directory.');
25
+ pathKind = info.isDirectory() ? 'directory' : 'file';
26
+ if (pathKind === 'directory') normalized = relative ? relative + '/' : './';
27
+ }
28
+ const line = values.line === undefined ? null : Number(values.line), symbol = values.symbol ?? null;
29
+ if ((line !== null || symbol !== null) && pathKind !== 'file') throw new CliError('USAGE_INVALID', '--line and --symbol require a single file.');
30
+ const text = line !== null || symbol !== null ? await readFile(absolute, 'utf8') : null;
31
+ if (line !== null && (!Number.isSafeInteger(line) || line < 1 || line > sourceLineCount(text))) throw new CliError('USAGE_INVALID', '--line must name an existing 1-based line in the implementation file.');
32
+ if (values.theme !== undefined && !['both', 'light', 'dark'].includes(values.theme)) throw new CliError('USAGE_INVALID', 'Use --theme=both, light or dark.');
33
+ return { query: { kind: 'file', input, normalized, pathKind, line, symbol, contains: false, locale: null, themes: !values.theme || values.theme === 'both' ? ['light', 'dark'] : [values.theme], rgba: null }, text };
34
+ }
35
+
36
+
37
+ /** Reuse owner's exact file/symbol/region scoping without starting its collector. */
38
+ export function implementationScope(map, query, text, files, { includeStale = false } = {}) {
39
+ const selectors = map.mappings.map(mapping => mapping.implementation).filter(s => s.file === query.normalized && s.symbol);
40
+ const region = text === null ? null : regionAt(symbolRegions(text, query.normalized, selectors), query.line ?? 1);
41
+ const mappingIndices = new Set();
42
+ map.mappings.forEach((mapping, i) => {
43
+ const s = mapping.implementation;
44
+ if (!files.some(file => selectorMatches(s, file))) return;
45
+ if (s.symbol && query.symbol !== null && s.symbol !== query.symbol) return;
46
+ if (s.symbol && query.line !== null) {
47
+ const locator = resolveLocator(text, s);
48
+ if (!(includeStale && locator.stale) && (region?.line !== locator.line || !region?.mapped.includes(s.symbol))) return;
49
+ }
50
+ mappingIndices.add(i);
51
+ });
52
+ return { mappingIndices, region };
53
+ }