@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
package/src/toolkit/compare.mjs
CHANGED
|
@@ -7,6 +7,8 @@ import { matchTexts, textDelta } from './text.mjs';
|
|
|
7
7
|
import { selectSources, relative } from './project.mjs';
|
|
8
8
|
import { buildSource } from './build.mjs';
|
|
9
9
|
import { viewport } from './config.mjs';
|
|
10
|
+
import { CliError, classifyError } from '../cli-output.mjs';
|
|
11
|
+
import { commandFailure, cleanup, emptySelection } from './results.mjs';
|
|
10
12
|
|
|
11
13
|
export function compareReport(asset, frame, fixture, design, implementation) {
|
|
12
14
|
const { pairs, missing, extra } = matchTexts(design.texts, implementation.texts);
|
|
@@ -45,58 +47,63 @@ async function overlay(page, target) {
|
|
|
45
47
|
writeFileSync(path.join(target, 'overlay.png'), Buffer.from(data, 'base64'));
|
|
46
48
|
}
|
|
47
49
|
const safeName = value => encodeURIComponent(value).replace(/\./g, '%2E');
|
|
48
|
-
async function settle(read) {
|
|
49
|
-
const started =
|
|
50
|
+
export async function settle(read, { now: monotonicNow = () => performance.now(), sleep = delay } = {}) {
|
|
51
|
+
const started = monotonicNow();
|
|
50
52
|
let previous, changed = started;
|
|
51
53
|
for (;;) {
|
|
52
54
|
const implementation = await read();
|
|
53
55
|
const state = JSON.stringify({ box: implementation.box, texts: implementation.texts.map(({ text, x, y, width, height }) => ({ text, x, y, width, height })) });
|
|
54
|
-
const now =
|
|
56
|
+
const now = monotonicNow();
|
|
55
57
|
if (state !== previous) { previous = state; changed = now; }
|
|
56
58
|
if (now - changed >= 300) return { implementation, settled: true };
|
|
57
59
|
if (now - started >= 5000) return { implementation, settled: false };
|
|
58
|
-
await
|
|
60
|
+
await sleep(Math.min(50, 5000 - (now - started)));
|
|
59
61
|
}
|
|
60
62
|
}
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
63
|
+
async function adapterCall(adapter, method, ...args) {
|
|
64
|
+
try { return await adapter[method](...args); }
|
|
65
|
+
catch (cause) {
|
|
66
|
+
if (cause instanceof CliError) throw cause;
|
|
67
|
+
const code = classifyError(cause).error.code;
|
|
68
|
+
throw new CliError(code === 'INTERNAL_ERROR' ? 'COMPARE_ADAPTER_FAILED' : code, cause.message, { cause });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function compareFrame(config, file, definition, options, data, { launchBrowser, clock, log }) {
|
|
73
|
+
const adapter = config.compare, frame = definition.name;
|
|
74
|
+
if (!adapter.fixture) throw new CliError('CONFIG_INVALID', 'Compare needs compare.fixture(name); add it to adg.config.mjs');
|
|
75
|
+
if ([options.region,options.selector,options.page].filter(Boolean).length > 1) throw new CliError('USAGE_INVALID', 'Choose --region, --selector or --page');
|
|
69
76
|
const settings = {...definition.capture};
|
|
70
77
|
if (options.region || options.selector || options.page) { delete settings.region; delete settings.selector; delete settings.page; }
|
|
71
78
|
for (const key of ['region','selector','page','origin','viewport']) if (options[key] !== undefined) settings[key] = options[key];
|
|
72
79
|
settings.clicks = options.click ?? settings.clicks ?? [];
|
|
73
|
-
const browser = await
|
|
74
|
-
let stop;
|
|
80
|
+
const browser = await launchBrowser();
|
|
81
|
+
let stop, primary;
|
|
75
82
|
try {
|
|
76
83
|
const fixtureName = options.fixture ?? definition.fixture;
|
|
77
|
-
if (!fixtureName) throw
|
|
78
|
-
const fixture = await adapter
|
|
79
|
-
if (!fixture || typeof fixture.url !== 'string' || !['light', 'dark'].includes(fixture.theme) || typeof fixture.locale !== 'string' || !fixture.locale || !Number.isFinite(Date.parse(fixture.clock))) throw new
|
|
84
|
+
if (!fixtureName) throw new CliError('CONFIG_INVALID', 'Frame needs a fixture; supply --fixture or Frame fixture');
|
|
85
|
+
const fixture = await adapterCall(adapter, 'fixture', fixtureName);
|
|
86
|
+
if (!fixture || typeof fixture.url !== 'string' || !['light', 'dark'].includes(fixture.theme) || typeof fixture.locale !== 'string' || !fixture.locale || !Number.isFinite(Date.parse(fixture.clock))) throw new CliError('CONFIG_INVALID', 'compare.fixture must return url, theme (light/dark), locale and a valid clock; fix adg.config.mjs');
|
|
80
87
|
if (fixture.timezone !== undefined) {
|
|
81
88
|
try {
|
|
82
89
|
if (typeof fixture.timezone !== 'string' || !fixture.timezone || /^[+-]/.test(fixture.timezone)) throw new Error();
|
|
83
90
|
new Intl.DateTimeFormat('en-US', { timeZone: fixture.timezone });
|
|
84
|
-
} catch { throw new
|
|
91
|
+
} catch { throw new CliError('CONFIG_INVALID', 'compare.fixture timezone must be a valid IANA time zone such as Asia/Shanghai; fix adg.config.mjs'); }
|
|
85
92
|
}
|
|
86
93
|
const sheet = await browser.newPage({colorScheme:fixture.theme,locale:fixture.locale,timezoneId:fixture.timezone,reducedMotion:'reduce'});
|
|
87
94
|
const frameBox = await loadFrame(sheet,definition,fixture.theme);
|
|
88
95
|
let design = await sheet.locator('[data-adg-frame] > :first-child').evaluate(implementationTexts);
|
|
89
96
|
const size = viewport(settings.viewport ?? adapter.viewport);
|
|
90
97
|
const origin = (settings.origin ?? '0 0').trim().split(/\s+/).map(Number);
|
|
91
|
-
if (settings.page && (origin.length !== 2 || !origin.every(Number.isFinite) || origin.some(n=>n<0) || origin[0]+frameBox.width>size.width || origin[1]+frameBox.height>size.height)) throw
|
|
92
|
-
if (!settings.page && !settings.region && !settings.selector) throw
|
|
98
|
+
if (settings.page && (origin.length !== 2 || !origin.every(Number.isFinite) || origin.some(n=>n<0) || origin[0]+frameBox.width>size.width || origin[1]+frameBox.height>size.height)) throw new CliError('CONFIG_INVALID', 'Frame does not fit capture viewport; fix origin or viewport');
|
|
99
|
+
if (!settings.page && !settings.region && !settings.selector) throw new CliError('CONFIG_INVALID', 'Frame needs capture; supply --page, --region or --selector');
|
|
93
100
|
const absolute = /^https?:\/\//.test(fixture.url);
|
|
94
|
-
if (!adapter.start && !absolute) throw new
|
|
101
|
+
if (!adapter.start && !absolute) throw new CliError('CONFIG_INVALID', 'Relative fixture URL needs compare.start; add it or return an absolute URL');
|
|
95
102
|
const url = new URL(fixture.url, `http://127.0.0.1:${adapter.port}`).href;
|
|
96
|
-
if (!/^https?:/.test(url)) throw new
|
|
103
|
+
if (!/^https?:/.test(url)) throw new CliError('CONFIG_INVALID', 'Fixture URL must use HTTP or HTTPS; fix compare.fixture');
|
|
97
104
|
if (adapter.start) {
|
|
98
|
-
stop = await adapter
|
|
99
|
-
if (typeof stop !== 'function') throw new
|
|
105
|
+
stop = await adapterCall(adapter, 'start', { port: adapter.port, root: config.root });
|
|
106
|
+
if (typeof stop !== 'function') throw new CliError('CONFIG_INVALID', 'compare.start must return a stop function; fix adg.config.mjs');
|
|
100
107
|
}
|
|
101
108
|
await sheet.emulateMedia({ colorScheme: fixture.theme, reducedMotion: 'reduce' });
|
|
102
109
|
await sheet.evaluate(theme => document.documentElement.setAttribute('data-theme', theme), fixture.theme);
|
|
@@ -119,8 +126,11 @@ export async function compare(config, args, options) {
|
|
|
119
126
|
else { const observer = new MutationObserver(() => { if (document.documentElement) { apply(); observer.disconnect(); } }); observer.observe(document, { childList: true }); }
|
|
120
127
|
document.addEventListener('DOMContentLoaded', apply, { once: true });
|
|
121
128
|
}, { clock: fixture.clock, theme: fixture.theme });
|
|
122
|
-
|
|
123
|
-
|
|
129
|
+
let response;
|
|
130
|
+
try { response = await app.goto(url, { waitUntil: 'load' }); }
|
|
131
|
+
catch (cause) { throw new CliError(browser.isConnected() ? 'NETWORK_FAILED' : 'BROWSER_FAILED', cause.message, { cause }); }
|
|
132
|
+
if ([401,403].includes(response?.status())) throw new CliError('AUTH_REQUIRED', `Fixture navigation was refused with HTTP ${response.status()}.`);
|
|
133
|
+
if (adapter.ready) await adapterCall(adapter, 'ready', app, fixtureName);
|
|
124
134
|
for (const name of settings.clicks) {
|
|
125
135
|
let control;
|
|
126
136
|
for (const role of ['button', 'radio', 'tab', 'checkbox', 'switch', 'menuitem', 'menuitemradio', 'option', 'link']) {
|
|
@@ -128,48 +138,85 @@ export async function compare(config, args, options) {
|
|
|
128
138
|
if (await candidate.count()) { control = candidate; break; }
|
|
129
139
|
}
|
|
130
140
|
if (!control) {
|
|
131
|
-
|
|
132
|
-
return 1;
|
|
141
|
+
throw new CliError('COMPARE_TARGET_NOT_FOUND', `No visible control matches --click=${JSON.stringify(name)}`);
|
|
133
142
|
}
|
|
134
143
|
await control.click();
|
|
135
144
|
}
|
|
136
145
|
await app.evaluate(() => document.fonts.ready);
|
|
137
146
|
const capture = settings.page ? { x: origin[0], y: origin[1], width: frameBox.width, height: frameBox.height } : undefined;
|
|
138
147
|
const panel = capture ? app.locator('html') : settings.selector ? app.locator(settings.selector).first() : app.getByRole('region', { name: settings.region, exact: true }).or(app.getByRole('dialog', { name: settings.region, exact: true })).first();
|
|
139
|
-
if (!capture)
|
|
148
|
+
if (!capture) {
|
|
149
|
+
if (!await panel.count()) throw new CliError('COMPARE_TARGET_NOT_FOUND', 'Frame capture target does not exist.');
|
|
150
|
+
await panel.scrollIntoViewIfNeeded();
|
|
151
|
+
}
|
|
140
152
|
const { implementation, settled } = await settle(async () => {
|
|
141
153
|
const result = await panel.evaluate(implementationTexts, capture);
|
|
142
154
|
if (adapter.texts) {
|
|
143
|
-
const additional = await adapter
|
|
144
|
-
if (!Array.isArray(additional) || additional.some(t => typeof t.text !== 'string' || !['x', 'y', 'width', 'height'].every(key => Number.isFinite(t[key])))) throw new
|
|
155
|
+
const additional = await adapterCall(adapter, 'texts', app), box = result.box;
|
|
156
|
+
if (!Array.isArray(additional) || additional.some(t => typeof t.text !== 'string' || !['x', 'y', 'width', 'height'].every(key => Number.isFinite(t[key])))) throw new CliError('CONFIG_INVALID', 'compare.texts must return text boxes in page coordinates; fix adg.config.mjs');
|
|
145
157
|
result.texts.push(...additional.filter(t => t.x >= box.x && t.y >= box.y && t.x + t.width <= box.x + box.width && t.y + t.height <= box.y + box.height).map(t => ({ ...t, x: t.x - box.x, y: t.y - box.y })));
|
|
146
158
|
}
|
|
147
159
|
return result;
|
|
148
|
-
});
|
|
160
|
+
}, clock);
|
|
149
161
|
const screenshot = { path: path.join(target, 'implementation.png') };
|
|
150
162
|
if (capture) await app.screenshot({ ...screenshot, clip: capture });
|
|
151
163
|
else await panel.screenshot(screenshot);
|
|
152
164
|
const canvasPage = await browser.newPage();
|
|
153
165
|
await overlay(canvasPage, target);
|
|
154
166
|
const report = { ...compareReport(relative(config, file), frame, fixtureName, {...design,box:frameBox}, implementation), settled };
|
|
155
|
-
if (options.collect) options.collect.push({...report, report: path.relative(path.join(config.output,'compare'),path.join(target,'index.html'))});
|
|
156
167
|
writeFileSync(path.join(target, 'report.json'), JSON.stringify(report, null, 2) + '\n');
|
|
157
168
|
writeFileSync(path.join(target, 'index.html'), reportHtml(report));
|
|
158
|
-
|
|
159
|
-
|
|
169
|
+
const paths = { design: path.join(target,'design.png'), implementation: path.join(target,'implementation.png'), overlay: path.join(target,'overlay.png'), report: path.join(target,'report.json'), html: path.join(target,'index.html') };
|
|
170
|
+
const {asset, ...measured} = report;
|
|
171
|
+
data.comparisons.push({source:asset, ...measured, theme:fixture.theme, paths});
|
|
172
|
+
data.summary.frames++;
|
|
173
|
+
data.summary.matched += report.matched;
|
|
174
|
+
data.summary.offsets += report.offBy2px.length;
|
|
175
|
+
data.summary.missing += report.missing.length;
|
|
176
|
+
data.summary.extra += report.extra.length;
|
|
177
|
+
if (!data.all) data.indexPath = paths.html;
|
|
178
|
+
log(`${relative(config, paths.html)}: matched ${report.matched}, ${report.offBy2px.length} off by >2px, ${report.missing.length} missing, ${report.extra.length} extra.`);
|
|
179
|
+
return {...report, report:path.relative(path.join(config.output,'compare'),paths.html)};
|
|
180
|
+
} catch (cause) {
|
|
181
|
+
primary = commandFailure(cause, data, [], browser.isConnected() ? 'RENDER_FAILED' : 'BROWSER_FAILED');
|
|
182
|
+
throw primary;
|
|
160
183
|
} finally {
|
|
161
|
-
try { await
|
|
184
|
+
try { await cleanup(() => browser.close(), primary); }
|
|
185
|
+
catch (cause) { primary = commandFailure(cause, data, []); throw primary; }
|
|
186
|
+
finally { if (typeof stop === 'function') await cleanup(stop, primary); }
|
|
162
187
|
}
|
|
163
188
|
}
|
|
164
189
|
|
|
165
|
-
async function
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
190
|
+
export async function compare(config, args = [], options = {}, { launchBrowser = launch, clock, log = console.log } = {}) {
|
|
191
|
+
/** @type {import('./results.mjs').CompareData} */
|
|
192
|
+
const data = {project:config.root, complete:false, all:!!options.all, comparisons:[], skipped:[], summary:{frames:0,matched:0,offsets:0,missing:0,extra:0}, indexPath:null, summaryPath:null};
|
|
193
|
+
const warnings = [], reports = [];
|
|
194
|
+
try {
|
|
195
|
+
const files = selectSources(config, args);
|
|
196
|
+
for (const file of files) {
|
|
197
|
+
const built = await buildSource(config,file,{allowLegacy:false});
|
|
198
|
+
const frames = options.all ? built.frames : built.frames.filter(frame => frame.name === options.frame);
|
|
199
|
+
if (!options.all && !frames.length) throw new CliError('FRAME_NOT_FOUND', `Unknown frame ${options.frame}; choose a declared frame`);
|
|
200
|
+
for (const frame of frames) {
|
|
201
|
+
if (options.all && !frame.fixture) {
|
|
202
|
+
data.skipped.push({source:relative(config,file),frame:frame.name,reason:'no_fixture'});
|
|
203
|
+
if (!warnings.length) warnings.push({code:'COMPARE_FRAMES_SKIPPED',message:'Frames without fixtures were skipped.',next:[]});
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
reports.push(await compareFrame(config,file,frame,options.all ? {frame:frame.name} : options,data,{launchBrowser,clock,log}));
|
|
207
|
+
if (!data.comparisons.at(-1).settled) throw new CliError('COMPARE_UNSETTLED', 'Comparison text boxes did not settle within 5 seconds.', {humanReported:true});
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
if (options.all) {
|
|
211
|
+
const target=path.join(config.output,'compare'); mkdirSync(target,{recursive:true});
|
|
212
|
+
writeFileSync(path.join(target,'summary.json'),JSON.stringify(reports,null,2)+'\n');
|
|
213
|
+
data.summaryPath = path.join(target,'summary.json');
|
|
214
|
+
writeFileSync(path.join(target,'index.html'),`<!doctype html><meta charset="utf-8"><title>Design comparisons</title><table><tr><th>Source</th><th>Frame</th><th>Matched</th><th>Offsets</th><th>Missing</th><th>Extra</th></tr>${reports.map(r=>`<tr><td>${cell(r.asset)}</td><td><a href="${cell(r.report)}">${cell(r.frame)}</a></td><td>${r.matched}</td><td>${r.offBy2px.length}</td><td>${r.missing.length}</td><td>${r.extra.length}</td></tr>`).join('')}</table>`);
|
|
215
|
+
data.indexPath = path.join(target,'index.html');
|
|
216
|
+
}
|
|
217
|
+
if (!data.comparisons.length) emptySelection(warnings);
|
|
218
|
+
data.complete = true;
|
|
219
|
+
if (data.summary.offsets || data.summary.missing || data.summary.extra) throw new CliError('COMPARE_FAILED', 'Comparison found text or position differences.', {data,warnings,humanReported:true});
|
|
220
|
+
return {data,warnings};
|
|
221
|
+
} catch (cause) { throw commandFailure(cause,data,warnings); }
|
|
175
222
|
}
|
package/src/toolkit/config.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
+
import { CliError } from '../cli-output.mjs';
|
|
3
4
|
import { pathToFileURL } from 'node:url';
|
|
4
5
|
import { createRequire } from 'node:module';
|
|
5
6
|
import { build } from 'esbuild';
|
|
@@ -18,7 +19,7 @@ export function legacyConfigFile(directory) {
|
|
|
18
19
|
export function requireMigration(directory) {
|
|
19
20
|
const old = legacyConfigFile(directory);
|
|
20
21
|
if (old && !CONFIG_NAMES.some(name => existsSync(path.join(directory, name)))) {
|
|
21
|
-
throw
|
|
22
|
+
throw new CliError('MIGRATION_REQUIRED', `Found ${old}; run adg migrate ${JSON.stringify(directory)} before using this project.`, { context: { project: directory } });
|
|
22
23
|
}
|
|
23
24
|
}
|
|
24
25
|
|
|
@@ -36,7 +37,7 @@ export function discoverRoot(cwd = process.cwd()) {
|
|
|
36
37
|
|
|
37
38
|
function versionParts(value) {
|
|
38
39
|
const match = value.match(/^(\d+)\.(\d+)\.(\d+)(?:-([\w.-]+))?(?:\+[\w.-]+)?$/);
|
|
39
|
-
if (!match) throw new
|
|
40
|
+
if (!match) throw new CliError('CONFIG_INVALID', `Invalid version ${value}; use major.minor.patch in requires`);
|
|
40
41
|
return [...match.slice(1, 4).map(Number), match[4]];
|
|
41
42
|
}
|
|
42
43
|
function order(a, b) {
|
|
@@ -59,13 +60,13 @@ function order(a, b) {
|
|
|
59
60
|
// Unsupported syntax fails explicitly instead of silently accepting a version.
|
|
60
61
|
export function satisfies(version, range) {
|
|
61
62
|
const actual = versionParts(version);
|
|
62
|
-
if (typeof range !== 'string' || !range.trim()) throw new
|
|
63
|
+
if (typeof range !== 'string' || !range.trim()) throw new CliError('CONFIG_INVALID', 'Invalid requires; use a range such as >=0.3.0');
|
|
63
64
|
const alternatives = range.split('||').map(branch => {
|
|
64
65
|
const terms = branch.trim().replace(/(>=|<=|>|<|=|\^|~)\s+/g, '$1').split(/\s+/);
|
|
65
66
|
return terms.map(term => {
|
|
66
67
|
if (term === '*') return !actual[3];
|
|
67
68
|
const match = term.match(/^(>=|<=|>|<|=|\^|~)?(\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?)$/);
|
|
68
|
-
if (!match) throw new
|
|
69
|
+
if (!match) throw new CliError('CONFIG_INVALID', `Unsupported requires ${range}; use comparisons with full versions, such as >=0.3.0`);
|
|
69
70
|
const target = versionParts(match[2]), delta = order(actual, target), op = match[1] ?? '=';
|
|
70
71
|
if (actual[3] && (!target[3] || actual.slice(0, 3).some((v, i) => v !== target[i]))) return false;
|
|
71
72
|
if (op === '^' || op === '~') {
|
|
@@ -82,7 +83,7 @@ export function satisfies(version, range) {
|
|
|
82
83
|
|
|
83
84
|
export function viewport(value) {
|
|
84
85
|
const match = typeof value === 'string' && value.match(/^([1-9]\d*)x([1-9]\d*)$/);
|
|
85
|
-
if (!match) throw new
|
|
86
|
+
if (!match) throw new CliError('CONFIG_INVALID', `Invalid viewport ${value}; use <width>x<height>, for example 1280x800`);
|
|
86
87
|
return { width: Number(match[1]), height: Number(match[2]) };
|
|
87
88
|
}
|
|
88
89
|
async function importConfig(file) {
|
|
@@ -113,22 +114,22 @@ export async function loadConfig(cwd = process.cwd(), { checkVersion = true } =
|
|
|
113
114
|
let config = {};
|
|
114
115
|
if (file) {
|
|
115
116
|
try { config = await importConfig(file); }
|
|
116
|
-
catch (error) { throw new
|
|
117
|
+
catch (error) { throw new CliError('CONFIG_INVALID', `Cannot load ${file}: ${error.message}; fix ${path.basename(file)}`, { cause: error }); }
|
|
117
118
|
}
|
|
118
|
-
if (!config || typeof config !== 'object' || Array.isArray(config)) throw new
|
|
119
|
-
if (config.name !== undefined && (typeof config.name !== 'string' || !config.name.trim())) throw new
|
|
119
|
+
if (!config || typeof config !== 'object' || Array.isArray(config)) throw new CliError('CONFIG_INVALID', 'Export a default object from adg.config.mjs');
|
|
120
|
+
if (config.name !== undefined && (typeof config.name !== 'string' || !config.name.trim())) throw new CliError('CONFIG_INVALID', 'Set name to a non-empty project name in the ADG config');
|
|
120
121
|
const compatible = config.requires === undefined || satisfies(VERSION, config.requires);
|
|
121
|
-
if (checkVersion && !compatible) throw new
|
|
122
|
-
for (const key of ['design', 'output', 'arch']) if (config[key] !== undefined && !(key === 'arch' && config[key] === false) && (typeof config[key] !== 'string' || !config[key].trim())) throw new
|
|
123
|
-
if (config.check !== undefined && (!config.check || typeof config.check!=='object' || Array.isArray(config.check))) throw new
|
|
124
|
-
if (config.check?.importDirection !== undefined && typeof config.check.importDirection!=='boolean') throw new
|
|
122
|
+
if (checkVersion && !compatible) throw new CliError('VERSION_UNSATISFIED', `ADG ${VERSION} does not satisfy requires ${config.requires}; run ${UPDATE}`);
|
|
123
|
+
for (const key of ['design', 'output', 'arch']) if (config[key] !== undefined && !(key === 'arch' && config[key] === false) && (typeof config[key] !== 'string' || !config[key].trim())) throw new CliError('CONFIG_INVALID', `Set ${key} to a directory path in adg.config.mjs`);
|
|
124
|
+
if (config.check !== undefined && (!config.check || typeof config.check!=='object' || Array.isArray(config.check))) throw new CliError('CONFIG_INVALID', 'Set check to an object in adg.config.mjs');
|
|
125
|
+
if (config.check?.importDirection !== undefined && typeof config.check.importDirection!=='boolean') throw new CliError('CONFIG_INVALID', 'Set check.importDirection to true or false in adg.config.mjs');
|
|
125
126
|
const compare = { port: 5188, viewport: '1280x800', ...config.compare };
|
|
126
127
|
viewport(compare.viewport);
|
|
127
|
-
if (!Number.isInteger(compare.port) || compare.port < 1 || compare.port > 65535) throw new
|
|
128
|
-
for (const key of ['start', 'fixture', 'ready', 'texts']) if (compare[key] !== undefined && typeof compare[key] !== 'function') throw new
|
|
129
|
-
if (compare.block !== undefined && (!Array.isArray(compare.block) || compare.block.some(value => typeof value !== 'string'))) throw new
|
|
130
|
-
if (config.check?.archMaxEdges !== undefined && (!Number.isInteger(config.check.archMaxEdges) || config.check.archMaxEdges < 0)) throw
|
|
131
|
-
if (typeof config.arch === 'string' && (path.isAbsolute(config.arch) || path.relative(root,path.resolve(root,config.arch)).startsWith('..'))) throw
|
|
128
|
+
if (!Number.isInteger(compare.port) || compare.port < 1 || compare.port > 65535) throw new CliError('CONFIG_INVALID', 'Set compare.port to an integer from 1 to 65535 in adg.config.mjs');
|
|
129
|
+
for (const key of ['start', 'fixture', 'ready', 'texts']) if (compare[key] !== undefined && typeof compare[key] !== 'function') throw new CliError('CONFIG_INVALID', `Set compare.${key} to a function in adg.config.mjs`);
|
|
130
|
+
if (compare.block !== undefined && (!Array.isArray(compare.block) || compare.block.some(value => typeof value !== 'string'))) throw new CliError('CONFIG_INVALID', 'Set compare.block to an array of request patterns in adg.config.mjs');
|
|
131
|
+
if (config.check?.archMaxEdges !== undefined && (!Number.isInteger(config.check.archMaxEdges) || config.check.archMaxEdges < 0)) throw new CliError('CONFIG_INVALID', 'Set check.archMaxEdges to a non-negative integer in adg.config.mjs');
|
|
132
|
+
if (typeof config.arch === 'string' && (path.isAbsolute(config.arch) || path.relative(root,path.resolve(root,config.arch)).startsWith('..'))) throw new CliError('CONFIG_INVALID', 'Set arch to a project-root-relative directory in adg.config.mjs');
|
|
132
133
|
const arch = config.arch === false ? false : path.resolve(root,config.arch ?? 'arch');
|
|
133
134
|
const design=path.resolve(root,config.design??'design');
|
|
134
135
|
return { root, name: config.name ?? path.basename(root), requires: config.requires ?? null, compatible, archDirectory: arch, arch: arch && (config.arch !== undefined || archFiles(arch).length) ? arch : false, sources: sourceDirectories({...config,design}), design, output: path.resolve(root, config.output ?? 'output/design'), check:{archMaxEdges:30,importDirection:true,...config.check}, compare };
|
package/src/toolkit/migrate.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import { existsSync, readFileSync, writeFileSync, readdirSync, renameSync, rmSyn
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { CONFIG_NAMES, LEGACY_CONFIG_NAMES, loadConfig } from './config.mjs';
|
|
4
4
|
import { refreshTypes, relative } from './project.mjs';
|
|
5
|
+
import { CliError, classifyError } from '../cli-output.mjs';
|
|
5
6
|
|
|
6
7
|
function files(directory) {
|
|
7
8
|
if (!existsSync(directory)) return [];
|
|
@@ -38,36 +39,47 @@ export async function migrate(project = process.cwd(), log = console.log) {
|
|
|
38
39
|
const root = path.resolve(project);
|
|
39
40
|
const oldConfigs = LEGACY_CONFIG_NAMES.filter(name => existsSync(path.join(root, name)));
|
|
40
41
|
const newConfigs = CONFIG_NAMES.filter(name => existsSync(path.join(root, name)));
|
|
41
|
-
if (oldConfigs.length && newConfigs.length) throw
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
const update = (file, next) => {
|
|
50
|
-
const original = readFileSync(file, 'utf8');
|
|
51
|
-
if (next === original) return;
|
|
52
|
-
writeFileSync(file, next);
|
|
53
|
-
log(`Updated ${relative(config, file)}`);
|
|
54
|
-
};
|
|
55
|
-
for (const file of files(config.design)) {
|
|
56
|
-
if (/\.[cm]?[jt]sx?$/.test(file)) update(file, rewriteImports(readFileSync(file, 'utf8')));
|
|
57
|
-
if (/^tsconfig(?:\.[^.]+)*\.json$/.test(path.basename(file))) {
|
|
58
|
-
update(file, readFileSync(file, 'utf8')
|
|
59
|
-
.replace(/(["'])sdg(?=["'/:])/g, '$1adg').replace(/\.sdg(?=[/\\])/g, '.adg'));
|
|
42
|
+
if (oldConfigs.length && newConfigs.length) throw new CliError('MIGRATION_CONFLICT', `Both old and new config names exist in ${root}; keep one configuration before running adg migrate.`, { context: { project: root } });
|
|
43
|
+
const data = { project: root, complete: false, changes: [] };
|
|
44
|
+
try {
|
|
45
|
+
for (const name of oldConfigs) {
|
|
46
|
+
const next = name.replace('sdg.', 'adg.');
|
|
47
|
+
renameSync(path.join(root, name), path.join(root, next));
|
|
48
|
+
data.changes.push({ action: 'renamed', path: path.join(root, next), from: path.join(root, name) });
|
|
49
|
+
log(`Renamed ${name} -> ${next}`);
|
|
60
50
|
}
|
|
51
|
+
const config = await loadConfig(root, { checkVersion: false });
|
|
52
|
+
if (config.root !== root) throw new CliError('PROJECT_NOT_FOUND', `No project configuration in ${root}; run adg migrate from the project root.`);
|
|
53
|
+
const update = (file, next) => {
|
|
54
|
+
const original = readFileSync(file, 'utf8');
|
|
55
|
+
if (next === original) return;
|
|
56
|
+
writeFileSync(file, next);
|
|
57
|
+
data.changes.push({ action: 'updated', path: file, from: null });
|
|
58
|
+
log(`Updated ${relative(config, file)}`);
|
|
59
|
+
};
|
|
60
|
+
for (const file of files(config.design)) {
|
|
61
|
+
if (/\.[cm]?[jt]sx?$/.test(file)) update(file, rewriteImports(readFileSync(file, 'utf8')));
|
|
62
|
+
if (/^tsconfig(?:\.[^.]+)*\.json$/.test(path.basename(file))) {
|
|
63
|
+
update(file, readFileSync(file, 'utf8')
|
|
64
|
+
.replace(/(["'])sdg(?=["'/:])/g, '$1adg').replace(/\.sdg(?=[/\\])/g, '.adg'));
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
for (const file of files(root).filter(file => path.basename(file) === '.gitignore')) {
|
|
68
|
+
update(file, readFileSync(file, 'utf8').replace(/^(?!\s*#)(.*)$/gm, line => line.replace(/(^|\/)\.sdg(?=\/|\r?$)/g, '$1.adg')));
|
|
69
|
+
}
|
|
70
|
+
const oldGenerated = path.join(config.design, '.sdg');
|
|
71
|
+
if (existsSync(oldGenerated)) {
|
|
72
|
+
rmSync(oldGenerated, { recursive: true });
|
|
73
|
+
data.changes.push({ action: 'deleted', path: oldGenerated, from: null });
|
|
74
|
+
log(`Deleted ${relative(config, oldGenerated)}/`);
|
|
75
|
+
}
|
|
76
|
+
refreshTypes(config, data.changes);
|
|
77
|
+
log(`Regenerated ${relative(config, path.join(config.design, '.adg'))}/`);
|
|
78
|
+
data.complete = true;
|
|
79
|
+
return data;
|
|
80
|
+
} catch (error) {
|
|
81
|
+
if (!data.changes.length) throw error;
|
|
82
|
+
if (error instanceof CliError) { error.data = data; throw error; }
|
|
83
|
+
throw new CliError(classifyError(error).error.code, error.message, { cause: error, data });
|
|
61
84
|
}
|
|
62
|
-
for (const file of files(root).filter(file => path.basename(file) === '.gitignore')) {
|
|
63
|
-
update(file, readFileSync(file, 'utf8').replace(/^(?!\s*#)(.*)$/gm, line => line.replace(/(^|\/)\.sdg(?=\/|\r?$)/g, '$1.adg')));
|
|
64
|
-
}
|
|
65
|
-
const oldGenerated = path.join(config.design, '.sdg');
|
|
66
|
-
if (existsSync(oldGenerated)) {
|
|
67
|
-
rmSync(oldGenerated, { recursive: true });
|
|
68
|
-
log(`Deleted ${relative(config, oldGenerated)}/`);
|
|
69
|
-
}
|
|
70
|
-
refreshTypes(config);
|
|
71
|
-
log(`Regenerated ${relative(config, path.join(config.design, '.adg'))}/`);
|
|
72
|
-
return 0;
|
|
73
85
|
}
|
package/src/toolkit/project.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync, realpathSync } from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { parseTokens } from './tokens.mjs';
|
|
4
|
+
import { CliError, classifyError } from '../cli-output.mjs';
|
|
4
5
|
export const starterTokens = `:root {
|
|
5
6
|
--font-ui: system-ui, sans-serif;
|
|
6
7
|
--font-mono: ui-monospace, monospace;
|
|
@@ -23,16 +24,18 @@ export function sourceDirectories(config = {}) {
|
|
|
23
24
|
readdirSync(path.join(config.design, 'studies'), {withFileTypes:true}).some(entry => entry.isFile() && isSourcePath(`studies/${entry.name}`, ['studies']));
|
|
24
25
|
const sources = config.sources === undefined ? [...defaultSources, ...(studies ? ['studies'] : [])] : config.sources;
|
|
25
26
|
if (!Array.isArray(sources) || !sources.length || sources.some(name => typeof name !== 'string' || !/^[A-Za-z0-9_-]+$/.test(name))) {
|
|
26
|
-
throw
|
|
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');
|
|
27
28
|
}
|
|
28
29
|
return [...new Set(sources)];
|
|
29
30
|
}
|
|
30
31
|
const sourceLocations = sources => sources.map(name => `${name}/`).join(', ');
|
|
31
|
-
export function refreshTypes(config) {
|
|
32
|
+
export function refreshTypes(config, changes) {
|
|
32
33
|
mkdirSync(path.join(config.design, '.adg'), { recursive: true });
|
|
33
34
|
const runtime = readFileSync(new URL('./runtime.d.ts', import.meta.url), 'utf8');
|
|
34
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 });
|
|
35
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 });
|
|
36
39
|
}
|
|
37
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'] };
|
|
38
41
|
function starterSources(sources) {
|
|
@@ -61,31 +64,42 @@ export default () => <Frame name="default"${last ? ' width={640} height={360}' :
|
|
|
61
64
|
});
|
|
62
65
|
}
|
|
63
66
|
export function init(config, log = console.log) {
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
[
|
|
74
|
-
...
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
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 });
|
|
82
102
|
}
|
|
83
|
-
const ignore = path.join(config.root, '.gitignore');
|
|
84
|
-
let text = existsSync(ignore) ? readFileSync(ignore, 'utf8') : '';
|
|
85
|
-
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`;
|
|
86
|
-
writeFileSync(ignore, text);
|
|
87
|
-
refreshTypes(config);
|
|
88
|
-
return 0;
|
|
89
103
|
}
|
|
90
104
|
export function listSources(directory, sources = sourceDirectories({design:directory})) {
|
|
91
105
|
return sources.flatMap(name => {
|
|
@@ -115,7 +129,7 @@ export function readGroups(directory, sources = sourceDirectories({design:direct
|
|
|
115
129
|
return data.groups;
|
|
116
130
|
} catch (error) {
|
|
117
131
|
if (error.code === 'ENOENT') return [];
|
|
118
|
-
throw
|
|
132
|
+
throw new CliError('CONFIG_INVALID', `gallery.json: ${error.message}`, { cause: error });
|
|
119
133
|
}
|
|
120
134
|
}
|
|
121
135
|
export function rejectLegacy(config, files) {
|
|
@@ -123,9 +137,7 @@ export function rejectLegacy(config, files) {
|
|
|
123
137
|
files ??= directories.flatMap(base => existsSync(base) ? readdirSync(base).map(name => path.join(base, name)) : []);
|
|
124
138
|
for (const file of files) {
|
|
125
139
|
if (/\.svg$/i.test(file) && directories.includes(path.dirname(file))) {
|
|
126
|
-
|
|
127
|
-
error.code = 'LEGACY_SVG';
|
|
128
|
-
throw error;
|
|
140
|
+
throw new CliError('LEGACY_SOURCE', `${relative(config, file)}: convert this SVG source to TSX; move artwork to design/art/`);
|
|
129
141
|
}
|
|
130
142
|
}
|
|
131
143
|
}
|
|
@@ -141,7 +153,7 @@ export function selectSources(config, args = [], { write = true, additional = []
|
|
|
141
153
|
if(path.isAbsolute(arg)) {
|
|
142
154
|
const root=realpathSync(config.root),file=existsSync(arg)?realpathSync(arg):path.resolve(arg);
|
|
143
155
|
const relative=path.relative(root,file);
|
|
144
|
-
if(relative==='..'||relative.startsWith('..'+path.sep)||path.isAbsolute(relative))throw
|
|
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}.`);
|
|
145
157
|
const found=sources.find(source=>(existsSync(source)?realpathSync(source):path.resolve(source))===file);
|
|
146
158
|
if(found)return found;
|
|
147
159
|
}
|
|
@@ -149,12 +161,12 @@ export function selectSources(config, args = [], { write = true, additional = []
|
|
|
149
161
|
let file = path.isAbsolute(arg) || fromRoot.startsWith(config.design + path.sep) ? fromRoot : path.resolve(config.design, arg);
|
|
150
162
|
if (existsSync(file)) rejectLegacy(config, [file]);
|
|
151
163
|
if (!file.endsWith('.tsx')) file += '.tsx';
|
|
152
|
-
if (!sources.includes(file)) throw
|
|
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(', ')}`);
|
|
153
165
|
return file;
|
|
154
166
|
});
|
|
155
167
|
}
|
|
156
168
|
export const relative = (config, file) => path.relative(config.root, file).split(path.sep).join('/');
|
|
157
169
|
export function loadTokens(config) {
|
|
158
170
|
try { return parseTokens(readFileSync(path.join(config.design, 'tokens.css'), 'utf8')); }
|
|
159
|
-
catch (error) { throw
|
|
171
|
+
catch (error) { throw new CliError('TOKENS_INVALID', `${error.message}; fix design/tokens.css or run adg init`, { cause: error }); }
|
|
160
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
|
+
}
|