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,245 @@
1
+ import { z } from "zod";
2
+ import { UserError } from "./errors.js";
3
+ import { diffText, diffView } from "./diff.js";
4
+ import { canonical, ConflictError } from "./storage/types.js";
5
+ /**
6
+ * Versions of Views and Docs. Every save (by a person or the AI) writes a new
7
+ * version, in the same transaction as the save:
8
+ *
9
+ * {n, at, by, note?, name?, restored_from?, data}
10
+ *
11
+ * `by` is "human" for the canvas, or the AI client's name (claude-code, cursor, ...).
12
+ * Folder store: `views/<id>/versions/<n>.json` (Docs: `doc-versions/<path>/<n>.json`);
13
+ * Postgres: the view_versions (doc_versions) table. Restore writes the chosen
14
+ * version as a new one; nothing is deleted, unless the project caps how many
15
+ * unnamed versions each View keeps (settings `keep_versions`; named ones always stay).
16
+ */
17
+ /** Who saves from the canvas. */
18
+ export const HUMAN = "human";
19
+ /** The app itself (a new project's empty System Overview): not a person, so not approved content. */
20
+ export const APP = "spatial-views";
21
+ export const VersionSchema = z.object({
22
+ n: z.number().int().positive(),
23
+ at: z.string(),
24
+ by: z.string().min(1),
25
+ /** What the save was ("restored from v12", "approved approval-3"). */
26
+ note: z.string().optional(),
27
+ /** A name a person or the AI gave it ("before AI tidy"); named versions are never pruned. */
28
+ name: z.string().optional(),
29
+ /** Set on a restore: the version it copied. */
30
+ restored_from: z.number().int().positive().optional(),
31
+ data: z.unknown(),
32
+ });
33
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
34
+ /** "2 modules added, 1 moved, 1 removed; 1 connection added", against the version before (null: the first). */
35
+ export function summarizeView(before, after) {
36
+ if (!before) {
37
+ const parts = [plural(after.modules.length, "module"), plural(after.connections.length, "connection")];
38
+ if (after.messages?.length)
39
+ parts.push(plural(after.messages.length, "message"));
40
+ return parts.join(", ");
41
+ }
42
+ const d = diffView(before, after);
43
+ const mods = { added: 0, changed: 0, moved: 0, removed: 0 };
44
+ for (const m of Object.values(d.modules)) {
45
+ if (m.status === "added")
46
+ mods.added++;
47
+ else if (m.status === "deleted")
48
+ mods.removed++;
49
+ else if (m.status === "amended")
50
+ m.changed.every((c) => c.field === "x" || c.field === "y") ? mods.moved++ : mods.changed++;
51
+ }
52
+ const count = (items) => {
53
+ const c = { added: 0, changed: 0, removed: 0 };
54
+ for (const x of Object.values(items)) {
55
+ if (x.status === "added")
56
+ c.added++;
57
+ else if (x.status === "amended")
58
+ c.changed++;
59
+ else if (x.status === "deleted")
60
+ c.removed++;
61
+ }
62
+ return c;
63
+ };
64
+ const words = (noun, c) => {
65
+ const bits = Object.entries(c).filter(([, n]) => n > 0);
66
+ if (!bits.length)
67
+ return null;
68
+ const [k0, n0] = bits[0];
69
+ return `${plural(n0, noun)} ${k0}${bits.slice(1).map(([k, n]) => `, ${n} ${k}`).join("")}`;
70
+ };
71
+ const parts = [words("module", mods), words("connection", count(d.connections)), words("message", count(d.messages ?? {}))].filter(Boolean);
72
+ if (d.fields.length)
73
+ parts.push(`${d.fields.map((f) => f.field).join(", ")} changed`);
74
+ return parts.length ? parts.join("; ") : "no change";
75
+ }
76
+ /** "2 lines added, 1 changed, 3 removed", against the version before (null: the first). */
77
+ export function summarizeDoc(before, after) {
78
+ if (before === null)
79
+ return plural(after.replace(/\n$/, "").split("\n").length, "line");
80
+ const c = { added: 0, changed: 0, removed: 0 };
81
+ for (const l of diffText(before, after)) {
82
+ if (l.status === "added")
83
+ c.added++;
84
+ else if (l.status === "amended")
85
+ c.changed++;
86
+ else if (l.status === "deleted")
87
+ c.removed++;
88
+ }
89
+ const bits = Object.entries(c).filter(([, n]) => n > 0);
90
+ if (!bits.length)
91
+ return "no change";
92
+ const [k0, n0] = bits[0];
93
+ return `${plural(n0, "line")} ${k0}${bits.slice(1).map(([k, n]) => `, ${n} ${k}`).join("")}`;
94
+ }
95
+ /**
96
+ * The versions of one kind of object (Views or Docs) in one project.
97
+ * Ids are `<object id>@<n>`.
98
+ */
99
+ export class Versions {
100
+ storage;
101
+ project;
102
+ kind;
103
+ parse;
104
+ summarize;
105
+ constructor(storage, project, kind, parse, summarize) {
106
+ this.storage = storage;
107
+ this.project = project;
108
+ this.kind = kind;
109
+ this.parse = parse;
110
+ this.summarize = summarize;
111
+ }
112
+ vid(of, n) {
113
+ return `${of}@${n}`;
114
+ }
115
+ read(x) {
116
+ const v = VersionSchema.parse(x);
117
+ return { ...v, data: this.parse(v.data) };
118
+ }
119
+ /** Every version of an object, oldest first. */
120
+ async list(of) {
121
+ const items = await this.storage.list(this.kind, this.project, { prefix: `${of}@` });
122
+ const out = [];
123
+ for (const it of items) {
124
+ if (it.id.slice(0, it.id.lastIndexOf("@")) !== of)
125
+ continue;
126
+ try {
127
+ out.push(this.read(it.data));
128
+ }
129
+ catch {
130
+ // A broken version is left alone; it must not hide the others.
131
+ }
132
+ }
133
+ return out.sort((a, b) => a.n - b.n);
134
+ }
135
+ /** The history list: newest first, with who, when, the name and a one-line summary. */
136
+ async history(of) {
137
+ const all = await this.list(of);
138
+ const out = [];
139
+ for (const [i, v] of all.entries()) {
140
+ const { data, ...rest } = v;
141
+ const before = i > 0 ? all[i - 1].data : null;
142
+ out.push({ ...rest, summary: v.restored_from ? `restored from v${v.restored_from}` : this.summarize(before, data) });
143
+ }
144
+ return out.reverse();
145
+ }
146
+ async get(of, n) {
147
+ const it = await this.storage.get(this.kind, this.project, this.vid(of, n));
148
+ if (!it)
149
+ throw new UserError(`no version ${n} of ${of}`);
150
+ return this.read(it.data);
151
+ }
152
+ /** Every object that has a version (live or deleted). */
153
+ async objects() {
154
+ const ids = await this.storage.listIds(this.kind, this.project);
155
+ return [...new Set(ids.map((id) => id.slice(0, id.lastIndexOf("@"))))].sort();
156
+ }
157
+ async latest(of) {
158
+ return this.newest(of);
159
+ }
160
+ /** The newest version, reading only the ids and that one version. */
161
+ async newest(of) {
162
+ const ids = await this.storage.listIds(this.kind, this.project, { prefix: `${of}@` });
163
+ let top = 0;
164
+ for (const id of ids) {
165
+ const at = id.lastIndexOf("@");
166
+ if (id.slice(0, at) === of)
167
+ top = Math.max(top, Number(id.slice(at + 1)));
168
+ }
169
+ if (!top)
170
+ return null;
171
+ const it = await this.storage.get(this.kind, this.project, this.vid(of, top));
172
+ return it ? this.read(it.data) : null;
173
+ }
174
+ /**
175
+ * The write that records `data` as the next version of `of` (none when it is
176
+ * the same as the latest version: a save that changed nothing adds nothing).
177
+ */
178
+ async op(of, data, meta = {}) {
179
+ const last = await this.newest(of);
180
+ if (last && !meta.restored_from && canonical(last.data) === canonical(data))
181
+ return null;
182
+ const v = {
183
+ n: (last?.n ?? 0) + 1,
184
+ at: new Date().toISOString(),
185
+ by: meta.by || HUMAN,
186
+ ...(meta.note ? { note: meta.note } : {}),
187
+ ...(meta.restored_from ? { restored_from: meta.restored_from } : {}),
188
+ data,
189
+ };
190
+ return { op: "put", kind: this.kind, project: this.project, id: this.vid(of, v.n), data: v, expected: null };
191
+ }
192
+ /** Name a version ("before AI tidy"), or clear its name with null. */
193
+ async name(of, n, name) {
194
+ const id = this.vid(of, n);
195
+ const it = await this.storage.get(this.kind, this.project, id);
196
+ if (!it)
197
+ throw new UserError(`no version ${n} of ${of}`);
198
+ const v = VersionSchema.parse(it.data);
199
+ const next = { ...v };
200
+ const clean = name?.trim();
201
+ if (clean)
202
+ next.name = clean.slice(0, 120);
203
+ else
204
+ delete next.name;
205
+ await this.storage.put(this.kind, this.project, id, next, { expected: it.version });
206
+ return this.read(next);
207
+ }
208
+ /**
209
+ * Keep the newest `keep` versions of an object, plus every named one (and
210
+ * the newest, always); the rest go. Without a cap, nothing is deleted.
211
+ */
212
+ async prune(of, keep) {
213
+ if (!keep || keep < 1)
214
+ return 0;
215
+ // Under the cap: nothing to read.
216
+ if ((await this.storage.listIds(this.kind, this.project, { prefix: `${of}@` })).length <= keep)
217
+ return 0;
218
+ const all = await this.list(of);
219
+ const cut = all.length - keep;
220
+ let gone = 0;
221
+ for (const v of all.slice(0, Math.max(0, cut))) {
222
+ if (v.name)
223
+ continue;
224
+ if (await this.storage.delete(this.kind, this.project, this.vid(of, v.n)))
225
+ gone++;
226
+ }
227
+ return gone;
228
+ }
229
+ }
230
+ /**
231
+ * Run a save's transaction, retrying when another client took the version
232
+ * number first (the ops are rebuilt each time).
233
+ */
234
+ export async function withVersion(storage, build, by) {
235
+ for (let n = 1;; n++) {
236
+ try {
237
+ return await storage.transact(await build(), by ? { by } : {});
238
+ }
239
+ catch (err) {
240
+ const lost = err instanceof ConflictError && (err.kind === "view_version" || err.kind === "doc_version");
241
+ if (!lost || n >= 5)
242
+ throw err;
243
+ }
244
+ }
245
+ }
@@ -0,0 +1,2 @@
1
+ /** The folder store's change stream, under its old path. */
2
+ export { ViewWatcher } from "./storage/folder-watch.js";
@@ -0,0 +1,68 @@
1
+ export function esc(s) {
2
+ return s
3
+ .replace(/&/g, "&amp;")
4
+ .replace(/</g, "&lt;")
5
+ .replace(/>/g, "&gt;")
6
+ .replace(/"/g, "&quot;");
7
+ }
8
+ /** Text as CDATA (a `]]>` inside is split so the XML stays well formed). */
9
+ export function cdata(s) {
10
+ return `<![CDATA[${s.replace(/]]>/g, "]]]]><![CDATA[>")}]]>`;
11
+ }
12
+ export const attr = (name, value) => value === undefined || value === "" ? "" : ` ${name}="${esc(value)}"`;
13
+ function linkAttrs(m, all) {
14
+ if (!m.linked_view_id)
15
+ return "";
16
+ const target = all.find((v) => v.id === m.linked_view_id);
17
+ return attr("LinkedView", m.linked_view_id) + (target ? attr("LinkedViewName", target.name) : ` Missing="true"`);
18
+ }
19
+ /**
20
+ * The XML the AI reads for a View. A linked module carries LinkedView (the id)
21
+ * and LinkedViewName; a link to a View that no longer exists says Missing="true".
22
+ * Lanes come first; a module says its Lane, and a connection across lanes says
23
+ * Dependency="true". A sequence View lists Participants, then its Messages in order.
24
+ */
25
+ export function viewToXml(view, all = [], indent = "") {
26
+ const byId = new Map(view.modules.map((m) => [m.id, m.name]));
27
+ const laneOf = new Map(view.modules.map((m) => [m.id, m.lane]));
28
+ const laneName = new Map((view.lanes ?? []).map((l) => [l.id, l.label]));
29
+ const seq = view.kind === "sequence";
30
+ const i = indent;
31
+ const lines = [
32
+ `${i}<View${attr("Id", view.id)}${attr("Name", view.name)}${attr("Type", view.type)}${seq ? ` Kind="sequence"` : ""}${view.draft ? ` Draft="true"` : ""}>`,
33
+ ];
34
+ for (const l of view.lanes ?? []) {
35
+ const names = view.modules.filter((m) => m.lane === l.id).map((m) => m.name).join(", ");
36
+ lines.push(`${i} <Lane${attr("Id", l.id)}${attr("Label", l.label)}${attr("Modules", names)}/>`);
37
+ }
38
+ for (const m of view.modules) {
39
+ const outs = view.connections.filter((c) => c.from === m.id);
40
+ const tag = seq ? "Participant" : "Module";
41
+ const open = `${i} <${tag}${attr("Id", m.id)}${attr("Name", m.name)}${attr("Type", m.type)}${attr("Lane", m.lane ? (laneName.get(m.lane) ?? m.lane) : undefined)}${linkAttrs(m, all)}`;
42
+ const body = [];
43
+ if (m.description)
44
+ body.push(`${i} <Description>${esc(m.description)}</Description>`);
45
+ for (const f of m.files ?? [])
46
+ body.push(`${i} <File${attr("Path", f)}/>`);
47
+ for (const c of outs) {
48
+ const a = laneOf.get(c.from);
49
+ const b = laneOf.get(c.to);
50
+ const dep = a && b && a !== b ? ` Dependency="true"${attr("ToLane", laneName.get(b) ?? b)}` : "";
51
+ body.push(`${i} <Connection${attr("GoTo", byId.get(c.to) ?? c.to)}${attr("Value", c.label)}${dep}/>`);
52
+ }
53
+ if (body.length === 0)
54
+ lines.push(`${open}/>`);
55
+ else
56
+ lines.push(`${open}>`, ...body, `${i} </${tag}>`);
57
+ }
58
+ (view.messages ?? []).forEach((msg, n) => {
59
+ const a = `${attr("Order", String(n + 1))}${attr("From", byId.get(msg.from) ?? msg.from)}${attr("To", byId.get(msg.to) ?? msg.to)}${attr("Kind", msg.kind)}`;
60
+ lines.push(msg.text ? `${i} <Message${a}>${esc(msg.text)}</Message>` : `${i} <Message${a}/>`);
61
+ });
62
+ for (const f of view.features ?? []) {
63
+ const names = f.module_ids.map((id) => byId.get(id) ?? id).join(", ");
64
+ lines.push(`${i} <Feature${attr("Id", f.id)}${attr("Name", f.name)}${attr("Modules", names)}/>`);
65
+ }
66
+ lines.push(`${i}</View>`);
67
+ return lines.join("\n");
68
+ }
@@ -0,0 +1,58 @@
1
+ import { UserError } from "../core/errors.js";
2
+ export const DEFAULT_DELAY = 2500;
3
+ export const DEMO_USAGE = `usage: spatial-views demo [--auto [--delay <ms>]] [--step <n>] [--port <n>]
4
+ space next step (in the browser window, or in this terminal)
5
+ --auto advance on a timer instead (--delay <ms> between steps, default ${DEFAULT_DELAY})
6
+ --step <n> start at step n; the earlier steps' state is set up at once, for retakes
7
+ --port <n> the canvas port (default: a free one)
8
+ q, Ctrl+C stop`;
9
+ /** The value after a flag (`--step 3` or `--step=3`), or an error naming the flag. */
10
+ function valueOf(argv, i, name) {
11
+ const a = argv[i];
12
+ if (a.startsWith(`${name}=`))
13
+ return { value: a.slice(name.length + 1), next: i };
14
+ const v = argv[i + 1];
15
+ if (v === undefined || v.startsWith("--"))
16
+ throw new UserError(`${name} needs a value\n${DEMO_USAGE}`);
17
+ return { value: v, next: i + 1 };
18
+ }
19
+ function int(value, name, min, max) {
20
+ const n = Number(value);
21
+ if (!Number.isInteger(n) || n < min || n > max)
22
+ throw new UserError(`${name} must be a whole number from ${min} to ${max}, not "${value}"`);
23
+ return n;
24
+ }
25
+ /** Parse the arguments after `demo`. `steps` is how many steps there are (for --step). */
26
+ export function parseDemoArgs(argv, steps) {
27
+ const out = { auto: false, delay: DEFAULT_DELAY, step: 1, headless: false };
28
+ let delayGiven = false;
29
+ for (let i = 0; i < argv.length; i++) {
30
+ const a = argv[i];
31
+ const flag = a.split("=")[0];
32
+ if (a === "--auto")
33
+ out.auto = true;
34
+ else if (a === "--headless")
35
+ out.headless = true;
36
+ else if (flag === "--delay") {
37
+ const { value, next } = valueOf(argv, i, "--delay");
38
+ out.delay = int(value, "--delay", 0, 600_000);
39
+ delayGiven = true;
40
+ i = next;
41
+ }
42
+ else if (flag === "--step") {
43
+ const { value, next } = valueOf(argv, i, "--step");
44
+ out.step = int(value, "--step", 1, steps);
45
+ i = next;
46
+ }
47
+ else if (flag === "--port") {
48
+ const { value, next } = valueOf(argv, i, "--port");
49
+ out.port = int(value, "--port", 1, 65535);
50
+ i = next;
51
+ }
52
+ else
53
+ throw new UserError(`spatial-views demo: unknown option "${a}"\n${DEMO_USAGE}`);
54
+ }
55
+ if (delayGiven && !out.auto)
56
+ throw new UserError(`--delay goes with --auto\n${DEMO_USAGE}`);
57
+ return out;
58
+ }
@@ -0,0 +1,301 @@
1
+ import { mkdir } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { UserError } from "../core/errors.js";
4
+ /**
5
+ * The window the demo records: Chromium through Playwright, 1920x1080, light,
6
+ * with no address bar or "controlled by automated software" bar. Captions and a
7
+ * visible cursor are drawn by a script the runner adds to every page; the app
8
+ * itself is not changed.
9
+ */
10
+ export const VIEWPORT = { width: 1920, height: 1080 };
11
+ const INSTALL = "npx playwright install chromium";
12
+ /** Playwright's Chromium: `playwright`, else `@playwright/test` (a dev dependency here). */
13
+ export async function loadChromium() {
14
+ for (const name of ["playwright", "@playwright/test"]) {
15
+ try {
16
+ const mod = (await import(name));
17
+ const chromium = mod.chromium ?? mod.default?.chromium;
18
+ if (chromium)
19
+ return chromium;
20
+ }
21
+ catch {
22
+ // try the next one
23
+ }
24
+ }
25
+ throw new UserError("The demo drives a browser with Playwright, which is not installed next to spatial-views.\n" +
26
+ " In a clone of the repo: npm install (it is a dev dependency)\n" +
27
+ " Otherwise: npm install playwright, in the folder spatial-views is installed in\n" +
28
+ `Then, once: ${INSTALL}`);
29
+ }
30
+ /** Launch errors that mean "the browser was never downloaded" get the one command that fixes it. */
31
+ export function launchError(err) {
32
+ const msg = err instanceof Error ? err.message : String(err);
33
+ if (/Executable doesn't exist|browserType\.launch.*(install|download)|playwright install/i.test(msg))
34
+ return new UserError(`Playwright's Chromium is not installed. Run:\n ${INSTALL}\nthen run the demo again.`);
35
+ if (/Missing X server|\$DISPLAY|cannot open display|Looks like you launched a headed browser/i.test(msg))
36
+ return new UserError("The demo opens a browser window, and there is no display here (no $DISPLAY). Run it on a desktop.");
37
+ return err instanceof Error ? err : new Error(msg);
38
+ }
39
+ /** Open the window on `url`. `profile` is a fresh folder (so the theme is the default: light). */
40
+ export async function openWindow(url, profile, headless, onSpace) {
41
+ const chromium = await loadChromium();
42
+ let context;
43
+ try {
44
+ context = await chromium.launchPersistentContext(profile, {
45
+ headless,
46
+ viewport: VIEWPORT,
47
+ screen: VIEWPORT,
48
+ deviceScaleFactor: 1,
49
+ colorScheme: "light",
50
+ reducedMotion: "no-preference",
51
+ // No "Chrome is being controlled by automated test software" bar.
52
+ ignoreDefaultArgs: ["--enable-automation"],
53
+ args: [
54
+ // An app window: no tabs, no address bar. Window capture records just the page.
55
+ `--app=${url}`,
56
+ "--window-position=0,0",
57
+ `--window-size=${VIEWPORT.width},${VIEWPORT.height}`,
58
+ "--disable-infobars",
59
+ "--no-first-run",
60
+ "--no-default-browser-check",
61
+ "--disable-features=Translate,AutofillServerCommunication,MediaRouter",
62
+ "--disable-session-crashed-bubble",
63
+ "--hide-crash-restore-bubble",
64
+ "--password-store=basic",
65
+ ],
66
+ });
67
+ }
68
+ catch (err) {
69
+ throw launchError(err);
70
+ }
71
+ await context.exposeFunction("__svDemoSpace", onSpace);
72
+ await context.addInitScript({ content: OVERLAY });
73
+ // A leave prompt (unsaved changes) must never stall a take.
74
+ context.on("page", (p) => p.on("dialog", (d) => void d.accept().catch(() => undefined)));
75
+ const page = context.pages()[0] ?? (await context.newPage());
76
+ page.on("dialog", (d) => void d.accept().catch(() => undefined));
77
+ if (page.url() !== url)
78
+ await page.goto(url);
79
+ else
80
+ await page.reload();
81
+ return { context, page };
82
+ }
83
+ /**
84
+ * The overlay: a caption card at the bottom and a cursor that follows the
85
+ * mouse events Playwright sends (the OS cursor does not move). Space is caught
86
+ * here while the runner waits for it, so it never clicks a focused button.
87
+ */
88
+ const OVERLAY = String.raw `(() => {
89
+ if (window.__svDemo) return;
90
+ window.__svDemo = { waiting: false };
91
+ const css = [
92
+ "#sv-demo-cursor { position: fixed; left: 0; top: 0; width: 28px; height: 28px; z-index: 2147483647; pointer-events: none; transform: translate(-100px, -100px); will-change: transform; }",
93
+ "#sv-demo-cursor svg { display: block; filter: drop-shadow(0 1px 2px rgba(15, 23, 42, 0.35)); }",
94
+ "#sv-demo-cursor .ring { position: absolute; left: -14px; top: -14px; width: 28px; height: 28px; border-radius: 50%; border: 2px solid rgba(37, 99, 235, 0.7); opacity: 0; transform: scale(0.4); }",
95
+ "#sv-demo-cursor .ring.on { animation: sv-demo-ring 420ms ease-out; }",
96
+ "@keyframes sv-demo-ring { 0% { opacity: 0.9; transform: scale(0.4); } 100% { opacity: 0; transform: scale(1.5); } }",
97
+ "#sv-demo-caption { position: fixed; left: 50%; bottom: 18px; z-index: 2147483646; pointer-events: none; display: flex; align-items: center; gap: 14px; white-space: nowrap; transform: translate(-50%, 10px); opacity: 0; transition: opacity 320ms ease, transform 320ms ease; padding: 12px 26px 12px 14px; border-radius: 14px; background: rgba(255, 255, 255, 0.97); border: 1px solid rgba(15, 23, 42, 0.08); box-shadow: 0 10px 36px rgba(15, 23, 42, 0.14); font-family: Inter, \"Segoe UI\", system-ui, -apple-system, sans-serif; color: #0f172a; }",
98
+ "#sv-demo-caption.on { opacity: 1; transform: translate(-50%, 0); }",
99
+ "#sv-demo-caption.plain { padding-left: 26px; }",
100
+ "#sv-demo-caption .kicker { flex: none; padding: 5px 11px; border-radius: 999px; font-size: 13px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; color: #1d4ed8; background: #dbeafe; }",
101
+ "#sv-demo-caption .kicker.ai { color: #6d28d9; background: #ede9fe; }",
102
+ "#sv-demo-caption .text { font-size: 23px; line-height: 1.3; font-weight: 500; }",
103
+ ].join("\n");
104
+ const mount = () => {
105
+ if (document.getElementById("sv-demo-cursor")) return;
106
+ const style = document.createElement("style");
107
+ style.textContent = css;
108
+ document.head.appendChild(style);
109
+ const cursor = document.createElement("div");
110
+ cursor.id = "sv-demo-cursor";
111
+ cursor.innerHTML = '<svg width="26" height="26" viewBox="0 0 26 26"><path d="M3 2 L3 21 L8.2 16.3 L11.6 24 L15 22.5 L11.7 15 L19 15 Z" fill="#0f172a" stroke="#fff" stroke-width="1.6" stroke-linejoin="round"/></svg><span class="ring"></span>';
112
+ document.body.appendChild(cursor);
113
+ const caption = document.createElement("div");
114
+ caption.id = "sv-demo-caption";
115
+ caption.innerHTML = '<span class="kicker"></span><span class="text"></span>';
116
+ document.body.appendChild(caption);
117
+ const at = window.__svDemo.at;
118
+ if (at) cursor.style.transform = "translate(" + at[0] + "px, " + at[1] + "px)";
119
+ if (window.__svDemo.caption) window.__svDemoCaption(window.__svDemo.caption.text, window.__svDemo.caption.kicker, true);
120
+ };
121
+ window.__svDemoCaption = (text, kicker, instant) => {
122
+ window.__svDemo.caption = text ? { text, kicker } : null;
123
+ const el = document.getElementById("sv-demo-caption");
124
+ if (!el) return;
125
+ const set = () => {
126
+ el.querySelector(".kicker").textContent = kicker || "";
127
+ el.querySelector(".kicker").className = "kicker" + (/^AI/.test(kicker || "") ? " ai" : "");
128
+ el.querySelector(".kicker").style.display = kicker ? "" : "none";
129
+ el.classList.toggle("plain", !kicker);
130
+ el.querySelector(".text").textContent = text || "";
131
+ if (text) el.classList.add("on");
132
+ };
133
+ if (!text) return el.classList.remove("on");
134
+ if (instant || !el.classList.contains("on")) return set();
135
+ el.classList.remove("on");
136
+ setTimeout(set, 260);
137
+ };
138
+ const move = (e) => {
139
+ window.__svDemo.at = [e.clientX, e.clientY];
140
+ const c = document.getElementById("sv-demo-cursor");
141
+ if (c) c.style.transform = "translate(" + e.clientX + "px, " + e.clientY + "px)";
142
+ };
143
+ window.addEventListener("mousemove", move, true);
144
+ window.addEventListener("pointermove", move, true);
145
+ window.addEventListener("mousedown", () => {
146
+ const r = document.querySelector("#sv-demo-cursor .ring");
147
+ if (!r) return;
148
+ r.classList.remove("on");
149
+ void r.offsetWidth;
150
+ r.classList.add("on");
151
+ }, true);
152
+ const editable = (t) => t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName));
153
+ window.addEventListener("keydown", (e) => {
154
+ if (e.key !== " " || e.repeat) return;
155
+ // Typing a space into a field goes through, unless the runner is waiting for the key.
156
+ if (!window.__svDemo.waiting && editable(e.target)) return;
157
+ e.preventDefault();
158
+ e.stopImmediatePropagation();
159
+ if (window.__svDemo.waiting && typeof window.__svDemoSpace === "function") window.__svDemoSpace();
160
+ }, true);
161
+ if (document.body) mount();
162
+ else document.addEventListener("DOMContentLoaded", mount);
163
+ })();`;
164
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
165
+ const ease = (t) => (t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2);
166
+ const isPoint = (t) => typeof t.x === "number" && typeof t.y === "number";
167
+ /** The person at the keyboard: the cursor glides, clicks land where it is, typing has a rhythm. */
168
+ export class Human {
169
+ page;
170
+ pace;
171
+ at = { x: VIEWPORT.width / 2, y: VIEWPORT.height * 0.62 };
172
+ constructor(page, pace = { speed: 1 }) {
173
+ this.page = page;
174
+ this.pace = pace;
175
+ }
176
+ pause(ms) {
177
+ return sleep(ms * this.pace.speed);
178
+ }
179
+ /** Put the cursor where the last one was (after a reload) without a glide. */
180
+ async place() {
181
+ await this.page.mouse.move(this.at.x, this.at.y);
182
+ }
183
+ /** Where a target is: a point, or the middle of a locator (nudged by dx, dy). */
184
+ async point(t, dx = 0, dy = 0) {
185
+ if (isPoint(t))
186
+ return { x: t.x + dx, y: t.y + dy };
187
+ await t.waitFor({ state: "visible" });
188
+ await t.scrollIntoViewIfNeeded().catch(() => undefined);
189
+ const b = await t.boundingBox();
190
+ if (!b)
191
+ throw new Error(`not on screen: ${t.toString()}`);
192
+ return { x: b.x + b.width / 2 + dx, y: b.y + b.height / 2 + dy };
193
+ }
194
+ /** Glide to a point, easing in and out, about 0.25 to 0.7 s. */
195
+ async moveTo(p) {
196
+ const from = this.at;
197
+ const d = Math.hypot(p.x - from.x, p.y - from.y);
198
+ const steps = Math.max(6, Math.min(42, Math.round(d / 22)));
199
+ for (let i = 1; i <= steps; i++) {
200
+ const k = ease(i / steps);
201
+ await this.page.mouse.move(from.x + (p.x - from.x) * k, from.y + (p.y - from.y) * k);
202
+ await sleep(14 * this.pace.speed);
203
+ }
204
+ this.at = p;
205
+ }
206
+ async hover(t, dx = 0, dy = 0) {
207
+ const p = await this.point(t, dx, dy);
208
+ await this.moveTo(p);
209
+ return p;
210
+ }
211
+ async click(t, opts = {}) {
212
+ const p = await this.hover(t, opts.dx, opts.dy);
213
+ await this.pause(140);
214
+ await this.page.mouse.click(p.x, p.y, { delay: 60 });
215
+ await this.pause(220);
216
+ }
217
+ async dblclick(t, opts = {}) {
218
+ const p = await this.hover(t, opts.dx, opts.dy);
219
+ await this.pause(160);
220
+ await this.page.mouse.dblclick(p.x, p.y, { delay: 40 });
221
+ await this.pause(260);
222
+ }
223
+ /** Press on a target, carry it by (dx, dy) at a hand's pace, let go. */
224
+ async drag(t, by, from = {}) {
225
+ const p = await this.hover(t, from.dx, from.dy);
226
+ await this.pause(160);
227
+ await this.page.mouse.down();
228
+ await this.pause(120);
229
+ // A small first move, so the canvas sees a drag start, then the rest.
230
+ await this.moveTo({ x: p.x + Math.sign(by.x) * 4, y: p.y + Math.sign(by.y) * 4 });
231
+ const steps = Math.max(18, Math.round(Math.hypot(by.x, by.y) / 6));
232
+ const start = this.at;
233
+ const end = { x: p.x + by.x, y: p.y + by.y };
234
+ for (let i = 1; i <= steps; i++) {
235
+ const k = ease(i / steps);
236
+ await this.page.mouse.move(start.x + (end.x - start.x) * k, start.y + (end.y - start.y) * k);
237
+ await sleep(16 * this.pace.speed);
238
+ }
239
+ this.at = end;
240
+ await this.pause(120);
241
+ await this.page.mouse.up();
242
+ await this.pause(260);
243
+ }
244
+ /** Type at a person's rhythm. */
245
+ async type(text) {
246
+ for (const ch of text) {
247
+ await this.page.keyboard.type(ch);
248
+ await sleep((70 + Math.round(Math.random() * 60)) * this.pace.speed);
249
+ }
250
+ }
251
+ async press(key) {
252
+ await this.page.keyboard.press(key);
253
+ await this.pause(160);
254
+ }
255
+ /** Scroll with the wheel where the cursor is, in small notches. */
256
+ async scroll(dy) {
257
+ const notches = Math.max(1, Math.round(Math.abs(dy) / 90));
258
+ for (let i = 0; i < notches; i++) {
259
+ await this.page.mouse.wheel(0, Math.sign(dy) * 90);
260
+ await sleep(90 * this.pace.speed);
261
+ }
262
+ }
263
+ }
264
+ /** Captions, fit-to-view, screenshots: what the runner does to the window that is not a person's input. */
265
+ export class Screen {
266
+ page;
267
+ shotsDir;
268
+ constructor(page, shotsDir) {
269
+ this.page = page;
270
+ this.shotsDir = shotsDir;
271
+ }
272
+ /** Show a caption (a kicker such as "AI · over MCP" above it); empty hides it. */
273
+ async caption(text, kicker = "") {
274
+ await this.page
275
+ .evaluate(([t, k]) => globalThis.__svDemoCaption?.(t, k), [text, kicker])
276
+ .catch(() => undefined);
277
+ }
278
+ /** Fit the View to the window, without the cursor going to the button (the change, not the click, is the point). */
279
+ async fit() {
280
+ const btn = this.page.getByRole("button", { name: /^fit view$/i }).first();
281
+ if (await btn.count())
282
+ await btn.dispatchEvent("click").catch(() => undefined);
283
+ }
284
+ /** Put away the app's last toast ("Saved", "Pending in Approvals"): it stays until dismissed. */
285
+ async dismissToast() {
286
+ const x = this.page.locator('.sv-toast button[aria-label="Dismiss"]');
287
+ if (await x.count())
288
+ await x.first().dispatchEvent("click").catch(() => undefined);
289
+ }
290
+ /** Mark the page as waiting for space (the overlay then catches it). */
291
+ async waiting(on) {
292
+ await this.page.evaluate((w) => (globalThis.__svDemo ??= { waiting: w }).waiting = w, on).catch(() => undefined);
293
+ }
294
+ /** SV_SHOTS=<dir>: a screenshot per beat, to check a run without watching it. */
295
+ async shot(name) {
296
+ if (!this.shotsDir)
297
+ return;
298
+ await mkdir(this.shotsDir, { recursive: true });
299
+ await this.page.screenshot({ path: join(this.shotsDir, `${name}.png`) }).catch(() => undefined);
300
+ }
301
+ }