@whzxc/agent-design-gallery 0.14.1 → 0.16.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 (111) hide show
  1. package/README.md +29 -16
  2. package/package.json +2 -1
  3. package/public/access.css +15 -2
  4. package/public/app.js +1284 -521
  5. package/public/arrangement-worker.js +7 -7
  6. package/public/arrangement.js +35 -30
  7. package/public/assets.js +85 -48
  8. package/public/auth.js +59 -4
  9. package/public/boards.js +129 -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 +51 -14
  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 +9 -0
  19. package/public/index.html +26 -10
  20. package/public/instance-actions.js +9 -2
  21. package/public/layout.js +156 -86
  22. package/public/motion-flow.js +28 -0
  23. package/public/motion-identity.js +100 -0
  24. package/public/motion-paint.js +332 -0
  25. package/public/motion-scene.js +165 -0
  26. package/public/motion-specimens.js +335 -0
  27. package/public/player.css +270 -0
  28. package/public/player.js +753 -0
  29. package/public/recent-updates.js +535 -0
  30. package/public/selection.js +1 -1
  31. package/public/style.css +91 -154
  32. package/public/switcher.css +5 -4
  33. package/public/switcher.js +109 -34
  34. package/public/token-catalog.js +8 -3
  35. package/public/tokens.css +20 -1
  36. package/public/view-boards.css +131 -0
  37. package/public/view-boards.js +350 -0
  38. package/public/view-route.js +1 -2
  39. package/src/boards/board.mjs +30 -0
  40. package/src/boards/motion-board.mjs +202 -0
  41. package/src/boards/token-board.mjs +200 -0
  42. package/src/cli-output.mjs +10 -5
  43. package/src/cli.mjs +89 -35
  44. package/src/comments.mjs +293 -0
  45. package/src/http.mjs +7 -5
  46. package/src/hub/project-link.mjs +41 -0
  47. package/src/hub/registry.mjs +5 -0
  48. package/src/hub.mjs +14 -10
  49. package/src/link.mjs +13 -1
  50. package/src/recent-frames.mjs +295 -0
  51. package/src/recent-history.mjs +100 -0
  52. package/src/recent-job.mjs +63 -0
  53. package/src/recent-worker.mjs +171 -0
  54. package/src/server.mjs +285 -110
  55. package/src/service.mjs +46 -12
  56. package/src/toolkit/arch-git.mjs +8 -14
  57. package/src/toolkit/arch.mjs +3 -2
  58. package/src/toolkit/asset-rules.mjs +24 -1
  59. package/src/toolkit/browser.mjs +1 -13
  60. package/src/toolkit/build-store.mjs +9 -1
  61. package/src/toolkit/build-worker.mjs +6 -0
  62. package/src/toolkit/build.mjs +22 -16
  63. package/src/toolkit/commands.mjs +105 -9
  64. package/src/toolkit/compare.mjs +13 -11
  65. package/src/toolkit/config.mjs +2 -2
  66. package/{public/review.js → src/toolkit/diff-document.mjs} +137 -43
  67. package/src/toolkit/diff-inputs.mjs +97 -52
  68. package/src/toolkit/diff.mjs +198 -43
  69. package/src/toolkit/frame-declarations.mjs +36 -0
  70. package/src/toolkit/git-blobs.mjs +50 -0
  71. package/src/toolkit/impact-inputs.mjs +11 -19
  72. package/src/toolkit/impact-selection.mjs +27 -12
  73. package/src/toolkit/impact.mjs +49 -15
  74. package/src/toolkit/implementation-map.mjs +17 -6
  75. package/src/toolkit/input-generation.mjs +15 -0
  76. package/src/toolkit/inspect-output.mjs +1 -1
  77. package/src/toolkit/inspect.d.ts +9 -1
  78. package/src/toolkit/inspect.mjs +25 -1
  79. package/src/toolkit/motion-check.mjs +382 -0
  80. package/src/toolkit/motion-css.mjs +105 -0
  81. package/src/toolkit/motion-flows.mjs +95 -0
  82. package/src/toolkit/motion-impact.mjs +87 -0
  83. package/src/toolkit/motion-inventory.mjs +202 -0
  84. package/src/toolkit/motion-label.mjs +111 -0
  85. package/src/toolkit/motion-patterns.mjs +216 -0
  86. package/src/toolkit/motion-primitives.mjs +94 -0
  87. package/src/toolkit/motion-queries.mjs +169 -0
  88. package/src/toolkit/motion.mjs +300 -0
  89. package/src/toolkit/move-pairing.mjs +140 -0
  90. package/src/toolkit/owner.mjs +19 -6
  91. package/src/toolkit/play-endpoint.mjs +66 -0
  92. package/src/toolkit/project-index.mjs +4 -4
  93. package/src/toolkit/recent-structure.mjs +201 -0
  94. package/src/toolkit/results.mjs +3 -3
  95. package/src/toolkit/review-document.mjs +440 -0
  96. package/src/toolkit/review-embed-document.mjs +671 -0
  97. package/src/toolkit/review-filmstrip.mjs +76 -0
  98. package/src/toolkit/review-groups.mjs +29 -0
  99. package/src/toolkit/review-motion-card.mjs +51 -0
  100. package/src/toolkit/review-motion.mjs +159 -0
  101. package/src/toolkit/review-observation.mjs +131 -0
  102. package/src/toolkit/review-playback.js +123 -0
  103. package/src/toolkit/review-sheet.mjs +125 -0
  104. package/src/toolkit/review-specimens.mjs +60 -0
  105. package/src/toolkit/review.mjs +240 -0
  106. package/src/toolkit/runtime.mjs +8 -2
  107. package/src/toolkit/theme.mjs +16 -0
  108. package/src/viewer-cache.mjs +48 -12
  109. package/public/annotations.js +0 -816
  110. package/public/labels.js +0 -122
  111. package/src/annotations.mjs +0 -238
package/src/server.mjs CHANGED
@@ -1,5 +1,8 @@
1
+ import { gunzip } from 'node:zlib';
2
+ import { promisify } from 'node:util';
1
3
  // Adapted from ARC's MIT-licensed tooling/design-server.mjs.
2
- import { annotations, annotationFile, readAnnotationContext } from './annotations.mjs';
4
+ import { frameKey as motionFrameKey, motionFlows } from './toolkit/motion-flows.mjs';
5
+ import { changeComment, commentFile, commentRevision, listComments, readComment } from './comments.mjs';
3
6
  import { randomUUID, createHash } from 'node:crypto';
4
7
  import { directLocal, viewerFile, shell, json } from './http.mjs';
5
8
  import { createServer } from "node:http";
@@ -17,6 +20,7 @@ import path from "node:path";
17
20
  import os from "node:os";
18
21
  import { perfSpan } from './perf.mjs';
19
22
 
23
+ import { createIndexStore } from './toolkit/index-store.mjs';
20
24
  import { createBuildStore } from './toolkit/build-store.mjs';
21
25
  import { CliError, asCliError } from './cli-output.mjs';
22
26
  import { cleanup } from './toolkit/results.mjs';
@@ -24,22 +28,25 @@ import { createViewerCache } from './viewer-cache.mjs';
24
28
  import { refreshTypes, archFiles, isSourcePath, readGroups, sourceDirectories, isFeatureInternal } from './toolkit/project.mjs';
25
29
  import { loadConfig } from './toolkit/config.mjs';
26
30
  import { parseTokens } from './toolkit/tokens.mjs';
31
+ import { tokenBoard } from './boards/token-board.mjs';
32
+ import { loadMotionPatterns, motionPatternFile } from './toolkit/motion-patterns.mjs';
33
+ import { motionCodeExcerpt, scanMotion } from './toolkit/motion-inventory.mjs';
27
34
  import { sourceRelationships } from '../public/relationships.js';
28
35
  import { resolveScope } from '../public/assets.js';
29
- import { diff } from './toolkit/diff.mjs';
30
36
  const digest = value => createHash('sha256').update(value).digest('hex');
31
37
  const tokenFile = 'tokens.css';
32
38
  function tokenSourcePath(directory, project) {
33
39
  const base = project.design === directory ? project.root : path.dirname(directory);
34
40
  return path.relative(base, path.join(directory, tokenFile)).split(path.sep).join('/');
35
41
  }
42
+ const decompress = promisify(gunzip);
36
43
  const viewerVersion = Promise.all(['assets.js','frame-identity.js','layout.js','selection.js','arrangement.js','arrangement-worker.js'].map(file => readFile(new URL('../public/'+file,import.meta.url)))).then(parts => digest(Buffer.concat(parts)));
37
44
  const defaultState = path.join(os.homedir(), ".agent-design-gallery");
38
45
  export async function startServer({
39
46
  directory,
40
47
  port = 0,
41
48
  stateDirectory = defaultState,
42
- annotationStateDirectory = stateDirectory,
49
+ commentStateDirectory = stateDirectory,
43
50
  fixtures = null,
44
51
  readOnly = false,
45
52
  instanceId = randomUUID(),
@@ -64,7 +71,71 @@ export async function startServer({
64
71
  revision = 0,
65
72
  closing = false,
66
73
  buildStore, viewerCache, codePaths=new Set();
67
- const overlayStores = new Map(), overlayHashes = new Set(), activeReviews = new Set();
74
+ const recentJobs = new Map();
75
+ const recentPages = new Map();
76
+ let historyRepository;
77
+ const motionOwners = new Map();
78
+ let motionFrames, playGraph, motionEdges;
79
+ // Project discovery and its watcher own this projection. Drawing and selection only read it.
80
+ async function indexMotion(project, directory, changed, inventory, reopening = false) {
81
+ playGraph = motionEdges = null;
82
+ if (!changed.size) return;
83
+ const summaries = await createIndexStore({
84
+ directory: path.join(stateDirectory, 'cache', digest(directory), 'motion-frames'),
85
+ persist: !readOnly
86
+ });
87
+ try {
88
+ for (const source of changed) {
89
+ if (!inventory.has(source)) { motionOwners.delete(source); continue; }
90
+ try {
91
+ const file = path.join(directory, source.replace(/\.tsx$/, '.motion.json'));
92
+ const { ino, size, ctimeNs } = await stat(file, { bigint: true });
93
+ const key = JSON.stringify([3, project.root, source, String(ino), String(size), String(ctimeNs)]);
94
+ // Pattern-backed edges also depend on the pattern file and token sheet.
95
+ const usesPatterns = (await readFile(file, 'utf8')).includes('"pattern"');
96
+ const saved = reopening && !usesPatterns && await summaries.get(key);
97
+ if (Array.isArray(saved?.frames) && Array.isArray(saved?.edges) && Array.isArray(saved?.declarations)) {
98
+ motionOwners.set(source, saved);
99
+ continue;
100
+ }
101
+ const { sourceMotion } = await import('./toolkit/play-endpoint.mjs');
102
+ const motion = sourceMotion(project, directory, source);
103
+ const frames = [...new Set(motion.records.map(r => r.edge.from.frame))];
104
+ const edges = motion.records.map(({ edge: { id, from, to, trigger, label } }) => ({ id, from, to, trigger, label }));
105
+ const entry = { frames, edges, declarations: motion.declarations };
106
+ motionOwners.set(source, { ...entry, motion });
107
+ if (!usesPatterns) await summaries.put(key, entry);
108
+ } catch (error) {
109
+ motionOwners.set(source, { error, frames: [] });
110
+ }
111
+ }
112
+ motionFrames = Object.fromEntries([...motionOwners].map(([source, row]) => [source, row.frames]));
113
+ playGraph = motionEdges = null;
114
+ } finally {
115
+ await summaries.close();
116
+ }
117
+ }
118
+ function boardMotionEdges(inventory = codePaths) {
119
+ if (motionEdges) return motionEdges;
120
+ const prefix = path.relative(activeProject.root, root).split(path.sep).join('/');
121
+ const base = prefix ? prefix + '/' : '';
122
+ const available = ref => ref.source.startsWith(base) && inventory.has(ref.source.slice(base.length));
123
+ const owners = [...motionOwners.keys()].sort().map(source => motionOwners.get(source));
124
+ const edges = owners.flatMap(row => row.edges ?? []);
125
+ const declarations = owners.flatMap(row => row.declarations ?? []);
126
+ const { byFrame } = motionFlows(edges.filter(edge => available(edge.from) && available(edge.to)).map(edge => ({ edge })), declarations);
127
+ motionEdges = edges.map(({ trigger, ...edge }) => {
128
+ const { on, key, value, target } = trigger;
129
+ const flow = byFrame.get(motionFrameKey(edge.from));
130
+ return {
131
+ ...edge,
132
+ trigger: { on, key, value, target: target.anchor ?? target.key ?? target.part },
133
+ ...(flow && { flow: { start: flow.start, id: flow.id, label: flow.label } }),
134
+ };
135
+ });
136
+ return motionEdges;
137
+ }
138
+ const overlayStores = new Map(), overlayHashes = new Set();
68
139
  let resettingOverlays = false;
69
140
  const knownBuilds = new Map(), legacyDependencies = new Map(), failedSources=new Set(), dirtyBuilds=new Set();
70
141
  const describe=built=>({...built,css:undefined,frames:built.frames.map(({html,...frame})=>frame)});
@@ -84,29 +155,33 @@ export async function startServer({
84
155
  });
85
156
  return writes;
86
157
  };
87
- const emit = (data) => {
158
+ const emit = (data, event) => {
159
+ const type = event ? `event: ${event}\n` : '';
88
160
  for (const client of clients)
89
- client.write(`data: ${JSON.stringify(data)}\n\n`);
161
+ client.write(`${type}data: ${JSON.stringify(data)}\n\n`);
90
162
  };
91
- let annotationStamp = null;
92
- async function readAnnotationStamp() {
93
- if (!activeProject) return null;
163
+ let commentsFile, commentStamp, checkingComments = false;
164
+ async function readCommentStamp(file) {
94
165
  try {
95
- const info = await stat(annotationFile(activeProject.root, annotationStateDirectory));
96
- return `${info.mtimeMs}-${info.size}`;
166
+ const info = await stat(file, { bigint: true });
167
+ return `${info.ino}-${info.mtimeNs}-${info.ctimeNs}`;
97
168
  } catch (e) {
98
169
  return e.code === 'ENOENT' ? 'missing' : null;
99
170
  }
100
171
  }
101
- const annotationTimer = setInterval(async () => {
102
- if (closing || !clients.size || !activeProject) return;
103
- const next = await readAnnotationStamp();
104
- if (next && next !== annotationStamp) {
105
- annotationStamp = next;
106
- emit({ annotations: true });
107
- }
108
- }, 800);
109
- annotationTimer.unref?.();
172
+ const commentTimer = setInterval(async () => {
173
+ if (closing || !clients.size || !commentsFile || checkingComments) return;
174
+ checkingComments = true;
175
+ const file = commentsFile;
176
+ try {
177
+ const next = await readCommentStamp(file);
178
+ if (file === commentsFile && next && next !== commentStamp) {
179
+ commentStamp = next;
180
+ emit({ comments: true }, 'comments');
181
+ }
182
+ } finally { checkingComments = false; }
183
+ }, 400);
184
+ commentTimer.unref?.();
110
185
  const diagnostic = (error, name = null, fallback = 'SOURCE_BUILD_FAILED') => {
111
186
  if (error.name === 'AbortError') return;
112
187
  const at = error.location ?? error.errors?.[0]?.location ?? error.cause?.errors?.[0]?.location;
@@ -152,14 +227,15 @@ export async function startServer({
152
227
  overlayHashes.add(built.hash);frameCounts.set(name,built.frames.length);
153
228
  return built;
154
229
  }
155
- async function collect(base, relative = "", out = new Map(), sourceNames = sources, discoveredCode = new Set()) {
230
+ async function collect(base, relative = "", out = new Map(), sourceNames = sources, discoveredCode = new Set(), sidecars = new Set()) {
156
231
  for (const entry of await readdir(path.join(base, relative), {
157
232
  withFileTypes: true,
158
233
  })) {
159
234
  if (entry.name.startsWith(".") || entry.name === "node_modules" || (relative === "" && entry.name === "art" && !sourceNames.includes("art"))) continue;
160
235
  const name = path.posix.join(relative, entry.name);
161
- if (entry.isDirectory()) await collect(base, name, out, sourceNames, discoveredCode);
236
+ if (entry.isDirectory()) await collect(base, name, out, sourceNames, discoveredCode, sidecars);
162
237
  else if (entry.isFile()) {
238
+ if(name.endsWith('.motion.json')) sidecars.add(name.replace(/\.motion\.json$/,'.tsx'));
163
239
  if(/\.[jt]sx?$/.test(name))discoveredCode.add(name);
164
240
  if(!(/\.svg$/i.test(name)||isSourcePath(name,sourceNames)))continue;
165
241
  const info = await stat(path.join(base, name));
@@ -182,8 +258,8 @@ export async function startServer({
182
258
  }
183
259
  return out;
184
260
  }
185
- async function collectProject(base, project, sourceNames, discoveredCode) {
186
- const out=await collect(base,'',new Map(),sourceNames,discoveredCode);
261
+ async function collectProject(base, project, sourceNames, discoveredCode, sidecars) {
262
+ const out=await collect(base,'',new Map(),sourceNames,discoveredCode,sidecars);
187
263
  if(project.design !== base) return out;
188
264
  for(const file of archFiles(project.arch)) {
189
265
  const name=path.relative(project.root,file).split(path.sep).join('/'),info=await stat(file),stamp=`${info.mtimeMs}-${info.size}`;
@@ -219,7 +295,7 @@ export async function startServer({
219
295
  if (hasTokens && !readOnly) refreshTypes({design:next});
220
296
  const project = await loadConfig(next);
221
297
  const nextSources = project.design === next ? project.sources : sourceDirectories({design:next});
222
- const nextCode=new Set(), nextFiles = await collectProject(next, project, nextSources, nextCode),
298
+ const nextCode=new Set(), sidecars=new Set(), nextFiles = await collectProject(next, project, nextSources, nextCode, sidecars),
223
299
  nextGroups = await readGroups(next, nextSources);
224
300
 
225
301
  const cacheBase=path.join(stateDirectory,'cache',digest(next));
@@ -249,9 +325,14 @@ export async function startServer({
249
325
  );
250
326
  watcher?.close();
251
327
  watcher = nextWatcher;
328
+ for (const controller of recentJobs.keys()) controller.abort();
329
+ recentPages.clear();
330
+ historyRepository = null;
252
331
  activeProject=project;watchArch(project,next);
253
332
  root = next;
254
- annotationStamp = await readAnnotationStamp();
333
+ motionOwners.clear(); motionFrames=motionEdges=undefined; await indexMotion(project, next, sidecars, sidecars, true);
334
+ commentsFile = await commentFile(project.root, commentStateDirectory);
335
+ commentStamp = await readCommentStamp(commentsFile);
255
336
  tokenSource = hasTokens ? tokenSourcePath(next, project) : null;
256
337
  codePaths=nextCode;
257
338
  sources = nextSources;
@@ -278,17 +359,27 @@ export async function startServer({
278
359
  refreshing = true;
279
360
  try {
280
361
  const observed = [...touched];
362
+ const motionSources = observed.filter(name=>name.endsWith('.motion.json')).map(name=>name.replace(/\.motion\.json$/,'.tsx'));
363
+
281
364
  touched.clear();
282
365
  const base = root,
283
366
  project = await loadConfig(base),
284
367
  nextSources = project.design===base ? project.sources : sourceDirectories({design:base}),
285
- nextCode=new Set(),
286
- next = await collectProject(base,project,nextSources,nextCode),
368
+ nextCode=new Set(), sidecars=new Set(),
369
+ next = await collectProject(base,project,nextSources,nextCode,sidecars),
287
370
  nextGroups = await readGroups(base, nextSources);
288
371
  const tokensChanged = observed.includes(tokenFile);
372
+ const patternsChanged = observed.includes(motionPatternFile);
289
373
  const hasTokens = tokensChanged ? (await readdir(base)).includes(tokenFile) : !!tokenSource;
290
374
  const nextTokenSource = hasTokens ? tokenSourcePath(base, project) : null;
291
375
  if (root !== base) return;
376
+ const changedMotion = new Set([...motionSources,...[...new Set([...sidecars,...motionOwners.keys()])].filter(name=>sidecars.has(name)!==motionOwners.has(name))]);
377
+ if (patternsChanged || tokensChanged) for (const source of sidecars) changedMotion.add(source);
378
+ if(changedMotion.size) {
379
+ await indexMotion(project,base,changedMotion,sidecars);
380
+ revision++;
381
+ emit({ revision, motionSources: [...changedMotion], motionFrames, motionEdges: boardMotionEdges(nextCode) });
382
+ }
292
383
  const stamps=[...new Set([...files.keys(),...next.keys()])].filter(name=>files.get(name)?.stamp!==next.get(name)?.stamp);
293
384
  const grouping=JSON.stringify(groups)!==JSON.stringify(nextGroups);
294
385
  const configChanged=JSON.stringify(sources)!==JSON.stringify(nextSources)||activeProject.arch!==project.arch;
@@ -299,7 +390,7 @@ export async function startServer({
299
390
  for(const name of failedSources)affected.add(name);
300
391
  for(const name of stamps)if(/\.(tsx|mmd)$/.test(name)&&next.has(name))affected.add(name);
301
392
  const legacyDirty=[...legacyDependencies.values()].some(dependencies=>dependencies.some(name=>observedPaths.includes(name)));
302
- if(!stamps.length&&!affected.size&&!grouping&&!legacyDirty&&!configChanged&&!tokensChanged&&nextTokenSource===tokenSource)return;
393
+ if(!stamps.length&&!affected.size&&!grouping&&!legacyDirty&&!configChanged&&!tokensChanged&&!patternsChanged&&nextTokenSource===tokenSource)return;
303
394
  const changed=[...new Set([...stamps,...affected])];
304
395
  for (const name of affected) {
305
396
  if (knownBuilds.delete(name)) dirtyBuilds.add(name);
@@ -326,6 +417,7 @@ export async function startServer({
326
417
  files = next;
327
418
  tokenSource = nextTokenSource;
328
419
  codePaths=nextCode;
420
+ if (structural) playGraph = motionEdges = null;
329
421
  sources = nextSources;
330
422
  groups = nextGroups;
331
423
  revision++;
@@ -347,6 +439,7 @@ export async function startServer({
347
439
  : "Agent Design Gallery",
348
440
  assets: [...files.values()].filter(asset => !isFeatureInternal(asset.path, sources)).sort((a, b) => a.path.localeCompare(b.path)),
349
441
  groups,
442
+ ...(motionOwners.size ? {motionFrames, motionEdges: boardMotionEdges()} : {}),
350
443
  revision,
351
444
  recent: state.recent,
352
445
  theme: state.theme,
@@ -361,7 +454,7 @@ export async function startServer({
361
454
  const preset = fixtures.states[name];
362
455
  if (!preset) throw new Error(`Unknown fixture ${name}; choose a declared ADG fixture.`);
363
456
  return { ...data, ...(preset.empty ? { directory: null, projectRoot: null, sourcePrefix: '', assets: [], groups: [] } : {}),
364
- label: 'agent-remote-control', recent: fixtures.recent, view: null, theme: preset.themeChoice ?? preset.theme,
457
+ label: fixtures.label ?? 'agent-remote-control', recent: fixtures.recent, view: null, theme: preset.themeChoice ?? preset.theme,
365
458
  sidebar: preset.sidebar, inspector: !!preset.inspector, fixture: { name, ...preset } };
366
459
  }
367
460
  const contextFor=async url=>(await viewerVersion)+'|'+(url.searchParams.get('context')??'')+(url.searchParams.has('base')?'|base:'+url.searchParams.get('base'):'');
@@ -369,17 +462,39 @@ export async function startServer({
369
462
  const data=baseManifest(),context=await contextFor(url), requested=url.searchParams.get('scope');
370
463
  const fixtureScope=fixtures?.states[url.searchParams.get('fixture')]?.scope;
371
464
  const desired = fixtureScope ?? requested ?? 'all';
465
+ if (data.tokenSource) {
466
+ try {
467
+ const css = await readFile(path.join(data.directory, tokenFile), 'utf8');
468
+ const { light, dark } = parseTokens(css);
469
+ const declarations = values => [...values].map(([name, value]) => `${name}:${value};`).join('\n');
470
+ data.boardCss = `#board-chrome{${declarations(light)}}
471
+ :where([data-theme="dark"]) #board-chrome, #board-chrome[data-theme="dark"]{${declarations(dark)}}`;
472
+ if (desired === 'tokens' || desired === 'all') {
473
+ data.tokens = [...light].map(([name, value]) => [name, value, dark.get(name) ?? null]);
474
+ let patterns, inventory;
475
+ if (desired === 'tokens') try {
476
+ const config = { ...activeProject, design: data.directory };
477
+ patterns = loadMotionPatterns(config, { light, dark });
478
+ inventory = scanMotion(config, patterns, undefined, { mappedOnly: true });
479
+ data.motionPatternCount = [...patterns.patterns.values()].filter(pattern => !pattern.extends).length;
480
+ } catch (error) {
481
+ patterns = null;
482
+ data.motionPatternError = error.message;
483
+ diagnostic(error);
484
+ }
485
+ const prefix = data.sourcePrefix;
486
+ data.tokenBoard = tokenBoard(data.tokenSource, css, { projectName: data.label, patterns, inventory, prefix, patternError: data.motionPatternError,
487
+ patternSource: prefix ? prefix + '/' + motionPatternFile : motionPatternFile });
488
+ }
489
+ } catch (error) {
490
+ data.tokenError = error.code ? `Cannot read ${data.tokenSource}.` : error.message;
491
+ diagnostic(new CliError('TOKENS_INVALID', error.message, { cause: error }));
492
+ }
493
+ }
372
494
  if (desired === 'tokens' && data.tokenSource) {
373
495
  // Keep the layer choices available without measuring or building any artboards.
374
496
  const { layers } = resolveScope(data, sources, 'all');
375
497
  const result = { ...data, scope: 'tokens', layers, assets: [] };
376
- try {
377
- const { light, dark } = parseTokens(await readFile(path.join(data.directory, tokenFile), 'utf8'));
378
- result.tokens = [...light].map(([name, value]) => [name, value, dark.get(name) ?? null]);
379
- } catch (error) {
380
- result.tokenError = error.code ? `Cannot read ${data.tokenSource}.` : error.message;
381
- diagnostic(new CliError('TOKENS_INVALID',error.message,{cause:error}));
382
- }
383
498
  return applyFixtureManifest(result, url.searchParams.get('fixture'));
384
499
  }
385
500
  const scoped=resolveScope(data,sources,desired === 'tokens' ? 'default' : desired);
@@ -411,55 +526,29 @@ export async function startServer({
411
526
  data.sourceImports=Object.fromEntries([...knownBuilds].map(([name,built])=>[name,built.imports]));
412
527
  const frameOnly = data.scope.startsWith('asset:') && url.searchParams.has('frame');
413
528
  if(viewerCache && !frameOnly) {
414
- const includeMetadata=url.searchParams.get('metadata')==='1';
529
+ const mode=url.searchParams.get('metadata');
415
530
  const requestedTheme=url.searchParams.get('initial')==='1'&&['light','dark'].includes(state.theme)?state.theme:(url.searchParams.get('theme')==='light'?'light':'dark');
531
+ const includeLayout=mode==='layout' && data.view && data.assets.every(asset=>
532
+ asset.hash && viewerCache.hasLayout(asset.hash,requestedTheme,context));
416
533
  data.metadataTheme=requestedTheme;
417
534
  data.assets=await Promise.all(data.assets.map(async asset=>{
418
535
  if(!asset.hash)return {...asset};
419
536
  const metadata={},metadataRefs={},previewIds={};
537
+ let layout;
420
538
  for(const theme of ['light','dark']) {
421
539
  const reference=viewerCache.reference(asset.hash,theme,context);
422
540
  if(reference){metadataRefs[theme]=true;previewIds[theme]=reference.previewIds;}
423
- if(includeMetadata&&theme===requestedTheme&&reference){const saved=await viewerCache.get(asset.hash,theme,context);if(saved)metadata[theme]=saved.metadata;}
541
+ if(theme===requestedTheme && reference) {
542
+ if(includeLayout)layout=await viewerCache.layout(asset.hash,theme,context);
543
+ if(mode==='1')metadata[theme]=(await viewerCache.get(asset.hash,theme,context))?.metadata;
544
+ }
424
545
  }
425
- return {...asset,metadata,metadataRefs,previewIds};
546
+ return {...asset,metadata,metadataRefs,previewIds,layout};
426
547
  }));
427
- data.packing=(await viewerCache.get(digest('catalog'),'light',context))?.metadata.packing??[];
428
548
  }
429
549
  data.features={compactSources:1,persistedMetadata:1,incrementalHashes:1};
430
550
  return applyFixtureManifest(data,url.searchParams.get('fixture'));
431
551
  }
432
- async function reviewManifest(url) {
433
- const baseParam = url.searchParams.get('base');
434
- if (typeof baseParam !== 'string' || !baseParam.trim())
435
- throw new CliError('USAGE_INVALID', 'Set ?base=<rev> to a Git revision.');
436
- if (!activeProject || !root)
437
- throw new CliError('DIRECTORY_NOT_FOUND', 'No project is open.');
438
- const data = baseManifest();
439
- const { layers } = resolveScope(data, sources, 'all');
440
- const reviewDir = path.join(stateDirectory, 'cache', digest(root), 'review', randomUUID());
441
- let review = null;
442
- const task = (async () => {
443
- try {
444
- await diff(activeProject, [], {
445
- base: baseParam,
446
- impacted: true,
447
- 'out-dir': reviewDir,
448
- 'state-dir': stateDirectory,
449
- json: true,
450
- }, { log: () => {}, onReview: value => { review = value; } });
451
- } catch (error) {
452
- if (error.code !== 'DIFF_FAILED') throw error;
453
- } finally {
454
- await rm(reviewDir, { recursive: true, force: true }).catch(() => {});
455
- }
456
- if (!review) throw new CliError('INTERNAL_ERROR', 'Review output was not produced.');
457
- return { ...data, scope: 'review', layers, assets: [], base: review.base, review: { ...review, label: data.label } };
458
- })();
459
- activeReviews.add(task);
460
- try { return await task; }
461
- finally { activeReviews.delete(task); }
462
- }
463
552
  async function sourceBuild(name) {
464
553
  const endBuild = perfSpan('build', name);
465
554
  let built;
@@ -540,10 +629,13 @@ export async function startServer({
540
629
  while(svgCache.size>128||bytes>32*1024*1024){const first=svgCache.keys().next().value;bytes-=svgCache.get(first).body.length;svgCache.delete(first);}
541
630
  return entry;
542
631
  }
543
- async function body(request,limit=16384,raw=false) {
632
+ async function body(request,limit=16384,raw=false,compressed=false) {
544
633
  const chunks=[];let size=0;
545
634
  for await(const chunk of request){size+=chunk.length;if(size>limit)throw Error('Request too large.');chunks.push(chunk);}
546
- const text=Buffer.concat(chunks).toString('utf8');
635
+ let bytes=Buffer.concat(chunks);
636
+ if(compressed && request.headers['content-encoding']==='gzip')
637
+ bytes=await decompress(bytes,{maxOutputLength:limit});
638
+ const text=bytes.toString('utf8');
547
639
  return raw?text:JSON.parse(text||'{}');
548
640
  }
549
641
  const server = createServer(async (request, response) => {
@@ -553,29 +645,115 @@ export async function startServer({
553
645
  const file = ['GET', 'HEAD'].includes(request.method) && viewerFile(url.pathname);
554
646
  if (file) return await shell(request, response, file, request.headers['x-adg-viewer-base']);
555
647
  if (!directLocal(request)) return json(response, 401, { error: 'Unauthorized' });
556
- if (url.pathname === '/api/annotations') {
648
+ if (request.method === 'GET' && ['/api/recent-visit','/api/recent-updates','/api/recent-state','/api/recent-visual','/api/recent-frames'].includes(url.pathname)) {
649
+ if (!activeProject) return json(response,404,{error:'No project is open.'});
650
+ const { visitRevision, dirtyGeneration } = await import('./recent-history.mjs');
651
+ const visual = url.pathname === '/api/recent-visual';
652
+ const feed = url.pathname === '/api/recent-frames';
653
+ if (!feed && !visual && url.pathname !== '/api/recent-updates') {
654
+ const visit = await visitRevision(activeProject.root);
655
+ if (visit.branch && url.pathname === '/api/recent-state')
656
+ visit.generation = (await dirtyGeneration(activeProject.root,visit.head,activeProject.output)).generation;
657
+ return json(response,200,visit);
658
+ }
659
+ const day=Number(url.searchParams.get('day')), week=Number(url.searchParams.get('week'));
660
+ if (!Number.isSafeInteger(day) || !Number.isSafeInteger(week) || week<=0 || week>day || day-week>7*86400000)
661
+ return json(response,400,{error:'Invalid local period boundaries.'});
662
+ const offset = Number(url.searchParams.get('offset'));
663
+ if (feed && (!Number.isSafeInteger(offset) || offset < 0 || offset % 20 || offset > Number.MAX_SAFE_INTEGER - 20))
664
+ return json(response,400,{error:'Invalid recent frame offset.'});
665
+ const {runRecentJob} = await import('./recent-job.mjs');
666
+ const controller = new AbortController();
667
+ response.once('close',()=>controller.abort());
668
+ const sendEvent = event => { if (!response.destroyed) response.write(JSON.stringify(event)+'\n'); };
669
+ if (visual) {
670
+ response.writeHead(200, {'Content-Type':'application/x-ndjson','Cache-Control':'no-store'});
671
+ sendEvent({phase:'Preparing visual comparison'});
672
+ }
673
+ const scoped = feed && resolveScope(baseManifest(), sources, url.searchParams.get('scope') ?? 'all');
674
+ const since = url.searchParams.get('since');
675
+ let direct, cacheKey;
676
+ if (feed) {
677
+ const directory = root, started = performance.now();
678
+ const { root: projectRoot, archDirectory, output } = activeProject;
679
+ const config = { root: projectRoot, design: directory, sources, archDirectory, output };
680
+ const params = { day, week, since, latest: url.searchParams.get('latest') === '1', scope: scoped.scope,
681
+ visible: scoped.scope === 'all' ? [] : scoped.assets.map(asset => asset.path).sort(), frame: url.searchParams.get('frame') };
682
+ const { recentFrameState } = await import('./recent-frames.mjs');
683
+ const state = await recentFrameState(config, params, historyRepository);
684
+ if (controller.signal.aborted) return;
685
+ if (directory !== root) return json(response, 200, { stale: true });
686
+ if (!state.available) return json(response, 200, state);
687
+ historyRepository = state.dirty.repository;
688
+ if (offset && url.searchParams.get('snapshot') !== state.snapshot) return json(response, 200, { stale: true });
689
+ cacheKey = JSON.stringify([directory, state.snapshot, offset]);
690
+ const cached = recentPages.get(cacheKey), preparationMs = performance.now() - started;
691
+ if (cached) return json(response, 200, { ...cached, timings: { gitScanMs: preparationMs, frameDiffMs: 0, cached: true } });
692
+ direct = { feed, config, state, offset, preparationMs, ...params };
693
+ }
694
+ const job = runRecentJob({root:activeProject.root, directory:path.join(stateDirectory,'cache',digest(root),feed ? 'recent-frames' : 'recent'),
695
+ ...direct, day,week,since, visual:visual && {base:url.searchParams.get('from'),
696
+ head:url.searchParams.get('to'),generation:url.searchParams.get('generation')}},controller.signal,visual ? sendEvent : null);
697
+ recentJobs.set(controller,job);
698
+ // Keep streaming proxies alive during long cold comparisons. Whitespace is valid JSON.
699
+ const heartbeat = setInterval(() => {
700
+ if (!response.destroyed) {
701
+ if (!response.headersSent) response.writeHead(200, {'Content-Type':'application/json','Cache-Control':'no-store'});
702
+ response.write('\n');
703
+ }
704
+ },10000);
705
+ try {
706
+ const result = await job;
707
+ if (feed && !result.stale && !result.failures?.length) {
708
+ recentPages.set(cacheKey, result);
709
+ if (recentPages.size > 32) recentPages.delete(recentPages.keys().next().value);
710
+ }
711
+ if (!response.destroyed) {
712
+ if (visual) {sendEvent({result});response.end();}
713
+ else if (response.headersSent) response.end(JSON.stringify(result));
714
+ else json(response,200,result);
715
+ }
716
+ } catch (error) {
717
+ if (!response.headersSent) throw error;
718
+ if (!response.destroyed) response.end(JSON.stringify({error:error.message}));
719
+ } finally { clearInterval(heartbeat); recentJobs.delete(controller); }
720
+ return;
721
+ }
722
+ if (url.pathname === '/api/motion-code' && request.method === 'GET') {
723
+ if (!activeProject) return json(response, 404, { error: 'No project is open.' });
724
+ const config = { ...activeProject, design: root };
725
+ const line = Number(url.searchParams.get('line'));
726
+ const lines = motionCodeExcerpt(config, loadMotionPatterns(config), url.searchParams.get('source'), line);
727
+ return lines ? json(response, 200, { line, lines }) : json(response, 404, { error: 'Unknown motion consumer.' });
728
+ }
729
+ if (url.pathname === '/api/play' && request.method === 'GET') {
730
+ const source = url.searchParams.get('source'), frame = url.searchParams.get('frame');
731
+ if (!activeProject || !codePaths.has(source) || !source.endsWith('.tsx')) return json(response,404,{error:'Unknown playback source.'});
732
+ const indexed = motionOwners.get(source);
733
+ if (indexed?.error) throw indexed.error;
734
+ if (!url.searchParams.has('scene')) return json(response, 200, { available: indexed?.frames.includes(frame) ?? false });
735
+ const { playEndpoint, playbackGraph } = await import('./toolkit/play-endpoint.mjs');
736
+ playGraph ??= playbackGraph(activeProject, root, motionOwners, codePaths);
737
+ if (indexed?.error) throw indexed.error;
738
+ const result = await playEndpoint(activeProject, root, source, frame, url.searchParams.get('theme'), sourceBuild, playGraph);
739
+ return json(response, 200, result);
740
+ }
741
+ if (url.pathname === '/api/comments') {
557
742
  if (request.method !== 'GET' && request.method !== 'POST') return json(response,405,{error:'Use GET or POST.'});
558
743
  if (request.method === 'POST' && request.headers.origin && ![`http://${host}`,`https://${host}`].includes(request.headers.origin)) return json(response,403,{error:'Cross-origin request refused.'});
559
- const config = await loadConfig(root);
744
+ if (!activeProject) return json(response, 404, { error: 'No project is open.' });
745
+ const { root: projectRoot } = activeProject;
560
746
  if (request.method === 'GET') {
561
- if (url.searchParams.has('id')) {
562
- const id = url.searchParams.get('id');
563
- const result = url.searchParams.get('context') === '1'
564
- ? await readAnnotationContext(config, annotationStateDirectory, id)
565
- : await annotations(config.root, annotationStateDirectory, 'read', { id });
566
- return json(response, 200, result);
567
- }
568
- const status = url.searchParams.get('status') ?? 'all';
569
- return json(response, 200, await annotations(config.root, annotationStateDirectory, 'list', { status }));
747
+ if (url.searchParams.has('id'))
748
+ return json(response, 200, await readComment(projectRoot, commentStateDirectory, url.searchParams.get('id')));
749
+ const [result, revision] = await Promise.all([
750
+ listComments(projectRoot, commentStateDirectory, { status: url.searchParams.get('status') ?? 'all' }),
751
+ commentRevision(projectRoot),
752
+ ]);
753
+ return json(response, 200, { ...result, revision });
570
754
  }
571
- const input = await body(request);
572
- const result = await annotations(config.root, annotationStateDirectory, input.action, {
573
- ...input,
574
- ...(input.action === 'reply' && !input.author ? { author: 'user' } : {}),
575
- });
576
- annotationStamp = await readAnnotationStamp();
577
- emit({ annotations: true });
578
- return json(response, 200, result);
755
+ const input = await body(request, 256 * 1024);
756
+ return json(response, 200, await changeComment(projectRoot, commentStateDirectory, input, { viewer: true }));
579
757
  }
580
758
  if(url.pathname==='/api/cache-stats'&&request.method==='GET')return json(response,200,{process:process.memoryUsage(),builds:buildStore?.stats(),viewer:viewerCache?.stats()});
581
759
  if (url.pathname === '/api/health' && request.method === 'GET') return json(response, 200, { id: instanceId, capabilities: { keyAuth: 1 } });
@@ -593,22 +771,16 @@ export async function startServer({
593
771
  const [,kind,hash]=cacheRoute,theme=url.searchParams.get('theme')==='dark'?'dark':'light',context=await contextFor(url);
594
772
  if(![...knownBuilds.values()].some(built=>built.hash===hash)&&!overlayHashes.has(hash))return json(response,409,{error:'Source changed; reload its metadata.'});
595
773
  if(kind==='metadata') {
596
- const data=await body(request,32*1024*1024),metadata=data.metadata;
774
+ const data=await body(request,32*1024*1024,false,true),metadata=data.metadata;
597
775
  if(!metadata||!Array.isArray(metadata.parts)||!metadata.full||!Number.isFinite(metadata.full.width)||!Number.isFinite(metadata.full.height))throw Error('Invalid measured source metadata.');
598
776
  await viewerCache.save(hash,theme,context,metadata);
599
777
  } else {
600
- const source=await body(request,32*1024*1024,true),crop=url.searchParams.get('crop')??'overview';
778
+ const source=await body(request,32*1024*1024,true,true),crop=url.searchParams.get('crop')??'overview';
601
779
  if(!/^\s*<svg\b/.test(source))throw Error('Expected an SVG preview.');
602
780
  await viewerCache.savePreview(hash,theme,context,crop,source);
603
781
  }
604
782
  return json(response,200,{ok:true});
605
783
  }
606
- if(url.pathname==='/catalog') {
607
- const data=await body(request,1024*1024),context=await contextFor(url);
608
- if(!Array.isArray(data.packing)||data.packing.length>32)throw Error('Invalid packing cache.');
609
- await viewerCache.save(digest('catalog'),'light',context,{packing:data.packing});
610
- return json(response,200,{ok:true});
611
- }
612
784
  const data = await body(request);
613
785
  if (url.pathname === "/preferences") {
614
786
  if (typeof data.sidebar === "boolean") state.sidebar = data.sidebar;
@@ -645,7 +817,6 @@ export async function startServer({
645
817
  return;
646
818
  }
647
819
  if (url.pathname === "/events") {
648
- annotationStamp ??= await readAnnotationStamp();
649
820
  response.writeHead(200, {
650
821
  "Content-Type": "text/event-stream",
651
822
  "Cache-Control": "no-store",
@@ -656,7 +827,13 @@ export async function startServer({
656
827
  return;
657
828
  }
658
829
  const metadataRoute=url.pathname.match(/^\/metadata\/([a-f0-9]{64})$/);
659
- if(metadataRoute){const saved=await viewerCache?.get(metadataRoute[1],url.searchParams.get('theme')==='dark'?'dark':'light',await contextFor(url));return json(response,saved?200:404,saved??{error:'Source metadata is not cached.'});}
830
+ if(metadataRoute) {
831
+ const saved=await viewerCache?.readMetadata(metadataRoute[1],url.searchParams.get('theme')==='dark'?'dark':'light',await contextFor(url));
832
+ if(!saved)return json(response,404,{error:'Source metadata is not cached.'});
833
+ response.writeHead(200,{'Content-Type':'application/json','Cache-Control':'no-store'});
834
+ response.end(`{"metadata":${saved.text},"previewIds":${JSON.stringify(saved.previewIds)}}`);
835
+ return;
836
+ }
660
837
  const previewRoute=url.pathname.match(/^\/preview\/([a-f0-9]{64})$/);
661
838
  if(previewRoute) {
662
839
  const content=await viewerCache?.preview(previewRoute[1],url.searchParams.get('theme')==='dark'?'dark':'light',await contextFor(url),url.searchParams.get('crop')??'overview');
@@ -668,9 +845,6 @@ export async function startServer({
668
845
  if (url.pathname === "/manifest") {
669
846
  content = JSON.stringify(await manifest(url));
670
847
  type = "application/json";
671
- } else if (url.pathname === "/review") {
672
- content = JSON.stringify(await reviewManifest(url));
673
- type = "application/json";
674
848
  } else if (url.pathname === "/relationships") {
675
849
  const assets = await Promise.all([...files.keys()].filter(name => /\.(tsx|mmd)$/.test(name)).map(async name => ({path:name, imports:(await sourceBuild(name)).imports})));
676
850
  content = JSON.stringify(sourceRelationships(assets));
@@ -708,15 +882,17 @@ export async function startServer({
708
882
  response.end(request.method === "HEAD" ? undefined : content);
709
883
  } catch (error) {
710
884
  if (response.destroyed) return;
711
- response.writeHead(error.name==='AbortError'?409:400, { "Content-Type": "application/json" });
712
- response.end(JSON.stringify({ error: error.message }));
885
+ const status = { COMMENT_NOT_FOUND: 404, COMMENT_FORBIDDEN: 403 }[error.code] ?? (error.name === 'AbortError' ? 409 : 400);
886
+ return json(response, status, { error: error.message });
713
887
  }
714
888
  });
715
889
  let closePromise;
716
890
  const close = () => closePromise ??= (async () => {
717
891
  closing = true;
892
+ for (const controller of recentJobs.keys()) controller.abort();
893
+ await Promise.allSettled(recentJobs.values());
718
894
  clearTimeout(refreshTimer);
719
- clearInterval(annotationTimer);
895
+ clearInterval(commentTimer);
720
896
  let primary;
721
897
  for (const step of [
722
898
  async () => { watcher?.close(); },
@@ -728,7 +904,6 @@ export async function startServer({
728
904
  },
729
905
  async () => { await writes; },
730
906
  async () => { await buildStore?.close(); },
731
- async () => { await Promise.allSettled([...activeReviews]); },
732
907
  closeOverlays,
733
908
  async () => { await viewerCache?.close(); },
734
909
  ]) {