@whzxc/agent-design-gallery 0.14.1 → 0.15.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 (62) hide show
  1. package/README.md +26 -16
  2. package/package.json +1 -1
  3. package/public/access.css +15 -2
  4. package/public/app.js +708 -483
  5. package/public/arrangement-worker.js +7 -7
  6. package/public/arrangement.js +35 -30
  7. package/public/assets.js +60 -38
  8. package/public/auth.js +59 -4
  9. package/public/boards.js +124 -0
  10. package/public/comment-anchors.js +50 -0
  11. package/public/comments.css +400 -0
  12. package/public/comments.js +1106 -0
  13. package/public/context-menu.js +97 -0
  14. package/public/frame-identity.js +26 -2
  15. package/public/hub.css +25 -3
  16. package/public/hub.html +10 -2
  17. package/public/hub.js +127 -23
  18. package/public/icons.js +2 -0
  19. package/public/index.html +13 -9
  20. package/public/instance-actions.js +9 -2
  21. package/public/layout.js +156 -86
  22. package/public/selection.js +1 -1
  23. package/public/style.css +74 -152
  24. package/public/switcher.css +5 -4
  25. package/public/switcher.js +109 -34
  26. package/public/token-catalog.js +8 -3
  27. package/public/tokens.css +14 -1
  28. package/public/view-route.js +0 -1
  29. package/src/boards/board.mjs +30 -0
  30. package/src/boards/token-board.mjs +196 -0
  31. package/src/cli-output.mjs +8 -5
  32. package/src/cli.mjs +49 -29
  33. package/src/comments.mjs +293 -0
  34. package/src/http.mjs +2 -3
  35. package/src/hub/project-link.mjs +41 -0
  36. package/src/hub/registry.mjs +5 -0
  37. package/src/hub.mjs +14 -10
  38. package/src/link.mjs +13 -1
  39. package/src/server.mjs +57 -93
  40. package/src/service.mjs +46 -12
  41. package/src/toolkit/arch.mjs +3 -2
  42. package/src/toolkit/asset-rules.mjs +24 -1
  43. package/src/toolkit/commands.mjs +12 -7
  44. package/{public/review.js → src/toolkit/diff-document.mjs} +137 -43
  45. package/src/toolkit/diff-inputs.mjs +66 -30
  46. package/src/toolkit/diff.mjs +181 -39
  47. package/src/toolkit/impact-selection.mjs +25 -10
  48. package/src/toolkit/impact.mjs +32 -12
  49. package/src/toolkit/move-pairing.mjs +140 -0
  50. package/src/toolkit/project-index.mjs +2 -2
  51. package/src/toolkit/results.mjs +1 -1
  52. package/src/toolkit/review-document.mjs +435 -0
  53. package/src/toolkit/review-groups.mjs +29 -0
  54. package/src/toolkit/review-observation.mjs +131 -0
  55. package/src/toolkit/review-sheet.mjs +117 -0
  56. package/src/toolkit/review-specimens.mjs +60 -0
  57. package/src/toolkit/review.mjs +140 -0
  58. package/src/toolkit/runtime.mjs +1 -1
  59. package/src/toolkit/theme.mjs +16 -0
  60. package/public/annotations.js +0 -816
  61. package/public/labels.js +0 -122
  62. package/src/annotations.mjs +0 -238
@@ -0,0 +1,293 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import os from 'node:os';
5
+ import { setTimeout as delay } from 'node:timers/promises';
6
+ import { CliError } from './cli-output.mjs';
7
+ import { isFeatureInternal, listSources, readGroups } from './toolkit/project.mjs';
8
+ import { currentHead } from './toolkit/arch-git.mjs';
9
+ import { groupAssets } from '../public/assets.js';
10
+ import { hubProjectURL } from './hub/project-link.mjs';
11
+
12
+ const defaultStateDirectory = path.join(os.homedir(), '.agent-design-gallery');
13
+ const statuses = ['open', 'resolved', 'all'];
14
+ const kinds = ['element', 'frame', 'source', 'chapter'];
15
+ const viewerActions = ['create', 'reply', 'edit', 'delete', 'delete-thread', 'move', 'resolve', 'reopen'];
16
+ const user = { kind: 'user' };
17
+ const invalid = message => new CliError('USAGE_INVALID', message);
18
+ const string = value => typeof value === 'string' && value.trim().length > 0;
19
+ const object = value => !!value && typeof value === 'object' && !Array.isArray(value);
20
+ const normalizeText = value => value.normalize('NFC').replace(/\p{White_Space}+/gu, ' ').trim().slice(0, 120) || null;
21
+
22
+ export async function commentFile(root, stateDirectory = defaultStateDirectory) {
23
+ const key = createHash('sha256').update(await realpath(root)).digest('hex');
24
+ return path.join(stateDirectory, 'comments', key + '.json');
25
+ }
26
+
27
+ export async function commentRevision(root) {
28
+ try { return await currentHead({ root }); }
29
+ catch (error) {
30
+ if (error.code === 'GIT_UNAVAILABLE') return null;
31
+ throw error;
32
+ }
33
+ }
34
+
35
+ // Each contender publishes a nonempty lock directory in one rename. Releasing
36
+ // or recovering it removes only its unique owner entry and then an empty directory.
37
+ async function withProjectLock(file, mutate) {
38
+ const lock = file + '.lock', folder = path.dirname(file);
39
+ const owner = `${process.pid}-${randomUUID()}`;
40
+ await mkdir(folder, { recursive: true });
41
+ const candidate = await mkdtemp(path.join(folder, '.lock-'));
42
+ const removeEmptyLock = async () => {
43
+ try { await rmdir(lock); }
44
+ catch (error) { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST', 'EPERM'].includes(error.code)) throw error; }
45
+ };
46
+ const removeOwner = async name => {
47
+ await rm(path.join(lock, name), { force: true });
48
+ await removeEmptyLock();
49
+ };
50
+ const deadline = Date.now() + 5000;
51
+ try {
52
+ await writeFile(path.join(candidate, owner), '');
53
+ for (;;) {
54
+ try { await rename(candidate, lock); break; }
55
+ catch (error) {
56
+ if (!['EEXIST', 'ENOTEMPTY', 'EPERM', 'EACCES'].includes(error.code)) throw error;
57
+ let entries;
58
+ try { entries = await readdir(lock); }
59
+ catch (cause) { if (cause.code !== 'ENOENT') throw error; entries = []; }
60
+ if (!entries.length) await removeEmptyLock();
61
+ for (const entry of entries) {
62
+ const pid = Number(/^(\d+)-[\da-f-]+$/.exec(entry)?.[1]);
63
+ if (!pid) continue;
64
+ try { process.kill(pid, 0); }
65
+ catch (cause) { if (cause.code === 'ESRCH') await removeOwner(entry); }
66
+ }
67
+ if (Date.now() >= deadline) throw new CliError('IO_FAILED', `Timed out waiting to write comments at ${file}; retry.`);
68
+ await delay(25);
69
+ }
70
+ }
71
+ try { return await mutate(); }
72
+ finally { await removeOwner(owner); }
73
+ } finally { await rm(candidate, { recursive: true, force: true }); }
74
+ }
75
+
76
+ async function readStore(file) {
77
+ let data;
78
+ try { data = JSON.parse(await readFile(file, 'utf8')); }
79
+ catch (error) {
80
+ if (error.code === 'ENOENT') return { nextNumber: 1, threads: [] };
81
+ if (error instanceof SyntaxError) throw new CliError('STATE_INVALID', `Invalid comments file: ${file}`, { cause: error });
82
+ throw error;
83
+ }
84
+ if (!object(data) || !Number.isSafeInteger(data.nextNumber) || data.nextNumber < 1 || !Array.isArray(data.threads))
85
+ throw new CliError('STATE_INVALID', `Invalid comments file: ${file}`);
86
+ return data;
87
+ }
88
+
89
+ async function writeStore(file, data) {
90
+ const temporary = `${file}.${randomUUID()}.tmp`;
91
+ try {
92
+ await writeFile(temporary, JSON.stringify(data, null, 2) + '\n', { mode: 0o600 });
93
+ await rename(temporary, file);
94
+ } finally { await rm(temporary, { force: true }); }
95
+ }
96
+
97
+ function findThread(threads, id) {
98
+ const number = (typeof id === 'number' || typeof id === 'string' && /^#?[1-9]\d*$/.test(id)) ? Number(String(id).replace(/^#/, '')) : null;
99
+ const index = threads.findIndex(thread => thread.id === id || thread.number === number);
100
+ if (index === -1) throw new CliError('COMMENT_NOT_FOUND', `Unknown comment thread ${JSON.stringify(id ?? null)}.`);
101
+ return index;
102
+ }
103
+
104
+ const sourcePath = value => string(value) && /\.(tsx|svg)$/i.test(value) && !/[\\:\0]/.test(value) &&
105
+ value.split('/').every(part => part && part !== '.' && part !== '..');
106
+
107
+ function placement(input, revision) {
108
+ const { anchor, target } = input;
109
+ if (!object(anchor) || !kinds.includes(anchor.kind) || !object(target) || !string(target.label))
110
+ throw invalid('Provide a comment anchor and target label.');
111
+ const { kind, layer = null, chapter = null, x, y } = anchor;
112
+ const hasFrame = kind === 'frame' || kind === 'element';
113
+ const source = kind === 'chapter' ? null : anchor.source;
114
+ const frame = hasFrame ? anchor.frame : null;
115
+ const element = kind === 'element' ? anchor.element : null;
116
+ const frameX = hasFrame ? anchor.frameX : null, frameY = hasFrame ? anchor.frameY : null;
117
+ if (source !== null && !sourcePath(source) || kind !== 'chapter' && !source ||
118
+ hasFrame && (!string(frame) || !Number.isFinite(frameX) || !Number.isFinite(frameY)) ||
119
+ kind === 'element' && (typeof element?.id !== 'string' || !/^e1_[\da-f]+$/.test(element.id)) ||
120
+ !Number.isFinite(x) || !Number.isFinite(y) ||
121
+ layer !== null && !string(layer) || chapter !== null && !string(chapter) ||
122
+ kind === 'chapter' && (!layer || !chapter || ['tokens', 'arch'].includes(layer)))
123
+ throw invalid('Provide a valid target identity and point for the comment anchor.');
124
+ if (revision !== null && (!string(revision) || revision.length > 128 || /[\r\n]/.test(revision)))
125
+ throw invalid('Provide a Git revision or null.');
126
+ if (target.displayName != null && !string(target.displayName)) throw invalid('Provide a valid target display name.');
127
+ const snapshot = { label: target.label, tag: null, text: null, owner: null, displayName: target.displayName ?? null };
128
+ if (element) {
129
+ if (!string(target.tag) || target.text != null && typeof target.text !== 'string' ||
130
+ target.owner != null && !string(target.owner)) throw invalid('Provide a valid element snapshot.');
131
+ Object.assign(snapshot, { tag: target.tag, text: target.text?.slice(0, 120) || null, owner: target.owner ?? null });
132
+ }
133
+ return { anchor: { kind, source, frame, layer, chapter, element: element ? { id: element.id } : null, x, y, frameX, frameY }, target: snapshot, revision };
134
+ }
135
+
136
+ function messageText(text) {
137
+ if (!string(text) || Array.from(text).length > 10000) throw invalid('Provide a message between 1 and 10,000 characters.');
138
+ return text;
139
+ }
140
+
141
+ function addMessage(thread, text, author, at) {
142
+ thread.messages.push({ id: randomUUID(), author, text: messageText(text), at, editedAt: null });
143
+ }
144
+
145
+ function reopen(thread) {
146
+ Object.assign(thread, { status: 'open', resolvedAt: null, resolvedBy: null });
147
+ }
148
+
149
+ function linked(thread, projectURL) {
150
+ return { ...thread, target: { displayName: null, ...thread.target },
151
+ link: projectURL ? new URL(`?comment=${thread.number}`, projectURL).href : null };
152
+ }
153
+
154
+ export async function listComments(root, stateDirectory, { status = 'all', source, frame } = {}) {
155
+ if (!statuses.includes(status)) throw invalid('Choose --status=open, --status=resolved or --status=all.');
156
+ const { threads } = await readStore(await commentFile(root, stateDirectory));
157
+ const matches = threads.filter(thread => (status === 'all' || thread.status === status) &&
158
+ (source === undefined || thread.anchor.source === source) && (frame === undefined || thread.anchor.frame === frame));
159
+ const projectURL = matches.length ? await hubProjectURL(root, stateDirectory) : null;
160
+ return { threads: matches.map(thread => linked(thread, projectURL)) };
161
+ }
162
+
163
+ export async function readComment(root, stateDirectory, id) {
164
+ const { threads } = await readStore(await commentFile(root, stateDirectory));
165
+ const thread = threads[findThread(threads, id)];
166
+ return { thread: linked(thread, await hubProjectURL(root, stateDirectory)) };
167
+ }
168
+
169
+ export async function changeComment(root, stateDirectory, input, { viewer = false, author } = {}) {
170
+ if (!object(input) || !viewerActions.includes(input.action) || !viewer && !['reply', 'resolve'].includes(input.action))
171
+ throw invalid('Choose a supported comment action.');
172
+ const { action, id, message, messageId } = input;
173
+ const actor = viewer ? user : { kind: 'agent', name: author?.trim() };
174
+ if (!viewer && !string(actor.name)) throw invalid('Set --author to the agent name.');
175
+ const file = await commentFile(root, stateDirectory);
176
+ const placed = ['create', 'move'].includes(action)
177
+ ? placement(input, input.revision === undefined ? await commentRevision(root) : input.revision)
178
+ : null;
179
+ const projectURL = await hubProjectURL(root, stateDirectory);
180
+ const thread = await withProjectLock(file, async () => {
181
+ const store = await readStore(file), { threads } = store, now = new Date().toISOString();
182
+ if (action === 'create') {
183
+ const thread = { id: randomUUID(), number: store.nextNumber++, status: 'open', ...placed, messages: [],
184
+ createdAt: now, updatedAt: now, resolvedAt: null, resolvedBy: null };
185
+ addMessage(thread, message, actor, now);
186
+ threads.push(thread);
187
+ await writeStore(file, store);
188
+ return thread;
189
+ }
190
+ const index = findThread(threads, id), thread = threads[index];
191
+ switch (action) {
192
+ case 'reply':
193
+ addMessage(thread, message, actor, now);
194
+ if (viewer && thread.status === 'resolved') reopen(thread);
195
+ break;
196
+ case 'resolve':
197
+ if (message !== undefined) addMessage(thread, message, actor, now);
198
+ Object.assign(thread, { status: 'resolved', resolvedAt: now, resolvedBy: actor });
199
+ break;
200
+ case 'reopen':
201
+ reopen(thread);
202
+ break;
203
+ case 'edit':
204
+ case 'delete': {
205
+ const index = thread.messages.findIndex(entry => entry.id === messageId);
206
+ if (index === -1) throw new CliError('COMMENT_NOT_FOUND', 'Unknown comment message.');
207
+ const entry = thread.messages[index];
208
+ if (entry.author.kind !== 'user') throw new CliError('COMMENT_FORBIDDEN', 'Only your own messages can be edited or deleted.');
209
+ if (action === 'edit') Object.assign(entry, { text: messageText(message), editedAt: now });
210
+ else thread.messages.splice(index, 1);
211
+ break;
212
+ }
213
+ case 'move':
214
+ Object.assign(thread, placed);
215
+ break;
216
+ }
217
+ const removed = action === 'delete-thread' || !thread.messages.length;
218
+ if (removed) threads.splice(index, 1);
219
+ else thread.updatedAt = now;
220
+ await writeStore(file, store);
221
+ return removed ? null : thread;
222
+ });
223
+ return { thread: thread ? linked(thread, projectURL) : null };
224
+ }
225
+
226
+ const quote = value => /^[\w/.#=-]+$/.test(value) ? value : "'" + value.replaceAll("'", "'\\''") + "'";
227
+ const inspectArgv = ({ source, frame }, element) => ['adg', 'inspect',
228
+ ...(frame ? [`--frame=${frame}`] : []), ...(element ? [`--element=${element}`] : []), '--json', '--', source];
229
+
230
+ function observedText(scene, element, displayName) {
231
+ const domRuns = scene.runs.filter(run => run.kind === 'dom');
232
+ const direct = domRuns.filter(run => run.element === element.id).map(run => run.raw).join('');
233
+ const name = element.role && element.name;
234
+ if (!displayName) return normalizeText(name || direct);
235
+ const named = normalizeText(element.attributes?.['aria-label'] || element.attributes?.alt || name || direct);
236
+ if (named) return named;
237
+ const children = new Map(scene.elements.map(entry => [entry.id, entry.children]));
238
+ const descendants = new Set(element.children);
239
+ for (const child of descendants) for (const id of children.get(child) ?? []) descendants.add(id);
240
+ const descendantText = domRuns.filter(run => descendants.has(run.element)).map(run => run.raw).join('');
241
+ return normalizeText(descendantText || element.attributes?.title || '');
242
+ }
243
+
244
+ export async function readCommentContext(config, stateDirectory, id) {
245
+ const { thread } = await readComment(config.root, stateDirectory, id);
246
+ const { anchor, target } = thread;
247
+ const result = { ...thread, state: 'attached', elementBox: null, commands: { inspect: null } };
248
+ if (anchor.kind === 'chapter') {
249
+ const assets = listSources(config.design, config.sources)
250
+ .map(file => path.relative(config.design, file).split(path.sep).join('/'))
251
+ .filter(file => !isFeatureInternal(file, config.sources))
252
+ .map(file => ({ path: file }));
253
+ const groups = readGroups(config.design, config.sources);
254
+ if (!groupAssets({ assets, groups }).some(group => group.layer === anchor.layer && group.title === anchor.chapter)) result.state = 'gone';
255
+ } else {
256
+ const file = path.resolve(config.root, anchor.source);
257
+ const candidates = listSources(config.design, config.sources);
258
+ if (!candidates.includes(file)) {
259
+ const legacy = file.endsWith('.svg') && file.startsWith(config.design + path.sep) && (await stat(file).catch(error => {
260
+ if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') throw error;
261
+ }))?.isFile();
262
+ if (!legacy) result.state = 'gone';
263
+ }
264
+ let elementId = null;
265
+ if (result.state === 'attached' && anchor.frame && file.endsWith('.tsx')) {
266
+ const { inspect } = await import('./toolkit/inspect.mjs');
267
+ try {
268
+ const { data } = await inspect(config, [anchor.source], {
269
+ frame: anchor.frame, ...(anchor.element ? {} : { theme: 'light' }),
270
+ wrappers: 'all', fields: 'structure,layout,text',
271
+ json: true, expand: true, ...(stateDirectory ? { 'state-dir': stateDirectory } : {}),
272
+ });
273
+ if (anchor.element) {
274
+ const scenes = [data.baseline, ...Object.values(data.additionalThemes)];
275
+ const matches = scenes.flatMap(scene => scene.elements.filter(entry => entry.id === anchor.element.id).map(element => ({ scene, element })));
276
+ const match = matches.find(({ element }) => element.geometry?.box?.width && element.geometry?.box?.height) ?? matches[0];
277
+ if (match) {
278
+ const { scene, element } = match;
279
+ elementId = element.id;
280
+ result.elementBox = element.geometry?.box ?? null;
281
+ if (element.tag !== target.tag || observedText(scene, element, target.displayName) !== target.text) result.state = 'changed';
282
+ } else result.state = 'changed';
283
+ }
284
+ } catch (error) {
285
+ if (error.code === 'SOURCE_NOT_FOUND') result.state = 'gone';
286
+ else if (error.code === 'FRAME_NOT_FOUND') result.state = 'changed';
287
+ else throw error;
288
+ }
289
+ }
290
+ if (file.endsWith('.tsx')) result.commands.inspect = inspectArgv(anchor, elementId).map(quote).join(' ');
291
+ }
292
+ return { thread: result };
293
+ }
package/src/http.mjs CHANGED
@@ -9,12 +9,11 @@ export function directLocal(request) {
9
9
  export const viewerFiles = {
10
10
  '/access.css': 'access.css', '/switcher.js': 'switcher.js', '/switcher.css': 'switcher.css', '/instance-actions.js': 'instance-actions.js',
11
11
  '/': 'index.html', '/index.html': 'index.html', '/app.js': 'app.js', '/auth.js': 'auth.js', '/favicon.svg': 'favicon.svg',
12
- '/assets.js': 'assets.js', '/frame-identity.js': 'frame-identity.js', '/icons.js': 'icons.js', '/layout.js': 'layout.js', '/labels.js': 'labels.js',
12
+ '/boards.js': 'boards.js', '/assets.js': 'assets.js', '/frame-identity.js': 'frame-identity.js', '/icons.js': 'icons.js', '/layout.js': 'layout.js',
13
13
  '/arrangement.js': 'arrangement.js', '/arrangement-worker.js': 'arrangement-worker.js',
14
14
  '/relationships.js': 'relationships.js', '/selection.js': 'selection.js', '/style.css': 'style.css', '/tokens.css': 'tokens.css',
15
15
  '/token-catalog.js': 'token-catalog.js',
16
- '/review.js': 'review.js',
17
- '/annotations.js': 'annotations.js',
16
+ '/comments.js': 'comments.js', '/comments.css': 'comments.css', '/comment-anchors.js': 'comment-anchors.js', '/context-menu.js': 'context-menu.js',
18
17
  '/view-route.js': 'view-route.js',
19
18
  };
20
19
  export const viewerFile = pathname => isViewPath(pathname) ? 'index.html' : viewerFiles[pathname];
@@ -0,0 +1,41 @@
1
+ import { readFile, rename, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { CliError } from '../cli-output.mjs';
4
+ import { defaultStateDirectory, registeredProject } from './registry.mjs';
5
+
6
+ const hubFile = stateDirectory => path.join(stateDirectory, 'hub.json');
7
+
8
+ export function hubPublicOrigin(value, setting = 'ADG_PUBLIC_ORIGIN') {
9
+ if (value === undefined) return null;
10
+ try {
11
+ const url = new URL(value);
12
+ if (['http:', 'https:'].includes(url.protocol) && !url.username && !url.password &&
13
+ url.pathname === '/' && !url.search && !url.hash) return url.origin;
14
+ } catch {}
15
+ throw new CliError('USAGE_INVALID', `Set ${setting} to an HTTP(S) origin, for example https://design.example.com.`);
16
+ }
17
+
18
+ export async function publishHubAddress(stateDirectory, address) {
19
+ const file = hubFile(stateDirectory);
20
+ const temporary = `${file}.${address.id}.tmp`;
21
+ await writeFile(temporary, JSON.stringify(address) + '\n');
22
+ await rename(temporary, file);
23
+ }
24
+
25
+ export async function hubProjectURL(root, stateDirectory = defaultStateDirectory) {
26
+ let hub;
27
+ try { hub = JSON.parse(await readFile(hubFile(stateDirectory), 'utf8')); }
28
+ catch (error) {
29
+ if (error.code === 'ENOENT' || error instanceof SyntaxError) return null;
30
+ throw error;
31
+ }
32
+ if (!hub || !Number.isInteger(hub.port) || hub.port < 1 || hub.port > 65535 || typeof hub.id !== 'string') return null;
33
+ const project = await registeredProject(root, stateDirectory);
34
+ if (!project?.slug) return null;
35
+ const local = `http://127.0.0.1:${hub.port}`;
36
+ try {
37
+ const response = await fetch(local + '/api/health', { signal: AbortSignal.timeout(750), redirect: 'error' });
38
+ if (!response.ok || (await response.json()).id !== hub.id) return null;
39
+ } catch { return null; }
40
+ return new URL(`/p/${project.slug}/`, hub.publicOrigin ?? local).href;
41
+ }
@@ -179,3 +179,8 @@ export async function listProjects(stateDirectory = defaultStateDirectory) {
179
179
  const unique = [...new Map(records.map(project => [project.path, project])).values()].sort((a, b) => a.path.localeCompare(b.path));
180
180
  return Promise.all(unique.map(projectMetadata));
181
181
  }
182
+
183
+ export async function registeredProject(directory, stateDirectory = defaultStateDirectory) {
184
+ const root = await realpath(directory);
185
+ return (await registry(stateDirectory)).roots.flatMap(entry => entry.projects).find(project => project.path === root);
186
+ }
package/src/hub.mjs CHANGED
@@ -10,8 +10,10 @@ import { json, shell, viewerFile } from './http.mjs';
10
10
  import { CliError, asCliError } from './cli-output.mjs';
11
11
  import { loadConfig } from './toolkit/config.mjs';
12
12
  import { cleanup } from './toolkit/results.mjs';
13
+ import { hubPublicOrigin, publishHubAddress } from './hub/project-link.mjs';
13
14
 
14
- export async function startHub({ port = 4310, stateDirectory = defaultStateDirectory, idleTimeout = 300_000, onDiagnostic, onFatal, startViewer = startServer } = {}) {
15
+ export async function startHub({ port = 4310, stateDirectory = defaultStateDirectory, publicOrigin = process.env.ADG_PUBLIC_ORIGIN, idleTimeout = 300_000, onDiagnostic, onFatal, startViewer = startServer } = {}) {
16
+ publicOrigin = hubPublicOrigin(publicOrigin);
15
17
  await hubKey(stateDirectory);
16
18
  let closing = false;
17
19
  const id = randomUUID(), viewers = new Map(), streams = new Set();
@@ -52,7 +54,7 @@ export async function startHub({ port = 4310, stateDirectory = defaultStateDirec
52
54
  if (url.pathname === '/api/roots' && request.method === 'GET') return json(response, 200, await listRoots(stateDirectory));
53
55
  if (url.pathname === '/api/rescan' && request.method === 'POST') return json(response, 200, (await scanRoots(undefined, stateDirectory)).data.roots);
54
56
  if (route) {
55
- if (!read && !(request.method === 'POST' && (route[2] === '/api/annotations' || route[2] === '/preferences' || route[2] === '/catalog' || /^\/(metadata|preview)\/[a-f0-9]{64}$/.test(route[2]??'')))) return json(response, 405, { error: 'Only annotations, viewer preferences and derived cache data may be changed.' });
57
+ if (!read && !(request.method === 'POST' && (route[2] === '/api/comments' || route[2] === '/preferences' || route[2] === '/catalog' || /^\/(metadata|preview)\/[a-f0-9]{64}$/.test(route[2]??'')))) return json(response, 405, { error: 'Only comments, viewer preferences and derived cache data may be changed.' });
56
58
  if (instanceRoute) {
57
59
  const instance = (await listInstances(stateDirectory)).find(item => item.id === instanceRoute[1]);
58
60
  if (!instance) return json(response, 404, { error: 'Instance is no longer live.' });
@@ -71,7 +73,7 @@ export async function startHub({ port = 4310, stateDirectory = defaultStateDirec
71
73
  const project = (await listProjects(stateDirectory)).find(item => item.slug === slug);
72
74
  if (!project) throw new CliError('PROJECT_NOT_FOUND','Unknown project; run adg root scan.');
73
75
  if (project.error) { await loadConfig(project.path); throw new CliError('CONFIG_INVALID',project.error); }
74
- entry.viewer = await startViewer({ directory: project.design, annotationStateDirectory: stateDirectory, stateDirectory: path.join(stateDirectory, 'projects', slug), onDiagnostic, onFatal });
76
+ entry.viewer = await startViewer({ directory: project.design, commentStateDirectory: stateDirectory, stateDirectory: path.join(stateDirectory, 'projects', slug), onDiagnostic, onFatal });
75
77
  return entry.viewer;
76
78
  })();
77
79
  viewers.set(slug, entry);
@@ -79,7 +81,7 @@ export async function startHub({ port = 4310, stateDirectory = defaultStateDirec
79
81
  try { await entry.pending; }
80
82
  catch (error) { if (viewers.get(slug) === entry) viewers.delete(slug); throw error; }
81
83
  entry.active++;
82
- try { await proxy(request, response, entry.viewer.port, route[2] + url.search, undefined, onDiagnostic); }
84
+ try { await proxy(request, response, entry.viewer.port, route[2] + url.search, `/p/${slug}/`, onDiagnostic); }
83
85
  finally { entry.active--; entry.last = Date.now(); }
84
86
  return;
85
87
  }
@@ -116,12 +118,14 @@ export async function startHub({ port = 4310, stateDirectory = defaultStateDirec
116
118
  for (const step of steps) try { await cleanup(step,primary); } catch (error) { primary=error; }
117
119
  if (primary) throw primary;
118
120
  })();
119
- try { await new Promise((resolve,reject) => {
120
- const startupError=error=>{server.off('listening',listening);reject(error);};
121
- const listening=()=>{server.off('error',startupError);server.on('error',error=>{if(!closing)onFatal?.(asCliError(error));});resolve();};
122
- server.once('error',startupError);server.listen(port,'127.0.0.1',listening);
123
- }); }
124
- catch (cause) { const primary=asCliError(cause);await cleanup(close,primary);throw primary; }
121
+ try {
122
+ await new Promise((resolve,reject) => {
123
+ const startupError=error=>{server.off('listening',listening);reject(error);};
124
+ const listening=()=>{server.off('error',startupError);server.on('error',error=>{if(!closing)onFatal?.(asCliError(error));});resolve();};
125
+ server.once('error',startupError);server.listen(port,'127.0.0.1',listening);
126
+ });
127
+ await publishHubAddress(stateDirectory, { id, port: server.address().port, publicOrigin });
128
+ } catch (cause) { const primary=asCliError(cause);await cleanup(close,primary);throw primary; }
125
129
  return {
126
130
  id, url: `http://127.0.0.1:${server.address().port}/`,port:server.address().port,stateDirectory:path.resolve(stateDirectory),close,
127
131
  };
package/src/link.mjs CHANGED
@@ -2,8 +2,14 @@ import { CliError } from './cli-output.mjs';
2
2
  import { readViewRoute, viewURL, viewerBase } from '../public/view-route.js';
3
3
 
4
4
  export function previewTarget(options) {
5
- const { asset, frame, group, layer, tokens, base, mode = 'query' } = options;
5
+ const { asset, frame, group, layer, tokens, base, comment, mode = 'query' } = options;
6
6
  if (!['path', 'query'].includes(mode)) throw new CliError('USAGE_INVALID', 'Choose --mode=path or --mode=query.');
7
+ if (comment !== undefined) {
8
+ if (!/^#?[1-9]\d*$/.test(comment) || !Number.isSafeInteger(Number(comment.replace(/^#/, ''))) ||
9
+ [asset, frame, group, layer, tokens, base, options.mode].some(value => value !== undefined))
10
+ throw new CliError('USAGE_INVALID', 'Use --comment=<number> by itself.');
11
+ return { comment: comment.replace(/^#/, '') };
12
+ }
7
13
  const targets = [asset, group, layer, tokens].filter(value => value !== undefined && value !== false);
8
14
  if (targets.length > 1 || (frame !== undefined && !asset) || targets.some(value => value === '') || frame === '')
9
15
  throw new CliError('USAGE_INVALID', 'Choose one of --asset, --group, --layer, or --tokens. --frame needs --asset.');
@@ -24,6 +30,12 @@ export function previewURL(input, target) {
24
30
  const root = viewerBase(pathname);
25
31
  if (pathname !== root && !pathname.startsWith(`${root}view/`) && pathname !== `${root}index.html`)
26
32
  throw new CliError('USAGE_INVALID', 'Use a direct viewer, hub project, or live instance URL.');
33
+ if (target.comment) {
34
+ base.pathname = root;
35
+ base.search = base.hash = '';
36
+ base.searchParams.set('comment', target.comment);
37
+ return base;
38
+ }
27
39
  const previous = target.asset || target.group || target.layer || target.tokens ? null : readViewRoute(base);
28
40
  const [kind, ...name] = (previous?.scope ?? '').split(':');
29
41
  const key = name.join(':');