@whzxc/agent-design-gallery 0.10.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 +3 -3
- package/package.json +1 -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 +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 +60 -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,169 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { resourceContentIdentity } from './part-snapshot.mjs';
|
|
3
|
+
import { elementIdentities } from './frame-identity.mjs';
|
|
4
|
+
import { styleDefaults } from './inspect-styles.mjs';
|
|
5
|
+
|
|
6
|
+
export const fieldGroups=['structure','layout','typography','color','text'];
|
|
7
|
+
const typography=/^(?:font-|line-height|letter-spacing|word-spacing|text-(?:align|indent|transform|decoration|underline|overflow)|white-space|word-break|overflow-wrap|vertical-align)/;
|
|
8
|
+
const color=/^(?:color|background-|opacity|border-|outline-|box-shadow|text-shadow|fill|stroke|stop-)/;
|
|
9
|
+
export const propertyGroup=name=>typography.test(name)?'typography':color.test(name)?'color':'layout';
|
|
10
|
+
const stable=value=>JSON.stringify(value);
|
|
11
|
+
const rawURL=value=>/^data:/i.test(value??'');
|
|
12
|
+
|
|
13
|
+
export function outputTables(data) {
|
|
14
|
+
const maps=Object.fromEntries(Object.keys(data.tables).map(k=>[k,new Map()]));
|
|
15
|
+
const next=Object.fromEntries(Object.keys(data.tables).map(k=>[k,0]));
|
|
16
|
+
return (table,value)=>{const key=stable(value),known=maps[table].get(key);if(known)return known;
|
|
17
|
+
const id=table[0]+next[table]++;maps[table].set(key,id);data.tables[table][id]=value;return id;};
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function projectInspection(data, observation, theme, config, intern, definitions) {
|
|
21
|
+
const {rich}=observation, idRows=elementIdentities(observation.identities,{source:data.frame.source,frame:data.frame.name});
|
|
22
|
+
const ids=new Map(idRows.map(row=>[row.path,row])), raw=new Map(rich.nodes.map(n=>[n.path,n]));
|
|
23
|
+
const selected=new Set(data.selection.fields), children=new Map(observation.identities.map(n=>[n.path,[]]));
|
|
24
|
+
for(const node of observation.identities)if(node.parentPath!==null)children.get(node.parentPath)?.push(node.path);
|
|
25
|
+
const parent=new Map(observation.identities.map(n=>[n.path,n.parentPath]));
|
|
26
|
+
const defineToken=name=>{
|
|
27
|
+
if(data.tables.tokens[name])return;
|
|
28
|
+
const token=definitions.find(t=>t.name===name);if(!token)return;
|
|
29
|
+
const light=token.values[0],dark=token.values[1];
|
|
30
|
+
data.tables.tokens[name]={source:token.source,line:light.line,declaration:light.declaration,resolved:theme==='light'?rich.palette[name]:null};
|
|
31
|
+
if(dark.declaration!==light.declaration||dark.line!==light.line)data.tables.tokens[name].dark={line:dark.line,declaration:dark.declaration};
|
|
32
|
+
for(const dep of new Set(token.values.flatMap(v=>v.references)))defineToken(dep);
|
|
33
|
+
};
|
|
34
|
+
const normalizeURLs=css=>css.replace(/url\(["']?(data:[^)'"\s]+)["']?\)/g,(_,url)=>{
|
|
35
|
+
const resource=intern('resources',{kind:/^data:image\/svg/i.test(url)?'svg':'raster',source:null,mime:url.match(/^data:([^;,]+)/)?.[1]??null,intrinsic:null,contentIdentity:resourceContentIdentity(url)});return 'url('+resource+')';
|
|
36
|
+
});
|
|
37
|
+
const propertyIndexes=new Map(rich.properties.map((p,i)=>[p,i])),projectedValues=new Map();
|
|
38
|
+
const styles=(values,geometry)=>{
|
|
39
|
+
const groups={layout:{},typography:{},color:{}};
|
|
40
|
+
const cssFor=p=>rich.valueFacts[values[propertyIndexes.get(p)]]?.css;
|
|
41
|
+
const inactive=cssFor('position')==='static',untransformed=['transform','rotate','scale','translate'].every(p=>!cssFor(p)||cssFor(p)==='none');
|
|
42
|
+
for(const [position,fact]of values.entries()){
|
|
43
|
+
const property=rich.properties[position],group=propertyGroup(property);
|
|
44
|
+
if(inactive&&['top','right','bottom','left'].includes(property)||untransformed&&property==='transform-origin')continue;
|
|
45
|
+
if(!selected.has(group) && !(selected.has('layout')&&/^border-.+-width$/.test(property)))continue;
|
|
46
|
+
const cacheKey=position+':'+fact;
|
|
47
|
+
if(!projectedValues.has(cacheKey)){
|
|
48
|
+
const value=rich.valueFacts[fact];
|
|
49
|
+
const refs=value.refs.map(ref=>{defineToken(ref.token);const record={...ref,property:ref.shorthand??property};delete record.shorthand;
|
|
50
|
+
if(!record.via.length)delete record.via;if(!record.inherited)delete record.inherited;
|
|
51
|
+
if(!record.localOverrides?.length)delete record.localOverrides;
|
|
52
|
+
return intern('references',record);});
|
|
53
|
+
const css=normalizeURLs(value.css),attribution=value.unresolved.length?'unresolved':refs.length?'references':'raw';
|
|
54
|
+
const result={css,attribution,...(refs.length?{refs}:{}),...(value.unresolved.length?{reason:value.unresolved.join(',')}:{})};
|
|
55
|
+
projectedValues.set(cacheKey,value.css===styleDefaults[property]&&attribution==='raw'?null:{key:intern('values',result),css:value.css,raw:attribution==='raw'});
|
|
56
|
+
}
|
|
57
|
+
const value=projectedValues.get(cacheKey);if(!value)continue;
|
|
58
|
+
const size=geometry?.layoutSize,measured=selected.has('layout')&&['width','height'].includes(property)&&size&&value.css===size[property]+'px'&&value.raw;
|
|
59
|
+
groups[group][property]=measured?'$'+property:value.key;
|
|
60
|
+
}
|
|
61
|
+
const keys=Object.values(groups).filter(g=>Object.keys(g).length).map(g=>intern('styles',g));return keys.length?keys:undefined;
|
|
62
|
+
};
|
|
63
|
+
const parts=new Map(), instanceRows=[];
|
|
64
|
+
const projectPart=owner=>({source:path.posix.join(path.relative(config.root,config.design).split(path.sep).join('/'),owner.source),export:owner.export});
|
|
65
|
+
for(const n of observation.identities){
|
|
66
|
+
const inherited=parts.get(n.parentPath)??null;let current=inherited;
|
|
67
|
+
for(const owner of n.owners){const part=intern('parts',projectPart(owner)),id=data.partInstances.find(i=>i.root===ids.get(n.path).id&&i.part===part)?.id??'i'+(data.partInstances.length+instanceRows.length);
|
|
68
|
+
const instance={id,part,root:ids.get(n.path).id,parent:current};instanceRows.push(instance);current=id;}
|
|
69
|
+
parts.set(n.path,current);
|
|
70
|
+
}
|
|
71
|
+
const resolveAttributes=attrs=>{
|
|
72
|
+
const result={...attrs};
|
|
73
|
+
for(const name of ['aria-labelledby','aria-describedby','for'])if(result[name]){
|
|
74
|
+
const targets=result[name].split(/\s+/).map(name=>rich.nodes.find(n=>n.attributes.id===name));
|
|
75
|
+
result[name]=targets.map((target,i)=>target?ids.get(target.path).id:attrs[name].split(/\s+/)[i]);
|
|
76
|
+
}
|
|
77
|
+
if(typeof result.href==='string'&&result.href.startsWith('#')){const target=rich.nodes.find(n=>n.attributes.id===result.href.slice(1));if(target)result.href='#'+ids.get(target.path).id;}
|
|
78
|
+
return result;
|
|
79
|
+
};
|
|
80
|
+
const elements=rich.nodes.map(n=>{
|
|
81
|
+
const row=ids.get(n.path),input=observation.identities.find(i=>i.path===n.path);
|
|
82
|
+
const element={id:row.id,identity:row.identity,tag:n.tag,namespace:n.namespace==='http://www.w3.org/1999/xhtml'?'html':n.namespace==='http://www.w3.org/2000/svg'?'svg':n.namespace,parent:ids.get(parent.get(n.path))?.id??null,children:children.get(n.path).map(p=>ids.get(p).id)};
|
|
83
|
+
if(selected.has('structure'))Object.assign(element,{role:n.role,name:n.name,a11y:n.a11y,attributes:resolveAttributes({...n.attributes,...Object.fromEntries(Object.entries(n.svgAttributes??{}).filter(([,v])=>!rawURL(v)))}),...(parts.get(n.path)?{owner:parts.get(n.path)}:{}),...(input.owners.length?{markers:input.owners.map(o=>intern('parts',projectPart(o)))}:{})});
|
|
84
|
+
const style=styles(n.values,n.geometry);if(style)element.style=style;
|
|
85
|
+
if(selected.has('layout'))element.geometry=n.geometry;
|
|
86
|
+
if(Object.keys(n.effects).length)element.effects=n.effects;
|
|
87
|
+
if(n.pseudo.length)element.pseudo=n.pseudo.map(p=>({id:element.id+'::'+p.kind,kind:p.kind,content:normalizeURLs(p.content),...(selected.has('layout')?{geometry:p.geometry}:{}),...(styles(p.values)?{style:styles(p.values)}:{})}));
|
|
88
|
+
if(n.resource){const r=n.resource;
|
|
89
|
+
const mime=r.url?.match(/^data:([^;,]+)/)?.[1]??(r.kind==='svg'||r.kind==='icon'?'image/svg+xml':null);
|
|
90
|
+
const resource={kind:mime==='image/svg+xml'&&r.kind==='raster'?'svg':r.kind,source:r.source?path.posix.join(path.relative(config.root,config.design).split(path.sep).join('/'),r.source):null,mime,intrinsic:r.intrinsic};
|
|
91
|
+
if(r.url)resource.contentIdentity=resourceContentIdentity(r.url);
|
|
92
|
+
if(!rawURL(r.url)&&r.url)resource.url=r.url;
|
|
93
|
+
if(r.icon)resource.icon={library:'lucide',name:r.icon,viewBox:r.viewBox};
|
|
94
|
+
if(r.kind==='svg'||r.kind==='icon'){
|
|
95
|
+
const descendants=[];const visit=p=>{descendants.push(raw.get(p));for(const c of children.get(p))visit(c);};visit(n.path);
|
|
96
|
+
const local=new Map(descendants.map((d,i)=>[d.path,'g'+i]));
|
|
97
|
+
const named=new Map(descendants.filter(d=>d.svgAttributes?.id).map(d=>[d.svgAttributes.id,local.get(d.path)]));
|
|
98
|
+
const geometry=descendants.map(d=>({id:local.get(d.path),tag:d.tag,attributes:Object.fromEntries(Object.entries(d.svgAttributes??{}).filter(([k])=>k!=='id').map(([k,v])=>[k,rawURL(v)?'embedded':v.replace(/url\(#([^)]+)\)|^#(.+)$/g,(_,a,b)=>a?'url(#'+(named.get(a)??a)+')':'#'+(named.get(b)??b))])),children:children.get(d.path).filter(p=>local.has(p)).map(p=>local.get(p))}));
|
|
99
|
+
resource.svg={viewBox:r.viewBox,geometry,definitions:geometry.filter(d=>['defs','linearGradient','radialGradient','mask','clipPath'].includes(d.tag))};
|
|
100
|
+
}
|
|
101
|
+
element.resource=intern('resources',resource);
|
|
102
|
+
}
|
|
103
|
+
if(n.backgrounds?.length)element.backgrounds=n.backgrounds.map(url=>intern('resources',{kind:/^data:image\/svg/i.test(url)?'svg':'raster',source:null,mime:url.match(/^data:([^;,]+)/)?.[1]??null,intrinsic:rich.backgroundDimensions?.[url]??null,contentIdentity:resourceContentIdentity(url),...(!rawURL(url)?{url}:{})}));
|
|
104
|
+
return element;
|
|
105
|
+
});
|
|
106
|
+
const byId=new Map(elements.map(e=>[e.id,e]));
|
|
107
|
+
const runs=rich.runs.map(run=>{
|
|
108
|
+
const element=ids.get(run.path).id,pseudo=run.pseudo?element+'::'+run.pseudo:element;
|
|
109
|
+
const owner=byId.get(element),style=run.pseudo?owner.pseudo?.find(p=>p.id===pseudo)?.style:owner.style;
|
|
110
|
+
return {id:pseudo+'/text-'+run.slot,kind:run.kind,element:pseudo,raw:run.raw,normalized:run.normalized,...(style?{style}:{}),fragments:[{element:pseudo,start:0,end:run.raw.length,boxes:run.boxes,accuracy:run.accuracy}]};
|
|
111
|
+
});
|
|
112
|
+
let matches=[];const query=data.selection.subtree;
|
|
113
|
+
if(!query)matches=elements.slice(0,1).map(n=>({element:n.id,themes:[theme]}));
|
|
114
|
+
else if(query.kind==='element'){
|
|
115
|
+
const node=byId.get(query.input)??elements.find(e=>e.pseudo?.some(p=>p.id===query.input));
|
|
116
|
+
if(node)matches=[{element:node.id,themes:[theme]}];
|
|
117
|
+
} else if(query.kind==='part'){
|
|
118
|
+
const [source,exp]=[query.input.slice(0,query.input.lastIndexOf('#')),query.input.slice(query.input.lastIndexOf('#')+1)];
|
|
119
|
+
matches=instanceRows.filter(i=>data.tables.parts[i.part].source===source&&data.tables.parts[i.part].export===exp).map(i=>({element:i.root,themes:[theme]}));
|
|
120
|
+
} else {
|
|
121
|
+
const normalized=query.input.normalize('NFC').replace(/\p{White_Space}+/gu,' ').trim();
|
|
122
|
+
matches=runs.filter(r=>{const node=byId.get(r.element.replace(/::(?:before|after|marker|placeholder)$/,''));return !['hidden','not_laid_out','clipped'].includes(raw.get(idRows.find(n=>n.id===node?.id)?.path)?.geometry.visibility)&& (query.contains?r.normalized.includes(normalized):r.normalized===normalized);}).map(r=>({element:r.element.replace(/::(?:before|after|marker|placeholder)$/,''),themes:[theme],runs:[r.id]}));
|
|
123
|
+
const grouped=[];
|
|
124
|
+
for(let i=0;i<rich.runs.length;i++){const original=rich.runs[i],run=runs[i];if(run.kind!=='dom'||['hidden','not_laid_out','clipped'].includes(raw.get(original.path)?.geometry.visibility))continue;
|
|
125
|
+
if(grouped.at(-1)?.group!==original.group)grouped.push({group:original.group,runs:[]});grouped.at(-1).runs.push(run);
|
|
126
|
+
}
|
|
127
|
+
for(const group of grouped){const text=group.runs.map(r=>r.raw).join('').normalize('NFC').replace(/\p{White_Space}+/gu,' ').trim();
|
|
128
|
+
if((query.contains?text.includes(normalized):text===normalized)&&!['hidden','not_laid_out','clipped'].includes(raw.get(group.group)?.geometry.visibility)){
|
|
129
|
+
const id=ids.get(group.group)?.id;if(id)matches.push({element:id,themes:[theme],runs:group.runs.map(r=>r.id)});
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
matches=[...new Map(matches.map(m=>[m.element,m])).values()];
|
|
134
|
+
const matched=new Set(matches.map(m=>m.element));
|
|
135
|
+
const roots=matches.filter(m=>{for(let n=byId.get(m.element)?.parent;n;n=byId.get(n)?.parent)if(matched.has(n))return false;return true;}).map(m=>m.element);
|
|
136
|
+
const scope=new Set(), included=new Set(), context=new Set();
|
|
137
|
+
const descend=(id,depth)=>{scope.add(id);if(data.selection.depth===null||depth<=data.selection.depth)included.add(id);for(const child of byId.get(id).children)descend(child,depth+1);};
|
|
138
|
+
for(const id of roots){descend(id,0);for(let n=byId.get(id)?.parent;n;n=byId.get(n)?.parent)context.add(n);}
|
|
139
|
+
let emitted=elements.filter(e=>included.has(e.id)).map(e=>{
|
|
140
|
+
const children=e.children.filter(id=>included.has(id));const result={...e,children};
|
|
141
|
+
if(children.length!==e.children.length){let count=0;const countAll=id=>{count++;byId.get(id).children.forEach(countAll);};e.children.forEach(countAll);result.cutoff={descendants:count};}
|
|
142
|
+
return result;
|
|
143
|
+
});
|
|
144
|
+
const emittedRuns=selected.has('text')?runs.filter((r,i)=>included.has(r.element.replace(/::(?:before|after|marker|placeholder)$/, '')) && (query?.kind==='element'||raw.get(rich.runs[i].path)?.geometry.visibility!=='not_laid_out')):[];
|
|
145
|
+
for(const run of emittedRuns){const owner=emitted.find(e=>e.id===run.element);const target=owner??emitted.flatMap(e=>e.pseudo??[]).find(p=>p.id===run.element);if(target)(target.text??=[]).push(run.id);}
|
|
146
|
+
const limitations=rich.limitations.filter(l=>included.has(ids.get(l.path)?.id)).map(l=>({...l,element:ids.get(l.path)?.id,theme}));
|
|
147
|
+
let collapsed=0;
|
|
148
|
+
if(data.selection.wrappers==='semantic'){
|
|
149
|
+
for(const e of [...emitted].reverse()){
|
|
150
|
+
const input=observation.identities[idRows.findIndex(r=>r.id===e.id)],child=emitted.find(n=>n.id===e.children[0]);
|
|
151
|
+
if(!input?.neutral||roots.includes(e.id)||!child||e.children.length!==1||e.role||e.name||Object.keys(e.attributes??{}).length||e.owner!==child.owner||e.pseudo||e.resource||e.effects||e.geometry?.scroll||JSON.stringify(e.geometry?.box)!==JSON.stringify(child.geometry?.box))continue;
|
|
152
|
+
const above=emitted.find(n=>n.id===e.parent);if(!above)continue;
|
|
153
|
+
above.children=above.children.flatMap(id=>id===e.id?e.children:[id]);child.parent=e.parent;emitted=emitted.filter(n=>n!==e);collapsed++;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
const scene={roots,context:elements.filter(e=>context.has(e.id)).map(e=>({...e,children:e.children.filter(id=>context.has(id)||included.has(id))})),elements:emitted,instances:[],runs:emittedRuns,size:rich.size};
|
|
157
|
+
return {scene,matches,limitations,instanceRows:instanceRows.filter(i=>included.has(i.root)||[...context].some(id=>id===i.root)),counts:{raw:scope.size,retained:scope.size-collapsed,collapsed,logical:included.size-collapsed,cutOff:scope.size-included.size,runs:emittedRuns.length}};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function pruneTables(data) {
|
|
161
|
+
const used=Object.fromEntries(Object.keys(data.tables).map(k=>[k,new Set()]));
|
|
162
|
+
const useStyle=keys=>{for(const key of keys??[]){if(used.styles.has(key))continue;used.styles.add(key);for(const value of Object.values(data.tables.styles[key])){if(value.startsWith('$'))continue;used.values.add(value);for(const m of data.tables.values[value].css.matchAll(/url\((r\d+)\)/g))used.resources.add(m[1]);for(const r of data.tables.values[value].refs??[]){used.references.add(r);used.tokens.add(data.tables.references[r].token);}}}};
|
|
163
|
+
for(const scene of [data.baseline,...Object.values(data.additionalThemes)].filter(Boolean))for(const e of [...scene.context,...scene.elements]){
|
|
164
|
+
useStyle(e.style);for(const p of e.pseudo??[]){useStyle(p.style);for(const m of p.content.matchAll(/url\((r\d+)\)/g))used.resources.add(m[1]);}if(e.resource)used.resources.add(e.resource);for(const r of e.backgrounds??[])used.resources.add(r);for(const p of e.markers??[])used.parts.add(p);
|
|
165
|
+
}
|
|
166
|
+
for(const i of data.partInstances)used.parts.add(i.part);
|
|
167
|
+
for(const name of used.tokens){const token=data.tables.tokens[name];for(const value of [token?.declaration,token?.dark?.declaration])for(const match of value?.matchAll(/var\(\s*(--[\w-]+)/g)??[])used.tokens.add(match[1]);}
|
|
168
|
+
for(const table of Object.keys(data.tables))for(const key of Object.keys(data.tables[table]))if(!used[table].has(key))delete data.tables[table][key];
|
|
169
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** inspectVersion 1: concrete CSS defaults, independent of the host font palette. */
|
|
2
|
+
export const inspectVersion = 1;
|
|
3
|
+
const sides = ['top','right','bottom','left'];
|
|
4
|
+
const corners = ['top-left','top-right','bottom-right','bottom-left'];
|
|
5
|
+
const entries = (names,value) => Object.fromEntries(names.map(name=>[name,value]));
|
|
6
|
+
export const styleDefaults = Object.freeze({
|
|
7
|
+
display:'inline', position:'static', ...entries(sides,'auto'), 'box-sizing':'content-box',
|
|
8
|
+
width:'auto',height:'auto','min-width':'auto','min-height':'auto','max-width':'none','max-height':'none',
|
|
9
|
+
'flex-direction':'row','flex-wrap':'nowrap','flex-grow':'0','flex-shrink':'1','flex-basis':'auto',
|
|
10
|
+
'justify-content':'normal','align-items':'normal','align-self':'auto','align-content':'normal',order:'0',
|
|
11
|
+
'row-gap':'normal','column-gap':'normal','grid-template-columns':'none','grid-template-rows':'none',
|
|
12
|
+
'grid-auto-flow':'row','grid-auto-columns':'auto','grid-auto-rows':'auto',
|
|
13
|
+
...entries(['grid-row-start','grid-row-end','grid-column-start','grid-column-end'],'auto'),
|
|
14
|
+
...entries(sides.flatMap(side=>[`margin-${side}`,`padding-${side}`]),'0px'),
|
|
15
|
+
'overflow-x':'visible','overflow-y':'visible',visibility:'visible','z-index':'auto',
|
|
16
|
+
transform:'none','transform-origin':'50% 50%',translate:'none',rotate:'none',scale:'none',direction:'ltr','writing-mode':'horizontal-tb',
|
|
17
|
+
'font-family':'serif','font-size':'16px','font-weight':'400','font-style':'normal','font-stretch':'100%',
|
|
18
|
+
'line-height':'normal','letter-spacing':'normal','word-spacing':'0px','font-feature-settings':'normal',
|
|
19
|
+
'font-variation-settings':'normal','font-kerning':'auto','text-align':'start','text-indent':'0px',
|
|
20
|
+
'text-transform':'none','text-decoration-line':'none','text-decoration-style':'solid',
|
|
21
|
+
'text-decoration-thickness':'auto','text-underline-offset':'auto','white-space':'normal','word-break':'normal',
|
|
22
|
+
'overflow-wrap':'normal','text-overflow':'clip','vertical-align':'baseline',
|
|
23
|
+
color:'rgb(0, 0, 0)','background-color':'rgba(0, 0, 0, 0)','background-image':'none',
|
|
24
|
+
'background-size':'auto','background-position':'0% 0%','background-repeat':'repeat','background-clip':'border-box',opacity:'1',
|
|
25
|
+
...entries(sides.map(side=>`border-${side}-color`),'rgb(0, 0, 0)'),
|
|
26
|
+
...entries(sides.map(side=>`border-${side}-style`),'none'), ...entries(sides.map(side=>`border-${side}-width`),'0px'),
|
|
27
|
+
...entries(corners.map(corner=>`border-${corner}-radius`),'0px'),
|
|
28
|
+
'outline-color':'rgb(0, 0, 0)','outline-style':'none','outline-width':'0px','outline-offset':'0px',
|
|
29
|
+
'box-shadow':'none','text-shadow':'none',fill:'rgb(0, 0, 0)','fill-opacity':'1',stroke:'none','stroke-width':'1px',
|
|
30
|
+
'stroke-opacity':'1','stroke-dasharray':'none','stroke-dashoffset':'0px','stroke-linecap':'butt','stroke-linejoin':'miter',
|
|
31
|
+
'fill-rule':'nonzero','stop-color':'rgb(0, 0, 0)','stop-opacity':'1',
|
|
32
|
+
});
|
|
33
|
+
export function expandStyle(style={}) { return {...styleDefaults,...style}; }
|
|
34
|
+
export function compactStyle(style) {return Object.fromEntries(Object.entries(style).filter(([name,value])=>styleDefaults[name]!==value));}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
export type Theme = 'light' | 'dark';
|
|
2
|
+
export type FieldGroup = 'structure' | 'layout' | 'typography' | 'color' | 'text';
|
|
3
|
+
export interface Box { x:number; y:number; width:number; height:number }
|
|
4
|
+
export interface Geometry {
|
|
5
|
+
box:Box|null; visibility:'visible'|'partial'|'clipped'|'hidden'|'not_laid_out';
|
|
6
|
+
clientRects?:Box[]; layoutSize?:{width:number;height:number}; visibleBox?:Box|null;
|
|
7
|
+
clip?:Box; clipAccuracy?:'rect'|'bounds';
|
|
8
|
+
scroll?:{x:number;y:number;width:number;height:number;clientWidth:number;clientHeight:number};
|
|
9
|
+
}
|
|
10
|
+
export interface Identity {
|
|
11
|
+
stability:'authored'|'semantic'|'positional'|'resource'; guard:string; anchor?:string; key?:string|number;
|
|
12
|
+
duplicate?:{group:string;ordinal:number;count:number}; slot?:number;
|
|
13
|
+
}
|
|
14
|
+
export interface Element {
|
|
15
|
+
id:string; identity:Identity; tag:string; namespace:string; parent:string|null; children:string[];
|
|
16
|
+
role?:string|null; name?:string|null; a11y?:'exposed'|'ignored'|'unavailable';
|
|
17
|
+
attributes?:Record<string,string|boolean|number|string[]>; owner?:string; markers?:string[];
|
|
18
|
+
style?:string[]; geometry?:Geometry; text?:string[]; resource?:string; backgrounds?:string[];
|
|
19
|
+
effects?:Record<string,string>; cutoff?:{descendants:number};
|
|
20
|
+
pseudo?:{id:string;kind:'before'|'after'|'marker'|'placeholder';content:string;style?:string[];geometry?:Geometry;text?:string[]}[];
|
|
21
|
+
}
|
|
22
|
+
export interface TextRun {
|
|
23
|
+
id:string;kind:'dom'|'control'|'pseudo';element:string;raw:string;normalized:string;style?:string[];
|
|
24
|
+
fragments:{element:string;start:number;end:number;boxes:Box[];accuracy:'range'|'control_box'|'owner_box'}[];
|
|
25
|
+
}
|
|
26
|
+
export interface Scene { roots:string[];context:Element[];elements:Element[];instances:never[];runs:TextRun[];size:{width:number;height:number} }
|
|
27
|
+
export interface Reference {
|
|
28
|
+
property:string;token:string;kind:'direct'|'alias'|'fallback';
|
|
29
|
+
expression:string;via?:string[];inherited?:true;basis:'authored_reference'|'inline';
|
|
30
|
+
localOverrides?:{name:string;declaration:string}[];
|
|
31
|
+
}
|
|
32
|
+
export interface Value { css:string;attribution:'raw'|'references'|'unresolved';refs?:string[];reason?:string }
|
|
33
|
+
export interface Token {
|
|
34
|
+
source:string;line:number;declaration:string;resolved:string|null;
|
|
35
|
+
dark?:{line?:number;declaration?:string;resolved?:string|null};
|
|
36
|
+
}
|
|
37
|
+
export interface Resource {
|
|
38
|
+
kind:'icon'|'svg'|'raster'|'opaque';source:string|null;mime:string|null;
|
|
39
|
+
intrinsic:{width:number;height:number}|null;contentIdentity?:string;url?:string;
|
|
40
|
+
icon?:{library:'lucide';name:string;viewBox:string};
|
|
41
|
+
svg?:{viewBox:string|null;geometry:SVGNode[];definitions:SVGNode[]};
|
|
42
|
+
}
|
|
43
|
+
export interface SVGNode {id:string;tag:string;attributes:Record<string,string>;children:string[]}
|
|
44
|
+
export interface InspectCommon {
|
|
45
|
+
inspectVersion:1;identityVersion:1;project:string;complete:boolean;mode:'catalog'|'frame';
|
|
46
|
+
selection:{source:string|null;frame:string|null;themes:Theme[];subtree:null|{kind:'part'|'element'|'text';input:string;contains:boolean};depth:number|null;fields:FieldGroup[];wrappers:'semantic'|'all';expand:boolean};
|
|
47
|
+
catalog:{source:string;frames:{name:string;locale:string|null;width:number|null;height:number|null}[]}[];
|
|
48
|
+
frame:{source:string;name:string;locale:string|null;authored:{width:number|null;height:number|null};parent:{source:string;frame:string;selector:string}|null}|null;
|
|
49
|
+
baselineTheme:Theme|null;
|
|
50
|
+
matches:{element:string;themes:Theme[];runs?:string[]}[];
|
|
51
|
+
limitations:{code:string;count:number;elements:string[];properties:string[];themes:Theme[];accuracy:'exact'|'bounds'|'unavailable'}[];
|
|
52
|
+
coverage:{domain:'tsx';discoveredSources:number;listedFrames:number;requestedObservations:number;completedObservations:number;rawElements:number;retainedElements:number;collapsedElements:number;cutOffElements:number;logicalElements:number;runs:number;cacheHits:number;frameLoads:number;materializedSources:number};
|
|
53
|
+
timings:{prepareMs:number;materializeMs:number;observeMs:number;projectMs:number;totalMs:number};
|
|
54
|
+
}
|
|
55
|
+
export interface ExpandedInspectData extends InspectCommon {
|
|
56
|
+
encoding:'expanded';baseline:Scene|null;delta:null;additionalThemes:Partial<Record<Theme,Scene>>;
|
|
57
|
+
tables:{values:Record<string,Value>;styles:Record<string,Record<string,string>>;tokens:Record<string,Token>;references:Record<string,Reference>;parts:Record<string,{source:string;export:string}>;templates:Record<string,never>;resources:Record<string,Resource>};
|
|
58
|
+
partInstances:{id:string;part:string;root:string;parent:string|null}[];
|
|
59
|
+
}
|
|
60
|
+
export type BoxTuple=[x:number,y:number,width:number,height:number];
|
|
61
|
+
export type LocalAddress=number|string;
|
|
62
|
+
export interface CompactGeometry {
|
|
63
|
+
box:BoxTuple|null;visibility?:Geometry['visibility'];clientRects?:BoxTuple[];
|
|
64
|
+
visibleBox?:BoxTuple|null;clip?:BoxTuple;clipAccuracy?:'rect'|'bounds';
|
|
65
|
+
layoutSize?:[width:number,height:number];scroll?:Geometry['scroll'];
|
|
66
|
+
}
|
|
67
|
+
export interface CompactExtra {
|
|
68
|
+
owner?:number|null;markers?:number[];attributes?:Record<string,unknown>;
|
|
69
|
+
resource?:number;backgrounds?:number[];effects?:Record<string,string>;cutoff?:{descendants:number};
|
|
70
|
+
identity?:Identity;text?:string[];
|
|
71
|
+
pseudo?:{id:string;kind:'before'|'after'|'marker'|'placeholder';content:string;style?:number[];geometry?:Geometry;text?:string[]}[];
|
|
72
|
+
}
|
|
73
|
+
// type indexes tables.elementTypes; styles indexes per-group records, not one monolithic style.
|
|
74
|
+
export type CompactElement=[id:number,type:number,children:number[],styles:number[]|null,geometry:BoxTuple|CompactGeometry|null,extra?:CompactExtra];
|
|
75
|
+
export interface CompactRun {
|
|
76
|
+
element:LocalAddress;slot:string;raw:string;normalized?:string;kind?:TextRun['kind'];style?:number[];
|
|
77
|
+
boxes?:Box[];accuracy?:'control_box'|'owner_box';fragments?:TextRun['fragments'];
|
|
78
|
+
}
|
|
79
|
+
export interface CompactInstance {at:number;template:string;ids:number[];origin:[number,number];parent:number|null;owner?:number}
|
|
80
|
+
export interface CompactScene {
|
|
81
|
+
roots:number[];context:CompactElement[];elements:CompactElement[];runs:CompactRun[];
|
|
82
|
+
instances:CompactInstance[];size:{width:number;height:number};runOrder?:string[];
|
|
83
|
+
}
|
|
84
|
+
export type StylePairs=(number|'$width'|'$height')[];
|
|
85
|
+
export interface NodeDelta {
|
|
86
|
+
added?:CompactElement[];removed?:number[];
|
|
87
|
+
changed?:({id:number;unset?:string[]}&Partial<Record<'1'|'2'|'3'|'4'|'5',unknown>>)[];
|
|
88
|
+
styles?:number[][]; // [element, group position, new style, ...]
|
|
89
|
+
order?:number[];
|
|
90
|
+
}
|
|
91
|
+
export interface CompactDelta {
|
|
92
|
+
theme:Theme;elements?:NodeDelta;context?:NodeDelta;
|
|
93
|
+
runs?:{added?:CompactRun[];removed?:string[];changed?:({id:string;unset?:string[]}&Partial<CompactRun>)[];order?:string[]};
|
|
94
|
+
roots?:number[];size?:{width:number;height:number};instances?:CompactInstance[];
|
|
95
|
+
}
|
|
96
|
+
export type CompactIdentity=[elementId:string,guard:string|null,stability:0|1|2|3,extra?:[group:number,ordinal:number]|{anchor?:string;key?:string|number;duplicate?:[number,number]}]|[resourceRoot:number,slot:number];
|
|
97
|
+
export interface CompactTables {
|
|
98
|
+
properties:string[];
|
|
99
|
+
values:(string|[css:string,refs:number[],reason?:string])[];
|
|
100
|
+
styles:(StylePairs|[base:[number],set:StylePairs,unset?:number[]])[];
|
|
101
|
+
references:[token:string,property:number,flags:number,extra?:{expression?:string;via?:string[];localOverrides?:[string,string][];basis?:string}][];
|
|
102
|
+
tokens:Record<string,[line:number,declaration:string,extra?:{source?:string;resolved?:string|null;dark?:Token['dark']}]>;tokenSource?:string;
|
|
103
|
+
parts:{source:string;export:string}[];
|
|
104
|
+
resources:(Omit<Resource,'mime'|'svg'>&{mime?:string|null;svg?:{viewBox:string|null;geometry:[tag:string,attributes:Record<string,string>,children:string[]][]}})[];
|
|
105
|
+
identities:CompactIdentity[];duplicates?:[digest:string,count:number,guard?:string][];
|
|
106
|
+
a11y:[role:string|null,name:string|null,status:'exposed'|'ignored'|'unavailable'][];
|
|
107
|
+
elementTypes:[tag:string,a11y:number|null,namespace?:string][];
|
|
108
|
+
templates:Record<string,Omit<CompactScene,'roots'|'size'>>;
|
|
109
|
+
}
|
|
110
|
+
export interface CompactInspectData extends Omit<InspectCommon,'matches'|'limitations'> {
|
|
111
|
+
mode:'frame';encoding:'compact';baseline:CompactScene;delta:CompactDelta|null;tables:CompactTables;
|
|
112
|
+
partInstances:[part:number,root:number,parent:number|null][];
|
|
113
|
+
matches:{element:number;themes:Theme[];runs?:string[]}[];
|
|
114
|
+
limitations:(Omit<InspectCommon['limitations'][number],'elements'>&{elements:number[]})[];
|
|
115
|
+
}
|
|
116
|
+
export type InspectData=ExpandedInspectData|CompactInspectData;
|
|
117
|
+
export function inspect(config:object,args?:string[],values?:Record<string,string|boolean>,options?:object):Promise<{data:InspectData;warnings:{code:string;message:string;next:{argv:string[];reason:string}[]}[]}>;
|
|
118
|
+
export function inspectText(data:InspectData):string;
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { CliError, nextActions } from '../cli-output.mjs';
|
|
3
|
+
import { openProjectIndex } from './project-index.mjs';
|
|
4
|
+
import { selectSources, relative } from './project.mjs';
|
|
5
|
+
import { observationEnvironment } from './owner-observation.mjs';
|
|
6
|
+
import { launch, browserTask } from './browser.mjs';
|
|
7
|
+
import { observeInspectFrame } from './inspect-observation.mjs';
|
|
8
|
+
import { outputTables, projectInspection, pruneTables, fieldGroups } from './inspect-output.mjs';
|
|
9
|
+
import { compactInspection, expandInspection } from './inspect-encoding.mjs';
|
|
10
|
+
import { createEligibilityChecker } from './impact-eligibility.mjs';
|
|
11
|
+
import { canonicalBytes, capturePolicy } from './impact-proof.mjs';
|
|
12
|
+
import { frameDocument } from './frame-document.mjs';
|
|
13
|
+
import { configInputFiles, inputBytes, trackedHash, verifyInputGeneration } from './input-generation.mjs';
|
|
14
|
+
import { commandFailure, cleanup } from './results.mjs';
|
|
15
|
+
|
|
16
|
+
export function inspectSelection(values) {
|
|
17
|
+
const subtree=['part','element','text'].find(k=>values[k]!==undefined);
|
|
18
|
+
return {source:null,frame:values.frame??null,themes:values.theme&&values.theme!=='both'?[values.theme]:['light','dark'],
|
|
19
|
+
subtree:subtree?{kind:subtree,input:values[subtree],contains:!!values.contains}:null,
|
|
20
|
+
depth:values.depth===undefined||values.depth==='all'?null:Number(values.depth),
|
|
21
|
+
fields:values.fields?fieldGroups.filter(k=>values.fields.split(',').includes(k)):[...fieldGroups],wrappers:values.wrappers??'semantic',expand:!!values.expand};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function inspect(config, args=[], values={}, {log=console.log, openIndex=openProjectIndex, launchBrowser=launch, environment=observationEnvironment}={}) {
|
|
25
|
+
const resolvedConfig=canonicalBytes(config);
|
|
26
|
+
const start=performance.now(),selection=inspectSelection(values),warnings=[],tracked=new Map();
|
|
27
|
+
let data={inspectVersion:1,identityVersion:1,project:config.root,complete:false,mode:'catalog',encoding:'expanded',selection,catalog:[],frame:null,
|
|
28
|
+
baselineTheme:null,baseline:null,delta:null,additionalThemes:{},tables:{values:{},styles:{},tokens:{},references:{},parts:{},templates:{},resources:{}},partInstances:[],matches:[],limitations:[],
|
|
29
|
+
coverage:{domain:'tsx',discoveredSources:0,listedFrames:0,requestedObservations:0,completedObservations:0,rawElements:0,retainedElements:0,collapsedElements:0,cutOffElements:0,logicalElements:0,runs:0,cacheHits:0,frameLoads:0,materializedSources:0},
|
|
30
|
+
timings:{prepareMs:0,materializeMs:0,observeMs:0,projectMs:0,totalMs:0}};
|
|
31
|
+
let index,browser,page,primary;
|
|
32
|
+
const warn=(code,message,next=[])=>{if(!warnings.some(w=>w.code===code))warnings.push({code,message,next});};
|
|
33
|
+
const retry=(reason,full=false)=>nextActions(full?'INSPECT_ELEMENT_NOT_FOUND':'INSPECT_UNSETTLED',{command:'inspect',values,positionals:args}).map(n=>({...n,reason}));
|
|
34
|
+
const timed=async(key,fn)=>{const begin=performance.now();try{return await fn();}finally{data.timings[key]+=performance.now()-begin;}};
|
|
35
|
+
const getPage=async()=>{browser??=await launchBrowser();page??=await browserTask(browser,()=>browser.newPage({locale:'en-US',timezoneId:'UTC',deviceScaleFactor:1}));return page;};
|
|
36
|
+
try {
|
|
37
|
+
const files=await configInputFiles(config),configInputs=new Set(files.map(f=>relative(config,f)));
|
|
38
|
+
for(const file of [...files,path.join(config.design,'tokens.css')])tracked.set(file,trackedHash(await inputBytes(file)));
|
|
39
|
+
index=await openIndex(config,{stateDirectory:values['state-dir'],fresh:true});data.coverage.discoveredSources=index.inventory.tsx.length;
|
|
40
|
+
let sources=index.inventory.tsx;
|
|
41
|
+
await timed('prepareMs',async()=>{
|
|
42
|
+
if(args.length){
|
|
43
|
+
if(/\.(?:mmd|svg|png|jpe?g|webp)$/.test(args[0]))throw new CliError('INSPECT_SOURCE_UNSUPPORTED','Choose a discovered TSX source.');
|
|
44
|
+
const selected=selectSources(config,args,{write:false});
|
|
45
|
+
if(selected.length!==1||!selected[0].endsWith('.tsx'))throw new CliError('INSPECT_SOURCE_UNSUPPORTED','Choose one TSX entry, not a source directory.');
|
|
46
|
+
sources=[relative(config,selected[0])];selection.source=sources[0];
|
|
47
|
+
}
|
|
48
|
+
const facts=await Promise.all(sources.map(async source=>{try{return args.length?await timed('materializeMs',()=>index.source(source,{fresh:true})):await index.source(source);}catch(cause){throw cause instanceof CliError?cause:new CliError('SOURCE_BUILD_FAILED',cause.message,{cause});}}));
|
|
49
|
+
data.catalog=facts.map(f=>({source:f.source,frames:f.frames.map(f=>({name:f.name,locale:f.locale??null,proposed:f.proposed??null,width:f.width??null,height:f.height??null}))}));
|
|
50
|
+
data.coverage.listedFrames=data.catalog.reduce((n,s)=>n+s.frames.length,0);
|
|
51
|
+
});
|
|
52
|
+
if(args.length)data.timings.prepareMs-=data.timings.materializeMs;
|
|
53
|
+
const candidates=data.catalog.flatMap(s=>s.frames.filter(f=>!values.frame||f.name===values.frame).map(f=>({source:s.source,frame:f.name})));
|
|
54
|
+
if(values.frame && !candidates.length)throw new CliError('FRAME_NOT_FOUND',`Unknown frame ${values.frame}.`);
|
|
55
|
+
if(values.frame && candidates.length>1)throw new CliError('INSPECT_FRAME_AMBIGUOUS',`Frame ${values.frame} occurs in ${candidates.length} sources: ${candidates.map(c=>c.source).join(', ')}.`,{context:{inspectSources:candidates.map(c=>c.source)}});
|
|
56
|
+
if(!values.frame && candidates.length!==1){
|
|
57
|
+
if(['theme','part','element','text','contains','depth','fields','wrappers','expand'].some(k=>values[k]!==undefined))throw new CliError('USAGE_INVALID','Choose a unique frame before setting frame-only options.',{context:{inspectCatalog:true}});
|
|
58
|
+
if(!candidates.length)warn('EMPTY_SELECTION','No TSX frames were discovered.');
|
|
59
|
+
} else {
|
|
60
|
+
const chosen=candidates[0];selection.source=chosen.source;selection.frame=chosen.frame;
|
|
61
|
+
const built=await timed('materializeMs',async()=>{try{return await index.materialize(chosen.source);}catch(cause){throw cause instanceof CliError?cause:new CliError('SOURCE_BUILD_FAILED',cause.message,{cause});}});data.coverage.materializedSources=1;await index.releaseMaterializers();
|
|
62
|
+
const frame=built.frames.find(f=>f.name===chosen.frame);
|
|
63
|
+
if(!frame)throw new CliError('INSPECT_INPUT_CHANGED','The selected frame disappeared during fresh execution.');
|
|
64
|
+
data.frame={source:chosen.source,name:frame.name,locale:frame.locale??null,proposed:frame.proposed??null,fixture:frame.fixture??null,capture:frame.capture??null,authored:{width:frame.width??null,height:frame.height??null},parent:frame.parent??null};
|
|
65
|
+
data.mode='frame';data.catalog=[];
|
|
66
|
+
if(selection.subtree?.kind==='part'){
|
|
67
|
+
const input=selection.subtree.input,separator=input.lastIndexOf('#');
|
|
68
|
+
if(separator<=0||separator===input.length-1)throw new CliError('USAGE_INVALID','Use --part=<defining-source>#<Export>.');
|
|
69
|
+
const source=relative(config,selectSources(config,[input.slice(0,separator)],{write:false})[0]),exp=input.slice(separator+1);
|
|
70
|
+
if(!(await index.source(source)).parts.includes(exp))throw new CliError('INSPECT_PART_NOT_FOUND',`Unknown defining export ${exp}.`);
|
|
71
|
+
selection.subtree.input=source+'#'+exp;
|
|
72
|
+
}
|
|
73
|
+
const tokens=index.tokens(),env=await environment(),eligible=createEligibilityChecker(),policy=capturePolicy(config),intern=outputTables(data),observations=[];
|
|
74
|
+
data.coverage.requestedObservations=selection.themes.length;
|
|
75
|
+
for(const theme of selection.themes){
|
|
76
|
+
const document=frameDocument(frame,theme,built.css);
|
|
77
|
+
const animated=/<(?:animate|animateTransform|set|canvas|video)\b/i.test(frame.html)||[...document.matchAll(/data:(image\/[^;,]+)(;base64)?,([^"'\s<)]+)/gi)].some(([,mime,base64,body])=>{
|
|
78
|
+
try{const bytes=base64?Buffer.from(body,'base64'):Buffer.from(decodeURIComponent(body));const text=bytes.toString('latin1');return /svg/i.test(mime)?/<(?:animate|animateTransform|set)\b/i.test(text):/NETSCAPE2\.0|ANIMEXTS1\.0|acTL|ANIM/.test(text);}catch{return true;}
|
|
79
|
+
});
|
|
80
|
+
const bypass=built.observationDynamic===true||env===null||eligible(document).length>0||animated;
|
|
81
|
+
if(bypass)warn('INSPECT_CACHE_BYPASSED','Dynamic/external resources or unavailable environment identity require live observation.');
|
|
82
|
+
const result=await timed('observeMs',()=>observeInspectFrame(index,chosen.source,built,frame,theme,env,getPage,tokens,policy,{bypass,onLoad:()=>data.coverage.frameLoads++}));
|
|
83
|
+
data.coverage.cacheHits+=Number(result.hit);data.coverage.completedObservations++;
|
|
84
|
+
observations.push({theme,palette:result.value.rich.palette});
|
|
85
|
+
const projected=await timed('projectMs',()=>projectInspection(data,result.value,theme,config,intern,tokens));
|
|
86
|
+
if(data.baseline===null){data.baselineTheme=theme;data.baseline=projected.scene;}else data.additionalThemes[theme]=projected.scene;
|
|
87
|
+
for(const match of projected.matches){const existing=data.matches.find(m=>m.element===match.element);if(existing)existing.themes.push(theme);else data.matches.push(match);}
|
|
88
|
+
for(const row of projected.instanceRows)if(!data.partInstances.some(i=>i.id===row.id))data.partInstances.push(row);
|
|
89
|
+
for(const l of projected.limitations){let entry=data.limitations.find(e=>e.code===l.code&&e.accuracy===l.accuracy);if(!entry){entry={code:l.code,count:0,elements:[],properties:[],themes:[],accuracy:l.accuracy};data.limitations.push(entry);}entry.count++;if(!entry.elements.includes(l.element))entry.elements.push(l.element);if(l.property&&!entry.properties.includes(l.property))entry.properties.push(l.property);if(!entry.themes.includes(theme))entry.themes.push(theme);}
|
|
90
|
+
const c=projected.counts;data.coverage.rawElements+=c.raw;data.coverage.retainedElements+=c.retained;data.coverage.collapsedElements+=c.collapsed;data.coverage.logicalElements+=c.logical;data.coverage.cutOffElements+=c.cutOff;data.coverage.runs+=c.runs;
|
|
91
|
+
}
|
|
92
|
+
if(selection.subtree?.kind==='element'&&!data.matches.length)throw new CliError('INSPECT_ELEMENT_NOT_FOUND','The selected identity is absent from the requested frame/themes.');
|
|
93
|
+
if(!data.matches.length)warn('INSPECT_NO_MATCH','No selected text/part occurrences matched.',retry('Read the full frame to choose a current selector.',true));
|
|
94
|
+
pruneTables(data);
|
|
95
|
+
for(const [name,token]of Object.entries(data.tables.tokens))for(const {theme,palette}of observations){
|
|
96
|
+
const resolved=palette[name]??null;
|
|
97
|
+
if(theme==='light')token.resolved=resolved;
|
|
98
|
+
else if(resolved!==token.resolved)(token.dark??={}).resolved=resolved;
|
|
99
|
+
}
|
|
100
|
+
if([data.baseline,...Object.values(data.additionalThemes)].some(s=>s.elements.some(n=>n.identity.stability==='positional')))warn('INSPECT_IDENTITY_POSITIONAL','Some elements have unkeyed repeated identities; use anchors/keys for durable targets.',retry('Add instance keys or anchors before persisting positional targets.'));
|
|
101
|
+
if(data.limitations.length)warn('INSPECT_RENDER_LIMITATIONS','Read the reported precision limitations.');
|
|
102
|
+
if(Object.values(data.tables.values).some(v=>v.attribution==='unresolved'))warn('INSPECT_TOKEN_UNRESOLVED','Some authored variable references are unresolved; computed CSS values are retained.',[{argv:['adg','check','--read-only','--json'],reason:'Repair the named variable chains before retrying.'}]);
|
|
103
|
+
|
|
104
|
+
}
|
|
105
|
+
await index.close();
|
|
106
|
+
await verifyInputGeneration({tracked,views:[{index,config,resolved:resolvedConfig,configInputs}],verifyConfig:true,code:'INSPECT_INPUT_CHANGED'});
|
|
107
|
+
} catch(cause){if(cause.code==='OWNER_INDEX_CHANGED')cause=new CliError('INSPECT_INPUT_CHANGED',cause.message,{cause});primary=commandFailure(cause,data,warnings);}
|
|
108
|
+
for(const close of [()=>page?.close(),()=>browser?.close(),()=>index?.close()])try{await cleanup(close,primary);}catch(cause){primary=commandFailure(cause,data,warnings);}
|
|
109
|
+
data.timings.totalMs=performance.now()-start;
|
|
110
|
+
if(primary)throw primary;
|
|
111
|
+
data.complete=true;
|
|
112
|
+
const projectStart=performance.now();data=compactInspection(data);if(values.expand)data=expandInspection(data);
|
|
113
|
+
data.timings.projectMs+=performance.now()-projectStart;data.timings.totalMs=performance.now()-start;
|
|
114
|
+
if(data.mode==='frame'&&Buffer.byteLength(JSON.stringify(data))>256*1024)warn('INSPECT_OUTPUT_LARGE','Inspection data exceeds 256 KiB; no facts were truncated.',retry('Choose narrower fields, depth or an observed subtree.'));
|
|
115
|
+
if(!values.json){log(inspectText(data));for(const warning of warnings)log(warning.code+': '+warning.message);}
|
|
116
|
+
return {data,warnings};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function inspectText(data) {
|
|
120
|
+
data=expandInspection(data);
|
|
121
|
+
if(data.mode==='catalog')return data.catalog.map(s=>`${s.source}\n${s.frames.map(f=>' '+f.name).join('\n')}`).join('\n')||'No TSX frames.';
|
|
122
|
+
return [data.frame.source+'#'+data.frame.name,...[data.baseline,...Object.values(data.additionalThemes)].map((scene,i)=>{
|
|
123
|
+
const nodes=new Map(scene.elements.map(e=>[e.id,e]));const lines=[data.selection.themes[i]];
|
|
124
|
+
const visit=(id,depth)=>{const e=nodes.get(id);if(!e)return;lines.push(' '.repeat(depth)+e.tag+(e.role?' ['+e.role+']':'')+(e.name?' '+e.name:'')+' '+e.id+(e.geometry?.box?' ['+Object.values(e.geometry.box).join(', ')+']':'')+(e.style?' style='+e.style:''));for(const run of scene.runs.filter(r=>r.element===id))lines.push(' '.repeat(depth+1)+JSON.stringify(run.raw));for(const child of e.children)visit(child,depth+1);};scene.roots.forEach(id=>visit(id,0));return lines.join('\n');})].join('\n');
|
|
125
|
+
}
|