@whzxc/agent-design-gallery 0.6.0 → 0.8.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.
- package/README.md +12 -1
- package/package.json +1 -1
- package/public/app.js +38 -10
- package/public/arrangement-worker.js +11 -0
- package/public/arrangement.js +49 -0
- package/public/assets.js +16 -4
- package/public/layout.js +29 -13
- package/src/cli-output.mjs +258 -0
- package/src/cli.mjs +120 -45
- package/src/http.mjs +1 -0
- package/src/hub/auth.mjs +2 -1
- package/src/hub/proxy.mjs +5 -3
- package/src/hub/registry.mjs +57 -23
- package/src/hub.mjs +36 -21
- package/src/lifecycle.mjs +109 -0
- package/src/link.mjs +10 -9
- package/src/open.mjs +58 -54
- package/src/perf.mjs +12 -0
- package/src/server.mjs +78 -41
- package/src/service.mjs +115 -94
- package/src/toolkit/arch-git.mjs +142 -10
- package/src/toolkit/arch-overlay.mjs +1 -1
- package/src/toolkit/arch.mjs +62 -58
- package/src/toolkit/browser.mjs +38 -12
- package/src/toolkit/build-store.mjs +11 -3
- package/src/toolkit/build-worker.mjs +4 -1
- package/src/toolkit/build.mjs +26 -2
- package/src/toolkit/commands.mjs +158 -86
- package/src/toolkit/compare.mjs +93 -46
- package/src/toolkit/config.mjs +23 -20
- package/src/toolkit/diff-inputs.mjs +239 -0
- package/src/toolkit/diff-policy.mjs +28 -0
- package/src/toolkit/diff.mjs +258 -0
- package/src/toolkit/migrate.mjs +42 -30
- package/src/toolkit/part-diff.mjs +118 -0
- package/src/toolkit/part-snapshot.mjs +264 -0
- package/src/toolkit/pixel-diff.mjs +103 -0
- package/src/toolkit/project.mjs +45 -33
- package/src/toolkit/results.mjs +44 -0
- package/src/toolkit/runtime.d.ts +2 -1
- package/src/toolkit/tokens.mjs +5 -4
package/src/toolkit/arch-git.mjs
CHANGED
|
@@ -1,8 +1,28 @@
|
|
|
1
|
-
import { execFile } from 'node:child_process';
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
2
|
import { promisify } from 'node:util';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
-
import { realpath } from 'node:fs/promises';
|
|
4
|
+
import { realpath, mkdtemp, mkdir, open, symlink, rm } from 'node:fs/promises';
|
|
5
|
+
import { tmpdir } from 'node:os';
|
|
6
|
+
import { pathToFileURL } from 'node:url';
|
|
7
|
+
import { CliError, asCliError } from '../cli-output.mjs';
|
|
8
|
+
import { cleanup } from './results.mjs';
|
|
5
9
|
const exec = promisify(execFile);
|
|
10
|
+
|
|
11
|
+
export function revisionValue(value, directory, root) {
|
|
12
|
+
if (typeof value === 'string') return value.replaceAll(pathToFileURL(directory).href, pathToFileURL(root).href).replaceAll(directory, root);
|
|
13
|
+
if (Array.isArray(value)) return value.map(item => revisionValue(item, directory, root));
|
|
14
|
+
if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, revisionValue(item, directory, root)]));
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function revisionError(error, directory, base) {
|
|
19
|
+
const failure = asCliError(error);
|
|
20
|
+
failure.message = `Base ${base.sha.slice(0, 7)}: ${revisionValue(failure.message, directory, base.root)}`;
|
|
21
|
+
failure.context = revisionValue(failure.context, directory, base.root);
|
|
22
|
+
failure.warnings = revisionValue(failure.warnings, directory, base.root);
|
|
23
|
+
failure.data = null;
|
|
24
|
+
return failure;
|
|
25
|
+
}
|
|
6
26
|
async function physicalPath(file) {
|
|
7
27
|
try { return await realpath(file); }
|
|
8
28
|
catch(error) {
|
|
@@ -12,26 +32,138 @@ async function physicalPath(file) {
|
|
|
12
32
|
}
|
|
13
33
|
}
|
|
14
34
|
async function git(root, args) {
|
|
15
|
-
try {
|
|
35
|
+
try {
|
|
36
|
+
const task = exec('git', ['-C', root, ...args], { maxBuffer: 16 * 1024 * 1024 });
|
|
37
|
+
task.child.stdin.end();
|
|
38
|
+
return (await task).stdout;
|
|
39
|
+
}
|
|
16
40
|
catch(error) {
|
|
17
|
-
if(error.code==='ENOENT')throw
|
|
18
|
-
throw error;
|
|
41
|
+
if(error.code==='ENOENT')throw new CliError('GIT_UNAVAILABLE', 'Git is unavailable; install Git and retry --base.', { cause: error });
|
|
42
|
+
throw new CliError('GIT_BASE_INVALID', error.message, { cause: error, context: { project: root, gitCause: 'read' } });
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function writeBaseBlobs(base, directory, entries) {
|
|
47
|
+
const child = spawn('git', ['-C', base.root, 'cat-file', '--batch']);
|
|
48
|
+
let stderr = '', spawnError;
|
|
49
|
+
child.stderr.setEncoding('utf8');
|
|
50
|
+
child.stderr.on('data', text => { stderr = (stderr + text).slice(-16384); });
|
|
51
|
+
child.stdin.on('error', () => {});
|
|
52
|
+
const done = new Promise((resolve, reject) => {
|
|
53
|
+
child.once('error', error => { spawnError = error; reject(error); });
|
|
54
|
+
child.once('close', code => code === 0 ? resolve() : reject(new Error(stderr || `Git cat-file exited ${code}.`)));
|
|
55
|
+
});
|
|
56
|
+
done.catch(() => {});
|
|
57
|
+
const chunks = child.stdout[Symbol.asyncIterator]();
|
|
58
|
+
let pending = Buffer.alloc(0);
|
|
59
|
+
const refill = async () => {
|
|
60
|
+
const next = await chunks.next();
|
|
61
|
+
if (next.done) throw new Error(stderr || 'Git blob stream ended early.');
|
|
62
|
+
pending = next.value;
|
|
63
|
+
};
|
|
64
|
+
try {
|
|
65
|
+
for (const entry of entries) {
|
|
66
|
+
if (entry.type !== 'blob') continue;
|
|
67
|
+
const target = path.join(directory, entry.name);
|
|
68
|
+
await mkdir(path.dirname(target), { recursive: true });
|
|
69
|
+
child.stdin.write(`${entry.blob}\n`);
|
|
70
|
+
let header = '';
|
|
71
|
+
for (;;) {
|
|
72
|
+
if (!pending.length) await refill();
|
|
73
|
+
const end = pending.indexOf(10);
|
|
74
|
+
if (end >= 0) {
|
|
75
|
+
header += pending.subarray(0, end).toString('ascii');
|
|
76
|
+
pending = pending.subarray(end + 1);
|
|
77
|
+
break;
|
|
78
|
+
}
|
|
79
|
+
header += pending.toString('ascii'); pending = Buffer.alloc(0);
|
|
80
|
+
}
|
|
81
|
+
const [id, type, length] = header.split(' ');
|
|
82
|
+
if (id !== entry.blob || type !== 'blob' || !/^\d+$/.test(length)) throw new Error(`Cannot read Git blob ${entry.blob}.`);
|
|
83
|
+
const linkChunks = [];
|
|
84
|
+
const file = entry.mode === '120000' ? null : await open(target, 'w', entry.mode === '100755' ? 0o755 : 0o644);
|
|
85
|
+
try {
|
|
86
|
+
let remaining = Number(length);
|
|
87
|
+
while (remaining > 0) {
|
|
88
|
+
if (!pending.length) await refill();
|
|
89
|
+
const count = Math.min(remaining, pending.length), bytes = pending.subarray(0, count);
|
|
90
|
+
if (file) await file.writeFile(bytes);
|
|
91
|
+
else linkChunks.push(bytes);
|
|
92
|
+
pending = pending.subarray(count); remaining -= count;
|
|
93
|
+
}
|
|
94
|
+
} finally { await file?.close(); }
|
|
95
|
+
if (!pending.length) await refill();
|
|
96
|
+
if (pending[0] !== 10) throw new Error('Invalid Git blob separator.');
|
|
97
|
+
pending = pending.subarray(1);
|
|
98
|
+
if (!file) {
|
|
99
|
+
const link = Buffer.concat(linkChunks).toString('utf8');
|
|
100
|
+
const relative = path.relative(directory, path.resolve(path.dirname(target), link));
|
|
101
|
+
if (!path.isAbsolute(link) && relative !== '..' && !relative.startsWith(`..${path.sep}`)) await symlink(link, target);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
child.stdin.end();
|
|
105
|
+
await done;
|
|
106
|
+
} catch (error) {
|
|
107
|
+
if (spawnError?.code === 'ENOENT') throw new CliError('GIT_UNAVAILABLE', 'Git is unavailable; install Git and retry --base.', { cause: spawnError });
|
|
108
|
+
if (error.code) throw error;
|
|
109
|
+
throw new CliError('GIT_BASE_INVALID', error.message, { cause: error, context: { project: base.root, gitCause: 'read' } });
|
|
110
|
+
} finally {
|
|
111
|
+
if (child.exitCode === null) child.kill();
|
|
112
|
+
await done.catch(() => {});
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Materialize tracked bytes without export attributes or a Git worktree. */
|
|
117
|
+
export async function materializeBase(base) {
|
|
118
|
+
const directory = await realpath(await mkdtemp(path.join(tmpdir(), 'adg-diff-')));
|
|
119
|
+
const close = async () => {
|
|
120
|
+
try { await cleanup(() => rm(directory, { recursive: true, force: true })); }
|
|
121
|
+
catch (error) { throw revisionError(error, directory, base); }
|
|
122
|
+
};
|
|
123
|
+
try {
|
|
124
|
+
const tree = await git(base.root, ['ls-tree', '-r', '-z', base.sha]);
|
|
125
|
+
const entries = tree.split('\0').filter(Boolean).map(entry => {
|
|
126
|
+
const [, mode, type, blob, name] = /^(\d{6}) (blob|commit) ([a-f0-9]+)\t([\s\S]+)$/.exec(entry);
|
|
127
|
+
return { mode, type, blob, name };
|
|
128
|
+
});
|
|
129
|
+
await writeBaseBlobs(base, directory, entries);
|
|
130
|
+
return { directory, close };
|
|
131
|
+
} catch (error) {
|
|
132
|
+
const failure = revisionError(error, directory, base);
|
|
133
|
+
await cleanup(() => rm(directory, { recursive: true, force: true }), failure);
|
|
134
|
+
failure.warnings = revisionValue(failure.warnings, directory, base.root);
|
|
135
|
+
throw failure;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export async function currentHead(base) {
|
|
140
|
+
try { return (await git(base.root, ['rev-parse', '--verify', 'HEAD'])).trim(); }
|
|
141
|
+
catch (error) { if (error.code === 'GIT_UNAVAILABLE') throw error; return null; }
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Rename hints include staged and unstaged tracked changes against the base. */
|
|
145
|
+
export async function sourceRenames(base) {
|
|
146
|
+
const fields = (await git(base.root, ['diff', '--name-status', '-z', '--find-renames', '--diff-filter=R', base.sha, '--'])).split('\0');
|
|
147
|
+
const renames = [];
|
|
148
|
+
for (let index = 0; index < fields.length - 1; index += 3) {
|
|
149
|
+
renames.push({ before: fields[index + 1], after: fields[index + 2] });
|
|
19
150
|
}
|
|
151
|
+
return renames;
|
|
20
152
|
}
|
|
21
153
|
export async function resolveBase(config, rev) {
|
|
22
|
-
if(typeof rev!=='string'||!rev.trim())throw
|
|
154
|
+
if(typeof rev!=='string'||!rev.trim())throw new CliError('USAGE_INVALID', 'Set --base to a Git revision, for example HEAD.');
|
|
23
155
|
let root;
|
|
24
156
|
try { root=await realpath((await git(config.root,['rev-parse','--show-toplevel'])).trim()); }
|
|
25
157
|
catch(error) {
|
|
26
|
-
if(error.
|
|
27
|
-
throw
|
|
158
|
+
if(error.code==='GIT_UNAVAILABLE')throw error;
|
|
159
|
+
throw new CliError('GIT_BASE_INVALID', 'This project is not in a Git repository; run from a repository or initialize one before using --base.', { cause: error, context: { project: config.root, gitCause: 'repository' } });
|
|
28
160
|
}
|
|
29
161
|
try {
|
|
30
162
|
const sha=(await git(root,['rev-parse','--verify','--end-of-options',`${rev}^{commit}`])).trim();
|
|
31
163
|
return {root,rev,sha};
|
|
32
164
|
} catch(error) {
|
|
33
|
-
if(error.
|
|
34
|
-
throw
|
|
165
|
+
if(error.code==='GIT_UNAVAILABLE')throw error;
|
|
166
|
+
throw new CliError('GIT_BASE_INVALID', `Unknown Git revision ${rev}; choose an existing commit or fetch the revision and retry --base.`, { cause: error, context: { project: root, gitCause: 'revision' } });
|
|
35
167
|
}
|
|
36
168
|
}
|
|
37
169
|
export async function readBase(base, file) {
|
|
@@ -206,7 +206,7 @@ export async function buildOverlay(config,file,{base,browser,snapshot}={}) {
|
|
|
206
206
|
const old=await readBase(base,file),bytes=readFileSync(file);snapshot.set(file,bytes);
|
|
207
207
|
const text=bytes.toString('utf8');
|
|
208
208
|
const checked=inspectArch(text,Infinity);
|
|
209
|
-
if(checked.problems.length)throw Error(checked.problems.join('\n'));
|
|
209
|
+
if(checked.problems.length)throw Error(checked.problems.map(problem=>problem.message).join('\n'));
|
|
210
210
|
const overlay=overlayModels(checked.model,old.text===null?null:parse(old.text));
|
|
211
211
|
const built=await buildArch(config,file,{model:overlay.model,browser,snapshot});
|
|
212
212
|
const frame=built.frames[0],used=new Set(checked.classes);
|
package/src/toolkit/arch.mjs
CHANGED
|
@@ -2,7 +2,8 @@ import { readFileSync, existsSync, globSync, statSync } from 'node:fs';
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { parse, render } from 'pele';
|
|
4
4
|
import { parseTokens } from './tokens.mjs';
|
|
5
|
-
import { launch } from './browser.mjs';
|
|
5
|
+
import { launch, browserTask } from './browser.mjs';
|
|
6
|
+
import { cleanup } from './results.mjs';
|
|
6
7
|
|
|
7
8
|
export const phases = ['progress', 'waiting', 'done', 'stopped', 'uncertain'];
|
|
8
9
|
export const marks = ['experimental', 'temporary', 'gap'];
|
|
@@ -10,34 +11,36 @@ export const vocabulary = [...phases, ...marks];
|
|
|
10
11
|
const reserved = ['added', 'removed', 'changed'];
|
|
11
12
|
|
|
12
13
|
export function sidecar(text = '') {
|
|
13
|
-
const problems = [], owners = []; let status, body = text.trim();
|
|
14
|
+
const problems = [], owners = [], ownerLines = []; let status, body = text.trim();
|
|
15
|
+
const add = (code, message, line = null) => problems.push({code, message, line, column:null});
|
|
14
16
|
if (/^---\r?\n/.test(text)) {
|
|
15
17
|
const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)([\s\S]*)$/.exec(text);
|
|
16
|
-
if (!match) return {owners, body:'', problems:['Unclosed sidecar frontmatter']};
|
|
18
|
+
if (!match) return {owners, ownerLines, body:'', problems:[{code:'ARCH_SIDECAR_INVALID',message:'Unclosed sidecar frontmatter',line:1,column:null}]};
|
|
17
19
|
body = match[2].trim(); let current; const keys = new Set();
|
|
18
20
|
const scalar = value => {
|
|
19
21
|
const quoted = /^(["'])(.*)\1$/.exec(value);
|
|
20
22
|
return quoted ? quoted[2] : value;
|
|
21
23
|
};
|
|
22
|
-
for (const raw of match[1].split(/\r?\n/)) {
|
|
24
|
+
for (const [index, raw] of match[1].split(/\r?\n/).entries()) {
|
|
25
|
+
const line = index + 2;
|
|
23
26
|
if (!raw.trim()) continue;
|
|
24
27
|
const key = /^(owners|status):\s*(.*)$/.exec(raw);
|
|
25
28
|
if (key) {
|
|
26
29
|
current = key[1];
|
|
27
|
-
if (keys.has(current))
|
|
30
|
+
if (keys.has(current)) add('ARCH_SIDECAR_INVALID', `Duplicate sidecar frontmatter key ${current}`, line);
|
|
28
31
|
keys.add(current);
|
|
29
32
|
if (current === 'status' && key[2].trim()) status = scalar(key[2].trim());
|
|
30
33
|
else if (current === 'owners' && !key[2].trim()) continue;
|
|
31
|
-
else
|
|
34
|
+
else add('ARCH_SIDECAR_INVALID', `Invalid sidecar ${current}; use ${current === 'owners' ? 'an indented list' : 'a non-empty string'}`, line);
|
|
32
35
|
} else {
|
|
33
36
|
const item = /^ +-[ \t]+(.+)$/.exec(raw);
|
|
34
|
-
if (item && current === 'owners') owners.push(scalar(item[1].trim()));
|
|
35
|
-
else
|
|
37
|
+
if (item && current === 'owners') { owners.push(scalar(item[1].trim())); ownerLines.push(line); }
|
|
38
|
+
else add('ARCH_SIDECAR_INVALID', `Invalid sidecar frontmatter key or entry: ${raw.trim()}`, line);
|
|
36
39
|
}
|
|
37
40
|
}
|
|
38
41
|
}
|
|
39
|
-
for (const owner of owners) if (path.isAbsolute(owner) || owner.split('/').includes('..') || owner.includes('\\'))
|
|
40
|
-
return {owners,status,body,problems};
|
|
42
|
+
for (const [index, owner] of owners.entries()) if (path.isAbsolute(owner) || owner.split('/').includes('..') || owner.includes('\\')) add('ARCH_OWNER_INVALID', `Invalid owners path ${owner}; use project-root-relative paths or globs`, ownerLines[index] ?? null);
|
|
43
|
+
return {owners,ownerLines,status,body,problems};
|
|
41
44
|
}
|
|
42
45
|
|
|
43
46
|
// Preserve newlines and statement delimiters while masking quoted labels and comments.
|
|
@@ -61,9 +64,10 @@ function statements(text) {
|
|
|
61
64
|
}
|
|
62
65
|
export function inspectArch(text, maxEdges = 30) {
|
|
63
66
|
const problems=[], classes=new Set(), clean=statements(text);
|
|
67
|
+
const add=(code,message,line=null)=>problems.push({code,message,line,column:null});
|
|
64
68
|
for (const match of clean.matchAll(/(?:^|[;\n])\s*(classDef|style|linkStyle)\b/g)) {
|
|
65
69
|
const line=clean.slice(0,match.index+match[0].length).split('\n').length;
|
|
66
|
-
|
|
70
|
+
add('ARCH_PAINT_FORBIDDEN', `Painting statement ${match[1]} at line ${line}; paint comes from tokens`, line);
|
|
67
71
|
}
|
|
68
72
|
// Inspect configuration keys without interpreting words inside prose or values.
|
|
69
73
|
const configRegions=[...text.matchAll(/%%\{[\s\S]*?\}%%/g), ...text.matchAll(/^---\r?\n[\s\S]*?\r?\n---/g)];
|
|
@@ -74,7 +78,7 @@ export function inspectArch(text, maxEdges = 30) {
|
|
|
74
78
|
if(!/[{,]\s*$/.test(before) && !/^[ \t]*(?:-[ \t]+)?$/.test(lineStart))continue;
|
|
75
79
|
const key=token[0].replace(/^["']|["']$/g,'');
|
|
76
80
|
if(/^(?:theme\w*|[\w-]*color[\w-]*|fill|stroke|background)$/i.test(key))
|
|
77
|
-
|
|
81
|
+
add('ARCH_PAINT_FORBIDDEN', `Painting directive/frontmatter key ${key} at line ${text.slice(0,region.index+token.index).split('\n').length}; paint comes from tokens`, text.slice(0,region.index+token.index).split('\n').length);
|
|
78
82
|
}
|
|
79
83
|
let model;
|
|
80
84
|
try {
|
|
@@ -82,32 +86,32 @@ export function inspectArch(text, maxEdges = 30) {
|
|
|
82
86
|
// The state graph flattens composite states; relations contains only root edges.
|
|
83
87
|
const count=(model.type==='state' ? model.graph.edges :
|
|
84
88
|
[model.edges,model.relations,model.messages,model.relationships,model.rels,model.graph?.edges,model.links].find(Array.isArray)??[]).length;
|
|
85
|
-
if(count>maxEdges)
|
|
86
|
-
} catch(error) {
|
|
89
|
+
if(count>maxEdges) add('ARCH_EDGE_LIMIT', `${count} edges/messages exceeds check.archMaxEdges (${maxEdges})`);
|
|
90
|
+
} catch(error) { add('ARCH_SYNTAX', `Pele: ${error.message.replace(/\s+/g,' ')} (line ${error.line ?? 1})`, error.line ?? null); }
|
|
87
91
|
if(model?.type==='flowchart' || model?.type==='state') {
|
|
88
|
-
const
|
|
92
|
+
const addClass=value=>{for(const name of (Array.isArray(value)?value.join(' '):value??'').split(/[ \t,]+/).filter(Boolean))classes.add(name);};
|
|
89
93
|
if(model.type==='flowchart') {
|
|
90
|
-
for(const node of model.nodes.values())
|
|
91
|
-
for(const item of [...model.edges,...model.subgraphs])
|
|
94
|
+
for(const node of model.nodes.values())addClass(node.classes);
|
|
95
|
+
for(const item of [...model.edges,...model.subgraphs])addClass(item.classes);
|
|
92
96
|
} else {
|
|
93
97
|
const visit=statements=>{for(const stmt of statements??[]) {
|
|
94
|
-
if(stmt.stmt==='applyClass')
|
|
95
|
-
|
|
98
|
+
if(stmt.stmt==='applyClass')addClass(stmt.styleClass);
|
|
99
|
+
addClass(stmt.classes);addClass(stmt.state1?.classes);addClass(stmt.state2?.classes);
|
|
96
100
|
visit(stmt.doc);
|
|
97
101
|
}};
|
|
98
102
|
visit(model.rootDoc);
|
|
99
103
|
}
|
|
100
104
|
// Keep assignments to unresolved IDs visible to the vocabulary check, too.
|
|
101
|
-
for(const match of clean.matchAll(/(?:^|[;\n])[ \t]*class[ \t]+[^ \t;\r\n]+[ \t]+([^;\r\n]+)/g))
|
|
102
|
-
for(const name of classes)if(!vocabulary.includes(name))
|
|
105
|
+
for(const match of clean.matchAll(/(?:^|[;\n])[ \t]*class[ \t]+[^ \t;\r\n]+[ \t]+([^;\r\n]+)/g))addClass(match[1]);
|
|
106
|
+
for(const name of classes)if(!vocabulary.includes(name))add('ARCH_CLASS_INVALID', `${reserved.includes(name)?'Reserved':'Unknown'} class ${name}; vocabulary: ${vocabulary.join(', ')} (added, removed, changed are reserved)`);
|
|
103
107
|
}
|
|
104
108
|
return {model,classes:vocabulary.filter(name=>classes.has(name)),problems};
|
|
105
109
|
}
|
|
106
110
|
export function ownerProblems(config, metadata) {
|
|
107
|
-
return metadata.owners.flatMap(owner => {
|
|
111
|
+
return metadata.owners.flatMap((owner, index) => {
|
|
108
112
|
if(path.isAbsolute(owner) || owner.split('/').includes('..') || owner.includes('\\')) return [];
|
|
109
113
|
const matches=globSync(owner,{cwd:config.root,exclude:['**/node_modules/**','**/.git/**']});
|
|
110
|
-
return matches.some(file=>statSync(path.join(config.root,file),{throwIfNoEntry:false})?.isFile()) ? [] : [
|
|
114
|
+
return matches.some(file=>statSync(path.join(config.root,file),{throwIfNoEntry:false})?.isFile()) ? [] : [{code:'ARCH_OWNER_INVALID',message:`Owners entry ${owner} matches no file`,line:metadata.ownerLines?.[index]??null,column:null}];
|
|
111
115
|
});
|
|
112
116
|
}
|
|
113
117
|
|
|
@@ -137,41 +141,41 @@ export async function renderArch(model, tokenSource, {browser: suppliedBrowser}
|
|
|
137
141
|
const requests=new Map(),measured=new Map();
|
|
138
142
|
const key=(text,size,style)=>JSON.stringify([text,size,style]);
|
|
139
143
|
const browser=suppliedBrowser ?? await launch();
|
|
140
|
-
let page;
|
|
144
|
+
let page, primary;
|
|
141
145
|
try {
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
const
|
|
146
|
-
|
|
146
|
+
return await browserTask(browser, async () => {
|
|
147
|
+
page=await browser.newPage();
|
|
148
|
+
await page.setContent(`<style>${tokenSource.replace(/<\/style/gi,'<\\/style')}</style>`);
|
|
149
|
+
const fonts=await page.evaluate(()=>{
|
|
150
|
+
const style=getComputedStyle(document.documentElement);
|
|
151
|
+
return {ui:style.getPropertyValue('--font-ui').trim(),mono:style.getPropertyValue('--font-mono').trim()};
|
|
152
|
+
});
|
|
153
|
+
for(let pass=0;pass<16;pass++) {
|
|
154
|
+
const result=render(model,{fontFamily:fonts.ui,fontFamilyMono:fonts.mono,measurer:{width(text,size,style){
|
|
155
|
+
const id=key(text,size,style);
|
|
156
|
+
if(!measured.has(id))requests.set(id,{text,size,style});
|
|
157
|
+
return measured.get(id)??text.length*size*.6;
|
|
158
|
+
}}});
|
|
159
|
+
if(!requests.size)return result;
|
|
160
|
+
const widths=await page.evaluate(async requests=>{
|
|
161
|
+
const canvas=document.createElement('canvas').getContext('2d'),widths=requests.map(()=>0);
|
|
162
|
+
for(const theme of ['light','dark']) {
|
|
163
|
+
document.documentElement.dataset.theme=theme;
|
|
164
|
+
const style=getComputedStyle(document.documentElement),ui=style.getPropertyValue('--font-ui').trim(),mono=style.getPropertyValue('--font-mono').trim();
|
|
165
|
+
await document.fonts.ready;
|
|
166
|
+
requests.forEach(({text,size,style},i)=>{
|
|
167
|
+
canvas.font=`${style&2?'italic ':''}${style&1?'bold ':''}${size}px ${style&4?mono:ui}`;
|
|
168
|
+
widths[i]=Math.max(widths[i],canvas.measureText(text).width);
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
return widths;
|
|
172
|
+
},[...requests.values()]);
|
|
173
|
+
[...requests.keys()].forEach((id,i)=>measured.set(id,widths[i]));requests.clear();
|
|
174
|
+
}
|
|
175
|
+
throw Error('Pele label measurement did not settle after 16 passes');
|
|
147
176
|
});
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
const id=key(text,size,style);
|
|
151
|
-
if(!measured.has(id))requests.set(id,{text,size,style});
|
|
152
|
-
return measured.get(id)??text.length*size*.6;
|
|
153
|
-
}}});
|
|
154
|
-
if(!requests.size)return result;
|
|
155
|
-
const widths=await page.evaluate(async requests=>{
|
|
156
|
-
const canvas=document.createElement('canvas').getContext('2d'),widths=requests.map(()=>0);
|
|
157
|
-
for(const theme of ['light','dark']) {
|
|
158
|
-
document.documentElement.dataset.theme=theme;
|
|
159
|
-
const style=getComputedStyle(document.documentElement),ui=style.getPropertyValue('--font-ui').trim(),mono=style.getPropertyValue('--font-mono').trim();
|
|
160
|
-
await document.fonts.ready;
|
|
161
|
-
requests.forEach(({text,size,style},i)=>{
|
|
162
|
-
canvas.font=`${style&2?'italic ':''}${style&1?'bold ':''}${size}px ${style&4?mono:ui}`;
|
|
163
|
-
widths[i]=Math.max(widths[i],canvas.measureText(text).width);
|
|
164
|
-
});
|
|
165
|
-
}
|
|
166
|
-
return widths;
|
|
167
|
-
},[...requests.values()]);
|
|
168
|
-
[...requests.keys()].forEach((id,i)=>measured.set(id,widths[i]));requests.clear();
|
|
169
|
-
}
|
|
170
|
-
throw Error('Pele label measurement did not settle after 16 passes');
|
|
171
|
-
} finally {
|
|
172
|
-
if(suppliedBrowser) await page?.close();
|
|
173
|
-
else await browser.close();
|
|
174
|
-
}
|
|
177
|
+
} catch (cause) { primary=cause; throw cause; }
|
|
178
|
+
finally { await cleanup(() => suppliedBrowser ? page?.close() : browser.close(), primary); }
|
|
175
179
|
}
|
|
176
180
|
|
|
177
181
|
export async function buildArch(config,file,{snapshot,model:overlayModel,browser}={}) {
|
|
@@ -185,7 +189,7 @@ export async function buildArch(config,file,{snapshot,model:overlayModel,browser
|
|
|
185
189
|
parseTokens(tokenSource);
|
|
186
190
|
const checked=inspectArch(text,Infinity);
|
|
187
191
|
const problems=[...checked.problems,...metadata.problems];
|
|
188
|
-
if(problems.length)throw Error(problems.join('\n'));
|
|
192
|
+
if(problems.length)throw Error(problems.map(problem=>problem.message).join('\n'));
|
|
189
193
|
const result=await renderArch(overlayModel??checked.model,tokenSource,{browser});
|
|
190
194
|
const legend=checked.classes.length?`<div class="arch-legend">${checked.classes.map(name=>`<span class="arch-key ${name}" style="--arch-color:var(--arch-${name})"><i class="arch-swatch"></i>${name}</span>`).join('')}</div>`:'';
|
|
191
195
|
const html=`<section data-adg-arch>${legend}${result.svg}</section>`;
|
|
@@ -210,7 +214,7 @@ export function inspectArchLabels() {
|
|
|
210
214
|
const matrix=shape.getScreenCTM()?.inverse();
|
|
211
215
|
const inside=matrix && [[r.left+1,r.top+1],[r.right-1,r.top+1],[r.left+1,r.bottom-1],[r.right-1,r.bottom-1]].every(([x,y])=>shape.isPointInFill(new DOMPoint(x,y).matrixTransform(matrix)));
|
|
212
216
|
if(!inside || r.left<box.left-1||r.right>box.right+1||r.top<box.top-1||r.bottom>box.bottom+1)
|
|
213
|
-
problems.push(
|
|
217
|
+
problems.push({code:'ARCH_LABEL_OVERFLOW',message:`Label overflows node ${node.dataset.id}: ${text.textContent.trim()}`,line:null,column:null});
|
|
214
218
|
}
|
|
215
219
|
}
|
|
216
220
|
return problems;
|
package/src/toolkit/browser.mjs
CHANGED
|
@@ -1,21 +1,47 @@
|
|
|
1
1
|
import { UPDATE } from './config.mjs';
|
|
2
|
+
import { CliError } from '../cli-output.mjs';
|
|
2
3
|
|
|
3
|
-
export async function launch() {
|
|
4
|
+
export async function launch({ importPlaywright = () => import('playwright') } = {}) {
|
|
4
5
|
let chromium;
|
|
5
|
-
try { ({ chromium } = await
|
|
6
|
-
catch { throw new
|
|
6
|
+
try { ({ chromium } = await importPlaywright()); }
|
|
7
|
+
catch (error) { throw new CliError('PLAYWRIGHT_UNAVAILABLE', `Playwright is missing; run ${UPDATE}`, { cause: error }); }
|
|
7
8
|
try { return await chromium.launch(); }
|
|
8
9
|
catch (error) {
|
|
9
|
-
if (/Executable doesn't exist|playwright install/i.test(error.message)) throw new
|
|
10
|
-
throw new
|
|
10
|
+
if (/Executable doesn't exist|playwright install/i.test(error.message)) throw new CliError('CHROMIUM_UNAVAILABLE', 'Chromium is missing; run npx playwright@1.64.1 install chromium', { cause: error });
|
|
11
|
+
throw new CliError('BROWSER_FAILED', `Cannot launch Chromium: ${error.message.split('\n')[0]}; check your Playwright installation (npx playwright@1.64.1 install chromium)`, { cause: error });
|
|
11
12
|
}
|
|
12
13
|
}
|
|
13
14
|
export async function loadFrame(page, frame, theme = 'light') {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
15
|
+
return browserTask(page.context().browser(), async () => {
|
|
16
|
+
await page.emulateMedia({ colorScheme: theme, reducedMotion: 'reduce' });
|
|
17
|
+
await page.setViewportSize({ width: Math.ceil(frame.width ?? 1600), height: Math.ceil(frame.height ?? 1200) });
|
|
18
|
+
await page.setContent(frame.document(theme));
|
|
19
|
+
await page.evaluate(() => document.fonts.ready);
|
|
20
|
+
const box = await page.locator('[data-adg-frame]').boundingBox();
|
|
21
|
+
await page.setViewportSize({ width: Math.max(1, Math.ceil(box.width)), height: Math.max(1, Math.ceil(box.height)) });
|
|
22
|
+
return box;
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export async function readyResources() {
|
|
27
|
+
await document.fonts.ready;
|
|
28
|
+
await Promise.all([...document.images].map(image => image.decode()));
|
|
29
|
+
const urls = new Set();
|
|
30
|
+
for (const element of document.querySelectorAll('*')) {
|
|
31
|
+
for (const match of getComputedStyle(element).backgroundImage.matchAll(/url\(["']?(.+?)["']?\)/g)) urls.add(match[1]);
|
|
32
|
+
}
|
|
33
|
+
for (const element of document.querySelectorAll('svg image')) {
|
|
34
|
+
const href = element.getAttribute('href') ?? element.getAttribute('xlink:href');
|
|
35
|
+
if (href) urls.add(href);
|
|
36
|
+
}
|
|
37
|
+
await Promise.all([...urls].map(async url => { const image = new Image(); image.src = url; await image.decode(); }));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Classify Playwright execution failures where the browser's connection is observable. */
|
|
41
|
+
export async function browserTask(browser, work) {
|
|
42
|
+
try { return await work(); }
|
|
43
|
+
catch (error) {
|
|
44
|
+
if (error instanceof CliError) throw error;
|
|
45
|
+
throw new CliError(browser?.isConnected() === false ? 'BROWSER_FAILED' : 'RENDER_FAILED', error.message, { cause: error });
|
|
46
|
+
}
|
|
21
47
|
}
|
|
@@ -4,6 +4,8 @@ import { createHash, randomUUID } from 'node:crypto';
|
|
|
4
4
|
import { createRequire } from 'node:module';
|
|
5
5
|
import { mkdir, readFile, writeFile, rename, readdir, stat, unlink, realpath } from 'node:fs/promises';
|
|
6
6
|
import path from 'node:path';
|
|
7
|
+
import { perfSpan } from '../perf.mjs';
|
|
8
|
+
import { CliError, errorCatalog } from '../cli-output.mjs';
|
|
7
9
|
|
|
8
10
|
const digest = value => createHash('sha256').update(value).digest('hex');
|
|
9
11
|
const aborted = () => Object.assign(new Error('Build superseded'), { name: 'AbortError' });
|
|
@@ -33,6 +35,7 @@ class BuildPool {
|
|
|
33
35
|
finish(job, error, result) {
|
|
34
36
|
if (job.done) return;
|
|
35
37
|
job.done = true; job.signal.removeEventListener('abort', job.abort);
|
|
38
|
+
job.perfEnd?.({ error: error?.message, frames: result?.frames?.length });
|
|
36
39
|
error ? job.reject(error) : job.resolve(result);
|
|
37
40
|
}
|
|
38
41
|
retire(slot) {
|
|
@@ -58,20 +61,22 @@ class BuildPool {
|
|
|
58
61
|
this.retiring.add(done);
|
|
59
62
|
}
|
|
60
63
|
create() {
|
|
61
|
-
const slot = { worker: new Worker(new URL('./build-worker.mjs', import.meta.url), { resourceLimits: { maxOldGenerationSizeMb: 256 } }), attempts: 0, job: null };
|
|
64
|
+
const slot = { worker: new Worker(new URL('./build-worker.mjs', import.meta.url), { resourceLimits: { maxOldGenerationSizeMb: 256 },stdout:true,stderr:true }), attempts: 0, job: null };
|
|
65
|
+
slot.worker.stdout.pipe(process.stderr);slot.worker.stderr.pipe(process.stderr);
|
|
62
66
|
this.slots.add(slot); this.counters.spawned++;
|
|
63
67
|
slot.worker.on('message', message => {
|
|
64
68
|
if (slot.retired || message.id !== slot.job?.id) return;
|
|
65
69
|
const job = slot.job; slot.job = null;
|
|
66
70
|
slot.heapBytes = message.heapBytes;
|
|
67
|
-
|
|
71
|
+
const failure=message.error && Object.assign(Object.hasOwn(errorCatalog,message.error.code) ? new CliError(message.error.code,message.error.message,{context:message.error.context}) : new Error(message.error.message),message.error);
|
|
72
|
+
this.finish(job, failure || null, message.result);
|
|
68
73
|
if (slot.attempts >= recycleAfter) { this.counters.recycled++; this.retire(slot); }
|
|
69
74
|
else slot.worker.unref();
|
|
70
75
|
this.drain();
|
|
71
76
|
});
|
|
72
77
|
const failed = error => {
|
|
73
78
|
if (slot.retired) return;
|
|
74
|
-
if (slot.job) this.finish(slot.job, error);
|
|
79
|
+
if (slot.job) this.finish(slot.job, new CliError('INTERNAL_ERROR',error.message,{cause:error}));
|
|
75
80
|
this.retire(slot); this.drain();
|
|
76
81
|
};
|
|
77
82
|
slot.worker.on('error', failed);
|
|
@@ -86,6 +91,7 @@ class BuildPool {
|
|
|
86
91
|
if (!slot && this.slots.size < workerLimit) slot = this.create();
|
|
87
92
|
if (!slot) return;
|
|
88
93
|
const job = this.queue.shift(); if (job.done) continue;
|
|
94
|
+
job.perfEnd = perfSpan('build-worker', job.payload.name);
|
|
89
95
|
slot.job = job; slot.attempts++; this.counters.attempts++; slot.worker.ref(); slot.worker.postMessage({ id: job.id, ...job.payload });
|
|
90
96
|
}
|
|
91
97
|
}
|
|
@@ -228,7 +234,9 @@ export async function createBuildStore({ config, cacheDirectory }) {
|
|
|
228
234
|
if (controller.signal.aborted || generation !== (generations.get(name) ?? 0)) throw aborted();
|
|
229
235
|
if (payload) return { ...old, ...payload };
|
|
230
236
|
}
|
|
237
|
+
const endQueue = perfSpan('build-request', name);
|
|
231
238
|
const built = await pool.run({ config: workerConfig, name }, controller.signal); counters.builds++;
|
|
239
|
+
endQueue?.({frames: built.frames.length});
|
|
232
240
|
if (controller.signal.aborted || generation !== (generations.get(name) ?? 0)) throw aborted();
|
|
233
241
|
const payload = { frames: built.frames, css: built.css };
|
|
234
242
|
const hash = digest(JSON.stringify({ path: name, component: !name.startsWith('surfaces/'), ...payload, ...(config.overlay?{base:config.overlay.sha,baseBlob:built.baseBlob}:{}), imports: built.imports }));
|
|
@@ -27,6 +27,9 @@ parentPort.on('message', async ({ id, config, name, type }) => {
|
|
|
27
27
|
}));
|
|
28
28
|
if (!shuttingDown) parentPort.postMessage({ id, result: { frames, css: built.css, ...(config.overlay?{baseBlob:built.baseBlob}:{}), imports: built.imports, dependencies, dependencyHashes }, heapBytes: process.memoryUsage().heapUsed });
|
|
29
29
|
} catch (error) {
|
|
30
|
-
|
|
30
|
+
const diagnostics=error.errors ?? error.cause?.errors ?? [];
|
|
31
|
+
// esbuild's onLoad error keeps transform diagnostics under detail.errors.
|
|
32
|
+
const location=diagnostics.find(item=>item.location)?.location ?? diagnostics.find(item=>item.detail?.errors?.[0]?.location)?.detail.errors[0].location;
|
|
33
|
+
if (!shuttingDown) parentPort.postMessage({ id, error: { message: error.message, stack: error.stack, code: error.code, context:error.context, location }, heapBytes: process.memoryUsage().heapUsed });
|
|
31
34
|
}
|
|
32
35
|
});
|
package/src/toolkit/build.mjs
CHANGED
|
@@ -7,6 +7,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
|
7
7
|
import { loadTokens, refreshTypes, rejectLegacy, relative, isSourcePath, sourceDirectories } from './project.mjs';
|
|
8
8
|
import { themeCss, parseTokens } from './tokens.mjs';
|
|
9
9
|
import { escape } from './runtime.mjs';
|
|
10
|
+
import { CliError, classifyError } from '../cli-output.mjs';
|
|
10
11
|
const require = createRequire(import.meta.url);
|
|
11
12
|
const runtime = fileURLToPath(new URL('./runtime.mjs', import.meta.url));
|
|
12
13
|
const tailwind = path.dirname(require.resolve('tailwindcss/package.json'));
|
|
@@ -60,12 +61,30 @@ function trimTransforms() {
|
|
|
60
61
|
export function validateFrame(frame) {
|
|
61
62
|
if (!frame?.frame || typeof frame.name !== 'string' || !frame.name.trim()) throw Error('Default export must return named Frames');
|
|
62
63
|
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`);
|
|
64
|
+
const parent = frame.parent;
|
|
65
|
+
if (parent !== undefined) {
|
|
66
|
+
if (!parent || typeof parent !== 'object' || Array.isArray(parent) ||
|
|
67
|
+
Object.keys(parent).some(key => !['source', 'frame', 'selector'].includes(key)) ||
|
|
68
|
+
['source', 'frame', 'selector'].some(key => typeof parent[key] !== 'string' || !parent[key].trim()) ||
|
|
69
|
+
!/\.(tsx|mmd)$/.test(parent.source) || /[\\:]|^\//.test(parent.source) ||
|
|
70
|
+
parent.source.split('/').some(part => ['', '.', '..'].includes(part))) {
|
|
71
|
+
throw Error('Invalid Frame parent; use project-relative source, frame and selector strings');
|
|
72
|
+
}
|
|
73
|
+
}
|
|
63
74
|
const c = frame.capture;
|
|
64
75
|
if (c !== undefined) {
|
|
65
76
|
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
77
|
}
|
|
67
78
|
}
|
|
68
|
-
export async function buildSource(config, file,
|
|
79
|
+
export async function buildSource(config, file, options = {}) {
|
|
80
|
+
try { return await buildDesignSource(config, file, options); }
|
|
81
|
+
catch (error) {
|
|
82
|
+
if (error instanceof CliError) throw error;
|
|
83
|
+
const code = classifyError(error).error.code;
|
|
84
|
+
throw new CliError(code === 'INTERNAL_ERROR' ? 'SOURCE_BUILD_FAILED' : code, error.message, { cause: error });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
async function buildDesignSource(config, file, { write = true, allowLegacy = true, snapshot, browser } = {}) {
|
|
69
88
|
if (file.endsWith('.mmd')) return (await import('./arch.mjs')).buildArch(config,file,{snapshot,browser});
|
|
70
89
|
if (write) refreshTypes(config);
|
|
71
90
|
const read = (name, encoding) => {
|
|
@@ -111,7 +130,12 @@ export async function buildSource(config, file, { write = true, allowLegacy = tr
|
|
|
111
130
|
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
131
|
return { contents: `import { artwork } from 'adg'; export default props => artwork(${JSON.stringify(source)}, props);`, loader:'js' };
|
|
113
132
|
});
|
|
114
|
-
} }] })
|
|
133
|
+
} }] }).catch(error => {
|
|
134
|
+
const typed = error.errors?.find(item => item.detail instanceof CliError)?.detail;
|
|
135
|
+
if (!typed) throw error;
|
|
136
|
+
// Retain esbuild's human diagnostics and details while carrying the owning boundary's code.
|
|
137
|
+
throw Object.assign(new CliError(typed.code, error.message, { cause: error, context: typed.context }), { errors: error.errors });
|
|
138
|
+
});
|
|
115
139
|
const mod = await import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}#${Date.now()}`);
|
|
116
140
|
if (typeof mod.default !== 'function') throw Error(`${relative(config,file)}: export a default function returning Frames`);
|
|
117
141
|
const value = mod.default(), frames = (Array.isArray(value) ? value.flat(Infinity) : [value]).filter(v => v != null && v !== false);
|