shapewall 0.0.0-stage → 0.2.2

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 (304) hide show
  1. package/CHANGELOG.md +139 -0
  2. package/Dockerfile.agent +45 -0
  3. package/LICENSE +202 -0
  4. package/NOTICE +12 -0
  5. package/README.md +651 -2
  6. package/THIRD_PARTY.md +165 -0
  7. package/bin/shapewall.js +29 -0
  8. package/dist/agent/package-lock.json +8384 -0
  9. package/dist/client/assets/BoardChat-D5SFd8HE.js +28 -0
  10. package/dist/client/assets/BuzzDialog-HWXBy52W.js +1 -0
  11. package/dist/client/assets/ChecksPanel-DTdImWoD.js +1 -0
  12. package/dist/client/assets/History-CEv6b-av.js +1 -0
  13. package/dist/client/assets/LocalSettings-C4vriEVQ.js +1 -0
  14. package/dist/client/assets/Management-DCfhcEUY.js +1 -0
  15. package/dist/client/assets/QuickConnect-DQGgUsl1.js +1 -0
  16. package/dist/client/assets/ShareDialog-C_plIto0.js +2 -0
  17. package/dist/client/assets/app-update-dialog-2hPz_N9G.js +1 -0
  18. package/dist/client/assets/circle-x-BZMPi8Zf.js +1 -0
  19. package/dist/client/assets/index-ByQRKVit.css +2 -0
  20. package/dist/client/assets/index-DweQ8Qtu.js +29 -0
  21. package/dist/client/assets/refresh-cw-CRow0Nbq.js +1 -0
  22. package/dist/client/assets/runtime-Bft6x_6E.js +4 -0
  23. package/dist/client/assets/square-A8EnIYLR.js +1 -0
  24. package/dist/client/assets/tts-dist-DYlBQmwG.js +18 -0
  25. package/dist/client/assets/tts-en-g2p-BPUtBFGG.js +1 -0
  26. package/dist/client/assets/tts-ort-wasm-simd-threaded-qh98TCA_.wasm +0 -0
  27. package/dist/client/assets/tts-ort.wasm.bundle.min-rEkcs_ow.js +12 -0
  28. package/dist/client/assets/tts-rolldown-runtime-D8NudN84.js +1 -0
  29. package/dist/client/assets/tts-spacy-en-tokenizer-6SNMl--A.json +1 -0
  30. package/dist/client/assets/tts-tts.worker-Bzm6aWbv.js +1 -0
  31. package/dist/client/assets/tts-us_gold-DcjeNMH1.json +92589 -0
  32. package/dist/client/assets/tts-us_silver-C964mEB5.json +93363 -0
  33. package/dist/client/assets/ui-CLbws0rx.js +41 -0
  34. package/dist/client/build-info.json +1 -0
  35. package/dist/client/favicon.svg +7 -0
  36. package/dist/client/icons/apple-touch-icon.png +0 -0
  37. package/dist/client/icons/icon-192.png +0 -0
  38. package/dist/client/icons/icon-512.png +0 -0
  39. package/dist/client/icons/maskable-512.png +0 -0
  40. package/dist/client/index.html +25 -0
  41. package/dist/client/manifest.webmanifest +15 -0
  42. package/dist/client/sw.js +53 -0
  43. package/dist/client/theme-boot.js +27 -0
  44. package/dist/console/assets/LocalAccountsApp-BQCcmj3x.js +1 -0
  45. package/dist/console/assets/LocalConsole-Bb2FUDs7.js +1 -0
  46. package/dist/console/assets/app-update-dialog-DIeYepLZ.js +1 -0
  47. package/dist/console/assets/console-C7uJLLOn.js +51 -0
  48. package/dist/console/assets/console-R8IBY3Am.css +2 -0
  49. package/dist/console/build-info.json +1 -0
  50. package/dist/console/console.html +21 -0
  51. package/dist/console/favicon.svg +7 -0
  52. package/dist/console/icons/apple-touch-icon.png +0 -0
  53. package/dist/console/icons/icon-192.png +0 -0
  54. package/dist/console/icons/icon-512.png +0 -0
  55. package/dist/console/icons/maskable-512.png +0 -0
  56. package/dist/console/manifest.webmanifest +15 -0
  57. package/dist/console/theme-boot.js +27 -0
  58. package/docs/agent-hardening.md +342 -0
  59. package/docs/agent-recipes.md +187 -0
  60. package/docs/agent-workflow.md +320 -0
  61. package/docs/agents.md +894 -0
  62. package/docs/architecture.md +242 -0
  63. package/docs/buzz.md +140 -0
  64. package/docs/capture-warnings.md +57 -0
  65. package/docs/config.md +489 -0
  66. package/docs/deployment.md +289 -0
  67. package/docs/design-system.md +162 -0
  68. package/docs/github.md +107 -0
  69. package/docs/hosted.md +764 -0
  70. package/docs/images/board-overview.png +0 -0
  71. package/docs/images/journeys.png +0 -0
  72. package/docs/images/live-comment.png +0 -0
  73. package/docs/images/phone-comment.png +0 -0
  74. package/docs/images/phone-overview.png +0 -0
  75. package/docs/images/variant.png +0 -0
  76. package/docs/interaction-audits.md +40 -0
  77. package/docs/journeys.md +137 -0
  78. package/docs/local-accounts.md +80 -0
  79. package/docs/notifications.md +237 -0
  80. package/docs/page-checks.md +69 -0
  81. package/docs/performance.md +174 -0
  82. package/docs/starter-agent.md +325 -0
  83. package/docs/updates.md +87 -0
  84. package/examples/audits/interaction.audit.json +17 -0
  85. package/package.json +132 -4
  86. package/src/accounts/avatar.js +121 -0
  87. package/src/accounts/local.js +464 -0
  88. package/src/agent/acp/command.js +204 -0
  89. package/src/agent/acp/detect.js +75 -0
  90. package/src/agent/acp/sandbox.js +160 -0
  91. package/src/agent/agent-health.js +75 -0
  92. package/src/agent/backends/acp.js +1297 -0
  93. package/src/agent/backends/index.js +61 -0
  94. package/src/agent/backends/openai.js +308 -0
  95. package/src/agent/composer.js +221 -0
  96. package/src/agent/config.js +338 -0
  97. package/src/agent/context.js +191 -0
  98. package/src/agent/control.js +122 -0
  99. package/src/agent/errors.js +17 -0
  100. package/src/agent/feedback-loop.js +137 -0
  101. package/src/agent/manage.js +94 -0
  102. package/src/agent/next-steps.js +51 -0
  103. package/src/agent/owner-mcp.js +38 -0
  104. package/src/agent/plain-text.js +52 -0
  105. package/src/agent/ratings-core.js +213 -0
  106. package/src/agent/ratings.js +100 -0
  107. package/src/agent/reply-text.js +67 -0
  108. package/src/agent/routes.js +1065 -0
  109. package/src/agent/run.js +326 -0
  110. package/src/agent/settings-routes.js +704 -0
  111. package/src/agent/showable.js +23 -0
  112. package/src/agent/starter/approvals.js +181 -0
  113. package/src/agent/starter/build-image.js +90 -0
  114. package/src/agent/starter/cli.js +163 -0
  115. package/src/agent/starter/disk.js +53 -0
  116. package/src/agent/starter/doctor.js +180 -0
  117. package/src/agent/starter/egress-proxy.js +351 -0
  118. package/src/agent/starter/gate.js +90 -0
  119. package/src/agent/starter/loop.js +114 -0
  120. package/src/agent/starter/model-relay.js +289 -0
  121. package/src/agent/starter/pause.js +14 -0
  122. package/src/agent/starter/probe.js +272 -0
  123. package/src/agent/starter/prompt.js +41 -0
  124. package/src/agent/starter/push-guard.js +146 -0
  125. package/src/agent/starter/rpc.js +164 -0
  126. package/src/agent/starter/runtime.js +287 -0
  127. package/src/agent/starter/sandbox-main.js +121 -0
  128. package/src/agent/starter/settings.js +290 -0
  129. package/src/agent/starter/source.js +69 -0
  130. package/src/agent/starter/supervisor.js +755 -0
  131. package/src/agent/starter/sweep.js +46 -0
  132. package/src/agent/starter/tools.js +524 -0
  133. package/src/agent/starter/watch.js +84 -0
  134. package/src/agent/starter/worktree.js +409 -0
  135. package/src/agent/text-diff.js +210 -0
  136. package/src/agent/thread-history.js +223 -0
  137. package/src/agent/threads.js +399 -0
  138. package/src/agent/tools.js +200 -0
  139. package/src/agent/turn-changes.js +424 -0
  140. package/src/agent/undo-state.js +26 -0
  141. package/src/agent/user-settings.js +308 -0
  142. package/src/auth/record.js +375 -0
  143. package/src/broken-links.js +164 -0
  144. package/src/buzz/client.js +75 -0
  145. package/src/buzz/config.js +151 -0
  146. package/src/buzz/environment.js +13 -0
  147. package/src/buzz/gateway.js +192 -0
  148. package/src/buzz/routes.js +61 -0
  149. package/src/buzz/signer-child.js +205 -0
  150. package/src/buzz/store.js +89 -0
  151. package/src/buzz/transport.js +60 -0
  152. package/src/buzz/verify.js +140 -0
  153. package/src/capture/actions.js +159 -0
  154. package/src/capture/capture.js +776 -0
  155. package/src/capture/dom-names.js +189 -0
  156. package/src/capture/element-map.js +509 -0
  157. package/src/capture/live.js +827 -0
  158. package/src/capture/media-scheme.js +317 -0
  159. package/src/capture/network-summary.js +86 -0
  160. package/src/capture/pacing.js +34 -0
  161. package/src/capture/requests.js +167 -0
  162. package/src/capture/sanitize.js +752 -0
  163. package/src/checks/accessibility.js +134 -0
  164. package/src/checks/budgets.js +58 -0
  165. package/src/checks/cli.js +55 -0
  166. package/src/checks/comparison.js +113 -0
  167. package/src/checks/environments.js +32 -0
  168. package/src/checks/flow-config.js +82 -0
  169. package/src/checks/flow-origin.js +53 -0
  170. package/src/checks/flows.js +398 -0
  171. package/src/checks/lighthouse-auth.js +145 -0
  172. package/src/checks/lighthouse-findings.js +130 -0
  173. package/src/checks/lighthouse.js +395 -0
  174. package/src/checks/robots.js +85 -0
  175. package/src/checks/routes.js +52 -0
  176. package/src/checks/run-control.js +259 -0
  177. package/src/checks/runner.js +724 -0
  178. package/src/checks/schema.js +133 -0
  179. package/src/checks/seo-analysis.js +443 -0
  180. package/src/checks/seo-probe.js +190 -0
  181. package/src/checks/seo-snapshot.js +99 -0
  182. package/src/checks/store.js +214 -0
  183. package/src/checks/transport.js +47 -0
  184. package/src/cli/args.js +319 -0
  185. package/src/cli/capture.js +79 -0
  186. package/src/cli/commands.js +92 -0
  187. package/src/cli/comments.js +84 -0
  188. package/src/cli/help.js +243 -0
  189. package/src/cli/init.js +214 -0
  190. package/src/cli/misc.js +64 -0
  191. package/src/cli/notify.js +87 -0
  192. package/src/cli/open.js +22 -0
  193. package/src/cli/serve.js +274 -0
  194. package/src/cli/variant.js +82 -0
  195. package/src/cli/watch.js +70 -0
  196. package/src/cli.js +130 -0
  197. package/src/comment-fields.js +76 -0
  198. package/src/comments-cli.js +208 -0
  199. package/src/config-reload.js +100 -0
  200. package/src/config.js +1061 -0
  201. package/src/devices-cli.js +21 -0
  202. package/src/diff.js +95 -0
  203. package/src/discover.js +284 -0
  204. package/src/doctor.js +295 -0
  205. package/src/event-log.js +268 -0
  206. package/src/events-cli.js +102 -0
  207. package/src/events.js +113 -0
  208. package/src/export.js +119 -0
  209. package/src/feedback.js +246 -0
  210. package/src/github.js +551 -0
  211. package/src/hosted/LICENSE.md +105 -0
  212. package/src/hosted/access-cli.js +78 -0
  213. package/src/hosted/admin.js +682 -0
  214. package/src/hosted/agent-approvals.js +163 -0
  215. package/src/hosted/agent-policy.js +189 -0
  216. package/src/hosted/app.js +510 -0
  217. package/src/hosted/auth-routes.js +540 -0
  218. package/src/hosted/auth.js +536 -0
  219. package/src/hosted/backup.js +483 -0
  220. package/src/hosted/board-context.js +35 -0
  221. package/src/hosted/board-routes.js +486 -0
  222. package/src/hosted/board-view.js +94 -0
  223. package/src/hosted/clean-worker.js +24 -0
  224. package/src/hosted/cleaner.js +89 -0
  225. package/src/hosted/comments.js +355 -0
  226. package/src/hosted/console-routes.js +401 -0
  227. package/src/hosted/cookies.js +18 -0
  228. package/src/hosted/crypto.js +80 -0
  229. package/src/hosted/db.js +496 -0
  230. package/src/hosted/device-routes.js +175 -0
  231. package/src/hosted/device.js +233 -0
  232. package/src/hosted/events.js +63 -0
  233. package/src/hosted/guards.js +172 -0
  234. package/src/hosted/guest-view.js +65 -0
  235. package/src/hosted/http.js +39 -0
  236. package/src/hosted/import.js +300 -0
  237. package/src/hosted/mail.js +73 -0
  238. package/src/hosted/mcp-http.js +71 -0
  239. package/src/hosted/membership.js +114 -0
  240. package/src/hosted/operator.js +478 -0
  241. package/src/hosted/ops-cli.js +345 -0
  242. package/src/hosted/pages.js +146 -0
  243. package/src/hosted/permissions.js +113 -0
  244. package/src/hosted/presence.js +372 -0
  245. package/src/hosted/projects.js +124 -0
  246. package/src/hosted/public.js +109 -0
  247. package/src/hosted/push.js +622 -0
  248. package/src/hosted/quotas.js +115 -0
  249. package/src/hosted/ratelimit.js +96 -0
  250. package/src/hosted/rebind.js +316 -0
  251. package/src/hosted/retention.js +128 -0
  252. package/src/hosted/server.js +260 -0
  253. package/src/hosted/setup-link.js +64 -0
  254. package/src/hosted/setup.js +323 -0
  255. package/src/hosted/shares.js +444 -0
  256. package/src/hosted/tailscale.js +204 -0
  257. package/src/hosted/tenancy.js +301 -0
  258. package/src/hosted/token-api.js +455 -0
  259. package/src/hosted/token-events.js +60 -0
  260. package/src/hosted/tokens.js +57 -0
  261. package/src/hosted/turnstile.js +49 -0
  262. package/src/hosted/usercontent.js +154 -0
  263. package/src/hosted/zip.js +155 -0
  264. package/src/invocation.js +58 -0
  265. package/src/journey-paths.js +282 -0
  266. package/src/journeys.js +189 -0
  267. package/src/links.js +106 -0
  268. package/src/local-projects.js +182 -0
  269. package/src/lock.js +193 -0
  270. package/src/mcp.js +417 -0
  271. package/src/mentions.js +151 -0
  272. package/src/net.js +15 -0
  273. package/src/notify/config.js +275 -0
  274. package/src/notify/index.js +301 -0
  275. package/src/notify/lease.js +73 -0
  276. package/src/notify/messages.js +212 -0
  277. package/src/notify/run.js +174 -0
  278. package/src/pixeldiff.js +49 -0
  279. package/src/png.js +143 -0
  280. package/src/reactions.js +111 -0
  281. package/src/remote/cli.js +133 -0
  282. package/src/remote/credentials.js +62 -0
  283. package/src/remote/ids.js +12 -0
  284. package/src/remote/login.js +155 -0
  285. package/src/remote/remote-mcp.js +237 -0
  286. package/src/remote/remote-watch.js +291 -0
  287. package/src/remote/remote.js +313 -0
  288. package/src/remote/share-state.js +78 -0
  289. package/src/remote/share.js +369 -0
  290. package/src/remote/terminal.js +13 -0
  291. package/src/serve-state.js +64 -0
  292. package/src/server/app.js +824 -0
  293. package/src/server/devices.js +186 -0
  294. package/src/server/local-console.js +28 -0
  295. package/src/server/local-user.js +59 -0
  296. package/src/server/pairing-routes.js +159 -0
  297. package/src/server/share-routes.js +89 -0
  298. package/src/server/tailscale.js +97 -0
  299. package/src/sitemap.js +431 -0
  300. package/src/store.js +983 -0
  301. package/src/tokens.js +11 -0
  302. package/src/update/routes.js +245 -0
  303. package/src/watch.js +403 -0
  304. package/src/which.js +58 -0
@@ -0,0 +1,154 @@
1
+ // Usercontent: live HTML through short-lived signed URLs (/uc/...), and the
2
+ // element maps the board places pins from.
3
+ //
4
+ // Live HTML is the one thing the hosted server serves that it did not write
5
+ // itself (a push's documents, sanitized again on arrival). It is locked four
6
+ // ways: the sanitizer, the document's CSP meta tag, this response's CSP
7
+ // (`sandbox` without allow-same-origin: an opaque origin, no script, no
8
+ // forms, even opened top-level) and the board's frame (sandbox=""). The board
9
+ // never reads the frame: pins come from the element map, which is JSON on the
10
+ // board API (session or guest cookie), not here.
11
+ //
12
+ // With `usercontentOrigin` (a separate registrable domain, e.g.
13
+ // https://example-usercontent.com) /uc/ is served only there and the app
14
+ // origin answers it with 404. That host serves nothing else, never sets or
15
+ // reads a cookie, and lets only the app origin frame it.
16
+ //
17
+ // Signed URLs last 2 minutes and name the share link when a guest asked for
18
+ // them: every load checks that link again, so revoking it stops new loads at
19
+ // once (a frame already open keeps its document). The board asks the board
20
+ // API for each load, which answers with a fresh redirect.
21
+
22
+ import { LIVE_CSP } from '../capture/live.js'
23
+ import { ID_RE } from '../config.js'
24
+ import { resolveFile } from '../store.js'
25
+ import { ID_PATTERNS, SHARE_ID_RE, safeEqual, signUsercontent } from './crypto.js'
26
+ import { findShareById, shareUsable } from './tenancy.js'
27
+
28
+ export const SIGNED_URL_MS = 2 * 60_000
29
+ const KINDS = new Set(['captures', 'variants', 'versions'])
30
+
31
+ export function usercontentOriginOf(value, appOrigin) {
32
+ if (!value) return null
33
+ let url
34
+ try {
35
+ url = new URL(String(value))
36
+ } catch {
37
+ throw new Error('usercontentOrigin: an http(s) origin without a path, e.g. https://example-usercontent.com')
38
+ }
39
+ if (!['http:', 'https:'].includes(url.protocol) || url.pathname !== '/' || url.search || url.hash || url.username || url.password)
40
+ throw new Error('usercontentOrigin: an http(s) origin without a path, e.g. https://example-usercontent.com')
41
+ const app = new URL(appOrigin)
42
+ if (url.origin === app.origin) throw new Error('usercontentOrigin: must be another origin than the app (ideally another domain)')
43
+ if (app.protocol === 'https:' && url.protocol !== 'https:') throw new Error('usercontentOrigin: must be https when the app is https')
44
+ return url.origin
45
+ }
46
+
47
+ // createUsercontent({ db, secret, appOrigin, usercontentOrigin, now, locate })
48
+ // - locate(ws, projectId, boardId, kind, file): the file's path, or null
49
+ export function createUsercontent({ db, secret, appOrigin, usercontentOrigin = null, now = () => new Date(), locate }) {
50
+ const separate = usercontentOriginOf(usercontentOrigin, appOrigin)
51
+ const separateHost = separate ? new URL(separate).host.toLowerCase() : null
52
+ const csp = `sandbox; ${LIVE_CSP}; frame-ancestors ${separate ? new URL(appOrigin).origin : "'self'"}`
53
+ const onUsercontentHost = (req) => Boolean(separateHost) && String(req.headers.host || '').toLowerCase() === separateHost
54
+
55
+ // The share link a URL is bound to: its id and the first part of its token
56
+ // hash, so a link whose token was replaced stops loading too.
57
+ const shareVersion = (row) => String(row?.token_hash || '').slice(0, 24)
58
+
59
+ function signedUrl({ workspaceId, projectId, boardId, kind, file, shareId = null }) {
60
+ const expires = now().getTime() + SIGNED_URL_MS
61
+ const share = shareId ? `${shareId}.${shareVersion(findShareById(db, shareId))}` : ''
62
+ const signature = signUsercontent(secret, [workspaceId, projectId, boardId, kind, file, expires, share])
63
+ const query = new URLSearchParams({ e: String(expires), s: signature })
64
+ if (share) query.set('g', share)
65
+ const enc = encodeURIComponent
66
+ return `${separate || ''}/uc/${enc(workspaceId)}/${enc(projectId)}/${enc(boardId)}/${enc(kind)}/${enc(file)}?${query}`
67
+ }
68
+
69
+ function notFound(res) {
70
+ res.removeHeader('Set-Cookie')
71
+ res.setHeader('Cache-Control', 'no-store')
72
+ res.status(404).type('text').send('Not found')
73
+ }
74
+
75
+ function serve(req, res) {
76
+ res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()')
77
+ // Never a cookie here, whatever ran before.
78
+ res.removeHeader('Set-Cookie')
79
+ if (!['GET', 'HEAD'].includes(req.method)) return notFound(res)
80
+ const parts = String(req.path || '').split('/')
81
+ if (parts.length !== 7 || parts[0] !== '' || parts[1] !== 'uc') return notFound(res)
82
+ let ws, pid, board, kind, file
83
+ try {
84
+ ;[ws, pid, board, kind, file] = parts.slice(2).map((part) => decodeURIComponent(part))
85
+ } catch {
86
+ return notFound(res)
87
+ }
88
+ if (!KINDS.has(kind) || !ID_PATTERNS.workspace.test(ws) || !ID_PATTERNS.project.test(pid) || !ID_RE.test(board)) return notFound(res)
89
+ if (!file.endsWith('.html') || file.includes('/')) return notFound(res)
90
+ const expires = Number(req.query.e)
91
+ const at = now().getTime()
92
+ if (!Number.isSafeInteger(expires) || expires < at || expires > at + SIGNED_URL_MS + 60_000) return notFound(res)
93
+ const share = typeof req.query.g === 'string' ? req.query.g : ''
94
+ const signature = typeof req.query.s === 'string' ? req.query.s : ''
95
+ if (!safeEqual(signature, signUsercontent(secret, [ws, pid, board, kind, file, expires, share]))) return notFound(res)
96
+ if (share) {
97
+ const [shareId, version] = share.split('.')
98
+ if (!SHARE_ID_RE.test(shareId || '')) return notFound(res)
99
+ const row = findShareById(db, shareId)
100
+ if (!shareUsable(row, now().toISOString()) || row.workspace_id !== ws || row.project_id !== pid || version !== shareVersion(row))
101
+ return notFound(res)
102
+ }
103
+ let target = null
104
+ try {
105
+ target = locate(ws, pid, board, kind, file)
106
+ } catch {
107
+ target = null
108
+ }
109
+ if (!target) return notFound(res)
110
+ res.setHeader('Content-Security-Policy', csp)
111
+ if (separate) res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin')
112
+ else {
113
+ res.setHeader('X-Frame-Options', 'SAMEORIGIN')
114
+ res.setHeader('Cross-Origin-Resource-Policy', 'same-origin')
115
+ }
116
+ // Every load goes through the board API for a fresh URL: nothing to reuse.
117
+ res.setHeader('Cache-Control', 'private, no-store')
118
+ res.type('html').sendFile(target, { dotfiles: 'allow' })
119
+ }
120
+
121
+ // Mounted before every other route: on the usercontent host only /uc/
122
+ // exists (nothing else runs, so nothing sets or reads a cookie); on the
123
+ // app host /uc/ exists only without a separate usercontent origin.
124
+ function gate(req, res, next) {
125
+ if (onUsercontentHost(req)) return serve(req, res)
126
+ if (req.path === '/uc' || req.path.startsWith('/uc/')) return separate ? notFound(res) : serve(req, res)
127
+ next()
128
+ }
129
+
130
+ // The board's own CSP may frame the usercontent origin.
131
+ const boardCsp = (base) => (separate ? base.replace("frame-src 'self'", `frame-src 'self' ${separate}`) : base)
132
+
133
+ // GET /boards/:bid/elements/:file and /variant-elements/:file on the board
134
+ // API (members and share link guests), as JSON from the app origin.
135
+ function elementRoutes(router, withBoard, fail) {
136
+ for (const [route, kind] of [
137
+ ['elements', 'captures'],
138
+ ['variant-elements', 'variants'],
139
+ ]) {
140
+ router.get(
141
+ `/boards/:bid/${route}/:file`,
142
+ withBoard((req, res, ctx) => {
143
+ const name = req.params.file
144
+ const target = name.endsWith('.elements.json') ? resolveFile(ctx.config, ctx.board.id, kind, name) : null
145
+ if (!target) return fail(res, 404, 'not_found', 'No such element map.')
146
+ res.setHeader('Cross-Origin-Resource-Policy', 'same-origin')
147
+ res.type('json').sendFile(target, { dotfiles: 'allow' })
148
+ }),
149
+ )
150
+ }
151
+ }
152
+
153
+ return { gate, serve, signedUrl, boardCsp, elementRoutes, origin: separate, csp }
154
+ }
@@ -0,0 +1,155 @@
1
+ // A small zip writer for workspace exports: entries go out one at a time
2
+ // (each file is read whole, so its size and CRC are known before its header;
3
+ // stream() writes one in pieces with the sizes after the data),
4
+ // JSON and HTML deflated, PNGs stored (they are compressed already). No
5
+ // zip64: an export stops below 4 GB (ZIP_MAX_BYTES) and the caller checks
6
+ // the total first.
7
+
8
+ import zlib from 'node:zlib'
9
+
10
+ export const ZIP_MAX_BYTES = 3.5 * 1024 ** 3
11
+ const MAX_ENTRIES = 65_000
12
+
13
+ function dosTime(date) {
14
+ const year = Math.max(1980, date.getUTCFullYear())
15
+ return {
16
+ time: (date.getUTCHours() << 11) | (date.getUTCMinutes() << 5) | Math.floor(date.getUTCSeconds() / 2),
17
+ date: ((year - 1980) << 9) | ((date.getUTCMonth() + 1) << 5) | date.getUTCDate(),
18
+ }
19
+ }
20
+
21
+ // createZip(write) -> { add(name, data), finish() }. `write(buffer)` may
22
+ // return a promise (backpressure); add and finish await it.
23
+ export function createZip(write, { now = new Date() } = {}) {
24
+ const central = []
25
+ let offset = 0
26
+ const stamp = dosTime(now)
27
+ const emit = async (buffer) => {
28
+ await write(buffer)
29
+ offset += buffer.length
30
+ }
31
+
32
+ async function add(name, data, { compress = !/\.png$/i.test(name) } = {}) {
33
+ if (central.length >= MAX_ENTRIES) throw new Error('too many files for one zip')
34
+ const bytes = Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'utf8')
35
+ const nameBytes = Buffer.from(name, 'utf8')
36
+ const body = compress ? zlib.deflateRawSync(bytes) : bytes
37
+ const method = compress ? 8 : 0
38
+ const crc = zlib.crc32(bytes) >>> 0
39
+ if (offset + body.length + 30 + nameBytes.length > 0xffffffff) throw new Error('the export is too large for one zip')
40
+ const header = Buffer.alloc(30)
41
+ header.writeUInt32LE(0x04034b50, 0)
42
+ header.writeUInt16LE(20, 4)
43
+ header.writeUInt16LE(0x0800, 6) // UTF-8 names
44
+ header.writeUInt16LE(method, 8)
45
+ header.writeUInt16LE(stamp.time, 10)
46
+ header.writeUInt16LE(stamp.date, 12)
47
+ header.writeUInt32LE(crc, 14)
48
+ header.writeUInt32LE(body.length, 18)
49
+ header.writeUInt32LE(bytes.length, 22)
50
+ header.writeUInt16LE(nameBytes.length, 26)
51
+ header.writeUInt16LE(0, 28)
52
+ central.push({ nameBytes, method, crc, compressed: body.length, size: bytes.length, offset })
53
+ await emit(Buffer.concat([header, nameBytes]))
54
+ await emit(body)
55
+ }
56
+
57
+ async function finish() {
58
+ const start = offset
59
+ for (const entry of central) {
60
+ const record = Buffer.alloc(46)
61
+ record.writeUInt32LE(0x02014b50, 0)
62
+ record.writeUInt16LE(20, 4)
63
+ record.writeUInt16LE(20, 6)
64
+ record.writeUInt16LE(entry.flags ?? 0x0800, 8)
65
+ record.writeUInt16LE(entry.method, 10)
66
+ record.writeUInt16LE(stamp.time, 12)
67
+ record.writeUInt16LE(stamp.date, 14)
68
+ record.writeUInt32LE(entry.crc, 16)
69
+ record.writeUInt32LE(entry.compressed, 20)
70
+ record.writeUInt32LE(entry.size, 24)
71
+ record.writeUInt16LE(entry.nameBytes.length, 28)
72
+ record.writeUInt32LE(entry.offset, 42)
73
+ await emit(Buffer.concat([record, entry.nameBytes]))
74
+ }
75
+ const end = Buffer.alloc(22)
76
+ end.writeUInt32LE(0x06054b50, 0)
77
+ end.writeUInt16LE(central.length, 8)
78
+ end.writeUInt16LE(central.length, 10)
79
+ end.writeUInt32LE(offset - start, 12)
80
+ end.writeUInt32LE(start, 16)
81
+ await emit(end)
82
+ }
83
+
84
+ // An entry written in pieces (the audit log, page by page), deflated, with
85
+ // its CRC and sizes in a data descriptor after the data (flag bit 3) and
86
+ // in the central directory. Each piece is its own sync-flushed deflate
87
+ // block, so nothing but the current piece is held in memory.
88
+ // stream(name) -> { write(data), end() }; one at a time, add() waits.
89
+ function stream(name) {
90
+ if (central.length >= MAX_ENTRIES) throw new Error('too many files for one zip')
91
+ const nameBytes = Buffer.from(name, 'utf8')
92
+ const entry = { nameBytes, method: 8, crc: 0, compressed: 0, size: 0, offset, flags: 0x0808 }
93
+ const header = Buffer.alloc(30)
94
+ header.writeUInt32LE(0x04034b50, 0)
95
+ header.writeUInt16LE(20, 4)
96
+ header.writeUInt16LE(entry.flags, 6) // UTF-8 names, sizes after the data
97
+ header.writeUInt16LE(8, 8)
98
+ header.writeUInt16LE(stamp.time, 10)
99
+ header.writeUInt16LE(stamp.date, 12)
100
+ header.writeUInt16LE(nameBytes.length, 26)
101
+ const started = emit(Buffer.concat([header, nameBytes]))
102
+ const piece = async (bytes, flush) => {
103
+ await started
104
+ const body = zlib.deflateRawSync(bytes, { finishFlush: flush })
105
+ // (crc32 of an empty buffer can answer 0 instead of the running value.)
106
+ if (bytes.length) entry.crc = zlib.crc32(bytes, entry.crc) >>> 0
107
+ entry.size += bytes.length
108
+ entry.compressed += body.length
109
+ if (offset + body.length + 16 > 0xffffffff) throw new Error('the export is too large for one zip')
110
+ if (body.length) await emit(body)
111
+ }
112
+ return {
113
+ write: (data) => piece(Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'utf8'), zlib.constants.Z_SYNC_FLUSH),
114
+ async end() {
115
+ await piece(Buffer.alloc(0), zlib.constants.Z_FINISH)
116
+ const descriptor = Buffer.alloc(16)
117
+ descriptor.writeUInt32LE(0x08074b50, 0)
118
+ descriptor.writeUInt32LE(entry.crc, 4)
119
+ descriptor.writeUInt32LE(entry.compressed, 8)
120
+ descriptor.writeUInt32LE(entry.size, 12)
121
+ await emit(descriptor)
122
+ central.push(entry)
123
+ },
124
+ }
125
+ }
126
+
127
+ return { add, stream, finish }
128
+ }
129
+
130
+ // Reads a zip made by createZip back into { name: Buffer } (for tests).
131
+ export function readZip(buffer) {
132
+ const out = {}
133
+ const endAt = buffer.lastIndexOf(Buffer.from([0x50, 0x4b, 0x05, 0x06]))
134
+ if (endAt < 0) throw new Error('not a zip')
135
+ const count = buffer.readUInt16LE(endAt + 10)
136
+ let at = buffer.readUInt32LE(endAt + 16)
137
+ for (let index = 0; index < count; index += 1) {
138
+ if (buffer.readUInt32LE(at) !== 0x02014b50) throw new Error('bad central directory')
139
+ const method = buffer.readUInt16LE(at + 10)
140
+ const crc = buffer.readUInt32LE(at + 16)
141
+ const compressed = buffer.readUInt32LE(at + 20)
142
+ const nameLength = buffer.readUInt16LE(at + 28)
143
+ const extraLength = buffer.readUInt16LE(at + 30)
144
+ const commentLength = buffer.readUInt16LE(at + 32)
145
+ const local = buffer.readUInt32LE(at + 42)
146
+ const name = buffer.subarray(at + 46, at + 46 + nameLength).toString('utf8')
147
+ const dataAt = local + 30 + buffer.readUInt16LE(local + 26) + buffer.readUInt16LE(local + 28)
148
+ const raw = buffer.subarray(dataAt, dataAt + compressed)
149
+ const data = method === 8 ? zlib.inflateRawSync(raw) : Buffer.from(raw)
150
+ if (zlib.crc32(data) >>> 0 !== crc) throw new Error(`bad CRC for ${name}`)
151
+ out[name] = data
152
+ at += 46 + nameLength + extraLength + commentLength
153
+ }
154
+ return out
155
+ }
@@ -0,0 +1,58 @@
1
+ // How this `shapewall` was started, so messages print a command that works
2
+ // for the person reading them: "npx shapewall" from npm, a GitHub spec for
3
+ // an unreleased build, a local install, a global one or the checkout itself.
4
+
5
+ import fs from 'node:fs'
6
+ import path from 'node:path'
7
+ import { fileURLToPath } from 'node:url'
8
+
9
+ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
10
+
11
+ // The npx cache keeps the spec it installed in a package.json two folders
12
+ // up: { "dependencies": { "shapewall": "github:danbaruch/shapewall" } }.
13
+ function npxSpec(root, readFile) {
14
+ try {
15
+ const spec = JSON.parse(readFile(path.join(root, '..', '..', 'package.json'), 'utf8'))?.dependencies?.shapewall
16
+ // A local tarball or folder (file:...) is relative to the npx cache, so no use to print.
17
+ if (typeof spec === 'string' && spec.startsWith('file:')) return null
18
+ if (typeof spec === 'string' && /^[\w@:/.#+^~-]{1,200}$/.test(spec))
19
+ return /^[\d^~]/.test(spec) || spec === 'latest' ? 'shapewall' : spec
20
+ } catch {
21
+ /* not there */
22
+ }
23
+ return 'shapewall'
24
+ }
25
+
26
+ const NEUTRAL = {
27
+ how: 'unknown',
28
+ command: 'shapewall',
29
+ note: 'run it the way you started this command (npx shapewall, or shapewall after a global install)',
30
+ }
31
+
32
+ // Returns { how, command, note }: how is npx, local, global, direct or
33
+ // unknown; command is what to type before the subcommand; note is set when
34
+ // the guess is a neutral "shapewall".
35
+ export function invocation({ argv1 = process.argv[1], root = ROOT, cwd = process.cwd(), readFile = fs.readFileSync } = {}) {
36
+ const sep = path.sep
37
+ if (root.includes(`${sep}_npx${sep}`)) {
38
+ const spec = npxSpec(root, readFile)
39
+ return spec ? { how: 'npx', command: `npx ${spec}`, note: null } : { ...NEUTRAL, how: 'npx' }
40
+ }
41
+ const script = argv1 ? path.resolve(cwd, argv1) : ''
42
+ const base = path.basename(script)
43
+ if (base === 'shapewall' || base === 'shapewall.cmd') {
44
+ if (script.includes(`${sep}node_modules${sep}.bin${sep}`)) return { how: 'local', command: 'npx shapewall', note: null }
45
+ return { how: 'global', command: 'shapewall', note: null }
46
+ }
47
+ if (script === path.join(root, 'bin', 'shapewall.js')) {
48
+ const relative = path.relative(cwd, script)
49
+ const shown = relative && !relative.startsWith(`..${sep}..${sep}..`) ? relative : script
50
+ return { how: 'direct', command: `node ${shown.includes(' ') ? JSON.stringify(shown) : shown}`, note: null }
51
+ }
52
+ return { ...NEUTRAL }
53
+ }
54
+
55
+ // "shapewall doctor" for this invocation, e.g. "npx shapewall doctor".
56
+ export function cliCommand(args, options) {
57
+ return `${invocation(options).command}${args ? ` ${args}` : ''}`
58
+ }
@@ -0,0 +1,282 @@
1
+ // Branching journeys: a journey's `steps` is a list of page ids, and any
2
+ // item after a page may instead be a fork that splits into named branches:
3
+ //
4
+ // ["home", "signup", { "branches": [
5
+ // { "id": "link-ok", "label": "Link works", "steps": ["verify"] },
6
+ // { "id": "link-expired", "label": "Link expired", "steps": ["verify-expired", "verify"] }
7
+ // ] }, "welcome"]
8
+ //
9
+ // Every branch rejoins at the item after the fork, unless it has
10
+ // `end: true` (the journey stops there, e.g. "card declined"). Branches may
11
+ // fork again, up to FORK_DEPTH_MAX deep. A list of plain page ids is a
12
+ // linear journey, exactly as before branches existed.
13
+ //
14
+ // Pure functions with no imports, so the server, the CLI, the MCP server and
15
+ // the board client all read journeys the same way.
16
+
17
+ export const BRANCHES_MIN = 2
18
+ export const BRANCHES_MAX = 6
19
+ export const BRANCH_LABEL_MAX = 60
20
+ export const FORK_DEPTH_MAX = 3
21
+ export const JOURNEY_PATHS_MAX = 64
22
+ const BRANCH_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/
23
+
24
+ export function isFork(item) {
25
+ return Boolean(item) && typeof item === 'object' && !Array.isArray(item) && Array.isArray(item.branches)
26
+ }
27
+
28
+ export function isBranching(steps) {
29
+ return Array.isArray(steps) && steps.some(isFork)
30
+ }
31
+
32
+ function slug(text) {
33
+ return (
34
+ String(text || '')
35
+ .toLowerCase()
36
+ .replace(/[^a-z0-9]+/g, '-')
37
+ .replace(/^-+|-+$/g, '')
38
+ .slice(0, 40) || 'branch'
39
+ )
40
+ }
41
+
42
+ // Validates and normalizes a journey's steps (linear or branching). Pushes
43
+ // one message per problem, each prefixed with `where`; returns the clean
44
+ // steps, or null if there was any problem. `stepsMax` caps the page
45
+ // references across every branch.
46
+ export function checkSteps(raw, pageIds, where, problems, { stepsMax = 50 } = {}) {
47
+ const before = problems.length
48
+ let pages = 0
49
+ const list = (items, at, depth, hasNext) => {
50
+ if (!Array.isArray(items)) {
51
+ problems.push(`${at}: a list of page ids and forks`)
52
+ return []
53
+ }
54
+ return items.map((item, index) => {
55
+ const here = `${at}[${index}]`
56
+ if (typeof item === 'string') {
57
+ if (!pageIds.has(item)) problems.push(`${here}: no page ${JSON.stringify(item)} on this board`)
58
+ pages += 1
59
+ return item
60
+ }
61
+ if (!isFork(item)) {
62
+ problems.push(`${here}: no page ${JSON.stringify(item)} on this board`)
63
+ return item
64
+ }
65
+ return fork(item, here, depth + 1, index, items, hasNext)
66
+ })
67
+ }
68
+ const fork = (item, here, depth, index, items, hasNext) => {
69
+ if (typeof items[index - 1] !== 'string') problems.push(`${here}: a fork follows a page (it cannot come first or right after a fork)`)
70
+ if (depth > FORK_DEPTH_MAX) problems.push(`${here}: forks nest at most ${FORK_DEPTH_MAX} deep`)
71
+ const { branches } = item
72
+ if (branches.length < BRANCHES_MIN || branches.length > BRANCHES_MAX) {
73
+ problems.push(`${here}.branches: ${BRANCHES_MIN} to ${BRANCHES_MAX} branches`)
74
+ }
75
+ const followed = index < items.length - 1 || hasNext
76
+ const ids = new Set()
77
+ const clean = branches.map((branch, at) => {
78
+ const where = `${here}.branches[${at}]`
79
+ if (!branch || typeof branch !== 'object' || Array.isArray(branch)) {
80
+ problems.push(`${where}: a branch is an object with label and steps`)
81
+ return null
82
+ }
83
+ const label = typeof branch.label === 'string' ? branch.label.replace(/\s+/g, ' ').trim() : ''
84
+ if (!label || label.length > BRANCH_LABEL_MAX) problems.push(`${where}.label: 1 to ${BRANCH_LABEL_MAX} characters`)
85
+ const id = branch.id === undefined ? slug(label) : branch.id
86
+ if (typeof id !== 'string' || !BRANCH_ID_RE.test(id)) {
87
+ problems.push(`${where}.id: lowercase letters, digits and dashes (got ${JSON.stringify(branch.id)})`)
88
+ } else if (ids.has(id)) {
89
+ problems.push(`${where}.id: "${id}" is used by another branch of this fork`)
90
+ }
91
+ ids.add(id)
92
+ if (branch.end !== undefined && typeof branch.end !== 'boolean') problems.push(`${where}.end: true or false`)
93
+ const end = branch.end === true
94
+ if (!Array.isArray(branch.steps)) {
95
+ problems.push(`${where}.steps: a list of page ids (empty to skip straight to the step after the fork)`)
96
+ return null
97
+ }
98
+ if (!branch.steps.length && (end || !followed)) {
99
+ problems.push(`${where}.steps: an empty branch needs a step after the fork to go to`)
100
+ }
101
+ const steps = list(branch.steps, `${where}.steps`, depth, !end && followed)
102
+ return { id, label, steps, ...(end ? { end: true } : {}) }
103
+ })
104
+ if (clean.length && clean.every((branch) => branch?.end) && index < items.length - 1) {
105
+ problems.push(`${here}: every branch ends, so nothing can follow this fork`)
106
+ }
107
+ return { branches: clean }
108
+ }
109
+ if (!Array.isArray(raw)) {
110
+ problems.push(`${where}: 2 to ${stepsMax} page ids, in order`)
111
+ return null
112
+ }
113
+ const steps = list(raw, where, 0, false)
114
+ if (problems.length > before) return null
115
+ if (pages < 2 || pages > stepsMax) {
116
+ problems.push(`${where}: 2 to ${stepsMax} page ids, in order${isBranching(steps) ? ' (counting every branch)' : ''}`)
117
+ return null
118
+ }
119
+ if (countPaths(steps) > JOURNEY_PATHS_MAX) {
120
+ problems.push(`${where}: at most ${JOURNEY_PATHS_MAX} different paths through the forks`)
121
+ return null
122
+ }
123
+ return steps
124
+ }
125
+
126
+ // How many different paths the forks allow (stops counting past the cap).
127
+ function countPaths(steps) {
128
+ const count = (items) => {
129
+ let total = 1
130
+ for (const item of items) {
131
+ if (!isFork(item)) continue
132
+ total *= item.branches.reduce((sum, branch) => sum + count(branch.steps), 0)
133
+ if (total > JOURNEY_PATHS_MAX) return JOURNEY_PATHS_MAX + 1
134
+ }
135
+ return total
136
+ }
137
+ return count(steps)
138
+ }
139
+
140
+ // Every page id the journey visits on any branch, once each, in order.
141
+ export function journeyPages(steps) {
142
+ const seen = new Set()
143
+ const walk = (items) => {
144
+ for (const item of items || []) {
145
+ if (typeof item === 'string') seen.add(item)
146
+ else if (isFork(item)) for (const branch of item.branches) walk(branch.steps)
147
+ }
148
+ }
149
+ walk(steps)
150
+ return [...seen]
151
+ }
152
+
153
+ // Every step as a node (a page can be visited at several positions) and
154
+ // every arrow between them. Node keys are positions: "3" is the 4th item,
155
+ // "2:1:0" the first step of the 2nd branch of the fork at item 2. Arrows
156
+ // into a branch carry its label. { nodes: [{ key, pageId }], edges: [{ from,
157
+ // to, label, branch }] }
158
+ export function journeyGraph(steps) {
159
+ const nodes = []
160
+ const edges = []
161
+ // `pending`: where arrows to the next step come from (a page node, maybe
162
+ // with the label of the branch it enters).
163
+ const walk = (items, prefix, pending) => {
164
+ let from = pending
165
+ items.forEach((item, index) => {
166
+ const key = prefix ? `${prefix}:${index}` : String(index)
167
+ if (typeof item === 'string') {
168
+ nodes.push({ key, pageId: item })
169
+ for (const source of from) {
170
+ edges.push({ from: source.key, to: key, label: source.label || null, branch: source.branch || null })
171
+ }
172
+ from = [{ key }]
173
+ return
174
+ }
175
+ if (!isFork(item)) return
176
+ const next = []
177
+ item.branches.forEach((branch, at) => {
178
+ const entering = from.map((source) => ({ key: source.key, label: branch.label, branch: branch.id }))
179
+ const out = walk(branch.steps, `${key}:${at}`, entering)
180
+ if (!branch.end) next.push(...out)
181
+ })
182
+ from = next
183
+ })
184
+ return from
185
+ }
186
+ walk(steps || [], '', [])
187
+ return { nodes, edges }
188
+ }
189
+
190
+ // One way through the journey: at the n-th fork reached, take the branch
191
+ // with id choices[n] (the first branch when missing or unknown).
192
+ // Returns { steps: [{ key, pageId, branch }], forks: [{ afterStep, options,
193
+ // chosen }], ended }: `branch` is the label of the branch a step is on (the
194
+ // innermost), `afterStep` the 1-based step whose page the fork leaves from,
195
+ // `ended` whether the path stopped in a branch marked `end`.
196
+ export function resolvePath(steps, choices = []) {
197
+ const path = []
198
+ const forks = []
199
+ let ended = false
200
+ const walk = (items, prefix, branchLabel) => {
201
+ for (let index = 0; index < items.length; index += 1) {
202
+ if (ended) return
203
+ const item = items[index]
204
+ const key = prefix ? `${prefix}:${index}` : String(index)
205
+ if (typeof item === 'string') {
206
+ path.push({ key, pageId: item, branch: branchLabel })
207
+ continue
208
+ }
209
+ if (!isFork(item) || !item.branches.length) continue
210
+ const wanted = choices[forks.length]
211
+ const at = Math.max(
212
+ 0,
213
+ item.branches.findIndex((branch) => branch.id === wanted),
214
+ )
215
+ const branch = item.branches[at]
216
+ forks.push({
217
+ afterStep: path.length,
218
+ options: item.branches.map((option) => ({ id: option.id, label: option.label, end: Boolean(option.end) })),
219
+ chosen: branch.id,
220
+ })
221
+ walk(branch.steps, `${key}:${at}`, branch.label)
222
+ if (branch.end) ended = true
223
+ }
224
+ }
225
+ walk(steps || [], '', null)
226
+ return { steps: path, forks, ended }
227
+ }
228
+
229
+ // The choices for a new pick: keep what was chosen before fork `ordinal`,
230
+ // take `id` there, and let later forks fall back to their first branch.
231
+ export function chooseBranch(route, ordinal, id) {
232
+ return [...route.forks.slice(0, ordinal).map((fork) => fork.chosen), id]
233
+ }
234
+
235
+ // Every path through the forks (at most JOURNEY_PATHS_MAX): { choices,
236
+ // labels, steps: [pageId], ended }.
237
+ export function journeyPaths(steps) {
238
+ const out = []
239
+ const visit = (prefix) => {
240
+ if (out.length >= JOURNEY_PATHS_MAX) return
241
+ const route = resolvePath(steps, prefix)
242
+ if (route.forks.length > prefix.length) {
243
+ for (const option of route.forks[prefix.length].options) visit([...prefix, option.id])
244
+ return
245
+ }
246
+ out.push({
247
+ choices: route.forks.map((fork) => fork.chosen),
248
+ labels: route.forks.map((fork) => fork.options.find((option) => option.id === fork.chosen).label),
249
+ steps: route.steps.map((step) => step.pageId),
250
+ ended: route.ended,
251
+ })
252
+ }
253
+ visit([])
254
+ return out
255
+ }
256
+
257
+ // Drops steps whose page is not in `keep` (a page that left the config).
258
+ // A fork left with one branch becomes that branch's steps; one left with
259
+ // none disappears. The result may be invalid (a fork right at the start);
260
+ // callers check it again.
261
+ export function pruneSteps(steps, keep) {
262
+ const prune = (items) => {
263
+ const out = []
264
+ for (const item of items) {
265
+ if (typeof item === 'string') {
266
+ if (keep.has(item)) out.push(item)
267
+ continue
268
+ }
269
+ if (!isFork(item)) continue
270
+ const branches = item.branches
271
+ .map((branch) => ({ ...branch, steps: prune(branch.steps || []) }))
272
+ .filter((branch) => branch.steps.length || !branch.end)
273
+ if (branches.length >= 2) out.push({ branches })
274
+ else if (branches.length === 1) {
275
+ out.push(...branches[0].steps)
276
+ if (branches[0].end) return out
277
+ }
278
+ }
279
+ return out
280
+ }
281
+ return prune(Array.isArray(steps) ? steps : [])
282
+ }