@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.
- package/README.md +19 -3
- package/package.json +4 -1
- package/public/annotations.js +816 -0
- package/public/app.js +245 -12
- package/public/assets.js +4 -13
- package/public/frame-identity.js +223 -0
- package/public/icons.js +1 -0
- package/public/index.html +3 -0
- package/public/selection.js +1 -1
- package/public/style.css +72 -2
- package/src/annotations.mjs +238 -0
- package/src/cli-output.mjs +49 -2
- package/src/cli.mjs +83 -12
- package/src/http.mjs +2 -1
- package/src/hub/instances.mjs +1 -1
- package/src/hub/registry.mjs +1 -1
- package/src/hub.mjs +2 -2
- package/src/server.mjs +59 -11
- package/src/service.mjs +1 -1
- package/src/toolkit/arch-git.mjs +19 -0
- package/src/toolkit/arch-overlay.mjs +1 -1
- package/src/toolkit/asset-rules.mjs +42 -3
- package/src/toolkit/build-store.mjs +5 -3
- package/src/toolkit/build-worker.mjs +5 -2
- package/src/toolkit/build.mjs +36 -14
- package/src/toolkit/commands.mjs +85 -22
- package/src/toolkit/config.mjs +8 -6
- package/src/toolkit/diff-inputs.mjs +5 -5
- package/src/toolkit/diff.mjs +18 -11
- package/src/toolkit/document.mjs +6 -6
- package/src/toolkit/frame-document.mjs +6 -0
- package/src/toolkit/frame-facets.mjs +167 -0
- package/src/toolkit/frame-identity.mjs +100 -0
- package/src/toolkit/frame-observation.mjs +147 -0
- package/src/toolkit/frame-primitives.mjs +85 -0
- package/src/toolkit/html.mjs +1 -0
- package/src/toolkit/impact-eligibility.mjs +136 -0
- package/src/toolkit/impact-inputs.mjs +52 -0
- package/src/toolkit/impact-output.mjs +46 -0
- package/src/toolkit/impact-proof.mjs +67 -0
- package/src/toolkit/impact-selection.mjs +96 -0
- package/src/toolkit/impact.mjs +382 -0
- package/src/toolkit/implementation-query.mjs +53 -0
- package/src/toolkit/input-generation.mjs +51 -0
- package/src/toolkit/inspect-encoding.mjs +459 -0
- package/src/toolkit/inspect-observation.mjs +56 -0
- package/src/toolkit/inspect-output.mjs +169 -0
- package/src/toolkit/inspect-styles.mjs +34 -0
- package/src/toolkit/inspect.d.ts +118 -0
- package/src/toolkit/inspect.mjs +125 -0
- package/src/toolkit/owner-observation.mjs +23 -189
- package/src/toolkit/owner-search.mjs +2 -2
- package/src/toolkit/owner.mjs +37 -45
- package/src/toolkit/part-diff.mjs +2 -0
- package/src/toolkit/part-snapshot.mjs +15 -23
- package/src/toolkit/project-index.mjs +100 -22
- package/src/toolkit/project.mjs +52 -6
- package/src/toolkit/results.mjs +2 -2
- package/src/toolkit/runtime.d.ts +7 -5
- package/src/toolkit/runtime.mjs +20 -7
- package/src/toolkit/token-reachability.mjs +71 -0
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { CliError } from '../cli-output.mjs';
|
|
3
|
+
|
|
4
|
+
export const identityVersion = 1;
|
|
5
|
+
const digest = value => createHash('sha256').update(value).digest('hex').slice(0, 24);
|
|
6
|
+
const normalize = value => value.normalize('NFC').replace(/\p{White_Space}+/gu, ' ').trim();
|
|
7
|
+
const namingAttributes = new Set(['id', 'data-part', 'role', 'aria-label', 'aria-labelledby', 'aria-describedby']);
|
|
8
|
+
|
|
9
|
+
export function resourceSlotIdentity(scope,slot,tag,namespace,hash=digest){
|
|
10
|
+
return {id:`e1_${hash(JSON.stringify([scope,['resource-slot',slot]]))}`,identity:{stability:'resource',guard:hash(JSON.stringify(['resource-slot',scope,slot,tag,namespace])),slot}};
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Assign on the complete raw inventory, before selection, folding or theme deltas. */
|
|
14
|
+
export function elementIdentities(nodes, { source, frame }, { hash = digest, metadata = true } = {}) {
|
|
15
|
+
const children=new Map(nodes.map(n=>[n.path,[]])), byPath=new Map(nodes.map(n=>[n.path,n]));
|
|
16
|
+
for(const n of nodes)children.get(n.parentPath)?.push(n);
|
|
17
|
+
const result=new Map(),seen=new Map(),rootScope=JSON.stringify([identityVersion,source,frame]);
|
|
18
|
+
const conflict=message=>{throw new CliError('INSPECT_IDENTITY_CONFLICT',message);};
|
|
19
|
+
function describe(node){
|
|
20
|
+
const attrs=node.attributes??{},owners=node.owners??[],keys=node.keys??[],anchor=attrs['data-adg-id'];
|
|
21
|
+
let defining=owners,ancestor=byPath.get(node.parentPath);
|
|
22
|
+
while(!defining.length&&ancestor){defining=ancestor.owners??[];ancestor=byPath.get(ancestor.parentPath);}
|
|
23
|
+
if(anchor!==undefined&&(typeof anchor!=='string'||!anchor.trim()))conflict('data-adg-id must be a nonempty string.');
|
|
24
|
+
const naming=Object.entries(attrs).filter(([name])=>namingAttributes.has(name)).sort(([a],[b])=>a.localeCompare(b));
|
|
25
|
+
const signature=[node.namespace,node.tag,naming,node.semantic??null,node.password?'':normalize(node.directText??'')];
|
|
26
|
+
const seed=anchor!==undefined?['anchor',anchor,owners,...keys]:keys.length?['key',keys,owners]:[node.neutral?'wrapper':'semantic',signature,defining];
|
|
27
|
+
const boundary=!node.neutral&&(anchor!==undefined||keys.length||owners.length||naming.length||node.semantic?.name);
|
|
28
|
+
return {node,signature,seed,defining,candidate:boundary,boundary:false,fixed:anchor!==undefined||keys.length>0,authored:anchor!==undefined||keys.length>0,strict:keys.length>0||anchor!==undefined&&!owners.length};
|
|
29
|
+
}
|
|
30
|
+
const descriptors=new Map(nodes.map(n=>[n.path,describe(n)]));
|
|
31
|
+
function assign(record,scope,ordinal,count,inherited,resourceSlot){
|
|
32
|
+
const duplicate=count>1, id=`e1_${hash(JSON.stringify([scope,record.seed,...(!record.strict&&duplicate?[ordinal]:[])]))}`;
|
|
33
|
+
if(seen.has(id))conflict(`Element identity conflicts at ${source}#${frame}, paths ${seen.get(id)} and ${record.node.path}; use unique anchors or instance keys.`);
|
|
34
|
+
seen.set(id,record.node.path);
|
|
35
|
+
const positional=inherited||!record.strict&&duplicate;
|
|
36
|
+
const identity=metadata?{stability:resourceSlot!==undefined?'resource':positional?'positional':record.authored?'authored':'semantic',guard:hash(JSON.stringify([record.node.namespace,record.node.tag,record.signature,scope,record.defining]))}:undefined;
|
|
37
|
+
if(identity){
|
|
38
|
+
if(resourceSlot!==undefined)identity.guard=resourceSlotIdentity(scope,resourceSlot,record.node.tag,record.node.namespace,hash).identity.guard;
|
|
39
|
+
if(record.node.attributes?.['data-adg-id']!==undefined)identity.anchor=record.node.attributes['data-adg-id'];
|
|
40
|
+
if(record.node.keys?.length)identity.key=record.node.keys.at(-1).key;
|
|
41
|
+
if(resourceSlot!==undefined)identity.slot=resourceSlot;
|
|
42
|
+
else if(!record.strict&&duplicate)identity.duplicate={group:hash(JSON.stringify([scope,record.seed])),ordinal,count};
|
|
43
|
+
}
|
|
44
|
+
const value={path:record.node.path,id,...(identity?{identity}:{})};result.set(record.node.path,value);
|
|
45
|
+
return {id,positional};
|
|
46
|
+
}
|
|
47
|
+
function resource(root,scope){
|
|
48
|
+
let slot=0;
|
|
49
|
+
function visit(node){const r=descriptors.get(node.path),local=slot++;
|
|
50
|
+
// Slots are local to this artwork instance, not ranked among frame elements.
|
|
51
|
+
const original=r.seed;r.seed=['resource-slot',local];assign(r,scope,0,1,false,local);r.seed=original;
|
|
52
|
+
for(const child of children.get(node.path))visit(child);
|
|
53
|
+
}
|
|
54
|
+
for(const child of children.get(root.path))visit(child);
|
|
55
|
+
}
|
|
56
|
+
function scope(roots,address,inherited=false){
|
|
57
|
+
let pool=[];
|
|
58
|
+
function gather(node){const r=descriptors.get(node.path);pool.push(r);if(!r.boundary&&!node.resource)for(const child of children.get(node.path))gather(child);}
|
|
59
|
+
// Unique semantic candidates open scopes. Repeated unkeyed owner roots do not
|
|
60
|
+
// impose their positional ordinal on every distinguishable descendant.
|
|
61
|
+
for(let changed=true;changed;){
|
|
62
|
+
changed=false;pool=[];roots.forEach(gather);
|
|
63
|
+
const candidates=new Map();
|
|
64
|
+
for(const r of pool)if(r.candidate){const key=JSON.stringify(r.seed);candidates.set(key,(candidates.get(key)??0)+1);}
|
|
65
|
+
for(const r of pool)if(r.candidate&&!r.boundary&&(r.fixed||candidates.get(JSON.stringify(r.seed))===1)){r.boundary=true;changed=true;}
|
|
66
|
+
}
|
|
67
|
+
const groups=new Map();
|
|
68
|
+
for(const r of pool){
|
|
69
|
+
// JSX keys belong to sibling lists, even where an unnamed parent is not an identity scope.
|
|
70
|
+
let parent=byPath.get(r.node.parentPath);while(parent?.neutral)parent=byPath.get(parent.parentPath);
|
|
71
|
+
const key=JSON.stringify([r.seed,...(r.node.keys?.length?[parent?.path??null]:[])]);
|
|
72
|
+
const peers=groups.get(key)??[];peers.push(r);groups.set(key,peers);r.peers=peers;
|
|
73
|
+
}
|
|
74
|
+
// Keyed children need their non-neutral parent's address before resolution.
|
|
75
|
+
const resolved=new Map();
|
|
76
|
+
function resolve(r){if(resolved.has(r.node.path))return resolved.get(r.node.path);
|
|
77
|
+
let local=address,localPositional=inherited;
|
|
78
|
+
if(r.node.attributes?.['data-adg-id']!==undefined&&!r.node.owners?.length){
|
|
79
|
+
let owner=byPath.get(r.node.parentPath);while(owner&&!owner.owners?.length)owner=byPath.get(owner.parentPath);
|
|
80
|
+
const ownerRecord=pool.find(p=>p.node===owner),value=ownerRecord?resolve(ownerRecord):null;
|
|
81
|
+
if(value){local=value.id;localPositional||=value.positional;}
|
|
82
|
+
}
|
|
83
|
+
if(r.node.keys?.length){let parent=byPath.get(r.node.parentPath);while(parent?.neutral)parent=byPath.get(parent.parentPath);
|
|
84
|
+
const parentRecord=pool.find(p=>p.node===parent),parentValue=parentRecord?resolve(parentRecord):null;
|
|
85
|
+
local=parentValue?.id??result.get(parent?.path)?.id??address;localPositional||=parentValue?.positional??false;}
|
|
86
|
+
const value=assign(r,local,r.peers.indexOf(r),r.peers.length,localPositional);resolved.set(r.node.path,value);return value;
|
|
87
|
+
}
|
|
88
|
+
for(const r of pool)resolve(r);
|
|
89
|
+
for(const r of pool){const value=resolved.get(r.node.path);
|
|
90
|
+
if(r.node.resource)resource(r.node,value.id);
|
|
91
|
+
else if(r.boundary)scope(children.get(r.node.path),value.id,value.positional);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
for(const root of nodes.filter(n=>!byPath.has(n.parentPath))){
|
|
95
|
+
const record=descriptors.get(root.path),seed=record.seed;record.seed=['frame-root'];
|
|
96
|
+
const value=assign(record,rootScope,0,1,false);record.seed=seed;
|
|
97
|
+
if(root.resource)resource(root,value.id);else scope(children.get(root.path),value.id);
|
|
98
|
+
}
|
|
99
|
+
return nodes.map(node=>result.get(node.path));
|
|
100
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { installFramePrimitives } from './frame-primitives.mjs';
|
|
2
|
+
export { installFramePrimitives };
|
|
3
|
+
|
|
4
|
+
/** Browser-side projection: provenance roots and authored references, no raster work. */
|
|
5
|
+
export function collectOwnerObservation({ tokens, theme, rich = false, properties = [], serialized = false }) {
|
|
6
|
+
const frame = document.querySelector('[data-adg-frame]'), root = frame?.firstElementChild;
|
|
7
|
+
if (!root || frame.children.length !== 1) throw Error('Ownership observation requires exactly one frame root.');
|
|
8
|
+
const { inventory, relativeBox, variables, selectors, reads, identityNode, styleRules, textRects } = globalThis.__adgFramePrimitives;
|
|
9
|
+
const origin = frame.getBoundingClientRect(), {elements,paths,neutralCandidates}=inventory(root), identities=[];
|
|
10
|
+
const tokenNames = new Set(tokens.map(token => token.name));
|
|
11
|
+
const definitions = new Map(tokens.map(token => [token.name, token.values.find(value => value.theme === theme).declaration]));
|
|
12
|
+
const box = r => relativeBox(r,origin,true), {style,rect}=reads(), declarations=new Map();
|
|
13
|
+
function clipped(node, r = rect(node), includeSelf = false) {
|
|
14
|
+
let left = Math.max(r.left, origin.left), right = Math.min(r.right, origin.right), top = Math.max(r.top, origin.top), bottom = Math.min(r.bottom, origin.bottom);
|
|
15
|
+
for (let p = node; p; p = p.parentElement) {
|
|
16
|
+
const s = style(p); if (s.display === 'none' || p === node && s.visibility !== 'visible' || Number(s.opacity) === 0) return null;
|
|
17
|
+
if ((p !== node || includeSelf) && s.display !== 'inline') {
|
|
18
|
+
const r = rect(p);
|
|
19
|
+
if (/(hidden|clip|scroll|auto)/.test(s.overflowX)) { left = Math.max(left, r.left); right = Math.min(right, r.right); }
|
|
20
|
+
if (/(hidden|clip|scroll|auto)/.test(s.overflowY)) { top = Math.max(top, r.top); bottom = Math.min(bottom, r.bottom); }
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return right > left && bottom > top ? box({ left, right, top, bottom }) : null;
|
|
24
|
+
}
|
|
25
|
+
const rules=styleRules({referencesOnly:true,includeCustom:rich,resolveNesting:true});
|
|
26
|
+
const probe = document.createElement('style'); document.head.append(probe);
|
|
27
|
+
function containerActive(node, conditions) {
|
|
28
|
+
if (!conditions.length) return true;
|
|
29
|
+
const previous = node.getAttribute('data-adg-owner-probe');
|
|
30
|
+
try {
|
|
31
|
+
node.setAttribute('data-adg-owner-probe', 'active');
|
|
32
|
+
probe.textContent = conditions.reduceRight((inner, condition) => `${condition}{${inner}}`, '[data-adg-owner-probe="active"]{--adg-owner-condition:1!important}');
|
|
33
|
+
return getComputedStyle(node).getPropertyValue('--adg-owner-condition').trim() === '1';
|
|
34
|
+
} finally { probe.textContent = ''; if (previous === null) node.removeAttribute('data-adg-owner-probe'); else node.setAttribute('data-adg-owner-probe', previous); }
|
|
35
|
+
}
|
|
36
|
+
function declarationsFor(node, pseudo = '') {
|
|
37
|
+
const key = pseudo ? `${paths.get(node)}${pseudo}` : node;
|
|
38
|
+
if (declarations.has(key)) return declarations.get(key);
|
|
39
|
+
const result = [];
|
|
40
|
+
for (const rule of rules) {
|
|
41
|
+
const matched = rule.selectors.some(selector => {
|
|
42
|
+
const suffix = /::(before|after)\b/.exec(selector);
|
|
43
|
+
if ((suffix ? `::${suffix[1]}` : '') !== pseudo) return false;
|
|
44
|
+
try { return node.matches(selector.replace(/::(?:before|after)\b/g, '')); } catch { return false; }
|
|
45
|
+
});
|
|
46
|
+
if (matched && containerActive(node, rule.containers)) for (const property of rule.style) result.push({ property, declaration: rule.style.getPropertyValue(property) });
|
|
47
|
+
}
|
|
48
|
+
if (!pseudo) for (const property of node.style) result.push({ property, declaration: node.style.getPropertyValue(property) });
|
|
49
|
+
declarations.set(key, result); return result;
|
|
50
|
+
}
|
|
51
|
+
const details = rich ? globalThis.__adgInspectFacets.create({elements,paths,style,rect,origin,declarationsFor,tokens,theme,properties}) : null;
|
|
52
|
+
const inherited = /^(?:color|font(?:-.+)?|line-height|letter-spacing|word-spacing|text-align|text-indent|text-transform|visibility|cursor|fill|stroke(?:-.+)?)$/;
|
|
53
|
+
const nodes = [], references = [], paints = [], texts = [], groups = [];
|
|
54
|
+
const normalize = value => value.normalize('NFC').replace(/\p{White_Space}+/gu, ' ').trim();
|
|
55
|
+
function paint(style, property, node, bounds, pseudo = '') {
|
|
56
|
+
const computed = style.getPropertyValue(property);
|
|
57
|
+
if (!computed || computed === 'none') return;
|
|
58
|
+
const values = property.includes('shadow') || property === 'background-image'
|
|
59
|
+
? computed.match(/(?:rgba?|hsla?|oklch|oklab|lab|lch|color(?:-mix)?)\((?:[^()]|\([^()]*\))*\)|#[\da-f]{3,8}\b/gi) ?? [] : [computed];
|
|
60
|
+
for (const value of values) {
|
|
61
|
+
const rgba = globalThis.__adgOwnerColor(value);
|
|
62
|
+
if (rgba?.[3]) paints.push({ path: paths.get(node) + pseudo, ownerPath: paths.get(node), box: bounds, property, computed: value, rgba });
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function fragment(node) {
|
|
66
|
+
const parent = node.parentElement;
|
|
67
|
+
if (!parent || parent.closest('script,style,input,textarea,select')) return null;
|
|
68
|
+
const {range,rects}=textRects(node); if (!rects.length) return null;
|
|
69
|
+
const extent = { left: Math.min(...rects.map(r => r.left)), right: Math.max(...rects.map(r => r.right)), top: Math.min(...rects.map(r => r.top)), bottom: Math.max(...rects.map(r => r.bottom)) };
|
|
70
|
+
const bounds = clipped(parent, extent, true); if (!bounds) return null;
|
|
71
|
+
const clipRect = r => {
|
|
72
|
+
const left = Math.max(r.left, origin.left + bounds.x), right = Math.min(r.right, origin.left + bounds.x + bounds.width), top = Math.max(r.top, origin.top + bounds.y), bottom = Math.min(r.bottom, origin.top + bounds.y + bounds.height);
|
|
73
|
+
return right > left && bottom > top ? box({ left, right, top, bottom }) : null;
|
|
74
|
+
};
|
|
75
|
+
const boxes = rects.map(clipRect).filter(Boolean);
|
|
76
|
+
if (!boxes.length) return null;
|
|
77
|
+
let raw = node.data;
|
|
78
|
+
if (rects.some(r => r.left < origin.left + bounds.x - .5 || r.right > origin.left + bounds.x + bounds.width + .5 || r.top < origin.top + bounds.y - .5 || r.bottom > origin.top + bounds.y + bounds.height + .5)) {
|
|
79
|
+
raw = '';
|
|
80
|
+
for (let i = 0; i < node.length; i++) { range.setStart(node, i); range.setEnd(node, i + 1); if ([...range.getClientRects()].some(r => clipRect(r))) raw += node.data[i]; }
|
|
81
|
+
}
|
|
82
|
+
const transform = style(parent).textTransform;
|
|
83
|
+
const rendered = transform === 'uppercase' ? raw.toLocaleUpperCase(document.documentElement.lang || 'en') : transform === 'lowercase' ? raw.toLocaleLowerCase(document.documentElement.lang || 'en') : transform === 'capitalize' ? raw.replace(/\b\p{L}/gu, value => value.toLocaleUpperCase(document.documentElement.lang || 'en')) : raw;
|
|
84
|
+
return { parent, raw, rendered, elementPath: `${paths.get(parent)}/text-${[...parent.childNodes].indexOf(node)}`, text: raw, boxes };
|
|
85
|
+
}
|
|
86
|
+
function textGroup(node) {
|
|
87
|
+
for (let p = node; p && p !== frame; p = p.parentElement) if (p.matches('button,a,label,input,textarea,select,text') || !['inline','contents'].includes(style(p).display)) return p;
|
|
88
|
+
return root;
|
|
89
|
+
}
|
|
90
|
+
try {
|
|
91
|
+
for (const node of elements) {
|
|
92
|
+
details?.node(node);
|
|
93
|
+
const bounds = clipped(node);
|
|
94
|
+
const own = JSON.parse(node.getAttribute('data-adg-owners') ?? '[]');
|
|
95
|
+
identities.push(identityNode(node,paths.get(node),paths.get(node.parentElement)??null,own,style(node),neutralCandidates.has(node)));
|
|
96
|
+
nodes.push({ path: paths.get(node), parentPath: paths.get(node.parentElement) ?? null, box: bounds, owners: own });
|
|
97
|
+
if (!bounds) continue;
|
|
98
|
+
const customs = new Map();
|
|
99
|
+
for (let p = node; p; p = p.parentElement) for (const declaration of declarationsFor(p)) if (declaration.property.startsWith('--') && !customs.has(declaration.property)) customs.set(declaration.property, declaration.declaration);
|
|
100
|
+
function expand(name, property, declaration, via = [], fallback = false) {
|
|
101
|
+
if (via.includes(name)) return;
|
|
102
|
+
if (tokenNames.has(name)) references.push({ path: paths.get(node), token: name, property, declaration, via,
|
|
103
|
+
matchKind: fallback ? 'token_fallback_reference' : via.length ? 'token_alias_reference' : 'token_reference' });
|
|
104
|
+
const expression = tokenNames.has(name) ? definitions.get(name) : customs.get(name);
|
|
105
|
+
if (expression) for (const variable of variables(expression)) expand(variable.name, property, declaration, [...via, name], fallback || variable.fallback);
|
|
106
|
+
}
|
|
107
|
+
for (const pseudo of ['', '::before', '::after']) {
|
|
108
|
+
const s = pseudo ? getComputedStyle(node, pseudo) : style(node);
|
|
109
|
+
if (pseudo && (['none', 'normal'].includes(s.content) || s.display === 'none' || s.visibility !== 'visible' || Number(s.opacity) === 0)) continue;
|
|
110
|
+
const active = [...declarationsFor(node, pseudo)];
|
|
111
|
+
if (!pseudo && (own.length || node === root)) for (let p = node.parentElement; p; p = p.parentElement) active.push(...declarationsFor(p).filter(d => inherited.test(d.property)));
|
|
112
|
+
for (const { property, declaration } of active) if (!property.startsWith('--')) for (const variable of variables(declaration)) expand(variable.name, property, declaration, [], variable.fallback);
|
|
113
|
+
const hasText = pseudo ? !['""', "''", 'none', 'normal'].includes(s.content) : node.matches('input,textarea,select') ? !!String(node.value || node.placeholder || [...(node.selectedOptions ?? [])].map(option => option.text).join('')).trim() : [...node.childNodes].some(n => n.nodeType === 3 && n.textContent.trim() && fragment(n));
|
|
114
|
+
if (hasText && !(node instanceof SVGElement)) paint(!pseudo && node.matches('input,textarea') && !node.value && node.placeholder ? getComputedStyle(node, '::placeholder') : s, 'color', node, bounds, pseudo);
|
|
115
|
+
paint(s, 'background-color', node, bounds, pseudo);
|
|
116
|
+
for (const side of ['top','right','bottom','left']) if (parseFloat(s.getPropertyValue(`border-${side}-width`)) > 0 && s.getPropertyValue(`border-${side}-style`) !== 'none') paint(s, `border-${side}-color`, node, bounds, pseudo);
|
|
117
|
+
if (parseFloat(s.outlineWidth) > 0 && s.outlineStyle !== 'none') paint(s, 'outline-color', node, bounds, pseudo);
|
|
118
|
+
if (node instanceof SVGElement && /^(path|rect|circle|ellipse|polygon|polyline|line|text|tspan)$/.test(node.localName) && (!/^(text|tspan)$/.test(node.localName) || hasText)) { paint(s, 'fill', node, bounds, pseudo); if (parseFloat(s.strokeWidth) > 0) paint(s, 'stroke', node, bounds, pseudo); }
|
|
119
|
+
for (const property of ['box-shadow','text-shadow','background-image']) if (property !== 'text-shadow' || hasText) paint(s, property, node, bounds, pseudo);
|
|
120
|
+
if (pseudo && !/\b(?:url|attr|counter)\(/.test(s.content)) {
|
|
121
|
+
const raw = [...s.content.matchAll(/"((?:\\.|[^"\\])*)"|'((?:\\.|[^'\\])*)'/g)].map(match => (match[1] ?? match[2]).replace(/\\([\da-f]{1,6})\s?|\\(.)/gi, (_, hex, char) => hex ? String.fromCodePoint(parseInt(hex, 16) || 0xfffd) : char)).join('');
|
|
122
|
+
if (normalize(raw)) texts.push({ path: paths.get(node) + pseudo, ownerPath: paths.get(node), raw, normalized: normalize(raw), fragments: [{ elementPath: paths.get(node) + pseudo, text: raw, boxes: [bounds] }] });
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (node.matches('input,textarea,select') && !(node.matches('input[type=password]') && node.value)) {
|
|
126
|
+
const raw = node.matches('select') ? [...node.selectedOptions].map(option => option.text).join(' ') : node.value || node.placeholder || '';
|
|
127
|
+
if (normalize(raw)) texts.push({ path: `${paths.get(node)}/value`, ownerPath: paths.get(node), raw, normalized: normalize(raw), fragments: [{ elementPath: `${paths.get(node)}/value`, text: raw, boxes: [bounds] }] });
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
|
131
|
+
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
|
132
|
+
const f = fragment(node); if (!f) continue;
|
|
133
|
+
const group = textGroup(f.parent);
|
|
134
|
+
if (groups.at(-1)?.[0] !== group) groups.push([group, []]);
|
|
135
|
+
groups.at(-1)[1].push(f);
|
|
136
|
+
}
|
|
137
|
+
for (const [group, fragments] of groups) {
|
|
138
|
+
const raw = fragments.map(f => f.raw).join(''), normalized = normalize(fragments.map(f => f.rendered).join(''));
|
|
139
|
+
if (!normalized) continue;
|
|
140
|
+
let common = fragments[0].parent;
|
|
141
|
+
while (common && !fragments.every(f => common.contains(f.parent))) common = common.parentElement;
|
|
142
|
+
texts.push({ path: `${paths.get(group)}/run-${texts.length}`, ownerPath: paths.get(common ?? group), raw, normalized, fragments: fragments.map(({ elementPath, text, boxes }) => ({ elementPath, text, boxes })) });
|
|
143
|
+
}
|
|
144
|
+
const result={ ...(rich?{rich:details.finish()}:{}), identities, nodes, references: [...new Map(references.map(ref => [JSON.stringify(ref), ref])).values()], texts, paints };
|
|
145
|
+
return serialized?JSON.stringify(result):result;
|
|
146
|
+
} finally { probe.remove(); }
|
|
147
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/** Installed once per page; browser collectors share these exact, synchronous primitives. */
|
|
2
|
+
export function installFramePrimitives() {
|
|
3
|
+
if (globalThis.__adgFramePrimitives) return;
|
|
4
|
+
const normalizeText = text => text.normalize('NFC').replace(/\p{White_Space}+/gu, ' ').trim();
|
|
5
|
+
function inventory(root) {
|
|
6
|
+
const elements=[root,...root.querySelectorAll('*')];
|
|
7
|
+
const neutralCandidates=new Set(elements);
|
|
8
|
+
for(const keyed of root.querySelectorAll('[data-adg-keys]'))for(let parent=keyed.parentElement;parent&&parent!==root;parent=parent.parentElement)neutralCandidates.add(parent);
|
|
9
|
+
return {elements, paths:new Map(elements.map((node,i)=>[node,String(i)])),neutralCandidates};
|
|
10
|
+
}
|
|
11
|
+
function relativeBox(rect, origin, clamp=false) {
|
|
12
|
+
const clean=n=>n===0?0:n;
|
|
13
|
+
return {x:clean(rect.left-origin.left),y:clean(rect.top-origin.top),width:clamp?Math.max(0,rect.right-rect.left):rect.width,height:clamp?Math.max(0,rect.bottom-rect.top):rect.height};
|
|
14
|
+
}
|
|
15
|
+
function variables(expression, fallback=false) {
|
|
16
|
+
const result=[]; const regex=/var\(\s*(--[\w-]+)/g;let match;
|
|
17
|
+
while((match=regex.exec(expression))){
|
|
18
|
+
let depth=1,comma=-1,end=regex.lastIndex;
|
|
19
|
+
for(;end<expression.length&&depth;end++){
|
|
20
|
+
if(expression[end]==='(')depth++;else if(expression[end]===')')depth--;
|
|
21
|
+
else if(expression[end]===','&&depth===1&&comma<0)comma=end;
|
|
22
|
+
}
|
|
23
|
+
result.push({name:match[1],fallback});
|
|
24
|
+
if(comma>=0)result.push(...variables(expression.slice(comma+1,end-1),true));
|
|
25
|
+
regex.lastIndex=end;
|
|
26
|
+
}return result;
|
|
27
|
+
}
|
|
28
|
+
function selectors(text) {
|
|
29
|
+
const out=[];let start=0,depth=0,quote='';
|
|
30
|
+
for(let i=0;i<text.length;i++){
|
|
31
|
+
const char=text[i];
|
|
32
|
+
if(quote){if(char==='\\')i++;else if(char===quote)quote='';}
|
|
33
|
+
else if(char==='"'||char==="'")quote=char;
|
|
34
|
+
else if(char==='('||char==='[')depth++;
|
|
35
|
+
else if(char===')'||char===']')depth--;
|
|
36
|
+
else if(char===','&&!depth){out.push(text.slice(start,i));start=i+1;}
|
|
37
|
+
}return [...out,text.slice(start)].map(v=>v.trim());
|
|
38
|
+
}
|
|
39
|
+
function reads(){
|
|
40
|
+
const styles=new Map(),rects=new Map();
|
|
41
|
+
return {style:node=>{if(!styles.has(node))styles.set(node,getComputedStyle(node));return styles.get(node);},
|
|
42
|
+
rect:node=>{if(!rects.has(node))rects.set(node,node.getBoundingClientRect());return rects.get(node);}};
|
|
43
|
+
}
|
|
44
|
+
function styleRules({referencesOnly=false,includeCustom=false,resolveNesting=false}={}) {
|
|
45
|
+
const rules=[];
|
|
46
|
+
function visitRules(list, containers = [], parents = []) {
|
|
47
|
+
for (const rule of list) {
|
|
48
|
+
if (rule instanceof CSSMediaRule && !matchMedia(rule.conditionText).matches || rule instanceof CSSSupportsRule && !CSS.supports(rule.conditionText)) continue;
|
|
49
|
+
const nested = typeof CSSContainerRule !== 'undefined' && rule instanceof CSSContainerRule ? [...containers, rule.cssText.slice(0, rule.cssText.indexOf('{'))] : containers;
|
|
50
|
+
let resolved = parents;
|
|
51
|
+
if (rule.selectorText && rule.style) {
|
|
52
|
+
const own = selectors(rule.selectorText);
|
|
53
|
+
resolved = resolveNesting && parents.length ? parents.flatMap(parent => own.map(selector => selector.includes('&') ? selector.replaceAll('&', `:is(${parent})`) : `${parent} ${selector}`)) : own;
|
|
54
|
+
if (!referencesOnly || [...rule.style].some(property => rule.style.getPropertyValue(property).includes('var(')||includeCustom&&property.startsWith('--'))) rules.push({ rule, selectors: resolved, style: rule.style, containers });
|
|
55
|
+
}
|
|
56
|
+
if (rule.cssRules) visitRules(rule.cssRules, nested, resolved);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
for(const sheet of document.styleSheets)visitRules(sheet.cssRules);return rules;
|
|
60
|
+
}
|
|
61
|
+
function textRects(node) {const range=document.createRange();range.selectNodeContents(node);return {range,rects:[...range.getClientRects()]};}
|
|
62
|
+
function identityNode(node,path,parentPath,owners,style,checkNeutral=true){
|
|
63
|
+
const attributes={};
|
|
64
|
+
for(const name of ['id','data-part','data-adg-id','role','aria-label','aria-labelledby','aria-describedby'])if(node.hasAttribute(name))attributes[name]=node.getAttribute(name);
|
|
65
|
+
const password=node.matches('input[type=password]');
|
|
66
|
+
const neutral = checkNeutral && !owners.length && !node.hasAttribute('data-adg-id') && !node.hasAttribute('data-adg-keys') &&
|
|
67
|
+
!Object.keys(attributes).length && /^(div|span)$/.test(node.localName) && (node.children.length===1 || style?.display==='contents') &&
|
|
68
|
+
![...node.childNodes].some(n=>n.nodeType===3 && n.data.trim()) && style &&
|
|
69
|
+
['block','inline','contents'].includes(style.display) && style.position==='static' &&
|
|
70
|
+
style.transform==='none' && style.overflowX==='visible' && style.overflowY==='visible' &&
|
|
71
|
+
style.opacity==='1' && style.backgroundColor==='rgba(0, 0, 0, 0)' && style.boxShadow==='none' &&
|
|
72
|
+
['Top','Right','Bottom','Left'].every(side=>parseFloat(style[`margin${side}`])===0 && parseFloat(style[`padding${side}`])===0 && parseFloat(style[`border${side}Width`])===0);
|
|
73
|
+
const native={button:'button',a:node.hasAttribute('href')?'link':null,input:node.type==='checkbox'?'checkbox':node.type==='radio'?'radio':node.type==='button'||node.type==='submit'?'button':'textbox',select:'combobox',textarea:'textbox',h1:'heading',h2:'heading',h3:'heading',h4:'heading',h5:'heading',h6:'heading',img:'img'};
|
|
74
|
+
const role=node.getAttribute('role')??native[node.localName];
|
|
75
|
+
const labelled=node.getAttribute('aria-labelledby')?.split(/\s+/).map(id=>node.ownerDocument.getElementById(id)?.textContent??'').join(' ');
|
|
76
|
+
// Theme-independent naming evidence; AX exposure/hidden state never changes an address.
|
|
77
|
+
const name=normalizeText(labelled||node.getAttribute('aria-label')||node.getAttribute('alt')||(role==='textbox'||role==='combobox'?Array.from(node.labels??[]).map(l=>l.textContent).join(' '):role?node.textContent:'')||'');
|
|
78
|
+
const resource=node.localName==='svg'&&(node.hasAttribute('data-adg-icon')||node.getAttribute('aria-hidden')==='true'||!node.querySelector('text,foreignObject')&&!node.hasAttribute('role'));
|
|
79
|
+
return {path,parentPath,tag:node.localName,namespace:node.namespaceURI,attributes,owners,neutral,resource,
|
|
80
|
+
...(role&&name?{semantic:{role,name}}:{}),
|
|
81
|
+
keys:JSON.parse(node.getAttribute('data-adg-keys')??'[]'),password,
|
|
82
|
+
directText:password?'':[...node.childNodes].filter(n=>n.nodeType===3).map(n=>n.data).join('')};
|
|
83
|
+
}
|
|
84
|
+
globalThis.__adgFramePrimitives={inventory,relativeBox,variables,selectors,reads,normalizeText,identityNode,styleRules,textRects};
|
|
85
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const escape = value => String(value).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { parse } from 'parse5';
|
|
2
|
+
import { tokenize, tokenTypes as T } from 'css-tree';
|
|
3
|
+
import { decodeCssEscapes } from './token-reachability.mjs';
|
|
4
|
+
|
|
5
|
+
const svg = 'http://www.w3.org/2000/svg';
|
|
6
|
+
const scriptTags = new Set(['script', 'iframe', 'object', 'embed']);
|
|
7
|
+
const urlAttributes = new Set(['href', 'src', 'action', 'formaction', 'data', 'poster', 'background', 'codebase', 'cite', 'longdesc', 'profile', 'usemap', 'manifest']);
|
|
8
|
+
const svgPaintAttributes = new Set(['fill', 'stroke', 'filter', 'clip-path', 'mask', 'marker', 'marker-start', 'marker-mid', 'marker-end', 'cursor', 'color-profile']);
|
|
9
|
+
const javascript = value => /^javascript:/i.test(value.replace(/[\u0000-\u0020]/g, ''));
|
|
10
|
+
|
|
11
|
+
// WHATWG srcset URLs consume non-whitespace bytes (including data-URL commas).
|
|
12
|
+
function srcsetUrls(value) {
|
|
13
|
+
const urls = [];
|
|
14
|
+
let i = 0;
|
|
15
|
+
while (i < value.length) {
|
|
16
|
+
while (/[\s,]/.test(value[i] ?? '') && i < value.length) i++;
|
|
17
|
+
const start = i;
|
|
18
|
+
while (i < value.length && !/\s/.test(value[i])) i++;
|
|
19
|
+
const url = value.slice(start, i);
|
|
20
|
+
if (url) urls.push(url.replace(/,+$/, ''));
|
|
21
|
+
if (url.endsWith(',')) continue;
|
|
22
|
+
let depth = 0;
|
|
23
|
+
while (i < value.length) {
|
|
24
|
+
const char = value[i++];
|
|
25
|
+
if (char === '(') depth++;
|
|
26
|
+
if (char === ')') depth--;
|
|
27
|
+
if (char === ',' && !depth) break;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return urls;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Two parsed-document checks only; no browser, rendering, or environment certificate. */
|
|
34
|
+
export function createEligibilityChecker() {
|
|
35
|
+
const resources = new Map(), stylesheets = new Map(), documents = new Map();
|
|
36
|
+
function cssReasons(css) {
|
|
37
|
+
if (stylesheets.has(css)) return stylesheets.get(css);
|
|
38
|
+
const reasons = new Set(), stack = [];
|
|
39
|
+
let importing = false;
|
|
40
|
+
try {
|
|
41
|
+
tokenize(css, (type, start, end) => {
|
|
42
|
+
const raw = css.slice(start, end);
|
|
43
|
+
if (type === T.BadString || type === T.BadUrl) reasons.add('unsupported_css');
|
|
44
|
+
if (type === T.AtKeyword) importing = decodeCssEscapes(raw.slice(1)).toLowerCase() === 'import';
|
|
45
|
+
if (type === T.Url) {
|
|
46
|
+
for (const reason of urlReasons(decodeCssEscapes(raw.slice(raw.indexOf('(') + 1, raw.endsWith(')') ? -1 : undefined).trim()))) reasons.add(reason);
|
|
47
|
+
importing = false;
|
|
48
|
+
} else if (type === T.String) {
|
|
49
|
+
if (raw.length < 2 || raw.at(-1) !== raw[0]) reasons.add('unsupported_css');
|
|
50
|
+
if (importing || ['url', 'image', 'image-set', '-webkit-image-set'].includes(stack.at(-1)?.name)) {
|
|
51
|
+
for (const reason of urlReasons(decodeCssEscapes(raw.slice(1, -1)))) reasons.add(reason);
|
|
52
|
+
}
|
|
53
|
+
importing = false;
|
|
54
|
+
} else if (type === T.Function) {
|
|
55
|
+
const name = decodeCssEscapes(raw.slice(0, -1)).toLowerCase();
|
|
56
|
+
if (['var', 'attr'].includes(name) && stack.some(context => ['image', 'image-set', '-webkit-image-set'].includes(context?.name))) reasons.add('unsupported_css');
|
|
57
|
+
stack.push({ name, start: end });
|
|
58
|
+
}
|
|
59
|
+
else if (type === T.LeftParenthesis) stack.push(null);
|
|
60
|
+
else if (type === T.RightParenthesis) {
|
|
61
|
+
const context = stack.pop();
|
|
62
|
+
if (context?.name === 'url') {
|
|
63
|
+
let value = css.slice(context.start, start).trim();
|
|
64
|
+
if (/^['"]/.test(value)) value = value.slice(1, -1);
|
|
65
|
+
for (const reason of urlReasons(decodeCssEscapes(value))) reasons.add(reason);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
else if (type === T.Semicolon) importing = false;
|
|
69
|
+
});
|
|
70
|
+
if (stack.length) reasons.add('unsupported_css');
|
|
71
|
+
} catch { reasons.add('unsupported_css'); }
|
|
72
|
+
const result = [...reasons].sort(); stylesheets.set(css, result); return result;
|
|
73
|
+
}
|
|
74
|
+
function urlReasons(value) {
|
|
75
|
+
value = value.trim();
|
|
76
|
+
if (javascript(value)) return ['dynamic_document'];
|
|
77
|
+
if (value.startsWith('#')) return [];
|
|
78
|
+
if (!/^data:/i.test(value)) return ['external_resource'];
|
|
79
|
+
if (resources.has(value)) return resources.get(value);
|
|
80
|
+
resources.set(value, []);
|
|
81
|
+
let result = [];
|
|
82
|
+
try {
|
|
83
|
+
const comma = value.indexOf(',');
|
|
84
|
+
if (comma < 0) return ['incomplete_identity'];
|
|
85
|
+
const header = value.slice(5, comma), encoded = decodeURIComponent(value.slice(comma + 1));
|
|
86
|
+
const text = /;base64(?:;|$)/i.test(header) ? Buffer.from(encoded, 'base64').toString('utf8') : encoded;
|
|
87
|
+
if (/^(?:image\/svg\+xml|text\/html|application\/xhtml\+xml)(?:;|$)/i.test(header) || /^\s*<(?:svg|html|!doctype)/i.test(text)) result = htmlReasons(text);
|
|
88
|
+
else if (/^text\/css(?:;|$)/i.test(header)) result = cssReasons(text);
|
|
89
|
+
} catch { result = ['incomplete_identity']; }
|
|
90
|
+
resources.set(value, result); return result;
|
|
91
|
+
}
|
|
92
|
+
function htmlReasons(document) {
|
|
93
|
+
if (documents.has(document)) return documents.get(document);
|
|
94
|
+
const reasons = new Set();
|
|
95
|
+
try {
|
|
96
|
+
const tree = parse(document);
|
|
97
|
+
function visit(node) {
|
|
98
|
+
const tag = node.tagName?.toLowerCase();
|
|
99
|
+
if (scriptTags.has(tag)) reasons.add('dynamic_document');
|
|
100
|
+
const attrs = Object.fromEntries((node.attrs ?? []).map(attr => [attr.name.toLowerCase(), attr.value]));
|
|
101
|
+
for (const attr of node.attrs ?? []) {
|
|
102
|
+
const name = attr.name.toLowerCase(), value = attr.value;
|
|
103
|
+
if (name.startsWith('on') || urlAttributes.has(name) && javascript(value)) reasons.add('dynamic_document');
|
|
104
|
+
if (name === 'style') for (const reason of cssReasons(value)) reasons.add(reason);
|
|
105
|
+
if (node.namespaceURI === svg && svgPaintAttributes.has(name)) for (const reason of cssReasons(value)) reasons.add(reason);
|
|
106
|
+
if (['src', 'poster', 'background'].includes(name) || name === 'href' && (node.namespaceURI === svg || ['link', 'base'].includes(tag))) {
|
|
107
|
+
for (const reason of urlReasons(value)) reasons.add(reason);
|
|
108
|
+
}
|
|
109
|
+
if (['srcset', 'imagesrcset'].includes(name)) for (const url of srcsetUrls(value)) for (const reason of urlReasons(url)) reasons.add(reason);
|
|
110
|
+
}
|
|
111
|
+
if (tag === 'meta' && attrs['http-equiv']?.toLowerCase() === 'refresh') {
|
|
112
|
+
const url = /(?:^|;)\s*url\s*=\s*['"]?([^'"]+)/i.exec(attrs.content ?? '')?.[1];
|
|
113
|
+
for (const reason of urlReasons(url ?? '')) reasons.add(reason);
|
|
114
|
+
}
|
|
115
|
+
// SMIL is allowed, but animated resource URLs still have to be closed.
|
|
116
|
+
if (['animate', 'set'].includes(tag)) {
|
|
117
|
+
for (const name of ['from', 'to', 'by', 'values']) if (attrs[name]) {
|
|
118
|
+
if (['href', 'xlink:href', 'src'].includes(attrs.attributename?.toLowerCase())) {
|
|
119
|
+
for (const url of attrs[name].split(';')) for (const reason of urlReasons(url)) reasons.add(reason);
|
|
120
|
+
} else for (const reason of cssReasons(attrs[name])) reasons.add(reason);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (tag === 'style') for (const reason of cssReasons((node.childNodes ?? []).map(child => child.value ?? '').join(''))) reasons.add(reason);
|
|
124
|
+
for (const child of node.childNodes ?? []) visit(child);
|
|
125
|
+
if (node.content) visit(node.content);
|
|
126
|
+
}
|
|
127
|
+
visit(tree);
|
|
128
|
+
} catch { reasons.add('incomplete_identity'); }
|
|
129
|
+
const result = [...reasons].sort(); documents.set(document, result); return result;
|
|
130
|
+
}
|
|
131
|
+
htmlReasons.withCss = css => {
|
|
132
|
+
const shared = cssReasons(css);
|
|
133
|
+
return markup => [...new Set([...shared, ...htmlReasons(markup)])].sort();
|
|
134
|
+
};
|
|
135
|
+
return htmlReasons;
|
|
136
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { realpath } from 'node:fs/promises';
|
|
3
|
+
import { prepareDiffInputs } from './diff-inputs.mjs';
|
|
4
|
+
import { revisionChanges, currentHead } from './arch-git.mjs';
|
|
5
|
+
import { cleanup } from './results.mjs';
|
|
6
|
+
import { CliError } from '../cli-output.mjs';
|
|
7
|
+
|
|
8
|
+
const slash = name => name.split(path.sep).join('/');
|
|
9
|
+
const within = (name, directory) => !directory || name === directory || name.startsWith(directory + '/');
|
|
10
|
+
|
|
11
|
+
export { configInputFiles } from './input-generation.mjs';
|
|
12
|
+
|
|
13
|
+
/** Reuse diff's historical config, dependency environment and disposable-tree lifecycle. */
|
|
14
|
+
export async function prepareImpactInputs(config, values) {
|
|
15
|
+
const sessions = [];
|
|
16
|
+
try {
|
|
17
|
+
const base = await prepareDiffInputs(config, [], { base: values.base }); sessions.push(base);
|
|
18
|
+
let head;
|
|
19
|
+
if (values.head !== undefined) { head = await prepareDiffInputs(config, [], { base: values.head }); sessions.push(head); }
|
|
20
|
+
const before = base.before, after = head ? head.before : base.after;
|
|
21
|
+
const projectPrefix = slash(path.relative(base.base.root, await realpath(config.root)));
|
|
22
|
+
const outputs = [before, after].map(side => slash(path.join(projectPrefix, path.relative(side.config.root, side.config.output))));
|
|
23
|
+
const artifacts = values['out-dir'] === undefined ? null : slash(path.relative(base.base.root, path.resolve(await realpath(config.root), values['out-dir'])));
|
|
24
|
+
const excluded = name => name.split('/').some(part => ['.git', 'node_modules', '.adg'].includes(part)) || outputs.some(output => within(name, output)) || artifacts !== null && within(name, artifacts) && /\.(?:png|json)$/.test(name);
|
|
25
|
+
const changes = (await revisionChanges(base.base, head?.base)).filter(change => [change.before, change.after].some(name => name !== null && !excluded(name)));
|
|
26
|
+
return {
|
|
27
|
+
session: base,
|
|
28
|
+
before: { config: before.config, revision: base.base },
|
|
29
|
+
after: { config: after.config, revision: head?.base ?? null },
|
|
30
|
+
query: { kind: 'git', base: { rev: base.base.rev, sha: base.base.sha }, head: head ? { rev: head.base.rev, sha: head.base.sha } : null },
|
|
31
|
+
repository: base.base.root, projectPrefix, changes,
|
|
32
|
+
head: head?.base.sha ?? await currentHead(base.base),
|
|
33
|
+
warnings: sessions.flatMap(session => session.warnings),
|
|
34
|
+
translate: value => sessions.reduce((result, session) => session.translateDiagnostic(result), value),
|
|
35
|
+
async verifyChanges() {
|
|
36
|
+
if (head) return;
|
|
37
|
+
const current = (await revisionChanges(base.base)).filter(change => [change.before, change.after].some(name => name !== null && !excluded(name)));
|
|
38
|
+
if (JSON.stringify(current) !== JSON.stringify(changes)) throw new CliError('IMPACT_INPUT_CHANGED', 'Git input inventory changed during query.');
|
|
39
|
+
},
|
|
40
|
+
async close() {
|
|
41
|
+
let failure;
|
|
42
|
+
for (const session of [...sessions].reverse()) {
|
|
43
|
+
try { await session.close(); } catch (error) { failure ??= error; }
|
|
44
|
+
}
|
|
45
|
+
if (failure) throw failure;
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
} catch (error) {
|
|
49
|
+
for (const session of [...sessions].reverse()) await cleanup(() => session.close(), error);
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
const present = object => Object.fromEntries(Object.entries(object).filter(([, value]) => value !== null && value !== undefined && (!Array.isArray(value) || value.length)));
|
|
2
|
+
|
|
3
|
+
function record(row, explain) {
|
|
4
|
+
return present({ candidate: row.candidate, disposition: row.disposition,
|
|
5
|
+
reasons: row.reasons.map(({ witness, ...reason }) => ({ ...reason, ...(explain && witness ? { witness: present(witness) } : {}) })),
|
|
6
|
+
proof: row.proof ? present({ ...row.proof, projection: explain ? row.proof.projection : undefined }) : null,
|
|
7
|
+
unassessedReasons: row.unassessedReasons });
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// Witnesses and proof digests describe the first represented row, not a grouping boundary.
|
|
11
|
+
function identity(row) {
|
|
12
|
+
const { proof, reasons, ...rest } = row;
|
|
13
|
+
return { ...rest, ...(proof ? { proof: Object.fromEntries(Object.entries(proof).filter(([key]) => key !== 'projection')) } : {}),
|
|
14
|
+
...(reasons ? { reasons: reasons.map(({ witness, ...reason }) => reason) } : {}) };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function addCounts(target, next) {
|
|
18
|
+
for (let i = 0; i < (target.reasons?.length ?? 0); i++) target.reasons[i].count += next.reasons[i].count;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Shared wire projection for ImpactData and the later ImpactSelection. */
|
|
22
|
+
export function groupImpactFrames(frames, { explain = false } = {}) {
|
|
23
|
+
const groups = [], byIdentity = new Map();
|
|
24
|
+
for (const frame of frames) {
|
|
25
|
+
const rows = [], byRecord = new Map();
|
|
26
|
+
for (const input of frame.themes) {
|
|
27
|
+
const value = record(input, explain), key = JSON.stringify(identity(value));
|
|
28
|
+
const same = byRecord.get(key);
|
|
29
|
+
if (same) { same.themes.push(input.theme); addCounts(same, value); }
|
|
30
|
+
else { const row = { themes: [input.theme], ...value }; rows.push(row); byRecord.set(key, row); }
|
|
31
|
+
}
|
|
32
|
+
const metadata = present({ source: frame.ref.source, status: frame.status, matchKind: frame.matchKind, matchCandidates: frame.matchCandidates });
|
|
33
|
+
const key = JSON.stringify({ ...metadata, rows: rows.map(identity) });
|
|
34
|
+
const same = byIdentity.get(key);
|
|
35
|
+
if (same) {
|
|
36
|
+
same.frames.push(frame.ref.frame);
|
|
37
|
+
for (let i = 0; i < rows.length; i++) addCounts(same.rows[i], rows[i]);
|
|
38
|
+
} else {
|
|
39
|
+
const group = { ...metadata, frames: [frame.ref.frame], rows };
|
|
40
|
+
groups.push(group); byIdentity.set(key, group);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return groups;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export const impactFrameCount = groups => groups.reduce((count, group) => count + group.frames.length, 0);
|