spatial-views 0.0.0-stage → 0.2.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 (220) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +245 -2
  3. package/dist/app/assets/abnfDiagram-S7VZAUFO-CFbb_Sz2.js +1 -0
  4. package/dist/app/assets/architecture-WOLXFQ4H-CsBD__5a.js +1 -0
  5. package/dist/app/assets/architectureDiagram-YGSQEFNW-C0ic4ib1.js +36 -0
  6. package/dist/app/assets/blockDiagram-APKKGZFW-BZDPbzAG.js +140 -0
  7. package/dist/app/assets/bpmnIcons-APHXDYXF-C0jbCElo.js +1 -0
  8. package/dist/app/assets/c4Diagram-KJ2TOQU5-BilBWuq5.js +38 -0
  9. package/dist/app/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
  10. package/dist/app/assets/chunk-5VM5RSS4-ZNzvKenW.js +15 -0
  11. package/dist/app/assets/chunk-6MUBBAK2-BBl-4tQr.js +2 -0
  12. package/dist/app/assets/chunk-AXFCVDMN-BhsttQ-k.js +62 -0
  13. package/dist/app/assets/chunk-BG4553SI-mWcPcFZr.js +127 -0
  14. package/dist/app/assets/chunk-DQASFODM-7FKe2gLt.js +10 -0
  15. package/dist/app/assets/chunk-DUW6YSOI-Dgx8z5s3.js +1 -0
  16. package/dist/app/assets/chunk-HFQBQIA3-nXrQ08BL.js +1 -0
  17. package/dist/app/assets/chunk-J5ZVWO5B-oDCd-gWO.js +1 -0
  18. package/dist/app/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
  19. package/dist/app/assets/chunk-KQLB2F66-swukhFmZ.js +2 -0
  20. package/dist/app/assets/chunk-KS47KZWR-DkDkwO82.js +1 -0
  21. package/dist/app/assets/chunk-LEVMRMFU-DXH6iXv3.js +1 -0
  22. package/dist/app/assets/chunk-M57EVK23-B-kEyOJF.js +1 -0
  23. package/dist/app/assets/chunk-NGNAAXSQ-DI_UYJZ4.js +136 -0
  24. package/dist/app/assets/chunk-OY52VR5R-DweG7qYw.js +88 -0
  25. package/dist/app/assets/chunk-QB3YPZ4I-DyozK3lV.js +213 -0
  26. package/dist/app/assets/chunk-R3KSYZAL-BEXCUN6J.js +1 -0
  27. package/dist/app/assets/chunk-STOXU5M4-BaTlty4O.js +72 -0
  28. package/dist/app/assets/chunk-TU62E6Q5-_rcUP1Fh.js +1 -0
  29. package/dist/app/assets/chunk-X3CZISLH-NOpCnvgE.js +1 -0
  30. package/dist/app/assets/chunk-X4PVCEUW-DGxTL3kB.js +1 -0
  31. package/dist/app/assets/chunk-XXDRQBXY-C02Gpej2.js +1 -0
  32. package/dist/app/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
  33. package/dist/app/assets/classDiagram-v2-L25IHNXF-DLEBwpvk.js +217 -0
  34. package/dist/app/assets/cose-bilkent-JH36ORCC-kNCXOm8k.js +1 -0
  35. package/dist/app/assets/cynefin-EF2NZ3EQ-6MWNLbuF.js +1 -0
  36. package/dist/app/assets/cynefinDiagram-L36ESFBY-CLFstukD.js +62 -0
  37. package/dist/app/assets/cytoscape.esm-nTrd5EVq.js +321 -0
  38. package/dist/app/assets/d3-scale-CaJQQYkF.js +1 -0
  39. package/dist/app/assets/dagre-SPEB5RXH-BaSAny1T.js +4 -0
  40. package/dist/app/assets/diagram-3B7GL73J-DJNlt5Sg.js +200 -0
  41. package/dist/app/assets/diagram-DNEMPZML-DEHeuILB.js +24 -0
  42. package/dist/app/assets/diagram-L3MUGCDN-ob5Ka2Xc.js +41 -0
  43. package/dist/app/assets/diagram-LA4NIPWU-DNESzFAc.js +24 -0
  44. package/dist/app/assets/diagram-MHCOC4E2-CVi9zKjG.js +3 -0
  45. package/dist/app/assets/diagram-XPFHEONP-DInT4C7e.js +30 -0
  46. package/dist/app/assets/dist-CjvHN74u.js +1 -0
  47. package/dist/app/assets/ebnfDiagram-UZSYDL2S-CRCZNsji.js +1 -0
  48. package/dist/app/assets/elk-XV6XMXQE-D4fsWI2l.js +2 -0
  49. package/dist/app/assets/erDiagram-EYBAPDEH-YQNM5StV.js +99 -0
  50. package/dist/app/assets/eventmodeling-K75KTNOO-Bev08J2F.js +1 -0
  51. package/dist/app/assets/flowDiagram-MALGAFMO-BhJ554DH.js +1 -0
  52. package/dist/app/assets/ganttDiagram-23REXITY-CkaBMYM4.js +292 -0
  53. package/dist/app/assets/gitGraph-VSP46ZUC-CtbZ0sIS.js +1 -0
  54. package/dist/app/assets/gitGraphDiagram-STJD7YCW-D15ZdQ-Z.js +106 -0
  55. package/dist/app/assets/graphlib-DS17s2tU.js +1 -0
  56. package/dist/app/assets/index-Bn6_wHEp.js +98 -0
  57. package/dist/app/assets/index-H-Z7MFhZ.css +1 -0
  58. package/dist/app/assets/info-OHQRW6UA-CfUW1XFR.js +1 -0
  59. package/dist/app/assets/infoDiagram-KBXO4MBG-DT7LbBRQ.js +2 -0
  60. package/dist/app/assets/ishikawaDiagram-M35NCXHK-CF51lhjB.js +70 -0
  61. package/dist/app/assets/journeyDiagram-OPLOXDXO-_36FonKk.js +139 -0
  62. package/dist/app/assets/kanban-definition-BZKZHSQY-tLk_OlQ-.js +89 -0
  63. package/dist/app/assets/katex-MEuSR36T.js +257 -0
  64. package/dist/app/assets/mermaid-parser.core-_3Vo8x6b.js +7 -0
  65. package/dist/app/assets/mermaid.core-y-x1CYxC.js +44 -0
  66. package/dist/app/assets/mindmap-definition-I2QAS2VK-BCI4HRX3.js +98 -0
  67. package/dist/app/assets/packet-JDAUHWVQ-Cco3UoaI.js +1 -0
  68. package/dist/app/assets/pegDiagram-FD4XPPHP-BOzSoNji.js +1 -0
  69. package/dist/app/assets/pie-XZMESJXO-reOB2GXn.js +1 -0
  70. package/dist/app/assets/pieDiagram-J4AKIIQI-PlHpwT_c.js +39 -0
  71. package/dist/app/assets/quadrantDiagram-XTYBLID2-CdxZ0ael.js +7 -0
  72. package/dist/app/assets/radar-ABXABTNO-DfCl8uV2.js +1 -0
  73. package/dist/app/assets/railroad-I3PHUGI6-4s14UyW1.js +1 -0
  74. package/dist/app/assets/railroad-abnf-LNEFI6M7-C49jJE4Y.js +1 -0
  75. package/dist/app/assets/railroad-ebnf-DWYD2UWJ-Bx-pcPc7.js +1 -0
  76. package/dist/app/assets/railroad-peg-JR7BVNR7-DjBPSCKV.js +1 -0
  77. package/dist/app/assets/railroadDiagram-MRQ6NCDL-wGcmIMqq.js +1 -0
  78. package/dist/app/assets/requirementDiagram-Y7LWUY3S-DprFI03z.js +84 -0
  79. package/dist/app/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  80. package/dist/app/assets/rough.esm-Dy-Kn_BL.js +1 -0
  81. package/dist/app/assets/sankeyDiagram-WGJFYUXA-DygYWLTR.js +40 -0
  82. package/dist/app/assets/sequenceDiagram-5NDRBG5M-BzIr2DBO.js +169 -0
  83. package/dist/app/assets/sizeCapture-INFHLROL-3uHXrFqA.js +1 -0
  84. package/dist/app/assets/stateDiagram-v2-FJ4FJNEA-MGCqKnm_.js +291 -0
  85. package/dist/app/assets/swimlanes-UMQ2AFYF-CIEH82Zt.js +1 -0
  86. package/dist/app/assets/swimlanesDiagram-OMPLPG4O-YWNJjl0g.js +8 -0
  87. package/dist/app/assets/timeline-definition-SEUHKTQE-BGYSqup2.js +120 -0
  88. package/dist/app/assets/treeView-D4JQ5SDB-B39o1sJo.js +1 -0
  89. package/dist/app/assets/treemap-SAJKECNS-BoGxrUH4.js +1 -0
  90. package/dist/app/assets/usecaseDiagram-AFA6YXN4-dy6oVOke.js +328 -0
  91. package/dist/app/assets/vennDiagram-NNMJR3RB-CUyuhcAk.js +34 -0
  92. package/dist/app/assets/wardley-7MLQ67FV-sYPAvQ06.js +1 -0
  93. package/dist/app/assets/wardleyDiagram-S7YFUSEH-DYtxYUHe.js +78 -0
  94. package/dist/app/assets/xychartDiagram-GGNKY7IX-ClR06AlB.js +7 -0
  95. package/dist/app/index.html +14 -0
  96. package/dist/cli/index.js +338 -0
  97. package/dist/core/api.js +420 -0
  98. package/dist/core/approvals.js +426 -0
  99. package/dist/core/context.js +259 -0
  100. package/dist/core/diff.js +156 -0
  101. package/dist/core/docs.js +140 -0
  102. package/dist/core/doctor.js +152 -0
  103. package/dist/core/doctypes.js +79 -0
  104. package/dist/core/edit.js +130 -0
  105. package/dist/core/errors.js +3 -0
  106. package/dist/core/flags.js +13 -0
  107. package/dist/core/gaps.js +119 -0
  108. package/dist/core/heading.js +4 -0
  109. package/dist/core/history.js +50 -0
  110. package/dist/core/home.js +345 -0
  111. package/dist/core/lanes.js +134 -0
  112. package/dist/core/launch.js +34 -0
  113. package/dist/core/layout.js +362 -0
  114. package/dist/core/links.js +68 -0
  115. package/dist/core/mermaid.js +175 -0
  116. package/dist/core/newdoc.js +66 -0
  117. package/dist/core/open-folder.js +30 -0
  118. package/dist/core/openspec.js +120 -0
  119. package/dist/core/paths.js +90 -0
  120. package/dist/core/project.js +392 -0
  121. package/dist/core/resolve.js +35 -0
  122. package/dist/core/route.js +420 -0
  123. package/dist/core/scan.js +514 -0
  124. package/dist/core/schema.js +270 -0
  125. package/dist/core/scope.js +126 -0
  126. package/dist/core/setup.js +134 -0
  127. package/dist/core/skills.js +181 -0
  128. package/dist/core/storage/config.js +74 -0
  129. package/dist/core/storage/events.js +54 -0
  130. package/dist/core/storage/folder-watch.js +147 -0
  131. package/dist/core/storage/folder.js +469 -0
  132. package/dist/core/storage/index.js +8 -0
  133. package/dist/core/storage/local.js +22 -0
  134. package/dist/core/storage/migrate.js +48 -0
  135. package/dist/core/storage/postgres.js +290 -0
  136. package/dist/core/storage/types.js +101 -0
  137. package/dist/core/storage.js +589 -0
  138. package/dist/core/suggest.js +283 -0
  139. package/dist/core/tree.js +254 -0
  140. package/dist/core/types.js +583 -0
  141. package/dist/core/version.js +1 -0
  142. package/dist/core/versions.js +245 -0
  143. package/dist/core/watch.js +2 -0
  144. package/dist/core/xml.js +68 -0
  145. package/dist/demo/args.js +58 -0
  146. package/dist/demo/browser.js +301 -0
  147. package/dist/demo/platform.js +147 -0
  148. package/dist/demo/run.js +198 -0
  149. package/dist/demo/steps.js +328 -0
  150. package/dist/mcp/project-tools.js +193 -0
  151. package/dist/mcp/server.js +785 -0
  152. package/examples/platform/README.md +33 -0
  153. package/examples/platform/api/package.json +8 -0
  154. package/examples/platform/api/src/auth-middleware.js +16 -0
  155. package/examples/platform/api/src/proxy.js +7 -0
  156. package/examples/platform/api/src/rate-limit.js +13 -0
  157. package/examples/platform/api/src/server.js +40 -0
  158. package/examples/platform/auth/package.json +9 -0
  159. package/examples/platform/auth/src/server.js +24 -0
  160. package/examples/platform/auth/src/tokens.js +19 -0
  161. package/examples/platform/auth/src/users.js +16 -0
  162. package/examples/platform/docs/api/PRD.md +10 -0
  163. package/examples/platform/docs/api/SDD.md +15 -0
  164. package/examples/platform/docs/auth/PRD.md +10 -0
  165. package/examples/platform/docs/auth/SDD.md +8 -0
  166. package/examples/platform/docs/frontend/PRD.md +18 -0
  167. package/examples/platform/docs/frontend/SDD.md +13 -0
  168. package/examples/platform/docs/pricing/PRD.md +9 -0
  169. package/examples/platform/docs/pricing/SDD.md +8 -0
  170. package/examples/platform/docs/products/PRD.md +9 -0
  171. package/examples/platform/docs/products/SDD.md +8 -0
  172. package/examples/platform/frontend/package.json +8 -0
  173. package/examples/platform/frontend/src/api-client.js +21 -0
  174. package/examples/platform/frontend/src/main.js +21 -0
  175. package/examples/platform/frontend/src/pages/products.js +12 -0
  176. package/examples/platform/frontend/src/pages/sign-in.js +14 -0
  177. package/examples/platform/frontend/src/session.js +11 -0
  178. package/examples/platform/pricing/package.json +9 -0
  179. package/examples/platform/pricing/src/cache.js +19 -0
  180. package/examples/platform/pricing/src/product-events.js +17 -0
  181. package/examples/platform/pricing/src/rules.js +19 -0
  182. package/examples/platform/pricing/src/server.js +32 -0
  183. package/examples/platform/products/package.json +9 -0
  184. package/examples/platform/products/src/catalog.js +20 -0
  185. package/examples/platform/products/src/events.js +11 -0
  186. package/examples/platform/products/src/search.js +9 -0
  187. package/examples/platform/products/src/server.js +31 -0
  188. package/migrations/postgres/001_init.sql +55 -0
  189. package/migrations/postgres/002_view_versions.sql +18 -0
  190. package/package.json +69 -4
  191. package/schema/approval.schema.json +173 -0
  192. package/schema/gap.schema.json +56 -0
  193. package/schema/pins.schema.json +122 -0
  194. package/schema/project.schema.json +93 -0
  195. package/schema/settings.schema.json +86 -0
  196. package/schema/toolbox.schema.json +206 -0
  197. package/schema/type.schema.json +121 -0
  198. package/schema/view.schema.json +240 -0
  199. package/skills/claude/build-gap/SKILL.md +28 -0
  200. package/skills/claude/check-ui/SKILL.md +40 -0
  201. package/skills/claude/draw-system/SKILL.md +38 -0
  202. package/skills/claude/gap-from-view/SKILL.md +29 -0
  203. package/skills/claude/post-audit/SKILL.md +58 -0
  204. package/skills/claude/pre-audit/SKILL.md +82 -0
  205. package/skills/claude/update-state/SKILL.md +56 -0
  206. package/skills/cursor/check-ui.mdc +40 -0
  207. package/skills/cursor/draw-system.mdc +38 -0
  208. package/skills/cursor/post-audit.mdc +44 -0
  209. package/skills/cursor/pre-audit.mdc +49 -0
  210. package/skills/cursor/update-state.mdc +45 -0
  211. package/skills/windsurf/spatial-views.md +212 -0
  212. package/toolboxes/aws.yaml +43 -0
  213. package/toolboxes/azure.yaml +41 -0
  214. package/toolboxes/cloud.yaml +95 -0
  215. package/toolboxes/docs.yaml +111 -0
  216. package/toolboxes/software.yaml +114 -0
  217. package/toolboxes/types/docs/gap.yaml +15 -0
  218. package/toolboxes/types/docs/mdd.yaml +19 -0
  219. package/toolboxes/types/docs/plain.yaml +7 -0
  220. package/toolboxes/types/docs/prd.yaml +17 -0
@@ -0,0 +1,420 @@
1
+ import { loadToolbox, loadTypes, userToolboxDir } from "./types.js";
2
+ import { ensureHome } from "./home.js";
3
+ import { openFolder as systemOpenFolder } from "./open-folder.js";
4
+ import { createDoc } from "./newdoc.js";
5
+ import { layoutView, typeLayout } from "./layout.js";
6
+ import { flags } from "./flags.js";
7
+ import { folderId, newDoc, newView, placeItem, projectTree, renameDoc, restoreItem, saveFolders } from "./tree.js";
8
+ import { readFile } from "node:fs/promises";
9
+ import { z, ZodError } from "zod";
10
+ import { trailTo } from "./context.js";
11
+ import { docSources, draftViewFromDoc, importDocs, mermaidBlocks, walkMarkdown } from "./docs.js";
12
+ import { UserError } from "./errors.js";
13
+ import { createGap, listGaps, updateGap } from "./gaps.js";
14
+ import { findChange, hasOpenSpec, listChanges, listSpecs, readChange, resolveChangePath, taskProgress } from "./openspec.js";
15
+ import { absPath } from "./paths.js";
16
+ import { approveItem, decideChange, denyItem, ApprovalStore, readSettings, summarizeApproval, writeSettings, StaleError, } from "./approvals.js";
17
+ import { docExists, readDoc, resolveDocPath } from "./project.js";
18
+ import { DecisionSchema, GapStateSchema, PinSchema, SettingsSchema, ViewSchema } from "./schema.js";
19
+ import { Session } from "./home.js";
20
+ import { NoProjectError } from "./scope.js";
21
+ import { readStorageConfig, storageInfo, StorageKindSchema, writeStorageConfig } from "./storage/config.js";
22
+ import { NotFoundError } from "./storage.js";
23
+ import { readOpen } from "./storage/local.js";
24
+ export function createApiHandler(target, watch, opts = {}) {
25
+ const session = target instanceof Session ? target : Session.fixed(target);
26
+ // Live events come from the active project's watcher; switching project swaps it.
27
+ const listeners = new Set();
28
+ const emit = (name, data) => listeners.forEach((fn) => fn(name, data));
29
+ let watcher = null;
30
+ let off = null;
31
+ const attach = (w) => {
32
+ off?.();
33
+ watcher = w;
34
+ // `open` is EventSource's own connection event, so open_view requests go out as `open_view`.
35
+ off = w ? w.subscribe((e) => emit(e.type === "open" ? "open_view" : e.type, e)) : null;
36
+ };
37
+ if (typeof watch === "function") {
38
+ if (session.hasProject)
39
+ attach(watch(session.spatial));
40
+ session.onChange((ws) => {
41
+ const old = watcher;
42
+ attach(ws ? watch(ws.spatial) : null);
43
+ old?.close();
44
+ emit("project", { slug: ws?.slug ?? null });
45
+ });
46
+ }
47
+ else if (watch)
48
+ attach(watch);
49
+ const live = typeof watch === "function" || watch !== undefined;
50
+ return async function handle(req, res) {
51
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
52
+ const path = url.pathname;
53
+ if (!path.startsWith("/api/"))
54
+ return false;
55
+ const send = (status, body) => {
56
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
57
+ res.end(JSON.stringify(body));
58
+ };
59
+ const host = (req.headers.host ?? "").replace(/:\d+$/, "");
60
+ if (host && !["127.0.0.1", "localhost", "[::1]"].includes(host))
61
+ return send(403, { error: "local only" }), true;
62
+ if (req.method !== "GET" && !(req.headers["content-type"] ?? "").includes("application/json"))
63
+ return send(415, { error: "send JSON" }), true;
64
+ if (path === "/api/events" && req.method === "GET" && live) {
65
+ res.writeHead(200, {
66
+ "content-type": "text/event-stream; charset=utf-8",
67
+ "cache-control": "no-cache",
68
+ connection: "keep-alive",
69
+ });
70
+ res.write("retry: 1000\n: connected\n\n");
71
+ const fn = (name, data) => res.write(`event: ${name}\ndata: ${JSON.stringify(data)}\n\n`);
72
+ listeners.add(fn);
73
+ const ping = setInterval(() => res.write(": ping\n\n"), 25_000);
74
+ req.on("close", () => (listeners.delete(fn), clearInterval(ping)));
75
+ return true;
76
+ }
77
+ const route = `${req.method} ${path}`;
78
+ try {
79
+ // ---- Storage (Settings → Storage; works with no project active)
80
+ if ((route === "GET /api/storage" || route === "PUT /api/storage") && opts.home) {
81
+ if (route === "PUT /api/storage") {
82
+ const body = z.object({ kind: StorageKindSchema, url: z.string().optional() }).strict().parse(await readJson(req));
83
+ await writeStorageConfig(opts.home, body);
84
+ }
85
+ const info = storageInfo(await readStorageConfig(opts.home, opts.env ?? process.env));
86
+ return send(200, { ...info, ...(opts.running ? { running: opts.running } : {}) }), true;
87
+ }
88
+ // ---- Projects (work with no project active)
89
+ if (route === "GET /api/flags")
90
+ return send(200, flags()), true;
91
+ // The user's toolboxes folder (~/SpatialViews/toolboxes): made if missing, opened in the file manager.
92
+ if (route === "POST /api/toolbox/open-folder") {
93
+ const dir = userToolboxDir(session.home.dir);
94
+ await ensureHome(session.home.dir);
95
+ await (opts.openFolder ?? systemOpenFolder)(dir);
96
+ return send(200, { dir }), true;
97
+ }
98
+ if (route === "GET /api/projects") {
99
+ const projects = await session.list();
100
+ return send(200, { projects, active: projects.find((p) => p.active)?.slug ?? null }), true;
101
+ }
102
+ if (route === "POST /api/projects") {
103
+ const { name } = z.object({ name: z.string() }).parse(await readJson(req));
104
+ const ws = await session.create(name);
105
+ return send(201, await ws.info()), true;
106
+ }
107
+ if (route === "POST /api/projects/use") {
108
+ const { project } = z.object({ project: z.string() }).parse(await readJson(req));
109
+ const ws = await session.use(project);
110
+ return send(200, await ws.info()), true;
111
+ }
112
+ // Everything else is the active project's.
113
+ const spatial = session.spatial;
114
+ const store = spatial.views;
115
+ const approvals = new ApprovalStore(spatial);
116
+ if (route === "GET /api/project")
117
+ return send(200, await session.current.info()), true;
118
+ // Where the project opens: always its root View (never the last one saved or opened).
119
+ if (route === "GET /api/home") {
120
+ const home = await session.current.landing();
121
+ return send(200, { view_id: home?.id ?? null }), true;
122
+ }
123
+ if (route === "GET /api/open") {
124
+ const want = await readOpen(spatial.localDir);
125
+ if (!want.view_id || !(await store.has(want.view_id)))
126
+ return send(404, { error: "nothing to open" }), true;
127
+ return send(200, { view_id: want.view_id, at: want.at, trail: trailTo(await store.listViews(), want.view_id, (await session.current.landing())?.id) }), true;
128
+ }
129
+ if (route === "GET /api/trail") {
130
+ const target = url.searchParams.get("view") ?? "";
131
+ if (!(await store.has(target)))
132
+ throw new NotFoundError(`no View ${target}`);
133
+ return send(200, trailTo(await store.listViews(), target, (await session.current.landing())?.id)), true;
134
+ }
135
+ // ---- Settings and approvals
136
+ if (route === "GET /api/settings")
137
+ return send(200, await readSettings(spatial)), true;
138
+ if (route === "PUT /api/settings") {
139
+ const patch = SettingsSchema.partial().strict().parse(await readJson(req));
140
+ return send(200, await writeSettings(spatial, patch)), true;
141
+ }
142
+ if (route === "GET /api/approvals")
143
+ return send(200, (await approvals.list()).map(summarizeApproval)), true;
144
+ const prM = /^(GET|POST) \/api\/approvals\/([^/]+)(?:\/(approve|deny)|\/changes\/([^/]+))?$/.exec(route);
145
+ if (prM) {
146
+ const [, method, rawId, action, changeId] = prM;
147
+ const id = decodeURIComponent(rawId);
148
+ if (method === "GET" && !action && !changeId)
149
+ return send(200, await approvals.get(id)), true;
150
+ if (method === "POST" && changeId) {
151
+ const { decision } = z.object({ decision: DecisionSchema.nullable() }).parse(await readJson(req));
152
+ return send(200, await decideChange(approvals, id, decodeURIComponent(changeId), decision)), true;
153
+ }
154
+ if (method === "POST" && action) {
155
+ // rev: how many revisions the person saw; approve refuses (409) if the AI amended it since.
156
+ const { note, rev } = z.object({ note: z.string().optional(), rev: z.number().int().nonnegative().optional() }).parse(await readJson(req));
157
+ try {
158
+ const p = action === "approve" ? await approveItem(spatial, approvals, id, note, rev) : await denyItem(approvals, id, note);
159
+ return send(200, p), true;
160
+ }
161
+ catch (err) {
162
+ if (err instanceof StaleError)
163
+ return send(409, { error: err.message, stale: true, rev: err.rev }), true;
164
+ throw err;
165
+ }
166
+ }
167
+ return send(405, { error: "method not allowed" }), true;
168
+ }
169
+ // ---- Gaps
170
+ if (route === "GET /api/gaps")
171
+ return send(200, await listGaps(spatial)), true;
172
+ if (route === "POST /api/gaps") {
173
+ const body = z
174
+ .object({
175
+ title: z.string(),
176
+ intent: z.string().optional(),
177
+ view: z.string(),
178
+ modules: z.array(z.string()),
179
+ milestone: z.string().optional(),
180
+ })
181
+ .parse(await readJson(req));
182
+ return send(201, await createGap(spatial, body)), true;
183
+ }
184
+ const gapM = /^PATCH \/api\/gaps\/([^/]+)$/.exec(route);
185
+ if (gapM) {
186
+ const patch = z
187
+ .object({
188
+ title: z.string().optional(),
189
+ intent: z.string().optional(),
190
+ state: GapStateSchema.optional(),
191
+ milestone: z.string().optional(),
192
+ modules: z.array(z.string()).optional(),
193
+ })
194
+ .parse(await readJson(req));
195
+ return send(200, await updateGap(spatial, decodeURIComponent(gapM[1]), patch)), true;
196
+ }
197
+ // ---- Pins
198
+ if (route === "GET /api/pins")
199
+ return send(200, await spatial.pins.read()), true;
200
+ if (route === "POST /api/pins" || route === "POST /api/pins/remove") {
201
+ const pin = PinSchema.parse(await readJson(req));
202
+ const doc = await resolveDocPath(spatial, pin.path);
203
+ pin.path = doc.rel;
204
+ if (route.endsWith("/remove"))
205
+ return send(200, { removed: await spatial.pins.remove(pin) }), true;
206
+ const real = doc.source || doc.report ? doc : await resolveDocPath(spatial, await resolveChangePath(spatial.root, pin.path));
207
+ if (!(await docExists(spatial, real)))
208
+ throw new UserError(`${pin.path} does not exist`);
209
+ return send(200, { added: await spatial.pins.add(pin) }), true;
210
+ }
211
+ // ---- Docs and OpenSpec
212
+ if (route === "GET /api/docs") {
213
+ const sources = await docSources(spatial);
214
+ const docs = [];
215
+ for (const s of sources)
216
+ docs.push({ source: s, files: await walkMarkdown(spatial.root, s) });
217
+ let openspec = null;
218
+ if (await hasOpenSpec(spatial.root)) {
219
+ const changes = [];
220
+ for (const c of await listChanges(spatial.root)) {
221
+ const tasks = await readFile(absPath(spatial.root, `${c.path}/tasks.md`), "utf8").catch(() => "");
222
+ changes.push({ ...c, progress: taskProgress(tasks) });
223
+ }
224
+ openspec = { specs: await listSpecs(spatial.root), changes };
225
+ }
226
+ return send(200, { sources, docs, openspec }), true;
227
+ }
228
+ if (route === "GET /api/doc") {
229
+ const doc = await resolveDocPath(spatial, url.searchParams.get("path") ?? "");
230
+ const rel = doc.source ? doc.rel : await resolveChangePath(spatial.root, doc.rel);
231
+ if (!rel.toLowerCase().endsWith(".md") || rel.startsWith(".spatial-local/"))
232
+ throw new UserError("only .md docs are served");
233
+ const text = await readDoc(spatial, doc.source || doc.report ? doc : await resolveDocPath(spatial, rel));
234
+ if (text === null)
235
+ throw new NotFoundError(`no doc ${rel}`);
236
+ const mermaid = mermaidBlocks(text).map(({ index, title, flowchart }) => ({ index, title, flowchart }));
237
+ return send(200, { path: rel, text, mermaid }), true;
238
+ }
239
+ if (route === "GET /api/project-doc") {
240
+ const path = spatial.docs.rel(url.searchParams.get("path") ?? "");
241
+ const text = await spatial.docs.liveRead(path);
242
+ if (text === null)
243
+ throw new NotFoundError(`no doc ${path}`);
244
+ return send(200, { path, text }), true;
245
+ }
246
+ if (route === "PUT /api/doc") {
247
+ const { text } = z.object({ text: z.string().max(2_000_000) }).parse(await readJson(req));
248
+ const path = spatial.docs.rel(url.searchParams.get("path") ?? "");
249
+ if ((await spatial.docs.liveRead(path)) === null)
250
+ throw new NotFoundError(`no doc ${path}`);
251
+ return send(200, { path: await spatial.docs.write(path, text) }), true;
252
+ }
253
+ if (route === "POST /api/doc/delete") {
254
+ const { path: p } = z.object({ path: z.string().min(1) }).parse(await readJson(req));
255
+ return send(200, { path: await spatial.docs.remove(p) }), true;
256
+ }
257
+ if (route === "POST /api/doc/rename") {
258
+ const b = z.object({ path: z.string().min(1), title: z.string().min(1).max(200) }).parse(await readJson(req));
259
+ return send(200, { path: await renameDoc(spatial, b.path, b.title) }), true;
260
+ }
261
+ // ---- The Project panel
262
+ if (route === "GET /api/tree")
263
+ return send(200, await projectTree(spatial)), true;
264
+ if (route === "PUT /api/tree/folders") {
265
+ const b = z.object({ folders: z.array(z.object({ id: z.string().min(1).optional(), name: z.string().min(1).max(60), parent: z.string().min(1).optional() })) }).parse(await readJson(req));
266
+ const taken = b.folders.flatMap((f) => (f.id ? [{ id: f.id, name: f.name }] : []));
267
+ const out = [];
268
+ for (const f of b.folders) {
269
+ const id = f.id ?? folderId(f.name, [...taken, ...out]);
270
+ out.push({ id, name: f.name, ...(f.parent ? { parent: f.parent } : {}) });
271
+ }
272
+ return send(200, await saveFolders(spatial, out)), true;
273
+ }
274
+ if (route === "POST /api/tree/place") {
275
+ const b = z.object({ kind: z.enum(["doc", "view"]), ref: z.string().min(1), folder: z.string().min(1) }).parse(await readJson(req));
276
+ await placeItem(spatial, b.kind, b.kind === "doc" ? spatial.docs.rel(b.ref) : b.ref, b.folder);
277
+ return send(200, { ok: true }), true;
278
+ }
279
+ if (route === "POST /api/tree/new-doc") {
280
+ const b = z.object({ type: z.string().min(1), title: z.string().max(200).optional(), folder: z.string().optional() }).parse(await readJson(req));
281
+ return send(201, await newDoc(spatial, b)), true;
282
+ }
283
+ if (route === "POST /api/tree/new-view") {
284
+ const b = z.object({ name: z.string().max(200).optional(), folder: z.string().optional() }).parse(await readJson(req));
285
+ return send(201, await newView(spatial, b)), true;
286
+ }
287
+ if (route === "POST /api/tree/restore") {
288
+ const b = z.object({ kind: z.enum(["doc", "view"]), ref: z.string().min(1) }).parse(await readJson(req));
289
+ await restoreItem(spatial, b.kind, b.ref);
290
+ return send(200, { ok: true }), true;
291
+ }
292
+ const delM = /^POST \/api\/views\/([^/]+)\/delete$/.exec(route);
293
+ if (delM) {
294
+ await store.delete(decodeURIComponent(delM[1]));
295
+ return send(200, { ok: true }), true;
296
+ }
297
+ const chM = /^GET \/api\/openspec\/changes\/([^/]+)$/.exec(route);
298
+ if (chM) {
299
+ const entry = await findChange(spatial.root, decodeURIComponent(chM[1]));
300
+ if (!entry)
301
+ throw new NotFoundError(`no OpenSpec change ${chM[1]}`);
302
+ return send(200, await readChange(spatial.root, entry)), true;
303
+ }
304
+ if (route === "POST /api/import") {
305
+ const { path: p } = z.object({ path: z.string() }).parse(await readJson(req));
306
+ return send(200, await importDocs(spatial, p, false)), true;
307
+ }
308
+ if (route === "POST /api/draft-view") {
309
+ const b = z.object({ path: z.string(), index: z.number().int().min(1) }).parse(await readJson(req));
310
+ return send(200, await draftViewFromDoc(spatial, b.path, b.index)), true;
311
+ }
312
+ // ---- The toolboxes (toolboxes/*.yaml: built-in, user, project)
313
+ if (route === "GET /api/toolbox")
314
+ return send(200, await loadToolbox(spatial.dataDir, { user: userToolboxDir(session.home.dir) })), true;
315
+ if (route === "POST /api/docs/new") {
316
+ const b = z
317
+ .object({ type: z.string().min(1), view_id: z.string().optional(), module_id: z.string().optional(), title: z.string().optional() })
318
+ .parse(await readJson(req));
319
+ const view = b.view_id ? await spatial.views.get(b.view_id) : undefined;
320
+ const module = b.module_id ? view?.modules.find((m) => m.id === b.module_id) : undefined;
321
+ if (b.module_id && !module)
322
+ throw new NotFoundError(`no module ${b.module_id} on ${b.view_id}`);
323
+ return send(201, await createDoc(spatial, { dirs: { user: userToolboxDir(session.home.dir) }, type: b.type, ...(b.title ? { title: b.title } : {}), ...(view ? { view } : {}), ...(module ? { module } : {}) })), true;
324
+ }
325
+ // ---- Versions (Views and Docs): read, name, restore (restore writes a new version)
326
+ const vm = /^\/api\/(?:views\/([^/]+)\/versions|doc-versions)(?:\/(\d+))?(?:\/(restore))?$/.exec(path);
327
+ if (vm) {
328
+ const n = vm[2] ? Number(vm[2]) : undefined;
329
+ const isView = vm[1] !== undefined;
330
+ const of = isView ? decodeURIComponent(vm[1]) : spatial.docs.rel(url.searchParams.get("path") ?? "");
331
+ if (isView && !(await store.has(of)) && !(await store.versions.latest(of)))
332
+ throw new NotFoundError(`no View ${of}`);
333
+ const versions = isView ? store.versions : spatial.docs.history;
334
+ if (req.method === "GET" && n === undefined && !vm[3])
335
+ return send(200, await versions.history(of)), true;
336
+ if (req.method === "GET" && n !== undefined && !vm[3])
337
+ return send(200, await versions.get(of, n)), true;
338
+ if (req.method === "POST" && n !== undefined && vm[3]) {
339
+ const { note } = z.object({ note: z.string().optional() }).parse(await readJson(req));
340
+ if (isView)
341
+ return send(200, await store.restore(of, n, note ? { note } : {})), true;
342
+ await spatial.docs.restore(of, n, note ? { note } : {});
343
+ return send(200, { path: of, restored_from: n }), true;
344
+ }
345
+ if (req.method === "PUT" && !vm[3]) {
346
+ const { name } = z.object({ name: z.string().max(120).nullable() }).parse(await readJson(req));
347
+ const v = isView ? await store.nameVersion(of, name, n) : await spatial.docs.nameVersion(of, name, n);
348
+ const { data: _d, ...head } = v;
349
+ return send(200, head), true;
350
+ }
351
+ return send(405, { error: "method not allowed" }), true;
352
+ }
353
+ // ---- Views
354
+ // Tidy layout (a person asked): lay out the whole View on the server, where ELK runs.
355
+ const lm = /^POST \/api\/views\/([^/]+)\/layout$/.exec(route);
356
+ if (lm) {
357
+ const b = z
358
+ .object({
359
+ direction: z.enum(["right", "down"]).optional(),
360
+ sizes: z.record(z.string(), z.object({ w: z.number().positive(), h: z.number().positive() })).optional(),
361
+ // The canvas lays out its unsaved draft and keeps the result as a draft too.
362
+ view: ViewSchema.optional(),
363
+ save: z.boolean().optional(),
364
+ })
365
+ .parse(await readJson(req));
366
+ const id = decodeURIComponent(lm[1]);
367
+ if (b.view && b.view.id !== id)
368
+ return send(400, { error: "view id does not match the path" }), true;
369
+ const v = b.view ?? (await store.get(id));
370
+ if (v.kind === "sequence")
371
+ return send(400, { error: "a sequence View is laid out already" }), true;
372
+ // The types give each module its tier (its row) and send externals to the side; measured sizes win.
373
+ const hints = typeLayout(v, await loadTypes(spatial.dataDir, { user: userToolboxDir(session.home.dir) }));
374
+ const laid = await layoutView(v, { ...hints, ...(b.direction ? { direction: b.direction } : {}), ...(b.sizes ? { sizes: b.sizes } : {}) });
375
+ if (b.save === false)
376
+ return send(200, { ...laid, auto_layout: true }), true;
377
+ return send(200, await store.save({ ...laid, auto_layout: true })), true;
378
+ }
379
+ const m = /^\/api\/views(?:\/([^/]+))?$/.exec(path);
380
+ if (!m)
381
+ return send(404, { error: "not found" }), true;
382
+ const id = m[1] ? decodeURIComponent(m[1]) : undefined;
383
+ if (req.method === "GET" && !id)
384
+ return send(200, await store.list()), true;
385
+ if (req.method === "GET" && id)
386
+ return send(200, await store.get(id)), true;
387
+ if (req.method === "PUT" && id) {
388
+ const view = ViewSchema.parse(await readJson(req));
389
+ if (view.id !== id)
390
+ return send(400, { error: "the body's id must match the path" }), true;
391
+ return send(200, await store.save(view)), true;
392
+ }
393
+ return send(405, { error: "method not allowed" }), true;
394
+ }
395
+ catch (err) {
396
+ if (err instanceof NoProjectError)
397
+ return send(409, { error: err.message }), true;
398
+ if (err instanceof NotFoundError)
399
+ return send(404, { error: err.message }), true;
400
+ if (err instanceof UserError)
401
+ return send(400, { error: err.message }), true;
402
+ if (err instanceof ZodError)
403
+ return send(400, { error: err.issues.map((i) => i.message).join("; ") }), true;
404
+ if (err instanceof SyntaxError)
405
+ return send(400, { error: String(err.message) }), true;
406
+ return send(500, { error: "internal error" }), true;
407
+ }
408
+ };
409
+ }
410
+ async function readJson(req) {
411
+ const chunks = [];
412
+ let size = 0;
413
+ for await (const chunk of req) {
414
+ size += chunk.length;
415
+ if (size > 5_000_000)
416
+ throw new SyntaxError("body too large");
417
+ chunks.push(chunk);
418
+ }
419
+ return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
420
+ }