@whzxc/agent-design-gallery 0.15.0 → 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 (76) hide show
  1. package/README.md +5 -2
  2. package/package.json +2 -1
  3. package/public/app.js +602 -64
  4. package/public/assets.js +25 -10
  5. package/public/boards.js +8 -3
  6. package/public/frame-identity.js +25 -12
  7. package/public/icons.js +7 -0
  8. package/public/index.html +14 -2
  9. package/public/motion-flow.js +28 -0
  10. package/public/motion-identity.js +100 -0
  11. package/public/motion-paint.js +332 -0
  12. package/public/motion-scene.js +165 -0
  13. package/public/motion-specimens.js +335 -0
  14. package/public/player.css +270 -0
  15. package/public/player.js +753 -0
  16. package/public/recent-updates.js +535 -0
  17. package/public/style.css +17 -2
  18. package/public/tokens.css +6 -0
  19. package/public/view-boards.css +131 -0
  20. package/public/view-boards.js +350 -0
  21. package/public/view-route.js +1 -1
  22. package/src/boards/motion-board.mjs +202 -0
  23. package/src/boards/token-board.mjs +9 -5
  24. package/src/cli-output.mjs +3 -1
  25. package/src/cli.mjs +52 -18
  26. package/src/http.mjs +5 -2
  27. package/src/recent-frames.mjs +295 -0
  28. package/src/recent-history.mjs +100 -0
  29. package/src/recent-job.mjs +63 -0
  30. package/src/recent-worker.mjs +171 -0
  31. package/src/server.mjs +229 -18
  32. package/src/toolkit/arch-git.mjs +8 -14
  33. package/src/toolkit/browser.mjs +1 -13
  34. package/src/toolkit/build-store.mjs +9 -1
  35. package/src/toolkit/build-worker.mjs +6 -0
  36. package/src/toolkit/build.mjs +22 -16
  37. package/src/toolkit/commands.mjs +93 -2
  38. package/src/toolkit/compare.mjs +13 -11
  39. package/src/toolkit/config.mjs +2 -2
  40. package/src/toolkit/diff-inputs.mjs +35 -26
  41. package/src/toolkit/diff.mjs +24 -11
  42. package/src/toolkit/frame-declarations.mjs +36 -0
  43. package/src/toolkit/git-blobs.mjs +50 -0
  44. package/src/toolkit/impact-inputs.mjs +11 -19
  45. package/src/toolkit/impact-selection.mjs +2 -2
  46. package/src/toolkit/impact.mjs +17 -3
  47. package/src/toolkit/implementation-map.mjs +17 -6
  48. package/src/toolkit/input-generation.mjs +15 -0
  49. package/src/toolkit/inspect-output.mjs +1 -1
  50. package/src/toolkit/inspect.d.ts +9 -1
  51. package/src/toolkit/inspect.mjs +25 -1
  52. package/src/toolkit/motion-check.mjs +382 -0
  53. package/src/toolkit/motion-css.mjs +105 -0
  54. package/src/toolkit/motion-flows.mjs +95 -0
  55. package/src/toolkit/motion-impact.mjs +87 -0
  56. package/src/toolkit/motion-inventory.mjs +202 -0
  57. package/src/toolkit/motion-label.mjs +111 -0
  58. package/src/toolkit/motion-patterns.mjs +216 -0
  59. package/src/toolkit/motion-primitives.mjs +94 -0
  60. package/src/toolkit/motion-queries.mjs +169 -0
  61. package/src/toolkit/motion.mjs +300 -0
  62. package/src/toolkit/owner.mjs +19 -6
  63. package/src/toolkit/play-endpoint.mjs +66 -0
  64. package/src/toolkit/project-index.mjs +2 -2
  65. package/src/toolkit/recent-structure.mjs +201 -0
  66. package/src/toolkit/results.mjs +2 -2
  67. package/src/toolkit/review-document.mjs +9 -4
  68. package/src/toolkit/review-embed-document.mjs +671 -0
  69. package/src/toolkit/review-filmstrip.mjs +76 -0
  70. package/src/toolkit/review-motion-card.mjs +51 -0
  71. package/src/toolkit/review-motion.mjs +159 -0
  72. package/src/toolkit/review-playback.js +123 -0
  73. package/src/toolkit/review-sheet.mjs +36 -28
  74. package/src/toolkit/review.mjs +131 -31
  75. package/src/toolkit/runtime.mjs +7 -1
  76. package/src/viewer-cache.mjs +48 -12
package/src/server.mjs CHANGED
@@ -1,4 +1,7 @@
1
+ import { gunzip } from 'node:zlib';
2
+ import { promisify } from 'node:util';
1
3
  // Adapted from ARC's MIT-licensed tooling/design-server.mjs.
4
+ import { frameKey as motionFrameKey, motionFlows } from './toolkit/motion-flows.mjs';
2
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';
@@ -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';
@@ -25,6 +29,8 @@ import { refreshTypes, archFiles, isSourcePath, readGroups, sourceDirectories, i
25
29
  import { loadConfig } from './toolkit/config.mjs';
26
30
  import { parseTokens } from './toolkit/tokens.mjs';
27
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';
28
34
  import { sourceRelationships } from '../public/relationships.js';
29
35
  import { resolveScope } from '../public/assets.js';
30
36
  const digest = value => createHash('sha256').update(value).digest('hex');
@@ -33,6 +39,7 @@ 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({
@@ -64,6 +71,70 @@ export async function startServer({
64
71
  revision = 0,
65
72
  closing = false,
66
73
  buildStore, viewerCache, codePaths=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
+ }
67
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();
@@ -156,14 +227,15 @@ export async function startServer({
156
227
  overlayHashes.add(built.hash);frameCounts.set(name,built.frames.length);
157
228
  return built;
158
229
  }
159
- 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()) {
160
231
  for (const entry of await readdir(path.join(base, relative), {
161
232
  withFileTypes: true,
162
233
  })) {
163
234
  if (entry.name.startsWith(".") || entry.name === "node_modules" || (relative === "" && entry.name === "art" && !sourceNames.includes("art"))) continue;
164
235
  const name = path.posix.join(relative, entry.name);
165
- if (entry.isDirectory()) await collect(base, name, out, sourceNames, discoveredCode);
236
+ if (entry.isDirectory()) await collect(base, name, out, sourceNames, discoveredCode, sidecars);
166
237
  else if (entry.isFile()) {
238
+ if(name.endsWith('.motion.json')) sidecars.add(name.replace(/\.motion\.json$/,'.tsx'));
167
239
  if(/\.[jt]sx?$/.test(name))discoveredCode.add(name);
168
240
  if(!(/\.svg$/i.test(name)||isSourcePath(name,sourceNames)))continue;
169
241
  const info = await stat(path.join(base, name));
@@ -186,8 +258,8 @@ export async function startServer({
186
258
  }
187
259
  return out;
188
260
  }
189
- async function collectProject(base, project, sourceNames, discoveredCode) {
190
- 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);
191
263
  if(project.design !== base) return out;
192
264
  for(const file of archFiles(project.arch)) {
193
265
  const name=path.relative(project.root,file).split(path.sep).join('/'),info=await stat(file),stamp=`${info.mtimeMs}-${info.size}`;
@@ -223,7 +295,7 @@ export async function startServer({
223
295
  if (hasTokens && !readOnly) refreshTypes({design:next});
224
296
  const project = await loadConfig(next);
225
297
  const nextSources = project.design === next ? project.sources : sourceDirectories({design:next});
226
- 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),
227
299
  nextGroups = await readGroups(next, nextSources);
228
300
 
229
301
  const cacheBase=path.join(stateDirectory,'cache',digest(next));
@@ -253,8 +325,12 @@ export async function startServer({
253
325
  );
254
326
  watcher?.close();
255
327
  watcher = nextWatcher;
328
+ for (const controller of recentJobs.keys()) controller.abort();
329
+ recentPages.clear();
330
+ historyRepository = null;
256
331
  activeProject=project;watchArch(project,next);
257
332
  root = next;
333
+ motionOwners.clear(); motionFrames=motionEdges=undefined; await indexMotion(project, next, sidecars, sidecars, true);
258
334
  commentsFile = await commentFile(project.root, commentStateDirectory);
259
335
  commentStamp = await readCommentStamp(commentsFile);
260
336
  tokenSource = hasTokens ? tokenSourcePath(next, project) : null;
@@ -283,17 +359,27 @@ export async function startServer({
283
359
  refreshing = true;
284
360
  try {
285
361
  const observed = [...touched];
362
+ const motionSources = observed.filter(name=>name.endsWith('.motion.json')).map(name=>name.replace(/\.motion\.json$/,'.tsx'));
363
+
286
364
  touched.clear();
287
365
  const base = root,
288
366
  project = await loadConfig(base),
289
367
  nextSources = project.design===base ? project.sources : sourceDirectories({design:base}),
290
- nextCode=new Set(),
291
- next = await collectProject(base,project,nextSources,nextCode),
368
+ nextCode=new Set(), sidecars=new Set(),
369
+ next = await collectProject(base,project,nextSources,nextCode,sidecars),
292
370
  nextGroups = await readGroups(base, nextSources);
293
371
  const tokensChanged = observed.includes(tokenFile);
372
+ const patternsChanged = observed.includes(motionPatternFile);
294
373
  const hasTokens = tokensChanged ? (await readdir(base)).includes(tokenFile) : !!tokenSource;
295
374
  const nextTokenSource = hasTokens ? tokenSourcePath(base, project) : null;
296
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
+ }
297
383
  const stamps=[...new Set([...files.keys(),...next.keys()])].filter(name=>files.get(name)?.stamp!==next.get(name)?.stamp);
298
384
  const grouping=JSON.stringify(groups)!==JSON.stringify(nextGroups);
299
385
  const configChanged=JSON.stringify(sources)!==JSON.stringify(nextSources)||activeProject.arch!==project.arch;
@@ -304,7 +390,7 @@ export async function startServer({
304
390
  for(const name of failedSources)affected.add(name);
305
391
  for(const name of stamps)if(/\.(tsx|mmd)$/.test(name)&&next.has(name))affected.add(name);
306
392
  const legacyDirty=[...legacyDependencies.values()].some(dependencies=>dependencies.some(name=>observedPaths.includes(name)));
307
- 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;
308
394
  const changed=[...new Set([...stamps,...affected])];
309
395
  for (const name of affected) {
310
396
  if (knownBuilds.delete(name)) dirtyBuilds.add(name);
@@ -331,6 +417,7 @@ export async function startServer({
331
417
  files = next;
332
418
  tokenSource = nextTokenSource;
333
419
  codePaths=nextCode;
420
+ if (structural) playGraph = motionEdges = null;
334
421
  sources = nextSources;
335
422
  groups = nextGroups;
336
423
  revision++;
@@ -352,6 +439,7 @@ export async function startServer({
352
439
  : "Agent Design Gallery",
353
440
  assets: [...files.values()].filter(asset => !isFeatureInternal(asset.path, sources)).sort((a, b) => a.path.localeCompare(b.path)),
354
441
  groups,
442
+ ...(motionOwners.size ? {motionFrames, motionEdges: boardMotionEdges()} : {}),
355
443
  revision,
356
444
  recent: state.recent,
357
445
  theme: state.theme,
@@ -366,7 +454,7 @@ export async function startServer({
366
454
  const preset = fixtures.states[name];
367
455
  if (!preset) throw new Error(`Unknown fixture ${name}; choose a declared ADG fixture.`);
368
456
  return { ...data, ...(preset.empty ? { directory: null, projectRoot: null, sourcePrefix: '', assets: [], groups: [] } : {}),
369
- 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,
370
458
  sidebar: preset.sidebar, inspector: !!preset.inspector, fixture: { name, ...preset } };
371
459
  }
372
460
  const contextFor=async url=>(await viewerVersion)+'|'+(url.searchParams.get('context')??'')+(url.searchParams.has('base')?'|base:'+url.searchParams.get('base'):'');
@@ -383,7 +471,20 @@ export async function startServer({
383
471
  :where([data-theme="dark"]) #board-chrome, #board-chrome[data-theme="dark"]{${declarations(dark)}}`;
384
472
  if (desired === 'tokens' || desired === 'all') {
385
473
  data.tokens = [...light].map(([name, value]) => [name, value, dark.get(name) ?? null]);
386
- data.tokenBoard = tokenBoard(data.tokenSource, css, { projectName: data.label });
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 });
387
488
  }
388
489
  } catch (error) {
389
490
  data.tokenError = error.code ? `Cannot read ${data.tokenSource}.` : error.message;
@@ -425,18 +526,24 @@ export async function startServer({
425
526
  data.sourceImports=Object.fromEntries([...knownBuilds].map(([name,built])=>[name,built.imports]));
426
527
  const frameOnly = data.scope.startsWith('asset:') && url.searchParams.has('frame');
427
528
  if(viewerCache && !frameOnly) {
428
- const includeMetadata=url.searchParams.get('metadata')==='1';
529
+ const mode=url.searchParams.get('metadata');
429
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));
430
533
  data.metadataTheme=requestedTheme;
431
534
  data.assets=await Promise.all(data.assets.map(async asset=>{
432
535
  if(!asset.hash)return {...asset};
433
536
  const metadata={},metadataRefs={},previewIds={};
537
+ let layout;
434
538
  for(const theme of ['light','dark']) {
435
539
  const reference=viewerCache.reference(asset.hash,theme,context);
436
540
  if(reference){metadataRefs[theme]=true;previewIds[theme]=reference.previewIds;}
437
- 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
+ }
438
545
  }
439
- return {...asset,metadata,metadataRefs,previewIds};
546
+ return {...asset,metadata,metadataRefs,previewIds,layout};
440
547
  }));
441
548
  }
442
549
  data.features={compactSources:1,persistedMetadata:1,incrementalHashes:1};
@@ -522,10 +629,13 @@ export async function startServer({
522
629
  while(svgCache.size>128||bytes>32*1024*1024){const first=svgCache.keys().next().value;bytes-=svgCache.get(first).body.length;svgCache.delete(first);}
523
630
  return entry;
524
631
  }
525
- async function body(request,limit=16384,raw=false) {
632
+ async function body(request,limit=16384,raw=false,compressed=false) {
526
633
  const chunks=[];let size=0;
527
634
  for await(const chunk of request){size+=chunk.length;if(size>limit)throw Error('Request too large.');chunks.push(chunk);}
528
- 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');
529
639
  return raw?text:JSON.parse(text||'{}');
530
640
  }
531
641
  const server = createServer(async (request, response) => {
@@ -535,6 +645,99 @@ export async function startServer({
535
645
  const file = ['GET', 'HEAD'].includes(request.method) && viewerFile(url.pathname);
536
646
  if (file) return await shell(request, response, file, request.headers['x-adg-viewer-base']);
537
647
  if (!directLocal(request)) return json(response, 401, { error: 'Unauthorized' });
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
+ }
538
741
  if (url.pathname === '/api/comments') {
539
742
  if (request.method !== 'GET' && request.method !== 'POST') return json(response,405,{error:'Use GET or POST.'});
540
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.'});
@@ -568,11 +771,11 @@ export async function startServer({
568
771
  const [,kind,hash]=cacheRoute,theme=url.searchParams.get('theme')==='dark'?'dark':'light',context=await contextFor(url);
569
772
  if(![...knownBuilds.values()].some(built=>built.hash===hash)&&!overlayHashes.has(hash))return json(response,409,{error:'Source changed; reload its metadata.'});
570
773
  if(kind==='metadata') {
571
- 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;
572
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.');
573
776
  await viewerCache.save(hash,theme,context,metadata);
574
777
  } else {
575
- 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';
576
779
  if(!/^\s*<svg\b/.test(source))throw Error('Expected an SVG preview.');
577
780
  await viewerCache.savePreview(hash,theme,context,crop,source);
578
781
  }
@@ -624,7 +827,13 @@ export async function startServer({
624
827
  return;
625
828
  }
626
829
  const metadataRoute=url.pathname.match(/^\/metadata\/([a-f0-9]{64})$/);
627
- 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
+ }
628
837
  const previewRoute=url.pathname.match(/^\/preview\/([a-f0-9]{64})$/);
629
838
  if(previewRoute) {
630
839
  const content=await viewerCache?.preview(previewRoute[1],url.searchParams.get('theme')==='dark'?'dark':'light',await contextFor(url),url.searchParams.get('crop')??'overview');
@@ -680,6 +889,8 @@ export async function startServer({
680
889
  let closePromise;
681
890
  const close = () => closePromise ??= (async () => {
682
891
  closing = true;
892
+ for (const controller of recentJobs.keys()) controller.abort();
893
+ await Promise.allSettled(recentJobs.values());
683
894
  clearTimeout(refreshTimer);
684
895
  clearInterval(commentTimer);
685
896
  let primary;
@@ -114,8 +114,8 @@ async function writeBaseBlobs(base, directory, entries) {
114
114
  }
115
115
 
116
116
  /** Materialize tracked bytes without export attributes or a Git worktree. */
117
- export async function materializeBase(base) {
118
- const directory = await realpath(await mkdtemp(path.join(tmpdir(), 'adg-diff-')));
117
+ export async function materializeBase(base, temporaryDirectory = tmpdir()) {
118
+ const directory = await realpath(await mkdtemp(path.join(temporaryDirectory, 'adg-diff-')));
119
119
  const close = async () => {
120
120
  try { await cleanup(() => rm(directory, { recursive: true, force: true })); }
121
121
  catch (error) { throw revisionError(error, directory, base); }
@@ -141,19 +141,13 @@ export async function currentHead(base) {
141
141
  catch (error) { if (error.code === 'GIT_UNAVAILABLE') throw error; return null; }
142
142
  }
143
143
 
144
- /** Rename hints include staged and unstaged tracked changes against the base. */
145
- export async function sourceRenames(base) {
146
- const fields = (await git(base.root, ['diff', '--name-status', '-z', '--find-renames', '--diff-filter=R', base.sha, '--'])).split('\0');
147
- const renames = [];
148
- for (let index = 0; index < fields.length - 1; index += 3) {
149
- renames.push({ before: fields[index + 1], after: fields[index + 2] });
150
- }
151
- return renames;
152
- }
153
-
154
144
  /** Actual endpoint changes; working-tree mode includes staged, unstaged and untracked paths. */
155
145
  export async function revisionChanges(base, head = null) {
156
- const fields = (await git(base.root, ['diff', '--name-status', '-z', '--find-renames', base.sha, ...(head ? [head.sha] : []), '--'])).split('\0');
146
+ const [tracked, untracked] = await Promise.all([
147
+ git(base.root, ['diff', '--name-status', '-z', '--find-renames', base.sha, ...(head ? [head.sha] : []), '--']),
148
+ head ? '' : git(base.root, ['ls-files', '--others', '--exclude-standard', '-z'])
149
+ ]);
150
+ const fields = tracked.split('\0');
157
151
  const changes = [];
158
152
  for (let i = 0; i < fields.length - 1;) {
159
153
  const code = fields[i++], first = fields[i++];
@@ -164,7 +158,7 @@ export async function revisionChanges(base, head = null) {
164
158
  status: code === 'A' ? 'added' : code === 'D' ? 'deleted' : code === 'T' ? 'type_changed' : 'modified' });
165
159
  }
166
160
  if (!head) {
167
- const names = (await git(base.root, ['ls-files', '--others', '--exclude-standard', '-z'])).split('\0').filter(Boolean);
161
+ const names = untracked.split('\0').filter(Boolean);
168
162
  for (const name of names) if (!changes.some(change => change.after === name)) changes.push({ before: null, after: name, status: 'added' });
169
163
  }
170
164
  return changes.sort((a, b) => (a.after ?? a.before) < (b.after ?? b.before) ? -1 : (a.after ?? a.before) > (b.after ?? b.before) ? 1 : 0);
@@ -23,19 +23,7 @@ export async function loadFrame(page, frame, theme = 'light') {
23
23
  });
24
24
  }
25
25
 
26
- export async function readyResources() {
27
- await document.fonts.ready;
28
- await Promise.all([...document.images].map(image => image.decode()));
29
- const urls = new Set();
30
- for (const element of document.querySelectorAll('*')) {
31
- for (const match of getComputedStyle(element).backgroundImage.matchAll(/url\(["']?(.+?)["']?\)/g)) urls.add(match[1]);
32
- }
33
- for (const element of document.querySelectorAll('svg image')) {
34
- const href = element.getAttribute('href') ?? element.getAttribute('xlink:href');
35
- if (href) urls.add(href);
36
- }
37
- await Promise.all([...urls].map(async url => { const image = new Image(); image.src = url; await image.decode(); }));
38
- }
26
+ export { readySceneResources as readyResources } from '../../public/motion-scene.js';
39
27
 
40
28
  /** Classify Playwright execution failures where the browser's connection is observable. */
41
29
  export async function browserTask(browser, work) {
@@ -187,7 +187,15 @@ export async function createBuildStore({ config, cacheDirectory }) {
187
187
  try {
188
188
  const saved = JSON.parse(await readFile(indexPath, 'utf8'));
189
189
  const startupHashes = new Map();
190
- for (const entry of saved?.namespace === namespace && Array.isArray(saved.entries) ? saved.entries : []) if (await valid(entry, startupHashes)) { entries.set(entry.path, entry); link(entry); }
190
+ if (saved?.namespace === namespace && Array.isArray(saved.entries)) {
191
+ for (let i = 0; i < saved.entries.length; i += 16) {
192
+ const batch = saved.entries.slice(i, i + 16);
193
+ const verified = await Promise.all(batch.map(entry => valid(entry, startupHashes)));
194
+ batch.forEach((entry, index) => {
195
+ if (verified[index]) { entries.set(entry.path, entry); link(entry); }
196
+ });
197
+ }
198
+ }
191
199
  } catch (error) { if (error.code !== 'ENOENT' && !(error instanceof SyntaxError)) throw error; }
192
200
  await trimDisk();
193
201
  async function loadPayload(hash) {
@@ -2,6 +2,7 @@ import { parentPort } from 'node:worker_threads';
2
2
  import { createHash } from 'node:crypto';
3
3
  import { realpathSync } from 'node:fs';
4
4
  import path from 'node:path';
5
+ import { captureFrameOrigins } from './runtime.mjs';
5
6
  import { buildSource } from './build.mjs';
6
7
  import { createArchBrowser } from './arch-browser.mjs';
7
8
 
@@ -17,10 +18,15 @@ parentPort.on('message', async ({ id, config, name, type }) => {
17
18
  }
18
19
  if (shuttingDown) return;
19
20
  try {
21
+ const origins = config.frameOrigins && captureFrameOrigins();
20
22
  const snapshot = new Map();
21
23
  const build = async browser => config.overlay && name.endsWith('.mmd') ? (await import('./arch-overlay.mjs')).buildOverlay(config,path.join(config.root,name),{base:config.overlay,browser,snapshot}) : buildSource(config, path.join(name.endsWith('.mmd')?config.root:config.design, name), { write: false, snapshot, browser, allowLegacy: config.allowLegacy ?? true });
22
24
  const built = await (name.endsWith('.mmd') ? archBrowser.run(build) : build());
23
25
  const frames = JSON.parse(JSON.stringify(built.frames.map(({ document, ...frame }) => frame)));
26
+ if (origins) built.frames.forEach((frame,i) => {
27
+ const origin = origins.get(frame);
28
+ if (origin) frames[i].declaration = {source:path.relative(config.root,path.resolve(origin.fileName)), line:origin.lineNumber,column:origin.columnNumber};
29
+ });
24
30
  const designRoot = realpathSync(config.design);
25
31
  const dependencies = [...new Set(built.dependencies.map(file => path.relative(file.startsWith(designRoot + path.sep) ? designRoot : config.design, file).split(path.sep).join('/')))].sort();
26
32
  const dependencyHashes = Object.fromEntries(dependencies.map(name => {
@@ -6,6 +6,7 @@ import path from 'node:path';
6
6
  import { fileURLToPath, pathToFileURL } from 'node:url';
7
7
  import { loadTokens, refreshTypes, rejectLegacy, relative, isSourcePath, sourceDirectories, isFeatureInternal } from './project.mjs';
8
8
  import { themeCss, parseTokens } from './tokens.mjs';
9
+ import { motionPrimitives, motionTokenCss } from './motion-primitives.mjs';
9
10
  import { componentOwner } from './runtime.mjs';
10
11
  import { CliError, classifyError } from '../cli-output.mjs';
11
12
  import { frameDocument } from './frame-document.mjs';
@@ -91,17 +92,18 @@ export async function buildSource(config, file, options = {}) {
91
92
  throw new CliError(code === 'INTERNAL_ERROR' ? 'SOURCE_BUILD_FAILED' : code, error.message, { cause: error });
92
93
  }
93
94
  }
94
- async function buildDesignSource(config, file, { write = true, allowLegacy = true, snapshot, browser } = {}) {
95
+ async function buildDesignSource(config, file, { write = true, allowLegacy = true, snapshot, browser, files, framesOnly = false } = {}) {
95
96
  if (file.endsWith('.mmd')) return (await import('./arch.mjs')).buildArch(config,file,{snapshot,browser});
96
97
  if (write) refreshTypes(config);
97
98
  const read = (name, encoding) => {
99
+ if (files) return files.read(name, encoding);
98
100
  if (!snapshot) return readFileSync(name, encoding);
99
101
  if (!snapshot.has(name)) snapshot.set(name, readFileSync(name));
100
102
  const value = snapshot.get(name);
101
103
  return encoding ? value.toString(encoding) : value;
102
104
  };
103
- file = realpathSync(file);
104
- const base = realpathSync(config.design), dependencies = new Set();
105
+ file = files ? path.resolve(file) : realpathSync(file);
106
+ const base = files ? path.resolve(config.design) : realpathSync(config.design), dependencies = new Set();
105
107
  const imports = new Set(), sources = sourceDirectories(config);
106
108
  const result = await build({ entryPoints: [file], bundle: true, write: false, format: 'esm', platform: 'node', jsx: 'automatic', jsxImportSource: 'adg', jsxDev: true, metafile: true, logLevel: 'silent', plugins: [{ name: 'adg-sources', setup(api) {
107
109
  api.onResolve({ filter: /.*/ }, args => {
@@ -112,9 +114,9 @@ async function buildDesignSource(config, file, { write = true, allowLegacy = tru
112
114
  const url = args.path.endsWith('?url');
113
115
  const requested = url ? args.path.slice(0,-4) : args.path;
114
116
  let resolved = args.kind === 'entry-point' ? path.resolve(requested) : path.resolve(args.resolveDir, requested);
115
- resolved = [resolved, ...['.tsx','.ts','.js','/index.tsx','/index.ts','/index.js'].map(ext => resolved + ext)].find(candidate => statSync(candidate, { throwIfNoEntry: false })?.isFile());
117
+ resolved = [resolved, ...['.tsx','.ts','.js','/index.tsx','/index.ts','/index.js'].map(ext => resolved + ext)].find(candidate => files ? files.has(candidate) : statSync(candidate, { throwIfNoEntry: false })?.isFile());
116
118
  if (!resolved) return { errors: [{ text: `Cannot resolve ${args.path}` }] };
117
- resolved = realpathSync(resolved);
119
+ if (!files) resolved = realpathSync(resolved);
118
120
  if (!resolved.startsWith(base + path.sep)) return { errors: [{ text: `Import ${args.path} leaves design/; move it inside design/` }] };
119
121
  if (!allowLegacy) rejectLegacy(config, [path.join(config.design, path.relative(base, resolved))]);
120
122
  dependencies.add(resolved);
@@ -123,7 +125,7 @@ async function buildDesignSource(config, file, { write = true, allowLegacy = tru
123
125
  if (url && !resolved.startsWith(path.join(base,'art')+path.sep)) return {errors:[{text:'?url imports must be under design/art/'}]};
124
126
  return { path: resolved, ...(url ? {namespace:'art-url'} : {}) };
125
127
  });
126
- api.onLoad({filter:/.*/,namespace:'art-bytes'}, args => ({contents:read(args.path),loader:'dataurl'}));
128
+ api.onLoad({filter:/.*/,namespace:'art-bytes'}, async args => ({contents:await read(args.path),loader:'dataurl'}));
127
129
  const artModule = file => {
128
130
  const source=path.relative(base,file).split(path.sep).join('/');
129
131
  return {contents:`import data from ${JSON.stringify('adg:art-bytes:'+file)};import {registerArtwork} from 'adg';export default registerArtwork(data,${JSON.stringify(source)});`,loader:'js'};
@@ -131,14 +133,14 @@ async function buildDesignSource(config, file, { write = true, allowLegacy = tru
131
133
  api.onLoad({filter:/.*/,namespace:'art-url'}, args => artModule(args.path));
132
134
  api.onLoad({filter:/\.tsx$/}, async args => {
133
135
  const sourcePath = path.relative(base, args.path).split(path.sep).join('/');
134
- if (!isSourcePath(sourcePath, sources)) return snapshot ? {contents:read(args.path,'utf8'),loader:'tsx'} : undefined;
135
- const original=read(args.path,'utf8');
136
+ if (!isSourcePath(sourcePath, sources)) return files || snapshot ? {contents:await read(args.path,'utf8'),loader:'tsx'} : undefined;
137
+ const original=await read(args.path,'utf8');
136
138
  return registeredSource(args.path, sourcePath, original);
137
139
  });
138
- if (snapshot) api.onLoad({filter:/\.(?:[cm]?js|jsx|ts|json)$/}, args => ({contents:read(args.path,'utf8'),loader:args.path.endsWith('.ts')?'ts':args.path.endsWith('.jsx')?'jsx':args.path.endsWith('.json')?'json':'js'}));
140
+ if (snapshot || files) api.onLoad({filter:/\.(?:[cm]?js|jsx|ts|json)$/}, async args => ({contents:await read(args.path,'utf8'),loader:args.path.endsWith('.ts')?'ts':args.path.endsWith('.jsx')?'jsx':args.path.endsWith('.json')?'json':'js'}));
139
141
  api.onLoad({ filter: /\.(png|jpe?g|webp)$/i }, args => artModule(args.path));
140
- api.onLoad({ filter: /\.svg$/i }, args => {
141
- const source = read(args.path,'utf8');
142
+ api.onLoad({ filter: /\.svg$/i }, async args => {
143
+ const source = await read(args.path,'utf8');
142
144
  const forbidden = /<(?:style|script)\b|\s(?:on[\w-]+|className)\s*=/i.exec(source);
143
145
  if (forbidden) { const before=source.slice(0,forbidden.index); return {errors:[{text:'Forbidden SVG markup; remove styles, scripts and event attributes',location:{file:args.path,line:before.split('\n').length,column:before.length-before.lastIndexOf('\n')-1}}]}; }
144
146
  return { contents: `import { artwork } from 'adg'; export default props => artwork(${JSON.stringify(source)}, props, ${JSON.stringify(path.relative(base,args.path).split(path.sep).join('/'))});`, loader:'js' };
@@ -160,7 +162,7 @@ async function buildDesignSource(config, file, { write = true, allowLegacy = tru
160
162
  }).sort();
161
163
  const internal = isFeatureInternal(sourceName, sources);
162
164
  if (internal) {
163
- const original = read(file, 'utf8');
165
+ const original = await read(file, 'utf8');
164
166
  if (/export\s+default[\s\S]*<Frame\b/.test(original)) throw Error(`${relative(config,file)}: feature-internal source must not export Frame defaults; move frames to index.tsx`);
165
167
  return { frames: [], parts, dependencies: [...dependencies], imports: [...imports].sort(), css: '', tokenCss: '', cssWithoutTokens: '', cssBeforeTokens: '', cssAfterTokens: '' };
166
168
  }
@@ -172,19 +174,23 @@ async function buildDesignSource(config, file, { write = true, allowLegacy = tru
172
174
  try { validateFrame(frame); if (names.has(frame.name)) throw Error(`Duplicate frame name ${frame.name}`); names.add(frame.name); }
173
175
  catch(error) { throw Error(`${relative(config,file)}: ${frame?.name ?? '-'}: ${error.message}`); }
174
176
  }
177
+ if (framesOnly) return { frames };
175
178
  const tokenFile = path.join(base, 'tokens.css');
176
179
  dependencies.add(tokenFile);
177
- const tokenSource = read(tokenFile,'utf8'), tokens = snapshot ? parseTokens(tokenSource) : loadTokens(config);
180
+ const tokenSource = await read(tokenFile,'utf8'), tokens = snapshot ? parseTokens(tokenSource) : loadTokens(config);
178
181
  const compiler = await compile(`${readFileSync(path.join(tailwind,'theme.css'),'utf8')}\n${themeCss(tokens)}\n${readFileSync(path.join(tailwind,'preflight.css'),'utf8')}\n@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));\n@tailwind utilities;`);
179
182
  const classes = [...new Set(frames.flatMap(f => [...f.html.matchAll(/\bclass="([^"]*)"/g)].flatMap(m => m[1].split(/\s+/))))];
180
183
  const utilities = compiler.build(classes);
181
184
  const defaults = 'html,body{margin:0;font-family:var(--font-ui);color:var(--text);background:var(--canvas)}[data-adg-frame]{display:flex;align-items:flex-start;position:relative;background:var(--canvas)}[data-adg-frame]>*,svg{flex-shrink:0} @media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important}}';
182
- const css = `${utilities}\n${tokenSource}\n${defaults}`;
185
+ const hasSprings = [...tokens.light.keys()].some(name => /^--motion-spring-.+-(?:duration|bounce)$/.test(name));
186
+ const generated = hasSprings ? motionTokenCss(motionPrimitives(tokens).generated) : '';
187
+ const cssAfterTokens = `\n${generated}${defaults}`;
188
+ const css = `${utilities}\n${tokenSource}${cssAfterTokens}`;
183
189
  for (const frame of frames) {
184
190
  frame.document = theme => frameDocument(frame, theme, css);
185
191
  if (write) { const destination = path.join(config.output, path.relative(base,file).replace(/\.tsx$/, ''), `${encodeURIComponent(frame.name)}.html`); mkdirSync(path.dirname(destination),{recursive:true}); writeFileSync(destination,frame.document('light')); }
186
192
  }
187
193
  return { ...(observationDynamic?{observationDynamic:true}:{}), frames, parts, dependencies: [...dependencies], imports: [...imports].sort(), css,
188
- tokenCss: tokenSource, cssWithoutTokens: `${utilities}\n${defaults}`,
189
- cssBeforeTokens: `${utilities}\n`, cssAfterTokens: `\n${defaults}` };
194
+ tokenCss: tokenSource, cssWithoutTokens: `${utilities}${cssAfterTokens}`,
195
+ cssBeforeTokens: `${utilities}\n`, cssAfterTokens };
190
196
  }