@whzxc/agent-design-gallery 0.6.0 → 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.
- package/README.md +2 -0
- 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 +236 -0
- package/src/cli.mjs +113 -42
- 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 +8 -7
- package/src/toolkit/arch-overlay.mjs +1 -1
- package/src/toolkit/arch.mjs +62 -58
- package/src/toolkit/browser.mjs +24 -12
- package/src/toolkit/build-store.mjs +11 -3
- package/src/toolkit/build-worker.mjs +4 -1
- package/src/toolkit/build.mjs +16 -2
- package/src/toolkit/commands.mjs +158 -86
- package/src/toolkit/compare.mjs +93 -46
- package/src/toolkit/config.mjs +18 -17
- package/src/toolkit/migrate.mjs +42 -30
- package/src/toolkit/project.mjs +45 -33
- package/src/toolkit/results.mjs +44 -0
- package/src/toolkit/tokens.mjs +5 -4
|
@@ -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'));
|
|
@@ -65,7 +66,15 @@ export function validateFrame(frame) {
|
|
|
65
66
|
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
|
}
|
|
67
68
|
}
|
|
68
|
-
export async function buildSource(config, file,
|
|
69
|
+
export async function buildSource(config, file, options = {}) {
|
|
70
|
+
try { return await buildDesignSource(config, file, options); }
|
|
71
|
+
catch (error) {
|
|
72
|
+
if (error instanceof CliError) throw error;
|
|
73
|
+
const code = classifyError(error).error.code;
|
|
74
|
+
throw new CliError(code === 'INTERNAL_ERROR' ? 'SOURCE_BUILD_FAILED' : code, error.message, { cause: error });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
async function buildDesignSource(config, file, { write = true, allowLegacy = true, snapshot, browser } = {}) {
|
|
69
78
|
if (file.endsWith('.mmd')) return (await import('./arch.mjs')).buildArch(config,file,{snapshot,browser});
|
|
70
79
|
if (write) refreshTypes(config);
|
|
71
80
|
const read = (name, encoding) => {
|
|
@@ -111,7 +120,12 @@ export async function buildSource(config, file, { write = true, allowLegacy = tr
|
|
|
111
120
|
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
121
|
return { contents: `import { artwork } from 'adg'; export default props => artwork(${JSON.stringify(source)}, props);`, loader:'js' };
|
|
113
122
|
});
|
|
114
|
-
} }] })
|
|
123
|
+
} }] }).catch(error => {
|
|
124
|
+
const typed = error.errors?.find(item => item.detail instanceof CliError)?.detail;
|
|
125
|
+
if (!typed) throw error;
|
|
126
|
+
// Retain esbuild's human diagnostics and details while carrying the owning boundary's code.
|
|
127
|
+
throw Object.assign(new CliError(typed.code, error.message, { cause: error, context: typed.context }), { errors: error.errors });
|
|
128
|
+
});
|
|
115
129
|
const mod = await import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}#${Date.now()}`);
|
|
116
130
|
if (typeof mod.default !== 'function') throw Error(`${relative(config,file)}: export a default function returning Frames`);
|
|
117
131
|
const value = mod.default(), frames = (Array.isArray(value) ? value.flat(Infinity) : [value]).filter(v => v != null && v !== false);
|
package/src/toolkit/commands.mjs
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
|
-
import { mkdirSync } from 'node:fs';
|
|
1
|
+
import { mkdirSync, readFileSync, existsSync } from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { availableParallelism } from 'node:os';
|
|
4
4
|
import { buildSource } from './build.mjs';
|
|
5
5
|
import { selectSources, relative, loadTokens, sourceDirectories, archFiles } from './project.mjs';
|
|
6
6
|
import { importDirectionViolations } from './asset-rules.mjs';
|
|
7
|
-
import { launch, loadFrame } from './browser.mjs';
|
|
7
|
+
import { launch, loadFrame, browserTask } from './browser.mjs';
|
|
8
|
+
import { CliError, classifyError } from '../cli-output.mjs';
|
|
9
|
+
import { commandFailure, cleanup, emptySelection } from './results.mjs';
|
|
8
10
|
export function inspectFrame(tokenNames) {
|
|
9
|
-
const frame = document.querySelector('[data-adg-frame]'), box = frame.getBoundingClientRect(), problems = new
|
|
10
|
-
|
|
11
|
+
const frame = document.querySelector('[data-adg-frame]'), box = frame.getBoundingClientRect(), problems = new Map();
|
|
12
|
+
const add = (code, message) => problems.set(message, {code, message, line:null, column:null});
|
|
13
|
+
if (frame.children.length !== 1 || [...frame.childNodes].some(n => n.nodeType === 3 && n.textContent.trim())) add('FRAME_ROOT_INVALID', 'Frame needs exactly one root element');
|
|
11
14
|
const sample = document.createElement('i'); document.body.append(sample);
|
|
12
15
|
const canvas = document.createElement('canvas'); canvas.width = canvas.height = 1;
|
|
13
16
|
const context = canvas.getContext('2d', { colorSpace: 'srgb', colorType: 'float16', willReadFrequently: true });
|
|
@@ -73,16 +76,16 @@ export function inspectFrame(tokenNames) {
|
|
|
73
76
|
const lines = [], covers = [];
|
|
74
77
|
for (const el of [frame, ...frame.querySelectorAll('*')]) {
|
|
75
78
|
const s = style(el), r = rectFor(el);
|
|
76
|
-
if (['STYLE','SCRIPT'].includes(el.tagName.toUpperCase()))
|
|
77
|
-
for (const attr of el.attributes) if (/^on/i.test(attr.name) || attr.name === 'classname')
|
|
79
|
+
if (['STYLE','SCRIPT'].includes(el.tagName.toUpperCase())) add('MARKUP_FORBIDDEN', `Forbidden <${el.tagName.toLowerCase()}> in output`);
|
|
80
|
+
for (const attr of el.attributes) if (/^on/i.test(attr.name) || attr.name === 'classname') add('MARKUP_FORBIDDEN', `Forbidden attribute ${attr.name} in output`);
|
|
78
81
|
if (!el.closest('[data-free]')) {
|
|
79
82
|
const authored = (el.getAttribute('class') ?? '') + ' ' + (el.getAttribute('style') ?? '');
|
|
80
|
-
if ([...authored.matchAll(/(-?(?:\d*\.)?\d+)px\b/g)].some(m => !Number.isInteger(Number(m[1]))))
|
|
81
|
-
for (const [,property] of (el.getAttribute('style') ?? '').matchAll(/(?:^|;)\s*([-\w]+)\s*:/g)) if (!['width','height'].includes(property) && !property.startsWith('--'))
|
|
83
|
+
if ([...authored.matchAll(/(-?(?:\d*\.)?\d+)px\b/g)].some(m => !Number.isInteger(Number(m[1])))) add('FRACTIONAL_LENGTH', 'Fractional pixel length outside data-free');
|
|
84
|
+
for (const [,property] of (el.getAttribute('style') ?? '').matchAll(/(?:^|;)\s*([-\w]+)\s*:/g)) if (!['width','height'].includes(property) && !property.startsWith('--')) add('STYLE_FORBIDDEN', `Style ${property} outside data-free; use layout classes`);
|
|
82
85
|
}
|
|
83
86
|
if (s.display === 'none' || s.visibility === 'hidden' || r.width === 0 || r.height === 0) continue;
|
|
84
87
|
const visibleBox=clipped(r,el.parentElement);
|
|
85
|
-
if (nonempty(visibleBox) && outside(visibleBox))
|
|
88
|
+
if (nonempty(visibleBox) && outside(visibleBox)) add('FRAME_OVERFLOW', 'Content overflows the frame');
|
|
86
89
|
// A border-box background has the same rounded hit shape as its element.
|
|
87
90
|
// Other background clips/masks cannot establish rectangular opaque coverage.
|
|
88
91
|
if (el instanceof HTMLElement && s.backgroundClip==='border-box' && opaqueColor(s.backgroundColor) && opaqueEffects(el)) {
|
|
@@ -101,7 +104,7 @@ export function inspectFrame(tokenNames) {
|
|
|
101
104
|
const matches = colors.some(color => alpha < 1
|
|
102
105
|
? paint.slice(0, 3).every((channel, i) => Math.abs(channel - color[i]) <= 2)
|
|
103
106
|
: paint.every((channel, i) => channel === color[i]));
|
|
104
|
-
if (!matches)
|
|
107
|
+
if (!matches) add('TOKEN_COLOR_MISMATCH', `Color ${value} matches no token`);
|
|
105
108
|
}
|
|
106
109
|
}
|
|
107
110
|
for (const node of el.childNodes) {
|
|
@@ -112,9 +115,9 @@ export function inspectFrame(tokenNames) {
|
|
|
112
115
|
const label = node.textContent.trim().replace(/\s+/g, ' ');
|
|
113
116
|
const visible=clipped(rect,el);
|
|
114
117
|
if (!nonempty(visible)) continue;
|
|
115
|
-
if (outside(visible))
|
|
118
|
+
if (outside(visible)) add('TEXT_OUTSIDE_FRAME', `Text leaves frame: ${label}`);
|
|
116
119
|
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)
|
|
120
|
+
(visible.top+visible.bottom)/2 < r.top - 1 || (visible.top+visible.bottom)/2 > r.bottom + 1) add('TEXT_OVERFLOW', `Text overflows its box: ${label}`);
|
|
118
121
|
const inFrame=intersect(visible,box);
|
|
119
122
|
if (nonempty(inFrame)) lines.push({rect:inFrame,label,el});
|
|
120
123
|
}
|
|
@@ -163,7 +166,7 @@ export function inspectFrame(tokenNames) {
|
|
|
163
166
|
if (a.el===b.el) continue;
|
|
164
167
|
const overlap=intersect(a.rect,b.rect);
|
|
165
168
|
if (overlap.right-overlap.left>1 && overlap.bottom-overlap.top>2 &&
|
|
166
|
-
!occluded(a.el,overlap) && !occluded(b.el,overlap))
|
|
169
|
+
!occluded(a.el,overlap) && !occluded(b.el,overlap)) add('TEXT_OVERLAP', `Text overlaps: ${a.label} / ${b.label}`);
|
|
167
170
|
}
|
|
168
171
|
} finally {
|
|
169
172
|
for (const [el,authored] of restored) {
|
|
@@ -174,100 +177,169 @@ export function inspectFrame(tokenNames) {
|
|
|
174
177
|
}
|
|
175
178
|
for (const [el,authored] of inert) el.setAttribute('inert',authored);
|
|
176
179
|
}
|
|
177
|
-
return [...problems];
|
|
180
|
+
return [...problems.values()];
|
|
178
181
|
}
|
|
179
|
-
export async function check(config, args = [], options = {}, log = console.log, error = console.error) {
|
|
180
|
-
const write
|
|
181
|
-
|
|
182
|
-
const
|
|
183
|
-
const
|
|
182
|
+
export async function check(config, args = [], options = {}, log = console.log, error = console.error, { launchBrowser = launch } = {}) {
|
|
183
|
+
const write = !options['read-only'];
|
|
184
|
+
/** @type {import('./results.mjs').CheckData} */
|
|
185
|
+
const data = { project: config.root, readOnly: !write, complete: false, sources: [], summary: { sources: 0, frames: 0, evaluations: 0, problems: 0 }, findings: [] };
|
|
186
|
+
const warnings = [], humanProblems = new Set(), findingKeys = new Set(), graph = {};
|
|
187
|
+
let browser, primary;
|
|
188
|
+
const add = (problem, file, frame = null, theme = null, source = relative(config, file)) => {
|
|
189
|
+
const finding = { ...problem, source, frame, theme };
|
|
190
|
+
const key = JSON.stringify(finding);
|
|
191
|
+
if (!findingKeys.has(key)) { findingKeys.add(key); data.findings.push(finding); }
|
|
192
|
+
humanProblems.add(`${relative(config, file)}: ${frame === null ? '' : `${frame}: ${theme}: `}${problem.message}`);
|
|
193
|
+
data.summary.problems = data.findings.length;
|
|
194
|
+
};
|
|
195
|
+
const failed = cause => {
|
|
196
|
+
const failure = cause instanceof CliError ? cause : new CliError('SOURCE_BUILD_FAILED', cause.message, { cause });
|
|
197
|
+
if (!primary) primary = failure;
|
|
198
|
+
else warnings.push(classifyError(failure).error);
|
|
199
|
+
};
|
|
184
200
|
try {
|
|
185
|
-
const
|
|
201
|
+
const files = selectSources(config, args, { write });
|
|
202
|
+
data.sources = files.map(file => relative(config, file));
|
|
203
|
+
data.summary.sources = files.length;
|
|
204
|
+
const tokens = files.length ? loadTokens(config) : null;
|
|
205
|
+
const arch = files.some(file => file.endsWith('.mmd')) ? await import('./arch.mjs') : null;
|
|
206
|
+
let page;
|
|
186
207
|
for (const file of files) {
|
|
187
|
-
const architecture=file.endsWith('.mmd');
|
|
188
|
-
if(architecture) {
|
|
189
|
-
const
|
|
190
|
-
const
|
|
191
|
-
const
|
|
192
|
-
|
|
193
|
-
|
|
208
|
+
const architecture = file.endsWith('.mmd');
|
|
209
|
+
if (architecture) {
|
|
210
|
+
const side = file.replace(/\.mmd$/, '.md');
|
|
211
|
+
const metadata = arch.sidecar(existsSync(side) ? readFileSync(side, 'utf8') : '');
|
|
212
|
+
const validation = arch.inspectArch(readFileSync(file, 'utf8'), config.check?.archMaxEdges ?? 30).problems;
|
|
213
|
+
const sidecarProblems = [...metadata.problems, ...arch.ownerProblems(config, metadata)];
|
|
214
|
+
for (const problem of validation) add(problem, file);
|
|
215
|
+
for (const problem of sidecarProblems) add(problem, file, null, null, relative(config, side));
|
|
216
|
+
if (validation.length || sidecarProblems.length) continue;
|
|
194
217
|
}
|
|
195
218
|
let built;
|
|
196
|
-
try {
|
|
197
|
-
|
|
198
|
-
|
|
219
|
+
try {
|
|
220
|
+
// Static architecture rejection is a completed rule evaluation and needs no browser.
|
|
221
|
+
browser ??= await launchBrowser();
|
|
222
|
+
built = await buildSource(config, file, { allowLegacy: false, write, browser });
|
|
223
|
+
} catch (cause) {
|
|
224
|
+
const legacy = cause.errors?.find(item => item.detail?.code === 'LEGACY_SOURCE');
|
|
199
225
|
if (legacy) throw legacy.detail;
|
|
200
|
-
|
|
226
|
+
if (['PLAYWRIGHT_UNAVAILABLE', 'CHROMIUM_UNAVAILABLE', 'BROWSER_FAILED', 'LEGACY_SOURCE'].includes(cause.code)) throw cause;
|
|
227
|
+
failed(cause);
|
|
228
|
+
for (const message of cause.message.split('\n')) humanProblems.add(`${relative(config, file)}: ${architecture ? '' : '-: '}${message.replace(/\s+/g, ' ')}`);
|
|
229
|
+
continue;
|
|
201
230
|
}
|
|
202
|
-
|
|
203
|
-
|
|
231
|
+
data.summary.frames += built.frames.length;
|
|
232
|
+
graph[path.relative(config.design, file).split(path.sep).join('/')] = { uses: built.imports };
|
|
233
|
+
for (const frame of built.frames) for (const theme of ['light', 'dark']) {
|
|
204
234
|
try {
|
|
205
|
-
await
|
|
206
|
-
|
|
207
|
-
|
|
235
|
+
page ??= await browserTask(browser, () => browser.newPage());
|
|
236
|
+
await loadFrame(page, frame, theme);
|
|
237
|
+
const findings = await browserTask(browser, () => page.evaluate(architecture ? arch.inspectArchLabels : inspectFrame, architecture ? undefined : [...tokens.light.keys()]));
|
|
238
|
+
for (const finding of findings) add(finding, file, frame.name, theme);
|
|
239
|
+
data.summary.evaluations++;
|
|
240
|
+
} catch (cause) {
|
|
241
|
+
failed(cause);
|
|
242
|
+
humanProblems.add(`${relative(config, file)}: ${frame.name}: ${theme}: ${cause.message.replace(/\s+/g, ' ')}`);
|
|
243
|
+
}
|
|
208
244
|
}
|
|
209
245
|
}
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
246
|
+
await cleanup(() => browser?.close(), primary);
|
|
247
|
+
browser = null;
|
|
248
|
+
if (config.check?.importDirection !== false) for (const { source, target, from, to } of importDirectionViolations(graph, sourceDirectories(config))) {
|
|
249
|
+
add({ code: 'IMPORT_DIRECTION', message: `import ${target} violates import direction (${from} -> ${to}); import from the same or a lower layer in sources`, line: null, column: null }, path.join(config.design, source));
|
|
250
|
+
}
|
|
251
|
+
for (const problem of humanProblems) error(problem);
|
|
252
|
+
const message = `Design check ${humanProblems.size ? 'failed' : 'passed'} for ${files.length} sources${humanProblems.size ? `: ${humanProblems.size} problems` : ''}.`;
|
|
253
|
+
log(message);
|
|
254
|
+
if (!files.length) emptySelection(warnings);
|
|
255
|
+
if (primary) { primary.humanReported = true; throw primary; }
|
|
256
|
+
data.complete = true;
|
|
257
|
+
if (data.findings.length) throw new CliError('CHECK_FAILED', message, { data, warnings, humanReported: true });
|
|
258
|
+
return { data, warnings };
|
|
259
|
+
} catch (cause) {
|
|
260
|
+
primary = commandFailure(cause, data, warnings);
|
|
261
|
+
throw primary;
|
|
262
|
+
} finally { if (browser) await cleanup(() => browser.close(), primary); }
|
|
217
263
|
}
|
|
218
|
-
|
|
219
|
-
|
|
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.');
|
|
264
|
+
|
|
265
|
+
export async function render(config, args = [], options = {}, log = console.log, { launchBrowser = launch } = {}) {
|
|
224
266
|
const output = options['out-dir'] ? path.resolve(config.root, options['out-dir']) : config.output;
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
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();
|
|
267
|
+
/** @type {import('./results.mjs').RenderData} */
|
|
268
|
+
const data = { project: config.root, outputDirectory: output, complete: false, base: null, captures: [], deleted: [] };
|
|
269
|
+
const warnings = [], completed = [], failures = [];
|
|
270
|
+
let browser, primary;
|
|
237
271
|
try {
|
|
272
|
+
const scale = Number(options.scale ?? 2);
|
|
273
|
+
if (!(Number.isFinite(scale) && scale > 0)) throw new CliError('USAGE_INVALID', 'Invalid --scale; use a positive number');
|
|
274
|
+
const themeOption = options.theme ?? 'both';
|
|
275
|
+
if (!['both', 'light', 'dark'].includes(themeOption)) throw new CliError('USAGE_INVALID', 'Choose --theme=both, light, or dark.');
|
|
276
|
+
if (options['out-dir'] === '') throw new CliError('USAGE_INVALID', 'Set --out-dir to a directory.');
|
|
277
|
+
const themes = themeOption === 'both' ? ['light', 'dark'] : [themeOption];
|
|
278
|
+
let base, additional = [];
|
|
279
|
+
if (options.base !== undefined && (!args.length || args.some(arg => arg.endsWith('.mmd')))) {
|
|
280
|
+
const git = await import('./arch-git.mjs');
|
|
281
|
+
base = await git.resolveBase(config, options.base);
|
|
282
|
+
additional = await git.baseArchFiles(config, base);
|
|
283
|
+
data.base = { rev: base.rev, sha: base.sha };
|
|
284
|
+
} else if (options.base !== undefined) warnings.push({ code: 'USAGE_INVALID', message: '--base applies only to architecture sources.', next: [] });
|
|
285
|
+
const selected = selectSources(config, args, { additional });
|
|
286
|
+
const currentArchitecture = base ? new Set(archFiles(config.arch)) : null;
|
|
287
|
+
const files = selected.filter(file => {
|
|
288
|
+
if (!existsSync(file) || (base && file.endsWith('.mmd') && !currentArchitecture.has(file))) { data.deleted.push(relative(config, file)); return false; }
|
|
289
|
+
return true;
|
|
290
|
+
});
|
|
291
|
+
if (!selected.length) emptySelection(warnings);
|
|
292
|
+
if (files.length) browser = await launchBrowser();
|
|
238
293
|
const captures = [];
|
|
239
294
|
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(
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
captures.push({source,frame,theme,target});
|
|
246
|
-
}
|
|
295
|
+
const built = base && file.endsWith('.mmd') ? await (await import('./arch-overlay.mjs')).buildOverlay(config, file, { base, browser }) : await buildSource(config, file, { allowLegacy: false, browser });
|
|
296
|
+
for (const frame of built.frames.filter(frame => !options.frame || frame.name === options.frame)) for (const theme of themes) {
|
|
297
|
+
const outputSource = file.endsWith('.mmd') ? relative(config, file) : path.relative(config.design, file);
|
|
298
|
+
const target = path.join(output, outputSource.replace(/\.(?:tsx|mmd)$/, ''), `${encodeURIComponent(frame.name)}-${theme}.png`);
|
|
299
|
+
captures.push({ source: relative(config, file), frame, theme, target });
|
|
247
300
|
}
|
|
248
301
|
}
|
|
249
|
-
if (options.frame && !captures.length && !deleted.length) throw
|
|
302
|
+
if (options.frame && !captures.length && !data.deleted.length) throw new CliError('FRAME_NOT_FOUND', `Unknown frame ${options.frame}; choose a declared frame`);
|
|
250
303
|
let next = 0;
|
|
251
|
-
|
|
304
|
+
await Promise.allSettled(Array.from({ length: Math.min(4, availableParallelism(), captures.length) }, async () => {
|
|
252
305
|
while (next < captures.length) {
|
|
253
|
-
const {frame,theme,target} = captures[
|
|
254
|
-
|
|
255
|
-
// A fresh page/context per capture keeps PNG bytes independent of history.
|
|
256
|
-
const page = await browser.newPage({deviceScaleFactor:scale});
|
|
306
|
+
const index = next++, { source, frame, theme, target } = captures[index];
|
|
307
|
+
let page, failure;
|
|
257
308
|
try {
|
|
258
|
-
await
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
309
|
+
page = await browserTask(browser, () => browser.newPage({ deviceScaleFactor: scale }));
|
|
310
|
+
await loadFrame(page, frame, theme);
|
|
311
|
+
mkdirSync(path.dirname(target), { recursive: true });
|
|
312
|
+
const { box, png } = await browserTask(browser, async () => {
|
|
313
|
+
const element = page.locator('[data-adg-frame]');
|
|
314
|
+
const box = await element.boundingBox();
|
|
315
|
+
if (!box) throw Error('Frame has no visible bounds.');
|
|
316
|
+
return { box, png: await element.screenshot({ path: target }) };
|
|
317
|
+
});
|
|
318
|
+
completed[index] = { source, frame: frame.name, theme, path: target, scale, width: box.width, height: box.height, pixelWidth: png.readUInt32BE(16), pixelHeight: png.readUInt32BE(20) };
|
|
319
|
+
} catch (cause) {
|
|
320
|
+
failure = commandFailure(cause, data, warnings);
|
|
321
|
+
failures.push({ index, failure });
|
|
322
|
+
throw failure;
|
|
323
|
+
} finally {
|
|
324
|
+
if (page) try { await cleanup(() => page.close(), failure); }
|
|
325
|
+
catch (cause) { failures.push({ index, failure: commandFailure(cause, data, warnings) }); throw cause; }
|
|
326
|
+
}
|
|
262
327
|
}
|
|
263
328
|
}));
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
if (
|
|
267
|
-
const
|
|
268
|
-
|
|
329
|
+
data.captures = completed.filter(Boolean);
|
|
330
|
+
failures.sort((a, b) => a.index - b.index);
|
|
331
|
+
if (failures.length) {
|
|
332
|
+
for (const { failure } of failures.slice(1)) warnings.push(classifyError(failure).error);
|
|
333
|
+
throw failures[0].failure;
|
|
269
334
|
}
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
335
|
+
if (!options.json) for (const capture of data.captures) log(relative(config, capture.path));
|
|
336
|
+
await cleanup(() => browser?.close(), null);
|
|
337
|
+
browser = null;
|
|
338
|
+
data.complete = true;
|
|
339
|
+
return { data, warnings };
|
|
340
|
+
} catch (cause) {
|
|
341
|
+
data.captures = completed.filter(Boolean);
|
|
342
|
+
primary = commandFailure(cause, data, warnings);
|
|
343
|
+
throw primary;
|
|
344
|
+
} finally { if (browser) await cleanup(() => browser.close(), primary); }
|
|
273
345
|
}
|