@whzxc/agent-design-gallery 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/LICENSE +69 -0
  2. package/README.md +216 -2
  3. package/package.json +43 -4
  4. package/public/access.css +10 -0
  5. package/public/app.js +1646 -0
  6. package/public/assets.js +344 -0
  7. package/public/auth.js +69 -0
  8. package/public/favicon.svg +6 -0
  9. package/public/hub.css +67 -0
  10. package/public/hub.html +33 -0
  11. package/public/hub.js +165 -0
  12. package/public/icons.js +50 -0
  13. package/public/index.html +70 -0
  14. package/public/instance-actions.js +27 -0
  15. package/public/labels.js +122 -0
  16. package/public/layout.js +103 -0
  17. package/public/relationships.js +28 -0
  18. package/public/selection.js +20 -0
  19. package/public/style.css +194 -0
  20. package/public/switcher.css +37 -0
  21. package/public/switcher.js +176 -0
  22. package/public/token-catalog.js +129 -0
  23. package/public/tokens.css +61 -0
  24. package/public/view-route.js +66 -0
  25. package/src/cli.mjs +105 -0
  26. package/src/http.mjs +37 -0
  27. package/src/hub/auth.mjs +40 -0
  28. package/src/hub/instances.mjs +99 -0
  29. package/src/hub/proxy.mjs +28 -0
  30. package/src/hub/registry.mjs +147 -0
  31. package/src/hub.mjs +113 -0
  32. package/src/link.mjs +54 -0
  33. package/src/open.mjs +57 -0
  34. package/src/server.mjs +642 -0
  35. package/src/service.mjs +163 -0
  36. package/src/toolkit/arch-browser.mjs +40 -0
  37. package/src/toolkit/arch-git.mjs +54 -0
  38. package/src/toolkit/arch-overlay.mjs +225 -0
  39. package/src/toolkit/arch.mjs +217 -0
  40. package/src/toolkit/asset-rules.mjs +14 -0
  41. package/src/toolkit/browser.mjs +21 -0
  42. package/src/toolkit/build-store.mjs +258 -0
  43. package/src/toolkit/build-worker.mjs +32 -0
  44. package/src/toolkit/build.mjs +133 -0
  45. package/src/toolkit/commands.mjs +273 -0
  46. package/src/toolkit/compare.mjs +175 -0
  47. package/src/toolkit/config.mjs +135 -0
  48. package/src/toolkit/document.mjs +85 -0
  49. package/src/toolkit/migrate.mjs +73 -0
  50. package/src/toolkit/project.mjs +160 -0
  51. package/src/toolkit/runtime.d.ts +14 -0
  52. package/src/toolkit/runtime.mjs +54 -0
  53. package/src/toolkit/text.mjs +12 -0
  54. package/src/toolkit/tokens.mjs +36 -0
  55. package/src/viewer-cache.mjs +85 -0
@@ -0,0 +1,133 @@
1
+ import { build, transform } from 'esbuild';
2
+ import { compile } from 'tailwindcss';
3
+ import { statSync, readFileSync, realpathSync, mkdirSync, writeFileSync } from 'node:fs';
4
+ import { createRequire } from 'node:module';
5
+ import path from 'node:path';
6
+ import { fileURLToPath, pathToFileURL } from 'node:url';
7
+ import { loadTokens, refreshTypes, rejectLegacy, relative, isSourcePath, sourceDirectories } from './project.mjs';
8
+ import { themeCss, parseTokens } from './tokens.mjs';
9
+ import { escape } from './runtime.mjs';
10
+ const require = createRequire(import.meta.url);
11
+ const runtime = fileURLToPath(new URL('./runtime.mjs', import.meta.url));
12
+ const tailwind = path.dirname(require.resolve('tailwindcss/package.json'));
13
+ // Imported source entries recur in many bundles. Retain their registration
14
+ // transforms by exact content, including pending work, without retaining a
15
+ // project's entire build graph or trusting modification times.
16
+ const sourceTransforms = new Map();
17
+ let transformBytes = 0;
18
+ const transformLimit = 8 * 1024 * 1024;
19
+ function forgetTransform(file) {
20
+ const entry = sourceTransforms.get(file);
21
+ if (entry) { transformBytes -= entry.bytes; sourceTransforms.delete(file); }
22
+ }
23
+ async function registeredSource(file, sourcePath, original) {
24
+ let entry = sourceTransforms.get(file);
25
+ if (entry?.original === original && entry.sourcePath === sourcePath) {
26
+ sourceTransforms.delete(file); sourceTransforms.set(file, entry);
27
+ return entry.result;
28
+ }
29
+ forgetTransform(file);
30
+ entry = { original, sourcePath, bytes: Buffer.byteLength(original) * 2, result: null };
31
+ entry.result = (async () => {
32
+ // esbuild's normalized export list supplies public names; static namespace
33
+ // accesses preserve aliases and let the bundler drop imported frame renderers.
34
+ const compiled = await transform(original, {loader:'tsx',format:'esm',jsx:'preserve'});
35
+ const names = [...compiled.code.matchAll(/\nexport\s*\{([^}]+)\}\s*;\s*$/g)].flatMap(match => match[1].split(',').map(item => item.trim().split(/\s+as\s+/).at(-1)).filter(name => name && name !== 'default'));
36
+ const registrations = names.map(name => `__adgRegister(__adgExports[${JSON.stringify(name)}],${JSON.stringify(sourcePath)},${JSON.stringify(name)});`).join('\n');
37
+ const contents = `${original}
38
+ import * as __adgExports from 'adg:self';
39
+ import {registerComponent as __adgRegister} from 'adg';
40
+ ${registrations}
41
+ `;
42
+ // Account for the generated text too; large individual sources need not
43
+ // occupy the cache even though their current callers can finish normally.
44
+ if (sourceTransforms.get(file) === entry) {
45
+ transformBytes += Buffer.byteLength(contents) - Buffer.byteLength(original);
46
+ entry.bytes = Buffer.byteLength(original) + Buffer.byteLength(contents);
47
+ trimTransforms();
48
+ }
49
+ return {contents,loader:'tsx'};
50
+ })();
51
+ sourceTransforms.set(file, entry); transformBytes += entry.bytes;
52
+ trimTransforms();
53
+ try { return await entry.result; }
54
+ catch (error) { if (sourceTransforms.get(file) === entry) forgetTransform(file); throw error; }
55
+ }
56
+ function trimTransforms() {
57
+ while (sourceTransforms.size > 256 || transformBytes > transformLimit)
58
+ forgetTransform(sourceTransforms.keys().next().value);
59
+ }
60
+ export function validateFrame(frame) {
61
+ if (!frame?.frame || typeof frame.name !== 'string' || !frame.name.trim()) throw Error('Default export must return named Frames');
62
+ for (const key of ['width', 'height']) if (frame[key] !== undefined && !(Number.isFinite(frame[key]) && frame[key] > 0)) throw Error(`Invalid Frame ${key}; use positive CSS pixels`);
63
+ const c = frame.capture;
64
+ if (c !== undefined) {
65
+ if (!c || typeof c !== 'object' || ['region','selector','page'].filter(k => c[k] !== undefined).length !== 1 || (c.page !== undefined && c.page !== true) || ['region','selector'].some(k => c[k] !== undefined && (typeof c[k] !== 'string' || !c[k].trim())) || (c.viewport !== undefined && !/^[1-9]\d*x[1-9]\d*$/.test(c.viewport)) || (c.origin !== undefined && (!c.page || !/^\d+(?:\.\d+)? \d+(?:\.\d+)?$/.test(c.origin))) || (c.clicks !== undefined && (!Array.isArray(c.clicks) || c.clicks.some(v => typeof v !== 'string' || !v)))) throw Error('Invalid capture; use region, selector or page with viewport, origin and clicks');
66
+ }
67
+ }
68
+ export async function buildSource(config, file, { write = true, allowLegacy = true, snapshot, browser } = {}) {
69
+ if (file.endsWith('.mmd')) return (await import('./arch.mjs')).buildArch(config,file,{snapshot,browser});
70
+ if (write) refreshTypes(config);
71
+ const read = (name, encoding) => {
72
+ if (!snapshot) return readFileSync(name, encoding);
73
+ if (!snapshot.has(name)) snapshot.set(name, readFileSync(name));
74
+ const value = snapshot.get(name);
75
+ return encoding ? value.toString(encoding) : value;
76
+ };
77
+ file = realpathSync(file);
78
+ const base = realpathSync(config.design), dependencies = new Set([path.join(base, 'tokens.css')]);
79
+ const imports = new Set(), sources = sourceDirectories(config);
80
+ const result = await build({ entryPoints: [file], bundle: true, write: false, format: 'esm', platform: 'node', jsx: 'automatic', jsxImportSource: 'adg', jsxDev: true, metafile: true, logLevel: 'silent', plugins: [{ name: 'adg-sources', setup(api) {
81
+ api.onResolve({ filter: /.*/ }, args => {
82
+ if (args.path === 'adg:self') return {path:args.importer};
83
+ if (['adg','adg/jsx-runtime','adg/jsx-dev-runtime'].includes(args.path)) return { path: pathToFileURL(runtime).href, external: true };
84
+ if (args.kind !== 'entry-point' && !args.path.startsWith('.')) return { errors: [{ text: `Bare import ${args.path} is unavailable; import adg or a relative file inside design/` }] };
85
+ const url = args.path.endsWith('?url');
86
+ const requested = url ? args.path.slice(0,-4) : args.path;
87
+ let resolved = args.kind === 'entry-point' ? path.resolve(requested) : path.resolve(args.resolveDir, requested);
88
+ resolved = [resolved, ...['.tsx','.ts','.js','/index.tsx','/index.ts','/index.js'].map(ext => resolved + ext)].find(candidate => statSync(candidate, { throwIfNoEntry: false })?.isFile());
89
+ if (!resolved) return { errors: [{ text: `Cannot resolve ${args.path}` }] };
90
+ resolved = realpathSync(resolved);
91
+ if (!resolved.startsWith(base + path.sep)) return { errors: [{ text: `Import ${args.path} leaves design/; move it inside design/` }] };
92
+ if (!allowLegacy) rejectLegacy(config, [path.join(config.design, path.relative(base, resolved))]);
93
+ dependencies.add(resolved);
94
+ const sourcePath = path.relative(base, resolved).split(path.sep).join('/');
95
+ if (args.importer === file && isSourcePath(sourcePath, sources)) imports.add(sourcePath);
96
+ if (url && !resolved.startsWith(path.join(base,'art')+path.sep)) return {errors:[{text:'?url imports must be under design/art/'}]};
97
+ return { path: resolved, ...(url ? {namespace:'art-url'} : {}) };
98
+ });
99
+ api.onLoad({filter:/.*/,namespace:'art-url'}, args => ({contents:read(args.path),loader:'dataurl'}));
100
+ api.onLoad({filter:/\.tsx$/}, async args => {
101
+ const sourcePath = path.relative(base, args.path).split(path.sep).join('/');
102
+ if (!isSourcePath(sourcePath, sources)) return snapshot ? {contents:read(args.path,'utf8'),loader:'tsx'} : undefined;
103
+ const original=read(args.path,'utf8');
104
+ return registeredSource(args.path, sourcePath, original);
105
+ });
106
+ if (snapshot) api.onLoad({filter:/\.(?:[cm]?js|jsx|ts|json)$/}, args => ({contents:read(args.path,'utf8'),loader:args.path.endsWith('.ts')?'ts':args.path.endsWith('.jsx')?'jsx':args.path.endsWith('.json')?'json':'js'}));
107
+ api.onLoad({ filter: /\.(png|jpe?g|webp)$/i }, args => ({ contents: read(args.path), loader: 'dataurl' }));
108
+ api.onLoad({ filter: /\.svg$/i }, args => {
109
+ const source = read(args.path,'utf8');
110
+ const forbidden = /<(?:style|script)\b|\s(?:on[\w-]+|className)\s*=/i.exec(source);
111
+ if (forbidden) { const before=source.slice(0,forbidden.index); return {errors:[{text:'Forbidden SVG markup; remove styles, scripts and event attributes',location:{file:args.path,line:before.split('\n').length,column:before.length-before.lastIndexOf('\n')-1}}]}; }
112
+ return { contents: `import { artwork } from 'adg'; export default props => artwork(${JSON.stringify(source)}, props);`, loader:'js' };
113
+ });
114
+ } }] });
115
+ const mod = await import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}#${Date.now()}`);
116
+ if (typeof mod.default !== 'function') throw Error(`${relative(config,file)}: export a default function returning Frames`);
117
+ const value = mod.default(), frames = (Array.isArray(value) ? value.flat(Infinity) : [value]).filter(v => v != null && v !== false);
118
+ if (!frames.length) throw Error(`${relative(config,file)}: default export must return at least one Frame`);
119
+ const names = new Set();
120
+ for (const frame of frames) {
121
+ try { validateFrame(frame); if (names.has(frame.name)) throw Error(`Duplicate frame name ${frame.name}`); names.add(frame.name); }
122
+ catch(error) { throw Error(`${relative(config,file)}: ${frame?.name ?? '-'}: ${error.message}`); }
123
+ }
124
+ const tokenSource = read(path.join(base,'tokens.css'),'utf8'), tokens = snapshot ? parseTokens(tokenSource) : loadTokens(config);
125
+ const compiler = await compile(`${readFileSync(path.join(tailwind,'theme.css'),'utf8')}\n${themeCss(tokens)}\n${readFileSync(path.join(tailwind,'preflight.css'),'utf8')}\n@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));\n@tailwind utilities;`);
126
+ const classes = [...new Set(frames.flatMap(f => [...f.html.matchAll(/\bclass="([^"]*)"/g)].flatMap(m => m[1].split(/\s+/))))];
127
+ const css = `${compiler.build(classes)}\n${tokenSource}\nhtml,body{margin:0;font-family:var(--font-ui);color:var(--text);background:var(--canvas)}[data-adg-frame]{display:flex;align-items:flex-start;position:relative;background:var(--canvas)}[data-adg-frame]>*,svg{flex-shrink:0} @media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important}}`;
128
+ for (const frame of frames) {
129
+ frame.document = theme => `<!doctype html><html data-theme="${theme}"><head><meta charset="utf-8"><style>${css.replace(/<\/style/gi,'<\\/style')}</style></head><body><div data-adg-frame="${escape(frame.name)}" style="${frame.width ? `width:${frame.width}px;` : 'width:max-content;'}${frame.height ? `height:${frame.height}px;` : ''}">${frame.html}</div></body></html>`;
130
+ if (write) { const destination = path.join(config.output, path.relative(base,file).replace(/\.tsx$/, ''), `${encodeURIComponent(frame.name)}.html`); mkdirSync(path.dirname(destination),{recursive:true}); writeFileSync(destination,frame.document('light')); }
131
+ }
132
+ return { frames, dependencies: [...dependencies], imports: [...imports].sort(), css };
133
+ }
@@ -0,0 +1,273 @@
1
+ import { mkdirSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { availableParallelism } from 'node:os';
4
+ import { buildSource } from './build.mjs';
5
+ import { selectSources, relative, loadTokens, sourceDirectories, archFiles } from './project.mjs';
6
+ import { importDirectionViolations } from './asset-rules.mjs';
7
+ import { launch, loadFrame } from './browser.mjs';
8
+ export function inspectFrame(tokenNames) {
9
+ const frame = document.querySelector('[data-adg-frame]'), box = frame.getBoundingClientRect(), problems = new Set();
10
+ if (frame.children.length !== 1 || [...frame.childNodes].some(n => n.nodeType === 3 && n.textContent.trim())) problems.add('Frame needs exactly one root element');
11
+ const sample = document.createElement('i'); document.body.append(sample);
12
+ const canvas = document.createElement('canvas'); canvas.width = canvas.height = 1;
13
+ const context = canvas.getContext('2d', { colorSpace: 'srgb', colorType: 'float16', willReadFrequently: true });
14
+ context.globalCompositeOperation = 'copy';
15
+ const normalized = new Map();
16
+ const normalize = value => {
17
+ if (!normalized.has(value)) {
18
+ context.fillStyle = value; context.fillRect(0, 0, 1, 1);
19
+ // Float pixels retain un-premultiplied RGB even at low opacity.
20
+ const [r, g, b, a] = context.getImageData(0, 0, 1, 1, { colorSpace: 'srgb', pixelFormat: 'rgba-float16' }).data;
21
+ normalized.set(value, [r, g, b].map(channel => Math.round(channel * 255)).concat(a));
22
+ }
23
+ return normalized.get(value);
24
+ };
25
+ const colors = [];
26
+ for (const name of tokenNames) {
27
+ const value = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
28
+ if (CSS.supports('color', value)) { sample.style.color = value; colors.push(normalize(getComputedStyle(sample).color)); }
29
+ for (const color of value.match(/(?:rgba?|hsla?|oklch|oklab|color)\([^)]*\)|#[\da-f]{3,8}\b/gi) ?? []) { sample.style.color = color; colors.push(normalize(getComputedStyle(sample).color)); }
30
+ }
31
+ sample.remove();
32
+ const outside = r => r.left < box.left - 1 || r.right > box.right + 1 || r.top < box.top - 1 || r.bottom > box.bottom + 1;
33
+ const styles = new Map(), bounds = new Map(), effects = new Map();
34
+ const style = el => { if (!styles.has(el)) styles.set(el,getComputedStyle(el)); return styles.get(el); };
35
+ const rectFor = el => { if (!bounds.has(el)) bounds.set(el,el.getBoundingClientRect()); return bounds.get(el); };
36
+ const intersect = (a,b) => ({left:Math.max(a.left,b.left),right:Math.min(a.right,b.right),top:Math.max(a.top,b.top),bottom:Math.min(a.bottom,b.bottom)});
37
+ const nonempty = r => r.right > r.left && r.bottom > r.top;
38
+ const clipped = (rect,start) => {
39
+ let visible = {left:rect.left,right:rect.right,top:rect.top,bottom:rect.bottom};
40
+ for (let p=start;p;p=p.parentElement) {
41
+ const ps=style(p),pr=rectFor(p);
42
+ // Overflow does not clip non-replaced inline boxes. Client bounds exclude
43
+ // borders/scrollbars and include padding, unlike the border-box DOMRect.
44
+ if (!(p instanceof HTMLElement && ps.display==='inline')) {
45
+ const sx=pr.width/(p.offsetWidth || p.clientWidth || pr.width || 1);
46
+ const sy=pr.height/(p.offsetHeight || p.clientHeight || pr.height || 1);
47
+ const left=pr.left+p.clientLeft*sx,top=pr.top+p.clientTop*sy;
48
+ if (ps.overflowX!=='visible') visible={...visible,left:Math.max(visible.left,left),right:Math.min(visible.right,left+p.clientWidth*sx)};
49
+ if (ps.overflowY!=='visible') visible={...visible,top:Math.max(visible.top,top),bottom:Math.min(visible.bottom,top+p.clientHeight*sy)};
50
+ }
51
+ if (p===frame) break;
52
+ }
53
+ return visible;
54
+ };
55
+ const opaqueEffects = el => {
56
+ if (!el) return true;
57
+ if (!effects.has(el)) {
58
+ const s=style(el);
59
+ effects.set(el,Number(s.opacity)===1 && s.filter==='none' && s.clipPath==='none' &&
60
+ s.maskImage==='none' && s.mixBlendMode==='normal' && opaqueEffects(el.parentElement));
61
+ }
62
+ return effects.get(el);
63
+ };
64
+ const opaqueColor = value => {
65
+ // Float16 canvas alpha rounds near-opaque colors up to 1. Read an explicit
66
+ // computed alpha before using canvas normalization for opaque color syntax.
67
+ if (value.startsWith('rgba(') || value.includes('/')) {
68
+ const alpha=value.match(/(?:,|\/)\s*([\d.e+-]+)(%)?\s*\)$/i);
69
+ return !!alpha && Number(alpha[1])===(alpha[2]?100:1);
70
+ }
71
+ return normalize(value)[3]===1;
72
+ };
73
+ const lines = [], covers = [];
74
+ for (const el of [frame, ...frame.querySelectorAll('*')]) {
75
+ const s = style(el), r = rectFor(el);
76
+ if (['STYLE','SCRIPT'].includes(el.tagName.toUpperCase())) problems.add(`Forbidden <${el.tagName.toLowerCase()}> in output`);
77
+ for (const attr of el.attributes) if (/^on/i.test(attr.name) || attr.name === 'classname') problems.add(`Forbidden attribute ${attr.name} in output`);
78
+ if (!el.closest('[data-free]')) {
79
+ const authored = (el.getAttribute('class') ?? '') + ' ' + (el.getAttribute('style') ?? '');
80
+ if ([...authored.matchAll(/(-?(?:\d*\.)?\d+)px\b/g)].some(m => !Number.isInteger(Number(m[1])))) problems.add('Fractional pixel length outside data-free');
81
+ for (const [,property] of (el.getAttribute('style') ?? '').matchAll(/(?:^|;)\s*([-\w]+)\s*:/g)) if (!['width','height'].includes(property) && !property.startsWith('--')) problems.add(`Style ${property} outside data-free; use layout classes`);
82
+ }
83
+ if (s.display === 'none' || s.visibility === 'hidden' || r.width === 0 || r.height === 0) continue;
84
+ const visibleBox=clipped(r,el.parentElement);
85
+ if (nonempty(visibleBox) && outside(visibleBox)) problems.add('Content overflows the frame');
86
+ // A border-box background has the same rounded hit shape as its element.
87
+ // Other background clips/masks cannot establish rectangular opaque coverage.
88
+ if (el instanceof HTMLElement && s.backgroundClip==='border-box' && opaqueColor(s.backgroundColor) && opaqueEffects(el)) {
89
+ covers.push({el,rect:intersect(visibleBox,box)});
90
+ }
91
+ if (!el.closest('[data-brand]')) {
92
+ const paints = [s.color, s.backgroundColor];
93
+ for (const side of ['Top','Right','Bottom','Left']) if (parseFloat(s[`border${side}Width`]) > 0) paints.push(s[`border${side}Color`]);
94
+ if (s.outlineStyle !== 'none') paints.push(s.outlineColor);
95
+ if (el instanceof SVGElement && /^(path|rect|circle|ellipse|polygon|polyline|line|text)$/.test(el.localName)) paints.push(s.fill, s.stroke);
96
+ paints.push(...((s.boxShadow+' '+s.textShadow+' '+s.backgroundImage).match(/(?:rgba?|hsla?|oklch|oklab|color)\([^)]*\)/g) ?? []));
97
+ for (const value of paints) {
98
+ if (!value || value === 'none' || value.startsWith('url(')) continue;
99
+ const paint = normalize(value), alpha = paint[3];
100
+ if (alpha === 0) continue;
101
+ const matches = colors.some(color => alpha < 1
102
+ ? paint.slice(0, 3).every((channel, i) => Math.abs(channel - color[i]) <= 2)
103
+ : paint.every((channel, i) => channel === color[i]));
104
+ if (!matches) problems.add(`Color ${value} matches no token`);
105
+ }
106
+ }
107
+ for (const node of el.childNodes) {
108
+ if (node.nodeType !== 3 || !node.textContent.trim()) continue;
109
+ const range = document.createRange(); range.selectNodeContents(node);
110
+ for (const rect of range.getClientRects()) {
111
+ if (rect.width < 1) continue;
112
+ const label = node.textContent.trim().replace(/\s+/g, ' ');
113
+ const visible=clipped(rect,el);
114
+ if (!nonempty(visible)) continue;
115
+ if (outside(visible)) problems.add(`Text leaves frame: ${label}`);
116
+ if (visible.left < r.left - 1 || visible.right > r.right + 1 ||
117
+ (visible.top+visible.bottom)/2 < r.top - 1 || (visible.top+visible.bottom)/2 > r.bottom + 1) problems.add(`Text overflows its box: ${label}`);
118
+ const inFrame=intersect(visible,box);
119
+ if (nonempty(inFrame)) lines.push({rect:inFrame,label,el});
120
+ }
121
+ }
122
+ }
123
+ // Hit testing omits inert and pointer-events:none content, though it still paints.
124
+ // Normalize only the text/cover nodes after validating authored styles, then
125
+ // restore their exact attributes so inspection has no lasting DOM changes.
126
+ const restored = [], inert = [];
127
+ for (let el=frame;el;el=el.parentElement) if (el.hasAttribute('inert')) inert.push([el,el.getAttribute('inert')]);
128
+ for (const el of frame.querySelectorAll('[inert]')) inert.push([el,el.getAttribute('inert')]);
129
+ for (const [el] of inert) el.removeAttribute('inert');
130
+ for (const el of new Set([...lines.map(line=>line.el),...covers.map(cover=>cover.el)])) {
131
+ if (style(el).pointerEvents==='none') {
132
+ restored.push([el,el.getAttribute('style')]);el.style.setProperty('pointer-events','auto','important');
133
+ }
134
+ }
135
+ const hits = new Map();
136
+ const paintStack = (x,y) => {
137
+ const key=`${x},${y}`;
138
+ if (!hits.has(key)) hits.set(key,document.elementsFromPoint(x,y));
139
+ return hits.get(key);
140
+ };
141
+ const occluded = (el,rect) => {
142
+ const dx=Math.min(.01,(rect.right-rect.left)/100),dy=Math.min(.01,(rect.bottom-rect.top)/100);
143
+ const points=[[rect.left+dx,rect.top+dy],[rect.right-dx,rect.top+dy],
144
+ [rect.left+dx,rect.bottom-dy],[rect.right-dx,rect.bottom-dy],[(rect.left+rect.right)/2,(rect.top+rect.bottom)/2]];
145
+ return covers.some(cover => {
146
+ if (cover.el.contains(el) || cover.rect.left>rect.left || cover.rect.right<rect.right ||
147
+ cover.rect.top>rect.top || cover.rect.bottom<rect.bottom) return false;
148
+ const samples=points.map(([x,y])=>{
149
+ const stack=paintStack(x,y);return [stack.indexOf(el),stack.indexOf(cover.el)];
150
+ });
151
+ // The SAME convex background must hit every corner. Rounded controls can
152
+ // omit their text owner at an edge, so establish paint order where both
153
+ // elements hit; absence alone is never evidence that the text is behind.
154
+ return samples.every(([subject,foreground])=>foreground>=0 && (subject<0 || foreground<subject)) &&
155
+ samples.some(([subject,foreground])=>subject>=0 && foreground<subject);
156
+ });
157
+ };
158
+ try {
159
+ for (let i=0;i<lines.length;i++) for(let j=i+1;j<lines.length;j++) {
160
+ const a=lines[i], b=lines[j];
161
+ // Each Range belongs to a direct text node; an ancestor's own text and a
162
+ // positioned child's text are distinct visible lines, not duplicate ranges.
163
+ if (a.el===b.el) continue;
164
+ const overlap=intersect(a.rect,b.rect);
165
+ if (overlap.right-overlap.left>1 && overlap.bottom-overlap.top>2 &&
166
+ !occluded(a.el,overlap) && !occluded(b.el,overlap)) problems.add(`Text overlaps: ${a.label} / ${b.label}`);
167
+ }
168
+ } finally {
169
+ for (const [el,authored] of restored) {
170
+ // Flush a CSSOM-created attribute before removing it (Chromium creates it lazily).
171
+ el.getAttribute('style');
172
+ if (authored===null) el.removeAttribute('style');
173
+ else el.setAttribute('style',authored);
174
+ }
175
+ for (const [el,authored] of inert) el.setAttribute('inert',authored);
176
+ }
177
+ return [...problems];
178
+ }
179
+ export async function check(config, args = [], options = {}, log = console.log, error = console.error) {
180
+ const write=!options['read-only'];
181
+ const files = selectSources(config,args,{write}), tokens = loadTokens(config), problems = new Set(), graph={};
182
+ const arch = files.some(file=>file.endsWith('.mmd')) ? await import('./arch.mjs') : null;
183
+ const browser = await launch();
184
+ try {
185
+ const page = await browser.newPage();
186
+ for (const file of files) {
187
+ const architecture=file.endsWith('.mmd');
188
+ if(architecture) {
189
+ const {readFileSync,existsSync}=await import('node:fs');
190
+ const text=readFileSync(file,'utf8'), side=file.replace(/\.mmd$/,'.md');
191
+ const metadata=arch.sidecar(existsSync(side)?readFileSync(side,'utf8'):'');
192
+ for(const problem of [...arch.inspectArch(text,config.check?.archMaxEdges??30).problems,...metadata.problems,...arch.ownerProblems(config,metadata)]) problems.add(`${relative(config,file)}: ${problem}`);
193
+ if([...problems].some(problem=>problem.startsWith(relative(config,file)+':'))) continue;
194
+ }
195
+ let built;
196
+ try { built = await buildSource(config,file,{allowLegacy:false,write,browser}); }
197
+ catch(e) {
198
+ const legacy = e.errors?.find(error => error.detail?.code === 'LEGACY_SVG');
199
+ if (legacy) throw legacy.detail;
200
+ for(const problem of e.message.split('\n')) problems.add(`${relative(config,file)}: ${architecture?'':'-: '}${problem.replace(/\s+/g,' ')}`); continue;
201
+ }
202
+ graph[path.relative(config.design,file).split(path.sep).join('/')]={uses:built.imports};
203
+ for (const frame of built.frames) for (const theme of ['light','dark']) {
204
+ try {
205
+ await loadFrame(page,frame,theme);
206
+ for (const problem of await page.evaluate(architecture?arch.inspectArchLabels:inspectFrame,architecture?undefined:[...tokens.light.keys()])) problems.add(`${relative(config,file)}: ${frame.name}: ${theme}: ${problem}`);
207
+ } catch(e) { problems.add(`${relative(config,file)}: ${frame.name}: ${theme}: ${e.message.replace(/\s+/g,' ')}`); }
208
+ }
209
+ }
210
+ } finally { await browser.close(); }
211
+ if (config.check?.importDirection!==false) for (const {source,target,from,to} of importDirectionViolations(graph,sourceDirectories(config))) {
212
+ problems.add(`${relative(config,path.join(config.design,source))}: import ${target} violates import direction (${from} -> ${to}); import from the same or a lower layer in sources`);
213
+ }
214
+ for (const problem of problems) error(problem);
215
+ log(`Design check ${problems.size ? 'failed' : 'passed'} for ${files.length} sources${problems.size ? `: ${problems.size} problems` : ''}.`);
216
+ return problems.size ? 1 : 0;
217
+ }
218
+ export async function render(config, args = [], options = {}) {
219
+ const scale = Number(options.scale ?? 2);
220
+ if (!(Number.isFinite(scale) && scale > 0)) throw Error('Invalid --scale; use a positive number');
221
+ const themeOption = options.theme ?? 'both';
222
+ if (!['both', 'light', 'dark'].includes(themeOption)) throw Error('Choose --theme=both, light, or dark.');
223
+ if (options['out-dir'] === '') throw Error('Set --out-dir to a directory.');
224
+ const output = options['out-dir'] ? path.resolve(config.root, options['out-dir']) : config.output;
225
+ const themes = themeOption === 'both' ? ['light', 'dark'] : [themeOption];
226
+ let base,deleted=[],additional=[];
227
+ if(options.base!==undefined && (!args.length || args.some(arg=>arg.endsWith('.mmd')))) {
228
+ const git=await import('./arch-git.mjs');
229
+ base=await git.resolveBase(config,options.base);
230
+ additional=await git.baseArchFiles(config,base);
231
+ }
232
+ const selected=selectSources(config,args,{additional});
233
+ const {existsSync}=await import('node:fs');
234
+ const currentArchitecture=base?new Set(archFiles(config.arch)):null;
235
+ const files=selected.filter(file=>{if(!existsSync(file)||(base&&file.endsWith('.mmd')&&!currentArchitecture.has(file))){deleted.push(relative(config,file));return false;}return true;});
236
+ const browser = base && !files.length ? null : await launch();
237
+ try {
238
+ const captures = [];
239
+ for (const file of files) {
240
+ const built = base&&file.endsWith('.mmd') ? await (await import('./arch-overlay.mjs')).buildOverlay(config,file,{base,browser}) : await buildSource(config,file,{allowLegacy:false,browser});
241
+ for (const frame of built.frames.filter(f => !options.frame || f.name === options.frame)) {
242
+ for (const theme of themes) {
243
+ const source = file.endsWith('.mmd') ? relative(config,file) : path.relative(config.design, file);
244
+ const target = path.join(output, source.replace(/\.(?:tsx|mmd)$/, ''), `${encodeURIComponent(frame.name)}-${theme}.png`);
245
+ captures.push({source,frame,theme,target});
246
+ }
247
+ }
248
+ }
249
+ if (options.frame && !captures.length && !deleted.length) throw Error(`Unknown frame ${options.frame}; choose a declared frame`);
250
+ let next = 0;
251
+ const workers = await Promise.allSettled(Array.from({length:Math.min(4,availableParallelism(),captures.length)},async () => {
252
+ while (next < captures.length) {
253
+ const {frame,theme,target} = captures[next++];
254
+ // Chromium reuses image resampling state across setContent calls.
255
+ // A fresh page/context per capture keeps PNG bytes independent of history.
256
+ const page = await browser.newPage({deviceScaleFactor:scale});
257
+ try {
258
+ await loadFrame(page,frame,theme);
259
+ mkdirSync(path.dirname(target),{recursive:true});
260
+ await page.locator('[data-adg-frame]').screenshot({path:target});
261
+ } finally { await page.close(); }
262
+ }
263
+ }));
264
+ const failed = workers.find(worker => worker.status === 'rejected');
265
+ if (failed) throw failed.reason;
266
+ if (options.json) {
267
+ const output=captures.map(({source,frame,theme,target})=>({source:source.split(path.sep).join('/'),frame:frame.name,theme,path:target}));
268
+ console.log(JSON.stringify(base?{base:{rev:base.rev,sha:base.sha},captures:output,deleted}:output));
269
+ }
270
+ else for (const {target} of captures) console.log(relative(config,target));
271
+ } finally { await browser?.close(); }
272
+ return 0;
273
+ }
@@ -0,0 +1,175 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { setTimeout as delay } from 'node:timers/promises';
4
+ import { launch, loadFrame } from './browser.mjs';
5
+ import { implementationTexts } from './document.mjs';
6
+ import { matchTexts, textDelta } from './text.mjs';
7
+ import { selectSources, relative } from './project.mjs';
8
+ import { buildSource } from './build.mjs';
9
+ import { viewport } from './config.mjs';
10
+
11
+ export function compareReport(asset, frame, fixture, design, implementation) {
12
+ const { pairs, missing, extra } = matchTexts(design.texts, implementation.texts);
13
+ const rows = pairs.map(([d, i]) => ({ text: d.text, ...textDelta(d, i) })).map(row => ({ ...row, off: Math.max(Math.abs(row.dx), Math.abs(row.dy), Math.abs(row.dw)) }));
14
+ return { asset, frame, fixture, size: { design: [Math.round(design.box.width), Math.round(design.box.height)], implementation: [Math.round(implementation.box.width), Math.round(implementation.box.height)] }, matched: rows.length,
15
+ offBy2px: rows.filter(row => row.off > 2).sort((a, b) => b.off - a.off), missing: missing.map(m => m.text), extra: extra.map(e => e.text) };
16
+ }
17
+ const cell = value => String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
18
+ export function reportHtml(report) {
19
+ const fmt = value => (value > 0 ? '+' : '') + value.toFixed(1);
20
+ return `<!doctype html><meta charset="utf-8"><title>${cell(report.asset)} ${cell(report.frame)}</title><style>body{font:13px system-ui;margin:24px;background:#f4f4f4}.row{display:flex;gap:16px;align-items:flex-start;overflow:auto}figure{margin:0}img{display:block;max-width:none;border:1px solid #ccc}table{border-collapse:collapse;margin-top:24px}td,th{padding:4px 10px;border-bottom:1px solid #ddd;text-align:left}td.n{font-family:ui-monospace,monospace;text-align:right}</style>
21
+ <h1>${cell(report.asset)} · ${cell(report.frame)} vs ${cell(report.fixture)}</h1><p>Matched ${report.matched} texts. ${report.offBy2px.length} differ by more than 2px. ${report.missing.length} missing in implementation. ${report.extra.length} extra in implementation.</p>
22
+ <div class="row">${['design', 'implementation', 'overlay'].map(name => `<figure><figcaption>${name}</figcaption><img src="${name}.png"></figure>`).join('')}</div>
23
+ <table><tr><th>Text</th><th>dx</th><th>dy</th><th>dw</th></tr>${report.offBy2px.map(row => `<tr><td>${cell(row.text)}</td><td class="n">${fmt(row.dx)}</td><td class="n">${fmt(row.dy)}</td><td class="n">${fmt(row.dw)}</td></tr>`).join('')}</table>
24
+ <h2>Missing in implementation</h2><p>${report.missing.map(cell).join(' · ') || 'None'}</p><h2>Extra in implementation</h2><p>${report.extra.map(cell).join(' · ') || 'None'}</p>`;
25
+ }
26
+ async function overlay(page, target) {
27
+ const images = ['design', 'implementation'].map(name => `data:image/png;base64,${readFileSync(path.join(target, `${name}.png`)).toString('base64')}`);
28
+ const data = await page.evaluate(async sources => {
29
+ const [a, b] = await Promise.all(sources.map(src => new Promise((resolve, reject) => {
30
+ const image = new Image(); image.onload = () => resolve(image); image.onerror = reject; image.src = src;
31
+ })));
32
+ const canvas = document.createElement('canvas');
33
+ canvas.width = Math.min(a.width, b.width); canvas.height = Math.min(a.height, b.height);
34
+ const context = canvas.getContext('2d');
35
+ context.drawImage(a, 0, 0); const first = context.getImageData(0, 0, canvas.width, canvas.height);
36
+ context.clearRect(0, 0, canvas.width, canvas.height); context.drawImage(b, 0, 0);
37
+ const second = context.getImageData(0, 0, canvas.width, canvas.height);
38
+ for (let i = 0; i < first.data.length; i += 4) {
39
+ for (let c = 0; c < 3; c++) first.data[i + c] = Math.round((first.data[i + c] + second.data[i + c]) / 2);
40
+ first.data[i + 3] = 255;
41
+ }
42
+ context.putImageData(first, 0, 0);
43
+ return canvas.toDataURL('image/png').split(',')[1];
44
+ }, images);
45
+ writeFileSync(path.join(target, 'overlay.png'), Buffer.from(data, 'base64'));
46
+ }
47
+ const safeName = value => encodeURIComponent(value).replace(/\./g, '%2E');
48
+ async function settle(read) {
49
+ const started = performance.now();
50
+ let previous, changed = started;
51
+ for (;;) {
52
+ const implementation = await read();
53
+ const state = JSON.stringify({ box: implementation.box, texts: implementation.texts.map(({ text, x, y, width, height }) => ({ text, x, y, width, height })) });
54
+ const now = performance.now();
55
+ if (state !== previous) { previous = state; changed = now; }
56
+ if (now - changed >= 300) return { implementation, settled: true };
57
+ if (now - started >= 5000) return { implementation, settled: false };
58
+ await delay(Math.min(50, 5000 - (now - started)));
59
+ }
60
+ }
61
+ export async function compare(config, args, options) {
62
+ if (options.all) return compareAll(config);
63
+ const file = selectSources(config, args)[0], adapter = config.compare;
64
+ if (!adapter.fixture) throw new Error('Compare needs compare.fixture(name); add it to adg.config.mjs');
65
+ if ([options.region,options.selector,options.page].filter(Boolean).length > 1) throw Error('Choose --region, --selector or --page');
66
+ const frame = options.frame;
67
+ const built = await buildSource(config,file,{allowLegacy:false}), definition = built.frames.find(f=>f.name===frame);
68
+ if (!definition) throw Error(`Unknown frame ${frame}; choose a declared frame`);
69
+ const settings = {...definition.capture};
70
+ if (options.region || options.selector || options.page) { delete settings.region; delete settings.selector; delete settings.page; }
71
+ for (const key of ['region','selector','page','origin','viewport']) if (options[key] !== undefined) settings[key] = options[key];
72
+ settings.clicks = options.click ?? settings.clicks ?? [];
73
+ const browser = await launch();
74
+ let stop;
75
+ try {
76
+ const fixtureName = options.fixture ?? definition.fixture;
77
+ if (!fixtureName) throw Error('Frame needs a fixture; supply --fixture or Frame fixture');
78
+ const fixture = await adapter.fixture(fixtureName);
79
+ if (!fixture || typeof fixture.url !== 'string' || !['light', 'dark'].includes(fixture.theme) || typeof fixture.locale !== 'string' || !fixture.locale || !Number.isFinite(Date.parse(fixture.clock))) throw new Error('compare.fixture must return url, theme (light/dark), locale and a valid clock; fix adg.config.mjs');
80
+ if (fixture.timezone !== undefined) {
81
+ try {
82
+ if (typeof fixture.timezone !== 'string' || !fixture.timezone || /^[+-]/.test(fixture.timezone)) throw new Error();
83
+ new Intl.DateTimeFormat('en-US', { timeZone: fixture.timezone });
84
+ } catch { throw new Error('compare.fixture timezone must be a valid IANA time zone such as Asia/Shanghai; fix adg.config.mjs'); }
85
+ }
86
+ const sheet = await browser.newPage({colorScheme:fixture.theme,locale:fixture.locale,timezoneId:fixture.timezone,reducedMotion:'reduce'});
87
+ const frameBox = await loadFrame(sheet,definition,fixture.theme);
88
+ let design = await sheet.locator('[data-adg-frame] > :first-child').evaluate(implementationTexts);
89
+ const size = viewport(settings.viewport ?? adapter.viewport);
90
+ const origin = (settings.origin ?? '0 0').trim().split(/\s+/).map(Number);
91
+ if (settings.page && (origin.length !== 2 || !origin.every(Number.isFinite) || origin.some(n=>n<0) || origin[0]+frameBox.width>size.width || origin[1]+frameBox.height>size.height)) throw Error('Frame does not fit capture viewport; fix origin or viewport');
92
+ if (!settings.page && !settings.region && !settings.selector) throw Error('Frame needs capture; supply --page, --region or --selector');
93
+ const absolute = /^https?:\/\//.test(fixture.url);
94
+ if (!adapter.start && !absolute) throw new Error('Relative fixture URL needs compare.start; add it or return an absolute URL');
95
+ const url = new URL(fixture.url, `http://127.0.0.1:${adapter.port}`).href;
96
+ if (!/^https?:/.test(url)) throw new Error('Fixture URL must use HTTP or HTTPS; fix compare.fixture');
97
+ if (adapter.start) {
98
+ stop = await adapter.start({ port: adapter.port, root: config.root });
99
+ if (typeof stop !== 'function') throw new Error('compare.start must return a stop function; fix adg.config.mjs');
100
+ }
101
+ await sheet.emulateMedia({ colorScheme: fixture.theme, reducedMotion: 'reduce' });
102
+ await sheet.evaluate(theme => document.documentElement.setAttribute('data-theme', theme), fixture.theme);
103
+ design = await sheet.locator('[data-adg-frame] > :first-child').evaluate(implementationTexts);
104
+ const target = path.join(config.output, 'compare', `${path.relative(config.design,file).replace(/\.tsx$/, '').split(path.sep).join('-')}-${safeName(frame)}-${safeName(fixtureName)}`);
105
+ mkdirSync(target, { recursive: true });
106
+ await sheet.screenshot({ path: path.join(target, 'design.png'), clip: frameBox });
107
+ const app = await browser.newPage({ viewport: size, colorScheme: fixture.theme, reducedMotion: 'reduce', locale: fixture.locale, timezoneId: fixture.timezone });
108
+ for (const pattern of adapter.block ?? []) await app.route(pattern, route => route.abort());
109
+ await app.addInitScript(({ clock, theme }) => {
110
+ const original = Date, fixed = original.parse(clock);
111
+ function FixedDate(...values) {
112
+ if (!new.target) return new original(fixed).toString();
113
+ return Reflect.construct(original, values.length ? values : [fixed], new.target);
114
+ }
115
+ Object.setPrototypeOf(FixedDate, original); FixedDate.prototype = original.prototype; FixedDate.now = () => fixed;
116
+ globalThis.Date = FixedDate;
117
+ const apply = () => document.documentElement?.setAttribute('data-theme', theme);
118
+ if (document.documentElement) apply();
119
+ else { const observer = new MutationObserver(() => { if (document.documentElement) { apply(); observer.disconnect(); } }); observer.observe(document, { childList: true }); }
120
+ document.addEventListener('DOMContentLoaded', apply, { once: true });
121
+ }, { clock: fixture.clock, theme: fixture.theme });
122
+ await app.goto(url, { waitUntil: 'load' });
123
+ if (adapter.ready) await adapter.ready(app, fixtureName);
124
+ for (const name of settings.clicks) {
125
+ let control;
126
+ for (const role of ['button', 'radio', 'tab', 'checkbox', 'switch', 'menuitem', 'menuitemradio', 'option', 'link']) {
127
+ const candidate = app.getByRole(role, { name, exact: true }).filter({ visible: true }).first();
128
+ if (await candidate.count()) { control = candidate; break; }
129
+ }
130
+ if (!control) {
131
+ console.error(`adg: No visible control matches --click=${JSON.stringify(name)}`);
132
+ return 1;
133
+ }
134
+ await control.click();
135
+ }
136
+ await app.evaluate(() => document.fonts.ready);
137
+ const capture = settings.page ? { x: origin[0], y: origin[1], width: frameBox.width, height: frameBox.height } : undefined;
138
+ const panel = capture ? app.locator('html') : settings.selector ? app.locator(settings.selector).first() : app.getByRole('region', { name: settings.region, exact: true }).or(app.getByRole('dialog', { name: settings.region, exact: true })).first();
139
+ if (!capture) await panel.scrollIntoViewIfNeeded();
140
+ const { implementation, settled } = await settle(async () => {
141
+ const result = await panel.evaluate(implementationTexts, capture);
142
+ if (adapter.texts) {
143
+ const additional = await adapter.texts(app), box = result.box;
144
+ if (!Array.isArray(additional) || additional.some(t => typeof t.text !== 'string' || !['x', 'y', 'width', 'height'].every(key => Number.isFinite(t[key])))) throw new Error('compare.texts must return text boxes in page coordinates; fix adg.config.mjs');
145
+ result.texts.push(...additional.filter(t => t.x >= box.x && t.y >= box.y && t.x + t.width <= box.x + box.width && t.y + t.height <= box.y + box.height).map(t => ({ ...t, x: t.x - box.x, y: t.y - box.y })));
146
+ }
147
+ return result;
148
+ });
149
+ const screenshot = { path: path.join(target, 'implementation.png') };
150
+ if (capture) await app.screenshot({ ...screenshot, clip: capture });
151
+ else await panel.screenshot(screenshot);
152
+ const canvasPage = await browser.newPage();
153
+ await overlay(canvasPage, target);
154
+ const report = { ...compareReport(relative(config, file), frame, fixtureName, {...design,box:frameBox}, implementation), settled };
155
+ if (options.collect) options.collect.push({...report, report: path.relative(path.join(config.output,'compare'),path.join(target,'index.html'))});
156
+ writeFileSync(path.join(target, 'report.json'), JSON.stringify(report, null, 2) + '\n');
157
+ writeFileSync(path.join(target, 'index.html'), reportHtml(report));
158
+ console.log(`${relative(config, path.join(target, 'index.html'))}: matched ${report.matched}, ${report.offBy2px.length} off by >2px, ${report.missing.length} missing, ${report.extra.length} extra.`);
159
+ return report.offBy2px.length || report.missing.length || report.extra.length ? 1 : 0;
160
+ } finally {
161
+ try { await browser.close(); } finally { if (typeof stop === 'function') await stop(); }
162
+ }
163
+ }
164
+
165
+ async function compareAll(config) {
166
+ const files = selectSources(config), summary = []; let code = 0;
167
+ for (const file of files) {
168
+ const built = await buildSource(config,file,{allowLegacy:false});
169
+ for (const frame of built.frames.filter(f=>f.fixture)) code = Math.max(code,await compare(config,[file],{frame:frame.name,collect:summary}));
170
+ }
171
+ const target=path.join(config.output,'compare'); mkdirSync(target,{recursive:true});
172
+ writeFileSync(path.join(target,'summary.json'),JSON.stringify(summary,null,2)+'\n');
173
+ writeFileSync(path.join(target,'index.html'),`<!doctype html><meta charset="utf-8"><title>Design comparisons</title><table><tr><th>Source</th><th>Frame</th><th>Matched</th><th>Offsets</th><th>Missing</th><th>Extra</th></tr>${summary.map(r=>`<tr><td>${cell(r.asset)}</td><td><a href="${cell(r.report)}">${cell(r.frame)}</a></td><td>${r.matched}</td><td>${r.offBy2px.length}</td><td>${r.missing.length}</td><td>${r.extra.length}</td></tr>`).join('')}</table>`);
174
+ return code;
175
+ }