@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.
Files changed (61) hide show
  1. package/LICENSE +69 -0
  2. package/README.md +218 -2
  3. package/package.json +43 -4
  4. package/public/access.css +10 -0
  5. package/public/app.js +1674 -0
  6. package/public/arrangement-worker.js +11 -0
  7. package/public/arrangement.js +49 -0
  8. package/public/assets.js +356 -0
  9. package/public/auth.js +69 -0
  10. package/public/favicon.svg +6 -0
  11. package/public/hub.css +67 -0
  12. package/public/hub.html +33 -0
  13. package/public/hub.js +165 -0
  14. package/public/icons.js +50 -0
  15. package/public/index.html +70 -0
  16. package/public/instance-actions.js +27 -0
  17. package/public/labels.js +122 -0
  18. package/public/layout.js +119 -0
  19. package/public/relationships.js +28 -0
  20. package/public/selection.js +20 -0
  21. package/public/style.css +194 -0
  22. package/public/switcher.css +37 -0
  23. package/public/switcher.js +176 -0
  24. package/public/token-catalog.js +129 -0
  25. package/public/tokens.css +61 -0
  26. package/public/view-route.js +66 -0
  27. package/src/cli-output.mjs +236 -0
  28. package/src/cli.mjs +176 -0
  29. package/src/http.mjs +38 -0
  30. package/src/hub/auth.mjs +41 -0
  31. package/src/hub/instances.mjs +99 -0
  32. package/src/hub/proxy.mjs +30 -0
  33. package/src/hub/registry.mjs +181 -0
  34. package/src/hub.mjs +128 -0
  35. package/src/lifecycle.mjs +109 -0
  36. package/src/link.mjs +55 -0
  37. package/src/open.mjs +61 -0
  38. package/src/perf.mjs +12 -0
  39. package/src/server.mjs +679 -0
  40. package/src/service.mjs +184 -0
  41. package/src/toolkit/arch-browser.mjs +40 -0
  42. package/src/toolkit/arch-git.mjs +55 -0
  43. package/src/toolkit/arch-overlay.mjs +225 -0
  44. package/src/toolkit/arch.mjs +221 -0
  45. package/src/toolkit/asset-rules.mjs +14 -0
  46. package/src/toolkit/browser.mjs +33 -0
  47. package/src/toolkit/build-store.mjs +266 -0
  48. package/src/toolkit/build-worker.mjs +35 -0
  49. package/src/toolkit/build.mjs +147 -0
  50. package/src/toolkit/commands.mjs +345 -0
  51. package/src/toolkit/compare.mjs +222 -0
  52. package/src/toolkit/config.mjs +136 -0
  53. package/src/toolkit/document.mjs +85 -0
  54. package/src/toolkit/migrate.mjs +85 -0
  55. package/src/toolkit/project.mjs +172 -0
  56. package/src/toolkit/results.mjs +44 -0
  57. package/src/toolkit/runtime.d.ts +14 -0
  58. package/src/toolkit/runtime.mjs +54 -0
  59. package/src/toolkit/text.mjs +12 -0
  60. package/src/toolkit/tokens.mjs +37 -0
  61. package/src/viewer-cache.mjs +85 -0
@@ -0,0 +1,66 @@
1
+ const locatorKeys = ['scope', 'group', 'asset', 'frame', 'element'];
2
+
3
+ export function viewerBase(pathname) {
4
+ return pathname.match(/^\/(?:p|i)\/[A-Za-z0-9_-]+\//)?.[0] ?? '/';
5
+ }
6
+
7
+ export function isViewPath(pathname) {
8
+ return pathname.startsWith('/view/');
9
+ }
10
+
11
+ export function readViewRoute(url) {
12
+ const query = url.searchParams;
13
+ const base=query.has('base')?{base:query.get('base')}:{};
14
+ const path = url.pathname.slice(viewerBase(url.pathname).length);
15
+ const explicitScope = query.get('scope');
16
+ const asset = query.get('asset'), group = query.get('group');
17
+ if (explicitScope || asset || group) {
18
+ return {
19
+ ...base,
20
+ scope: explicitScope ?? (asset ? `asset:${asset}` : `group:${group}`),
21
+ target: asset || group ? { path: asset, group, form: query.get('frame'), element: query.has('element') ? { id: query.get('element') } : null } : null,
22
+ onlyFrame: asset && !explicitScope ? query.get('frame') : null,
23
+ isolated: true,
24
+ strict: !explicitScope,
25
+ };
26
+ }
27
+ if (path.startsWith('view/')) {
28
+ const match = /^view\/(?:all|layer\/([^/]+))(?:\/(group|asset)\/([^/]+)(?:\/frame\/([^/]+)(?:\/element\/([^/]+))?)?)?\/?$/.exec(path);
29
+ if (!match) throw Error('Invalid design path. Use a link generated by ADG.');
30
+ const [layer, kind, key, frame, element] = match.slice(1).map(value => value === undefined ? null : decodeURIComponent(value));
31
+ if (kind !== 'asset' && frame) throw Error('A frame needs an asset path.');
32
+ return {
33
+ ...base,
34
+ scope: layer ? `layer:${layer}` : 'all',
35
+ target: kind ? { path: kind === 'asset' ? key : null, group: kind === 'group' ? key : null, form: frame, element: element ? { id: element } : null } : null,
36
+ strict: true,
37
+ };
38
+ }
39
+ return { ...base, scope: 'default', target: null };
40
+ }
41
+
42
+ export function viewURL(base, scope, target = {}, { isolated = false, onlyFrame = null } = {}) {
43
+ const url = new URL(base);
44
+ url.pathname = viewerBase(url.pathname);
45
+ for (const key of locatorKeys) url.searchParams.delete(key);
46
+ const { path, group, form, element } = target;
47
+ if (onlyFrame) {
48
+ url.searchParams.set('asset', path);
49
+ url.searchParams.set('frame', onlyFrame);
50
+ if (element?.id != null) url.searchParams.set('element', element.id);
51
+ } else if (isolated || !['all', 'layer'].includes(scope.split(':', 1)[0])) {
52
+ url.searchParams.set('scope', scope);
53
+ if (path) url.searchParams.set('asset', path);
54
+ else if (group) url.searchParams.set('group', group);
55
+ if (path && form) url.searchParams.set('frame', form);
56
+ if (path && form && element?.id != null) url.searchParams.set('element', element.id);
57
+ } else {
58
+ const segments = ['view', ...(scope === 'all' ? ['all'] : ['layer', scope.slice('layer:'.length)])];
59
+ if (path) segments.push('asset', path);
60
+ else if (group) segments.push('group', group);
61
+ if (path && form) segments.push('frame', form);
62
+ if (path && form && element?.id != null) segments.push('element', element.id);
63
+ url.pathname += segments.map(encodeURIComponent).join('/');
64
+ }
65
+ return url;
66
+ }
@@ -0,0 +1,236 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { stripVTControlCharacters } from 'node:util';
3
+ import { AsyncLocalStorage } from 'node:async_hooks';
4
+
5
+ /** @typedef {{argv: string[], reason: string}} NextAction */
6
+ /** @typedef {{code: string, message: string, next: NextAction[]}} Diagnostic */
7
+ /** @typedef {keyof typeof errorCatalog} ErrorCode */
8
+ /** @typedef {{schemaVersion: 1, command: string, ok: boolean, data: unknown, warnings: Diagnostic[], error: Diagnostic | null}} Envelope */
9
+ /** @typedef {{command?: string, project?: string, stateDirectory?: string, gitCause?: 'repository' | 'revision' | 'read', positionals?: string[], values?: Record<string, string | string[] | boolean>, failureCode?: ErrorCode}} ErrorContext */
10
+ /** @typedef {{json: boolean, command: string, revealKey?: boolean, stdout?: (text: string) => void, stderr?: (text: string) => void}} OutputOptions */
11
+
12
+ // Recovery kinds keep the catalog declarative; actions are constructed from known operands.
13
+ /** @satisfies {Record<string, [number, string, string]>} */
14
+ export const errorCatalog = {
15
+ USAGE_INVALID: [2, 'help', 'Read command arguments.'],
16
+ CONFIG_INVALID: [2, 'check', 'Recheck after fixing configuration.'],
17
+ TOKENS_INVALID: [2, 'check', 'Recheck after repairing tokens.css.'],
18
+ MIGRATION_REQUIRED: [2, 'migrate', 'Migrate the legacy project.'],
19
+ MIGRATION_CONFLICT: [2, 'migration', 'Inspect migration inputs before resolving the conflict.'],
20
+ VERSION_UNSATISFIED: [2, 'install', 'Install a version satisfying project requires.'],
21
+ DIRECTORY_NOT_FOUND: [2, 'help', 'Choose an existing directory.'],
22
+ PROJECT_NOT_FOUND: [2, 'migrate-help', 'Select the project root.'],
23
+ SOURCE_NOT_FOUND: [2, 'check-help', 'Choose a discovered source inside the project.'],
24
+ FRAME_NOT_FOUND: [2, 'render-help', 'Choose a declared frame in the selected sources.'],
25
+ ROOT_NOT_REGISTERED: [2, 'roots', 'Read registered roots.'],
26
+ LEGACY_SOURCE: [2, 'check', 'Recheck after converting the SVG source to TSX.'],
27
+ SOURCE_BUILD_FAILED: [2, 'check', 'Read source diagnostics after repairing the source.'],
28
+ GIT_UNAVAILABLE: [2, 'git-version', 'Verify Git after installing it.'],
29
+ GIT_BASE_INVALID: [2, 'git', 'Inspect the project repository and base revision.'],
30
+ CHECK_FAILED: [1, 'check', 'Recheck after fixing findings.'],
31
+ COMPARE_FAILED: [1, 'compare', 'Compare again after reviewing the reports.'],
32
+ PLAYWRIGHT_UNAVAILABLE: [2, 'install', 'Restore the packaged browser dependency.'],
33
+ CHROMIUM_UNAVAILABLE: [2, 'chromium', 'Install Chromium matching ADG\'s Playwright.'],
34
+ BROWSER_FAILED: [2, 'chromium', 'Repair Chromium before retrying.'],
35
+ RENDER_FAILED: [2, 'check', 'Inspect frame execution diagnostics.'],
36
+ COMPARE_TARGET_NOT_FOUND: [2, 'compare', 'Retry after repairing the fixture target.'],
37
+ COMPARE_ADAPTER_FAILED: [2, 'compare', 'Retry after repairing the adapter callback.'],
38
+ COMPARE_UNSETTLED: [2, 'compare', 'Retry after stabilizing fixture readiness.'],
39
+ STATE_INVALID: [2, 'help', 'Inspect the reported state file before retrying.'],
40
+ HUB_KEY_INVALID: [2, 'rotate', 'Replace the invalid key; existing access will expire.'],
41
+ SERVICE_UNSUPPORTED: [2, 'serve-help', 'Use a foreground hub on this platform.'],
42
+ SERVICE_ALREADY_INSTALLED: [2, 'status', 'Inspect the existing installation.'],
43
+ SERVICE_FAILED: [2, 'logs', 'Inspect service diagnostics before retrying.'],
44
+ WATCH_FAILED: [2, 'check', 'Inspect project inputs before reopening the viewer.'],
45
+ SHUTDOWN_FAILED: [2, 'help', 'Inspect the reported resource before retrying.'],
46
+ PORT_IN_USE: [2, 'help', 'Choose an unused port.'],
47
+ NETWORK_FAILED: [2, 'compare', 'Retry after restoring fixture connectivity.'],
48
+ AUTH_REQUIRED: [2, 'compare', 'Retry after providing fixture access.'],
49
+ IO_FAILED: [2, 'help', 'Repair access to the reported path before retrying.'],
50
+ INTERNAL_ERROR: [2, 'version', 'Record the runtime version with the diagnostic.'],
51
+ };
52
+
53
+ export class CliError extends Error {
54
+ /** @param {ErrorCode} code @param {string} message @param {{data?: unknown, cause?: unknown, context?: ErrorContext, warnings?: Diagnostic[], humanReported?: boolean}} [options] */
55
+ constructor(code, message, { data = null, cause, context = {}, warnings = [], humanReported = false } = {}) {
56
+ super(message, { cause });
57
+ this.name = 'CliError';
58
+ this.code = code;
59
+ this.data = data;
60
+ this.context = context;
61
+ this.warnings = warnings;
62
+ this.humanReported = humanReported;
63
+ }
64
+ }
65
+
66
+ const canonicalCommands = new Set([
67
+ 'open', 'link', 'serve', 'root', 'service', 'migrate', 'init', 'check', 'render', 'compare',
68
+ 'root add', 'root remove', 'root list', 'root scan',
69
+ 'service install', 'service uninstall', 'service status', 'service logs', 'service migrate',
70
+ 'help', 'version', 'adg',
71
+ ]);
72
+ const playwrightVersion = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).dependencies.playwright;
73
+
74
+ /** Sanitize strings before either diagnostic channel; never stringify raw errors/configs. @param {string} text */
75
+ export function sanitize(text) {
76
+ return stripVTControlCharacters(text)
77
+ .replace(/\b(?:adg|sdg)_[a-f0-9]{64}\b/gi, '[REDACTED]')
78
+ .replace(/(\bBearer\s+)[^\s"'<>]+/gi, '$1[REDACTED]')
79
+ .replace(/(\b(?:X-(?:ADG|SDG)-Key|authorization)["']?\s*[:=]\s*["']?)[^\s"',}<>]+/gi, '$1[REDACTED]')
80
+ .replace(/(https?:\/\/)[^\s/@]+(?::[^\s/@]*)?@/gi, '$1[REDACTED]@')
81
+ .replace(/([?&](?:key|token|access_token|api_key|authorization)=)[^&#\s"'<>]*/gi, '$1[REDACTED]');
82
+ }
83
+
84
+ /** @param {string} [command] */
85
+ function helpArgv(command = 'adg') {
86
+ return ['adg', ...(canonicalCommands.has(command) && !['adg', 'help', 'version'].includes(command) ? command.split(' ') : []), '--help', '--json'];
87
+ }
88
+
89
+ /** @param {ErrorCode} code @param {ErrorContext} [context] @returns {NextAction[]} */
90
+ export function nextActions(code, context = {}) {
91
+ const [, recovery, reason] = errorCatalog[code];
92
+ const state = context.stateDirectory ? ['--state-dir', context.stateDirectory] : [];
93
+ let argv;
94
+ switch (recovery) {
95
+ case 'check': argv = ['adg', 'check', '--read-only', '--json', ...(context.positionals?.length && context.command === 'check' ? ['--', ...context.positionals] : [])]; break;
96
+ case 'install': argv = ['npm', 'install', '-g', '@whzxc/agent-design-gallery']; break;
97
+ case 'migrate': argv = context.project ? ['adg', 'migrate', context.project, '--json'] : helpArgv('migrate'); break;
98
+ case 'migration': argv = context.command === 'service migrate' ? ['adg', 'service', 'status', ...state, '--json'] : helpArgv('migrate'); break;
99
+ case 'migrate-help': argv = helpArgv('migrate'); break;
100
+ case 'check-help': argv = helpArgv('check'); break;
101
+ case 'render-help': argv = helpArgv('render'); break;
102
+ case 'serve-help': argv = helpArgv('serve'); break;
103
+ case 'roots': argv = ['adg', 'root', 'list', ...state, '--json']; break;
104
+ case 'rotate': argv = ['adg', 'serve', '--rotate-key', ...state, '--json']; break;
105
+ case 'status': argv = ['adg', 'service', 'status', ...state, '--json']; break;
106
+ case 'logs': argv = ['adg', 'service', 'logs', ...state, '--json']; break;
107
+ case 'version': argv = ['adg', '--version', '--json']; break;
108
+ case 'git-version': argv = ['git', '--version']; break;
109
+ case 'git': {
110
+ const operation = context.gitCause === 'revision' ? ['log', '-5', '--oneline'] : context.gitCause === 'read' ? ['status', '--short'] : ['rev-parse', '--show-toplevel'];
111
+ argv = context.project ? ['git', '-C', context.project, ...operation] : helpArgv(context.command);
112
+ break;
113
+ }
114
+ case 'chromium': argv = ['npx', `playwright@${playwrightVersion}`, 'install', 'chromium']; break;
115
+ case 'compare': {
116
+ const values = context.values ?? {}, sources = context.positionals ?? [];
117
+ if (context.command !== 'compare' || (!values.all && (sources.length !== 1 || typeof values.frame !== 'string' || !values.frame))) {
118
+ argv = helpArgv(context.command);
119
+ break;
120
+ }
121
+ argv = ['adg', 'compare'];
122
+ if (values.all) argv.push('--all');
123
+ else {
124
+ // Attached values preserve literal operands starting with '-'.
125
+ for (const key of ['frame', 'fixture', 'region', 'selector', 'origin', 'viewport']) {
126
+ if (typeof values[key] === 'string') argv.push(`--${key}=${values[key]}`);
127
+ }
128
+ if (values.page) argv.push('--page');
129
+ for (const click of Array.isArray(values.click) ? values.click : []) argv.push(`--click=${click}`);
130
+ argv.push('--json', '--', sources[0]);
131
+ break;
132
+ }
133
+ argv.push('--json');
134
+ break;
135
+ }
136
+ default: argv = helpArgv(context.command);
137
+ }
138
+ // Redacted operands are not executable corrections; offer safe help instead.
139
+ if (argv.some(value => sanitize(value) !== value)) return [{ argv: helpArgv(context.command), reason: 'Read command arguments without exposing credentials.' }];
140
+ return [{ argv, reason: String(reason) }];
141
+ }
142
+
143
+ const ioCodes = new Set(['EACCES', 'EPERM', 'ENOENT', 'ENOTDIR', 'EISDIR', 'ENOSPC', 'EROFS', 'EEXIST', 'EXDEV', 'EMFILE', 'ENFILE', 'EIO']);
144
+ const networkCodes = new Set(['ECONNREFUSED', 'ECONNRESET', 'ENOTFOUND', 'EAI_AGAIN', 'ETIMEDOUT', 'ERR_TLS_CERT_ALTNAME_INVALID', 'CERT_HAS_EXPIRED']);
145
+
146
+ /** @param {unknown} cause @param {ErrorContext} [context] @returns {{error: Diagnostic & {code: ErrorCode}, exitCode: number, data: unknown, warnings: Diagnostic[]}} */
147
+ export function classifyError(cause, context = {}) {
148
+ const raw = cause instanceof Error ? cause : null;
149
+ const rawCode = raw && 'code' in raw ? String(raw.code) : '';
150
+ /** @type {ErrorCode} */
151
+ let code = 'INTERNAL_ERROR';
152
+ if (raw instanceof CliError && Object.hasOwn(errorCatalog, raw.code)) code = raw.code;
153
+ else if (rawCode === 'EADDRINUSE') code = 'PORT_IN_USE';
154
+ else if (context.failureCode && Object.hasOwn(errorCatalog, context.failureCode)) code = context.failureCode;
155
+ else if (ioCodes.has(rawCode)) code = 'IO_FAILED';
156
+ else if (networkCodes.has(rawCode)) code = 'NETWORK_FAILED';
157
+ const message = sanitize(raw?.message ?? (typeof cause === 'string' ? cause : 'Unexpected ADG error.')).replace(/\s+/g, ' ').trim();
158
+ return {
159
+ error: { code, message, next: nextActions(code, { ...context, ...(raw instanceof CliError ? raw.context : {}) }) },
160
+ exitCode: Number(errorCatalog[code][0]),
161
+ data: raw instanceof CliError ? raw.data : null,
162
+ warnings: raw instanceof CliError ? raw.warnings : [],
163
+ };
164
+ }
165
+
166
+ /** @param {unknown} cause @param {ErrorCode} [fallback] */
167
+ export function asCliError(cause, fallback = 'INTERNAL_ERROR') {
168
+ if (cause instanceof CliError) return cause;
169
+ const classified = classifyError(cause);
170
+ return new CliError(classified.error.code === 'INTERNAL_ERROR' ? fallback : classified.error.code, cause instanceof Error ? cause.message : String(cause), { cause });
171
+ }
172
+
173
+ /** @param {unknown} value @returns {unknown} */
174
+ function sanitizedValue(value) {
175
+ if (typeof value === 'string') return sanitize(value);
176
+ if (Array.isArray(value)) return value.map(sanitizedValue);
177
+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, sanitizedValue(item)]));
178
+ return value;
179
+ }
180
+
181
+ /** @type {AsyncLocalStorage<(text: string) => void>} */
182
+ const humanOutput = new AsyncLocalStorage();
183
+ /**
184
+ * Route config/module writes in this invocation without capturing the caller's output.
185
+ * @template T
186
+ * @param {() => T | Promise<T>} work
187
+ * @param {(text: string) => void} stderr
188
+ * @returns {Promise<T>}
189
+ */
190
+ export async function withHumanOutput(work, stderr) {
191
+ const originals = [process.stdout.write, process.stderr.write];
192
+ for (const [index, stream] of [process.stdout, process.stderr].entries()) {
193
+ /** @param {string | Uint8Array} chunk @param {BufferEncoding | ((error?: Error | null) => void)} [encoding] @param {(error?: Error | null) => void} [callback] */
194
+ function redirect(chunk, encoding, callback) {
195
+ const sink = humanOutput.getStore();
196
+ const done = typeof encoding === 'function' ? encoding : callback;
197
+ if (!sink) return originals[index].call(stream, chunk, typeof encoding === 'string' ? encoding : undefined, done);
198
+ sink(sanitize(typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString(typeof encoding === 'string' ? encoding : 'utf8')));
199
+ done?.();
200
+ return true;
201
+ }
202
+ stream.write = redirect;
203
+ }
204
+ try { return await humanOutput.run(stderr, work); }
205
+ finally { [process.stdout.write, process.stderr.write] = originals; }
206
+ }
207
+
208
+ /** @param {OutputOptions} options */
209
+ export function createOutput({ json, command, revealKey = false, stdout = text => { process.stdout.write(text); }, stderr = text => { process.stderr.write(text); } }) {
210
+ /** @param {Envelope} envelope */
211
+ const emit = envelope => {
212
+ const clean = /** @type {Envelope} */ (sanitizedValue(envelope));
213
+ const data = envelope.data;
214
+ if (json && revealKey && command === 'serve' && envelope.ok && data && typeof data === 'object' && 'action' in data && data.action === 'print-key' && 'key' in data && typeof data.key === 'string' && /^adg_[a-f0-9]{64}$/.test(data.key) && clean.data && typeof clean.data === 'object') {
215
+ // Only the explicit print-key result field is exempt; siblings and diagnostics stay sanitized.
216
+ Object.assign(clean.data, { key: data.key });
217
+ }
218
+ stdout(`${JSON.stringify(clean)}\n`);
219
+ };
220
+ /** @param {string} text */
221
+ const log = text => (json ? stderr : stdout)(`${sanitize(text)}\n`);
222
+ return {
223
+ log,
224
+ /** @param {string} text */
225
+ progress: text => stderr(`${sanitize(text)}\n`),
226
+ /** @param {unknown} data @param {Diagnostic[]} [warnings] */
227
+ success(data, warnings = []) { emit({ schemaVersion: 1, command, ok: true, data: data ?? null, warnings, error: null }); },
228
+ /** @param {unknown} cause @param {ErrorContext} [context] */
229
+ failure(cause, context = {}) {
230
+ const failure = classifyError(cause, { ...context, command });
231
+ if (json) emit({ schemaVersion: 1, command, ok: false, data: failure.data, warnings: failure.warnings, error: failure.error });
232
+ else if (!(cause instanceof CliError && cause.humanReported)) stderr(`adg: ${failure.error.message}\n`);
233
+ return failure.exitCode;
234
+ },
235
+ };
236
+ }
package/src/cli.mjs ADDED
@@ -0,0 +1,176 @@
1
+ #!/usr/bin/env node
2
+ import path from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { realpathSync } from 'node:fs';
6
+ import { VERSION, loadConfig } from './toolkit/config.mjs';
7
+ import { CliError, createOutput, withHumanOutput } from './cli-output.mjs';
8
+
9
+ export const commands = ['open', 'link', 'serve', 'root', 'service', 'migrate', 'init', 'check', 'render', 'compare'];
10
+ const targetOptions = '[--asset=<path> [--frame=<name>] | --group=<name> | --layer=<name> | --tokens] [--mode=query|path] [--base=<rev>]';
11
+ const usage = {
12
+ open: `[directory] [--port=<n>] [--no-open] [--state-dir=<path>] ${targetOptions}`,
13
+ link: `<viewer-url> ${targetOptions}`,
14
+ serve: '[--port=4310] [--state-dir=<path>] [--print-key | --rotate-key]',
15
+ service: 'install|uninstall|status|logs|migrate [--state-dir=<path>] [--port=4310]',
16
+ root: 'add <dir> [--depth=2] | remove <dir> | list | scan [dir] [--state-dir=<path>]',
17
+ migrate: '[project]', init: '', check: '[source...] [--read-only]', render: '[source...] [--frame=<name>] [--theme=both|light|dark] [--scale=2] [--out-dir=<path>] [--json] [--base=<rev>]',
18
+ compare: '<source> --frame=<name> [--fixture=<name>] [--region=<name> | --selector=<css> | --page] [--origin="<x> <y>"] [--click=<name>...] [--viewport=<w>x<h>] | --all',
19
+ };
20
+ const details = {
21
+ migrate: 'Rename a project configuration and runtime imports, update editor paths and ignore entries, remove old generated files and regenerate declarations. Refuses mixed config names; safe to run again.',
22
+ serve: 'Run the resident multi-project hub on 127.0.0.1. Projects build on viewer access and idle viewers stop after five minutes. --print-key prints the key and exits; --rotate-key rotates the running hub key and exits. Forwarded data requests require a header or query key; direct-local requests are exempt.',
23
+ service: 'Manage the macOS resident hub LaunchAgent. install starts it with RunAtLoad and KeepAlive, recording absolute Node/CLI paths. --port applies only to install. status prints JSON; logs prints the last 200 lines per log. Uninstall retains state and logs. migrate moves old hub state and replaces its LaunchAgent, then lists other agents referencing the old state path. --state-dir selects the migration destination. Other platforms are unsupported.',
24
+ root: 'Manage registered scan roots. add scans immediately. scan rescans registered roots only; depth is 0 through 3. Hidden directories, node_modules and Git worktrees are skipped.',
25
+ open: 'Browse TSX, Mermaid architecture sources and legacy SVG designs on an independent random-port server.', init: 'Create design sources, tokens and editor configuration without overwriting files.',
26
+ link: 'Print a clean ADG preview URL. Query mode isolates a target. Path mode locates it in the design hierarchy.',
27
+ check: 'Check import direction and every selected frame in both themes. --read-only skips generated types and build files.', render: 'Render selected frames as PNG. Defaults to both themes at 2×. --json prints a versioned result with capture geometry and absolute paths.',
28
+ compare: 'Compare fixture text positions. Flags override Frame fixture and capture. --all writes a summary for every fixture frame.',
29
+ };
30
+ export function help(command) {
31
+ if (command) return `Usage: adg ${command} ${usage[command]}\n\n${details[command]}\n\n-h, --help Show help\nExit codes: 0 success, 1 check/compare problems, 2 usage/configuration/environment error.`;
32
+ return `Usage: adg [open] [directory] [options]\n\n${commands.map(name => ` adg ${name} ${usage[name]}`).join('\n')}\n\nAny first argument that is not a command opens a directory. Use adg open check for a directory named check.\nRun adg <command> --help for details. -v, --version prints the installed version.`;
33
+ }
34
+ export function parseCli(args) {
35
+ let globalJson = false;
36
+ while (args[0] === '--json') { globalJson = true; args = args.slice(1); }
37
+ const explicit = commands.includes(args[0]), command = explicit ? args[0] : 'open';
38
+ const options = { help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' }, json: { type: 'boolean' } };
39
+ const locators = ['asset', 'frame', 'group', 'layer', 'mode', 'base'];
40
+ const strings = { open: ['port', 'state-dir', ...locators], link: locators, serve: ['port', 'state-dir'], root: ['depth', 'state-dir'], service: ['port', 'state-dir'], render: ['scale', 'frame', 'theme', 'out-dir', 'base'], compare: ['frame', 'fixture', 'region', 'selector', 'viewport', 'origin'] };
41
+ for (const name of strings[command] ?? []) options[name] = { type: 'string' };
42
+ if (command === 'serve') for (const name of ['print-key', 'rotate-key']) options[name] = { type: 'boolean' };
43
+ if (command === 'open') options['no-open'] = { type: 'boolean' };
44
+ if (command === 'open' || command === 'link') options.tokens = { type: 'boolean' };
45
+ if (command === 'check') options['read-only'] = { type: 'boolean' };
46
+ if (command === 'compare') { options.all = { type: 'boolean' }; options.page = { type: 'boolean' }; }
47
+ if (command === 'compare') options.click = { type: 'string', multiple: true };
48
+ let parsed;
49
+ try { parsed = parseArgs({ args: explicit ? args.slice(1) : args, options, allowPositionals: true }); }
50
+ catch (error) { throw new CliError('USAGE_INVALID', `${error.message}; run adg ${command} --help`); }
51
+ const { values, positionals } = parsed;
52
+ if (globalJson) values.json = true;
53
+ if (!values.help && !values.version) {
54
+ if ((command === 'init' && positionals.length) || (['open', 'migrate'].includes(command) && positionals.length > 1) || (command === 'compare' && (values.all ? positionals.length || values.frame : positionals.length !== 1 || !values.frame))) throw new CliError('USAGE_INVALID', `Invalid arguments; run adg ${command} --help`);
55
+ if (command === 'link' && positionals.length !== 1) throw new CliError('USAGE_INVALID', 'Expected one viewer URL. Run adg link --help.');
56
+ if (command === 'service' && (positionals.length !== 1 || !serviceActions.includes(positionals[0]) || (values.port !== undefined && positionals[0] !== 'install'))) throw new CliError('USAGE_INVALID', 'Invalid arguments; run adg service --help');
57
+ if (command === 'root') {
58
+ const [action, directory, ...extra] = positionals;
59
+ if (extra.length || !rootActions.includes(action) || (['add', 'remove'].includes(action) && !directory) || (action === 'list' && directory) || (values.depth !== undefined && action !== 'add')) throw new CliError('USAGE_INVALID', 'Invalid arguments; run adg root --help');
60
+ }
61
+ if (command === 'serve' && positionals.length) throw new CliError('USAGE_INVALID', 'Invalid arguments; run adg serve --help');
62
+ if (command === 'serve' && ((values['print-key'] && values['rotate-key']) || (values.port !== undefined && (values['print-key'] || values['rotate-key'])))) throw new CliError('USAGE_INVALID','Choose --print-key or --rotate-key without --port; run adg serve --help');
63
+ } else if (values.json && values.help && ['root', 'service'].includes(command) && (positionals.length > 1 || (positionals.length && !(command === 'root' ? rootActions : serviceActions).includes(positionals[0])))) {
64
+ throw new CliError('USAGE_INVALID', `Invalid arguments; run adg ${command} --help`);
65
+ }
66
+ return { command, values, positionals, explicit };
67
+ }
68
+ const rootActions = ['add', 'remove', 'list', 'scan'];
69
+ const serviceActions = ['install', 'uninstall', 'status', 'logs', 'migrate'];
70
+
71
+ export function commandIdentity({ command, positionals = [] }) {
72
+ const actions = command === 'root' ? rootActions : command === 'service' ? serviceActions : [];
73
+ return actions.includes(positionals[0]) ? `${command} ${positionals[0]}` : command;
74
+ }
75
+
76
+ export function jsonRequested(args) {
77
+ const separator = args.indexOf('--');
78
+ return (separator < 0 ? args : args.slice(0, separator)).includes('--json');
79
+ }
80
+
81
+ function errorCommand(args) {
82
+ while (args[0] === '--json') args = args.slice(1);
83
+ if (commands.includes(args[0])) return commandIdentity({ command: args[0], positionals: args.slice(1) });
84
+ return args[0] && !args[0].startsWith('-') ? 'open' : 'adg';
85
+ }
86
+
87
+ async function dispatch({ command, values, positionals }, cwd, output, serviceOptions) {
88
+ if (command === 'migrate') return { data: await (await import('./toolkit/migrate.mjs')).migrate(positionals[0] === undefined ? cwd : path.resolve(cwd, positionals[0]), output.log) };
89
+ if (command === 'link') {
90
+ const { previewTarget, previewURL } = await import('./link.mjs');
91
+ const data = { url: previewURL(positionals[0], previewTarget(values)).href };
92
+ if (!values.json) output.log(data.url);
93
+ return { data };
94
+ }
95
+ if (command === 'service') {
96
+ const options={...serviceOptions,output:output.log};
97
+ if (values['state-dir'] !== undefined) values={...values,'state-dir':path.resolve(cwd,values['state-dir'])};
98
+ return (await import('./service.mjs')).service(positionals[0], values, options);
99
+ }
100
+ if (command === 'root') {
101
+ const [action, directory] = positionals;
102
+ const registry = await import('./hub/registry.mjs');
103
+ const state = path.resolve(cwd, values['state-dir'] ?? registry.defaultStateDirectory);
104
+ const options = { cwd, error: output.progress };
105
+ const result = action === 'add' ? await registry.addRoot(directory, values.depth === undefined ? 2 : Number(values.depth), state, options)
106
+ : action === 'remove' ? await registry.removeRoot(directory, state, options)
107
+ : action === 'scan' ? await registry.scanRoots(directory, state, options)
108
+ : { data: { stateDirectory: state, roots: await registry.listRoots(state), affected: [] } };
109
+ if (!values.json) output.log(JSON.stringify(result.data.roots, null, 2));
110
+ return result;
111
+ }
112
+ if (command === 'serve') {
113
+ const {defaultStateDirectory}=await import('./hub/registry.mjs');
114
+ const stateDirectory=path.resolve(cwd,values['state-dir'] ?? defaultStateDirectory);
115
+ const key=await (await import('./hub/auth.mjs')).hubKey(stateDirectory,{rotate:!!values['rotate-key']});
116
+ if (!values.json && !values['print-key']) output.log('Hub key rotated.');
117
+ return {data:values['print-key'] ? {action:'print-key',stateDirectory,key} : {action:'rotate-key',stateDirectory,rotated:true}};
118
+ }
119
+ const config = await loadConfig(cwd);
120
+ if (command === 'init') return { data: (await import('./toolkit/project.mjs')).init(config, output.log) };
121
+ if (command === 'compare') return (await import('./toolkit/compare.mjs')).compare(config, positionals, values, {log:output.log});
122
+ const toolkit = await import('./toolkit/commands.mjs');
123
+ return command === 'check' ? toolkit.check(config, positionals, values, output.log, output.progress) : toolkit.render(config, positionals, values, output.log);
124
+ }
125
+ export async function main(args = process.argv.slice(2), cwd = process.cwd(), {
126
+ stdout = process.stdout.write.bind(process.stdout), stderr = process.stderr.write.bind(process.stderr),
127
+ exit = code => { process.exitCode = code; },
128
+ serviceOptions, openOptions, hubOptions, signals = process, stdoutEvents = process.stdout,
129
+ } = {}) {
130
+ let command = errorCommand(args), parsed;
131
+ const json = jsonRequested(args);
132
+ let output = createOutput({ json, command, stdout, stderr });
133
+ let code;
134
+ try {
135
+ parsed = parseCli(args);
136
+ command = parsed.values.help ? 'help' : parsed.values.version ? 'version' : commandIdentity(parsed);
137
+ output = createOutput({ json, command, stdout, stderr, revealKey:command === 'serve' && !!parsed.values['print-key'] });
138
+ if (command === 'help') {
139
+ const text = help(parsed.explicit ? parsed.command : undefined);
140
+ if (json) output.success({ subject: parsed.explicit ? commandIdentity(parsed) : null, usage: text.split('\n')[0], text });
141
+ else output.log(text);
142
+ code = 0;
143
+ } else if (command === 'version') {
144
+ if (json) output.success({ version: VERSION });
145
+ else output.log(VERSION);
146
+ code = 0;
147
+ } else if (command === 'open' || (command === 'serve' && !parsed.values['print-key'] && !parsed.values['rotate-key'])) {
148
+ const {defaultStateDirectory}=await import('./hub/registry.mjs');
149
+ const stateDirectory=path.resolve(cwd,parsed.values['state-dir'] ?? defaultStateDirectory);
150
+ const port=parsed.values.port === undefined ? command === 'open' ? 0 : 4310 : Number(parsed.values.port);
151
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new CliError('USAGE_INVALID','--port must be an integer from 0 to 65535.');
152
+ const {runForeground}=await import('./lifecycle.mjs');
153
+ const start=command === 'open'
154
+ ? async callbacks => (await import('./open.mjs')).open(parsed.positionals,parsed.values,{...openOptions,cwd,...callbacks})
155
+ : async callbacks => (await import('./hub.mjs')).startHub({...hubOptions,port,stateDirectory,...callbacks});
156
+ const run=()=>runForeground(command,start,{output,json,signals,stdoutEvents,context:{...parsed,command,stateDirectory}});
157
+ code=json ? await withHumanOutput(run,stderr) : await run();
158
+ } else {
159
+ const run=()=>dispatch(parsed,cwd,output,serviceOptions);
160
+ const result = json ? await withHumanOutput(run, stderr) : await run();
161
+ if (json) output.success(result.data, result.warnings);
162
+ else if (command === 'serve' && parsed.values['print-key']) stdout(`${result.data.key}\n`);
163
+ code = 0;
164
+ }
165
+ } catch (error) {
166
+ code = output.failure(error, {
167
+ ...(parsed ?? {}), command,
168
+ ...(parsed?.values['state-dir'] ? { stateDirectory: path.resolve(cwd, parsed.values['state-dir']) } : {}),
169
+ });
170
+ }
171
+ exit(code);
172
+ return code;
173
+ }
174
+ if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
175
+ await main();
176
+ }
package/src/http.mjs ADDED
@@ -0,0 +1,38 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { isViewPath } from '../public/view-route.js';
3
+
4
+ export function directLocal(request) {
5
+ return /^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$|^::1$/i.test(request.headers.host ?? '') &&
6
+ !Object.keys(request.headers).some(name => name.toLowerCase() === 'forwarded' || name.toLowerCase().startsWith('x-forwarded-'));
7
+ }
8
+
9
+ export const viewerFiles = {
10
+ '/access.css': 'access.css', '/switcher.js': 'switcher.js', '/switcher.css': 'switcher.css', '/instance-actions.js': 'instance-actions.js',
11
+ '/': 'index.html', '/index.html': 'index.html', '/app.js': 'app.js', '/auth.js': 'auth.js', '/favicon.svg': 'favicon.svg',
12
+ '/assets.js': 'assets.js', '/icons.js': 'icons.js', '/layout.js': 'layout.js', '/labels.js': 'labels.js',
13
+ '/arrangement.js': 'arrangement.js', '/arrangement-worker.js': 'arrangement-worker.js',
14
+ '/relationships.js': 'relationships.js', '/selection.js': 'selection.js', '/style.css': 'style.css', '/tokens.css': 'tokens.css',
15
+ '/token-catalog.js': 'token-catalog.js',
16
+ '/view-route.js': 'view-route.js',
17
+ };
18
+ export const viewerFile = pathname => isViewPath(pathname) ? 'index.html' : viewerFiles[pathname];
19
+ const designFiles = { 'tokens.css': 'tokens.css', 'favicon.svg': 'art/adg-mark.svg' };
20
+ const shellTypes = { '.html': 'text/html', '.css': 'text/css', '.svg': 'image/svg+xml' };
21
+ export function json(response, code, data) {
22
+ response.writeHead(code, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
23
+ response.end(JSON.stringify(data));
24
+ }
25
+ export async function shell(request, response, file, base = '/') {
26
+ const packaged = new URL(`../public/${file}`, import.meta.url);
27
+ const source = designFiles[file];
28
+ let content = source
29
+ ? await readFile(new URL(`../design/${source}`, import.meta.url)).catch(() => readFile(packaged))
30
+ : await readFile(packaged);
31
+ if (file === 'index.html' && /^\/(?:p|i)\/[A-Za-z0-9_-]+\/$/.test(base)) {
32
+ content = content.toString('utf8').replace('<base href="/">', `<base href="${base}">`);
33
+ }
34
+ const type = shellTypes[file.slice(file.lastIndexOf('.'))] ?? 'text/javascript';
35
+ response.writeHead(200, { 'Content-Type': `${type}; charset=utf-8`,
36
+ 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer' });
37
+ response.end(request.method === 'HEAD' ? undefined : content);
38
+ }
@@ -0,0 +1,41 @@
1
+ import { randomBytes, createHash, timingSafeEqual } from 'node:crypto';
2
+ import { mkdir, readFile, writeFile, rename, chmod } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { directLocal } from '../http.mjs';
5
+ import { defaultStateDirectory } from './registry.mjs';
6
+ import { CliError } from '../cli-output.mjs';
7
+
8
+ export async function hubKey(stateDirectory = defaultStateDirectory, { rotate = false } = {}) {
9
+ const file = path.join(stateDirectory, 'hub.key');
10
+ if (!rotate) {
11
+ try {
12
+ const key = (await readFile(file, 'utf8')).trim();
13
+ if (!/^adg_[a-f0-9]{64}$/.test(key)) throw new CliError('HUB_KEY_INVALID', `Invalid hub key in ${file}; run adg serve --rotate-key.`, { context: {stateDirectory:path.resolve(stateDirectory)} });
14
+ await chmod(file, 0o600);
15
+ return key;
16
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
17
+ }
18
+ await mkdir(stateDirectory, { recursive: true });
19
+ const key = `adg_${randomBytes(32).toString('hex')}`;
20
+ if (rotate) {
21
+ const temporary = `${file}.${process.pid}.tmp`;
22
+ await writeFile(temporary, `${key}\n`, { mode: 0o600 });
23
+ await rename(temporary, file);
24
+ } else {
25
+ try { await writeFile(file, `${key}\n`, { flag: 'wx', mode: 0o600 }); }
26
+ catch (error) { if (error.code === 'EEXIST') return hubKey(stateDirectory); throw error; }
27
+ }
28
+ return key;
29
+ }
30
+ export function equalKey(actual, expected) {
31
+ const digest = value => createHash('sha256').update(value).digest();
32
+ return timingSafeEqual(digest(typeof actual === 'string' ? actual : ''), digest(expected));
33
+ }
34
+ export async function authorized(request, url, stateDirectory) {
35
+ if (directLocal(request)) return true;
36
+ const key = request.headers.authorization?.match(/^Bearer (\S+)$/i)?.[1] ?? request.headers['x-adg-key'] ?? url.searchParams.get('key');
37
+ // Read back on every request so CLI rotation also applies to a running service.
38
+ const expected = (await readFile(path.join(stateDirectory, 'hub.key'), 'utf8')).trim();
39
+ const equal = equalKey(key, expected);
40
+ return /^adg_[a-f0-9]{64}$/.test(expected) && equal;
41
+ }