@whzxc/agent-design-gallery 0.0.0-stage → 0.7.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 (61) hide show
  1. package/LICENSE +69 -0
  2. package/README.md +218 -2
  3. package/package.json +43 -4
  4. package/public/access.css +10 -0
  5. package/public/app.js +1674 -0
  6. package/public/arrangement-worker.js +11 -0
  7. package/public/arrangement.js +49 -0
  8. package/public/assets.js +356 -0
  9. package/public/auth.js +69 -0
  10. package/public/favicon.svg +6 -0
  11. package/public/hub.css +67 -0
  12. package/public/hub.html +33 -0
  13. package/public/hub.js +165 -0
  14. package/public/icons.js +50 -0
  15. package/public/index.html +70 -0
  16. package/public/instance-actions.js +27 -0
  17. package/public/labels.js +122 -0
  18. package/public/layout.js +119 -0
  19. package/public/relationships.js +28 -0
  20. package/public/selection.js +20 -0
  21. package/public/style.css +194 -0
  22. package/public/switcher.css +37 -0
  23. package/public/switcher.js +176 -0
  24. package/public/token-catalog.js +129 -0
  25. package/public/tokens.css +61 -0
  26. package/public/view-route.js +66 -0
  27. package/src/cli-output.mjs +236 -0
  28. package/src/cli.mjs +176 -0
  29. package/src/http.mjs +38 -0
  30. package/src/hub/auth.mjs +41 -0
  31. package/src/hub/instances.mjs +99 -0
  32. package/src/hub/proxy.mjs +30 -0
  33. package/src/hub/registry.mjs +181 -0
  34. package/src/hub.mjs +128 -0
  35. package/src/lifecycle.mjs +109 -0
  36. package/src/link.mjs +55 -0
  37. package/src/open.mjs +61 -0
  38. package/src/perf.mjs +12 -0
  39. package/src/server.mjs +679 -0
  40. package/src/service.mjs +184 -0
  41. package/src/toolkit/arch-browser.mjs +40 -0
  42. package/src/toolkit/arch-git.mjs +55 -0
  43. package/src/toolkit/arch-overlay.mjs +225 -0
  44. package/src/toolkit/arch.mjs +221 -0
  45. package/src/toolkit/asset-rules.mjs +14 -0
  46. package/src/toolkit/browser.mjs +33 -0
  47. package/src/toolkit/build-store.mjs +266 -0
  48. package/src/toolkit/build-worker.mjs +35 -0
  49. package/src/toolkit/build.mjs +147 -0
  50. package/src/toolkit/commands.mjs +345 -0
  51. package/src/toolkit/compare.mjs +222 -0
  52. package/src/toolkit/config.mjs +136 -0
  53. package/src/toolkit/document.mjs +85 -0
  54. package/src/toolkit/migrate.mjs +85 -0
  55. package/src/toolkit/project.mjs +172 -0
  56. package/src/toolkit/results.mjs +44 -0
  57. package/src/toolkit/runtime.d.ts +14 -0
  58. package/src/toolkit/runtime.mjs +54 -0
  59. package/src/toolkit/text.mjs +12 -0
  60. package/src/toolkit/tokens.mjs +37 -0
  61. package/src/viewer-cache.mjs +85 -0
@@ -0,0 +1,172 @@
1
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync, realpathSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { parseTokens } from './tokens.mjs';
4
+ import { CliError, classifyError } from '../cli-output.mjs';
5
+ export const starterTokens = `:root {
6
+ --font-ui: system-ui, sans-serif;
7
+ --font-mono: ui-monospace, monospace;
8
+ --canvas: #ffffff;
9
+ --text: #171717;
10
+ }
11
+ :root[data-theme="dark"] {
12
+ --canvas: #171717;
13
+ --text: #ffffff;
14
+ }
15
+ `;
16
+ export function archFiles(directory) {
17
+ if (!directory || !existsSync(directory)) return [];
18
+ return readdirSync(directory, {withFileTypes:true}).flatMap(entry => entry.name.startsWith('.') ? [] :
19
+ entry.isDirectory() ? archFiles(path.join(directory,entry.name)) : entry.isFile() && entry.name.endsWith('.mmd') ? [path.join(directory,entry.name)] : []).sort();
20
+ }
21
+ const defaultSources = ['components', 'modules', 'surfaces'];
22
+ export function sourceDirectories(config = {}) {
23
+ const studies = config.sources === undefined && config.design && existsSync(path.join(config.design, 'studies')) &&
24
+ readdirSync(path.join(config.design, 'studies'), {withFileTypes:true}).some(entry => entry.isFile() && isSourcePath(`studies/${entry.name}`, ['studies']));
25
+ const sources = config.sources === undefined ? [...defaultSources, ...(studies ? ['studies'] : [])] : config.sources;
26
+ if (!Array.isArray(sources) || !sources.length || sources.some(name => typeof name !== 'string' || !/^[A-Za-z0-9_-]+$/.test(name))) {
27
+ throw new CliError('CONFIG_INVALID', 'Set sources to a non-empty array of plain top-level directory names in adg.config.mjs; nesting is not allowed');
28
+ }
29
+ return [...new Set(sources)];
30
+ }
31
+ const sourceLocations = sources => sources.map(name => `${name}/`).join(', ');
32
+ export function refreshTypes(config, changes) {
33
+ mkdirSync(path.join(config.design, '.adg'), { recursive: true });
34
+ const runtime = readFileSync(new URL('./runtime.d.ts', import.meta.url), 'utf8');
35
+ writeFileSync(path.join(config.design, '.adg/runtime.d.ts'), runtime);
36
+ changes?.push({ action: 'regenerated', path: path.join(config.design, '.adg/runtime.d.ts'), from: null });
37
+ writeFileSync(path.join(config.design, '.adg/assets.d.ts'), `declare module '*?url' { const url: string; export default url; }\ndeclare module '*.svg' { const Art: (props: Record<string, unknown>) => any; export default Art; }\n${['png','jpg','jpeg','webp'].map(ext => `declare module '*.${ext}' { const url: string; export default url; }`).join('\n')}\n`);
38
+ changes?.push({ action: 'regenerated', path: path.join(config.design, '.adg/assets.d.ts'), from: null });
39
+ }
40
+ export const tsconfig = { compilerOptions: { target: 'ESNext', module: 'ESNext', moduleResolution: 'Bundler', jsx: 'react-jsx', jsxImportSource: 'adg', noEmit: true, strict: true, paths: { adg: ['./.adg/runtime.d.ts'], 'adg/jsx-runtime': ['./.adg/runtime.d.ts'] } }, include: ['**/*.tsx', '**/*.ts', '.adg/*.d.ts'] };
41
+ function starterSources(sources) {
42
+ const layers=sources.filter(name=>name!=='studies');
43
+ return layers.map((directory,index) => {
44
+ const imports=`import { Frame } from 'adg';\n`;
45
+ let body;
46
+ if (!index) body=`import { example } from '../fixtures/example';
47
+
48
+ export function Example({ label = example.action }: { label?: string }) {
49
+ return <button class="rounded-lg bg-text px-4 py-2 text-canvas">{label}</button>;
50
+ }
51
+ export default () => <Frame name="default"><Example /></Frame>;
52
+ `;
53
+ else {
54
+ const last=index===layers.length-1;
55
+ body=`import { Example as Part } from '../${layers[index-1]}/example';
56
+ ${last ? '' : "import { example } from '../fixtures/example';\n"}
57
+ export function Example() {
58
+ return ${last ? '<main class="flex h-[360px] w-[640px] items-center justify-center bg-canvas p-6"><Part /></main>' : '<section class="flex flex-col items-start gap-3 p-4"><h2>{example.title}</h2><Part /></section>'};
59
+ }
60
+ export default () => <Frame name="default"${last ? ' width={640} height={360}' : ''}><Example /></Frame>;
61
+ `;
62
+ }
63
+ return [path.join(directory,'example.tsx'),imports+body];
64
+ });
65
+ }
66
+ export function init(config, log = console.log) {
67
+ const data = { project: config.root, complete: false, changes: [] };
68
+ try {
69
+ config.design ??= path.join(config.root, 'design');
70
+ refreshTypes(config, data.changes); rejectLegacy(config);
71
+ const sources=sourceDirectories(config), fresh=sources.some(name=>name!=='studies') &&
72
+ !listSources(config.design,sources).length && !existsSync(path.join(config.design,'fixtures/example.ts'));
73
+ for (const [file, content] of [
74
+ [path.join(config.root, 'adg.config.mjs'), "export default { requires: '>=0.5.0', design: 'design', output: 'output/design' };\n"],
75
+ [path.join(config.design, 'tokens.css'), starterTokens],
76
+ ...[...sources.filter(name=>name!=='studies'), 'fixtures', 'art'].map(name => [path.join(config.design, name), null]),
77
+ ...(fresh ? [
78
+ [path.join(config.design,'fixtures/example.ts'), "export const example = { title: 'Example', action: 'Continue' };\n"],
79
+ ...starterSources(sources).map(([name,content])=>[path.join(config.design,name),content]),
80
+ ] : []),
81
+ [path.join(config.design, 'tsconfig.json'), JSON.stringify(tsconfig, null, 2) + '\n'],
82
+ ]) {
83
+ if (existsSync(file)) { data.changes.push({ action: 'skipped', path: file, from: null }); log(`skipped ${relative(config, file)}`); continue; }
84
+ mkdirSync(content === null ? file : path.dirname(file), { recursive: true });
85
+ if (content !== null) writeFileSync(file, content);
86
+ data.changes.push({ action: 'created', path: file, from: null });
87
+ log(`created ${relative(config, file)}`);
88
+ }
89
+ const ignore = path.join(config.root, '.gitignore');
90
+ const existed = existsSync(ignore), original = existed ? readFileSync(ignore, 'utf8') : '';
91
+ let text = original;
92
+ for (const entry of [`/${relative(config, config.design)}/.adg/`, `/${relative(config, config.output ?? path.join(config.root, 'output/design'))}/`]) if (!text.split('\n').includes(entry)) text += `\n${entry}\n`;
93
+ writeFileSync(ignore, text);
94
+ if (!existed || text !== original) data.changes.push({ action: existed ? 'updated' : 'created', path: ignore, from: null });
95
+ refreshTypes(config, data.changes);
96
+ data.complete = true;
97
+ return data;
98
+ } catch (error) {
99
+ if (!data.changes.length) throw error;
100
+ if (error instanceof CliError) { error.data = data; throw error; }
101
+ throw new CliError(classifyError(error).error.code, error.message, { cause: error, data });
102
+ }
103
+ }
104
+ export function listSources(directory, sources = sourceDirectories({design:directory})) {
105
+ return sources.flatMap(name => {
106
+ const base = path.join(directory, name);
107
+ if (!existsSync(base)) return [];
108
+ return readdirSync(base, { withFileTypes: true })
109
+ .filter(entry => entry.isFile() && isSourcePath(`${name}/${entry.name}`, sources))
110
+ .map(entry => path.join(base, entry.name));
111
+ }).sort();
112
+ }
113
+ export function isSourcePath(name, sources = defaultSources) {
114
+ const slash = name.indexOf('/');
115
+ return slash > 0 && sources.includes(name.slice(0, slash)) && /^[^/.][^/]*\.tsx$/.test(name.slice(slash + 1));
116
+ }
117
+ export function readGroups(directory, sources = sourceDirectories({design:directory})) {
118
+ try {
119
+ const data = JSON.parse(readFileSync(path.join(directory, 'gallery.json'), 'utf8'));
120
+ if (!Array.isArray(data.groups) || data.groups.some(group => typeof group.title !== 'string' || !Array.isArray(group.assets))) {
121
+ throw Error('Expected groups with title and assets (relative source paths).');
122
+ }
123
+ for (const group of data.groups) for (const asset of group.assets) {
124
+ // Legacy SVGs remain browsable during staged conversion.
125
+ if (typeof asset !== 'string' || !isSourcePath(asset.replace(/\.svg$/i, '.tsx'), sources)) {
126
+ throw Error(`Invalid source ${asset}; use files directly in ${sourceLocations(sources)}.`);
127
+ }
128
+ }
129
+ return data.groups;
130
+ } catch (error) {
131
+ if (error.code === 'ENOENT') return [];
132
+ throw new CliError('CONFIG_INVALID', `gallery.json: ${error.message}`, { cause: error });
133
+ }
134
+ }
135
+ export function rejectLegacy(config, files) {
136
+ const directories = sourceDirectories(config).map(dir => path.join(config.design, dir));
137
+ files ??= directories.flatMap(base => existsSync(base) ? readdirSync(base).map(name => path.join(base, name)) : []);
138
+ for (const file of files) {
139
+ if (/\.svg$/i.test(file) && directories.includes(path.dirname(file))) {
140
+ throw new CliError('LEGACY_SOURCE', `${relative(config, file)}: convert this SVG source to TSX; move artwork to design/art/`);
141
+ }
142
+ }
143
+ }
144
+ export function selectSources(config, args = [], { write = true, additional = [] } = {}) {
145
+ if (write && (!args.length || args.some(arg=>!arg.endsWith('.mmd')))) refreshTypes(config);
146
+ if (!args.length) rejectLegacy(config);
147
+ const directories = sourceDirectories(config);
148
+ readGroups(config.design, directories);
149
+ const sources = [...new Set([...listSources(config.design, directories), ...archFiles(config.arch), ...additional])];
150
+ if (!args.length) return sources;
151
+ return args.map(arg => {
152
+ const fromRoot = path.resolve(config.root, arg);
153
+ if(path.isAbsolute(arg)) {
154
+ const root=realpathSync(config.root),file=existsSync(arg)?realpathSync(arg):path.resolve(arg);
155
+ const relative=path.relative(root,file);
156
+ if(relative==='..'||relative.startsWith('..'+path.sep)||path.isAbsolute(relative))throw new CliError('SOURCE_NOT_FOUND', `Source ${arg} is outside the project root; choose a source inside ${config.root}.`);
157
+ const found=sources.find(source=>(existsSync(source)?realpathSync(source):path.resolve(source))===file);
158
+ if(found)return found;
159
+ }
160
+ if (arg.endsWith('.mmd') && sources.includes(fromRoot)) return fromRoot;
161
+ let file = path.isAbsolute(arg) || fromRoot.startsWith(config.design + path.sep) ? fromRoot : path.resolve(config.design, arg);
162
+ if (existsSync(file)) rejectLegacy(config, [file]);
163
+ if (!file.endsWith('.tsx')) file += '.tsx';
164
+ if (!sources.includes(file)) throw new CliError('SOURCE_NOT_FOUND', `Invalid source ${arg}; name a discovered .mmd file or a TSX file directly in ${directories.map(name => path.join(config.design, name) + '/').join(', ')}`);
165
+ return file;
166
+ });
167
+ }
168
+ export const relative = (config, file) => path.relative(config.root, file).split(path.sep).join('/');
169
+ export function loadTokens(config) {
170
+ try { return parseTokens(readFileSync(path.join(config.design, 'tokens.css'), 'utf8')); }
171
+ catch (error) { throw new CliError('TOKENS_INVALID', `${error.message}; fix design/tokens.css or run adg init`, { cause: error }); }
172
+ }
@@ -0,0 +1,44 @@
1
+ import { CliError, classifyError } from '../cli-output.mjs';
2
+
3
+ /** @typedef {'light' | 'dark'} Theme */
4
+ /** @typedef {{source: string | null, frame: string | null, theme: Theme | null, line: number | null, column: number | null}} Location */
5
+ /** @typedef {Location & {code: string, message: string}} Finding */
6
+ /** @typedef {{project: string, readOnly: boolean, complete: boolean, sources: string[], summary: {sources: number, frames: number, evaluations: number, problems: number}, findings: Finding[]}} CheckData */
7
+ /** @typedef {{source: string, frame: string, theme: Theme, path: string, scale: number, width: number, height: number, pixelWidth: number, pixelHeight: number}} Capture */
8
+ /** @typedef {{project: string, outputDirectory: string, complete: boolean, base: {rev: string, sha: string} | null, captures: Capture[], deleted: string[]}} RenderData */
9
+ /** @typedef {{source: string, frame: string, fixture: string, theme: Theme, settled: boolean, size: {design: [number, number], implementation: [number, number]}, matched: number, offBy2px: {text: string, dx: number, dy: number, dw: number, off: number}[], missing: string[], extra: string[], paths: {design: string, implementation: string, overlay: string, report: string, html: string}}} Comparison */
10
+ /** @typedef {{project: string, complete: boolean, all: boolean, comparisons: Comparison[], skipped: {source: string, frame: string, reason: 'no_fixture'}[], summary: {frames: number, matched: number, offsets: number, missing: number, extra: number}, indexPath: string | null, summaryPath: string | null}} CompareData */
11
+
12
+ /**
13
+ * Attach observed command data without replacing a typed boundary's code or message.
14
+ * @param {unknown} error
15
+ * @param {{complete: boolean}} data
16
+ * @param {import('../cli-output.mjs').Diagnostic[]} warnings
17
+ * @param {import('../cli-output.mjs').ErrorCode} [fallback]
18
+ */
19
+ export function commandFailure(error, data, warnings, fallback = 'INTERNAL_ERROR') {
20
+ const classified = classifyError(error);
21
+ const failure = error instanceof CliError ? error : new CliError(classified.error.code === 'INTERNAL_ERROR' ? fallback : classified.error.code, classified.error.message, { cause: error });
22
+ if (!['CHECK_FAILED', 'COMPARE_FAILED'].includes(failure.code)) data.complete = false;
23
+ failure.data = data;
24
+ failure.warnings = [...new Set([...warnings, ...failure.warnings])];
25
+ return failure;
26
+ }
27
+
28
+ /** Always attempt cleanup, retaining an earlier operation failure as primary.
29
+ * @param {() => Promise<unknown>} close
30
+ * @param {unknown} primary
31
+ */
32
+ export async function cleanup(close, primary) {
33
+ try { await close(); }
34
+ catch (error) {
35
+ const failure = new CliError('SHUTDOWN_FAILED', error instanceof Error ? error.message : String(error), { cause: error });
36
+ if (primary instanceof CliError) primary.warnings.push(classifyError(failure).error);
37
+ else if (!primary) throw failure;
38
+ }
39
+ }
40
+
41
+ /** @param {import('../cli-output.mjs').Diagnostic[]} warnings */
42
+ export function emptySelection(warnings) {
43
+ warnings.push({ code: 'EMPTY_SELECTION', message: 'No sources or fixture frames were selected.', next: [] });
44
+ }
@@ -0,0 +1,14 @@
1
+ export type Content = unknown;
2
+ export type Capture = ({ region: string; selector?: never; page?: never } | { selector: string; region?: never; page?: never } | { page: true; region?: never; selector?: never }) & { viewport?: string; origin?: string; clicks?: string[] };
3
+ export interface FrameProps { name: string; width?: number; height?: number; fixture?: string; capture?: Capture; note?: string; children?: Content }
4
+ export interface IconProps { name: string; size?: number; class?: string }
5
+ export function Frame(props: FrameProps): JSX.Element;
6
+ export function Icon(props: IconProps): JSX.Element;
7
+ export function jsx(type: unknown, props: unknown): JSX.Element;
8
+ export { jsx as jsxs, jsx as jsxDEV };
9
+ export function Fragment(props: { children?: Content }): JSX.Element;
10
+ export namespace JSX {
11
+ type Element = any;
12
+ interface ElementChildrenAttribute { children: {} }
13
+ interface IntrinsicElements { [name: string]: { class?: string; children?: Content; [attribute: string]: unknown } }
14
+ }
@@ -0,0 +1,54 @@
1
+ import { icons } from 'lucide';
2
+ export const escape = value => String(value).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
3
+ const voids = new Set('area base br col embed hr img input link meta param source track wbr'.split(' '));
4
+ export const markup = html => ({ html, toString() { return this.html; } });
5
+ export function children(value) {
6
+ if (value == null || typeof value === 'boolean') return '';
7
+ if (Array.isArray(value)) return value.map(children).join('');
8
+ if (typeof value === 'object' && typeof value.html === 'string') return value.html;
9
+ return escape(value);
10
+ }
11
+ export function attributes(props) {
12
+ return Object.entries(props).filter(([key, value]) => !['children', 'key', '__source'].includes(key) && value != null && value !== false).map(([key, value]) => {
13
+ if (/^on/i.test(key) || key === 'className' || key === 'dangerouslySetInnerHTML') throw Error(`Forbidden attribute ${key}; use static markup and class`);
14
+ if (key === 'style' && typeof value === 'object') value = Object.entries(value).map(([name, v]) => `${name.startsWith('--') ? name : name.replace(/[A-Z]/g, c => '-' + c.toLowerCase())}:${typeof v === 'number' && !/^(opacity|zIndex|fontWeight|lineHeight|flex|flexGrow|flexShrink|order|gridColumn|gridRow|scale)$/.test(name) && !name.startsWith('--') ? v + 'px' : v}`).join(';');
15
+ return ` ${key}="${escape(value === true ? '' : value)}"`;
16
+ }).join('');
17
+ }
18
+ const componentOwners = new WeakMap();
19
+ export function registerComponent(component, source, name) {
20
+ if (typeof component === 'function' && !componentOwners.has(component)) componentOwners.set(component, {source, export:name});
21
+ }
22
+ const stamp = (value, owner) => Array.isArray(value) ? value.map(item => stamp(item, owner)) : value?.withOwner ? value.withOwner(owner) : value;
23
+ export const Fragment = ({ children: value }) => ({...markup(children(value)), withOwner:owner => Fragment({children:stamp(value,owner)})});
24
+ export function jsx(type, props = {}) {
25
+ if (typeof type === 'function') {
26
+ const value = type(props), owner = componentOwners.get(type);
27
+ return owner ? stamp(value, owner) : value;
28
+ }
29
+ if (['script', 'style'].includes(type.toLowerCase())) throw Error(`Forbidden <${type}>; use tokens and utility classes`);
30
+ const result = markup(`<${type}${attributes(props)}>${voids.has(type) ? '' : children(props.children) + `</${type}>`}`);
31
+ result.withOwner = owner => jsx(type, {...props, 'data-adg-owners':JSON.stringify([...(props['data-adg-owners'] ? JSON.parse(props['data-adg-owners']) : []), owner])});
32
+ return result;
33
+ }
34
+ export const jsxs = jsx;
35
+ export function jsxDEV(type, props, key, isStatic, source) {
36
+ try { return jsx(type, props); }
37
+ catch (error) { if (!error.located && source) { error.message = `${source.fileName}:${source.lineNumber}:${source.columnNumber}: ${error.message}`; error.located = true; } throw error; }
38
+ }
39
+ export function Frame({ children: content, ...props }) { return { frame: true, ...props, html: children(content) }; }
40
+ export function Icon({ name, size = 16, class: className, ...props }) {
41
+ const key = name.split('-').map(s => s[0].toUpperCase() + s.slice(1)).join('');
42
+ const geometry = icons[key];
43
+ if (!geometry) throw Error(`Unknown Lucide icon ${name}`);
44
+ return jsx('svg', { xmlns: 'http://www.w3.org/2000/svg', width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': 1.75 * 24 / size, 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true', class: className, ...props, children: geometry.map(([tag, attrs]) => jsx(tag, attrs)) });
45
+ }
46
+ export function artwork(source, props) {
47
+ const match = source.match(/<svg\b([^>]*)>([\s\S]*)<\/svg>/i);
48
+ if (!match) throw Error('Invalid SVG artwork');
49
+ let attrs = match[1];
50
+ for (const key of Object.keys(props)) attrs = attrs.replace(new RegExp(`\\s${key}\\s*=\\s*(["']).*?\\1`, 'g'), '');
51
+ const result = markup(`<svg${attrs}${attributes(props)}>${match[2]}</svg>`);
52
+ result.withOwner = owner => artwork(source, {...props, 'data-adg-owners':JSON.stringify([...(props['data-adg-owners'] ? JSON.parse(props['data-adg-owners']) : []), owner])});
53
+ return result;
54
+ }
@@ -0,0 +1,12 @@
1
+ export function matchTexts(design, implementation) {
2
+ const candidates = design.flatMap((d, di) => implementation.flatMap((i, ii) => d.text === i.text ? [{di,ii,distance:Math.hypot(d.x-i.x,d.y-i.y)}] : [])).sort((a,b)=>a.distance-b.distance);
3
+ const usedD=new Set(), usedI=new Set(), pairs=[];
4
+ for (const {di,ii} of candidates) if (!usedD.has(di) && !usedI.has(ii)) { usedD.add(di); usedI.add(ii); pairs.push([design[di],implementation[ii]]); }
5
+ return {pairs,missing:design.filter((_,i)=>!usedD.has(i)),extra:implementation.filter((_,i)=>!usedI.has(i))};
6
+ }
7
+
8
+ // Compares the anchored edge, vertical center and width of a paired text.
9
+ export function textDelta(design, implementation) {
10
+ const edge = box => design.anchor === 'middle' ? box.x + box.width / 2 : design.anchor === 'end' ? box.x + box.width : box.x;
11
+ return { dx: edge(implementation) - edge(design), dy: (implementation.y + implementation.height / 2) - (design.y + design.height / 2), dw: implementation.width - design.width };
12
+ }
@@ -0,0 +1,37 @@
1
+ import { CliError } from '../cli-output.mjs';
2
+ export function parseTokens(css) {
3
+ const source = css.replace(/\/\*[\s\S]*?\*\//g, '');
4
+ const blocks = [...source.matchAll(/([^{}]+)\{([^{}]*)\}/g)];
5
+ if (blocks.length !== 2 || source.replace(/[^{}]+\{[^{}]*\}/g, '').trim() ||
6
+ blocks[0][1].trim() !== ':root' || blocks[1][1].trim() !== ':root[data-theme="dark"]') {
7
+ throw new CliError('TOKENS_INVALID', 'tokens.css needs exactly :root and :root[data-theme="dark"] blocks; fix the token source');
8
+ }
9
+ const maps = blocks.map(([, , body]) => {
10
+ const map = new Map();
11
+ for (const line of body.split('\n').map(line => line.trim()).filter(Boolean)) {
12
+ const match = line.match(/^(--[\w-]+)\s*:\s*([^;]+);$/);
13
+ if (!match || map.has(match[1])) throw new CliError('TOKENS_INVALID', `Invalid token declaration ${line}; put each unique token on its own line`);
14
+ map.set(match[1], match[2].trim());
15
+ }
16
+ return map;
17
+ });
18
+ for (const key of ['--font-ui', '--font-mono', '--canvas', '--text']) {
19
+ if (!maps[0].has(key)) throw new CliError('TOKENS_INVALID', `tokens.css is missing ${key}; add it to :root`);
20
+ }
21
+ for (const key of maps[1].keys()) if (!maps[0].has(key)) throw new CliError('TOKENS_INVALID', `Dark token ${key} has no light value; add it to :root`);
22
+ return { light: maps[0], dark: maps[1] };
23
+ }
24
+
25
+ const namedColors = new Set(('aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkgrey darkkhaki darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray darkslategrey darkturquoise darkviolet deeppink deepskyblue dimgray dimgrey dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow grey honeydew hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen lightgrey lightpink lightsalmon lightseagreen lightskyblue lightslategray lightslategrey lightsteelblue lightyellow lime limegreen linen magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna silver skyblue slateblue slategray slategrey snow springgreen steelblue tan teal thistle tomato transparent turquoise violet wheat white whitesmoke yellow yellowgreen').split(' '));
26
+ export function themeCss(tokens) {
27
+ const color = (value, seen = new Set()) => {
28
+ const alias = /^var\((--[\w-]+)\)$/.exec(value);
29
+ if (alias) { if (seen.has(alias[1])) return false; seen.add(alias[1]); return color(tokens.light.get(alias[1]) ?? '', seen); }
30
+ return namedColors.has(value.toLowerCase()) || /^(#|rgba?\(|hsla?\(|oklch\(|oklab\(|lab\(|lch\(|color\(|color-mix\(|(?:transparent|black|white|red|blue|green|rebeccapurple|orange|purple|pink|gray|grey|yellow|cyan|magenta|currentColor)$)/i.test(value);
31
+ };
32
+ const declarations = [...tokens.light].flatMap(([key, value]) => {
33
+ const theme = color(value) ? '--color-' + key.slice(2) : /^(--font-|--radius-|--shadow-)/.test(key) || (key.startsWith('--text-') && /^[-.\d]+(?:px|rem|em|ch)$/.test(value)) ? key : null;
34
+ return theme ? [`${theme}:var(${key});`] : [];
35
+ });
36
+ return `@theme { --color-*:initial; --text-*:initial; --font-*:initial; --radius-*:initial; --shadow-*:initial; --inset-shadow-*:initial; --drop-shadow-*:initial; --text-shadow-*:initial; }\n@theme inline reference { ${declarations.join('\n')} }`;
37
+ }
@@ -0,0 +1,85 @@
1
+ import {createHash,randomUUID} from 'node:crypto';
2
+ import {readFile,writeFile,mkdir,rename,rm} from 'node:fs/promises';
3
+ import path from 'node:path';
4
+
5
+ const digest = value => createHash('sha256').update(value).digest('hex');
6
+ // Geometry and ready-to-decode SVGs are derived data, scoped to one project and
7
+ // browser measurement context. Source files are never written by this cache.
8
+ export async function createViewerCache(directory, {memoryBytes=32*1024*1024,diskBytes=256*1024*1024}={}) {
9
+ await mkdir(directory,{recursive:true});
10
+ const indexPath=path.join(directory,'index.json');
11
+ let entries=new Map(), total=0, residentBytes=0, pending=Promise.resolve();
12
+ const resident=new Map();
13
+ try {
14
+ const data=JSON.parse(await readFile(indexPath,'utf8'));
15
+ if(data.version===1) entries=new Map(data.entries.map(entry=>[entry.key,entry]));
16
+ } catch(error) {if(error.code!=='ENOENT' && !(error instanceof SyntaxError)) throw error;}
17
+ total=[...entries.values()].reduce((n,entry)=>n+entry.bytes,0);
18
+ const keyFor=(hash,theme,context)=>digest(JSON.stringify([hash,theme,context]));
19
+ function remember(key,metadata) {
20
+ if(resident.has(key)){residentBytes-=resident.get(key).bytes;resident.delete(key);}
21
+ const bytes=Buffer.byteLength(JSON.stringify(metadata));
22
+ if(bytes>memoryBytes)return;
23
+ resident.set(key,{metadata,bytes});residentBytes+=bytes;
24
+ while(residentBytes>memoryBytes){const first=resident.keys().next().value;residentBytes-=resident.get(first).bytes;resident.delete(first);}
25
+ }
26
+ async function persist() {
27
+ const temporary=indexPath+'.'+randomUUID()+'.tmp';
28
+ await writeFile(temporary,JSON.stringify({version:1,entries:[...entries.values()]}));
29
+ await rename(temporary,indexPath);
30
+ }
31
+ async function trim() {
32
+ for(const entry of [...entries.values()].sort((a,b)=>a.used-b.used)) {
33
+ if(total<=diskBytes && entries.size<=2048)break;
34
+ entries.delete(entry.key);total-=entry.bytes;
35
+ if(resident.has(entry.key)){residentBytes-=resident.get(entry.key).bytes;resident.delete(entry.key);}
36
+ await rm(path.join(directory,entry.key),{recursive:true,force:true});
37
+ }
38
+ }
39
+ function mutate(operation) {
40
+ const result=pending.then(operation);
41
+ pending=result.catch(()=>{});
42
+ return result;
43
+ }
44
+ async function get(hash,theme,context) {
45
+ const key=keyFor(hash,theme,context),entry=entries.get(key);
46
+ if(!entry)return null;
47
+ let metadata=resident.get(key)?.metadata;
48
+ if(!metadata){try{metadata=JSON.parse(await readFile(path.join(directory,key,'metadata.json'),'utf8'));}catch(error){if(error.code==='ENOENT')return null;throw error;}}
49
+ if(resident.has(key)){const item=resident.get(key);resident.delete(key);resident.set(key,item);}else remember(key,metadata);entry.used=Date.now();
50
+ return {metadata,previewIds:Object.keys(entry.previews)};
51
+ }
52
+ async function save(hash,theme,context,metadata) {
53
+ return mutate(async()=>{
54
+ const key=keyFor(hash,theme,context),location=path.join(directory,key),text=JSON.stringify(metadata);
55
+ await mkdir(location,{recursive:true});
56
+ const temporary=path.join(location,'metadata.'+randomUUID()+'.tmp');
57
+ await writeFile(temporary,text);
58
+ await rename(temporary,path.join(location,'metadata.json'));
59
+ const old=entries.get(key),bytes=Buffer.byteLength(text);
60
+ const entry={key,hash,theme,context,metadataBytes:bytes,previews:old?.previews??{},bytes:bytes+Object.values(old?.previews??{}).reduce((n,p)=>n+p.bytes,0),used:Date.now()};
61
+ total+=entry.bytes-(old?.bytes??0);entries.set(key,entry);remember(key,metadata);
62
+ await trim();await persist();
63
+ });
64
+ }
65
+ async function savePreview(hash,theme,context,crop,source) {
66
+ return mutate(async()=>{
67
+ const key=keyFor(hash,theme,context),entry=entries.get(key);
68
+ if(!entry)return false;
69
+ const filename=digest(crop)+'.svg',bytes=Buffer.byteLength(source),location=path.join(directory,key,filename);
70
+ const temporary=location+'.'+randomUUID()+'.tmp';
71
+ await writeFile(temporary,source);await rename(temporary,location);
72
+ const previous=entry.previews[crop]?.bytes??0;
73
+ entry.previews[crop]={filename,bytes};entry.bytes+=bytes-previous;entry.used=Date.now();total+=bytes-previous;
74
+ await trim();await persist();return entries.has(key);
75
+ });
76
+ }
77
+ async function preview(hash,theme,context,crop) {
78
+ const entry=entries.get(keyFor(hash,theme,context)),item=entry?.previews[crop];
79
+ if(!item)return null;
80
+ try {const body=await readFile(path.join(directory,entry.key,item.filename));entry.used=Date.now();return body;}
81
+ catch(error){if(error.code==='ENOENT')return null;throw error;}
82
+ }
83
+ const reference=(hash,theme,context)=>{const entry=entries.get(keyFor(hash,theme,context));if(entry)entry.used=Date.now();return entry?{previewIds:Object.keys(entry.previews)}:null;};
84
+ return {get,reference,save,savePreview,preview,close:()=>pending,stats:()=>({entries:entries.size,residentBytes,diskBytes:total})};
85
+ }