@1agh/maude 2.0.3 → 2.0.6

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 (242) hide show
  1. package/README.md +6 -5
  2. package/apps/hub/src/project-transactions/kernel.mjs +10 -1
  3. package/apps/studio/access/filters.ts +12 -5
  4. package/apps/studio/access/known-canvases.ts +24 -1
  5. package/apps/studio/access/refused-inputs.ts +89 -0
  6. package/apps/studio/access/request.ts +0 -1
  7. package/apps/studio/acp/adapter-stderr.ts +43 -13
  8. package/apps/studio/acp/background-tasks.ts +155 -0
  9. package/apps/studio/acp/bridge.ts +44 -5
  10. package/apps/studio/acp/connected-fact.ts +15 -4
  11. package/apps/studio/acp/index.ts +14 -5
  12. package/apps/studio/actions/agents.ts +10 -0
  13. package/apps/studio/actions/defs/app.ts +12 -0
  14. package/apps/studio/actions/defs/view.ts +12 -0
  15. package/apps/studio/actions.manifest.json +25 -1
  16. package/apps/studio/actions.parity.json +13 -1
  17. package/apps/studio/annotations/ui/element-node.tsx +139 -54
  18. package/apps/studio/annotations/ui/lod.tsx +1 -1
  19. package/apps/studio/annotations/ui/text-style.ts +1 -1
  20. package/apps/studio/annotations-layer.tsx +0 -12
  21. package/apps/studio/api.ts +73 -24
  22. package/apps/studio/artboard-live-gate.tsx +267 -0
  23. package/apps/studio/artboard-live.ts +336 -0
  24. package/apps/studio/artboard-webgl.ts +668 -0
  25. package/apps/studio/bin/_agent-browser-bin.mjs +8 -0
  26. package/apps/studio/bin/_agent-browser-safe.mjs +2 -1
  27. package/apps/studio/bin/_canvas-reasons.mjs +34 -0
  28. package/apps/studio/bin/_ds-check-live.mjs +37 -0
  29. package/apps/studio/bin/_ds-check.mjs +4 -1
  30. package/apps/studio/bin/_ds-prove-judge.mjs +167 -0
  31. package/apps/studio/bin/_ds-prove-playwright.mjs +183 -105
  32. package/apps/studio/bin/_import-asset.mjs +2 -1
  33. package/apps/studio/bin/_perf-probe.mjs +2 -1
  34. package/apps/studio/bin/_png-playwright.mjs +10 -1
  35. package/apps/studio/bin/_pw-launch.mjs +14 -0
  36. package/apps/studio/bin/_studio-verb.mjs +24 -3
  37. package/apps/studio/bin/_thumb-blank.mjs +70 -0
  38. package/apps/studio/bin/_thumb-cover.mjs +35 -0
  39. package/apps/studio/bin/_thumbs-playwright.mjs +93 -13
  40. package/apps/studio/bin/ds-check.sh +5 -1
  41. package/apps/studio/bin/perf.sh +11 -1
  42. package/apps/studio/bin/server-up.sh +7 -2
  43. package/apps/studio/bin/smoke.sh +19 -0
  44. package/apps/studio/boot-progress.ts +31 -0
  45. package/apps/studio/canvas-build-sandbox.ts +275 -42
  46. package/apps/studio/canvas-build-worker.ts +10 -0
  47. package/apps/studio/canvas-create.ts +24 -0
  48. package/apps/studio/canvas-lib.tsx +131 -12
  49. package/apps/studio/canvas-module-cache.ts +93 -0
  50. package/apps/studio/canvas-source/errors.ts +39 -0
  51. package/apps/studio/canvas-source/waiting.ts +290 -0
  52. package/apps/studio/client/actions/shell-key-handlers.js +5 -0
  53. package/apps/studio/client/app.jsx +19 -9
  54. package/apps/studio/client/canvas-url.js +13 -0
  55. package/apps/studio/client/github.js +23 -3
  56. package/apps/studio/client/home/HomeAccounts.jsx +262 -0
  57. package/apps/studio/client/home/Shelves.jsx +4 -3
  58. package/apps/studio/client/home/home-accounts-model.js +121 -0
  59. package/apps/studio/client/home/home-api.js +36 -19
  60. package/apps/studio/client/home/home-app.jsx +141 -40
  61. package/apps/studio/client/home/home-model.js +172 -6
  62. package/apps/studio/client/home/home.css +169 -5
  63. package/apps/studio/client/home/shell-mode.js +8 -1
  64. package/apps/studio/client/hooks/use-git-actions.jsx +2 -1
  65. package/apps/studio/client/hooks/use-project-data.jsx +2 -0
  66. package/apps/studio/client/hooks/use-shell-core.jsx +3 -0
  67. package/apps/studio/client/hooks/use-tabs.jsx +64 -35
  68. package/apps/studio/client/index-loader.ts +23 -3
  69. package/apps/studio/client/panels/ChatPanel.jsx +49 -57
  70. package/apps/studio/client/panels/CreateProject.jsx +19 -5
  71. package/apps/studio/client/panels/DiffView.jsx +314 -248
  72. package/apps/studio/client/panels/TeamProjects.jsx +119 -69
  73. package/apps/studio/client/panels/acp-runtime.js +25 -0
  74. package/apps/studio/client/panels/caps-cache.js +46 -0
  75. package/apps/studio/client/panels/chat-finish.js +66 -0
  76. package/apps/studio/client/shell/frame-cap.js +53 -0
  77. package/apps/studio/client/shell/viewport.jsx +45 -8
  78. package/apps/studio/client/styles/_index.css +2 -0
  79. package/apps/studio/client/tree/tree.jsx +48 -21
  80. package/apps/studio/client/v2/access/access-client.js +2 -0
  81. package/apps/studio/client/v2/access/access-host.jsx +12 -1
  82. package/apps/studio/client/v2/access/trashed-banner.jsx +6 -3
  83. package/apps/studio/client/v2/ai/Advanced.jsx +12 -0
  84. package/apps/studio/client/v2/ai/BackgroundStrip.jsx +120 -0
  85. package/apps/studio/client/v2/ai/Composer.jsx +27 -10
  86. package/apps/studio/client/v2/ai/StoppedDivider.jsx +2 -1
  87. package/apps/studio/client/v2/ai/ai-run.css +87 -3
  88. package/apps/studio/client/v2/ai/background-model.js +113 -0
  89. package/apps/studio/client/v2/ai/needs-you-store.js +2 -1
  90. package/apps/studio/client/v2/ai/run-api.js +7 -3
  91. package/apps/studio/client/v2/ai/runs-store.js +2 -1
  92. package/apps/studio/client/v2/annotations/vote-store.js +11 -5
  93. package/apps/studio/client/v2/assets/asset-state-lane.js +6 -3
  94. package/apps/studio/client/v2/assets/assets-bus.js +10 -8
  95. package/apps/studio/client/v2/assets/browse-view.jsx +2 -0
  96. package/apps/studio/client/v2/assets/ds-library-view.jsx +47 -0
  97. package/apps/studio/client/v2/assets/spotlight-model.js +75 -0
  98. package/apps/studio/client/v2/assets/spotlight.css +153 -0
  99. package/apps/studio/client/v2/assets/spotlight.jsx +199 -0
  100. package/apps/studio/client/v2/assets/tile-menu.jsx +3 -1
  101. package/apps/studio/client/v2/assets/tile.jsx +3 -0
  102. package/apps/studio/client/v2/assets/use-assets.js +2 -1
  103. package/apps/studio/client/v2/canvases/canvases-panel.jsx +13 -2
  104. package/apps/studio/client/v2/canvases/covers.js +11 -5
  105. package/apps/studio/client/v2/canvases/folder-ask.js +139 -0
  106. package/apps/studio/client/v2/canvases/folder-dialogs.jsx +150 -0
  107. package/apps/studio/client/v2/canvases/trash-canvas.js +10 -2
  108. package/apps/studio/client/v2/canvases/trash-queue.js +152 -0
  109. package/apps/studio/client/v2/canvases/use-canvas-index.js +42 -18
  110. package/apps/studio/client/v2/canvases/use-pins.js +2 -1
  111. package/apps/studio/client/v2/code/canvas-error-card.jsx +70 -5
  112. package/apps/studio/client/v2/code/canvas-imports-card.jsx +15 -14
  113. package/apps/studio/client/v2/code/canvas-imports-words.js +44 -0
  114. package/apps/studio/client/v2/code/canvas-waiting-card.jsx +128 -0
  115. package/apps/studio/client/v2/code/canvas-waiting.js +164 -0
  116. package/apps/studio/client/v2/code/code-bus.js +5 -0
  117. package/apps/studio/client/v2/code/code.css +67 -0
  118. package/apps/studio/client/v2/code/use-canvas-source.js +19 -4
  119. package/apps/studio/client/v2/create/NameDialog.jsx +4 -2
  120. package/apps/studio/client/v2/create/name-dialog.css +10 -0
  121. package/apps/studio/client/v2/ds/advanced-host.jsx +11 -23
  122. package/apps/studio/client/v2/ds/ds-refresh.js +161 -0
  123. package/apps/studio/client/v2/ds/library-host.jsx +45 -45
  124. package/apps/studio/client/v2/ds/make-host.jsx +13 -12
  125. package/apps/studio/client/v2/ds/off-system-host.jsx +18 -16
  126. package/apps/studio/client/v2/ds/review-host.jsx +7 -1
  127. package/apps/studio/client/v2/ds/truth-host.jsx +15 -14
  128. package/apps/studio/client/v2/ds/upgrade-host.jsx +26 -10
  129. package/apps/studio/client/v2/empty/arriving.jsx +29 -12
  130. package/apps/studio/client/v2/empty/empty-host.jsx +8 -2
  131. package/apps/studio/client/v2/empty/not-local.jsx +31 -1
  132. package/apps/studio/client/v2/empty/use-empty-canvas.js +10 -1
  133. package/apps/studio/client/v2/export/last-finished.js +2 -1
  134. package/apps/studio/client/v2/history/branch-actions.js +13 -9
  135. package/apps/studio/client/v2/history/git-advanced.jsx +8 -1
  136. package/apps/studio/client/v2/history/git-model.js +21 -5
  137. package/apps/studio/client/v2/history/git-parts.jsx +76 -43
  138. package/apps/studio/client/v2/history/history.css +6 -0
  139. package/apps/studio/client/v2/left-panel/assets-panel.jsx +87 -10
  140. package/apps/studio/client/v2/left-panel/use-trash.js +2 -1
  141. package/apps/studio/client/v2/onboarding/AdvancedSheets.jsx +100 -33
  142. package/apps/studio/client/v2/onboarding/HubSheet.jsx +51 -83
  143. package/apps/studio/client/v2/onboarding/onboarding-model.js +10 -6
  144. package/apps/studio/client/v2/presence/faces.jsx +42 -14
  145. package/apps/studio/client/v2/present/order-notes-artboards.js +2 -1
  146. package/apps/studio/client/v2/search/search-recent.js +3 -1
  147. package/apps/studio/client/v2/search/search-remote.js +6 -4
  148. package/apps/studio/client/v2/settings/connections-model.js +1 -1
  149. package/apps/studio/client/v2/shell/account-card.jsx +10 -4
  150. package/apps/studio/client/v2/shell/canvas-crash-guard.js +137 -0
  151. package/apps/studio/client/v2/shell/github-signin-host.jsx +42 -0
  152. package/apps/studio/client/v2/shell/menu-runner.js +12 -0
  153. package/apps/studio/client/v2/shell/occlusion-insets.js +14 -2
  154. package/apps/studio/client/v2/shell/project-account-card.jsx +203 -0
  155. package/apps/studio/client/v2/shell/project-account-model.js +182 -0
  156. package/apps/studio/client/v2/shell/recovery-store.js +2 -1
  157. package/apps/studio/client/v2/shell/served-routes.js +120 -0
  158. package/apps/studio/client/v2/shell/share-cluster-host.jsx +139 -11
  159. package/apps/studio/client/v2/shell/share-cluster.css +58 -0
  160. package/apps/studio/client/v2/shell/share-cluster.jsx +26 -7
  161. package/apps/studio/client/v2/shell/shell-activity.js +19 -0
  162. package/apps/studio/client/v2/shell/team-switch.js +94 -0
  163. package/apps/studio/client/v2/shell/too-heavy-card.jsx +38 -0
  164. package/apps/studio/client/v2/shell/use-account.js +8 -1
  165. package/apps/studio/client/v2/shell/use-occluded-insets.js +3 -0
  166. package/apps/studio/client/v2/sync-states/conflict-card.jsx +7 -2
  167. package/apps/studio/client/v2/undo/use-undo-projection.jsx +3 -1
  168. package/apps/studio/cloud/endpoints.ts +23 -1
  169. package/apps/studio/collab/persistence.ts +9 -1
  170. package/apps/studio/collab/registry.ts +32 -0
  171. package/apps/studio/collab/room.ts +8 -0
  172. package/apps/studio/config-reload-wire.ts +53 -0
  173. package/apps/studio/dist/client.bundle.js +1098 -1102
  174. package/apps/studio/dist/styles.css +1 -1
  175. package/apps/studio/ds/board/specimen.tsx +12 -1
  176. package/apps/studio/ds/canvas-cli.ts +58 -2
  177. package/apps/studio/ds/check.ts +26 -1
  178. package/apps/studio/ds/cli.ts +7 -3
  179. package/apps/studio/ds/convert.ts +34 -6
  180. package/apps/studio/ds/ds-verb.ts +13 -0
  181. package/apps/studio/ds/post-build.ts +38 -0
  182. package/apps/studio/ds/upgrade-apply.ts +27 -5
  183. package/apps/studio/ds/upgrade-cli.ts +22 -2
  184. package/apps/studio/ds/upgrade-prove.ts +198 -15
  185. package/apps/studio/ds/upgrade-stage.ts +4 -1
  186. package/apps/studio/editing/minimap-context.tsx +3 -3
  187. package/apps/studio/editing/page-activity.ts +251 -0
  188. package/apps/studio/editing/rotate-handle.tsx +9 -5
  189. package/apps/studio/editing/sticky-name.tsx +4 -4
  190. package/apps/studio/history/restore-artboard-action.ts +40 -0
  191. package/apps/studio/history/trash.ts +6 -0
  192. package/apps/studio/home/accounts.ts +87 -0
  193. package/apps/studio/home/hub.ts +77 -175
  194. package/apps/studio/home/index-reader.ts +24 -2
  195. package/apps/studio/home/routes.ts +66 -8
  196. package/apps/studio/http.ts +131 -68
  197. package/apps/studio/index-flight.ts +40 -0
  198. package/apps/studio/managed-projects.ts +52 -24
  199. package/apps/studio/migrate/hub.ts +7 -1
  200. package/apps/studio/routes/canvas-source.ts +44 -2
  201. package/apps/studio/routes/ds-convert.ts +18 -0
  202. package/apps/studio/routes/history.ts +28 -5
  203. package/apps/studio/routes/hub-signin.ts +115 -0
  204. package/apps/studio/routes/index.ts +4 -0
  205. package/apps/studio/routes/table.ts +7 -0
  206. package/apps/studio/routes/trash.ts +19 -1
  207. package/apps/studio/server.ts +19 -10
  208. package/apps/studio/sync/accepted-cold-start.ts +54 -16
  209. package/apps/studio/sync/accepted-link.ts +9 -4
  210. package/apps/studio/sync/asset-push.ts +146 -23
  211. package/apps/studio/sync/asset-state.ts +3 -2
  212. package/apps/studio/sync/code-module-consent.ts +74 -0
  213. package/apps/studio/sync/file-ledger.ts +35 -0
  214. package/apps/studio/sync/file-membership.ts +28 -3
  215. package/apps/studio/sync/file-plane.ts +483 -86
  216. package/apps/studio/sync/file-pull.ts +304 -33
  217. package/apps/studio/sync/hub-browser-signin.ts +377 -0
  218. package/apps/studio/sync/hub-link.ts +1 -2
  219. package/apps/studio/sync/hub-text-undo.ts +30 -10
  220. package/apps/studio/sync/index.ts +381 -161
  221. package/apps/studio/sync/journal-client.ts +94 -5
  222. package/apps/studio/sync/pending-deletes.ts +100 -0
  223. package/apps/studio/sync/projection.ts +121 -14
  224. package/apps/studio/sync/pull-pacer.ts +160 -0
  225. package/apps/studio/sync/pull-priority.ts +119 -0
  226. package/apps/studio/sync/seed-progress.ts +58 -3
  227. package/apps/studio/sync/status.ts +3 -1
  228. package/apps/studio/sync/transaction-client.ts +71 -6
  229. package/apps/studio/sync/workspace-signin.ts +6 -256
  230. package/apps/studio/sync/writer-registry.ts +5 -1
  231. package/apps/studio/thumbs/service.ts +12 -2
  232. package/apps/studio/thumbs/validate.ts +7 -0
  233. package/apps/studio/ui-prefs-migrate.ts +4 -0
  234. package/apps/studio/video-comp.tsx +23 -0
  235. package/apps/studio/video-links-overlay.tsx +3 -2
  236. package/apps/studio/whats-new.json +126 -0
  237. package/cli/lib/bash-guard.mjs +13 -1
  238. package/cli/lib/design-help.gen.mjs +1 -1
  239. package/cli/lib/design-hook.mjs +20 -0
  240. package/cli/lib/studio-locate.mjs +35 -10
  241. package/cli/lib/workspace-plan.mjs +14 -0
  242. package/package.json +8 -8
@@ -22,6 +22,9 @@
22
22
  // - `/_home/internal/*` (Rust only): a constant-time `Authorization: Bearer $MAUDE_HOME_TOKEN`,
23
23
  // refused outright when the request carries `Origin` or `Sec-Fetch-Site` — a browser never
24
24
  // gets in, even holding the token
25
+ // - `/_api/hub-signin/return` (#204 K2, the team server's page sending the browser back): the
26
+ // ONE path outside the table — GET, a top-level navigation only, a loopback Host; it acts only
27
+ // on a sign-in this process started (createHomeFetch's navigation lane)
25
28
  // - a picture is served only when that pid's snapshot references its key; missing and forbidden
26
29
  // are the same 404 (no existence oracle)
27
30
  // So a project page (same site, other port), a canvas iframe or a web page can neither read nor
@@ -35,9 +38,11 @@ import { nameFromPrompt } from '../canvas-create.ts';
35
38
  import { fold } from '../index/match.ts';
36
39
  import { DIST_DIR } from '../paths.ts';
37
40
  import { serveClientAsset, serveFile, serveIndexHtml } from '../static-lane.ts';
41
+ import { HUB_SIGNIN_RETURN_PATH, returnPage } from '../sync/hub-browser-signin.ts';
38
42
  import { thumbNotFound, thumbResponse } from '../thumbs/routes.ts';
39
43
  import { checkJpeg } from '../thumbs/validate.ts';
40
44
  import { isLoopbackHost } from '../ws.ts';
45
+ import { createHomeAccounts } from './accounts.ts';
41
46
  import { createHomeAi, type HomeAi } from './ai.ts';
42
47
  import { createHomeCli, type HomeCli } from './cli.ts';
43
48
  import type { HomeCloud } from './cloud.ts';
@@ -240,7 +245,7 @@ interface HomeRoute {
240
245
  function post(
241
246
  path: string,
242
247
  kind: Kind,
243
- run: (body: unknown) => HomeAnswer | Promise<HomeAnswer>
248
+ run: (body: unknown, req: Request) => HomeAnswer | Promise<HomeAnswer>
244
249
  ): HomeRoute {
245
250
  return {
246
251
  method: 'POST',
@@ -249,7 +254,7 @@ function post(
249
254
  handle: async (req) => {
250
255
  const b = await readBody(req);
251
256
  if (!b.ok) return b.res;
252
- const r = await run(b.value);
257
+ const r = await run(b.value, req);
253
258
  return json(r.status, r.body);
254
259
  },
255
260
  };
@@ -277,6 +282,7 @@ export function homeRouteTable(deps: HomeDeps): HomeRoute[] {
277
282
  const cli = deps.cli ?? createHomeCli();
278
283
  const whatsNew = deps.whatsNew ?? createHomeWhatsNew();
279
284
  const github = deps.github ?? createHomeGithub();
285
+ const accounts = createHomeAccounts({ forgetCloud: (p) => deps.cloud.forget(p) });
280
286
  return [
281
287
  {
282
288
  method: 'GET',
@@ -466,13 +472,34 @@ export function homeRouteTable(deps: HomeDeps): HomeRoute[] {
466
472
  post('/_home/invite/pending/accept', 'home', (b) => invite.pendingAccept(b)),
467
473
  post('/_home/invite/pending/leave', 'home', (b) => invite.pendingLeave(b)),
468
474
  post('/_home/internal/signin/profile', 'internal', (b) => signin.register(b)),
469
- // S6.6 — page routes behind the page secret. The hub password rides one POST body to
470
- // `prepare` and is handed straight to the hub (home/hub.ts); nothing here stores or logs it.
475
+ // S6.6 — page routes behind the page secret. Issue #204 K2: Home takes no team-server password
476
+ // (`prepare` refuses one); Sign in — and an invite — goes through the hub's own page in the
477
+ // browser (home/hub.ts), and the browser comes back to HUB_SIGNIN_RETURN_PATH, served outside
478
+ // this table (createHomeFetch's navigation lane).
471
479
  post('/_home/hub/test', 'home', (b) => hub.test(b)),
472
480
  post('/_home/hub/prepare', 'home', (b) => hub.prepare(b)),
473
- // S6.11b — the hub sheet's "Invite link or key": the invite key, email and password ride this
474
- // one body to the hub's own POST /join (home/hub.ts); nothing here stores or logs them.
475
- post('/_home/hub/join', 'home', (b) => hub.join(b)),
481
+ post('/_home/hub/signin/start', 'home', (b, req) =>
482
+ hub.signInStart(b, new URL(req.url).origin)
483
+ ),
484
+ post('/_home/hub/signin/poll', 'home', (b) => hub.signInPoll(b)),
485
+ post('/_home/hub/signin/cancel', 'home', (b) => hub.signInCancel(b)),
486
+ // 2.0.5 W4b — Home's avatar: each profile's team-server sign-ins (no tokens), and a sign-out per
487
+ // account (one credential out of that profile's own file)
488
+ {
489
+ method: 'GET',
490
+ path: '/_home/accounts',
491
+ kind: 'home',
492
+ handle: (_req, url) => {
493
+ const r = accounts.list(url.searchParams.get('profiles'));
494
+ return json(r.status, r.body);
495
+ },
496
+ },
497
+ post('/_home/hub/signout', 'home', (b) =>
498
+ accounts.hubSignOut((b ?? {}) as Record<string, unknown>)
499
+ ),
500
+ post('/_home/cloud/signout', 'home', (b) =>
501
+ accounts.cloudSignOut((b ?? {}) as Record<string, unknown>)
502
+ ),
476
503
  get('/_home/ai/status', () => ai.status()),
477
504
  post('/_home/ai/connect', 'home', (b) => ai.connect(b)),
478
505
  get('/_home/cli/status', () => cli.status()),
@@ -519,6 +546,15 @@ export function homeRouteTable(deps: HomeDeps): HomeRoute[] {
519
546
  ];
520
547
  }
521
548
 
549
+ /** A browser's top-level GET navigation (Fetch Metadata) — the same test http.ts applies. */
550
+ function isTopLevelNavigation(req: Request): boolean {
551
+ return (
552
+ req.method === 'GET' &&
553
+ req.headers.get('sec-fetch-mode') === 'navigate' &&
554
+ req.headers.get('sec-fetch-dest') === 'document'
555
+ );
556
+ }
557
+
522
558
  function isStatic(pathname: string): boolean {
523
559
  return (
524
560
  pathname === '/' ||
@@ -544,7 +580,9 @@ async function serveStatic(pathname: string): Promise<Response> {
544
580
 
545
581
  /** The Home server's whole `fetch`: guards first, then the table. */
546
582
  export function createHomeFetch(deps: HomeDeps): (req: Request) => Promise<Response> {
547
- const table = homeRouteTable(deps);
583
+ // one hub flow for the table (start/poll/cancel) AND the navigation lane (the return)
584
+ const hub = deps.hub ?? createHomeHub();
585
+ const table = homeRouteTable({ ...deps, hub });
548
586
  // fail closed: a page secret that IS the internal bearer would let the bearer open page routes
549
587
  const pageSecret = deps.pageSecret && deps.pageSecret !== deps.token ? deps.pageSecret : null;
550
588
  return async (req) => {
@@ -562,6 +600,26 @@ export function createHomeFetch(deps: HomeDeps): (req: Request) => Promise<Respo
562
600
  if (req.method !== 'GET' && req.method !== 'HEAD') return refuse(405, 'Method Not Allowed');
563
601
  return serveStatic(pathname);
564
602
  }
603
+ // #204 K2 — THE NAVIGATION LANE: the one path a cross-site page may reach, where the team
604
+ // server's own page sends the browser back with a one-time code. No page secret (a browser tab
605
+ // has none) and no Sec-Fetch-Site gate (it IS cross-site), so only a top-level navigation
606
+ // (Sec-Fetch-Mode navigate + Dest document) of a GET is answered: a fetch, an image or a frame
607
+ // from any page gets 403. What protects it is what protects any OAuth redirect endpoint — it
608
+ // acts only on a `state` this process minted, once, and the code is worthless without the
609
+ // verifier that never left this process (sync/hub-browser-signin.ts).
610
+ if (pathname === HUB_SIGNIN_RETURN_PATH) {
611
+ if (req.method !== 'GET') return refuse(405, 'Method Not Allowed');
612
+ if (!isTopLevelNavigation(req)) return refuse(403, 'navigation only');
613
+ try {
614
+ return returnPage(await hub.signInReturn(url.searchParams));
615
+ } catch (err) {
616
+ console.error(
617
+ '[home] hub sign-in return failed:',
618
+ err instanceof Error ? err.message : err
619
+ );
620
+ return refuse(500, 'Server error');
621
+ }
622
+ }
565
623
  const candidates = table.filter((r) =>
566
624
  r.prefix ? pathname.startsWith(r.path) : pathname === r.path
567
625
  );
@@ -60,6 +60,7 @@ import {
60
60
  verifyFrameCap,
61
61
  } from './access/frame.ts';
62
62
  import { closureConfigFor } from './access/known-canvases.ts';
63
+ import { entryRel, refusedDesignInputs, refusedInputsFor } from './access/refused-inputs.ts';
63
64
  import {
64
65
  ACP_REFUSAL,
65
66
  accessForDesktop,
@@ -105,10 +106,16 @@ import { createRunRegistry, type RunRegistry } from './ai/runs.ts';
105
106
  import { type Api, ASSET_CHUNK_BYTES, ASSET_MAX_BYTES, ASSET_MAX_VIDEO_BYTES } from './api.ts';
106
107
  import { importBrandRequest } from './bin/_brand-site.mjs';
107
108
  import { buildCanvasModule } from './canvas-build.ts';
108
- import { buildCanvasSandboxed, buildStats } from './canvas-build-sandbox.ts';
109
+ import { buildCanvasSandboxed, buildStats, sandboxFailureClass } from './canvas-build-sandbox.ts';
109
110
  import { canvasLibPath } from './canvas-lib-resolver.ts';
111
+ import { budgetFromEnv, createModuleCache, moduleBytes } from './canvas-module-cache.ts';
110
112
  import { TranspileError } from './canvas-pipeline.ts';
111
- import { CanvasBuildError, canvasSourceSig, recordCanvasBuild } from './canvas-source/errors.ts';
113
+ import {
114
+ CanvasBuildError,
115
+ canvasSourceSig,
116
+ recordBuildFailure,
117
+ recordCanvasBuild,
118
+ } from './canvas-source/errors.ts';
112
119
  import { rememberCanvasBuild } from './canvas-source-memo.ts';
113
120
  import { createCloudEndpoints } from './cloud/endpoints.ts';
114
121
  import type { AiActivity } from './collab/ai-activity.ts';
@@ -238,7 +245,7 @@ import { pidOf, projectDir } from './index/snapshot.ts';
238
245
  import { feedVersionsToIndex } from './index/version-feed.ts';
239
246
  import type { InspectRegistry } from './inspect.ts';
240
247
  import { canvasSlug, writeLocator } from './locator.ts';
241
- import { prepareManagedProject } from './managed-projects.ts';
248
+ import { parsePrepareBody, prepareManagedProject } from './managed-projects.ts';
242
249
  import { materializeMissing } from './materialize-client.ts';
243
250
  import { createHubReachability } from './outbox/hub-reachability.ts';
244
251
  import { createOutbox, type GateFacts, type IntentRecord } from './outbox/index.ts';
@@ -294,7 +301,7 @@ import { createLinkGate } from './sync/link-consent.ts';
294
301
  import { createResyncTrace, type ResyncStatusSource } from './sync/resync-trace.ts';
295
302
  import { isFirstAnchorMode, readSyncSettings, writeSyncSettings } from './sync/settings.ts';
296
303
  import { listTrash, pruneTrash, restoreFromTrash } from './sync/trash.ts';
297
- import { signInToWorkspace, workspaceDisclosure } from './sync/workspace-signin.ts';
304
+ import { workspaceDisclosure } from './sync/workspace-signin.ts';
298
305
  import { thumbNotFound, thumbResponse, wantResponse } from './thumbs/routes.ts';
299
306
  import { BOOT_COVERS_DELAY_MS, createThumbService } from './thumbs/service.ts';
300
307
  import { normalizeTreeState } from './tree-state.ts';
@@ -587,6 +594,19 @@ export function sameOriginRead(req: Request): boolean {
587
594
  return site === 'same-origin' || site === 'none';
588
595
  }
589
596
 
597
+ /**
598
+ * Issue #204 — a browser's own top-level navigation (a link, a redirect, a meta refresh), never a
599
+ * fetch, an image or a frame: Fetch Metadata says `navigate` + `document`. Only a table spec that
600
+ * sets `crossSiteNavigation` accepts one from another site (the team-server sign-in return).
601
+ */
602
+ export function isTopLevelNavigation(req: Request): boolean {
603
+ return (
604
+ req.method === 'GET' &&
605
+ req.headers.get('sec-fetch-mode') === 'navigate' &&
606
+ req.headers.get('sec-fetch-dest') === 'document'
607
+ );
608
+ }
609
+
590
610
  /**
591
611
  * Every table route is privileged (migrate rewrites the tree; the outbox lists queued intents):
592
612
  * the same double gate every main-origin route carries — Origin check (reads and writes) +
@@ -597,7 +617,10 @@ export function guardTableRoute(spec: RouteSpec): RouteSpec {
597
617
  return {
598
618
  ...spec,
599
619
  handle: (req, params) => {
600
- const sameOrigin = spec.method === 'GET' ? sameOriginRead(req) : sameOriginWrite(req);
620
+ const sameOrigin =
621
+ spec.method === 'GET'
622
+ ? sameOriginRead(req) || (spec.crossSiteNavigation === true && isTopLevelNavigation(req))
623
+ : sameOriginWrite(req);
601
624
  if (!sameOrigin)
602
625
  return (
603
626
  spec.refuse?.('cross-origin') ?? new Response('cross-origin rejected', { status: 403 })
@@ -764,7 +787,10 @@ interface CanvasCacheEntry {
764
787
  * (DDR-064 collab dogfooding finding, 2026-05-29.) */
765
788
  sig: string;
766
789
  etag: string;
767
- js: string;
790
+ /** The built module as UTF-8 bytes (issue #204 — half a JS string's size, off the heap). */
791
+ body: Uint8Array<ArrayBuffer>;
792
+ /** What the byte budget counts. */
793
+ bytes: number;
768
794
  /** Absolute paths of the relative imports inlined into this build (`.css` +
769
795
  * local `.tsx/.ts` modules, incl. unresolved extensionless candidates) —
770
796
  * re-statted each request to recompute `sig` without re-reading the source. */
@@ -772,7 +798,19 @@ interface CanvasCacheEntry {
772
798
  /** gate-b-c4e — every file the build inlined (absolute), held to the frame's closure on serve. */
773
799
  inputs: readonly string[];
774
800
  }
775
- const canvasCache = new Map<string, CanvasCacheEntry>();
801
+ // Issue #204 — byte-bounded: every module bundles the shared chrome (~2 MB), and covers alone build
802
+ // every canvas of a project once, so a per-path Map with no bound held them all for good.
803
+ let canvasCache = createModuleCache<CanvasCacheEntry>({
804
+ maxBytes: budgetFromEnv('MAUDE_CANVAS_MODULE_CACHE_MB', 64),
805
+ });
806
+
807
+ /** Test seam (issue #204): what the live module cache holds, and a budget to hold it to. */
808
+ export function _canvasModuleCache(budgetBytes?: number): { size: number; bytes: number } {
809
+ if (budgetBytes !== undefined) {
810
+ canvasCache = createModuleCache<CanvasCacheEntry>({ maxBytes: budgetBytes });
811
+ }
812
+ return { size: canvasCache.size, bytes: canvasCache.bytes };
813
+ }
776
814
 
777
815
  /**
778
816
  * gate-b-c4e — may THIS request receive a module built from `inputs` (absolute paths)? null = yes.
@@ -907,7 +945,36 @@ export async function serveCanvasTsx(
907
945
  canvasAbs: absPath,
908
946
  assetUrlBase: designRootUrlBase(ctx.paths),
909
947
  });
948
+ if (!built.ok && built.kind === 'building') {
949
+ // 2.0.4 task P — the wait ran out and the build goes on (to the sandbox's hard ceiling). Its
950
+ // outcome is recorded when it settles, for `/_api/canvas-errors`; a success is in the
951
+ // sandbox's cache, so the client's next open is a hit. While it runs, canvas-errors answers
952
+ // `building` (`sandboxBuildRunning`) and the card says so instead of "can't be drawn".
953
+ const sig = canvasSourceSig(source);
954
+ void built.settled?.then((r) => {
955
+ if (r.ok) recordCanvasBuild(absPath, sig, null);
956
+ else if (r.kind !== 'building') {
957
+ const failure = sandboxFailureClass(r);
958
+ if (failure) recordBuildFailure(absPath, sig, failure);
959
+ else recordCanvasBuild(absPath, sig, null);
960
+ }
961
+ });
962
+ // The frame's own canvas (the path gate and the closure's `before` ran already), so saying
963
+ // "not yet" tells it nothing a refusal would hide (gate-b-c4m).
964
+ return new Response('This canvas is still being built.', {
965
+ status: 503,
966
+ headers: {
967
+ 'Content-Type': 'text/plain; charset=utf-8',
968
+ 'Cache-Control': 'no-store',
969
+ 'Retry-After': '5',
970
+ },
971
+ });
972
+ }
910
973
  if (!built.ok) {
974
+ // #189 — why it stopped, as OUR class (never the build's text) for /_api/canvas-errors
975
+ const failure = sandboxFailureClass(built);
976
+ if (failure) recordBuildFailure(absPath, canvasSourceSig(source), failure);
977
+ else recordCanvasBuild(absPath, canvasSourceSig(source), null);
911
978
  // gate-b-c4m (defender L-B) — a frame's failed build answers like a refused one: Bun
912
979
  // resolves imports the closure walk does not follow (a CSS `url()`), and "Could not resolve"
913
980
  // beside the refusal's 403 was an existence oracle. A syntax error in the canvas's own source
@@ -928,10 +995,12 @@ export async function serveCanvasTsx(
928
995
  // cache entry, no remembered source and no locator file (the sandbox caches the build).
929
996
  const refusedHere = inputsGate?.(result.inputs, absPath);
930
997
  if (refusedHere) return refusedHere;
998
+ const body = moduleBytes(result.js);
931
999
  cached = {
932
1000
  sig: builtSig,
933
1001
  etag: `${result.etag}-${RUNTIME_BOOT_ID}-${CHROME_EPOCH}`,
934
- js: result.js,
1002
+ body,
1003
+ bytes: body.byteLength,
935
1004
  deps,
936
1005
  inputs: result.inputs,
937
1006
  };
@@ -959,6 +1028,9 @@ export async function serveCanvasTsx(
959
1028
  canvasSourceSig(source),
960
1029
  err instanceof CanvasBuildError ? (err.errors[0] ?? null) : null
961
1030
  );
1031
+ // #189 — neither the canvas's syntax nor its build log: the engine itself failed
1032
+ if (!(err instanceof CanvasBuildError) && !(err instanceof TranspileError))
1033
+ recordBuildFailure(absPath, canvasSourceSig(source), { class: 'engine' });
962
1034
  if (err instanceof TranspileError) {
963
1035
  return new Response(`Transpile error: ${err.message}`, {
964
1036
  status: 500,
@@ -976,13 +1048,15 @@ export async function serveCanvasTsx(
976
1048
  if (refusedHere) return refusedHere;
977
1049
  // The signature against the freshly-parsed deps — this very edit may have
978
1050
  // added or removed a `.css` import — stamped before the build (above).
1051
+ const body = moduleBytes(result.js);
979
1052
  cached = {
980
1053
  sig: builtSig,
981
1054
  // Fold in the boot id (restart) + chrome epoch (live edit) so a chrome
982
1055
  // change busts the browser's cached transpile even when the canvas source
983
1056
  // (hence result.etag) is unchanged. See RUNTIME_BOOT_ID / CHROME_EPOCH.
984
1057
  etag: `${result.etag}-${RUNTIME_BOOT_ID}-${CHROME_EPOCH}`,
985
- js: result.js,
1058
+ body,
1059
+ bytes: body.byteLength,
986
1060
  deps,
987
1061
  inputs: result.inputs,
988
1062
  };
@@ -1003,7 +1077,10 @@ export async function serveCanvasTsx(
1003
1077
  /** The conditional-GET half of serving a built canvas module. Shared by the
1004
1078
  * in-process (desktop) and sandboxed (cell) build paths so the two cannot
1005
1079
  * disagree about caching semantics. */
1006
- function respondWithCanvasModule(req: Request, cached: { js: string; etag: string }): Response {
1080
+ function respondWithCanvasModule(
1081
+ req: Request,
1082
+ cached: { body: Uint8Array<ArrayBuffer>; etag: string }
1083
+ ): Response {
1007
1084
  const ifNoneMatch = req.headers.get('if-none-match');
1008
1085
  if (ifNoneMatch === cached.etag) {
1009
1086
  return new Response(null, {
@@ -1011,7 +1088,7 @@ function respondWithCanvasModule(req: Request, cached: { js: string; etag: strin
1011
1088
  headers: { ETag: cached.etag, 'Cache-Control': 'no-cache' },
1012
1089
  });
1013
1090
  }
1014
- return new Response(cached.js, {
1091
+ return new Response(cached.body, {
1015
1092
  status: 200,
1016
1093
  headers: {
1017
1094
  'Content-Type': 'application/javascript; charset=utf-8',
@@ -1031,11 +1108,14 @@ function respondWithCanvasModule(req: Request, cached: { js: string; etag: strin
1031
1108
  // otherwise OOM the sidecar (security review — ethical-hacker, Finding 1).
1032
1109
  // `cssSig`: today's same-name CSS file as the build saw it — set only when the version had no CSS
1033
1110
  // lane of its own (the build then used today's file), so such an entry goes stale with that file.
1034
- const historicalCanvasCache = new Map<
1035
- string,
1036
- { js: string; etag: string; cssSig: string | null; inputs: readonly string[] }
1037
- >();
1038
- const HIST_MAX_CACHE = 96;
1111
+ // Issue #204 — and byte-bounded like the live cache: 96 two-megabyte modules is ~200 MB.
1112
+ const historicalCanvasCache = createModuleCache<{
1113
+ body: Uint8Array<ArrayBuffer>;
1114
+ bytes: number;
1115
+ etag: string;
1116
+ cssSig: string | null;
1117
+ inputs: readonly string[];
1118
+ }>({ maxBytes: budgetFromEnv('MAUDE_CANVAS_VERSION_CACHE_MB', 32), maxEntries: 96 });
1039
1119
  // Rate-limit the EXPENSIVE miss path (git show + Bun.build, or a non-resolving
1040
1120
  // git lookup) so a distinct-sha spray from the canvas origin can't starve the
1041
1121
  // event loop. Cache HITS are free; only a NEW (path,sha) build consumes budget.
@@ -1173,11 +1253,7 @@ async function serveHistoricalCanvas(
1173
1253
  historicalCanvasCache.delete(key);
1174
1254
  cached = undefined;
1175
1255
  }
1176
- if (cached) {
1177
- // LRU touch — re-insert so the hot entry isn't the next eviction victim.
1178
- historicalCanvasCache.delete(key);
1179
- historicalCanvasCache.set(key, cached);
1180
- } else {
1256
+ if (!cached) {
1181
1257
  if (!historicalBuildAllowed()) {
1182
1258
  return new Response('Too many version previews — try again in a moment.', {
1183
1259
  status: 429,
@@ -1252,17 +1328,16 @@ async function serveHistoricalCanvas(
1252
1328
  restrictImportsTo: ctx.paths.designRoot,
1253
1329
  assetUrlBase: designRootUrlBase(ctx.paths),
1254
1330
  });
1331
+ const body = moduleBytes(result.js);
1255
1332
  cached = {
1256
- js: result.js,
1333
+ body,
1334
+ bytes: body.byteLength,
1257
1335
  etag: `${result.etag}-${sha}-${RUNTIME_BOOT_ID}-${CHROME_EPOCH}`,
1258
1336
  cssSig,
1259
1337
  inputs: result.inputs,
1260
1338
  };
1339
+ // LRU with both bounds (count + bytes); `get` above is the touch.
1261
1340
  historicalCanvasCache.set(key, cached);
1262
- if (historicalCanvasCache.size > HIST_MAX_CACHE) {
1263
- const oldest = historicalCanvasCache.keys().next().value;
1264
- if (oldest !== undefined) historicalCanvasCache.delete(oldest);
1265
- }
1266
1341
  } catch (err) {
1267
1342
  // gate-b-c4l (L-b) — a past version is not what the closure walked: to a gated session
1268
1343
  // (a frame) a failed build answers like a refused one, so it probes nothing.
@@ -1278,7 +1353,7 @@ async function serveHistoricalCanvas(
1278
1353
  headers: { ETag: cached.etag, 'Cache-Control': 'no-cache' },
1279
1354
  });
1280
1355
  }
1281
- return new Response(cached.js, {
1356
+ return new Response(cached.body, {
1282
1357
  status: 200,
1283
1358
  headers: {
1284
1359
  'Content-Type': 'application/javascript; charset=utf-8',
@@ -2603,6 +2678,10 @@ export function createHttp(
2603
2678
  cloudPlan: { cloud: cloudApi },
2604
2679
  // S11.14 — GET /_api/connections/hub (routes/connections.ts): main origin only, the hub credential.
2605
2680
  connections: { designRoot: ctx.paths.designRoot },
2681
+ hubSignin: {
2682
+ linkedHubUrl: () => ctx.cfg.linkedHub?.url,
2683
+ restartSync: () => ctx.syncControl?.restart(),
2684
+ },
2606
2685
  }).map(guardTableRoute);
2607
2686
  // p8-a1-claims — outside the gates: a write that names an AI chat answers inside its run's claim
2608
2687
  // (in place, so every consumer of the table — the mount, the local gate — sees the same specs)
@@ -4815,56 +4894,29 @@ export function createHttp(
4815
4894
  return gitJson(await linkHub(body));
4816
4895
  },
4817
4896
 
4818
- // Cloud Phase 3 Task 3 — "Sign in to workspace". The person-facing
4819
- // counterpart to /_api/hub/link: an address plus an email and password,
4820
- // rather than a token to paste. Same gates as the link route (MAIN ORIGIN
4821
- // only, loopback, POST CSRF) for the same reason — this handler receives a
4822
- // PASSWORD, so the untrusted canvas origin must never be able to reach it.
4823
- // MANAGED PROJECTS (T21/T22): sign in / open, store the credential and
4824
- // describe the project, so the native shell can create its own copy.
4825
- // Main origin only — this mints and stores a credential.
4897
+ // MANAGED PROJECTS (T21/T22): open with the credential this computer holds (Maude Cloud, a
4898
+ // handoff code, or a team server the browser sign-in stored) and describe the project, so the
4899
+ // native shell can create its own copy. Main origin only. No email or password is accepted.
4826
4900
  '/_api/projects/prepare': async (req: Request) => {
4827
4901
  if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 });
4828
4902
  if (!sameOriginWrite(req))
4829
4903
  return new Response('cross-origin write rejected', { status: 403 });
4830
4904
  if (!isTrustedRequestHost(req))
4831
4905
  return new Response('local request required', { status: 403 });
4832
- const body = (await readJson<Record<string, unknown>>(req, 8 * 1024)) ?? {};
4833
- const kind = body.kind;
4834
- const str = (v: unknown) => (typeof v === 'string' ? v : '');
4835
- const input =
4836
- kind === 'cloud'
4837
- ? { kind, projectId: str(body.projectId) }
4838
- : kind === 'handoff'
4839
- ? { kind, code: str(body.code), claimedProject: str(body.claimedProject) || undefined }
4840
- : kind === 'hub'
4841
- ? { kind, url: str(body.url), email: str(body.email), password: str(body.password) }
4842
- : kind === 'known-hub'
4843
- ? { kind, url: str(body.url) }
4844
- : null;
4845
- if (!input) return new Response('unknown kind', { status: 400 });
4846
- const r = await prepareManagedProject(
4847
- ctx,
4848
- input as Parameters<typeof prepareManagedProject>[1]
4849
- );
4906
+ // Issue #204: the desktop owns no team-server login — a body carrying an email or a password
4907
+ // (or the retired `hub` kind) is a plain 400 and is never forwarded anywhere.
4908
+ const parsed = parsePrepareBody(await readJson<unknown>(req, 8 * 1024));
4909
+ if (!parsed.ok)
4910
+ return Response.json(
4911
+ { ok: false, error: parsed.error, reason: parsed.reason },
4912
+ { status: parsed.status, headers: { 'Cache-Control': 'no-store' } }
4913
+ );
4914
+ const r = await prepareManagedProject(ctx, parsed.input);
4850
4915
  return Response.json(r, {
4851
4916
  status: r.ok ? 200 : r.status,
4852
4917
  headers: { 'Cache-Control': 'no-store' },
4853
4918
  });
4854
4919
  },
4855
- '/_api/workspace/sign-in': async (req: Request) => {
4856
- if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 });
4857
- if (!sameOriginWrite(req))
4858
- return new Response('cross-origin write rejected', { status: 403 });
4859
- if (!isTrustedRequestHost(req))
4860
- return new Response('local request required', { status: 403 });
4861
- const body = await readJson<unknown>(req, 8 * 1024);
4862
- const result = await signInToWorkspace((body ?? {}) as Record<string, unknown>);
4863
- return Response.json(result.json, {
4864
- status: result.status,
4865
- headers: { 'Cache-Control': 'no-store' },
4866
- });
4867
- },
4868
4920
 
4869
4921
  // The DDR-054 trust model in plain words, for the panel that replaces
4870
4922
  // DDR-079's terminal banner (DDR-192 §6). Read-only and main-origin — the
@@ -7911,8 +7963,19 @@ export function createHttp(
7911
7963
  function canvasInputsGate(req: Request): CanvasInputsGate | undefined {
7912
7964
  const see = seerFor(req);
7913
7965
  if (see === null) return undefined;
7914
- const gate: CanvasInputsGate = (inputs, entry) =>
7915
- inputsRefusal(inputs, designRoots, see, { entry });
7966
+ const gate: CanvasInputsGate = (inputs, entry) => {
7967
+ const refused = inputsRefusal(inputs, designRoots, see, { entry });
7968
+ // 2.0.5 (#205) — keep WHY on the server, per canvas; the main origin's /_index-data reports it
7969
+ // (`canvasRefusedInputs`). The answer here stays the bare not-in-scope body.
7970
+ const canvas = entryRel(entry, designRoots);
7971
+ if (canvas) {
7972
+ const names = refused ? refusedDesignInputs(inputs, designRoots, see) : [];
7973
+ const store = refusedInputsFor(ctx);
7974
+ const changed = names.length ? store.record(canvas, names) : store.clear(canvas);
7975
+ if (changed) ctx.bus.emit('canvas-list-update', { action: 'refused', rel: canvas });
7976
+ }
7977
+ return refused;
7978
+ };
7916
7979
  // gate-b-c4l (L-b) — a canvas whose import walk the closure blocked is refused before the build.
7917
7980
  gate.before = (entry) => {
7918
7981
  const closure = closureOf(accessOf(req));
@@ -0,0 +1,40 @@
1
+ // apps/studio/index-flight.ts — #204: one project-index build at a time per reader.
2
+ //
3
+ // `/_index-data` walks every canvas group, reads each canvas's sidecar and its import closure: on a
4
+ // ~311-canvas, 7612-file workspace on a small cell that took longer than the client's timeout. The
5
+ // client aborted and asked again, but an aborted fetch does not stop the build on the server, so
6
+ // every retry started ANOTHER full build next to the one still running — each slower than the last.
7
+ //
8
+ // A request that arrives while a build for the same reader is in flight joins it, as long as the
9
+ // tree has not changed since that build started (`bump()` on every file event). A change after it
10
+ // started means its answer would be stale, so the next caller starts a fresh one.
11
+
12
+ export interface SingleFlight<T> {
13
+ run(key: string, build: () => Promise<T>): Promise<T>;
14
+ /** The tree changed: builds started before now must not be shared with later callers. */
15
+ bump(): void;
16
+ /** In-flight builds (for tests). */
17
+ size(): number;
18
+ }
19
+
20
+ export function createSingleFlight<T>(): SingleFlight<T> {
21
+ let gen = 0;
22
+ const flights = new Map<string, { gen: number; promise: Promise<T> }>();
23
+ return {
24
+ run(key, build) {
25
+ const hit = flights.get(key);
26
+ if (hit && hit.gen === gen) return hit.promise;
27
+ const entry = { gen, promise: Promise.resolve().then(build) };
28
+ flights.set(key, entry);
29
+ const clear = () => {
30
+ if (flights.get(key) === entry) flights.delete(key);
31
+ };
32
+ entry.promise.then(clear, clear);
33
+ return entry.promise;
34
+ },
35
+ bump() {
36
+ gen++;
37
+ },
38
+ size: () => flights.size,
39
+ };
40
+ }