@whzxc/agent-design-gallery 0.0.0-stage → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +69 -0
- package/README.md +218 -2
- package/package.json +43 -4
- package/public/access.css +10 -0
- package/public/app.js +1674 -0
- package/public/arrangement-worker.js +11 -0
- package/public/arrangement.js +49 -0
- package/public/assets.js +356 -0
- package/public/auth.js +69 -0
- package/public/favicon.svg +6 -0
- package/public/hub.css +67 -0
- package/public/hub.html +33 -0
- package/public/hub.js +165 -0
- package/public/icons.js +50 -0
- package/public/index.html +70 -0
- package/public/instance-actions.js +27 -0
- package/public/labels.js +122 -0
- package/public/layout.js +119 -0
- package/public/relationships.js +28 -0
- package/public/selection.js +20 -0
- package/public/style.css +194 -0
- package/public/switcher.css +37 -0
- package/public/switcher.js +176 -0
- package/public/token-catalog.js +129 -0
- package/public/tokens.css +61 -0
- package/public/view-route.js +66 -0
- package/src/cli-output.mjs +236 -0
- package/src/cli.mjs +176 -0
- package/src/http.mjs +38 -0
- package/src/hub/auth.mjs +41 -0
- package/src/hub/instances.mjs +99 -0
- package/src/hub/proxy.mjs +30 -0
- package/src/hub/registry.mjs +181 -0
- package/src/hub.mjs +128 -0
- package/src/lifecycle.mjs +109 -0
- package/src/link.mjs +55 -0
- package/src/open.mjs +61 -0
- package/src/perf.mjs +12 -0
- package/src/server.mjs +679 -0
- package/src/service.mjs +184 -0
- package/src/toolkit/arch-browser.mjs +40 -0
- package/src/toolkit/arch-git.mjs +55 -0
- package/src/toolkit/arch-overlay.mjs +225 -0
- package/src/toolkit/arch.mjs +221 -0
- package/src/toolkit/asset-rules.mjs +14 -0
- package/src/toolkit/browser.mjs +33 -0
- package/src/toolkit/build-store.mjs +266 -0
- package/src/toolkit/build-worker.mjs +35 -0
- package/src/toolkit/build.mjs +147 -0
- package/src/toolkit/commands.mjs +345 -0
- package/src/toolkit/compare.mjs +222 -0
- package/src/toolkit/config.mjs +136 -0
- package/src/toolkit/document.mjs +85 -0
- package/src/toolkit/migrate.mjs +85 -0
- package/src/toolkit/project.mjs +172 -0
- package/src/toolkit/results.mjs +44 -0
- package/src/toolkit/runtime.d.ts +14 -0
- package/src/toolkit/runtime.mjs +54 -0
- package/src/toolkit/text.mjs +12 -0
- package/src/toolkit/tokens.mjs +37 -0
- package/src/viewer-cache.mjs +85 -0
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
4
|
+
import { launch, loadFrame } from './browser.mjs';
|
|
5
|
+
import { implementationTexts } from './document.mjs';
|
|
6
|
+
import { matchTexts, textDelta } from './text.mjs';
|
|
7
|
+
import { selectSources, relative } from './project.mjs';
|
|
8
|
+
import { buildSource } from './build.mjs';
|
|
9
|
+
import { viewport } from './config.mjs';
|
|
10
|
+
import { CliError, classifyError } from '../cli-output.mjs';
|
|
11
|
+
import { commandFailure, cleanup, emptySelection } from './results.mjs';
|
|
12
|
+
|
|
13
|
+
export function compareReport(asset, frame, fixture, design, implementation) {
|
|
14
|
+
const { pairs, missing, extra } = matchTexts(design.texts, implementation.texts);
|
|
15
|
+
const rows = pairs.map(([d, i]) => ({ text: d.text, ...textDelta(d, i) })).map(row => ({ ...row, off: Math.max(Math.abs(row.dx), Math.abs(row.dy), Math.abs(row.dw)) }));
|
|
16
|
+
return { asset, frame, fixture, size: { design: [Math.round(design.box.width), Math.round(design.box.height)], implementation: [Math.round(implementation.box.width), Math.round(implementation.box.height)] }, matched: rows.length,
|
|
17
|
+
offBy2px: rows.filter(row => row.off > 2).sort((a, b) => b.off - a.off), missing: missing.map(m => m.text), extra: extra.map(e => e.text) };
|
|
18
|
+
}
|
|
19
|
+
const cell = value => String(value).replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"');
|
|
20
|
+
export function reportHtml(report) {
|
|
21
|
+
const fmt = value => (value > 0 ? '+' : '') + value.toFixed(1);
|
|
22
|
+
return `<!doctype html><meta charset="utf-8"><title>${cell(report.asset)} ${cell(report.frame)}</title><style>body{font:13px system-ui;margin:24px;background:#f4f4f4}.row{display:flex;gap:16px;align-items:flex-start;overflow:auto}figure{margin:0}img{display:block;max-width:none;border:1px solid #ccc}table{border-collapse:collapse;margin-top:24px}td,th{padding:4px 10px;border-bottom:1px solid #ddd;text-align:left}td.n{font-family:ui-monospace,monospace;text-align:right}</style>
|
|
23
|
+
<h1>${cell(report.asset)} · ${cell(report.frame)} vs ${cell(report.fixture)}</h1><p>Matched ${report.matched} texts. ${report.offBy2px.length} differ by more than 2px. ${report.missing.length} missing in implementation. ${report.extra.length} extra in implementation.</p>
|
|
24
|
+
<div class="row">${['design', 'implementation', 'overlay'].map(name => `<figure><figcaption>${name}</figcaption><img src="${name}.png"></figure>`).join('')}</div>
|
|
25
|
+
<table><tr><th>Text</th><th>dx</th><th>dy</th><th>dw</th></tr>${report.offBy2px.map(row => `<tr><td>${cell(row.text)}</td><td class="n">${fmt(row.dx)}</td><td class="n">${fmt(row.dy)}</td><td class="n">${fmt(row.dw)}</td></tr>`).join('')}</table>
|
|
26
|
+
<h2>Missing in implementation</h2><p>${report.missing.map(cell).join(' · ') || 'None'}</p><h2>Extra in implementation</h2><p>${report.extra.map(cell).join(' · ') || 'None'}</p>`;
|
|
27
|
+
}
|
|
28
|
+
async function overlay(page, target) {
|
|
29
|
+
const images = ['design', 'implementation'].map(name => `data:image/png;base64,${readFileSync(path.join(target, `${name}.png`)).toString('base64')}`);
|
|
30
|
+
const data = await page.evaluate(async sources => {
|
|
31
|
+
const [a, b] = await Promise.all(sources.map(src => new Promise((resolve, reject) => {
|
|
32
|
+
const image = new Image(); image.onload = () => resolve(image); image.onerror = reject; image.src = src;
|
|
33
|
+
})));
|
|
34
|
+
const canvas = document.createElement('canvas');
|
|
35
|
+
canvas.width = Math.min(a.width, b.width); canvas.height = Math.min(a.height, b.height);
|
|
36
|
+
const context = canvas.getContext('2d');
|
|
37
|
+
context.drawImage(a, 0, 0); const first = context.getImageData(0, 0, canvas.width, canvas.height);
|
|
38
|
+
context.clearRect(0, 0, canvas.width, canvas.height); context.drawImage(b, 0, 0);
|
|
39
|
+
const second = context.getImageData(0, 0, canvas.width, canvas.height);
|
|
40
|
+
for (let i = 0; i < first.data.length; i += 4) {
|
|
41
|
+
for (let c = 0; c < 3; c++) first.data[i + c] = Math.round((first.data[i + c] + second.data[i + c]) / 2);
|
|
42
|
+
first.data[i + 3] = 255;
|
|
43
|
+
}
|
|
44
|
+
context.putImageData(first, 0, 0);
|
|
45
|
+
return canvas.toDataURL('image/png').split(',')[1];
|
|
46
|
+
}, images);
|
|
47
|
+
writeFileSync(path.join(target, 'overlay.png'), Buffer.from(data, 'base64'));
|
|
48
|
+
}
|
|
49
|
+
const safeName = value => encodeURIComponent(value).replace(/\./g, '%2E');
|
|
50
|
+
export async function settle(read, { now: monotonicNow = () => performance.now(), sleep = delay } = {}) {
|
|
51
|
+
const started = monotonicNow();
|
|
52
|
+
let previous, changed = started;
|
|
53
|
+
for (;;) {
|
|
54
|
+
const implementation = await read();
|
|
55
|
+
const state = JSON.stringify({ box: implementation.box, texts: implementation.texts.map(({ text, x, y, width, height }) => ({ text, x, y, width, height })) });
|
|
56
|
+
const now = monotonicNow();
|
|
57
|
+
if (state !== previous) { previous = state; changed = now; }
|
|
58
|
+
if (now - changed >= 300) return { implementation, settled: true };
|
|
59
|
+
if (now - started >= 5000) return { implementation, settled: false };
|
|
60
|
+
await sleep(Math.min(50, 5000 - (now - started)));
|
|
61
|
+
}
|
|
62
|
+
}
|
|
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');
|
|
76
|
+
const settings = {...definition.capture};
|
|
77
|
+
if (options.region || options.selector || options.page) { delete settings.region; delete settings.selector; delete settings.page; }
|
|
78
|
+
for (const key of ['region','selector','page','origin','viewport']) if (options[key] !== undefined) settings[key] = options[key];
|
|
79
|
+
settings.clicks = options.click ?? settings.clicks ?? [];
|
|
80
|
+
const browser = await launchBrowser();
|
|
81
|
+
let stop, primary;
|
|
82
|
+
try {
|
|
83
|
+
const fixtureName = options.fixture ?? definition.fixture;
|
|
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');
|
|
87
|
+
if (fixture.timezone !== undefined) {
|
|
88
|
+
try {
|
|
89
|
+
if (typeof fixture.timezone !== 'string' || !fixture.timezone || /^[+-]/.test(fixture.timezone)) throw new Error();
|
|
90
|
+
new Intl.DateTimeFormat('en-US', { timeZone: fixture.timezone });
|
|
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'); }
|
|
92
|
+
}
|
|
93
|
+
const sheet = await browser.newPage({colorScheme:fixture.theme,locale:fixture.locale,timezoneId:fixture.timezone,reducedMotion:'reduce'});
|
|
94
|
+
const frameBox = await loadFrame(sheet,definition,fixture.theme);
|
|
95
|
+
let design = await sheet.locator('[data-adg-frame] > :first-child').evaluate(implementationTexts);
|
|
96
|
+
const size = viewport(settings.viewport ?? adapter.viewport);
|
|
97
|
+
const origin = (settings.origin ?? '0 0').trim().split(/\s+/).map(Number);
|
|
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');
|
|
100
|
+
const absolute = /^https?:\/\//.test(fixture.url);
|
|
101
|
+
if (!adapter.start && !absolute) throw new CliError('CONFIG_INVALID', 'Relative fixture URL needs compare.start; add it or return an absolute URL');
|
|
102
|
+
const url = new URL(fixture.url, `http://127.0.0.1:${adapter.port}`).href;
|
|
103
|
+
if (!/^https?:/.test(url)) throw new CliError('CONFIG_INVALID', 'Fixture URL must use HTTP or HTTPS; fix compare.fixture');
|
|
104
|
+
if (adapter.start) {
|
|
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');
|
|
107
|
+
}
|
|
108
|
+
await sheet.emulateMedia({ colorScheme: fixture.theme, reducedMotion: 'reduce' });
|
|
109
|
+
await sheet.evaluate(theme => document.documentElement.setAttribute('data-theme', theme), fixture.theme);
|
|
110
|
+
design = await sheet.locator('[data-adg-frame] > :first-child').evaluate(implementationTexts);
|
|
111
|
+
const target = path.join(config.output, 'compare', `${path.relative(config.design,file).replace(/\.tsx$/, '').split(path.sep).join('-')}-${safeName(frame)}-${safeName(fixtureName)}`);
|
|
112
|
+
mkdirSync(target, { recursive: true });
|
|
113
|
+
await sheet.screenshot({ path: path.join(target, 'design.png'), clip: frameBox });
|
|
114
|
+
const app = await browser.newPage({ viewport: size, colorScheme: fixture.theme, reducedMotion: 'reduce', locale: fixture.locale, timezoneId: fixture.timezone });
|
|
115
|
+
for (const pattern of adapter.block ?? []) await app.route(pattern, route => route.abort());
|
|
116
|
+
await app.addInitScript(({ clock, theme }) => {
|
|
117
|
+
const original = Date, fixed = original.parse(clock);
|
|
118
|
+
function FixedDate(...values) {
|
|
119
|
+
if (!new.target) return new original(fixed).toString();
|
|
120
|
+
return Reflect.construct(original, values.length ? values : [fixed], new.target);
|
|
121
|
+
}
|
|
122
|
+
Object.setPrototypeOf(FixedDate, original); FixedDate.prototype = original.prototype; FixedDate.now = () => fixed;
|
|
123
|
+
globalThis.Date = FixedDate;
|
|
124
|
+
const apply = () => document.documentElement?.setAttribute('data-theme', theme);
|
|
125
|
+
if (document.documentElement) apply();
|
|
126
|
+
else { const observer = new MutationObserver(() => { if (document.documentElement) { apply(); observer.disconnect(); } }); observer.observe(document, { childList: true }); }
|
|
127
|
+
document.addEventListener('DOMContentLoaded', apply, { once: true });
|
|
128
|
+
}, { clock: fixture.clock, theme: fixture.theme });
|
|
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);
|
|
134
|
+
for (const name of settings.clicks) {
|
|
135
|
+
let control;
|
|
136
|
+
for (const role of ['button', 'radio', 'tab', 'checkbox', 'switch', 'menuitem', 'menuitemradio', 'option', 'link']) {
|
|
137
|
+
const candidate = app.getByRole(role, { name, exact: true }).filter({ visible: true }).first();
|
|
138
|
+
if (await candidate.count()) { control = candidate; break; }
|
|
139
|
+
}
|
|
140
|
+
if (!control) {
|
|
141
|
+
throw new CliError('COMPARE_TARGET_NOT_FOUND', `No visible control matches --click=${JSON.stringify(name)}`);
|
|
142
|
+
}
|
|
143
|
+
await control.click();
|
|
144
|
+
}
|
|
145
|
+
await app.evaluate(() => document.fonts.ready);
|
|
146
|
+
const capture = settings.page ? { x: origin[0], y: origin[1], width: frameBox.width, height: frameBox.height } : undefined;
|
|
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();
|
|
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
|
+
}
|
|
152
|
+
const { implementation, settled } = await settle(async () => {
|
|
153
|
+
const result = await panel.evaluate(implementationTexts, capture);
|
|
154
|
+
if (adapter.texts) {
|
|
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');
|
|
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 })));
|
|
158
|
+
}
|
|
159
|
+
return result;
|
|
160
|
+
}, clock);
|
|
161
|
+
const screenshot = { path: path.join(target, 'implementation.png') };
|
|
162
|
+
if (capture) await app.screenshot({ ...screenshot, clip: capture });
|
|
163
|
+
else await panel.screenshot(screenshot);
|
|
164
|
+
const canvasPage = await browser.newPage();
|
|
165
|
+
await overlay(canvasPage, target);
|
|
166
|
+
const report = { ...compareReport(relative(config, file), frame, fixtureName, {...design,box:frameBox}, implementation), settled };
|
|
167
|
+
writeFileSync(path.join(target, 'report.json'), JSON.stringify(report, null, 2) + '\n');
|
|
168
|
+
writeFileSync(path.join(target, 'index.html'), reportHtml(report));
|
|
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;
|
|
183
|
+
} finally {
|
|
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); }
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
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); }
|
|
222
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { CliError } from '../cli-output.mjs';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { createRequire } from 'node:module';
|
|
6
|
+
import { build } from 'esbuild';
|
|
7
|
+
import { sourceDirectories, archFiles } from './project.mjs';
|
|
8
|
+
|
|
9
|
+
export const VERSION = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url))).version;
|
|
10
|
+
export const UPDATE = 'npm install -g @whzxc/agent-design-gallery';
|
|
11
|
+
export const CONFIG_NAMES = ['adg.config.mjs', 'adg.config.js', 'adg.config.ts'];
|
|
12
|
+
export const configFile = directory => CONFIG_NAMES.map(name => path.join(directory, name)).find(file => statSync(file, { throwIfNoEntry: false })?.isFile());
|
|
13
|
+
|
|
14
|
+
// Old names belong only to this one-time migration and the discovery error.
|
|
15
|
+
export const LEGACY_CONFIG_NAMES = ['sdg.config.mjs', 'sdg.config.js', 'sdg.config.ts'];
|
|
16
|
+
export function legacyConfigFile(directory) {
|
|
17
|
+
return LEGACY_CONFIG_NAMES.map(name => path.join(directory, name)).find(existsSync);
|
|
18
|
+
}
|
|
19
|
+
export function requireMigration(directory) {
|
|
20
|
+
const old = legacyConfigFile(directory);
|
|
21
|
+
if (old && !CONFIG_NAMES.some(name => existsSync(path.join(directory, name)))) {
|
|
22
|
+
throw new CliError('MIGRATION_REQUIRED', `Found ${old}; run adg migrate ${JSON.stringify(directory)} before using this project.`, { context: { project: directory } });
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function discoverRoot(cwd = process.cwd()) {
|
|
27
|
+
let directory = path.resolve(cwd), packageRoot;
|
|
28
|
+
while (true) {
|
|
29
|
+
requireMigration(directory);
|
|
30
|
+
if (configFile(directory)) return directory;
|
|
31
|
+
if (!packageRoot && existsSync(path.join(directory, 'package.json'))) packageRoot = directory;
|
|
32
|
+
const parent = path.dirname(directory);
|
|
33
|
+
if (parent === directory) return packageRoot ?? path.resolve(cwd);
|
|
34
|
+
directory = parent;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function versionParts(value) {
|
|
39
|
+
const match = value.match(/^(\d+)\.(\d+)\.(\d+)(?:-([\w.-]+))?(?:\+[\w.-]+)?$/);
|
|
40
|
+
if (!match) throw new CliError('CONFIG_INVALID', `Invalid version ${value}; use major.minor.patch in requires`);
|
|
41
|
+
return [...match.slice(1, 4).map(Number), match[4]];
|
|
42
|
+
}
|
|
43
|
+
function order(a, b) {
|
|
44
|
+
for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return Math.sign(a[i] - b[i]);
|
|
45
|
+
if (a[3] === b[3]) return 0;
|
|
46
|
+
if (!a[3]) return 1;
|
|
47
|
+
if (!b[3]) return -1;
|
|
48
|
+
const x = a[3].split('.'), y = b[3].split('.');
|
|
49
|
+
for (let i = 0; i < Math.max(x.length, y.length); i++) {
|
|
50
|
+
if (x[i] === y[i]) continue;
|
|
51
|
+
if (x[i] === undefined) return -1;
|
|
52
|
+
if (y[i] === undefined) return 1;
|
|
53
|
+
const nx = /^\d+$/.test(x[i]), ny = /^\d+$/.test(y[i]);
|
|
54
|
+
return nx && ny ? Math.sign(Number(x[i]) - Number(y[i])) : nx !== ny ? (nx ? -1 : 1) : (x[i] < y[i] ? -1 : 1);
|
|
55
|
+
}
|
|
56
|
+
return 0;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Intentionally small range grammar: exact, comparisons, ^, ~, AND and ||.
|
|
60
|
+
// Unsupported syntax fails explicitly instead of silently accepting a version.
|
|
61
|
+
export function satisfies(version, range) {
|
|
62
|
+
const actual = versionParts(version);
|
|
63
|
+
if (typeof range !== 'string' || !range.trim()) throw new CliError('CONFIG_INVALID', 'Invalid requires; use a range such as >=0.3.0');
|
|
64
|
+
const alternatives = range.split('||').map(branch => {
|
|
65
|
+
const terms = branch.trim().replace(/(>=|<=|>|<|=|\^|~)\s+/g, '$1').split(/\s+/);
|
|
66
|
+
return terms.map(term => {
|
|
67
|
+
if (term === '*') return !actual[3];
|
|
68
|
+
const match = term.match(/^(>=|<=|>|<|=|\^|~)?(\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?)$/);
|
|
69
|
+
if (!match) throw new CliError('CONFIG_INVALID', `Unsupported requires ${range}; use comparisons with full versions, such as >=0.3.0`);
|
|
70
|
+
const target = versionParts(match[2]), delta = order(actual, target), op = match[1] ?? '=';
|
|
71
|
+
if (actual[3] && (!target[3] || actual.slice(0, 3).some((v, i) => v !== target[i]))) return false;
|
|
72
|
+
if (op === '^' || op === '~') {
|
|
73
|
+
const upper = [...target]; upper[3] = undefined;
|
|
74
|
+
const index = op === '~' ? 1 : target[0] ? 0 : target[1] ? 1 : 2;
|
|
75
|
+
upper[index]++; for (let i = index + 1; i < 3; i++) upper[i] = 0;
|
|
76
|
+
return delta >= 0 && order(actual, upper) < 0;
|
|
77
|
+
}
|
|
78
|
+
return ({ '=': delta === 0, '>=': delta >= 0, '<=': delta <= 0, '>': delta > 0, '<': delta < 0 })[op];
|
|
79
|
+
}).every(Boolean);
|
|
80
|
+
});
|
|
81
|
+
return alternatives.some(Boolean);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function viewport(value) {
|
|
85
|
+
const match = typeof value === 'string' && value.match(/^([1-9]\d*)x([1-9]\d*)$/);
|
|
86
|
+
if (!match) throw new CliError('CONFIG_INVALID', `Invalid viewport ${value}; use <width>x<height>, for example 1280x800`);
|
|
87
|
+
return { width: Number(match[1]), height: Number(match[2]) };
|
|
88
|
+
}
|
|
89
|
+
async function importConfig(file) {
|
|
90
|
+
if (!file.endsWith('.ts')) {
|
|
91
|
+
const info = statSync(file), url = pathToFileURL(file);
|
|
92
|
+
url.searchParams.set('revision', `${info.mtimeMs}-${info.size}`);
|
|
93
|
+
return (await import(url.href)).default;
|
|
94
|
+
}
|
|
95
|
+
const require = createRequire(pathToFileURL(file));
|
|
96
|
+
const result = await build({ entryPoints: [file], bundle: true, write: false, format: 'esm', platform: 'node', logLevel: 'silent',
|
|
97
|
+
define: { 'import.meta.url': JSON.stringify(pathToFileURL(file).href) },
|
|
98
|
+
plugins: [{ name: 'config-imports', setup(api) {
|
|
99
|
+
api.onResolve({filter: /.*/}, args => {
|
|
100
|
+
if (args.kind === 'entry-point' || args.path.startsWith('node:')) return;
|
|
101
|
+
const candidate = args.path.startsWith('.') ? path.resolve(args.resolveDir, args.path) : args.path;
|
|
102
|
+
// Keep JS modules at their original URLs, including their own import.meta.url.
|
|
103
|
+
// TypeScript helpers are bundled by esbuild without writing generated files.
|
|
104
|
+
if (/\.[cm]?js$/.test(candidate) || !candidate.startsWith('/')) {
|
|
105
|
+
const resolved = require.resolve(candidate);
|
|
106
|
+
return { path: resolved.startsWith('/') ? pathToFileURL(resolved).href : resolved, external: true };
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
}}] });
|
|
110
|
+
return (await import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}`)).default;
|
|
111
|
+
}
|
|
112
|
+
export async function loadConfig(cwd = process.cwd(), { checkVersion = true } = {}) {
|
|
113
|
+
const root = discoverRoot(cwd), file = configFile(root);
|
|
114
|
+
let config = {};
|
|
115
|
+
if (file) {
|
|
116
|
+
try { config = await importConfig(file); }
|
|
117
|
+
catch (error) { throw new CliError('CONFIG_INVALID', `Cannot load ${file}: ${error.message}; fix ${path.basename(file)}`, { cause: error }); }
|
|
118
|
+
}
|
|
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');
|
|
121
|
+
const compatible = config.requires === undefined || satisfies(VERSION, config.requires);
|
|
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');
|
|
126
|
+
const compare = { port: 5188, viewport: '1280x800', ...config.compare };
|
|
127
|
+
viewport(compare.viewport);
|
|
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');
|
|
133
|
+
const arch = config.arch === false ? false : path.resolve(root,config.arch ?? 'arch');
|
|
134
|
+
const design=path.resolve(root,config.design??'design');
|
|
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 };
|
|
136
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
export function implementationTexts(root, clip) {
|
|
2
|
+
const bounds = root.getBoundingClientRect();
|
|
3
|
+
const origin = clip ? { left: clip.x - scrollX, top: clip.y - scrollY, right: clip.x - scrollX + clip.width, bottom: clip.y - scrollY + clip.height } : bounds;
|
|
4
|
+
const texts = [];
|
|
5
|
+
const measure = document.createElement('canvas').getContext('2d');
|
|
6
|
+
const visible = owner => {
|
|
7
|
+
for (let el = owner; el; el = el.parentElement) {
|
|
8
|
+
const style = getComputedStyle(el);
|
|
9
|
+
if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') return false;
|
|
10
|
+
}
|
|
11
|
+
const hidden = owner.closest('[aria-hidden="true"]');
|
|
12
|
+
return (!hidden || hidden === root || !root.contains(hidden)) && !owner.closest('script, style, .sr-only');
|
|
13
|
+
};
|
|
14
|
+
const inside = (box, owner) => {
|
|
15
|
+
let left = origin.left, right = origin.right, top = origin.top, bottom = origin.bottom;
|
|
16
|
+
for (let el = owner; el; el = el.parentElement) {
|
|
17
|
+
const style = getComputedStyle(el), bounds = el.getBoundingClientRect();
|
|
18
|
+
if (/(hidden|clip|auto|scroll)/.test(style.overflowX)) { left = Math.max(left, bounds.left); right = Math.min(right, bounds.right); }
|
|
19
|
+
if (/(hidden|clip|auto|scroll)/.test(style.overflowY)) { top = Math.max(top, bounds.top); bottom = Math.min(bottom, bounds.bottom); }
|
|
20
|
+
}
|
|
21
|
+
return box.left >= left - 0.5 && box.right <= right + 0.5 && (box.top + box.bottom) / 2 >= top && (box.top + box.bottom) / 2 <= bottom;
|
|
22
|
+
};
|
|
23
|
+
const push = (text, box, owner, style = getComputedStyle(owner)) => {
|
|
24
|
+
if (!inside(box, owner)) return;
|
|
25
|
+
texts.push({ text, x: box.left - origin.left, y: box.top - origin.top, width: box.right - box.left, height: box.bottom - box.top,
|
|
26
|
+
space: (measure.font = `${style.fontWeight} ${style.fontSize} ${style.fontFamily}`, measure.measureText(' ').width), anchor: style.textAlign === 'center' ? 'middle' : style.textAlign === 'right' ? 'end' : 'start', fill: style.color, size: style.fontSize, weight: style.fontWeight, family: style.fontFamily });
|
|
27
|
+
};
|
|
28
|
+
const linesFor = node => {
|
|
29
|
+
const result=[];
|
|
30
|
+
const range = document.createRange(), lines = [];
|
|
31
|
+
for (let index = 0; index < node.length; index++) {
|
|
32
|
+
range.setStart(node, index); range.setEnd(node, index + 1);
|
|
33
|
+
const rect = [...range.getClientRects()].find(r => r.width > 0 && r.height > 1);
|
|
34
|
+
if (!rect) continue;
|
|
35
|
+
let line = lines.at(-1);
|
|
36
|
+
if (!line || Math.abs(line.top - rect.top) >= rect.height / 2) {
|
|
37
|
+
line = { text: '', top: rect.top, bottom: rect.bottom, chars: [] }; lines.push(line);
|
|
38
|
+
}
|
|
39
|
+
line.text += node.data[index]; line.chars.push({ index, rect }); line.bottom = Math.max(line.bottom, rect.bottom);
|
|
40
|
+
}
|
|
41
|
+
for (const line of lines) {
|
|
42
|
+
const content = line.text.replace(/\s+/g, ' ').trim();
|
|
43
|
+
if (!content) continue;
|
|
44
|
+
const chars = line.chars.filter(({ index }) => !/\s/.test(node.data[index]));
|
|
45
|
+
const box = { left: Math.min(...chars.map(c => c.rect.left)), right: Math.max(...chars.map(c => c.rect.right)), top: line.top, bottom: line.bottom };
|
|
46
|
+
result.push({content,box});
|
|
47
|
+
}
|
|
48
|
+
return result;
|
|
49
|
+
};
|
|
50
|
+
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
|
51
|
+
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
|
52
|
+
const owner=node.parentElement;
|
|
53
|
+
if (!node.textContent.trim() || !owner || owner.closest('input,textarea') || !visible(owner)) continue;
|
|
54
|
+
for (const {content,box} of linesFor(node)) push(content,box,owner);
|
|
55
|
+
}
|
|
56
|
+
const canvas = document.createElement('canvas').getContext('2d');
|
|
57
|
+
const fields='input:not([type]), input[type=text], input[type=search], input[type=email], input[type=url], input[type=tel], input[type=number], textarea';
|
|
58
|
+
for (const input of [...(root.matches(fields) ? [root] : []), ...root.querySelectorAll(fields)]) {
|
|
59
|
+
if (!visible(input)) continue;
|
|
60
|
+
const raw = input.value || input.placeholder || '';
|
|
61
|
+
const content = raw.replace(/\s+/g, ' ').trim();
|
|
62
|
+
if (!content) continue;
|
|
63
|
+
const rect = input.getBoundingClientRect(), style = getComputedStyle(input, input.value ? null : '::placeholder');
|
|
64
|
+
if (rect.width < 1) continue;
|
|
65
|
+
if (input.tagName === 'TEXTAREA') {
|
|
66
|
+
const box=getComputedStyle(input), mirror=document.createElement('div');
|
|
67
|
+
Object.assign(mirror.style,{position:'fixed',visibility:'hidden',left:(rect.left+parseFloat(box.borderLeftWidth)+parseFloat(box.paddingLeft)-input.scrollLeft)+'px',top:(rect.top+parseFloat(box.borderTopWidth)+parseFloat(box.paddingTop)-input.scrollTop)+'px',width:(input.clientWidth-parseFloat(box.paddingLeft)-parseFloat(box.paddingRight))+'px',fontFamily:style.fontFamily,fontSize:style.fontSize,fontWeight:style.fontWeight,lineHeight:style.lineHeight,letterSpacing:style.letterSpacing,whiteSpace:input.wrap==='off'?'pre':'pre-wrap',overflowWrap:'break-word'});
|
|
68
|
+
mirror.textContent=raw;document.body.append(mirror);
|
|
69
|
+
for (const {content,box} of linesFor(mirror.firstChild)) push(content,box,input,style);
|
|
70
|
+
mirror.remove();continue;
|
|
71
|
+
}
|
|
72
|
+
canvas.font = `${style.fontWeight} ${style.fontSize} ${style.fontFamily}`;
|
|
73
|
+
const box = getComputedStyle(input), height = parseFloat(style.fontSize) * 1.2;
|
|
74
|
+
const left = rect.left + parseFloat(box.borderLeftWidth) + parseFloat(box.paddingLeft);
|
|
75
|
+
const top = input.tagName === 'TEXTAREA' ? rect.top + parseFloat(box.borderTopWidth) + parseFloat(box.paddingTop) : rect.top + rect.height / 2 - height / 2;
|
|
76
|
+
push(content, { left, right: left + canvas.measureText(content).width, top, bottom: top + height }, input, style);
|
|
77
|
+
}
|
|
78
|
+
const merged = [];
|
|
79
|
+
for (const item of texts.sort((a,b) => a.y - b.y || a.x - b.x)) {
|
|
80
|
+
const previous = merged.findLast(p => Math.abs(p.y + p.height/2 - item.y - item.height/2) < 1 && item.x >= p.x + p.width - .5 && item.x - p.x - p.width < Math.max(p.space, item.space) - .1);
|
|
81
|
+
if (previous) { const gap = item.x - previous.x - previous.width; previous.text += (gap > .5 ? ' ' : '') + item.text; previous.width = item.x + item.width - previous.x; }
|
|
82
|
+
else merged.push({...item});
|
|
83
|
+
}
|
|
84
|
+
return { box: { x: origin.left + scrollX, y: origin.top + scrollY, width: origin.right - origin.left, height: origin.bottom - origin.top }, texts: merged };
|
|
85
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync, readdirSync, renameSync, rmSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { CONFIG_NAMES, LEGACY_CONFIG_NAMES, loadConfig } from './config.mjs';
|
|
4
|
+
import { refreshTypes, relative } from './project.mjs';
|
|
5
|
+
import { CliError, classifyError } from '../cli-output.mjs';
|
|
6
|
+
|
|
7
|
+
function files(directory) {
|
|
8
|
+
if (!existsSync(directory)) return [];
|
|
9
|
+
return readdirSync(directory, { withFileTypes: true }).flatMap(entry => {
|
|
10
|
+
if (['.git', 'node_modules', '.sdg', '.adg'].includes(entry.name)) return [];
|
|
11
|
+
const file = path.join(directory, entry.name);
|
|
12
|
+
return entry.isDirectory() ? files(file) : entry.isFile() ? [file] : [];
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// Keep source formatting, comments and ordinary string literals intact. Tokenize
|
|
17
|
+
// strings/comments first so text containing an import is never treated as code.
|
|
18
|
+
export function rewriteImports(source) {
|
|
19
|
+
const tokens = /\/\/[^\n]*|\/\*[\s\S]*?\*\/|"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|`(?:\\[\s\S]|[^`\\])*`|[\w$]+|[^\s]/g;
|
|
20
|
+
let previous = [], result = '', end = 0;
|
|
21
|
+
for (const match of source.matchAll(tokens)) {
|
|
22
|
+
const value = match[0];
|
|
23
|
+
if (value.startsWith('//') || value.startsWith('/*')) continue;
|
|
24
|
+
if (/^["']/.test(value) && (['from', 'import'].includes(previous.at(-1)) ||
|
|
25
|
+
(previous.at(-1) === '(' && previous.at(-2) === 'import'))) {
|
|
26
|
+
const replacement = value.replace(/^(["'])sdg(?=["'/:])/, '$1adg');
|
|
27
|
+
if (replacement !== value) {
|
|
28
|
+
result += source.slice(end, match.index) + replacement;
|
|
29
|
+
end = match.index + value.length;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
previous.push(value);
|
|
33
|
+
if (previous.length > 2) previous.shift();
|
|
34
|
+
}
|
|
35
|
+
return result + source.slice(end);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function migrate(project = process.cwd(), log = console.log) {
|
|
39
|
+
const root = path.resolve(project);
|
|
40
|
+
const oldConfigs = LEGACY_CONFIG_NAMES.filter(name => existsSync(path.join(root, name)));
|
|
41
|
+
const newConfigs = CONFIG_NAMES.filter(name => existsSync(path.join(root, name)));
|
|
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}`);
|
|
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 });
|
|
84
|
+
}
|
|
85
|
+
}
|