@whzxc/agent-design-gallery 0.10.0 → 0.13.2
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 +3 -3
- package/package.json +2 -2
- 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 +25 -2
- package/src/cli.mjs +46 -7
- 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-overlay.mjs +1 -1
- package/src/toolkit/asset-rules.mjs +42 -3
- package/src/toolkit/build-store.mjs +1 -1
- package/src/toolkit/build-worker.mjs +1 -1
- package/src/toolkit/build.mjs +27 -11
- package/src/toolkit/commands.mjs +61 -8
- package/src/toolkit/config.mjs +2 -1
- package/src/toolkit/diff.mjs +4 -1
- package/src/toolkit/document.mjs +6 -6
- package/src/toolkit/frame-document.mjs +1 -1
- 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-inputs.mjs +2 -21
- package/src/toolkit/impact.mjs +3 -24
- 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 +33 -4
- package/src/toolkit/part-diff.mjs +2 -0
- package/src/toolkit/part-snapshot.mjs +15 -23
- package/src/toolkit/project-index.mjs +22 -5
- package/src/toolkit/project.mjs +52 -6
- package/src/toolkit/runtime.d.ts +7 -5
- package/src/toolkit/runtime.mjs +20 -7
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { readFile, realpath, stat } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { CliError } from '../cli-output.mjs';
|
|
4
|
+
import { indexDigest } from './index-store.mjs';
|
|
5
|
+
import { canonicalBytes } from './impact-proof.mjs';
|
|
6
|
+
import { loadConfig, configFile } from './config.mjs';
|
|
7
|
+
|
|
8
|
+
/** Literal local config imports supply path roles; opaque inputs retain unknown classification. */
|
|
9
|
+
export async function configInputFiles(config) {
|
|
10
|
+
const found = new Set(), entry = configFile(config.root);
|
|
11
|
+
async function visit(file) {
|
|
12
|
+
file = await realpath(file);
|
|
13
|
+
if (found.has(file)) return;
|
|
14
|
+
found.add(file);
|
|
15
|
+
const text = await readFile(file, 'utf8');
|
|
16
|
+
for (const [, specifier] of text.matchAll(/\b(?:from\s*|import\s*(?:\(\s*)?|require\(\s*)['"](\.[^'"]+)['"]/g)) {
|
|
17
|
+
const requested = path.resolve(path.dirname(file), specifier);
|
|
18
|
+
for (const candidate of [requested, ...['.ts', '.js', '.mjs', '/index.ts', '/index.js'].map(extension => requested + extension)]) {
|
|
19
|
+
try { if ((await stat(candidate)).isFile()) { await visit(candidate); break; } }
|
|
20
|
+
catch (error) { if (!['ENOENT', 'ENOTDIR'].includes(error.code)) throw error; }
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
if (entry) await visit(entry);
|
|
25
|
+
return [...found];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export const trackedHash = contents => indexDigest(contents === null ? 'missing\0' : Buffer.concat([Buffer.from('present\0'), contents]));
|
|
29
|
+
export async function inputBytes(file) {
|
|
30
|
+
try { return await readFile(file); } catch (error) { if (['ENOENT','ENOTDIR'].includes(error.code)) return null; throw error; }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Verify both sides of configuration evaluation; callers stop builders before final verification. */
|
|
34
|
+
export async function verifyInputGeneration({ tracked, views, inputs, verifyConfig=!!inputs, code='IMPACT_INPUT_CHANGED' }) {
|
|
35
|
+
const fail = message => { throw new CliError(code,message); };
|
|
36
|
+
const verifyTracked=async()=>{for(const [file,expected] of tracked)if(trackedHash(await inputBytes(file))!==expected)fail(`Input changed during query: ${file}.`);};
|
|
37
|
+
await verifyTracked();
|
|
38
|
+
for(const view of views){
|
|
39
|
+
await view.index.verifyInputs();
|
|
40
|
+
if(verifyConfig){
|
|
41
|
+
let resolved;
|
|
42
|
+
try {resolved=await loadConfig(view.config.root,{discover:false,fresh:true});}
|
|
43
|
+
catch(cause){throw new CliError(code,`Configuration could not be revalidated: ${view.config.root}. ${cause.message}`,{cause});}
|
|
44
|
+
if(canonicalBytes(resolved)!==view.resolved)fail(`Resolved configuration changed during query: ${view.config.root}.`);
|
|
45
|
+
const files=await configInputFiles(resolved);
|
|
46
|
+
const names=files.map(file=>path.relative(resolved.root,file).split(path.sep).join('/')).sort();
|
|
47
|
+
if(canonicalBytes(names)!==canonicalBytes([...view.configInputs].sort()))fail('Configuration dependency inventory changed during query.');
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
await verifyTracked();await inputs?.verifyChanges();
|
|
51
|
+
}
|
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
import { resourceSlotIdentity } from './frame-identity.mjs';
|
|
2
|
+
import { propertyGroup } from './inspect-output.mjs';
|
|
3
|
+
import { styleDefaults } from './inspect-styles.mjs';
|
|
4
|
+
|
|
5
|
+
const same=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
|
|
6
|
+
const clone=value=>structuredClone(value);
|
|
7
|
+
const boxKeys=['x','y','width','height'];
|
|
8
|
+
const properties=Object.keys(styleDefaults);
|
|
9
|
+
const shortDigest=s=>Buffer.from(s,'hex').toString('base64url');
|
|
10
|
+
const fullDigest=s=>Buffer.from(s,'base64url').toString('hex');
|
|
11
|
+
const stability=['semantic','authored','positional','resource'];
|
|
12
|
+
const box=value=>value===null?null:boxKeys.map(k=>value[k]);
|
|
13
|
+
const unbox=value=>value===null?null:Object.fromEntries(boxKeys.map((k,i)=>[k,value[i]]));
|
|
14
|
+
|
|
15
|
+
/** The same expansion is used by --expand, human output and the independent live audit. */
|
|
16
|
+
export function styleValues(data,element) {
|
|
17
|
+
const result={};
|
|
18
|
+
for(const key of element.style??[])for(const [property,value]of Object.entries(data.tables.styles[key]??{})){
|
|
19
|
+
result[property]=value==='$width'||value==='$height'?{css:element.geometry.layoutSize[value.slice(1)]+'px',attribution:'raw'}:data.tables.values[value];
|
|
20
|
+
}
|
|
21
|
+
return result;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function geometryScene(scene,encode) {
|
|
25
|
+
const nodes=new Map([...scene.context,...scene.elements].map(e=>[e.id,e]));
|
|
26
|
+
const done=new Set();
|
|
27
|
+
function visit(e){if(done.has(e.id))return;done.add(e.id);const parent=nodes.get(e.parent);if(parent)visit(parent);
|
|
28
|
+
const inheritedClip=parent?clips.get(parent.id):{x:0,y:0,...scene.size};
|
|
29
|
+
const g=e.geometry;if(!g){clips.set(e.id,inheritedClip);return;}
|
|
30
|
+
if(encode){
|
|
31
|
+
// Parent geometry has already been encoded: keep its original effective clip separately.
|
|
32
|
+
const clip=g.clip;const above=parent?clips.get(parent.id):{x:0,y:0,...scene.size};
|
|
33
|
+
if(g.box){
|
|
34
|
+
if(same(g.visibleBox,g.box))delete g.visibleBox;
|
|
35
|
+
if(e.namespace==='html'&&same(g.layoutSize,{width:g.box.width,height:g.box.height}))delete g.layoutSize;
|
|
36
|
+
if(same(g.clip,above))delete g.clip;
|
|
37
|
+
if(g.clipAccuracy==='rect')delete g.clipAccuracy;
|
|
38
|
+
if(g.visibility==='visible')delete g.visibility;
|
|
39
|
+
}
|
|
40
|
+
clips.set(e.id,clip??above);
|
|
41
|
+
for(const k of ['box','visibleBox','clip'])if(k in g)g[k]=box(g[k]);
|
|
42
|
+
if(g.layoutSize)g.layoutSize=[g.layoutSize.width,g.layoutSize.height];
|
|
43
|
+
if(g.clientRects)g.clientRects=g.clientRects.map(box);
|
|
44
|
+
}else{
|
|
45
|
+
for(const k of ['box','visibleBox','clip'])if(k in g)g[k]=unbox(g[k]);
|
|
46
|
+
if(g.layoutSize)g.layoutSize={width:g.layoutSize[0],height:g.layoutSize[1]};
|
|
47
|
+
if(g.clientRects)g.clientRects=g.clientRects.map(unbox);
|
|
48
|
+
if(g.box){
|
|
49
|
+
g.visibility??='visible';if(!('visibleBox'in g))g.visibleBox=clone(g.box);
|
|
50
|
+
if(e.namespace==='html')g.layoutSize??={width:g.box.width,height:g.box.height};
|
|
51
|
+
g.clip??=clone(inheritedClip);g.clipAccuracy??='rect';
|
|
52
|
+
}
|
|
53
|
+
clips.set(e.id,g.clip??inheritedClip);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
const clips=new Map();for(const e of nodes.values())visit(e);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const defaults={namespace:'html',parent:null,children:[],role:null,name:null,a11y:'ignored',attributes:{}};
|
|
60
|
+
function sceneDefaults(scene,encode,fields){
|
|
61
|
+
for(const e of [...scene.context,...scene.elements]){
|
|
62
|
+
for(const [k,v]of Object.entries(defaults)){
|
|
63
|
+
if(encode){if(same(e[k],v))delete e[k];}
|
|
64
|
+
else if(!(k in e)&&(fields.includes('structure')||!['role','name','a11y','attributes'].includes(k)))e[k]=clone(v);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function changes(before,after){
|
|
70
|
+
const set={},unset=[];
|
|
71
|
+
for(const [key,value]of Object.entries(after))if(!same(value,before[key]))set[key]=value;
|
|
72
|
+
for(const key of Object.keys(before))if(!(key in after))unset.push(key);
|
|
73
|
+
return {...set,...(unset.length?{unset}:{})};
|
|
74
|
+
}
|
|
75
|
+
function sceneDelta(before,after){
|
|
76
|
+
const delta={};
|
|
77
|
+
for(const field of ['elements','context','runs']){
|
|
78
|
+
const a=new Map(before[field].map(e=>[rowId(e),e])),b=new Map(after[field].map(e=>[rowId(e),e]));
|
|
79
|
+
const added=after[field].filter(e=>!a.has(rowId(e))),removed=before[field].filter(e=>!b.has(rowId(e))).map(rowId),changed=[];
|
|
80
|
+
const styles=[];
|
|
81
|
+
for(const e of after[field])if(a.has(rowId(e))){const previous=a.get(rowId(e)),diff=changes(previous,e);
|
|
82
|
+
if(field!=='runs'&&diff[3]&&previous[3]?.length===e[3].length){styles.push([rowId(e),...e[3].flatMap((key,i)=>key===previous[3][i]?[]:[i,key])]);delete diff[3];}
|
|
83
|
+
if(Object.keys(diff).length)changed.push({id:rowId(e),...diff});}
|
|
84
|
+
const order=after[field].map(rowId),oldOrder=before[field].filter(e=>b.has(rowId(e))).map(rowId).concat(added.map(rowId));
|
|
85
|
+
if(added.length||removed.length||changed.length||styles.length||!same(order,oldOrder))delta[field]={...(added.length?{added}:{}),...(removed.length?{removed}:{}),...(changed.length?{changed}:{}),...(styles.length?{styles}:{}),...(!same(order,oldOrder)?{order}:{})};
|
|
86
|
+
}
|
|
87
|
+
for(const field of ['roots','size','instances'])if(!same(before[field],after[field]))delta[field]=after[field];
|
|
88
|
+
return delta;
|
|
89
|
+
}
|
|
90
|
+
function applyDelta(baseline,delta){
|
|
91
|
+
const scene=clone(baseline);
|
|
92
|
+
for(const field of ['elements','context','runs'])if(delta[field]){
|
|
93
|
+
const diff=delta[field],map=new Map(scene[field].filter(e=>!diff.removed?.includes(rowId(e))).map(e=>[rowId(e),e]));
|
|
94
|
+
for(const e of diff.added??[])map.set(rowId(e),clone(e));
|
|
95
|
+
for(const {id,unset=[],...change}of diff.changed??[]){const e=map.get(id);if(!e)throw Error('Invalid inspect delta element '+id);Object.assign(e,clone(change));for(const key of unset)delete e[key];}
|
|
96
|
+
for(const [id,...pairs]of diff.styles??[]){const row=map.get(id);for(let i=0;i<pairs.length;i+=2)row[3][pairs[i]]=pairs[i+1];}
|
|
97
|
+
scene[field]=(diff.order??[...map.keys()]).map(id=>map.get(id));
|
|
98
|
+
}
|
|
99
|
+
for(const field of ['roots','size','instances'])if(field in delta)scene[field]=clone(delta[field]);
|
|
100
|
+
return scene;
|
|
101
|
+
}
|
|
102
|
+
const rowId=e=>Array.isArray(e)?e[0]:e.id??e.element+'/text-'+e.slot;
|
|
103
|
+
|
|
104
|
+
// Fixed protocol columns keep repeated JSON property names out of large surfaces.
|
|
105
|
+
// Extras retain uncommon facts by name; this is JSON, not an opaque compressed blob.
|
|
106
|
+
export const elementColumns=['id','tag','children','style','geometry','extra'];
|
|
107
|
+
function packScene(scene,data){
|
|
108
|
+
const svg=svgSlots(scene,data.tables);
|
|
109
|
+
const pack=e=>{const {id,tag,children,style,geometry,parent,...extra}=e;
|
|
110
|
+
const above=nodes.get(parent);
|
|
111
|
+
const inferred=tag==='svg'||above?.namespace==='svg'&&above.tag!=='foreignObject'?'svg':'html';
|
|
112
|
+
if((e.namespace??'html')===inferred)delete extra.namespace;
|
|
113
|
+
if(extra.attributes&&svg.has(id)){
|
|
114
|
+
const attrs={...extra.attributes};for(const [k,v]of Object.entries(svg.get(id)))if(attrs[k]===v)delete attrs[k];
|
|
115
|
+
if(Object.keys(attrs).length)extra.attributes=attrs;else delete extra.attributes;
|
|
116
|
+
}
|
|
117
|
+
if(extra.owner===above?.owner)delete extra.owner;
|
|
118
|
+
else if(extra.owner===undefined&&above?.owner)extra.owner=null;
|
|
119
|
+
if(extra.markers&&same(extra.markers,data.partInstances.filter(i=>i.root===id).map(i=>i.part)))delete extra.markers;
|
|
120
|
+
const ownRuns=scene.runs.filter(r=>r.element===id).map(r=>r.id);
|
|
121
|
+
if(extra.text&&same(extra.text,ownRuns))delete extra.text;
|
|
122
|
+
if('a11y'in extra||'role'in extra||'name'in extra){
|
|
123
|
+
const semantics=[extra.role??null,extra.name??null,extra.a11y??'ignored'];
|
|
124
|
+
const table=data.tables.a11y??=[];let key=table.findIndex(r=>same(r,semantics));if(key<0){key=table.length;table.push(semantics);}
|
|
125
|
+
delete extra.role;delete extra.name;extra.a11y=key;
|
|
126
|
+
}
|
|
127
|
+
let g=geometry??null;
|
|
128
|
+
if(g&&Object.keys(g).length===1&&Array.isArray(g.box))g=g.box;
|
|
129
|
+
|
|
130
|
+
const row=[id,tag,children??[],style??null,g];
|
|
131
|
+
if(Object.keys(extra).length)row.push(extra);return row;};
|
|
132
|
+
const nodes=new Map([...scene.context,...scene.elements].map(e=>[e.id,e]));
|
|
133
|
+
scene.runs=scene.runs.map(r=>{
|
|
134
|
+
const {id,normalized,style,fragments,...rest}=r,owner=nodes.get(r.element),slot=id.slice(id.lastIndexOf('/text-')+6);
|
|
135
|
+
const simple=fragments.length===1&&fragments[0].element===r.element&&fragments[0].start===0&&fragments[0].end===r.raw.length;
|
|
136
|
+
return {element:r.element,slot,...(r.kind!=='dom'?{kind:r.kind}:{}),raw:r.raw,
|
|
137
|
+
...(!same(style,owner?.style)?{style}:{}),...(simple?{boxes:fragments[0].boxes,...(fragments[0].accuracy!=='range'?{accuracy:fragments[0].accuracy}:{})}:{fragments}),
|
|
138
|
+
...(normalized!==r.raw.normalize('NFC').replace(/\p{White_Space}+/gu,' ').trim()?{normalized}:{}),
|
|
139
|
+
...(rest.kind!==r.kind?rest:{})};
|
|
140
|
+
});
|
|
141
|
+
scene.context=scene.context.map(pack);scene.elements=scene.elements.map(pack);
|
|
142
|
+
}
|
|
143
|
+
function unpackScene(scene,data){
|
|
144
|
+
for(const row of [...scene.context,...scene.elements])if(typeof row[1]==='number'){
|
|
145
|
+
const [tag,semantics,namespace]=data.tables.elementTypes[row[1]];row[1]=tag;
|
|
146
|
+
row[5]={...(semantics===null?{}:{a11y:semantics}),...(namespace?{namespace}:{}),...row[5]};
|
|
147
|
+
}
|
|
148
|
+
const unpack=([id,tag,children,style,geometry,extra={}])=>({id,tag,...(children.length?{children}:{}),...(style?{style}:{}),...(geometry?{geometry:Array.isArray(geometry)?{box:geometry}:geometry}:{}),...extra});
|
|
149
|
+
scene.context=scene.context.map(unpack);scene.elements=scene.elements.map(unpack);
|
|
150
|
+
const nodes=new Map([...scene.context,...scene.elements].map(e=>[e.id,e]));
|
|
151
|
+
for(const e of nodes.values())for(const id of e.children??[])if(nodes.has(id))nodes.get(id).parent=e.id;
|
|
152
|
+
const visited=new Set();
|
|
153
|
+
function inherited(e){if(visited.has(e.id))return;visited.add(e.id);const parent=nodes.get(e.parent);if(parent)inherited(parent);
|
|
154
|
+
e.namespace??=e.tag==='svg'||parent?.namespace==='svg'&&parent.tag!=='foreignObject'?'svg':'html';
|
|
155
|
+
if(e.owner===null)delete e.owner;else if(!('owner'in e)&&parent?.owner)e.owner=parent.owner;
|
|
156
|
+
if(typeof e.a11y==='number'){const [role,name,a11y]=data.tables.a11y[e.a11y];e.role=role;e.name=name;e.a11y=a11y;}
|
|
157
|
+
if(data.selection.fields.includes('structure')){const markers=data.partInstances.filter(i=>i.root===e.id).map(i=>i.part);if(markers.length)e.markers??=markers;}
|
|
158
|
+
}
|
|
159
|
+
for(const e of nodes.values())inherited(e);
|
|
160
|
+
if(data.selection.fields.includes('structure'))for(const [id,attrs]of svgSlots(scene,data.tables))nodes.get(id).attributes={...attrs,...nodes.get(id).attributes};
|
|
161
|
+
scene.runs=scene.runs.map(r=>{
|
|
162
|
+
const {slot,boxes,accuracy,fragments,normalized,style,...rest}=r,owner=nodes.get(r.element);
|
|
163
|
+
const resolved=style??owner?.style;
|
|
164
|
+
return {id:r.element+'/text-'+slot,kind:r.kind??'dom',...rest,normalized:normalized??r.raw.normalize('NFC').replace(/\p{White_Space}+/gu,' ').trim(),...(resolved?{style:resolved}:{}),fragments:fragments??[{element:r.element,start:0,end:r.raw.length,boxes,accuracy:accuracy??'range'}]};
|
|
165
|
+
});
|
|
166
|
+
for(const r of scene.runs){const node=nodes.get(r.element)??[...nodes.values()].flatMap(e=>e.pseudo??[]).find(p=>p.id===r.element);if(node&&!node.text)(node.text=[]);if(node&&!node.text.includes(r.id))node.text.push(r.id);}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function svgSlots(scene,tables){
|
|
170
|
+
const nodes=new Map([...scene.context,...scene.elements].map(e=>[e.id,e])),result=new Map();
|
|
171
|
+
for(const root of nodes.values())if(tables.resources[root.resource]?.svg){const definition=tables.resources[root.resource].svg.geometry;let slot=0;
|
|
172
|
+
function visit(e){const fact=definition[slot++];if(fact&&fact.tag===e.tag)result.set(e.id,Object.fromEntries(Object.entries(fact.attributes).filter(([,v])=>v!=='embedded')));for(const id of e.children??[])if(nodes.has(id))visit(nodes.get(id));}
|
|
173
|
+
// Depth-limited queries cannot align omitted resource slots; leave their attributes explicit.
|
|
174
|
+
const count=e=>1+(e.children??[]).reduce((n,id)=>n+(nodes.has(id)?count(nodes.get(id)):0),0);
|
|
175
|
+
if(count(root)===definition.length)visit(root);
|
|
176
|
+
}
|
|
177
|
+
return result;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function elementTypes(scene,tables){
|
|
181
|
+
const types=tables.elementTypes??=[];
|
|
182
|
+
for(const row of [...scene.context,...scene.elements]){
|
|
183
|
+
const extra=row[5]??{},type=[row[1],extra.a11y??null,...(extra.namespace?[extra.namespace]:[])];
|
|
184
|
+
let key=types.findIndex(t=>same(t,type));if(key<0){key=types.length;types.push(type);}
|
|
185
|
+
row[1]=key;delete extra.a11y;delete extra.namespace;
|
|
186
|
+
if(!Object.keys(extra).length)row.length=5;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function packStyles(styles,dictionary){
|
|
191
|
+
const previous=new Map(),indices=new Map(dictionary.map((p,i)=>[p,i]));
|
|
192
|
+
const scalar=v=>typeof v==='number'?String(v).length:v.length+2;
|
|
193
|
+
const size=pairs=>2+pairs.reduce((n,v)=>n+scalar(v),0)+Math.max(0,pairs.length-1);
|
|
194
|
+
for(const [key,style]of Object.entries(styles)){
|
|
195
|
+
const entries=Object.entries(style).map(([p,v])=>[p,v,indices.get(p)]),group=propertyGroup(entries[0][0]);
|
|
196
|
+
let packed=entries.flatMap(([,v,p])=>[p,v]),length=size(packed);
|
|
197
|
+
for(const other of previous.get(group)??[]){
|
|
198
|
+
const diff=entries.filter(([p,v])=>other.style[p]!==v).flatMap(([,v,p])=>[p,v]);
|
|
199
|
+
const removed=other.entries.filter(([p])=>!(p in style)).map(([, ,p])=>p);
|
|
200
|
+
const candidateLength=2+scalar(other.key)+1+size(diff)+(removed.length?1+size(removed):0);
|
|
201
|
+
if(candidateLength<length){packed=[other.key,diff,...(removed.length?[removed]:[])];length=candidateLength;}
|
|
202
|
+
}
|
|
203
|
+
const peers=previous.get(group)??[];peers.push({key,style,entries});previous.set(group,peers);styles[key]=packed;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
function unpackStyles(styles,dictionary){
|
|
207
|
+
const resolved=new Map();
|
|
208
|
+
function read(key){if(resolved.has(key))return resolved.get(key);const row=styles[key];
|
|
209
|
+
const based=typeof row[0]==='string',pairs=based?row[1]:row;
|
|
210
|
+
const style={...(based?read(row[0]):{}),...Object.fromEntries(Array.from({length:pairs.length/2},(_,i)=>[dictionary[pairs[i*2]],pairs[i*2+1]]))};
|
|
211
|
+
for(const p of based?row[2]??[]:[])delete style[dictionary[p]];resolved.set(key,style);return style;
|
|
212
|
+
}
|
|
213
|
+
for(const key of Object.keys(styles))read(key);for(const [key,value]of resolved)styles[key]=value;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const round=n=>Math.round(n*100)/100||0;
|
|
217
|
+
function moveGeometry(value,origin,direction){
|
|
218
|
+
if(!value)return;
|
|
219
|
+
const rect=r=>{if(r){r[0]=round(r[0]+direction*origin[0]);r[1]=round(r[1]+direction*origin[1]);}};
|
|
220
|
+
if(Array.isArray(value)){rect(value);return;}
|
|
221
|
+
for(const field of ['box','visibleBox','clip'])if(value[field])rect(value[field]);
|
|
222
|
+
for(const r of value.clientRects??[])rect(r);
|
|
223
|
+
}
|
|
224
|
+
function localAddresses(value,map,key=''){
|
|
225
|
+
if(key==='attributes'&&value)return Object.fromEntries(Object.entries(value).map(([k,v])=>[k,['href','for','aria-labelledby','aria-describedby'].includes(k)?localAddresses(v,map,'element'):v]));
|
|
226
|
+
if(typeof value==='string'&&addressFields.has(key))return value.replace(/(?:^|(?<=#))(?:e[0-9a-z]+|@\d+)(?=::|\/text-|$)/g,id=>map.get(id)??id);
|
|
227
|
+
if(Array.isArray(value))return value.map(v=>localAddresses(v,map,key));
|
|
228
|
+
if(value&&typeof value==='object')return Object.fromEntries(Object.entries(value).map(([k,v])=>[k,localAddresses(v,map,k)]));
|
|
229
|
+
return value;
|
|
230
|
+
}
|
|
231
|
+
/** Exact subtree sharing, only when the definition plus every instance is smaller. */
|
|
232
|
+
function templateScene(scene,tables){
|
|
233
|
+
const nodes=new Map(scene.elements.map(e=>[e.id,e])),groups=new Map(),ownText=new Map(),textKeys=new Map();
|
|
234
|
+
for(const r of scene.runs){const id=r.element.replace(/::.+$/,''),rows=ownText.get(id)??[];rows.push([r.kind,r.raw,r.normalized,r.style]);ownText.set(id,rows);}
|
|
235
|
+
function textKey(e){if(!textKeys.has(e.id))textKeys.set(e.id,JSON.stringify([ownText.get(e.id)??[],...(e.children??[]).filter(id=>nodes.has(id)).map(id=>textKey(nodes.get(id)))]));return textKeys.get(e.id);}
|
|
236
|
+
const probes=new Map(),counts=new Map();
|
|
237
|
+
for(const e of scene.elements)if(e.children?.length&&e.geometry?.box){const key=JSON.stringify([e.tag,e.namespace,e.style,e.role,e.name,e.resource,textKey(e)]);probes.set(e.id,key);counts.set(key,(counts.get(key)??0)+1);}
|
|
238
|
+
for(const root of scene.elements){
|
|
239
|
+
// Exact repeats need equal root semantics/styles and authored subtree text. Avoid cloning unique rows.
|
|
240
|
+
if((counts.get(probes.get(root.id))??0)<2)continue;
|
|
241
|
+
if(!root.children?.length||!root.geometry?.box)continue;
|
|
242
|
+
const subtree=[];function visit(e){subtree.push(e);for(const id of e.children??[])if(nodes.has(id))visit(nodes.get(id));}visit(root);
|
|
243
|
+
const ids=subtree.map(e=>e.id),mapping=new Map(ids.map((id,i)=>[id,'@'+i])),origin=root.geometry.box.slice(0,2);
|
|
244
|
+
const ownRuns=scene.runs.filter(r=>ids.includes(r.element.replace(/::.+$/,'')));
|
|
245
|
+
const normalized=localAddresses({elements:subtree,runs:ownRuns},mapping);
|
|
246
|
+
normalized.elements[0].parent='$parent';
|
|
247
|
+
for(const e of normalized.elements){moveGeometry(e.geometry,origin,-1);if(e.owner===root.owner&&e.owner)e.owner='$owner';}
|
|
248
|
+
for(const r of normalized.runs)for(const f of r.fragments)for(const b of f.boxes){b.x=round(b.x-origin[0]);b.y=round(b.y-origin[1]);}
|
|
249
|
+
const key=JSON.stringify(normalized),group=groups.get(key)??{definition:normalized,items:[]};
|
|
250
|
+
group.items.push({root,ids,origin,at:scene.elements.indexOf(root)});groups.set(key,group);
|
|
251
|
+
}
|
|
252
|
+
const removed=new Set(),removedRuns=new Set();
|
|
253
|
+
for(const group of [...groups.values()].sort((a,b)=>b.definition.elements.length-a.definition.elements.length)){
|
|
254
|
+
const available=group.items.filter(i=>i.ids.every(id=>!removed.has(id)));if(available.length<2)continue;
|
|
255
|
+
const key='t'+Object.keys(tables.templates).length;
|
|
256
|
+
const instances=available.map(i=>({at:i.at,template:key,ids:i.ids,origin:i.origin,parent:i.root.parent??null,...(i.root.owner?{owner:i.root.owner}:{})}));
|
|
257
|
+
const oldBytes=available.reduce((n,i)=>n+JSON.stringify(i.ids.map(id=>nodes.get(id))).length,0),newBytes=JSON.stringify(group.definition).length+JSON.stringify(instances).length;
|
|
258
|
+
if(newBytes>=oldBytes)continue;
|
|
259
|
+
tables.templates[key]=group.definition;scene.instances.push(...instances);
|
|
260
|
+
for(const i of available)for(const id of i.ids){removed.add(id);for(const r of scene.runs)if(r.element===id||r.element.startsWith(id+'::'))removedRuns.add(r.id);}
|
|
261
|
+
}
|
|
262
|
+
scene.elements=scene.elements.filter(e=>!removed.has(e.id));scene.runs=scene.runs.filter(r=>!removedRuns.has(r.id));
|
|
263
|
+
scene.instances.sort((a,b)=>a.at-b.at);
|
|
264
|
+
}
|
|
265
|
+
function expandTemplates(scene,tables){
|
|
266
|
+
if(!scene.instances.length)return;
|
|
267
|
+
const nodes=scene.elements;
|
|
268
|
+
for(const instance of scene.instances){
|
|
269
|
+
const definition=clone(tables.templates[instance.template]);unpackScene(definition,{tables,selection:{fields:[]},partInstances:[]});
|
|
270
|
+
const map=new Map(instance.ids.map((id,i)=>['@'+i,id]));let {elements,runs}=localAddresses(definition,map);
|
|
271
|
+
elements[0].parent=instance.parent;
|
|
272
|
+
for(const e of elements){moveGeometry(e.geometry,instance.origin,1);if(e.owner==='$owner')e.owner=instance.owner;}
|
|
273
|
+
for(const r of runs)for(const f of r.fragments)for(const b of f.boxes){b.x=round(b.x+instance.origin[0]);b.y=round(b.y+instance.origin[1]);}
|
|
274
|
+
// Return packed rows for the normal theme-delta stage.
|
|
275
|
+
const packed={context:[],elements,runs};packScene(packed,{tables,partInstances:[]});elementTypes(packed,tables);
|
|
276
|
+
nodes.splice(instance.at,0,...packed.elements);scene.runs.push(...packed.runs);
|
|
277
|
+
}
|
|
278
|
+
// Text order follows the original full-frame DOM run order, stored once for templates.
|
|
279
|
+
if(scene.runOrder){const order=new Map(scene.runOrder.map((id,i)=>[id,i]));scene.runs.sort((a,b)=>order.get(rowId(a))-order.get(rowId(b)));delete scene.runOrder;}
|
|
280
|
+
scene.instances=[];
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const addressFields=new Set(['id','parent','children','roots','element','elements','root','href','for','aria-labelledby','aria-describedby','text','runs','removed','order','ids']);
|
|
284
|
+
function addresses(value,map,encode,key=''){
|
|
285
|
+
if(key==='attributes'&&value){const links=new Set(['href','for','aria-labelledby','aria-describedby']);
|
|
286
|
+
const link=v=>{if(Array.isArray(v))return v.map(link);if(!encode&&v&&typeof v==='object'&&'literal'in v)return v.literal;
|
|
287
|
+
if(encode&&typeof v==='string'&&!/e1_[a-f0-9]{24}/.test(v)&&/^#?(?:e[0-9a-z]+|\d+)(?=::|\/text-|$)/.test(v))return {literal:v};
|
|
288
|
+
return addresses(v,map,encode,'element');};
|
|
289
|
+
return Object.fromEntries(Object.entries(value).map(([k,v])=>[k,links.has(k)?link(v):v]));
|
|
290
|
+
}
|
|
291
|
+
if(typeof value==='string')return addressFields.has(key)?value.replace(encode?/e1_[a-f0-9]{24}/g:/(?:^|(?<=#))e[0-9a-z]+(?=::|\/text-|$)/g,id=>map.get(id)??id):value;
|
|
292
|
+
if(Array.isArray(value)){for(let i=0;i<value.length;i++)value[i]=addresses(value[i],map,encode,key);return value;}
|
|
293
|
+
if(value&&typeof value==='object'){for(const k of Object.keys(value))value[k]=addresses(value[k],map,encode,k);return value;}
|
|
294
|
+
return value;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// Array indices are output-local table keys. Stable e1_ addresses live once in identities.
|
|
298
|
+
function indexTables(data,encode){
|
|
299
|
+
const names=['values','styles','references','parts','resources','identities','duplicates'];
|
|
300
|
+
const prefixes={values:'v',styles:'s',references:'r',parts:'p',resources:'r',identities:'e',duplicates:'d'};
|
|
301
|
+
const maps=Object.fromEntries(names.map(name=>[name,new Map(encode?Object.keys(data.tables[name]??{}).map((k,i)=>[k,i]):(data.tables[name]??[]).map((_,i)=>[i,prefixes[name]+(name==='identities'?i.toString(36):i)]))]));
|
|
302
|
+
if(!encode)data.partInstances=data.partInstances.map(([part,root,parent],i)=>({id:'i'+i,part,root,parent:parent===null?null:'i'+parent}));
|
|
303
|
+
const owners=new Map(data.partInstances.map((p,i)=>encode?[p.id,i]:[i,p.id]));
|
|
304
|
+
const ref=(name,key)=>maps[name].get(key)??key;
|
|
305
|
+
function address(value){if(encode&&typeof value==='string'){
|
|
306
|
+
if(maps.identities.has(value))return ref('identities',value);
|
|
307
|
+
return value.replace(/(?:^|(?<=#))e[0-9a-z]+(?=::|\/text-|$)/g,key=>String(ref('identities',key)));
|
|
308
|
+
}if(!encode){if(typeof value==='number')return ref('identities',value);if(typeof value==='string')return value.replace(/(?:^|(?<=#))\d+(?=::|\/text-|$)/g,key=>ref('identities',Number(key)));}return value;}
|
|
309
|
+
function node(row){row[0]=address(row[0]);row[2]=row[2].map(address);if(row[3])row[3]=row[3].map(k=>ref('styles',k));const e=row[5];if(!e)return;
|
|
310
|
+
if(e.owner!==undefined&&e.owner!==null)e.owner=owners.get(e.owner);
|
|
311
|
+
if(e.markers)e.markers=e.markers.map(k=>ref('parts',k));if(e.resource!==undefined)e.resource=ref('resources',e.resource);if(e.backgrounds)e.backgrounds=e.backgrounds.map(k=>ref('resources',k));
|
|
312
|
+
if(e.text)e.text=e.text.map(address);
|
|
313
|
+
for(const p of e.pseudo??[]){p.id=address(p.id);if(p.style)p.style=p.style.map(k=>ref('styles',k));if(p.text)p.text=p.text.map(address);}
|
|
314
|
+
for(const k of ['href','for','aria-labelledby','aria-describedby'])if(e.attributes?.[k])e.attributes[k]=Array.isArray(e.attributes[k])?e.attributes[k].map(address):address(e.attributes[k]);
|
|
315
|
+
}
|
|
316
|
+
function run(r){r.element=address(r.element);if(r.id)r.id=address(r.id);if(r.style)r.style=r.style.map(k=>ref('styles',k));for(const f of r.fragments??[])f.element=address(f.element);}
|
|
317
|
+
function scene(s){if(s.roots)s.roots=s.roots.map(address);s.context.forEach(node);s.elements.forEach(node);s.runs.forEach(run);
|
|
318
|
+
if(s.runOrder)s.runOrder=s.runOrder.map(address);
|
|
319
|
+
for(const i of s.instances??[]){i.ids=i.ids.map(address);i.parent=address(i.parent);if(i.owner!==undefined)i.owner=owners.get(i.owner);}
|
|
320
|
+
}
|
|
321
|
+
scene(data.baseline);
|
|
322
|
+
for(const definition of Object.values(data.tables.templates))scene(definition);
|
|
323
|
+
if(data.delta){const d=data.delta;if(d.roots)d.roots=d.roots.map(address);
|
|
324
|
+
for(const field of ['elements','context','runs'])if(d[field]){const diff=d[field];
|
|
325
|
+
if(diff.removed)diff.removed=diff.removed.map(address);if(diff.order)diff.order=diff.order.map(address);
|
|
326
|
+
for(const row of diff.styles??[]){row[0]=address(row[0]);for(let i=2;i<row.length;i+=2)row[i]=ref('styles',row[i]);}
|
|
327
|
+
for(const r of diff.added??[])field==='runs'?run(r):node(r);
|
|
328
|
+
for(const r of diff.changed??[]){r.id=address(r.id);if(field==='runs'){if(r.style)r.style=r.style.map(k=>ref('styles',k));if(r.element!==undefined)r.element=address(r.element);}
|
|
329
|
+
else{if(r[2])r[2]=r[2].map(address);if(r[3])r[3]=r[3].map(k=>ref('styles',k));if(r[5]){const fake=[null,null,[],null,null,r[5]];node(fake);}}}
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
for(const m of data.matches){m.element=address(m.element);if(m.runs)m.runs=m.runs.map(address);}
|
|
333
|
+
for(const l of data.limitations)l.elements=l.elements.map(address);
|
|
334
|
+
for(const p of data.partInstances){p.part=ref('parts',p.part);p.root=address(p.root);}
|
|
335
|
+
if(encode)data.partInstances=data.partInstances.map(p=>[p.part,p.root,p.parent===null?null:owners.get(p.parent)]);
|
|
336
|
+
for(const value of Object.values(data.tables.values))if(Array.isArray(value))value[1]=value[1].map(k=>ref('references',k));
|
|
337
|
+
for(const row of Object.values(data.tables.styles)){
|
|
338
|
+
const based=encode?typeof row[0]==='string':Array.isArray(row[0]),pairs=based?row[1]:row;
|
|
339
|
+
if(based)row[0]=encode?[ref('styles',row[0])]:ref('styles',row[0][0]);
|
|
340
|
+
for(let i=1;i<pairs.length;i+=2)pairs[i]=ref('values',pairs[i]);
|
|
341
|
+
}
|
|
342
|
+
for(const row of Object.values(data.tables.identities)){if(row.length===2)row[0]=ref('identities',row[0]);if(Array.isArray(row[3]))row[3][0]=ref('duplicates',row[3][0]);else if(row[3]?.duplicate)row[3].duplicate[0]=ref('duplicates',row[3].duplicate[0]);}
|
|
343
|
+
// CSS url(rN) also uses the resource table, including in pseudo content.
|
|
344
|
+
function urls(v){if(typeof v==='string')return v.replace(/url\(r(\d+)\)/g,(_,n)=>'url('+ (encode?'r'+ref('resources','r'+n):ref('resources',Number(n))) +')');
|
|
345
|
+
if(Array.isArray(v))return v.map(urls);if(v&&typeof v==='object')return Object.fromEntries(Object.entries(v).map(([k,x])=>[k,urls(x)]));return v;}
|
|
346
|
+
data.tables.values=urls(data.tables.values);
|
|
347
|
+
for(const name of names){const table=data.tables[name];if(!table){if(encode)continue;delete data.tables[name];continue;}
|
|
348
|
+
data.tables[name]=encode?Object.values(table):Object.fromEntries(Object.entries(table).map(([k,v])=>[ref(name,Number(k)),v]));}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function factTables(data,encode){
|
|
352
|
+
const t=data.tables;
|
|
353
|
+
if(encode){
|
|
354
|
+
for(const [key,r]of Object.entries(t.references)){
|
|
355
|
+
const flags=(r.kind==='alias'?2:r.kind==='fallback'?4:0)|(r.inherited?1:0),extra={};
|
|
356
|
+
if(r.expression!==`var(${r.token})`)extra.expression=r.expression;
|
|
357
|
+
if(r.via?.length)extra.via=r.via;if(r.localOverrides?.length)extra.localOverrides=r.localOverrides.map(d=>[d.name,d.declaration]);
|
|
358
|
+
if(r.basis)extra.basis=r.basis;
|
|
359
|
+
t.references[key]=[r.token,t.properties.indexOf(r.property),flags,...(Object.keys(extra).length?[extra]:[])];
|
|
360
|
+
}
|
|
361
|
+
if(Object.keys(t.tokens).length){t.tokenSource=Object.values(t.tokens)[0].source;
|
|
362
|
+
for(const [name,r]of Object.entries(t.tokens)){const extra={};if(r.source!==t.tokenSource)extra.source=r.source;if(r.resolved!==r.declaration)extra.resolved=r.resolved;
|
|
363
|
+
if(r.dark){extra.dark={...r.dark};}
|
|
364
|
+
t.tokens[name]=[r.line,r.declaration,...(Object.keys(extra).length?[extra]:[])];}
|
|
365
|
+
}
|
|
366
|
+
for(const r of Object.values(t.resources))if(r.svg){r.svg.geometry=r.svg.geometry.map(n=>[n.tag,n.attributes,n.children]);if(r.mime==='image/svg+xml')delete r.mime;}
|
|
367
|
+
}else{
|
|
368
|
+
for(const [key,[token,p,flags,extra={}]]of Object.entries(t.references)){
|
|
369
|
+
const {localOverrides,...rest}=extra;t.references[key]={token,property:t.properties[p],kind:flags&4?'fallback':flags&2?'alias':'direct',expression:extra.expression??`var(${token})`,...(flags&1?{inherited:true}:{}),...rest,...(localOverrides?{localOverrides:localOverrides.map(([name,declaration])=>({name,declaration}))}:{})};
|
|
370
|
+
}
|
|
371
|
+
for(const [name,[line,declaration,extra={}]]of Object.entries(t.tokens)){
|
|
372
|
+
const {dark,...rest}=extra;t.tokens[name]={source:t.tokenSource,line,declaration,resolved:declaration,...rest,...(dark?{dark}:{})};
|
|
373
|
+
}
|
|
374
|
+
delete t.tokenSource;
|
|
375
|
+
for(const r of Object.values(t.resources))if(r.svg){r.mime??='image/svg+xml';r.svg.geometry=r.svg.geometry.map(([tag,attributes,children],i)=>({id:'g'+i,tag,attributes,children}));}
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
export function compactInspection(input) { return compact(input,true); }
|
|
380
|
+
|
|
381
|
+
function compact(input,templates) {
|
|
382
|
+
if(input.encoding==='compact'||input.mode==='catalog')return input;
|
|
383
|
+
let data=clone(input);data.tables.a11y=[];
|
|
384
|
+
const scenes=[data.baseline,...Object.values(data.additionalThemes)],identities={},ids=new Map(),groups={},groupKeys=new Map(),allNodes=new Map(scenes.flatMap(s=>[...s.context,...s.elements]).map(e=>[e.id,e])),originalIdentity=new Map();
|
|
385
|
+
for(const scene of scenes)for(const e of [...scene.context,...scene.elements])if(!ids.has(e.id)){
|
|
386
|
+
const key='e'+ids.size.toString(36),{guard,stability:s,duplicate,...extra}=e.identity;
|
|
387
|
+
ids.set(e.id,key);originalIdentity.set(e.id,e.identity);
|
|
388
|
+
const row=[e.id,shortDigest(guard),stability.indexOf(s)];
|
|
389
|
+
if(duplicate){let group=groupKeys.get(duplicate.group);if(!group){group='d'+groupKeys.size;groupKeys.set(duplicate.group,group);groups[group]=[shortDigest(duplicate.group),duplicate.count];}extra.duplicate=[group,duplicate.ordinal];}
|
|
390
|
+
if(Object.keys(extra).length)row.push(Object.keys(extra).length===1&&extra.duplicate?extra.duplicate:extra);identities[key]=row;
|
|
391
|
+
}
|
|
392
|
+
for(const scene of scenes){geometryScene(scene,true);sceneDefaults(scene,true,data.selection.fields);for(const e of [...scene.context,...scene.elements])if(same(e.identity,originalIdentity.get(e.id)))delete e.identity;}
|
|
393
|
+
for(const [full,key]of ids){const e=allNodes.get(full),ownIdentity=originalIdentity.get(full);if(ownIdentity.stability==='resource'){
|
|
394
|
+
let parent=allNodes.get(e.parent);while(parent&&originalIdentity.get(parent.id)?.stability==='resource')parent=allNodes.get(parent.parent);
|
|
395
|
+
if(parent)identities[key]=[ids.get(parent.id),ownIdentity.slot];
|
|
396
|
+
}}
|
|
397
|
+
for(const [key,group]of Object.entries(groups)){
|
|
398
|
+
const members=Object.values(identities).filter(r=>(Array.isArray(r[3])?r[3][0]:r[3]?.duplicate?.[0])===key);
|
|
399
|
+
if(members.length&&members.every(r=>r[1]===members[0][1])){group.push(members[0][1]);for(const row of members)row[1]=null;}
|
|
400
|
+
}
|
|
401
|
+
data=addresses(data,ids,true);data.tables.identities=identities;
|
|
402
|
+
if(Object.keys(groups).length)data.tables.duplicates=groups;
|
|
403
|
+
for(const [key,value]of Object.entries(data.tables.values))data.tables.values[key]=value.attribution==='raw'?value.css:[value.css,value.refs??[],...(value.reason?[value.reason]:[])];
|
|
404
|
+
const used=new Set([...Object.values(data.tables.styles).flatMap(s=>Object.keys(s)),...Object.values(data.tables.references).map(r=>r.property)]);
|
|
405
|
+
data.tables.properties=[...properties.filter(p=>used.has(p)),...[...used].filter(p=>!properties.includes(p)).sort()];
|
|
406
|
+
packStyles(data.tables.styles,data.tables.properties);
|
|
407
|
+
for(const ref of Object.values(data.tables.references))if(ref.basis==='authored_reference')delete ref.basis;
|
|
408
|
+
for(const resource of Object.values(data.tables.resources))if(resource.svg)delete resource.svg.definitions;
|
|
409
|
+
// Delta compares full logical rows; template instances never cause a second dark tree.
|
|
410
|
+
const baselineBefore=templates?{...data.baseline,instances:[]}:null;
|
|
411
|
+
for(const scene of [data.baseline,...Object.values(data.additionalThemes)]){packScene(scene,data);elementTypes(scene,data.tables);}
|
|
412
|
+
data.delta=Object.keys(data.additionalThemes).length?{theme:Object.keys(data.additionalThemes)[0],...sceneDelta(data.baseline,Object.values(data.additionalThemes)[0])}:null;
|
|
413
|
+
delete data.additionalThemes;
|
|
414
|
+
if(baselineBefore){baselineBefore.runOrder=baselineBefore.runs.map(r=>r.id);templateScene(baselineBefore,data.tables);}
|
|
415
|
+
if(baselineBefore?.instances.length){
|
|
416
|
+
packScene(baselineBefore,data);elementTypes(baselineBefore,data.tables);data.baseline=baselineBefore;
|
|
417
|
+
for(const definition of Object.values(data.tables.templates)){definition.context=[];definition.instances=[];packScene(definition,data);elementTypes(definition,data.tables);}
|
|
418
|
+
}
|
|
419
|
+
factTables(data,true);
|
|
420
|
+
indexTables(data,true);
|
|
421
|
+
data.encoding='compact';
|
|
422
|
+
// Judge the actual final wire size, including dictionaries and instances, not a pre-pack estimate.
|
|
423
|
+
if(templates&&Object.keys(data.tables.templates).length){const ordinary=compact(input,false);if(Buffer.byteLength(JSON.stringify(ordinary))<=Buffer.byteLength(JSON.stringify(data)))return ordinary;}
|
|
424
|
+
return data;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
export function expandInspection(input) {
|
|
428
|
+
if(input.encoding!=='compact')return clone(input);
|
|
429
|
+
let data=clone(input);
|
|
430
|
+
indexTables(data,false);
|
|
431
|
+
factTables(data,false);
|
|
432
|
+
expandTemplates(data.baseline,data.tables);
|
|
433
|
+
data.additionalThemes=data.delta?{[data.delta.theme]:applyDelta(data.baseline,data.delta)}:{};
|
|
434
|
+
for(const scene of [data.baseline,...Object.values(data.additionalThemes)])unpackScene(scene,data);
|
|
435
|
+
const identities=data.tables.identities,ids=new Map(),resolvedMetadata=new Map();
|
|
436
|
+
const nodes=new Map([data.baseline,...Object.values(data.additionalThemes)].flatMap(s=>[...s.context,...s.elements]).map(e=>[e.id,e]));
|
|
437
|
+
function identity(key){if(resolvedMetadata.has(key))return resolvedMetadata.get(key);const row=identities[key];
|
|
438
|
+
if(row.length===2){identity(row[0]);const e=nodes.get(key),resource=resourceSlotIdentity(ids.get(row[0]),row[1],e.tag,e.namespace==='svg'?'http://www.w3.org/2000/svg':e.namespace??'http://www.w3.org/1999/xhtml');ids.set(key,resource.id);resolvedMetadata.set(key,resource.identity);return resource.identity;}
|
|
439
|
+
const duplicate=Array.isArray(row[3])?row[3]:row[3]?.duplicate;
|
|
440
|
+
ids.set(key,row[0]);const value={stability:stability[row[2]],guard:fullDigest(row[1]??data.tables.duplicates[duplicate[0]][2])};resolvedMetadata.set(key,value);return value;
|
|
441
|
+
}
|
|
442
|
+
const metadata=new Map(Object.keys(identities).map(key=>[key,identity(key)]));
|
|
443
|
+
for(const scene of [data.baseline,...Object.values(data.additionalThemes)]){
|
|
444
|
+
sceneDefaults(scene,false,data.selection.fields);
|
|
445
|
+
for(const e of [...scene.context,...scene.elements]){
|
|
446
|
+
const [,guard,s,rawExtra={}]=identities[e.id],extra=Array.isArray(rawExtra)?{duplicate:rawExtra}:rawExtra,{duplicate,...rest}=extra;
|
|
447
|
+
if(!e.identity)e.identity=identities[e.id].length===2?resourceSlotIdentity(ids.get(identities[e.id][0]),identities[e.id][1],e.tag,e.namespace==='svg'?'http://www.w3.org/2000/svg':e.namespace==='html'?'http://www.w3.org/1999/xhtml':e.namespace).identity:{...metadata.get(e.id),...rest};
|
|
448
|
+
if(duplicate){const [group,count]=data.tables.duplicates[duplicate[0]];e.identity.duplicate={group:fullDigest(group),ordinal:duplicate[1],count};}
|
|
449
|
+
}
|
|
450
|
+
geometryScene(scene,false);
|
|
451
|
+
}
|
|
452
|
+
delete data.tables.identities;delete data.tables.duplicates;delete data.tables.a11y;delete data.tables.elementTypes;
|
|
453
|
+
data.tables.templates={};
|
|
454
|
+
for(const [key,value]of Object.entries(data.tables.values))data.tables.values[key]=typeof value==='string'?{css:value,attribution:'raw'}:{css:value[0],attribution:value[2]?'unresolved':'references',...(value[1].length?{refs:value[1]}:{}),...(value[2]?{reason:value[2]}:{})};
|
|
455
|
+
unpackStyles(data.tables.styles,data.tables.properties);delete data.tables.properties;
|
|
456
|
+
for(const ref of Object.values(data.tables.references))ref.basis??='authored_reference';
|
|
457
|
+
for(const resource of Object.values(data.tables.resources))if(resource.svg)resource.svg.definitions=resource.svg.geometry.filter(d=>['defs','linearGradient','radialGradient','mask','clipPath'].includes(d.tag));
|
|
458
|
+
data=addresses(data,ids,false);data.delta=null;data.encoding='expanded';return data;
|
|
459
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { frameDocument } from './frame-document.mjs';
|
|
2
|
+
import { loadFrame, readyResources, browserTask } from './browser.mjs';
|
|
3
|
+
import { installFramePrimitives, collectOwnerObservation } from './frame-observation.mjs';
|
|
4
|
+
import { installInspectFacets } from './frame-facets.mjs';
|
|
5
|
+
import { installColorResolver } from './owner-colors.mjs';
|
|
6
|
+
import { settleOwnerObservation } from './owner-observation.mjs';
|
|
7
|
+
import { styleDefaults } from './inspect-styles.mjs';
|
|
8
|
+
import { CliError } from '../cli-output.mjs';
|
|
9
|
+
|
|
10
|
+
export const inspectFacets = ['a11y','color','identity','layout','owner','structure','text','typography'];
|
|
11
|
+
|
|
12
|
+
/** One DOM protocol read + one AX protocol read, matched by backend node id. */
|
|
13
|
+
export async function observeAccessibility(page) {
|
|
14
|
+
const session=await page.context().newCDPSession(page);
|
|
15
|
+
try {
|
|
16
|
+
const [{root},{nodes}]=await Promise.all([session.send('DOM.getDocument',{depth:-1,pierce:true}),session.send('Accessibility.getFullAXTree')]);
|
|
17
|
+
let frame;
|
|
18
|
+
function find(node){const a=node.attributes??[];if(a.some((v,i)=>i%2===0&&v==='data-adg-frame'))frame=node;for(const child of node.children??[])find(child);}
|
|
19
|
+
find(root);
|
|
20
|
+
if(!frame)throw Error('Frame DOM node unavailable for accessibility.');
|
|
21
|
+
const ax=new Map(nodes.filter(n=>n.backendDOMNodeId).map(n=>[n.backendDOMNodeId,n])), result=[];
|
|
22
|
+
function visit(node){if(node.nodeType!==1)return;const value=ax.get(node.backendNodeId);
|
|
23
|
+
result.push({role:value&&!value.ignored?value.role?.value??null:null,name:value&&!value.ignored?value.name?.value??null:null,a11y:value?.ignored||!value?'ignored':'exposed'});
|
|
24
|
+
for(const child of node.children??[])visit(child);
|
|
25
|
+
}
|
|
26
|
+
visit(frame.children.find(n=>n.nodeType===1));return result;
|
|
27
|
+
} finally {await session.detach();}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function observeInspectFrame(index, source, built, frame, theme, environment, getPage, tokens, policy, { bypass=false, onLoad=()=>{} }={}) {
|
|
31
|
+
let loaded=false;
|
|
32
|
+
const collect=async()=>{
|
|
33
|
+
loaded=true;onLoad();const page=await getPage();
|
|
34
|
+
await loadFrame(page,{...frame,document:theme=>frameDocument(frame,theme,built.css)},theme);
|
|
35
|
+
return browserTask(page.context().browser(),async()=>{
|
|
36
|
+
await page.evaluate(readyResources);await page.evaluate(installColorResolver);await page.evaluate(installFramePrimitives);await page.evaluate(installInspectFacets);
|
|
37
|
+
let observed;
|
|
38
|
+
try {observed=await settleOwnerObservation(async()=>JSON.parse(await page.evaluate(collectOwnerObservation,{tokens,theme,rich:true,serialized:true,properties:Object.keys(styleDefaults)})),()=>page.evaluate(()=>new Promise(requestAnimationFrame)));}
|
|
39
|
+
catch(error){if(error.code==='OWNER_UNSETTLED')throw new CliError('INSPECT_UNSETTLED',error.message,{cause:error});throw error;}
|
|
40
|
+
try {
|
|
41
|
+
const a11y=await observeAccessibility(page);
|
|
42
|
+
if(a11y.length!==observed.rich.nodes.length)throw Error('AX/DOM node association changed.');
|
|
43
|
+
observed.rich.nodes.forEach((node,i)=>Object.assign(node,a11y[i]));
|
|
44
|
+
} catch(error) {
|
|
45
|
+
if(!page.context().browser().isConnected())throw error;
|
|
46
|
+
observed.rich.nodes.forEach(node=>Object.assign(node,{role:null,name:null,a11y:'unavailable'}));
|
|
47
|
+
observed.rich.limitations.push({code:'A11Y_UNAVAILABLE',path:'0',accuracy:'unavailable'});
|
|
48
|
+
}
|
|
49
|
+
const urls=[...new Set(observed.rich.nodes.flatMap(n=>n.backgrounds??[]))];
|
|
50
|
+
if(urls.length)observed.rich.backgroundDimensions=await page.evaluate(async urls=>Object.fromEntries(await Promise.all(urls.map(async url=>{const image=new Image();image.src=url;await image.decode();return [url,{width:image.naturalWidth,height:image.naturalHeight}];}))),urls);
|
|
51
|
+
return observed;
|
|
52
|
+
});
|
|
53
|
+
};
|
|
54
|
+
const value=bypass?await collect():await index.observation(source,built,frame,theme,environment,collect,{facets:inspectFacets,policy});
|
|
55
|
+
return {value,hit:!loaded};
|
|
56
|
+
}
|