@whzxc/agent-design-gallery 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -55,6 +55,8 @@ adg render components/button --frame=disabled --theme=dark --out-dir=output/revi
55
55
 
56
56
  Use the independent link in a change report. Add the path link when the surrounding assets matter. Use the project URL on a hub the recipient can reach. `adg open` provides a live loopback preview while its server runs. `render` exports exact frame PNGs for attachments or automation. Without `--theme`, it exports both themes. See the [review handoff workflow](docs/design-toolkit.md#review-handoff).
57
57
 
58
+ Every command accepts `--json`: finite commands return one versioned envelope, while foreground `open`/`serve` stream NDJSON events. `render` PNGs are in `data.captures`, with CSS and PNG pixel dimensions. See the [agent CLI interface](docs/agent-interface.md) for schemas, exits and recovery actions.
59
+
58
60
  The rightmost toolbar button opens the Inspector for the selected node. It starts closed and overlays the canvas. It follows the selection and shows source path, frame name, dimensions, frames, and discovered **Uses** / **Used by** relationships. Indirect relationships are muted with their shortest `via` path. Click a relationship to focus the source, or to open it by itself when outside the current scope. An element selection shows its owning export and matching frames from the current scope. `GET /relationships` explicitly computes the complete direct graph as JSON, keyed by source path with `uses` and `usedBy` arrays.
59
61
 
60
62
  Click a canvas source or frame title to select it and copy its name. The copy icon copies without changing the selection and appears on hover or keyboard focus. Section titles also copy their names. Enter and Space activate a focused title. A check confirms a successful copy for 1.2 seconds. The inspector has separate source-path and frame-name copy controls.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whzxc/agent-design-gallery",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Local TSX design toolkit and SVG viewer",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/public/app.js CHANGED
@@ -9,6 +9,9 @@ import { sourceRelationships, relatedSources } from './relationships.js';
9
9
  import { hitSelection, frameBox, exportFrames } from './selection.js';
10
10
  import { groupTokens, renderTokenTable } from './token-catalog.js';
11
11
  import { readViewRoute, viewURL } from './view-route.js';
12
+ import { createArranger } from './arrangement.js';
13
+ const arranger = createArranger();
14
+ window.addEventListener('pagehide',()=>arranger.close());
12
15
  // ARC's gallery layout and camera model, decoupled from its React runtime.
13
16
  const $ = (selector) => document.querySelector(selector);
14
17
  const viewport = $(".gallery-viewport"),
@@ -335,10 +338,12 @@ function save() {
335
338
  }
336
339
  window.addEventListener('pagehide', () => void persistPreferences(true));
337
340
  document.addEventListener('visibilitychange', () => {if (document.hidden) void persistPreferences(true)});
338
- function layout(data, preserve = false) {
341
+ const layoutData = data => onlyFrame ? { ...data, assets: data.assets.map(asset => ({ ...asset, component: false, parts: asset.parts.filter(part => part.name === onlyFrame) })) } : data;
342
+ function layout(data, preserve = false, options = {}) {
343
+ const endArrangement = globalThis.__adgTiming?.span('arrangement', undefined, {sources:data.assets.length,provisional:!!options.provisional});
339
344
  const previous = assets,
340
345
  previousGroups = groups,
341
- result = arrange(onlyFrame ? { ...data, assets: data.assets.map(asset => ({ ...asset, component: false, parts: asset.parts.filter(part => part.name === onlyFrame) })) } : data);
346
+ result = arrange(layoutData(data),options);
342
347
  groups = result.groups;
343
348
  assets = result.items;
344
349
  world = result.world;
@@ -419,6 +424,8 @@ function layout(data, preserve = false) {
419
424
  );
420
425
  $("#empty").hidden = !!assets.length || !data.directory;
421
426
  if (!assets.length) $("#empty").textContent = scopedUI(data) ? 'No assets in this scope.' : 'No SVG files in this directory.';
427
+ endArrangement?.({items:assets.length});
428
+ if (assets.length) globalThis.__adgTiming?.mark('first-layout');
422
429
  }
423
430
  function makeRow(name, label, count, className = 'tree-row') {
424
431
  const button = document.createElement('button'); button.className = className;
@@ -781,6 +788,7 @@ function pump() {
781
788
  }
782
789
  }
783
790
  async function loadPreview(e) {
791
+ const endPreview = globalThis.__adgTiming?.span('preview', e.asset.path, {crop:e.part.id});
784
792
  let url,local=false;
785
793
  const theme=e.theme??effectiveTheme;
786
794
  const generated=async restore=>{
@@ -806,7 +814,8 @@ async function loadPreview(e) {
806
814
  if(cache.get(e.key)!==e)return;
807
815
  while(moving)await new Promise(resolve=>setTimeout(resolve,16));
808
816
  const img=new Image();e.image=img;img.decoding='async';img.src=source;
809
- await img.decode();e.state='ready';
817
+ const endDecode = globalThis.__adgTiming?.span('decode', e.asset.path, {crop:e.part.id});
818
+ try { await img.decode();e.state='ready'; } finally {endDecode?.();}
810
819
  };
811
820
  try {
812
821
  const cached=e.asset.hash&&e.asset.previewIds?.[theme]?.includes(e.part.id);
@@ -829,6 +838,7 @@ async function loadPreview(e) {
829
838
  if(failure.name!=='AbortError'&&cache.get(e.key)===e&&theme===effectiveTheme&&manifest?.assets.some(a=>a.path===e.asset.path&&a.version===e.asset.version))
830
839
  error(`Cannot render ${e.asset.path}: ${failure.message}`);
831
840
  } finally {
841
+ endPreview?.({state:e.state});
832
842
  if(local&&url)URL.revokeObjectURL(url);
833
843
  loading--;requestDraw(false);pump();
834
844
  }
@@ -871,12 +881,13 @@ function drawBackground() {
871
881
  }
872
882
  }
873
883
  function draw() {
884
+ const endDrawing = globalThis.__adgTiming?.span('drawing');
874
885
  raf = 0;
875
886
  drawBackground();
876
887
  if (tokenManifest) {
877
888
  window.__adg.ready = true;
878
889
  if (fixtureState) document.documentElement.dataset.fixtureReady = fixtureState.name;
879
- return;
890
+ endDrawing?.(); return;
880
891
  }
881
892
  if (!labelObstacles) readChromeBounds();
882
893
  const displayed = manifest?.renderTheme === effectiveTheme ? inspection ? [inspection] : assets : [];
@@ -927,6 +938,7 @@ function draw() {
927
938
  const sx = source.width / pos.part.width, sy = source.height / pos.part.height;
928
939
  ctx.drawImage(source, (left-pos.x)*sx, (top-pos.y)*sy, (right-left)*sx, (bottom-top)*sy, left, top, right-left, bottom-top);
929
940
  } else ctx.drawImage(source, pos.x, pos.y, pos.part.width, pos.part.height);
941
+ if (inViewport) globalThis.__adgTiming?.paint('first-content', {source:a.path,crop:pos.part.id});
930
942
  }
931
943
  ctx.restore();
932
944
  const chosen = selected === a.path && selectedForm === null;
@@ -943,10 +955,11 @@ function draw() {
943
955
  const percentage = `${Math.round(view.scale * 100)}%`;
944
956
  if (zoomValue.textContent !== percentage) zoomValue.textContent = percentage;
945
957
  if (zoomOutput.value !== percentage) zoomOutput.value = percentage;
946
- window.__adg.ready = !!manifest && !manifest.loading && manifest.renderTheme === effectiveTheme && drawingReady === drawingCount && !moving;
958
+ window.__adg.ready = !!manifest && !manifest.loading && manifest.renderTheme === effectiveTheme && drawingReady === drawingCount && !moving && !arranger.pending;
947
959
  if(fixtureState && fixtureApplied && window.__adg.ready) document.documentElement.dataset.fixtureReady=fixtureState.name;
948
960
  window.__adg.revision = manifest?.revision;
949
961
  window.__adg.visibleReady = drawingReady; window.__adg.visibleCount = drawingCount;
962
+ if (window.__adg.ready && drawingCount > 0) globalThis.__adgTiming?.paint('visible-ready', {count:drawingCount});
950
963
  drawMap();
951
964
  if(!moving&&queued.length)pump();
952
965
  if (cache.size > 100) {
@@ -954,6 +967,7 @@ function draw() {
954
967
  .flatMap(a => placements(a).map(({part}) => assetURL(a, part))));
955
968
  evictPreviews(cache, activeKeys);
956
969
  }
970
+ endDrawing?.();
957
971
  }
958
972
  function backgroundColor() { return backgroundChoice === 'theme' ? palette.canvas : backgroundColors[backgroundChoice]; }
959
973
 
@@ -1226,10 +1240,16 @@ $("#shortcuts").onclick = () => {
1226
1240
  $("#more-menu").hidePopover();
1227
1241
  $("#keys").showModal();
1228
1242
  };
1229
- $("#arrange").onclick = () => {
1243
+ $("#arrange").onclick = async () => {
1244
+ const data=manifest,previousCatalog=catalog;
1245
+ window.__adg.ready=false;
1246
+ let placed;
1247
+ try {if(!data.loading)placed=await arranger.arrange(layoutData(data));}
1248
+ catch(failure){if(failure.name!=='AbortError')error(failure.message);requestDraw();return;}
1249
+ if(manifest!==data || catalog!==previousCatalog || tokenManifest){requestDraw();return;}
1230
1250
  const old = assets,
1231
1251
  oldGroups = groups;
1232
- layout(manifest);
1252
+ layout(manifest,false,{placed,provisional:!!data.loading});
1233
1253
  if (active !== null) {
1234
1254
  const g = groups[active],
1235
1255
  prev = oldGroups[active],
@@ -1392,7 +1412,7 @@ async function applyManifest(data, force = false) {
1392
1412
  publishedCount=available.length;nextPublish=Math.max(publishedCount+1,publishedCount*2);
1393
1413
  if(streamView&&view!==streamView)streamMoved=true;
1394
1414
  manifest={...data,assets:available,renderTheme:versionTheme,loading:true};
1395
- layout(manifest,false);
1415
+ layout(manifest,false,{provisional:true});
1396
1416
  if(streaming&&!streamMoved){view=entry?.view??data.view??fitWorld(cameraArea(),data);streamView=view;}
1397
1417
  requestDraw();
1398
1418
  };
@@ -1402,7 +1422,7 @@ async function applyManifest(data, force = false) {
1402
1422
  if(metadata){results[i]=decorateMetadata(a,metadata);metadataCache.set(key,metadata);}
1403
1423
  }
1404
1424
  let completed=results.filter(Boolean).length;
1405
- if(streaming&&completed)publish();
1425
+ if(streaming&&completed&&completed<data.assets.length)publish();
1406
1426
  await Promise.all(Array.from({length:4},async()=>{
1407
1427
  while(next<data.assets.length) {
1408
1428
  signal?.throwIfAborted();
@@ -1430,6 +1450,13 @@ async function applyManifest(data, force = false) {
1430
1450
  if(publishFrame)cancelAnimationFrame(publishFrame);
1431
1451
  if(versionTheme!==effectiveTheme){pending=true;return;}
1432
1452
  signal?.throwIfAborted();
1453
+ const complete={...data,assets:results};
1454
+ const placed=await arranger.arrange(layoutData(complete),{signal,onPending:()=>{
1455
+ if(streaming&&completed>publishedCount)publish();
1456
+ }});
1457
+ if(versionTheme!==effectiveTheme){pending=true;return;}
1458
+ signal?.throwIfAborted();
1459
+ if(streamView&&view!==streamView)streamMoved=true;
1433
1460
  for(const [key,entry] of prepared)if(!data.assets.some(a=>key===sourceKey(a,versionTheme,data.directory)||key===sourceKey(a,versionTheme==='dark'?'light':'dark',data.directory)))prepared.delete(key);
1434
1461
  const live=new Set(data.assets.flatMap(a=>['light','dark'].map(t=>sourceKey(a,t,data.directory))));
1435
1462
  for(const key of metadataCache.keys())if(!live.has(key))metadataCache.delete(key);
@@ -1437,12 +1464,13 @@ async function applyManifest(data, force = false) {
1437
1464
  tokenManifest = null;
1438
1465
  // Early streamed worlds can use a much larger camera scale. Discard those
1439
1466
  // raster intermediates so the completed world starts at its exact final scale.
1440
- if(streaming&&publishedCount<data.assets.length)for(const entry of cache.values()){delete entry.bitmap;delete entry.bitmapScale;}
1467
+ if(streaming&&publishedCount)for(const entry of cache.values()){delete entry.bitmap;delete entry.bitmapScale;}
1441
1468
  catalog = null;
1442
1469
  layout(
1443
1470
  manifest,
1444
1471
  !first && !!previous &&
1445
1472
  JSON.stringify(previous.groups) === JSON.stringify(data.groups),
1473
+ {placed},
1446
1474
  );
1447
1475
  for(const element of document.querySelectorAll('.directory-name')) element.textContent=data.label;
1448
1476
  $("#app-directory").title=data.directory||'';
@@ -0,0 +1,11 @@
1
+ import { layoutWorld, packingSnapshot, restorePacking } from './layout.js';
2
+
3
+ self.onmessage = ({data:{id,input,packing}}) => {
4
+ try {
5
+ restorePacking(packing);
6
+ const start=performance.now(),placed=layoutWorld(input);
7
+ self.postMessage({id,placed,packing:packingSnapshot(),durationMs:performance.now()-start});
8
+ } catch(error) {
9
+ self.postMessage({id,error:error.message});
10
+ }
11
+ };
@@ -0,0 +1,49 @@
1
+ import { arrangementInput } from './assets.js';
2
+ import { packingSnapshot, restorePacking, layoutWorld } from './layout.js';
3
+
4
+ const aborted = () => new DOMException('Arrangement superseded', 'AbortError');
5
+
6
+ export function createArranger() {
7
+ let worker, nextId=0;
8
+ const pending=new Map();
9
+ function close(failure=aborted()) {
10
+ worker?.terminate();worker=undefined;
11
+ for(const task of pending.values())task.finish(failure);
12
+ pending.clear();
13
+ }
14
+ function start() {
15
+ if(worker)return;
16
+ worker=new Worker(new URL('./arrangement-worker.js',import.meta.url),{type:'module'});
17
+ worker.onmessage=({data})=>{
18
+ const task=pending.get(data.id);
19
+ if(!task)return;
20
+ if(data.error)task.finish(Error(`Cannot arrange designs: ${data.error}`));
21
+ else {restorePacking(data.packing);task.finish(null,data);}
22
+ };
23
+ worker.onerror=event=>close(Error(`Cannot start arrangement worker: ${event.message}`));
24
+ }
25
+ return {
26
+ close,
27
+ get pending() {return pending.size;},
28
+ arrange(data,{signal,onPending}={}) {
29
+ signal?.throwIfAborted();
30
+ const endProbe=globalThis.__adgTiming?.span('arrangement-cache-probe');
31
+ const input=arrangementInput(data),cached=layoutWorld(input,{cachedOnly:true});
32
+ endProbe?.({hit:!!cached});
33
+ if(cached)return Promise.resolve(cached);
34
+ onPending?.();
35
+ start();
36
+ const id=++nextId,end=globalThis.__adgTiming?.span('arrangement-wait');
37
+ return new Promise((resolve,reject)=>{
38
+ const abort=()=>close();
39
+ pending.set(id,{finish(failure,result){
40
+ pending.delete(id);signal?.removeEventListener('abort',abort);
41
+ end?.({workerMs:result?.durationMs});
42
+ failure?reject(failure):resolve(result.placed);
43
+ }});
44
+ signal?.addEventListener('abort',abort,{once:true});
45
+ worker.postMessage({id,input,packing:packingSnapshot()});
46
+ });
47
+ },
48
+ };
49
+ }
package/public/assets.js CHANGED
@@ -122,6 +122,7 @@ export function compactPreparedSource(asset) {
122
122
  }
123
123
 
124
124
  export function imageURL(asset, crop, onSource) {
125
+ const endPreview = globalThis.__adgTiming?.span('preview-generation', asset.path, {crop:crop?.id});
125
126
  if (!crop)
126
127
  return URL.createObjectURL(
127
128
  new Blob([asset.source], { type: "image/svg+xml" }),
@@ -169,7 +170,9 @@ export function imageURL(asset, crop, onSource) {
169
170
  root.setAttribute("height", crop.height);
170
171
  const rendered=new XMLSerializer().serializeToString(doc);
171
172
  onSource?.(rendered);
172
- return URL.createObjectURL(new Blob([rendered], {type:"image/svg+xml"}));
173
+ const url = URL.createObjectURL(new Blob([rendered], {type:"image/svg+xml"}));
174
+ endPreview?.();
175
+ return url;
173
176
  }
174
177
 
175
178
  // Keep current visible previews and a small LRU of offscreen previews. Identity
@@ -247,9 +250,15 @@ export function resolveScope(data, layers, requested) {
247
250
  }
248
251
 
249
252
 
250
- export function arrange(data) {
253
+ export function arrangementInput(data) {
254
+ return groupAssets(data).map(group => ({blocks:group.assets.map(blockForAsset)}));
255
+ }
256
+
257
+ export function arrange(data, { provisional = false, placed } = {}) {
251
258
  const grouped = groupAssets(data);
252
- const sections = layoutWorld(grouped.map(g => ({ ...g, blocks: g.assets.map(blockForAsset) })));
259
+ const sections = placed
260
+ ? placed.map((section,index) => ({...grouped[index],...section}))
261
+ : layoutWorld(grouped.map(g => ({ ...g, blocks: g.assets.map(blockForAsset) })), {provisional});
253
262
  const groups = sections.map(s => ({ ...s, width: s.w, height: s.h }));
254
263
  const items = [];
255
264
  for (const [group, section] of groups.entries()) {
@@ -272,6 +281,7 @@ function formDocument(form,css,theme) {
272
281
  return `<!doctype html><html data-theme="${theme}"><head><meta charset="utf-8"><style>${css.replace(/<\/style/gi,'<\\/style')}</style></head><body><div data-adg-frame="${escape(form.name)}" style="${form.width ? `width:${form.width}px;` : 'width:max-content;'}${form.height ? `height:${form.height}px;` : ''}">${form.html}</div></body></html>`;
273
282
  }
274
283
  async function prepareSource(asset, built, theme, signal) {
284
+ const endMeasurement = globalThis.__adgTiming?.span('measurement', asset.path, {frames:built.frames.length});
275
285
  const parts = [];
276
286
  const frame = document.createElement('iframe');
277
287
  frame.setAttribute('sandbox','allow-same-origin');
@@ -280,6 +290,7 @@ async function prepareSource(asset, built, theme, signal) {
280
290
  try {
281
291
  let sliceStart=performance.now();
282
292
  for (const [index, form] of built.frames.entries()) {
293
+ const endFrame = globalThis.__adgTiming?.span('measurement-frame', asset.path, {frame:form.name});
283
294
  signal?.throwIfAborted();
284
295
  if(performance.now()-sliceStart>8) {
285
296
  await (globalThis.scheduler?.yield?.()??new Promise(resolve=>setTimeout(resolve,0)));
@@ -320,6 +331,7 @@ async function prepareSource(asset, built, theme, signal) {
320
331
  content.setAttribute('style','font:16px/1.5 var(--font-ui);color:var(--text);');
321
332
  content.append(frame.contentDocument.querySelector('style').cloneNode(true),shell.cloneNode(true));
322
333
  parts.push({id:String(index),name:form.name,note:form.note,width:box.width,height:box.height,elements,markup:new XMLSerializer().serializeToString(content)});
334
+ endFrame?.();
323
335
  }
324
336
  const wrapWidth = built.component ? componentWrapWidth(parts) : Infinity;
325
337
  let x=0,y=0,rowHeight=0;
@@ -340,5 +352,5 @@ async function prepareSource(asset, built, theme, signal) {
340
352
  });
341
353
  const source=header+markup.join('')+'</svg>';
342
354
  return {...asset,imports:built.imports,format:'tsx',source,frameRanges,full:{x:0,y:0,width,height},parts:parts.map(({markup,...p})=>p),component:built.component,background:frame.contentWindow.getComputedStyle(frame.contentDocument.documentElement).getPropertyValue('--canvas').trim()};
343
- } finally { frame.remove(); }
355
+ } finally { frame.remove(); endMeasurement?.(); }
344
356
  }
package/public/layout.js CHANGED
@@ -14,17 +14,25 @@ export function rows(blocks, limit, gapX, gapY, nextWidth) {
14
14
  });
15
15
  }
16
16
  export function skyline(blocks, limit, nextWidth, gapX = 64, gapY = 112) {
17
- const placed = [], result = [];
17
+ const lefts = [], rights = [], bottoms = [], result = [];
18
18
  // Pack tall blocks first, but keep returned identities in source order for
19
19
  // navigation, selection and incremental placement across geometry changes.
20
+ // Candidate ties prefer lower y, then lower x. Occupied edges keep exact Float arithmetic.
20
21
  const ordered = blocks.map((block, index) => ({ block, index }))
21
22
  .sort((a, b) => b.block.h - a.block.h || b.block.w - a.block.w || a.index - b.index);
22
23
  for (const { block, index } of ordered) {
23
- const candidates = [0, ...placed.map(p => p.x + p.w + gapX)].filter(x => { if (x + block.w <= limit) return true; nextWidth?.(x + block.w); return false; });
24
- const positions = candidates.map(x => ({ x, y: Math.max(0, ...placed.filter(p => x < p.x + p.w + gapX && x + block.w + gapX > p.x).map(p => p.y + p.h + gapY)) }));
25
- positions.sort((a, b) => a.y - b.y || a.x - b.x);
26
- result[index] = { ...block, ...positions[0] };
27
- placed.push(result[index]);
24
+ let bestX=Infinity,bestY=Infinity;
25
+ for(let candidate=0;candidate<=lefts.length;candidate++) {
26
+ const x=candidate ? rights[candidate-1] : 0,edge=x+block.w;
27
+ if(edge>limit){nextWidth?.(edge);continue;}
28
+ const right=edge+gapX;
29
+ let y=0;
30
+ for(let i=0;i<lefts.length;i++)
31
+ if(x<rights[i] && right>lefts[i])y=Math.max(y,bottoms[i]);
32
+ if(y<bestY || (y===bestY && x<bestX)){bestX=x;bestY=y;}
33
+ }
34
+ result[index] = { ...block, x:bestX, y:bestY };
35
+ lefts.push(bestX);rights.push(bestX+block.w+gapX);bottoms.push(bestY+block.h+gapY);
28
36
  }
29
37
  return result;
30
38
  }
@@ -38,11 +46,12 @@ export function restorePacking(entries=[]) {
38
46
  while(widthChoices.size>32)widthChoices.delete(widthChoices.keys().next().value);
39
47
  }
40
48
  const aspectPenalty = 0.6;
41
- function chooseWidth(blocks, step, ratio, gapX, gapY) {
49
+ function chooseWidth(blocks, step, ratio, gapX, gapY, cachedOnly = false) {
42
50
  if (!blocks.length) return [];
43
51
  const pack = (limit, nextWidth) => skyline(blocks, limit, nextWidth, gapX, gapY);
44
52
  const key = JSON.stringify(['area-skyline-v1', step, ratio, aspectPenalty, gapX, gapY, blocks.map(b => [b.kind, b.w, b.h])]);
45
53
  if (widthChoices.has(key)) return pack(widthChoices.get(key));
54
+ if (cachedOnly) return null;
46
55
  const minimum = Math.max(...blocks.map(b => b.w));
47
56
  const maximum = blocks.reduce((n, b) => n + b.w, 0) + blocks.length * gapX;
48
57
  // Browser layout widths are exact multiples of 1/64px. Skip only on that
@@ -66,13 +75,20 @@ function chooseWidth(blocks, step, ratio, gapX, gapY) {
66
75
  }
67
76
  return best;
68
77
  }
69
- export function layoutWorld(input) {
70
- const sections = input.map(section => {
71
- const blocks = chooseWidth(section.blocks, 50, 1.6, 64, 112);
78
+ export function layoutWorld(input, { provisional = false, cachedOnly = false } = {}) {
79
+ const place = provisional ? (blocks, step, ratio, gapX, gapY) => {
80
+ const area = blocks.reduce((sum, block) => sum + (block.w + gapX) * (block.h + gapY), 0);
81
+ return rows(blocks, Math.max(1, ...blocks.map(block => block.w), Math.sqrt(area * ratio)), gapX, gapY);
82
+ } : (...args) => chooseWidth(...args, cachedOnly);
83
+ const sections = [];
84
+ for (const section of input) {
85
+ const blocks = place(section.blocks, 50, 1.6, 64, 112);
86
+ if (!blocks) return null;
72
87
  const box = bounds(blocks);
73
- return { ...section, blocks, w: box.w + 128, h: box.h + 168 };
74
- });
75
- const placed = chooseWidth(sections, 100, 1.5, 240, 240);
88
+ sections.push({ ...section, blocks, w: box.w + 128, h: box.h + 168 });
89
+ }
90
+ const placed = place(sections, 100, 1.5, 240, 240);
91
+ if (!placed) return null;
76
92
  return placed.map(section => ({ ...section, blocks: section.blocks.map(block => {
77
93
  const x = section.x + 64 + block.x, y = section.y + 104 + block.y;
78
94
  return { ...block, x, y, ...(block.frames ? { frames: block.frames.map(frame => ({ ...frame, x: x + frame.x, y: y + frame.y })) } : {}) };
@@ -0,0 +1,236 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { stripVTControlCharacters } from 'node:util';
3
+ import { AsyncLocalStorage } from 'node:async_hooks';
4
+
5
+ /** @typedef {{argv: string[], reason: string}} NextAction */
6
+ /** @typedef {{code: string, message: string, next: NextAction[]}} Diagnostic */
7
+ /** @typedef {keyof typeof errorCatalog} ErrorCode */
8
+ /** @typedef {{schemaVersion: 1, command: string, ok: boolean, data: unknown, warnings: Diagnostic[], error: Diagnostic | null}} Envelope */
9
+ /** @typedef {{command?: string, project?: string, stateDirectory?: string, gitCause?: 'repository' | 'revision' | 'read', positionals?: string[], values?: Record<string, string | string[] | boolean>, failureCode?: ErrorCode}} ErrorContext */
10
+ /** @typedef {{json: boolean, command: string, revealKey?: boolean, stdout?: (text: string) => void, stderr?: (text: string) => void}} OutputOptions */
11
+
12
+ // Recovery kinds keep the catalog declarative; actions are constructed from known operands.
13
+ /** @satisfies {Record<string, [number, string, string]>} */
14
+ export const errorCatalog = {
15
+ USAGE_INVALID: [2, 'help', 'Read command arguments.'],
16
+ CONFIG_INVALID: [2, 'check', 'Recheck after fixing configuration.'],
17
+ TOKENS_INVALID: [2, 'check', 'Recheck after repairing tokens.css.'],
18
+ MIGRATION_REQUIRED: [2, 'migrate', 'Migrate the legacy project.'],
19
+ MIGRATION_CONFLICT: [2, 'migration', 'Inspect migration inputs before resolving the conflict.'],
20
+ VERSION_UNSATISFIED: [2, 'install', 'Install a version satisfying project requires.'],
21
+ DIRECTORY_NOT_FOUND: [2, 'help', 'Choose an existing directory.'],
22
+ PROJECT_NOT_FOUND: [2, 'migrate-help', 'Select the project root.'],
23
+ SOURCE_NOT_FOUND: [2, 'check-help', 'Choose a discovered source inside the project.'],
24
+ FRAME_NOT_FOUND: [2, 'render-help', 'Choose a declared frame in the selected sources.'],
25
+ ROOT_NOT_REGISTERED: [2, 'roots', 'Read registered roots.'],
26
+ LEGACY_SOURCE: [2, 'check', 'Recheck after converting the SVG source to TSX.'],
27
+ SOURCE_BUILD_FAILED: [2, 'check', 'Read source diagnostics after repairing the source.'],
28
+ GIT_UNAVAILABLE: [2, 'git-version', 'Verify Git after installing it.'],
29
+ GIT_BASE_INVALID: [2, 'git', 'Inspect the project repository and base revision.'],
30
+ CHECK_FAILED: [1, 'check', 'Recheck after fixing findings.'],
31
+ COMPARE_FAILED: [1, 'compare', 'Compare again after reviewing the reports.'],
32
+ PLAYWRIGHT_UNAVAILABLE: [2, 'install', 'Restore the packaged browser dependency.'],
33
+ CHROMIUM_UNAVAILABLE: [2, 'chromium', 'Install Chromium matching ADG\'s Playwright.'],
34
+ BROWSER_FAILED: [2, 'chromium', 'Repair Chromium before retrying.'],
35
+ RENDER_FAILED: [2, 'check', 'Inspect frame execution diagnostics.'],
36
+ COMPARE_TARGET_NOT_FOUND: [2, 'compare', 'Retry after repairing the fixture target.'],
37
+ COMPARE_ADAPTER_FAILED: [2, 'compare', 'Retry after repairing the adapter callback.'],
38
+ COMPARE_UNSETTLED: [2, 'compare', 'Retry after stabilizing fixture readiness.'],
39
+ STATE_INVALID: [2, 'help', 'Inspect the reported state file before retrying.'],
40
+ HUB_KEY_INVALID: [2, 'rotate', 'Replace the invalid key; existing access will expire.'],
41
+ SERVICE_UNSUPPORTED: [2, 'serve-help', 'Use a foreground hub on this platform.'],
42
+ SERVICE_ALREADY_INSTALLED: [2, 'status', 'Inspect the existing installation.'],
43
+ SERVICE_FAILED: [2, 'logs', 'Inspect service diagnostics before retrying.'],
44
+ WATCH_FAILED: [2, 'check', 'Inspect project inputs before reopening the viewer.'],
45
+ SHUTDOWN_FAILED: [2, 'help', 'Inspect the reported resource before retrying.'],
46
+ PORT_IN_USE: [2, 'help', 'Choose an unused port.'],
47
+ NETWORK_FAILED: [2, 'compare', 'Retry after restoring fixture connectivity.'],
48
+ AUTH_REQUIRED: [2, 'compare', 'Retry after providing fixture access.'],
49
+ IO_FAILED: [2, 'help', 'Repair access to the reported path before retrying.'],
50
+ INTERNAL_ERROR: [2, 'version', 'Record the runtime version with the diagnostic.'],
51
+ };
52
+
53
+ export class CliError extends Error {
54
+ /** @param {ErrorCode} code @param {string} message @param {{data?: unknown, cause?: unknown, context?: ErrorContext, warnings?: Diagnostic[], humanReported?: boolean}} [options] */
55
+ constructor(code, message, { data = null, cause, context = {}, warnings = [], humanReported = false } = {}) {
56
+ super(message, { cause });
57
+ this.name = 'CliError';
58
+ this.code = code;
59
+ this.data = data;
60
+ this.context = context;
61
+ this.warnings = warnings;
62
+ this.humanReported = humanReported;
63
+ }
64
+ }
65
+
66
+ const canonicalCommands = new Set([
67
+ 'open', 'link', 'serve', 'root', 'service', 'migrate', 'init', 'check', 'render', 'compare',
68
+ 'root add', 'root remove', 'root list', 'root scan',
69
+ 'service install', 'service uninstall', 'service status', 'service logs', 'service migrate',
70
+ 'help', 'version', 'adg',
71
+ ]);
72
+ const playwrightVersion = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).dependencies.playwright;
73
+
74
+ /** Sanitize strings before either diagnostic channel; never stringify raw errors/configs. @param {string} text */
75
+ export function sanitize(text) {
76
+ return stripVTControlCharacters(text)
77
+ .replace(/\b(?:adg|sdg)_[a-f0-9]{64}\b/gi, '[REDACTED]')
78
+ .replace(/(\bBearer\s+)[^\s"'<>]+/gi, '$1[REDACTED]')
79
+ .replace(/(\b(?:X-(?:ADG|SDG)-Key|authorization)["']?\s*[:=]\s*["']?)[^\s"',}<>]+/gi, '$1[REDACTED]')
80
+ .replace(/(https?:\/\/)[^\s/@]+(?::[^\s/@]*)?@/gi, '$1[REDACTED]@')
81
+ .replace(/([?&](?:key|token|access_token|api_key|authorization)=)[^&#\s"'<>]*/gi, '$1[REDACTED]');
82
+ }
83
+
84
+ /** @param {string} [command] */
85
+ function helpArgv(command = 'adg') {
86
+ return ['adg', ...(canonicalCommands.has(command) && !['adg', 'help', 'version'].includes(command) ? command.split(' ') : []), '--help', '--json'];
87
+ }
88
+
89
+ /** @param {ErrorCode} code @param {ErrorContext} [context] @returns {NextAction[]} */
90
+ export function nextActions(code, context = {}) {
91
+ const [, recovery, reason] = errorCatalog[code];
92
+ const state = context.stateDirectory ? ['--state-dir', context.stateDirectory] : [];
93
+ let argv;
94
+ switch (recovery) {
95
+ case 'check': argv = ['adg', 'check', '--read-only', '--json', ...(context.positionals?.length && context.command === 'check' ? ['--', ...context.positionals] : [])]; break;
96
+ case 'install': argv = ['npm', 'install', '-g', '@whzxc/agent-design-gallery']; break;
97
+ case 'migrate': argv = context.project ? ['adg', 'migrate', context.project, '--json'] : helpArgv('migrate'); break;
98
+ case 'migration': argv = context.command === 'service migrate' ? ['adg', 'service', 'status', ...state, '--json'] : helpArgv('migrate'); break;
99
+ case 'migrate-help': argv = helpArgv('migrate'); break;
100
+ case 'check-help': argv = helpArgv('check'); break;
101
+ case 'render-help': argv = helpArgv('render'); break;
102
+ case 'serve-help': argv = helpArgv('serve'); break;
103
+ case 'roots': argv = ['adg', 'root', 'list', ...state, '--json']; break;
104
+ case 'rotate': argv = ['adg', 'serve', '--rotate-key', ...state, '--json']; break;
105
+ case 'status': argv = ['adg', 'service', 'status', ...state, '--json']; break;
106
+ case 'logs': argv = ['adg', 'service', 'logs', ...state, '--json']; break;
107
+ case 'version': argv = ['adg', '--version', '--json']; break;
108
+ case 'git-version': argv = ['git', '--version']; break;
109
+ case 'git': {
110
+ const operation = context.gitCause === 'revision' ? ['log', '-5', '--oneline'] : context.gitCause === 'read' ? ['status', '--short'] : ['rev-parse', '--show-toplevel'];
111
+ argv = context.project ? ['git', '-C', context.project, ...operation] : helpArgv(context.command);
112
+ break;
113
+ }
114
+ case 'chromium': argv = ['npx', `playwright@${playwrightVersion}`, 'install', 'chromium']; break;
115
+ case 'compare': {
116
+ const values = context.values ?? {}, sources = context.positionals ?? [];
117
+ if (context.command !== 'compare' || (!values.all && (sources.length !== 1 || typeof values.frame !== 'string' || !values.frame))) {
118
+ argv = helpArgv(context.command);
119
+ break;
120
+ }
121
+ argv = ['adg', 'compare'];
122
+ if (values.all) argv.push('--all');
123
+ else {
124
+ // Attached values preserve literal operands starting with '-'.
125
+ for (const key of ['frame', 'fixture', 'region', 'selector', 'origin', 'viewport']) {
126
+ if (typeof values[key] === 'string') argv.push(`--${key}=${values[key]}`);
127
+ }
128
+ if (values.page) argv.push('--page');
129
+ for (const click of Array.isArray(values.click) ? values.click : []) argv.push(`--click=${click}`);
130
+ argv.push('--json', '--', sources[0]);
131
+ break;
132
+ }
133
+ argv.push('--json');
134
+ break;
135
+ }
136
+ default: argv = helpArgv(context.command);
137
+ }
138
+ // Redacted operands are not executable corrections; offer safe help instead.
139
+ if (argv.some(value => sanitize(value) !== value)) return [{ argv: helpArgv(context.command), reason: 'Read command arguments without exposing credentials.' }];
140
+ return [{ argv, reason: String(reason) }];
141
+ }
142
+
143
+ const ioCodes = new Set(['EACCES', 'EPERM', 'ENOENT', 'ENOTDIR', 'EISDIR', 'ENOSPC', 'EROFS', 'EEXIST', 'EXDEV', 'EMFILE', 'ENFILE', 'EIO']);
144
+ const networkCodes = new Set(['ECONNREFUSED', 'ECONNRESET', 'ENOTFOUND', 'EAI_AGAIN', 'ETIMEDOUT', 'ERR_TLS_CERT_ALTNAME_INVALID', 'CERT_HAS_EXPIRED']);
145
+
146
+ /** @param {unknown} cause @param {ErrorContext} [context] @returns {{error: Diagnostic & {code: ErrorCode}, exitCode: number, data: unknown, warnings: Diagnostic[]}} */
147
+ export function classifyError(cause, context = {}) {
148
+ const raw = cause instanceof Error ? cause : null;
149
+ const rawCode = raw && 'code' in raw ? String(raw.code) : '';
150
+ /** @type {ErrorCode} */
151
+ let code = 'INTERNAL_ERROR';
152
+ if (raw instanceof CliError && Object.hasOwn(errorCatalog, raw.code)) code = raw.code;
153
+ else if (rawCode === 'EADDRINUSE') code = 'PORT_IN_USE';
154
+ else if (context.failureCode && Object.hasOwn(errorCatalog, context.failureCode)) code = context.failureCode;
155
+ else if (ioCodes.has(rawCode)) code = 'IO_FAILED';
156
+ else if (networkCodes.has(rawCode)) code = 'NETWORK_FAILED';
157
+ const message = sanitize(raw?.message ?? (typeof cause === 'string' ? cause : 'Unexpected ADG error.')).replace(/\s+/g, ' ').trim();
158
+ return {
159
+ error: { code, message, next: nextActions(code, { ...context, ...(raw instanceof CliError ? raw.context : {}) }) },
160
+ exitCode: Number(errorCatalog[code][0]),
161
+ data: raw instanceof CliError ? raw.data : null,
162
+ warnings: raw instanceof CliError ? raw.warnings : [],
163
+ };
164
+ }
165
+
166
+ /** @param {unknown} cause @param {ErrorCode} [fallback] */
167
+ export function asCliError(cause, fallback = 'INTERNAL_ERROR') {
168
+ if (cause instanceof CliError) return cause;
169
+ const classified = classifyError(cause);
170
+ return new CliError(classified.error.code === 'INTERNAL_ERROR' ? fallback : classified.error.code, cause instanceof Error ? cause.message : String(cause), { cause });
171
+ }
172
+
173
+ /** @param {unknown} value @returns {unknown} */
174
+ function sanitizedValue(value) {
175
+ if (typeof value === 'string') return sanitize(value);
176
+ if (Array.isArray(value)) return value.map(sanitizedValue);
177
+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, sanitizedValue(item)]));
178
+ return value;
179
+ }
180
+
181
+ /** @type {AsyncLocalStorage<(text: string) => void>} */
182
+ const humanOutput = new AsyncLocalStorage();
183
+ /**
184
+ * Route config/module writes in this invocation without capturing the caller's output.
185
+ * @template T
186
+ * @param {() => T | Promise<T>} work
187
+ * @param {(text: string) => void} stderr
188
+ * @returns {Promise<T>}
189
+ */
190
+ export async function withHumanOutput(work, stderr) {
191
+ const originals = [process.stdout.write, process.stderr.write];
192
+ for (const [index, stream] of [process.stdout, process.stderr].entries()) {
193
+ /** @param {string | Uint8Array} chunk @param {BufferEncoding | ((error?: Error | null) => void)} [encoding] @param {(error?: Error | null) => void} [callback] */
194
+ function redirect(chunk, encoding, callback) {
195
+ const sink = humanOutput.getStore();
196
+ const done = typeof encoding === 'function' ? encoding : callback;
197
+ if (!sink) return originals[index].call(stream, chunk, typeof encoding === 'string' ? encoding : undefined, done);
198
+ sink(sanitize(typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString(typeof encoding === 'string' ? encoding : 'utf8')));
199
+ done?.();
200
+ return true;
201
+ }
202
+ stream.write = redirect;
203
+ }
204
+ try { return await humanOutput.run(stderr, work); }
205
+ finally { [process.stdout.write, process.stderr.write] = originals; }
206
+ }
207
+
208
+ /** @param {OutputOptions} options */
209
+ export function createOutput({ json, command, revealKey = false, stdout = text => { process.stdout.write(text); }, stderr = text => { process.stderr.write(text); } }) {
210
+ /** @param {Envelope} envelope */
211
+ const emit = envelope => {
212
+ const clean = /** @type {Envelope} */ (sanitizedValue(envelope));
213
+ const data = envelope.data;
214
+ if (json && revealKey && command === 'serve' && envelope.ok && data && typeof data === 'object' && 'action' in data && data.action === 'print-key' && 'key' in data && typeof data.key === 'string' && /^adg_[a-f0-9]{64}$/.test(data.key) && clean.data && typeof clean.data === 'object') {
215
+ // Only the explicit print-key result field is exempt; siblings and diagnostics stay sanitized.
216
+ Object.assign(clean.data, { key: data.key });
217
+ }
218
+ stdout(`${JSON.stringify(clean)}\n`);
219
+ };
220
+ /** @param {string} text */
221
+ const log = text => (json ? stderr : stdout)(`${sanitize(text)}\n`);
222
+ return {
223
+ log,
224
+ /** @param {string} text */
225
+ progress: text => stderr(`${sanitize(text)}\n`),
226
+ /** @param {unknown} data @param {Diagnostic[]} [warnings] */
227
+ success(data, warnings = []) { emit({ schemaVersion: 1, command, ok: true, data: data ?? null, warnings, error: null }); },
228
+ /** @param {unknown} cause @param {ErrorContext} [context] */
229
+ failure(cause, context = {}) {
230
+ const failure = classifyError(cause, { ...context, command });
231
+ if (json) emit({ schemaVersion: 1, command, ok: false, data: failure.data, warnings: failure.warnings, error: failure.error });
232
+ else if (!(cause instanceof CliError && cause.humanReported)) stderr(`adg: ${failure.error.message}\n`);
233
+ return failure.exitCode;
234
+ },
235
+ };
236
+ }