@whzxc/agent-design-gallery 0.0.0-stage → 0.6.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 +216 -2
- package/package.json +43 -4
- package/public/access.css +10 -0
- package/public/app.js +1646 -0
- package/public/assets.js +344 -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 +103 -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.mjs +105 -0
- package/src/http.mjs +37 -0
- package/src/hub/auth.mjs +40 -0
- package/src/hub/instances.mjs +99 -0
- package/src/hub/proxy.mjs +28 -0
- package/src/hub/registry.mjs +147 -0
- package/src/hub.mjs +113 -0
- package/src/link.mjs +54 -0
- package/src/open.mjs +57 -0
- package/src/server.mjs +642 -0
- package/src/service.mjs +163 -0
- package/src/toolkit/arch-browser.mjs +40 -0
- package/src/toolkit/arch-git.mjs +54 -0
- package/src/toolkit/arch-overlay.mjs +225 -0
- package/src/toolkit/arch.mjs +217 -0
- package/src/toolkit/asset-rules.mjs +14 -0
- package/src/toolkit/browser.mjs +21 -0
- package/src/toolkit/build-store.mjs +258 -0
- package/src/toolkit/build-worker.mjs +32 -0
- package/src/toolkit/build.mjs +133 -0
- package/src/toolkit/commands.mjs +273 -0
- package/src/toolkit/compare.mjs +175 -0
- package/src/toolkit/config.mjs +135 -0
- package/src/toolkit/document.mjs +85 -0
- package/src/toolkit/migrate.mjs +73 -0
- package/src/toolkit/project.mjs +160 -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 +36 -0
- package/src/viewer-cache.mjs +85 -0
package/src/service.mjs
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { readFile, writeFile, mkdir, rm, realpath, rename, readdir, lstat } from 'node:fs/promises';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { promisify } from 'node:util';
|
|
7
|
+
import { defaultStateDirectory } from './hub/registry.mjs';
|
|
8
|
+
|
|
9
|
+
export const SERVICE_LABEL = 'org.agent-design-gallery.hub';
|
|
10
|
+
const execute = promisify(execFile);
|
|
11
|
+
const xml = value => String(value).replace(/[&<>"']/g, character => ({
|
|
12
|
+
'&': '&', '<': '<', '>': '>', '"': '"', "'": ''',
|
|
13
|
+
})[character]);
|
|
14
|
+
const unxml = value => value.replace(/&(amp|lt|gt|quot|apos);/g, (_, entity) => ({
|
|
15
|
+
amp: '&', lt: '<', gt: '>', quot: '"', apos: "'",
|
|
16
|
+
})[entity]);
|
|
17
|
+
|
|
18
|
+
export function renderLaunchAgent({ nodePath, cliPath, stateDirectory, port = 4310 }) {
|
|
19
|
+
const args = [nodePath, cliPath, 'serve', '--port', String(port), '--state-dir', stateDirectory];
|
|
20
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
21
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
22
|
+
<plist version="1.0"><dict>
|
|
23
|
+
<key>Label</key><string>${SERVICE_LABEL}</string>
|
|
24
|
+
<key>ProgramArguments</key><array>${args.map(arg => `<string>${xml(arg)}</string>`).join('')}</array>
|
|
25
|
+
<key>RunAtLoad</key><true/>
|
|
26
|
+
<key>KeepAlive</key><true/>
|
|
27
|
+
<key>StandardOutPath</key><string>${xml(path.join(stateDirectory, 'service.stdout.log'))}</string>
|
|
28
|
+
<key>StandardErrorPath</key><string>${xml(path.join(stateDirectory, 'service.stderr.log'))}</string>
|
|
29
|
+
</dict></plist>
|
|
30
|
+
`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function launchArguments(plist) {
|
|
34
|
+
const array = plist?.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/)?.[1] ?? '';
|
|
35
|
+
return [...array.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(match => unxml(match[1]));
|
|
36
|
+
}
|
|
37
|
+
const readOptional = async file => {
|
|
38
|
+
try { return await readFile(file, 'utf8'); }
|
|
39
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; return null; }
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
async function migrateService(values, { home, run, nodePath, cliPath, uid, output }) {
|
|
43
|
+
const oldLabel = 'org.svg-design-gallery.hub';
|
|
44
|
+
const agents = path.join(home, 'Library', 'LaunchAgents');
|
|
45
|
+
const oldAgent = path.join(agents, `${oldLabel}.plist`);
|
|
46
|
+
const newAgent = path.join(agents, `${SERVICE_LABEL}.plist`);
|
|
47
|
+
const installed = await readOptional(oldAgent), args = launchArguments(installed);
|
|
48
|
+
const argument = flag => args.includes(flag) ? args[args.indexOf(flag) + 1] : undefined;
|
|
49
|
+
const base = process.env.XDG_STATE_HOME || path.join(home, '.local/state');
|
|
50
|
+
const oldState = path.resolve(argument('--state-dir') ?? path.join(base, 'svg-design-gallery'));
|
|
51
|
+
const newState = path.resolve(values['state-dir'] ?? path.join(base, 'agent-design-gallery'));
|
|
52
|
+
const exists = async file => (await lstat(file).catch(error => { if (error.code !== 'ENOENT') throw error; return null; })) !== null;
|
|
53
|
+
if (await exists(newState)) throw Error(`Migration target already exists: ${newState}; move it aside before running adg service migrate.`);
|
|
54
|
+
if (await exists(newAgent)) throw Error(`LaunchAgent already exists: ${newAgent}; inspect it before running adg service migrate.`);
|
|
55
|
+
if (!(await lstat(oldState)).isDirectory()) throw Error(`Hub state is not a directory: ${oldState}`);
|
|
56
|
+
const executable = await realpath(nodePath), entry = await realpath(cliPath);
|
|
57
|
+
const port = Number(argument('--port') ?? 4310);
|
|
58
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw Error('Invalid port in the old LaunchAgent; correct it before migration.');
|
|
59
|
+
const oldKey = await readOptional(path.join(oldState, 'hub.key'));
|
|
60
|
+
if (oldKey !== null && !/^(?:sdg|adg)_[a-f0-9]{64}$/.test(oldKey.trim())) throw Error('Invalid hub key file; correct it before migration.');
|
|
61
|
+
const domain = `gui/${uid}`, oldTarget = `${domain}/${oldLabel}`;
|
|
62
|
+
let loaded = false;
|
|
63
|
+
try { await run('/bin/launchctl', ['print', oldTarget]); loaded = true; }
|
|
64
|
+
catch (error) { if (![3, 113].includes(error.code)) throw error; }
|
|
65
|
+
if (loaded) {
|
|
66
|
+
await run('/bin/launchctl', ['bootout', oldTarget]);
|
|
67
|
+
output(`Stopped ${oldLabel}`);
|
|
68
|
+
}
|
|
69
|
+
await mkdir(path.dirname(newState), { recursive: true });
|
|
70
|
+
await rename(oldState, newState);
|
|
71
|
+
output(`Moved ${oldState} -> ${newState}`);
|
|
72
|
+
if (oldKey?.trim().startsWith('sdg_')) {
|
|
73
|
+
await writeFile(path.join(newState, 'hub.key'), oldKey.replace('sdg_', 'adg_'), { mode: 0o600 });
|
|
74
|
+
output('Updated hub key prefix; use adg serve --print-key when updating browser access.');
|
|
75
|
+
}
|
|
76
|
+
await mkdir(agents, { recursive: true });
|
|
77
|
+
await writeFile(newAgent, renderLaunchAgent({ nodePath: executable, cliPath: entry, stateDirectory: newState, port }));
|
|
78
|
+
if (installed !== null) {
|
|
79
|
+
await rm(oldAgent);
|
|
80
|
+
output(`Removed ${oldAgent}`);
|
|
81
|
+
}
|
|
82
|
+
output(`Created ${newAgent}`);
|
|
83
|
+
await run('/bin/launchctl', ['bootstrap', domain, newAgent]);
|
|
84
|
+
output(`Started ${SERVICE_LABEL}`);
|
|
85
|
+
output(`Other LaunchAgents referencing ${oldState}:`);
|
|
86
|
+
let count = 0;
|
|
87
|
+
for (const name of (await readdir(agents)).sort()) {
|
|
88
|
+
if (!name.endsWith('.plist') || name === `${SERVICE_LABEL}.plist`) continue;
|
|
89
|
+
const file = path.join(agents, name), content = await readFile(file, 'utf8');
|
|
90
|
+
if (unxml(content).includes(oldState)) { output(file); count++; }
|
|
91
|
+
}
|
|
92
|
+
if (!count) output('None.');
|
|
93
|
+
return 0;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Overrides keep launchctl and the user's LaunchAgents directory out of contract checks.
|
|
97
|
+
export async function service(action, values = {}, {
|
|
98
|
+
platform = process.platform, home = homedir(), run = execute,
|
|
99
|
+
nodePath = process.execPath, cliPath = fileURLToPath(new URL('./cli.mjs', import.meta.url)),
|
|
100
|
+
uid = process.getuid?.(), output = console.log,
|
|
101
|
+
} = {}) {
|
|
102
|
+
if (platform !== 'darwin') throw new Error('adg service is supported only on macOS (LaunchAgent).');
|
|
103
|
+
if (!['install', 'uninstall', 'status', 'logs', 'migrate'].includes(action)) {
|
|
104
|
+
throw new Error('Expected adg service install|uninstall|status|logs|migrate; run adg service --help.');
|
|
105
|
+
}
|
|
106
|
+
if (action === 'migrate') return migrateService(values, { home, run, nodePath, cliPath, uid, output });
|
|
107
|
+
const agentFile = path.join(home, 'Library', 'LaunchAgents', `${SERVICE_LABEL}.plist`);
|
|
108
|
+
let installedPlist = null;
|
|
109
|
+
try { installedPlist = await readFile(agentFile, 'utf8'); }
|
|
110
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
111
|
+
const installedArgs = launchArguments(installedPlist);
|
|
112
|
+
const stateFlag = installedArgs.indexOf('--state-dir');
|
|
113
|
+
const installedStateDirectory = stateFlag >= 0 ? installedArgs[stateFlag + 1] : undefined;
|
|
114
|
+
const stateDirectory = path.resolve(values['state-dir'] ?? (action === 'install' ? undefined : installedStateDirectory) ?? defaultStateDirectory);
|
|
115
|
+
const domain = `gui/${uid}`, target = `${domain}/${SERVICE_LABEL}`;
|
|
116
|
+
const stdout = path.join(stateDirectory, 'service.stdout.log');
|
|
117
|
+
const stderr = path.join(stateDirectory, 'service.stderr.log');
|
|
118
|
+
const loaded = async () => {
|
|
119
|
+
try { return (await run('/bin/launchctl', ['print', target])).stdout; }
|
|
120
|
+
catch (error) {
|
|
121
|
+
if ([3, 113].includes(error.code)) return null;
|
|
122
|
+
throw new Error(`Cannot inspect ${SERVICE_LABEL}: ${error.stderr?.trim() || error.message}`);
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
if (action === 'logs') {
|
|
126
|
+
for (const file of [stdout, stderr]) {
|
|
127
|
+
let content;
|
|
128
|
+
try { content = await readFile(file, 'utf8'); }
|
|
129
|
+
catch (error) { if (error.code === 'ENOENT') continue; throw error; }
|
|
130
|
+
output(`${file}\n${content.trimEnd().split('\n').slice(-200).join('\n')}`);
|
|
131
|
+
}
|
|
132
|
+
return 0;
|
|
133
|
+
}
|
|
134
|
+
if (action === 'status') {
|
|
135
|
+
const status = await loaded();
|
|
136
|
+
output(JSON.stringify({ label: SERVICE_LABEL, installed: installedPlist !== null, loaded: status !== null,
|
|
137
|
+
state: status?.match(/^\s*state = (.+)$/m)?.[1] ?? null,
|
|
138
|
+
pid: Number(status?.match(/^\s*pid = (\d+)$/m)?.[1]) || null,
|
|
139
|
+
plist: agentFile, stateDirectory, logs: { stdout, stderr } }, null, 2));
|
|
140
|
+
return 0;
|
|
141
|
+
}
|
|
142
|
+
if (action === 'uninstall') {
|
|
143
|
+
if (await loaded() !== null) await run('/bin/launchctl', ['bootout', target]);
|
|
144
|
+
await rm(agentFile, { force: true });
|
|
145
|
+
output(`Uninstalled ${SERVICE_LABEL}. State and logs retained in ${stateDirectory}.`);
|
|
146
|
+
return 0;
|
|
147
|
+
}
|
|
148
|
+
const port = values.port === undefined ? 4310 : Number(values.port);
|
|
149
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('--port must be an integer from 1 to 65535.');
|
|
150
|
+
if (installedPlist !== null) throw new Error(`${SERVICE_LABEL} is already installed; run adg service uninstall before reinstalling.`);
|
|
151
|
+
const executable = await realpath(nodePath), entry = await realpath(cliPath);
|
|
152
|
+
await mkdir(path.dirname(agentFile), { recursive: true });
|
|
153
|
+
await mkdir(stateDirectory, { recursive: true });
|
|
154
|
+
await Promise.all([stdout, stderr].map(file => writeFile(file, '', { flag: 'a' })));
|
|
155
|
+
await writeFile(agentFile, renderLaunchAgent({ nodePath: executable, cliPath: entry, stateDirectory, port }));
|
|
156
|
+
try { await run('/bin/launchctl', ['bootstrap', domain, agentFile]); }
|
|
157
|
+
catch (error) {
|
|
158
|
+
await rm(agentFile, { force: true });
|
|
159
|
+
throw new Error(`Cannot install ${SERVICE_LABEL}: ${error.stderr?.trim() || error.message}`);
|
|
160
|
+
}
|
|
161
|
+
output(`Installed ${SERVICE_LABEL}. Logs: ${stdout} and ${stderr}.`);
|
|
162
|
+
return 0;
|
|
163
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { launch } from './browser.mjs';
|
|
2
|
+
|
|
3
|
+
// A worker owns one lazy measurement browser. Each lease closes its pages itself;
|
|
4
|
+
// only the idle timer or worker shutdown closes the shared browser process.
|
|
5
|
+
export function createArchBrowser({launchBrowser = launch, idleMs = 30000} = {}) {
|
|
6
|
+
let pending, timer, active = 0, closed = false, disposing = Promise.resolve();
|
|
7
|
+
function dispose() {
|
|
8
|
+
const current = pending; pending = null;
|
|
9
|
+
if (current) disposing = disposing.then(async () => {
|
|
10
|
+
const browser = await current.catch(() => null);
|
|
11
|
+
await browser?.close();
|
|
12
|
+
});
|
|
13
|
+
return disposing;
|
|
14
|
+
}
|
|
15
|
+
return {
|
|
16
|
+
async run(build) {
|
|
17
|
+
if (closed) throw Error('Architecture browser is closed');
|
|
18
|
+
clearTimeout(timer); active++;
|
|
19
|
+
try {
|
|
20
|
+
await disposing;
|
|
21
|
+
if (closed) throw Error('Architecture browser is closed');
|
|
22
|
+
if (!pending) {
|
|
23
|
+
const attempt = Promise.resolve().then(launchBrowser);
|
|
24
|
+
pending = attempt;
|
|
25
|
+
attempt.then(browser => browser.on('disconnected', () => {
|
|
26
|
+
if (pending === attempt) pending = null;
|
|
27
|
+
}), () => { if (pending === attempt) pending = null; });
|
|
28
|
+
}
|
|
29
|
+
return await build(await pending);
|
|
30
|
+
} finally {
|
|
31
|
+
active--;
|
|
32
|
+
if (!closed && !active) {
|
|
33
|
+
timer = setTimeout(() => { dispose().catch(() => {}); }, idleMs);
|
|
34
|
+
timer.unref();
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
close() { closed = true; clearTimeout(timer); return dispose(); },
|
|
39
|
+
};
|
|
40
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { promisify } from 'node:util';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { realpath } from 'node:fs/promises';
|
|
5
|
+
const exec = promisify(execFile);
|
|
6
|
+
async function physicalPath(file) {
|
|
7
|
+
try { return await realpath(file); }
|
|
8
|
+
catch(error) {
|
|
9
|
+
if(error.code!=='ENOENT')throw error;
|
|
10
|
+
// Deleted sources still resolve through their closest existing ancestor.
|
|
11
|
+
return path.join(await physicalPath(path.dirname(file)),path.basename(file));
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
async function git(root, args) {
|
|
15
|
+
try { return (await exec('git',['-C',root,...args],{maxBuffer:16*1024*1024})).stdout; }
|
|
16
|
+
catch(error) {
|
|
17
|
+
if(error.code==='ENOENT')throw Error('Git is unavailable; install Git and retry --base.');
|
|
18
|
+
throw error;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export async function resolveBase(config, rev) {
|
|
22
|
+
if(typeof rev!=='string'||!rev.trim())throw Error('Set --base to a Git revision, for example HEAD.');
|
|
23
|
+
let root;
|
|
24
|
+
try { root=await realpath((await git(config.root,['rev-parse','--show-toplevel'])).trim()); }
|
|
25
|
+
catch(error) {
|
|
26
|
+
if(error.message.startsWith('Git is unavailable'))throw error;
|
|
27
|
+
throw Error('This project is not in a Git repository; run from a repository or initialize one before using --base.');
|
|
28
|
+
}
|
|
29
|
+
try {
|
|
30
|
+
const sha=(await git(root,['rev-parse','--verify','--end-of-options',`${rev}^{commit}`])).trim();
|
|
31
|
+
return {root,rev,sha};
|
|
32
|
+
} catch(error) {
|
|
33
|
+
if(error.message.startsWith('Git is unavailable'))throw error;
|
|
34
|
+
throw Error(`Unknown Git revision ${rev}; choose an existing commit or fetch the revision and retry --base.`);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
export async function readBase(base, file) {
|
|
38
|
+
const name=path.relative(base.root,await physicalPath(file)).split(path.sep).join('/');
|
|
39
|
+
const entry=await git(base.root,['ls-tree','-z',base.sha,'--',name]);
|
|
40
|
+
if(!entry)return {text:null,blob:null};
|
|
41
|
+
const blob=/^100(?:644|755) blob ([a-f0-9]+)\t/.exec(entry)?.[1];
|
|
42
|
+
if(!blob)return {text:null,blob:null};
|
|
43
|
+
return {blob,text:await git(base.root,['show',`${base.sha}:${name}`])};
|
|
44
|
+
}
|
|
45
|
+
export async function baseArchFiles(config,base) {
|
|
46
|
+
if(!config.archDirectory)return [];
|
|
47
|
+
const directory=await physicalPath(config.archDirectory);
|
|
48
|
+
const prefix=path.relative(base.root,directory).split(path.sep).join('/');
|
|
49
|
+
return (await git(base.root,['ls-tree','-r','-z',base.sha,'--',prefix])).split('\0')
|
|
50
|
+
.flatMap(entry=>/^100(?:644|755) blob [a-f0-9]+\t(.+\.mmd)$/.exec(entry)?.slice(1)??[])
|
|
51
|
+
.map(name=>path.relative(directory,path.join(base.root,name)))
|
|
52
|
+
.filter(name=>!name.split(path.sep).some(part=>part.startsWith('.')))
|
|
53
|
+
.map(name=>path.join(config.archDirectory,name));
|
|
54
|
+
}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { parse } from 'pele';
|
|
2
|
+
import { buildArch, inspectArch, vocabulary } from './arch.mjs';
|
|
3
|
+
import { readFileSync } from 'node:fs';
|
|
4
|
+
import { readBase } from './arch-git.mjs';
|
|
5
|
+
import { escape } from './runtime.mjs';
|
|
6
|
+
|
|
7
|
+
export const diffClasses=['added','changed','removed'];
|
|
8
|
+
const words=value=>(Array.isArray(value)?value.join(' '):value??'').split(/[\s,]+/).filter(Boolean);
|
|
9
|
+
const addClass=(object,key,name)=>{object[key]=Array.isArray(object[key])?[...words(object[key]),name]:[...words(object[key]),name].join(' ');};
|
|
10
|
+
const same=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
|
|
11
|
+
const labelDetail=text=>text?.trim()?`: ${text}`:'';
|
|
12
|
+
const diffLabel=(name,text)=>name!=='changed'&&text?.trim()?`${name==='added'?'+':'-'} ${text}`:text;
|
|
13
|
+
function changeDetail(oldLabel,label,oldParent,parent,oldShape,shape) {
|
|
14
|
+
const changes=[];
|
|
15
|
+
if(oldLabel!==label)changes.push(`${oldLabel} -> ${label}`);
|
|
16
|
+
if(oldParent!==parent)changes.push(`parent ${oldParent??'root'} -> ${parent??'root'}`);
|
|
17
|
+
if(oldShape!==shape)changes.push(`shape ${oldShape} -> ${shape}`);
|
|
18
|
+
return changes.join('; ')||'structure changed';
|
|
19
|
+
}
|
|
20
|
+
const identityEdges=edges=>{
|
|
21
|
+
const counts=new Map();
|
|
22
|
+
return new Map(edges.map(edge=>{
|
|
23
|
+
const pair=JSON.stringify([edge.start,edge.end]),index=counts.get(pair)??0;counts.set(pair,index+1);
|
|
24
|
+
return [JSON.stringify([edge.start,edge.end,index]),edge];
|
|
25
|
+
}));
|
|
26
|
+
};
|
|
27
|
+
function compareNodes(current,base,describe,kind,result,insert) {
|
|
28
|
+
for(const [id,node] of current) {
|
|
29
|
+
const old=base.get(id),name=!old?'added':same(describe(node),describe(old))?null:'changed';
|
|
30
|
+
if(name) {
|
|
31
|
+
result.nodes.set(id,name);
|
|
32
|
+
result.changes.push(`${name==='added'?'+':'~'} ${kind} ${id}${name==='changed'?`: ${changeDetail(describe(old)[0],describe(node)[0],undefined,undefined,describe(old)[1],describe(node)[1])}`:''}`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
for(const [id,node] of base)if(!current.has(id)) {
|
|
36
|
+
insert(id,structuredClone(node));result.nodes.set(id,'removed');result.changes.push(`- ${kind} ${id}`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function compareEdges(current,base,kind,result) {
|
|
40
|
+
const oldEdges=identityEdges(base),newEdges=identityEdges(current);
|
|
41
|
+
for(const [key,edge] of newEdges) {
|
|
42
|
+
const old=oldEdges.get(key),name=!old?'added':!same([old.text,old.type,old.stroke,old.parent],[edge.text,edge.type,edge.stroke,edge.parent])?'changed':null;
|
|
43
|
+
if(name) {
|
|
44
|
+
edge.diff=name;
|
|
45
|
+
const detail=name==='changed'?changeDetail(old.text,edge.text,old.parent,edge.parent,`${old.type??''}/${old.stroke??''}`,`${edge.type??''}/${edge.stroke??''}`):edge.text;
|
|
46
|
+
result.changes.push(`${name==='added'?'+':'~'} ${kind} ${edge.start} -> ${edge.end}${labelDetail(detail)}`);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
for(const [key,edge] of oldEdges)if(!newEdges.has(key)) {
|
|
50
|
+
const ghost=structuredClone(edge);ghost.diff='removed';current.push(ghost);
|
|
51
|
+
result.changes.push(`- ${kind} ${edge.start} -> ${edge.end}${labelDetail(edge.text)}`);
|
|
52
|
+
}
|
|
53
|
+
return current;
|
|
54
|
+
}
|
|
55
|
+
function flowchart(model,base,result) {
|
|
56
|
+
const groups=new Map(model.subgraphs.map(g=>[g.id,g])),oldGroups=new Map((base?.subgraphs??[]).map(g=>[g.id,g]));
|
|
57
|
+
const parents=groups=>new Map([...groups].flatMap(([id,g])=>g.nodes.map(child=>[child,id])));
|
|
58
|
+
const parent=parents(groups),oldParent=parents(oldGroups),currentGroups=new Set(groups.keys());
|
|
59
|
+
// A subgraph referenced by an edge also has a placeholder in nodes. It is one
|
|
60
|
+
// element, including when a proposal changes that ID from a group to a node.
|
|
61
|
+
const elements=(nodes,groups)=>new Map([
|
|
62
|
+
...[...nodes].filter(([id])=>!groups.has(id)).map(([id,value])=>[id,{kind:'node',value}]),
|
|
63
|
+
...[...groups].map(([id,value])=>[id,{kind:'subgraph',value}]),
|
|
64
|
+
]);
|
|
65
|
+
const current=elements(model.nodes,groups),old=elements(base?.nodes??new Map(),oldGroups);
|
|
66
|
+
const describe=(element,parent)=>[element.kind==='subgraph'?element.value.title:element.value.text??element.value.id,
|
|
67
|
+
element.kind==='subgraph'?'group':element.value.type??'square',parent];
|
|
68
|
+
for(const [id,element] of current) {
|
|
69
|
+
const previous=old.get(id),name=!previous?'added':same(describe(element,parent.get(id)),describe(previous,oldParent.get(id)))?null:'changed';
|
|
70
|
+
if(name){result.nodes.set(id,name);result.changes.push(`${name==='added'?'+':'~'} ${element.kind} ${id}${previous?`: ${changeDetail(describe(previous)[0],describe(element)[0],oldParent.get(id),parent.get(id),describe(previous)[1],describe(element)[1])}`:''}`);}
|
|
71
|
+
}
|
|
72
|
+
for(const [id,element] of old)if(!current.has(id)) {
|
|
73
|
+
const ghost=structuredClone(element.value);
|
|
74
|
+
if(element.kind==='subgraph') {
|
|
75
|
+
ghost.nodes=[];groups.set(id,ghost);
|
|
76
|
+
if(base.nodes.has(id))model.nodes.set(id,structuredClone(base.nodes.get(id)));
|
|
77
|
+
} else model.nodes.set(id,ghost);
|
|
78
|
+
result.nodes.set(id,'removed');result.changes.push(`- ${element.kind} ${id}`);
|
|
79
|
+
if(currentGroups.has(oldParent.get(id)))parent.set(id,oldParent.get(id));
|
|
80
|
+
}
|
|
81
|
+
for(const g of groups.values())g.nodes=[];
|
|
82
|
+
for(const [child,id] of parent)if(groups.has(id))groups.get(id).nodes.push(child);
|
|
83
|
+
model.subgraphs=[...groups.values()];model.subgraphLookup=groups;model.members=new Set([...parent.keys()]);
|
|
84
|
+
for(const [id,name] of result.nodes)addClass(groups.get(id)??model.nodes.get(id),'classes',name);
|
|
85
|
+
const toEdge=e=>({...e,text:e.text??''});
|
|
86
|
+
model.edges=compareEdges(model.edges.map(toEdge),(base?.edges??[]).map(toEdge),'edge',result);
|
|
87
|
+
const used=new Set();
|
|
88
|
+
for(const [i,edge] of model.edges.entries()) {
|
|
89
|
+
if(!edge.id||used.has(edge.id))edge.id=`adg-overlay-edge${i}`;
|
|
90
|
+
used.add(edge.id);
|
|
91
|
+
if(edge.diff){if(edge.stroke==='invisible')edge.stroke='normal';addClass(edge,'classes',edge.diff);result.edges.set(edge.id,edge.diff);edge.text=diffLabel(edge.diff,edge.text);}
|
|
92
|
+
}
|
|
93
|
+
model.edgeById=new Map(model.edges.map(edge=>[edge.id,edge]));
|
|
94
|
+
}
|
|
95
|
+
function state(model,base,result) {
|
|
96
|
+
const originalNodes=new Map(model.graph.nodes.map(node=>[node.id,node])),oldNodes=new Map((base?.graph.nodes??[]).map(node=>[node.id,node]));
|
|
97
|
+
const currentIds=new Set(originalNodes.keys());
|
|
98
|
+
// Graph nodes include composite states, with their direct parent and label.
|
|
99
|
+
const label=node=>[node.label,...(node.description??[])].filter(Boolean).join(': ');
|
|
100
|
+
for(const [id,node] of originalNodes) {
|
|
101
|
+
const old=oldNodes.get(id),name=!old?'added':same([node.label,node.description,node.parentId,node.shape,node.isGroup],[old.label,old.description,old.parentId,old.shape,old.isGroup])?null:'changed';
|
|
102
|
+
if(name){result.nodes.set(id,name);result.changes.push(`${name==='added'?'+':'~'} state ${id}${old?`: ${changeDetail(label(old),label(node),old.parentId,node.parentId,old.shape,node.shape)}`:''}`);}
|
|
103
|
+
}
|
|
104
|
+
for(const [id,node] of oldNodes)if(!originalNodes.has(id)) {
|
|
105
|
+
const ghost=structuredClone(node);if(!currentIds.has(ghost.parentId))delete ghost.parentId;
|
|
106
|
+
model.graph.nodes.push(ghost);result.nodes.set(id,'removed');result.changes.push(`- state ${id}`);
|
|
107
|
+
}
|
|
108
|
+
for(const node of model.graph.nodes)if(result.nodes.has(node.id))addClass(node,'cssClasses',result.nodes.get(node.id));
|
|
109
|
+
const transitions=source=>{
|
|
110
|
+
const parents=[];
|
|
111
|
+
const visit=(doc,parent)=>{for(const stmt of doc??[]) {
|
|
112
|
+
if(stmt.stmt==='relation')parents.push(parent);
|
|
113
|
+
if(stmt.doc)visit(stmt.doc,stmt.id);
|
|
114
|
+
}};
|
|
115
|
+
visit(source?.rootDoc,undefined);
|
|
116
|
+
return (source?.graph.edges??[]).map((edge,index)=>({...edge,text:edge.label??'',parent:parents[index]}));
|
|
117
|
+
};
|
|
118
|
+
const edges=compareEdges(transitions(model),transitions(base),'transition',result);
|
|
119
|
+
model.graph.edges=edges.map((edge,i)=>{
|
|
120
|
+
edge.id=`edge${i}`;edge.label=edge.text;
|
|
121
|
+
if(edge.diff){addClass(edge,'classes',edge.diff);result.edges.set(edge.id,edge.diff);edge.label=diffLabel(edge.diff,edge.text);}
|
|
122
|
+
return edge;
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
function sequence(model,base,result) {
|
|
126
|
+
const oldActors=base?.actors??new Map();
|
|
127
|
+
compareNodes(model.actors,oldActors,a=>[a.description,a.type],'participant',result,(id,node)=>{
|
|
128
|
+
const box=node.box&&model.boxes.find(box=>box.name===node.box.name);
|
|
129
|
+
node.box=box;if(box)box.actorKeys.push(id);
|
|
130
|
+
model.actors.set(id,node);
|
|
131
|
+
});
|
|
132
|
+
// Rebuild neighbor links after appending ghost participants.
|
|
133
|
+
const actors=[...model.actors];actors.forEach(([,actor],i)=>{actor.prevActor=actors[i-1]?.[0];actor.nextActor=actors[i+1]?.[0];});
|
|
134
|
+
for(const [id,name] of result.nodes)addClass(model.actors.get(id),'classes',name);
|
|
135
|
+
const all=model.messages,isMessage=m=>m.from!==undefined&&m.to!==undefined&&typeof m.message==='string';
|
|
136
|
+
const current=all.filter(isMessage),old=(base?.messages??[]).filter(isMessage),key=m=>JSON.stringify([m.from,m.to,m.message]);
|
|
137
|
+
const rows=Array.from({length:old.length+1},()=>new Uint32Array(current.length+1));
|
|
138
|
+
for(let i=old.length-1;i>=0;i--)for(let j=current.length-1;j>=0;j--)rows[i][j]=key(old[i])===key(current[j])?1+rows[i+1][j+1]:Math.max(rows[i+1][j],rows[i][j+1]);
|
|
139
|
+
const aligned=[];let i=0,j=0;
|
|
140
|
+
while(i<old.length||j<current.length) {
|
|
141
|
+
if(i<old.length&&j<current.length&&key(old[i])===key(current[j])){aligned.push({...current[j++]});i++;}
|
|
142
|
+
else if(i<old.length&&j<current.length&&old[i].from===current[j].from&&old[i].to===current[j].to&&rows[i][j]===rows[i+1][j+1]) {aligned.push({...old[i++],diff:'removed'},{...current[j++],diff:'added'});}
|
|
143
|
+
else if(i<old.length&&(j===current.length||rows[i+1][j]>=rows[i][j+1]))aligned.push({...old[i++],diff:'removed'});
|
|
144
|
+
else aligned.push({...current[j++],diff:'added'});
|
|
145
|
+
}
|
|
146
|
+
const merged=[];
|
|
147
|
+
for(let n=0;n<aligned.length;n++) {
|
|
148
|
+
const a=aligned[n],b=aligned[n+1];
|
|
149
|
+
if(a.diff&&b?.diff&&a.diff!==b.diff&&a.from===b.from&&a.to===b.to) {
|
|
150
|
+
const next=a.diff==='added'?a:b,previous=a.diff==='removed'?a:b;
|
|
151
|
+
merged.push({...next,diff:'changed'});result.changes.push(`~ message ${a.from} -> ${a.to}: ${previous.message} -> ${next.message}`);n++;
|
|
152
|
+
} else {merged.push(a);if(a.diff)result.changes.push(`${a.diff==='added'?'+':'-'} message ${a.from} -> ${a.to}${labelDetail(a.message)}`);}
|
|
153
|
+
}
|
|
154
|
+
const withControls=[];let cursor=0;
|
|
155
|
+
for(const message of merged) {
|
|
156
|
+
if(message.diff!=='removed') {
|
|
157
|
+
while(cursor<all.length&&!isMessage(all[cursor]))withControls.push(all[cursor++]);
|
|
158
|
+
cursor++;
|
|
159
|
+
}
|
|
160
|
+
withControls.push(message);
|
|
161
|
+
}
|
|
162
|
+
withControls.push(...all.slice(cursor));
|
|
163
|
+
const positions=new Map();
|
|
164
|
+
model.messages=withControls.map((message,index)=>{
|
|
165
|
+
if(message.diff!=='removed')positions.set(message.id,index);
|
|
166
|
+
message.id=String(index);
|
|
167
|
+
if(message.diff){addClass(message,'classes',message.diff);result.edges.set(`i${index}`,message.diff);message.message=diffLabel(message.diff,message.message);}
|
|
168
|
+
return message;
|
|
169
|
+
});
|
|
170
|
+
for(const entries of [model.createdActors,model.destroyedActors])for(const [id,index] of entries)entries.set(id,positions.get(String(index))??index);
|
|
171
|
+
}
|
|
172
|
+
export function overlayModels(current,base=null) {
|
|
173
|
+
// Pele brands parse models internally. Consume the current model to keep that brand.
|
|
174
|
+
const result={model:current,nodes:new Map(),edges:new Map(),changes:[],classes:[]};
|
|
175
|
+
if(!['flowchart','state','sequence'].includes(current.type)||base&&base.type!==current.type) {
|
|
176
|
+
result.unsupported=`Proposal overlays are unsupported for ${base&&base.type!==current.type?'a change of diagram type':current.type}.`;return result;
|
|
177
|
+
}
|
|
178
|
+
({flowchart,state,sequence}[current.type])(result.model,base,result);
|
|
179
|
+
result.classes=diffClasses.filter(name=>[...result.nodes.values(),...result.edges.values()].includes(name));
|
|
180
|
+
return result;
|
|
181
|
+
}
|
|
182
|
+
const decode=value=>value.replace(/&(amp|quot|apos|lt|gt|#\d+|#x[\da-f]+);/gi,(_,s)=>s[0]==='#'?String.fromCodePoint(parseInt(s.slice(s[1]==='x'?2:1),s[1]==='x'?16:10)):({amp:'&',quot:'"',apos:"'",lt:'<',gt:'>'})[s]);
|
|
183
|
+
export function stampOverlay(svg,overlay) {
|
|
184
|
+
return svg.replace(/<g\b[^>]*>/g,tag=>{
|
|
185
|
+
const classes=/\bclass="([^"]*)"/.exec(tag),id=/\bdata-id="([^"]*)"/.exec(tag);
|
|
186
|
+
if(!classes||!id)return tag;
|
|
187
|
+
const name=/\bpele-(?:edge|edge-label)\b/.test(classes[1])?overlay.edges.get(decode(id[1])):
|
|
188
|
+
/\bpele-(?:node|cluster)\b/.test(classes[1])?overlay.nodes.get(decode(id[1])):null;
|
|
189
|
+
return name?tag.replace(classes[0],`class="${[...new Set([...words(classes[1]),name])].join(' ')}"`):tag;
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
export function overlayStyles() {
|
|
193
|
+
const shape=':is(rect,path,polygon,circle,ellipse)';
|
|
194
|
+
return `:root{--arch-added:var(--accent,#6a5ad0);--arch-changed:var(--accent,#6a5ad0);--arch-removed:var(--text-tertiary,#737373)}:root[data-theme="dark"]{--arch-added:var(--accent,#ab9fff);--arch-changed:var(--accent,#ab9fff);--arch-removed:var(--text-tertiary,#a3a3a3)}
|
|
195
|
+
${diffClasses.map(name=>`[data-adg-arch] .pele :is(.pele-node,.pele-cluster).${name}>${shape}{stroke:var(--arch-${name});stroke-width:2.5px;stroke-dasharray:${name==='changed'?'4 3':name==='removed'?'5 4':'none'}}
|
|
196
|
+
[data-adg-arch] .pele .pele-edge.${name},[data-adg-arch] .pele .pele-edge.${name}>:is(path,line,polyline){stroke:var(--arch-${name});stroke-width:2.25px;stroke-dasharray:${name==='changed'?'4 3':name==='removed'?'5 4':'none'}}
|
|
197
|
+
[data-adg-arch] .pele .pele-edge.${name} .pele-marker{fill:var(--arch-${name});stroke:var(--arch-${name});stroke-dasharray:none}
|
|
198
|
+
[data-adg-arch] .pele .pele-edge-label.${name}{fill:var(--arch-${name})}`).join('\n')}
|
|
199
|
+
[data-adg-arch] .pele :is(.pele-node,.pele-cluster,.pele-edge).removed{opacity:.5}
|
|
200
|
+
[data-adg-arch] .pele .pele-edge-label.removed text{opacity:.5}
|
|
201
|
+
.arch-key.changed .arch-swatch{border:2.5px dashed var(--arch-color);background:transparent}.arch-key.added .arch-swatch{border-width:2.5px;background:transparent}.arch-key.removed .arch-swatch{border:2px dashed var(--arch-color);background:transparent;opacity:.5}
|
|
202
|
+
.arch-comparison{margin-bottom:16px;color:var(--text-secondary,var(--text));font-size:12px}`;
|
|
203
|
+
}
|
|
204
|
+
export async function buildOverlay(config,file,{base,browser,snapshot}={}) {
|
|
205
|
+
snapshot??=new Map();
|
|
206
|
+
const old=await readBase(base,file),bytes=readFileSync(file);snapshot.set(file,bytes);
|
|
207
|
+
const text=bytes.toString('utf8');
|
|
208
|
+
const checked=inspectArch(text,Infinity);
|
|
209
|
+
if(checked.problems.length)throw Error(checked.problems.join('\n'));
|
|
210
|
+
const overlay=overlayModels(checked.model,old.text===null?null:parse(old.text));
|
|
211
|
+
const built=await buildArch(config,file,{model:overlay.model,browser,snapshot});
|
|
212
|
+
const frame=built.frames[0],used=new Set(checked.classes);
|
|
213
|
+
for(const match of frame.html.matchAll(/<g\b[^>]*\bclass="([^"]*)"/g))for(const name of words(match[1]))if(vocabulary.includes(name))used.add(name);
|
|
214
|
+
const names=[...vocabulary.filter(name=>used.has(name)),...overlay.classes];
|
|
215
|
+
const swatches=names.map(name=>`<span class="arch-key ${name}" style="--arch-color:var(--arch-${name})"><i class="arch-swatch"></i>${name}</span>`).join('');
|
|
216
|
+
let html=stampOverlay(frame.html,overlay);
|
|
217
|
+
if(swatches)html=html.includes('class="arch-legend"')?html.replace(/<div class="arch-legend">[\s\S]*?<\/div>/,()=>`<div class="arch-legend">${swatches}</div>`):html.replace('<section data-adg-arch>',()=>`<section data-adg-arch><div class="arch-legend">${swatches}</div>`);
|
|
218
|
+
html=html.replace(/(<section data-adg-arch>)([\s\S]*?)(<svg\b)/,(_,start,legend,svg)=>`${start}${legend}<div class="arch-comparison">Compared with ${base.sha.slice(0,7)} (${escape(base.rev)})</div>${svg}`);
|
|
219
|
+
const css=overlayStyles()+'\n'+built.css;
|
|
220
|
+
const plain=value=>decode(value.replace(/<br\s*\/?>/gi,' ').replace(/<\/?(?:b|i|em|strong|span|code)\b[^>]*>/gi,''));
|
|
221
|
+
const note=[frame.note,overlay.unsupported,...overlay.changes.map(plain)].filter(Boolean).join('\n');
|
|
222
|
+
const output={...frame,html,note};
|
|
223
|
+
output.document=theme=>`<!doctype html><html data-theme="${theme}"><head><meta charset="utf-8"><style>${css.replace(/<\/style/gi,'<\\/style')}</style></head><body><div data-adg-frame="default">${html}</div></body></html>`;
|
|
224
|
+
return {...built,frames:[output],css,baseBlob:old.blob};
|
|
225
|
+
}
|