@johnhenry/mallory-cli 0.0.0-stage → 0.1.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 (760) hide show
  1. package/README.md +60 -2
  2. package/bin/mallory.mjs +51 -0
  3. package/package.json +51 -4
  4. package/src/a2a/client.js +511 -0
  5. package/src/a2a/demo-agent.js +396 -0
  6. package/src/a2a/hub.js +578 -0
  7. package/src/a2a/settings.js +88 -0
  8. package/src/a2a/task.js +358 -0
  9. package/src/acp/client.js +573 -0
  10. package/src/acp/demo-agent.js +332 -0
  11. package/src/acp/hub.js +632 -0
  12. package/src/acp/settings.js +78 -0
  13. package/src/actions/map.js +524 -0
  14. package/src/agent/cloud.js +77 -0
  15. package/src/agent/compact.js +84 -0
  16. package/src/agent/constants.js +39 -0
  17. package/src/agent/diff.js +101 -0
  18. package/src/agent/fork.js +159 -0
  19. package/src/agent/grounding.js +73 -0
  20. package/src/agent/guards.js +129 -0
  21. package/src/agent/local-transport.js +152 -0
  22. package/src/agent/loop.js +479 -0
  23. package/src/agent/park-store.js +77 -0
  24. package/src/agent/park.js +76 -0
  25. package/src/agent/ports.js +28 -0
  26. package/src/agent/providers.js +591 -0
  27. package/src/agent/restart.js +51 -0
  28. package/src/agent/router.js +380 -0
  29. package/src/agent/run.js +861 -0
  30. package/src/agent/tools.js +247 -0
  31. package/src/agent-library/engine.js +43 -0
  32. package/src/ai/bridge.js +155 -0
  33. package/src/ai/policy.js +131 -0
  34. package/src/aimatey/vendor.js +18 -0
  35. package/src/audio/container-duration.js +35 -0
  36. package/src/audio/instruments.js +776 -0
  37. package/src/audio/lanes.js +230 -0
  38. package/src/audio/patch.js +1410 -0
  39. package/src/audio/plan.js +276 -0
  40. package/src/audio/rack.js +1006 -0
  41. package/src/audio/sample-trim.js +293 -0
  42. package/src/audio/soundfont.js +243 -0
  43. package/src/audio/take-store.js +87 -0
  44. package/src/audio/takes.js +129 -0
  45. package/src/audio/wav.js +170 -0
  46. package/src/audio/zzfx.js +333 -0
  47. package/src/autonomy/bundle.js +207 -0
  48. package/src/autonomy/confine.js +61 -0
  49. package/src/autonomy/enforce.js +155 -0
  50. package/src/autonomy/file-kv.js +88 -0
  51. package/src/autonomy/ledger.js +203 -0
  52. package/src/autonomy/pins.js +50 -0
  53. package/src/autonomy/psl/index.js +32 -0
  54. package/src/autonomy/psl/suffixes.json +1 -0
  55. package/src/autonomy/record.js +28 -0
  56. package/src/autonomy/routines.js +107 -0
  57. package/src/autonomy/server.js +175 -0
  58. package/src/autonomy/signer-node.js +167 -0
  59. package/src/autonomy/store.js +43 -0
  60. package/src/autonomy/unattended.js +13 -0
  61. package/src/bytes/bytes.js +378 -0
  62. package/src/calc/syntax.js +125 -0
  63. package/src/calc/tex.js +28 -0
  64. package/src/calendar/vendor.js +2 -0
  65. package/src/clipboard.js +130 -0
  66. package/src/clsh/clsh.js +3417 -0
  67. package/src/codec/capnp.js +1804 -0
  68. package/src/codec/core.js +2043 -0
  69. package/src/codec/vendor/avro.js +136 -0
  70. package/src/codec/vendor/cbor.js +25 -0
  71. package/src/codec/vendor/flatbuffers.js +206 -0
  72. package/src/codec/vendor/msgpack.js +9 -0
  73. package/src/codec/vendor/protobuf.js +53 -0
  74. package/src/delegation/caps.js +60 -0
  75. package/src/delegation/config.js +32 -0
  76. package/src/device/model.js +246 -0
  77. package/src/device/recording.js +198 -0
  78. package/src/device/stream-model.js +151 -0
  79. package/src/documents/documents.js +1224 -0
  80. package/src/effects/catalog.js +63 -0
  81. package/src/effects/extras.js +133 -0
  82. package/src/effects/parse.js +339 -0
  83. package/src/embed/protocol.js +131 -0
  84. package/src/env/env.js +159 -0
  85. package/src/exact/vendor.js +45 -0
  86. package/src/example-meta.js +164 -0
  87. package/src/examples.js +94 -0
  88. package/src/export/canvas-image.js +217 -0
  89. package/src/export/expr-latex-lazy.js +8 -0
  90. package/src/export/formats.js +322 -0
  91. package/src/export/latex.js +183 -0
  92. package/src/export/pane.js +184 -0
  93. package/src/export/value.js +452 -0
  94. package/src/export/zip.js +214 -0
  95. package/src/ext/access.js +58 -0
  96. package/src/ext/btasks.js +225 -0
  97. package/src/ext/client.js +209 -0
  98. package/src/ext/tools.js +69 -0
  99. package/src/ext/view.js +105 -0
  100. package/src/ext/webmcp-tabs.js +299 -0
  101. package/src/files/archive.js +232 -0
  102. package/src/files/files.js +317 -0
  103. package/src/formats/json.js +24 -0
  104. package/src/formats/jupyter.js +188 -0
  105. package/src/formats/markdown.js +254 -0
  106. package/src/formats/n8n.js +276 -0
  107. package/src/formats/node-red.js +363 -0
  108. package/src/formats/registry.js +177 -0
  109. package/src/formats/rivet.js +259 -0
  110. package/src/formats/shared.js +98 -0
  111. package/src/formats/structure.js +182 -0
  112. package/src/formats/yaml.js +127 -0
  113. package/src/frame/frame.js +962 -0
  114. package/src/frame/vendor.js +1484 -0
  115. package/src/gate/audit.js +116 -0
  116. package/src/gate/gate.js +365 -0
  117. package/src/gate/policy.js +295 -0
  118. package/src/gate/scripted.js +110 -0
  119. package/src/gate/seams.js +32 -0
  120. package/src/gate/store.js +66 -0
  121. package/src/geometry/model.js +533 -0
  122. package/src/grant-key.js +149 -0
  123. package/src/graph/model.js +381 -0
  124. package/src/headless/a2a-push.js +123 -0
  125. package/src/headless/channels/config.js +142 -0
  126. package/src/headless/channels/connectors.js +283 -0
  127. package/src/headless/channels/index.js +257 -0
  128. package/src/headless/channels/mail.js +197 -0
  129. package/src/headless/channels/mailnet.js +223 -0
  130. package/src/headless/channels/platforms.js +194 -0
  131. package/src/headless/channels/replay.js +49 -0
  132. package/src/headless/cli.js +1397 -0
  133. package/src/headless/companion-client.js +182 -0
  134. package/src/headless/cost-cli.js +177 -0
  135. package/src/headless/deprecations-cli.js +102 -0
  136. package/src/headless/examples.js +48 -0
  137. package/src/headless/ffmpeg-exec.js +217 -0
  138. package/src/headless/gateways/config.js +213 -0
  139. package/src/headless/gateways/homeassistant.js +159 -0
  140. package/src/headless/gateways/index.js +121 -0
  141. package/src/headless/gateways/matter.js +150 -0
  142. package/src/headless/gateways/mqtt-client.js +177 -0
  143. package/src/headless/gateways/mqtt.js +70 -0
  144. package/src/headless/gateways/netway.js +226 -0
  145. package/src/headless/gateways/serverpod-worker.mjs +16 -0
  146. package/src/headless/gateways/serverpod.js +71 -0
  147. package/src/headless/gateways/util.js +27 -0
  148. package/src/headless/grant-cli.js +208 -0
  149. package/src/headless/guard.js +125 -0
  150. package/src/headless/guards.js +124 -0
  151. package/src/headless/machine-cli.js +853 -0
  152. package/src/headless/mcp-endpoint.js +287 -0
  153. package/src/headless/mcp-roots.js +38 -0
  154. package/src/headless/model-endpoint.js +88 -0
  155. package/src/headless/net.js +151 -0
  156. package/src/headless/node.js +263 -0
  157. package/src/headless/npm-tarball.js +29 -0
  158. package/src/headless/operator-page.js +112 -0
  159. package/src/headless/operator.js +242 -0
  160. package/src/headless/people.js +34 -0
  161. package/src/headless/pkg-cli.js +1103 -0
  162. package/src/headless/pkg-serve.js +138 -0
  163. package/src/headless/process-worker.js +88 -0
  164. package/src/headless/runner-remote.js +477 -0
  165. package/src/headless/sandbox-child.mjs +21 -0
  166. package/src/headless/scheduled.js +557 -0
  167. package/src/headless/serve-stream.js +97 -0
  168. package/src/headless/serve.js +2238 -0
  169. package/src/headless/short-links.js +158 -0
  170. package/src/headless/static-dirs.js +207 -0
  171. package/src/headless/trust-file.js +51 -0
  172. package/src/headless/watch.js +291 -0
  173. package/src/headless/ws-connect.js +65 -0
  174. package/src/headless/ws-connections.js +44 -0
  175. package/src/headless/ws-echo.js +150 -0
  176. package/src/headless/ws-proxy.js +354 -0
  177. package/src/headless/ws-ticket.js +48 -0
  178. package/src/hooks/config.js +50 -0
  179. package/src/hooks/engine.js +189 -0
  180. package/src/input/log.js +613 -0
  181. package/src/input/player.js +217 -0
  182. package/src/input/replay.js +209 -0
  183. package/src/jth/vendor.js +28 -0
  184. package/src/ledger/tx.js +94 -0
  185. package/src/machine/apply.js +193 -0
  186. package/src/machine/diff.js +168 -0
  187. package/src/machine/drive.js +296 -0
  188. package/src/machine/engine.js +478 -0
  189. package/src/machine/files-tool.js +76 -0
  190. package/src/machine/lint.js +139 -0
  191. package/src/machine/llmtm-trace.js +117 -0
  192. package/src/machine/llmtm.js +475 -0
  193. package/src/machine/otel.js +80 -0
  194. package/src/machine/pane-provider.js +51 -0
  195. package/src/machine/propose.js +159 -0
  196. package/src/machine/random.js +52 -0
  197. package/src/machine/risk.js +107 -0
  198. package/src/machine/session.js +1017 -0
  199. package/src/machine/shell-tool.js +45 -0
  200. package/src/machine/tape.js +349 -0
  201. package/src/machine/templates.js +104 -0
  202. package/src/machine/trace.js +664 -0
  203. package/src/machine/view.js +73 -0
  204. package/src/machine/vm-tool.js +47 -0
  205. package/src/machine/watchdog.js +46 -0
  206. package/src/mcp/app-args.js +51 -0
  207. package/src/mcp/app-run.js +56 -0
  208. package/src/mcp/apps.js +468 -0
  209. package/src/mcp/cache.js +232 -0
  210. package/src/mcp/client.js +507 -0
  211. package/src/mcp/demo-app.js +183 -0
  212. package/src/mcp/demo-server.js +602 -0
  213. package/src/mcp/elicitation.js +116 -0
  214. package/src/mcp/hub.js +1326 -0
  215. package/src/mcp/roots.js +139 -0
  216. package/src/mcp/sampling.js +105 -0
  217. package/src/mcp/settings.js +125 -0
  218. package/src/mcp/tape.js +292 -0
  219. package/src/mcp/uri-template.js +156 -0
  220. package/src/mcp/wsh-client.js +164 -0
  221. package/src/media/animated-codec.js +7 -0
  222. package/src/media/animated.js +623 -0
  223. package/src/media/compare-agent.js +70 -0
  224. package/src/media/compare-job.js +63 -0
  225. package/src/media/compare-page.js +296 -0
  226. package/src/media/compare-worker.js +14 -0
  227. package/src/media/compare.js +600 -0
  228. package/src/media/contract.js +62 -0
  229. package/src/media/decode-frame.js +57 -0
  230. package/src/media/decode-pool.js +188 -0
  231. package/src/media/ffmpeg-edit.js +344 -0
  232. package/src/media/ffmpeg-wasm-client.js +121 -0
  233. package/src/media/ffmpeg-wasm-session.js +79 -0
  234. package/src/media/ffmpeg-wasm.js +139 -0
  235. package/src/media/ffmpeg-worker.js +23 -0
  236. package/src/media/ffmpeg.js +903 -0
  237. package/src/media/helpers.js +419 -0
  238. package/src/media/keep.js +108 -0
  239. package/src/media/metadata-worker.js +16 -0
  240. package/src/media/metadata.js +2518 -0
  241. package/src/media/mime.js +102 -0
  242. package/src/media/page-decode.js +74 -0
  243. package/src/media/persist.js +114 -0
  244. package/src/media/png.js +226 -0
  245. package/src/media/sample-input.js +67 -0
  246. package/src/media/store.js +86 -0
  247. package/src/media/wav.js +109 -0
  248. package/src/midi/mappings.js +250 -0
  249. package/src/midi/message.js +125 -0
  250. package/src/model/action-hub.js +143 -0
  251. package/src/model/adapters.js +284 -0
  252. package/src/model/agent-runs.js +12 -0
  253. package/src/model/arrange.js +308 -0
  254. package/src/model/automation-clock.js +494 -0
  255. package/src/model/automation.js +653 -0
  256. package/src/model/batches.js +78 -0
  257. package/src/model/binary-view.js +195 -0
  258. package/src/model/breakpoints.js +392 -0
  259. package/src/model/calc-settings.js +65 -0
  260. package/src/model/calendar.js +254 -0
  261. package/src/model/canvas-id.js +5 -0
  262. package/src/model/canvas.js +5048 -0
  263. package/src/model/channel-names.js +29 -0
  264. package/src/model/channels.js +692 -0
  265. package/src/model/chart-clock.js +631 -0
  266. package/src/model/chart-code.js +69 -0
  267. package/src/model/codecs.js +60 -0
  268. package/src/model/companion-access.js +271 -0
  269. package/src/model/companion-pane.js +50 -0
  270. package/src/model/composite.js +324 -0
  271. package/src/model/context.js +380 -0
  272. package/src/model/controls.js +231 -0
  273. package/src/model/converter-presets.js +368 -0
  274. package/src/model/cost.js +580 -0
  275. package/src/model/curve-transform.js +122 -0
  276. package/src/model/cycles.js +176 -0
  277. package/src/model/debug-log.js +168 -0
  278. package/src/model/decision-clock.js +100 -0
  279. package/src/model/decisions.js +265 -0
  280. package/src/model/desk.js +87 -0
  281. package/src/model/device-hub.js +400 -0
  282. package/src/model/diff.js +445 -0
  283. package/src/model/emit-events.js +179 -0
  284. package/src/model/errors.js +238 -0
  285. package/src/model/event-presets.js +297 -0
  286. package/src/model/events.js +1303 -0
  287. package/src/model/explicit-setters.js +139 -0
  288. package/src/model/field-mapping.js +623 -0
  289. package/src/model/files-pane.js +263 -0
  290. package/src/model/flow-idle.js +89 -0
  291. package/src/model/foreach.js +549 -0
  292. package/src/model/frame-loop.js +71 -0
  293. package/src/model/frame-pressure.js +180 -0
  294. package/src/model/function-scaffold.js +1000 -0
  295. package/src/model/geometry-settings.js +54 -0
  296. package/src/model/goals.js +176 -0
  297. package/src/model/graph-settings.js +76 -0
  298. package/src/model/grid-widget.js +175 -0
  299. package/src/model/groups.js +332 -0
  300. package/src/model/hash.js +21 -0
  301. package/src/model/history.js +259 -0
  302. package/src/model/http-copy.js +88 -0
  303. package/src/model/http-send-companion.js +110 -0
  304. package/src/model/http-send.js +163 -0
  305. package/src/model/http-tap.js +521 -0
  306. package/src/model/http-tools.js +1138 -0
  307. package/src/model/import-lock.js +78 -0
  308. package/src/model/imports.js +258 -0
  309. package/src/model/infer-outputs.js +822 -0
  310. package/src/model/ink-connect.js +150 -0
  311. package/src/model/ink-diff.js +75 -0
  312. package/src/model/ink-gone.js +71 -0
  313. package/src/model/ink-route.js +120 -0
  314. package/src/model/ink-svg.js +206 -0
  315. package/src/model/ink.js +739 -0
  316. package/src/model/input-log-hub.js +456 -0
  317. package/src/model/input-split.js +69 -0
  318. package/src/model/json-schema-host.js +9 -0
  319. package/src/model/json-schema.js +368 -0
  320. package/src/model/jth.js +78 -0
  321. package/src/model/latex-expr.js +528 -0
  322. package/src/model/layout-history.js +120 -0
  323. package/src/model/lazy-map.js +88 -0
  324. package/src/model/ledger-pane.js +101 -0
  325. package/src/model/legacy-viaframe.js +90 -0
  326. package/src/model/lessons.js +448 -0
  327. package/src/model/links.js +981 -0
  328. package/src/model/live.js +411 -0
  329. package/src/model/math-widget.js +53 -0
  330. package/src/model/memory-settings.js +33 -0
  331. package/src/model/midi-controls.js +350 -0
  332. package/src/model/nl-time.js +408 -0
  333. package/src/model/notebook.js +137 -0
  334. package/src/model/pane-view-store.js +15 -0
  335. package/src/model/partial.js +115 -0
  336. package/src/model/pause-clock.js +53 -0
  337. package/src/model/peer-pane.js +32 -0
  338. package/src/model/persist-state.js +290 -0
  339. package/src/model/person-only.js +122 -0
  340. package/src/model/pin.js +209 -0
  341. package/src/model/plot-3d.js +213 -0
  342. package/src/model/plot-series.js +157 -0
  343. package/src/model/plot-settings.js +531 -0
  344. package/src/model/ports.js +312 -0
  345. package/src/model/presentation.js +222 -0
  346. package/src/model/preset-apply.js +316 -0
  347. package/src/model/preset-banks.js +335 -0
  348. package/src/model/preset-morph.js +263 -0
  349. package/src/model/preset-ops.js +205 -0
  350. package/src/model/preset-player.js +283 -0
  351. package/src/model/preset-states.js +172 -0
  352. package/src/model/profile-settings.js +109 -0
  353. package/src/model/promote.js +103 -0
  354. package/src/model/protected.js +10 -0
  355. package/src/model/proxy-log.js +230 -0
  356. package/src/model/proxy.js +367 -0
  357. package/src/model/quantity-widget.js +61 -0
  358. package/src/model/queue-book.js +359 -0
  359. package/src/model/quick-add.js +224 -0
  360. package/src/model/rate-limit.js +313 -0
  361. package/src/model/rate.js +95 -0
  362. package/src/model/recovery.js +216 -0
  363. package/src/model/rename-follow.js +113 -0
  364. package/src/model/repeater.js +1126 -0
  365. package/src/model/retention.js +664 -0
  366. package/src/model/route-edit.js +132 -0
  367. package/src/model/router.js +155 -0
  368. package/src/model/runaway.js +232 -0
  369. package/src/model/runlog.js +1033 -0
  370. package/src/model/runners/a2a.js +2 -0
  371. package/src/model/runners/acp.js +2 -0
  372. package/src/model/runners/actions.js +4 -0
  373. package/src/model/runners/agent.js +4 -0
  374. package/src/model/runners/audio.js +21 -0
  375. package/src/model/runners/automation.js +2 -0
  376. package/src/model/runners/calc.js +23 -0
  377. package/src/model/runners/catch.js +10 -0
  378. package/src/model/runners/codec.js +24 -0
  379. package/src/model/runners/companion-run.js +2 -0
  380. package/src/model/runners/device.js +7 -0
  381. package/src/model/runners/dom.js +13 -0
  382. package/src/model/runners/effects.js +2 -0
  383. package/src/model/runners/embed.js +11 -0
  384. package/src/model/runners/eval.js +2 -0
  385. package/src/model/runners/files.js +19 -0
  386. package/src/model/runners/geometry.js +23 -0
  387. package/src/model/runners/goals.js +18 -0
  388. package/src/model/runners/graph.js +23 -0
  389. package/src/model/runners/html.js +2 -0
  390. package/src/model/runners/http-proxy.js +185 -0
  391. package/src/model/runners/http-send.js +61 -0
  392. package/src/model/runners/http-static.js +83 -0
  393. package/src/model/runners/http-tap.js +26 -0
  394. package/src/model/runners/http.js +40 -0
  395. package/src/model/runners/import.js +2 -0
  396. package/src/model/runners/index.js +74 -0
  397. package/src/model/runners/input.js +14 -0
  398. package/src/model/runners/inputlog.js +7 -0
  399. package/src/model/runners/ledger.js +15 -0
  400. package/src/model/runners/machine.js +4 -0
  401. package/src/model/runners/mcp.js +2 -0
  402. package/src/model/runners/mcpapp.js +2 -0
  403. package/src/model/runners/media.js +18 -0
  404. package/src/model/runners/memory.js +28 -0
  405. package/src/model/runners/mesh-inspect.js +13 -0
  406. package/src/model/runners/peer.js +14 -0
  407. package/src/model/runners/plot.js +22 -0
  408. package/src/model/runners/render.js +14 -0
  409. package/src/model/runners/respond.js +2 -0
  410. package/src/model/runners/sample-soundfont.js +85 -0
  411. package/src/model/runners/sample.js +159 -0
  412. package/src/model/runners/scene.js +8 -0
  413. package/src/model/runners/score.js +24 -0
  414. package/src/model/runners/secret.js +10 -0
  415. package/src/model/runners/select.js +2 -0
  416. package/src/model/runners/shared.js +4 -0
  417. package/src/model/runners/shares.js +15 -0
  418. package/src/model/runners/shell.js +7 -0
  419. package/src/model/runners/skill.js +26 -0
  420. package/src/model/runners/state.js +2 -0
  421. package/src/model/runners/statechart.js +4 -0
  422. package/src/model/runners/subgraph.js +9 -0
  423. package/src/model/runners/tabs.js +25 -0
  424. package/src/model/runners/terminal.js +5 -0
  425. package/src/model/runners/text.js +4 -0
  426. package/src/model/runners/timer.js +7 -0
  427. package/src/model/runners/traffic.js +65 -0
  428. package/src/model/runners/trigger.js +2 -0
  429. package/src/model/runners/verdict.js +29 -0
  430. package/src/model/runners/vm.js +7 -0
  431. package/src/model/runners/wait.js +4 -0
  432. package/src/model/runners/ws-client.js +57 -0
  433. package/src/model/safe-regex.js +719 -0
  434. package/src/model/sample-settings.js +43 -0
  435. package/src/model/sample-source.js +47 -0
  436. package/src/model/saved-mapping.js +153 -0
  437. package/src/model/score-controllers.js +87 -0
  438. package/src/model/score-edit.js +399 -0
  439. package/src/model/score-instruments.js +300 -0
  440. package/src/model/score-library.js +407 -0
  441. package/src/model/score-markup.js +235 -0
  442. package/src/model/score-mix.js +248 -0
  443. package/src/model/score-patterns.js +276 -0
  444. package/src/model/score-selection.js +34 -0
  445. package/src/model/score-time.js +139 -0
  446. package/src/model/score-transforms.js +336 -0
  447. package/src/model/score-transport.js +192 -0
  448. package/src/model/selection.js +351 -0
  449. package/src/model/serial-controls.js +328 -0
  450. package/src/model/shares-pane.js +17 -0
  451. package/src/model/shell-pane.js +106 -0
  452. package/src/model/signature.js +1122 -0
  453. package/src/model/size-hints.js +106 -0
  454. package/src/model/size-ratio.js +12 -0
  455. package/src/model/skill-settings.js +23 -0
  456. package/src/model/snapping.js +466 -0
  457. package/src/model/split.js +375 -0
  458. package/src/model/spring-player.js +222 -0
  459. package/src/model/statecharts.js +1369 -0
  460. package/src/model/states-preset.js +208 -0
  461. package/src/model/static-route.js +100 -0
  462. package/src/model/step-words.js +45 -0
  463. package/src/model/subgraph.js +1042 -0
  464. package/src/model/switch.js +98 -0
  465. package/src/model/tabs-store.js +10 -0
  466. package/src/model/tensor-view.js +146 -0
  467. package/src/model/timer-clock.js +361 -0
  468. package/src/model/timers.js +422 -0
  469. package/src/model/timing.js +212 -0
  470. package/src/model/traffic-agent.js +111 -0
  471. package/src/model/traffic-store.js +20 -0
  472. package/src/model/traffic.js +665 -0
  473. package/src/model/transport.js +364 -0
  474. package/src/model/turns.js +86 -0
  475. package/src/model/types.js +425 -0
  476. package/src/model/value-path.js +138 -0
  477. package/src/model/versions.js +535 -0
  478. package/src/model/view-outputs.js +144 -0
  479. package/src/model/viewport-bookmarks.js +194 -0
  480. package/src/model/virtual-clock.js +85 -0
  481. package/src/model/vm-pane.js +258 -0
  482. package/src/model/wait-clock.js +715 -0
  483. package/src/model/wait-persist.js +248 -0
  484. package/src/model/waits.js +431 -0
  485. package/src/model/watch.js +80 -0
  486. package/src/model/webhook.js +496 -0
  487. package/src/model/when.js +48 -0
  488. package/src/model/widget-values.js +392 -0
  489. package/src/model/window-commands.js +278 -0
  490. package/src/model/windows.js +348 -0
  491. package/src/model/wire-inspect.js +343 -0
  492. package/src/model/wire-ops.js +324 -0
  493. package/src/model/wire-pipeline.js +378 -0
  494. package/src/model/wire-route.js +637 -0
  495. package/src/model/workspaces.js +122 -0
  496. package/src/model/ws-client.js +155 -0
  497. package/src/model/ws-demo.js +31 -0
  498. package/src/model/ws-frames.js +141 -0
  499. package/src/model/ws-hub.js +219 -0
  500. package/src/model/ws-served.js +13 -0
  501. package/src/model/xstate.js +374 -0
  502. package/src/narrative/narrative.js +1557 -0
  503. package/src/network/auth.js +224 -0
  504. package/src/network/csp-frame.js +197 -0
  505. package/src/network/declarative-shadow.js +27 -0
  506. package/src/network/frame-net-shim.js +962 -0
  507. package/src/network/hosts.js +157 -0
  508. package/src/network/policy.js +520 -0
  509. package/src/network/rtc-shim.js +418 -0
  510. package/src/network/secret-gate.js +78 -0
  511. package/src/network/secrets.js +261 -0
  512. package/src/network/sockets.js +287 -0
  513. package/src/network/store.js +186 -0
  514. package/src/network/streams.js +99 -0
  515. package/src/packages/asset-values.js +50 -0
  516. package/src/packages/assets.js +99 -0
  517. package/src/packages/deprecation.js +203 -0
  518. package/src/packages/fetch.js +152 -0
  519. package/src/packages/function-canvas.js +73 -0
  520. package/src/packages/module.js +120 -0
  521. package/src/packages/package.js +474 -0
  522. package/src/packages/published.js +27 -0
  523. package/src/packages/requires.js +83 -0
  524. package/src/packages/signing.js +145 -0
  525. package/src/packages/trust.js +107 -0
  526. package/src/panes/a2a.js +51 -0
  527. package/src/panes/acp.js +60 -0
  528. package/src/panes/actions.js +54 -0
  529. package/src/panes/agent.js +83 -0
  530. package/src/panes/audio.js +103 -0
  531. package/src/panes/automation.js +112 -0
  532. package/src/panes/calc.js +67 -0
  533. package/src/panes/catch.js +52 -0
  534. package/src/panes/codec.js +59 -0
  535. package/src/panes/colors.js +12 -0
  536. package/src/panes/companion.js +54 -0
  537. package/src/panes/decision.js +65 -0
  538. package/src/panes/device.js +56 -0
  539. package/src/panes/dom.js +37 -0
  540. package/src/panes/effects.js +118 -0
  541. package/src/panes/embed.js +30 -0
  542. package/src/panes/eval.js +186 -0
  543. package/src/panes/fields.js +299 -0
  544. package/src/panes/files.js +45 -0
  545. package/src/panes/gate.js +70 -0
  546. package/src/panes/geometry.js +64 -0
  547. package/src/panes/goals.js +75 -0
  548. package/src/panes/graph.js +66 -0
  549. package/src/panes/html.js +54 -0
  550. package/src/panes/http.js +82 -0
  551. package/src/panes/import.js +38 -0
  552. package/src/panes/input.js +124 -0
  553. package/src/panes/inputlog.js +66 -0
  554. package/src/panes/ledger.js +56 -0
  555. package/src/panes/machine.js +138 -0
  556. package/src/panes/mcp.js +85 -0
  557. package/src/panes/mcpapp.js +64 -0
  558. package/src/panes/media.js +38 -0
  559. package/src/panes/memory.js +46 -0
  560. package/src/panes/mesh-inspect.js +49 -0
  561. package/src/panes/note.js +38 -0
  562. package/src/panes/peer.js +44 -0
  563. package/src/panes/plot.js +196 -0
  564. package/src/panes/registry.js +475 -0
  565. package/src/panes/render.js +87 -0
  566. package/src/panes/respond.js +44 -0
  567. package/src/panes/router.js +84 -0
  568. package/src/panes/sample.js +75 -0
  569. package/src/panes/scene.js +55 -0
  570. package/src/panes/score.js +87 -0
  571. package/src/panes/secret.js +38 -0
  572. package/src/panes/select.js +67 -0
  573. package/src/panes/shader.js +166 -0
  574. package/src/panes/shared.js +33 -0
  575. package/src/panes/shares.js +43 -0
  576. package/src/panes/shell.js +47 -0
  577. package/src/panes/skill.js +44 -0
  578. package/src/panes/state.js +91 -0
  579. package/src/panes/statechart.js +63 -0
  580. package/src/panes/story.js +33 -0
  581. package/src/panes/subgraph.js +94 -0
  582. package/src/panes/tabs.js +52 -0
  583. package/src/panes/terminal.js +57 -0
  584. package/src/panes/text.js +36 -0
  585. package/src/panes/timer.js +55 -0
  586. package/src/panes/traffic.js +59 -0
  587. package/src/panes/verdict.js +62 -0
  588. package/src/panes/vm.js +46 -0
  589. package/src/panes/wait.js +61 -0
  590. package/src/panes/watch.js +57 -0
  591. package/src/panes/webhook.js +67 -0
  592. package/src/panes/ws-client.js +67 -0
  593. package/src/persist.js +281 -0
  594. package/src/plot/tex.js +19 -0
  595. package/src/plot/vendor.js +59 -0
  596. package/src/plot/view-vendor.js +5 -0
  597. package/src/privacy/levels.js +108 -0
  598. package/src/protocol/devtools.js +116 -0
  599. package/src/protocol/inspector.js +368 -0
  600. package/src/render/time.js +381 -0
  601. package/src/rooms/mesh-metrics.js +162 -0
  602. package/src/run/companion.js +355 -0
  603. package/src/run/describe.js +114 -0
  604. package/src/run/local-model.js +150 -0
  605. package/src/run/monitor.js +208 -0
  606. package/src/run/publish.js +360 -0
  607. package/src/run/respond-outcome.js +12 -0
  608. package/src/run/run.js +820 -0
  609. package/src/run/runner-pairing.js +243 -0
  610. package/src/run/values.js +122 -0
  611. package/src/runtime/compile.js +122 -0
  612. package/src/runtime/console-tag.js +64 -0
  613. package/src/runtime/frame-signals.js +126 -0
  614. package/src/runtime/iteration-push.js +19 -0
  615. package/src/runtime/keys.js +474 -0
  616. package/src/runtime/midi-input.js +170 -0
  617. package/src/runtime/person-waits.js +140 -0
  618. package/src/runtime/resource-timing.js +56 -0
  619. package/src/runtime/runtime.js +2150 -0
  620. package/src/runtime/sandbox-modules.js +163 -0
  621. package/src/runtime/spring.js +246 -0
  622. package/src/runtime/strict.js +215 -0
  623. package/src/runtime/transfer.js +75 -0
  624. package/src/runtime/tween.js +158 -0
  625. package/src/runtime/wasm-fuel.js +596 -0
  626. package/src/runtime/worker/00-prelude.js +88 -0
  627. package/src/runtime/worker/10-helpers.js +295 -0
  628. package/src/runtime/worker/20-io.js +645 -0
  629. package/src/runtime/worker/30-previews.js +210 -0
  630. package/src/runtime/worker/40-profile-lineage.js +278 -0
  631. package/src/runtime/worker/50-own-worker.js +233 -0
  632. package/src/runtime/worker/60-timers.js +172 -0
  633. package/src/runtime/worker/70-state-keyed.js +193 -0
  634. package/src/runtime/worker/80-each-compile-generators.js +619 -0
  635. package/src/runtime/worker/90-events-operators.js +655 -0
  636. package/src/runtime/worker/95-agents-batches.js +1820 -0
  637. package/src/runtime/worker/96-plot.js +47 -0
  638. package/src/runtime/worker/97-calc.js +28 -0
  639. package/src/runtime/worker/98-geometry.js +24 -0
  640. package/src/runtime/worker/99-graph.js +30 -0
  641. package/src/runtime/worker/99-shell.js +30 -0
  642. package/src/safety/config.js +57 -0
  643. package/src/safety/engine.js +324 -0
  644. package/src/scene/pixi-scene.js +806 -0
  645. package/src/scene/scene-assets.js +241 -0
  646. package/src/scene/scene-edit.js +319 -0
  647. package/src/secret/settings.js +41 -0
  648. package/src/security/multipart.js +257 -0
  649. package/src/security/redact.js +261 -0
  650. package/src/serial/broker.js +473 -0
  651. package/src/serial/config.js +185 -0
  652. package/src/serial/framers.js +389 -0
  653. package/src/serial/packets.js +64 -0
  654. package/src/shader/audio-texture.js +87 -0
  655. package/src/shader/channels.js +496 -0
  656. package/src/shader/common.js +90 -0
  657. package/src/shader/model.js +867 -0
  658. package/src/shader/passes.js +150 -0
  659. package/src/shader/shadertoy.js +198 -0
  660. package/src/shell/hub.js +287 -0
  661. package/src/sim/checkpoints.js +850 -0
  662. package/src/sim/compile.js +37 -0
  663. package/src/sim/fixed.js +377 -0
  664. package/src/sim/headless.js +205 -0
  665. package/src/sim/physics.js +399 -0
  666. package/src/smf-helper/vendor.js +2 -0
  667. package/src/sources/config.js +435 -0
  668. package/src/storage.js +153 -0
  669. package/src/table/table-geo.js +2344 -0
  670. package/src/table/table-lineage.js +808 -0
  671. package/src/table/table-quality.js +355 -0
  672. package/src/table/table-schema.js +392 -0
  673. package/src/table/table-sql.js +1650 -0
  674. package/src/table/table-stats.js +480 -0
  675. package/src/table/table.js +2102 -0
  676. package/src/tensor/tensor.js +1153 -0
  677. package/src/terminal/hub.js +715 -0
  678. package/src/terminal/screen.js +516 -0
  679. package/src/tests/capture.js +88 -0
  680. package/src/tests/compare.js +480 -0
  681. package/src/tests/dataset.js +170 -0
  682. package/src/tests/evaluate.js +286 -0
  683. package/src/tests/from-runs.js +99 -0
  684. package/src/tests/judge.js +134 -0
  685. package/src/tests/matchers.js +263 -0
  686. package/src/tests/matrix-spec.js +87 -0
  687. package/src/tests/matrix.js +397 -0
  688. package/src/tests/metrics.js +369 -0
  689. package/src/tests/no-value.js +42 -0
  690. package/src/tests/pane-check.js +45 -0
  691. package/src/tests/report.js +124 -0
  692. package/src/tests/reporters.js +140 -0
  693. package/src/tests/run.js +155 -0
  694. package/src/tilemap/tilemap.js +1122 -0
  695. package/src/units/units.js +3 -0
  696. package/src/util/bytes-text.js +21 -0
  697. package/src/util/num.js +10 -0
  698. package/src/util/regexp.js +2 -0
  699. package/src/util/text.js +38 -0
  700. package/src/verdict/engine.js +154 -0
  701. package/src/vm/guest-wsh.js +108 -0
  702. package/src/vm/hub.js +457 -0
  703. package/src/vm/image-files.js +4 -0
  704. package/src/vm/image.js +33 -0
  705. package/src/vm/image.lock.json +13 -0
  706. package/src/vm/link.js +266 -0
  707. package/src/vm/mount.js +212 -0
  708. package/src/vm/net.js +85 -0
  709. package/src/vm/pipe-ws.js +187 -0
  710. package/src/vm/v86-loader.js +11 -0
  711. package/src/webmcp/args.js +212 -0
  712. package/src/webmcp/hidden.js +218 -0
  713. package/src/webmcp/text.js +250 -0
  714. package/src/webmcp/tools/bookmark-tools.js +106 -0
  715. package/src/webmcp/tools/breakpoint-tools.js +48 -0
  716. package/src/webmcp/tools/canvases.js +208 -0
  717. package/src/webmcp/tools/context-tools.js +84 -0
  718. package/src/webmcp/tools/core.js +170 -0
  719. package/src/webmcp/tools/devices.js +41 -0
  720. package/src/webmcp/tools/edit.js +357 -0
  721. package/src/webmcp/tools/event-tools.js +145 -0
  722. package/src/webmcp/tools/image-tools.js +173 -0
  723. package/src/webmcp/tools/ink-tools.js +247 -0
  724. package/src/webmcp/tools/input-log-tools.js +163 -0
  725. package/src/webmcp/tools/live.js +166 -0
  726. package/src/webmcp/tools/machine-tools.js +74 -0
  727. package/src/webmcp/tools/media.js +161 -0
  728. package/src/webmcp/tools/midi-tools.js +32 -0
  729. package/src/webmcp/tools/preset-tools.js +184 -0
  730. package/src/webmcp/tools/quick-add-tools.js +95 -0
  731. package/src/webmcp/tools/reshape.js +152 -0
  732. package/src/webmcp/tools/run-tools.js +309 -0
  733. package/src/webmcp/tools/runs.js +101 -0
  734. package/src/webmcp/tools/scaffold-tools.js +161 -0
  735. package/src/webmcp/tools/serial-tools.js +36 -0
  736. package/src/webmcp/tools/shared.js +338 -0
  737. package/src/webmcp/tools/subgraphs.js +360 -0
  738. package/src/webmcp/tools/tests.js +170 -0
  739. package/src/webmcp/tools/traffic-tools.js +70 -0
  740. package/src/webmcp/tools/transport-tools.js +65 -0
  741. package/src/webmcp/tools/version-tools.js +126 -0
  742. package/src/webmcp/tools/versions.js +11 -0
  743. package/src/webmcp/tools/wire-tools.js +90 -0
  744. package/src/webmcp/tools/workspace-tools.js +93 -0
  745. package/src/webmcp/tools.js +1323 -0
  746. package/src/wsh/connect.js +347 -0
  747. package/src/wsh/demo-host.js +361 -0
  748. package/src/wsh/e2e.js +27 -0
  749. package/src/wsh/keys.js +154 -0
  750. package/src/wsh/known-hosts.js +39 -0
  751. package/src/wsh/private-key.js +95 -0
  752. package/src/wsh/reverse.js +34 -0
  753. package/src/wsh/settings.js +118 -0
  754. package/src/wsh/transfer.js +62 -0
  755. package/src/wsh/vendor.js +5 -0
  756. package/src/x402/challenge.js +171 -0
  757. package/src/x402/demo-server.js +127 -0
  758. package/src/x402/pay.js +125 -0
  759. package/src/x402/retry.js +95 -0
  760. package/src/x402/store.js +76 -0
@@ -0,0 +1,1804 @@
1
+ // Cap'n Proto for the codec pane (src/codec/core.js): a .capnp schema read at run time, laid out the way the capnp compiler
2
+ // lays it out, and messages read and written from that layout. No code generation and no compiler: the schema language's
3
+ // data subset (structs, enums, unions, groups, lists, defaults, nested and aliased types) is parsed here, and each struct's
4
+ // field offsets come from a port of the compiler's own layout algorithm (capnproto c++/src/capnp/compiler/node-translator.c++,
5
+ // StructLayout and StructTranslator), checked against libcapnp's layouts (test/fixtures/capnp-layouts.json).
6
+ //
7
+ // Self-contained (no imports): the sandbox Worker loads it as the virtual module mallory:codec/capnp, only for a canvas
8
+ // with a Cap'n Proto codec pane; the headless runner and the tests import it as a plain file.
9
+ //
10
+ // What isn't read: interfaces (RPC) are skipped where they are declared, and a field whose type is one, or AnyPointer,
11
+ // reads a capability as { capability: n } and anything else it points at as an error; generic types (Foo(T)) and imports of
12
+ // other files are refused where they are used (annotations, including the standard /capnp/c++.capnp ones, are skipped).
13
+ //
14
+ // BOUNDS: a decode reads at most `items` values and nests at most `depth` structs and lists deep, and it reads at most eight
15
+ // times the message's own size in words (a pointer can point at the same data again and again: the "amplification" the
16
+ // capnp readers limit with their traversal limit); every pointer is checked against its segment, far pointers included.
17
+ // An encode writes one segment and stops at `maxBytes`.
18
+
19
+ export class CapnpError extends Error {
20
+ constructor(message, { path, offset, kind, line, column, problems } = {}) {
21
+ super(message);
22
+ this.name = "CapnpError";
23
+ if (path !== undefined) this.path = path;
24
+ if (offset !== undefined) this.offset = offset;
25
+ if (kind !== undefined) this.kind = kind; // "depth" | "items" | "size" for the limits
26
+ if (line !== undefined) this.line = line;
27
+ if (column !== undefined) this.column = column;
28
+ if (problems !== undefined) this.problems = problems;
29
+ }
30
+ }
31
+
32
+ // ── reading the schema text ──────────────────────────────────────────────────
33
+
34
+ const PUNCT = "@:;{}()[]=,.$->"; // ">" only in an interface's methods (-> results), which are skipped
35
+
36
+ /** The schema's tokens: { t: "id" | "int" | "float" | "str" | "data" | "p", v, line, col }. */
37
+ function lex(src) {
38
+ const out = [];
39
+ let i = 0;
40
+ let line = 1;
41
+ let lineStart = 0;
42
+ const n = src.length;
43
+ const fail = (message, at = i) => {
44
+ throw new CapnpError(message, { line, column: at - lineStart + 1 });
45
+ };
46
+ while (i < n) {
47
+ const c = src[i];
48
+ if (c === "\n") {
49
+ line++;
50
+ i++;
51
+ lineStart = i;
52
+ continue;
53
+ }
54
+ if (c === " " || c === "\t" || c === "\r" || c === "\f" || c === "\v") {
55
+ i++;
56
+ continue;
57
+ }
58
+ if (c === "#") {
59
+ while (i < n && src[i] !== "\n") i++;
60
+ continue;
61
+ }
62
+ const at = { line, col: i - lineStart + 1 };
63
+ if (/[A-Za-z_]/.test(c)) {
64
+ let j = i + 1;
65
+ while (j < n && /\w/.test(src[j])) j++;
66
+ out.push({ t: "id", v: src.slice(i, j), ...at });
67
+ i = j;
68
+ continue;
69
+ }
70
+ if (c === "0" && (src[i + 1] === "x" || src[i + 1] === "X") && src[i + 2] === '"') {
71
+ // a data literal: 0x"62 61 72"
72
+ let j = i + 3;
73
+ while (j < n && src[j] !== '"' && src[j] !== "\n") j++;
74
+ if (src[j] !== '"') fail("this data literal (0x\"…\") never ends");
75
+ const hex = src.slice(i + 3, j).replace(/\s+/g, "");
76
+ if (hex.length % 2 || /[^0-9a-f]/i.test(hex)) fail("a data literal is pairs of hex digits, like 0x\"62 61 72\"");
77
+ out.push({ t: "data", v: Uint8Array.from({ length: hex.length / 2 }, (_, k) => parseInt(hex.slice(k * 2, k * 2 + 2), 16)), ...at });
78
+ i = j + 1;
79
+ continue;
80
+ }
81
+ if (/[0-9]/.test(c)) {
82
+ const rest = src.slice(i);
83
+ let m;
84
+ if ((m = /^0[xX][0-9a-fA-F]+/.exec(rest))) out.push({ t: "int", v: BigInt(m[0]), ...at });
85
+ else if ((m = /^\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/.exec(rest)) && /[.eE]/.test(m[0])) out.push({ t: "float", v: Number(m[0]), ...at });
86
+ else if ((m = /^0[0-7]+/.exec(rest))) out.push({ t: "int", v: BigInt(`0o${m[0].slice(1)}`), ...at });
87
+ else {
88
+ m = /^\d+/.exec(rest);
89
+ out.push({ t: "int", v: BigInt(m[0]), ...at });
90
+ }
91
+ i += m[0].length;
92
+ if (i < n && /\w/.test(src[i])) fail(`"${m[0]}${src[i]}" isn't a number`);
93
+ continue;
94
+ }
95
+ if (c === '"') {
96
+ let j = i + 1;
97
+ let s = "";
98
+ for (;;) {
99
+ if (j >= n || src[j] === "\n") fail("this text never ends (a \" is missing)");
100
+ const d = src[j];
101
+ if (d === '"') break;
102
+ if (d !== "\\") {
103
+ s += d;
104
+ j++;
105
+ continue;
106
+ }
107
+ const e = src[j + 1];
108
+ const simple = { n: "\n", t: "\t", r: "\r", a: "\x07", b: "\b", f: "\f", v: "\v", "\\": "\\", "'": "'", '"': '"', "?": "?" };
109
+ if (e in simple) {
110
+ s += simple[e];
111
+ j += 2;
112
+ } else if (e === "x" && /^[0-9a-fA-F]{2}/.test(src.slice(j + 2, j + 4))) {
113
+ s += String.fromCharCode(parseInt(src.slice(j + 2, j + 4), 16));
114
+ j += 4;
115
+ } else if (/[0-7]/.test(e)) {
116
+ const m = /^[0-7]{1,3}/.exec(src.slice(j + 1));
117
+ s += String.fromCharCode(parseInt(m[0], 8));
118
+ j += 1 + m[0].length;
119
+ } else fail(`"\\${e ?? ""}" isn't an escape Cap'n Proto knows`, j);
120
+ }
121
+ out.push({ t: "str", v: s, ...at });
122
+ i = j + 1;
123
+ continue;
124
+ }
125
+ if (PUNCT.includes(c)) {
126
+ out.push({ t: "p", v: c, ...at });
127
+ i++;
128
+ continue;
129
+ }
130
+ fail(`"${c}" isn't part of the Cap'n Proto schema language`);
131
+ }
132
+ out.push({ t: "eof", v: "", line, col: i - lineStart + 1 });
133
+ return out;
134
+ }
135
+
136
+ const describeTok = (tok) => (tok.t === "eof" ? "the end of the schema" : tok.t === "str" ? "text" : `"${tok.t === "data" ? "0x\"…\"" : String(tok.v)}"`);
137
+
138
+ /** The declarations of a .capnp text as a tree (see `compile`). Throws a CapnpError with the line at the first syntax error. */
139
+ function parse(src) {
140
+ const toks = lex(src);
141
+ let k = 0;
142
+ const peek = (o = 0) => toks[Math.min(k + o, toks.length - 1)];
143
+ const next = () => toks[k < toks.length - 1 ? k++ : k];
144
+ const fail = (tok, message) => {
145
+ throw new CapnpError(message, { line: tok.line, column: tok.col });
146
+ };
147
+ const is = (v, o = 0) => peek(o).t === "p" && peek(o).v === v;
148
+ const isId = (v, o = 0) => peek(o).t === "id" && peek(o).v === v;
149
+ const expect = (v, what) => {
150
+ const t = next();
151
+ if (t.t !== "p" || t.v !== v) fail(t, `expected "${v}"${what ? ` ${what}` : ""}, found ${describeTok(t)}`);
152
+ return t;
153
+ };
154
+ const name = (what) => {
155
+ const t = next();
156
+ if (t.t !== "id") fail(t, `expected ${what}, found ${describeTok(t)}`);
157
+ return t;
158
+ };
159
+ const ordinal = () => {
160
+ expect("@");
161
+ const t = next();
162
+ if (t.t !== "int") fail(t, `expected a number after "@", found ${describeTok(t)}`);
163
+ if (t.v > 65534n) fail(t, "an ordinal is at most 65534");
164
+ return { value: Number(t.v), line: t.line, col: t.col };
165
+ };
166
+ const skipId = () => {
167
+ // @0x… after a declaration's name: its 64-bit id, which this reader doesn't need
168
+ if (is("@") && peek(1).t === "int") {
169
+ next();
170
+ next();
171
+ }
172
+ };
173
+ /** Skip from an opening bracket to its partner. */
174
+ const balanced = () => {
175
+ const open = next();
176
+ const close = { "(": ")", "[": "]", "{": "}" }[open.v];
177
+ let depth = 1;
178
+ while (depth) {
179
+ const t = next();
180
+ if (t.t === "eof") fail(open, `this "${open.v}" is never closed`);
181
+ if (t.t === "p" && t.v === open.v) depth++;
182
+ else if (t.t === "p" && t.v === close) depth--;
183
+ }
184
+ };
185
+ const annotations = () => {
186
+ while (is("$")) {
187
+ next();
188
+ name("an annotation's name");
189
+ while (is(".")) {
190
+ next();
191
+ name("a name after the dot");
192
+ }
193
+ if (is("(")) balanced();
194
+ }
195
+ };
196
+ const typeExpr = () => {
197
+ const at = peek();
198
+ let absolute = false;
199
+ if (is(".")) {
200
+ next();
201
+ absolute = true;
202
+ }
203
+ const path = [name("a type").v];
204
+ while (is(".")) {
205
+ next();
206
+ path.push(name("a name after the dot").v);
207
+ }
208
+ const out = { path, absolute, line: at.line, col: at.col };
209
+ if (is("(")) {
210
+ next();
211
+ out.args = [];
212
+ if (!is(")"))
213
+ for (;;) {
214
+ out.args.push(typeExpr());
215
+ if (is(",")) next();
216
+ else break;
217
+ }
218
+ expect(")", "to close the type's parameters");
219
+ }
220
+ return out;
221
+ };
222
+ const value = () => {
223
+ const t = peek();
224
+ const at = { line: t.line, col: t.col };
225
+ if (is("-")) {
226
+ next();
227
+ const u = next();
228
+ if (u.t === "int") return { k: "int", v: -u.v, ...at };
229
+ if (u.t === "float") return { k: "float", v: -u.v, ...at };
230
+ if (u.t === "id" && u.v === "inf") return { k: "float", v: -Infinity, ...at };
231
+ fail(u, `expected a number after "-", found ${describeTok(u)}`);
232
+ }
233
+ if (t.t === "int") return (next(), { k: "int", v: t.v, ...at });
234
+ if (t.t === "float") return (next(), { k: "float", v: t.v, ...at });
235
+ if (t.t === "data") return (next(), { k: "data", v: t.v, ...at });
236
+ if (t.t === "str") {
237
+ let s = "";
238
+ while (peek().t === "str") s += next().v; // "a" "b" is "ab"
239
+ return { k: "str", v: s, ...at };
240
+ }
241
+ if (t.t === "id") {
242
+ next();
243
+ const path = [t.v];
244
+ while (is(".")) {
245
+ next();
246
+ path.push(name("a name after the dot").v);
247
+ }
248
+ if (path.length === 1 && t.v === "inf") return { k: "float", v: Infinity, ...at };
249
+ if (path.length === 1 && t.v === "nan") return { k: "float", v: NaN, ...at };
250
+ return { k: "id", path, ...at };
251
+ }
252
+ if (is("(")) {
253
+ next();
254
+ const fields = [];
255
+ if (!is(")"))
256
+ for (;;) {
257
+ const n = name("a field name");
258
+ expect("=", `after the field name ${n.v}`);
259
+ fields.push({ name: n.v, value: value(), line: n.line, col: n.col });
260
+ if (is(",")) next();
261
+ else break;
262
+ }
263
+ expect(")", "to close the struct value");
264
+ return { k: "struct", fields, ...at };
265
+ }
266
+ if (is("[")) {
267
+ next();
268
+ const items = [];
269
+ if (!is("]"))
270
+ for (;;) {
271
+ items.push(value());
272
+ if (is(",")) next();
273
+ else break;
274
+ }
275
+ expect("]", "to close the list");
276
+ return { k: "list", items, ...at };
277
+ }
278
+ fail(t, `expected a value, found ${describeTok(t)}`);
279
+ };
280
+
281
+ /** A declaration that can appear in a file or a struct; returns it, or null when `peek()` doesn't start one. */
282
+ const declaration = (scope) => {
283
+ const t = peek();
284
+ if (t.t !== "id") return null;
285
+ const at = { line: t.line, col: t.col };
286
+ switch (t.v) {
287
+ case "struct": {
288
+ next();
289
+ const n = name("the struct's name");
290
+ const decl = { kind: "struct", name: n.v, parent: scope, children: new Map(), body: [], line: n.line, col: n.col };
291
+ if (is("(")) {
292
+ decl.generic = true;
293
+ balanced();
294
+ }
295
+ skipId();
296
+ annotations();
297
+ expect("{", `to open struct ${n.v}`);
298
+ decl.body = members(decl, decl, "struct");
299
+ expect("}", `to close struct ${n.v}`);
300
+ return decl;
301
+ }
302
+ case "enum": {
303
+ next();
304
+ const n = name("the enum's name");
305
+ const decl = { kind: "enum", name: n.v, parent: scope, enumerants: [], line: n.line, col: n.col };
306
+ skipId();
307
+ annotations();
308
+ expect("{", `to open enum ${n.v}`);
309
+ while (!is("}")) {
310
+ if (peek().t === "eof") fail(peek(), `enum ${n.v} is never closed`);
311
+ const e = name("an enumerant's name");
312
+ if (!is("@")) fail(peek(), `enumerant ${e.v} needs an ordinal, like ${e.v} @0;`);
313
+ const o = ordinal();
314
+ annotations();
315
+ expect(";", `after enumerant ${e.v}`);
316
+ decl.enumerants.push({ name: e.v, ordinal: o.value, line: e.line, col: e.col, ordLine: o.line, ordCol: o.col });
317
+ }
318
+ expect("}");
319
+ return decl;
320
+ }
321
+ case "interface": {
322
+ next();
323
+ const n = name("the interface's name");
324
+ if (is("(")) balanced();
325
+ skipId();
326
+ if (isId("extends")) {
327
+ next();
328
+ balanced();
329
+ }
330
+ annotations();
331
+ if (!is("{")) fail(peek(), `expected "{" to open interface ${n.v}`);
332
+ balanced();
333
+ return { kind: "interface", name: n.v, parent: scope, line: n.line, col: n.col };
334
+ }
335
+ case "const": {
336
+ next();
337
+ const n = name("the constant's name");
338
+ expect(":", `after the constant's name ${n.v}`);
339
+ const type = typeExpr();
340
+ expect("=", `after constant ${n.v}'s type`);
341
+ const v = value();
342
+ annotations();
343
+ expect(";", `after constant ${n.v}`);
344
+ return { kind: "const", name: n.v, parent: scope, type, value: v, line: n.line, col: n.col };
345
+ }
346
+ case "annotation": {
347
+ next();
348
+ const n = name("the annotation's name");
349
+ skipId();
350
+ if (is("(")) balanced();
351
+ expect(":", `after annotation ${n.v}'s targets`);
352
+ typeExpr();
353
+ annotations();
354
+ expect(";", `after annotation ${n.v}`);
355
+ return { kind: "annotation", name: n.v, parent: scope, line: n.line, col: n.col };
356
+ }
357
+ case "using": {
358
+ next();
359
+ let alias = null;
360
+ if (peek().t === "id" && is("=", 1)) {
361
+ alias = next();
362
+ next();
363
+ }
364
+ if (isId("import")) {
365
+ next();
366
+ const file = next();
367
+ if (file.t !== "str") fail(file, "expected the imported file's name in quotes");
368
+ const path = [];
369
+ while (is(".")) {
370
+ next();
371
+ path.push(name("a name after the dot").v);
372
+ }
373
+ expect(";", "after the using declaration");
374
+ const nm = alias?.v ?? path[path.length - 1];
375
+ if (!nm) return { kind: "skip" };
376
+ return { kind: "using", name: nm, parent: scope, import: file.v, line: (alias ?? file).line, col: (alias ?? file).col };
377
+ }
378
+ const target = typeExpr();
379
+ expect(";", "after the using declaration");
380
+ const nm = alias?.v ?? target.path[target.path.length - 1];
381
+ return { kind: "using", name: nm, parent: scope, target, line: at.line, col: at.col };
382
+ }
383
+ default:
384
+ return null;
385
+ }
386
+ };
387
+
388
+ /** The members of a struct, group or union body, up to its "}" (nested declarations go into `struct.children`). */
389
+ const members = (struct, owner, where) => {
390
+ const out = [];
391
+ while (!is("}")) {
392
+ const t = peek();
393
+ if (t.t === "eof") fail(t, `${owner.kind === "struct" ? `struct ${owner.name}` : `${owner.kind} ${owner.name || ""}`.trim()} is never closed (a "}" is missing)`);
394
+ const decl = declaration(struct);
395
+ if (decl) {
396
+ if (decl.kind !== "skip") addChild(struct, decl);
397
+ continue;
398
+ }
399
+ if (isId("union") && (is("{", 1) || is("@", 1) || is("$", 1))) {
400
+ // an unnamed union
401
+ next();
402
+ const u = { kind: "union", name: "", line: t.line, col: t.col };
403
+ if (is("@")) u.ordinal = ordinal();
404
+ annotations();
405
+ expect("{", "to open the union");
406
+ u.body = members(struct, u, "union");
407
+ expect("}", "to close the union");
408
+ out.push(u);
409
+ continue;
410
+ }
411
+ const n = name(where === "union" ? "a union member" : "a field");
412
+ if (is("@")) {
413
+ const o = ordinal();
414
+ expect(":", `after ${n.v} @${o.value}`);
415
+ if (isId("union")) {
416
+ next();
417
+ annotations();
418
+ expect("{", `to open union ${n.v}`);
419
+ const u = { kind: "union", name: n.v, ordinal: o, line: n.line, col: n.col };
420
+ u.body = members(struct, u, "union");
421
+ expect("}", `to close union ${n.v}`);
422
+ out.push(u);
423
+ continue;
424
+ }
425
+ const field = { kind: "field", name: n.v, ordinal: o, type: typeExpr(), line: n.line, col: n.col };
426
+ if (is("=")) {
427
+ next();
428
+ field.def = value();
429
+ }
430
+ annotations();
431
+ expect(";", `after field ${n.v}`);
432
+ out.push(field);
433
+ continue;
434
+ }
435
+ if (is(":")) {
436
+ next();
437
+ const what = peek();
438
+ if (isId("group") || isId("union")) {
439
+ next();
440
+ annotations();
441
+ expect("{", `to open ${what.v} ${n.v}`);
442
+ const g = { kind: what.v, name: n.v, line: n.line, col: n.col };
443
+ g.body = members(struct, g, what.v);
444
+ expect("}", `to close ${what.v} ${n.v}`);
445
+ out.push(g);
446
+ continue;
447
+ }
448
+ fail(what, `field ${n.v} needs an ordinal, like ${n.v} @0 :${what.t === "id" ? what.v : "Text"};`);
449
+ }
450
+ fail(peek(), `expected "@" and an ordinal after ${n.v}, like ${n.v} @0 :Text;`);
451
+ }
452
+ return out;
453
+ };
454
+
455
+ const file = { kind: "file", name: "", parent: null, children: new Map(), line: 1, col: 1 };
456
+ const errors = [];
457
+ const addChild = (scope, decl) => {
458
+ if (scope.children.has(decl.name)) errors.push({ line: decl.line, column: decl.col, message: `"${decl.name}" is already defined in this scope` });
459
+ else scope.children.set(decl.name, decl);
460
+ };
461
+ while (peek().t !== "eof") {
462
+ if (is("@")) {
463
+ next();
464
+ const id = next();
465
+ if (id.t !== "int") fail(id, "expected the file's id after \"@\", like @0xdbb9ad1f14bf0b36;");
466
+ expect(";", "after the file's id");
467
+ continue;
468
+ }
469
+ if (is("$")) {
470
+ annotations();
471
+ expect(";", "after the file's annotation");
472
+ continue;
473
+ }
474
+ const decl = declaration(file);
475
+ if (!decl) fail(peek(), `expected a declaration (struct, enum, const, using…), found ${describeTok(peek())}`);
476
+ if (decl.kind !== "skip") addChild(file, decl);
477
+ }
478
+ return { file, errors };
479
+ }
480
+
481
+ // ── the layout algorithm: a port of capnp's StructLayout ─────────────────────
482
+
483
+ class HoleSet {
484
+ constructor() {
485
+ this.holes = [0, 0, 0, 0, 0, 0];
486
+ }
487
+ tryAllocate(lg) {
488
+ if (lg >= 6) return null;
489
+ if (this.holes[lg] !== 0) {
490
+ const r = this.holes[lg];
491
+ this.holes[lg] = 0;
492
+ return r;
493
+ }
494
+ const next = this.tryAllocate(lg + 1);
495
+ if (next === null) return null;
496
+ const r = next * 2;
497
+ this.holes[lg] = r + 1;
498
+ return r;
499
+ }
500
+ addHolesAtEnd(lg, offset, limit = 6) {
501
+ while (lg < limit) {
502
+ this.holes[lg] = offset;
503
+ lg++;
504
+ offset = (offset + 1) / 2;
505
+ }
506
+ }
507
+ tryExpand(oldLg, oldOffset, factor) {
508
+ if (factor === 0) return true;
509
+ if (oldLg === 6) return false;
510
+ if (this.holes[oldLg] !== oldOffset + 1) return false;
511
+ if (this.tryExpand(oldLg + 1, oldOffset >>> 1, factor - 1)) {
512
+ this.holes[oldLg] = 0;
513
+ return true;
514
+ }
515
+ return false;
516
+ }
517
+ smallestAtLeast(size) {
518
+ for (let i = size; i < 6; i++) if (this.holes[i] !== 0) return i;
519
+ return null;
520
+ }
521
+ }
522
+
523
+ const ISSUE_344 = "this union layout is one Cap'n Proto 0.5 and older compiled wrongly, and capnp refuses it (capnproto issue 344): reorder the nested unions' fields";
524
+
525
+ class Top {
526
+ constructor() {
527
+ this.dataWordCount = 0;
528
+ this.pointerCount = 0;
529
+ this.holes = new HoleSet();
530
+ }
531
+ addVoid() {}
532
+ addData(lg) {
533
+ const hole = this.holes.tryAllocate(lg);
534
+ if (hole !== null) return hole;
535
+ const offset = this.dataWordCount++ * 2 ** (6 - lg);
536
+ this.holes.addHolesAtEnd(lg, offset + 1);
537
+ return offset;
538
+ }
539
+ addPointer() {
540
+ return this.pointerCount++;
541
+ }
542
+ tryExpandData(oldLg, oldOffset, factor) {
543
+ return this.holes.tryExpand(oldLg, oldOffset, factor);
544
+ }
545
+ }
546
+
547
+ class Union {
548
+ constructor(parent) {
549
+ this.parent = parent;
550
+ this.groupCount = 0;
551
+ this.discriminantOffset = null;
552
+ this.dataLocations = []; // { lgSize, offset }
553
+ this.pointerLocations = [];
554
+ }
555
+ addNewDataLocation(lg) {
556
+ const offset = this.parent.addData(lg);
557
+ this.dataLocations.push({ lgSize: lg, offset });
558
+ return offset;
559
+ }
560
+ addNewPointerLocation() {
561
+ const p = this.parent.addPointer();
562
+ this.pointerLocations.push(p);
563
+ return p;
564
+ }
565
+ newGroupAddingFirstMember() {
566
+ if (++this.groupCount === 2) this.addDiscriminant();
567
+ }
568
+ addDiscriminant() {
569
+ if (this.discriminantOffset === null) {
570
+ this.discriminantOffset = this.parent.addData(4);
571
+ return true;
572
+ }
573
+ return false;
574
+ }
575
+ }
576
+
577
+ function tryExpandTo(location, union, newLg) {
578
+ if (newLg <= location.lgSize) return true;
579
+ if (union.parent.tryExpandData(location.lgSize, location.offset, newLg - location.lgSize)) {
580
+ location.offset = location.offset >>> (newLg - location.lgSize);
581
+ location.lgSize = newLg;
582
+ return true;
583
+ }
584
+ return false;
585
+ }
586
+
587
+ class DataLocationUsage {
588
+ constructor(lg) {
589
+ this.isUsed = lg !== undefined;
590
+ this.lgSizeUsed = lg ?? 0;
591
+ this.holes = new HoleSet();
592
+ }
593
+ smallestHoleAtLeast(location, lg) {
594
+ if (!this.isUsed) return lg <= location.lgSize ? location.lgSize : null;
595
+ if (lg >= this.lgSizeUsed) return lg < location.lgSize ? lg : null;
596
+ const hole = this.holes.smallestAtLeast(lg);
597
+ if (hole !== null) return hole;
598
+ return this.lgSizeUsed < location.lgSize ? this.lgSizeUsed : null;
599
+ }
600
+ allocateFromHole(group, location, lg) {
601
+ let result;
602
+ if (!this.isUsed) {
603
+ result = 0;
604
+ this.isUsed = true;
605
+ this.lgSizeUsed = lg;
606
+ } else if (lg >= this.lgSizeUsed) {
607
+ this.holes.addHolesAtEnd(this.lgSizeUsed, 1, lg);
608
+ this.lgSizeUsed = lg + 1;
609
+ result = 1;
610
+ } else {
611
+ const hole = this.holes.tryAllocate(lg);
612
+ if (hole !== null) result = hole;
613
+ else {
614
+ result = 2 ** (this.lgSizeUsed - lg);
615
+ this.holes.addHolesAtEnd(lg, result + 1, this.lgSizeUsed);
616
+ this.lgSizeUsed += 1;
617
+ }
618
+ }
619
+ return location.offset * 2 ** (location.lgSize - lg) + result;
620
+ }
621
+ tryAllocateByExpanding(group, location, lg) {
622
+ if (!this.isUsed) {
623
+ if (!tryExpandTo(location, group.parent, lg)) return null;
624
+ this.isUsed = true;
625
+ this.lgSizeUsed = lg;
626
+ return location.offset * 2 ** (location.lgSize - lg);
627
+ }
628
+ const newSize = Math.max(this.lgSizeUsed, lg) + 1;
629
+ if (!this.tryExpandUsage(group, location, newSize, true)) return null;
630
+ const result = this.holes.tryAllocate(lg);
631
+ return location.offset * 2 ** (location.lgSize - lg) + result;
632
+ }
633
+ tryExpand(group, location, oldLg, oldOffset, factor) {
634
+ if (oldOffset === 0 && this.lgSizeUsed === oldLg) return this.tryExpandUsage(group, location, oldLg + factor, false);
635
+ return this.holes.tryExpand(oldLg, oldOffset, factor);
636
+ }
637
+ tryExpandUsage(group, location, desired, newHoles) {
638
+ if (desired > location.lgSize && !tryExpandTo(location, group.parent, desired)) return false;
639
+ if (newHoles) this.holes.addHolesAtEnd(this.lgSizeUsed, 1, desired);
640
+ else throw new CapnpError(ISSUE_344);
641
+ this.lgSizeUsed = desired;
642
+ return true;
643
+ }
644
+ }
645
+
646
+ class Group {
647
+ constructor(parent) {
648
+ this.parent = parent; // a Union
649
+ this.usage = []; // DataLocationUsage per parent.dataLocations
650
+ this.pointerUsage = 0;
651
+ this.hasMembers = false;
652
+ }
653
+ addMember() {
654
+ if (!this.hasMembers) {
655
+ this.hasMembers = true;
656
+ this.parent.newGroupAddingFirstMember();
657
+ }
658
+ }
659
+ addVoid() {
660
+ this.addMember();
661
+ this.parent.parent.addVoid();
662
+ }
663
+ addData(lg) {
664
+ this.addMember();
665
+ let bestSize = Infinity;
666
+ let best = null;
667
+ const locations = this.parent.dataLocations;
668
+ for (let i = 0; i < locations.length; i++) {
669
+ if (this.usage.length === i) this.usage.push(new DataLocationUsage());
670
+ const hole = this.usage[i].smallestHoleAtLeast(locations[i], lg);
671
+ if (hole !== null && hole < bestSize) {
672
+ bestSize = hole;
673
+ best = i;
674
+ }
675
+ }
676
+ if (best !== null) return this.usage[best].allocateFromHole(this, locations[best], lg);
677
+ for (let i = 0; i < locations.length; i++) {
678
+ const r = this.usage[i].tryAllocateByExpanding(this, locations[i], lg);
679
+ if (r !== null) return r;
680
+ }
681
+ const r = this.parent.addNewDataLocation(lg);
682
+ this.usage.push(new DataLocationUsage(lg));
683
+ return r;
684
+ }
685
+ addPointer() {
686
+ this.addMember();
687
+ if (this.pointerUsage < this.parent.pointerLocations.length) return this.parent.pointerLocations[this.pointerUsage++];
688
+ this.pointerUsage++;
689
+ return this.parent.addNewPointerLocation();
690
+ }
691
+ tryExpandData(oldLg, oldOffset, factor) {
692
+ const mustFail = oldLg + factor > 6 || (oldOffset & (2 ** factor - 1)) !== 0;
693
+ for (let i = 0; i < this.usage.length; i++) {
694
+ const location = this.parent.dataLocations[i];
695
+ if (location.lgSize >= oldLg && Math.floor(oldOffset / 2 ** (location.lgSize - oldLg)) === location.offset) {
696
+ const localOld = oldOffset - location.offset * 2 ** (location.lgSize - oldLg);
697
+ const result = this.usage[i].tryExpand(this, location, oldLg, localOld, factor);
698
+ if (mustFail && result) throw new CapnpError(ISSUE_344);
699
+ return result;
700
+ }
701
+ }
702
+ throw new CapnpError("the layout tried to expand a field that was never allocated");
703
+ }
704
+ }
705
+
706
+ // ── the schema: types, layouts, defaults ─────────────────────────────────────
707
+
708
+ const PRIMS = {
709
+ Void: { k: "void", lg: -1 },
710
+ Bool: { k: "bool", lg: 0 },
711
+ Int8: { k: "int8", lg: 3 },
712
+ Int16: { k: "int16", lg: 4 },
713
+ Int32: { k: "int32", lg: 5 },
714
+ Int64: { k: "int64", lg: 6 },
715
+ UInt8: { k: "uint8", lg: 3 },
716
+ UInt16: { k: "uint16", lg: 4 },
717
+ UInt32: { k: "uint32", lg: 5 },
718
+ UInt64: { k: "uint64", lg: 6 },
719
+ Float32: { k: "float32", lg: 5 },
720
+ Float64: { k: "float64", lg: 6 },
721
+ Text: { k: "text", lg: -2 },
722
+ Data: { k: "data", lg: -2 },
723
+ AnyPointer: { k: "any", lg: -2 },
724
+ AnyStruct: { k: "any", lg: -2 },
725
+ AnyList: { k: "any", lg: -2 },
726
+ Capability: { k: "any", lg: -2 },
727
+ };
728
+ const TYPE_WORDS = { void: "Void", bool: "Bool", int8: "Int8", int16: "Int16", int32: "Int32", int64: "Int64", uint8: "UInt8", uint16: "UInt16", uint32: "UInt32", uint64: "UInt64", float32: "Float32", float64: "Float64", text: "Text", data: "Data", any: "AnyPointer" };
729
+ export const typeWords = (t) => (t.k === "list" ? `List(${typeWords(t.of)})` : t.k === "struct" || t.k === "enum" ? t.name : t.k === "interface" ? `interface ${t.name}` : TYPE_WORDS[t.k]);
730
+ const fullName = (decl) => {
731
+ const parts = [];
732
+ for (let d = decl; d && d.kind !== "file"; d = d.parent) parts.unshift(d.name);
733
+ return parts.join(".");
734
+ };
735
+
736
+ /**
737
+ * A .capnp text read into something `decode` and `encode` use:
738
+ * { ok, errors: [{ line?, column?, message }], types: ["Reading", "Outer.Inner", …], structs: Map(name -> node), first }
739
+ * `limits`: { maxTypes, maxFields } (structs, and fields in all).
740
+ */
741
+ export function compile(text, { maxTypes = 500, maxFields = 1000 } = {}) {
742
+ const errors = [];
743
+ const types = [];
744
+ const structs = new Map();
745
+ let parsed;
746
+ try {
747
+ parsed = parse(text);
748
+ } catch (e) {
749
+ if (!(e instanceof CapnpError)) throw e;
750
+ return { ok: false, errors: [{ line: e.line, column: e.column, message: e.message }], types, structs };
751
+ }
752
+ errors.push(...parsed.errors);
753
+ const err = (at, message) => {
754
+ if (errors.length < 20) errors.push({ ...(at?.line ? { line: at.line, column: at.col } : {}), message });
755
+ };
756
+
757
+ // every struct and enum, in declaration order
758
+ const structDecls = [];
759
+ const enumDecls = [];
760
+ const walk = (scope) => {
761
+ for (const d of scope.children.values()) {
762
+ if (d.kind === "struct") {
763
+ structDecls.push(d);
764
+ walk(d);
765
+ } else if (d.kind === "enum") enumDecls.push(d);
766
+ }
767
+ };
768
+ walk(parsed.file);
769
+ if (structDecls.length > maxTypes) return { ok: false, errors: [{ message: `a schema has at most ${maxTypes} structs (this one has ${structDecls.length})` }], types, structs };
770
+
771
+ const enums = new Map();
772
+ for (const d of enumDecls) {
773
+ const sorted = [...d.enumerants].sort((a, b) => a.ordinal - b.ordinal);
774
+ let expected = 0;
775
+ const names = new Set();
776
+ for (const e of sorted) {
777
+ if (names.has(e.name)) err(e, `enumerant "${e.name}" is defined twice in enum ${d.name}`);
778
+ names.add(e.name);
779
+ if (e.ordinal < expected) err({ line: e.ordLine, col: e.ordCol }, `ordinal @${e.ordinal} is used twice in enum ${d.name}`);
780
+ else if (e.ordinal > expected) err({ line: e.ordLine, col: e.ordCol }, `skipped ordinal @${expected} in enum ${d.name}: ordinals must be sequential with no holes`);
781
+ expected = Math.max(expected, e.ordinal + 1);
782
+ }
783
+ enums.set(d, { k: "enum", name: fullName(d), values: sorted.map((e) => ({ name: e.name, value: e.ordinal })), byName: new Map(sorted.map((e) => [e.name, e.ordinal])), byValue: new Map(sorted.map((e) => [e.ordinal, e.name])) });
784
+ }
785
+
786
+ // names: looked up from the innermost scope outward, then the built-in types
787
+ const lookup = (scope, n) => {
788
+ for (let s = scope; s; s = s.parent) if (s.children?.has(n)) return s.children.get(n);
789
+ return null;
790
+ };
791
+ const nodes = new Map(); // struct decl -> its compiled node (filled in below)
792
+ const resolveType = (expr, scope, seen = new Set()) => {
793
+ let decl = expr.absolute ? parsed.file.children.get(expr.path[0]) ?? null : lookup(scope, expr.path[0]);
794
+ if (!decl && !expr.absolute && expr.path.length === 1) {
795
+ const n = expr.path[0];
796
+ if (n === "List") {
797
+ if (expr.args?.length !== 1) throw new CapnpError("List takes one type, like List(Text)", { line: expr.line, column: expr.col });
798
+ return { k: "list", of: resolveType(expr.args[0], scope, seen), lg: -2 };
799
+ }
800
+ if (PRIMS[n]) {
801
+ if (expr.args) throw new CapnpError(`${n} takes no parameters`, { line: expr.line, column: expr.col });
802
+ return PRIMS[n];
803
+ }
804
+ }
805
+ const shown = `${expr.absolute ? "." : ""}${expr.path.join(".")}`;
806
+ for (let i = 0; ; i++) {
807
+ if (!decl) throw new CapnpError(`unknown type ${shown}${i ? ` ("${expr.path[i]}" isn't declared in ${expr.path.slice(0, i).join(".")})` : ""}`, { line: expr.line, column: expr.col });
808
+ if (decl.kind === "using") {
809
+ if (decl.import !== undefined) throw new CapnpError(`${shown} comes from "${decl.import}", and a schema here is one piece of text: put the types it needs in this schema`, { line: expr.line, column: expr.col });
810
+ if (seen.has(decl)) throw new CapnpError(`the alias ${decl.name} refers to itself`, { line: decl.line, column: decl.col });
811
+ seen.add(decl);
812
+ const target = resolveType(decl.target, decl.parent, seen);
813
+ if (i === expr.path.length - 1) return target;
814
+ if (target.k !== "struct") throw new CapnpError(`unknown type ${shown}`, { line: expr.line, column: expr.col });
815
+ decl = target.decl.children.get(expr.path[i + 1]) ?? null;
816
+ continue;
817
+ }
818
+ if (i === expr.path.length - 1) break;
819
+ decl = decl.children?.get(expr.path[i + 1]) ?? null;
820
+ }
821
+ if (expr.args || decl.generic) throw new CapnpError(`${shown} is a generic type, which this reader doesn't support`, { line: expr.line, column: expr.col });
822
+ if (decl.kind === "struct") return { k: "struct", name: fullName(decl), decl, lg: -2, get node() { return nodes.get(decl); } };
823
+ if (decl.kind === "enum") return { ...enums.get(decl), lg: 4 };
824
+ if (decl.kind === "interface") return { k: "interface", name: fullName(decl), lg: -2 };
825
+ throw new CapnpError(`${shown} is a ${decl.kind}, not a type`, { line: expr.line, column: expr.col });
826
+ };
827
+
828
+ let fieldCount = 0;
829
+ const pending = []; // pointer and data defaults, checked once every struct is laid out
830
+ for (const decl of structDecls) {
831
+ if (decl.generic) continue; // refused where it is used
832
+ try {
833
+ nodes.set(decl, layoutStruct(decl, resolveType, err, pending));
834
+ } catch (e) {
835
+ if (!(e instanceof CapnpError)) throw e;
836
+ err(e.line ? { line: e.line, col: e.column } : decl, e.line ? e.message : `struct ${decl.name}: ${e.message}`);
837
+ continue;
838
+ }
839
+ fieldCount += nodes.get(decl).fieldCount;
840
+ if (fieldCount > maxFields) return { ok: false, errors: [{ message: `a schema has at most ${maxFields} fields in all` }], types, structs };
841
+ }
842
+ for (const decl of structDecls) {
843
+ const node = nodes.get(decl);
844
+ if (!node) continue;
845
+ structs.set(node.name, node);
846
+ types.push(node.name);
847
+ }
848
+ // defaults: a primitive's as the bits it is stored XORed with, a pointer's as a small message of its own
849
+ for (const { member, expr } of pending) {
850
+ try {
851
+ setDefault(member, expr);
852
+ } catch (e) {
853
+ if (!(e instanceof CapnpError)) throw e;
854
+ err(expr, `the default of ${member.name}: ${e.message}`);
855
+ }
856
+ }
857
+ // the constants' types and values are checked too, as capnp does
858
+ const consts = [];
859
+ const walkConsts = (scope) => {
860
+ for (const d of scope.children.values()) {
861
+ if (d.kind === "const") consts.push(d);
862
+ if (d.kind === "struct") walkConsts(d);
863
+ }
864
+ };
865
+ walkConsts(parsed.file);
866
+ for (const c of consts) {
867
+ try {
868
+ const type = resolveType(c.type, c.parent);
869
+ checkLiteral(literal(c.value), type);
870
+ } catch (e) {
871
+ if (!(e instanceof CapnpError)) throw e;
872
+ err(e.line ? { line: e.line, col: e.column } : c, `constant ${c.name}: ${e.message}`);
873
+ }
874
+ }
875
+ const first = structDecls.find((d) => d.parent.kind === "file" && nodes.has(d));
876
+ return { ok: errors.length === 0, errors: errors.sort((a, b) => (a.line ?? 0) - (b.line ?? 0)), types, structs, first: first ? nodes.get(first).name : types[0] };
877
+ }
878
+
879
+ /** One struct laid out: StructTranslator, member by member in ordinal order. */
880
+ function layoutStruct(decl, resolveType, err, pending) {
881
+ const top = new Top();
882
+ const byOrdinal = [];
883
+ const all = [];
884
+ let fieldCount = 0;
885
+ const member = (parent, codeOrder, d, isInUnion, fieldScope = null) => ({ parent, codeOrder, decl: d, kind: d.kind, isInUnion, fieldScope, unionScope: null, schema: null, fields: null, childCount: 0, unionDiscriminantCount: 0 });
886
+ const root = { parent: null, kind: "root", fields: null, unionScope: null, unionDiscriminantCount: 0 };
887
+ const getSchema = (m) => {
888
+ if (!m.schema) {
889
+ const b = addMemberSchema(m.parent);
890
+ if (m.isInUnion) b.disc = m.parent.unionDiscriminantCount++;
891
+ b.name = m.decl.name;
892
+ b.codeOrder = m.codeOrder;
893
+ b.line = m.decl.line;
894
+ m.schema = b;
895
+ }
896
+ return m.schema;
897
+ };
898
+ const addMemberSchema = (m) => {
899
+ if (m.fields === null) {
900
+ if (m.parent) getSchema(m);
901
+ m.fields = [];
902
+ }
903
+ const f = {};
904
+ m.fields.push(f);
905
+ return f;
906
+ };
907
+ const names = (members, where) => {
908
+ const seen = new Set();
909
+ for (const d of members) {
910
+ if (!d.name) continue;
911
+ if (seen.has(d.name)) err(d, `"${d.name}" is already defined in ${where}`);
912
+ seen.add(d.name);
913
+ }
914
+ };
915
+ const traverseUnion = (d, members, parent, layout, codeOrder) => {
916
+ if (members.length < 2) err(d, "a union needs at least two members");
917
+ names(members, `union ${d.name || "(unnamed)"}`);
918
+ for (const m of members) {
919
+ let mi = null;
920
+ let ordinal;
921
+ if (m.kind === "field") {
922
+ parent.childCount++;
923
+ mi = member(parent, codeOrder.v++, m, true, new Group(layout));
924
+ all.push(mi);
925
+ ordinal = m.ordinal;
926
+ } else if (m.kind === "union") {
927
+ if (!m.name) {
928
+ err(m, "a union can't hold an unnamed union");
929
+ continue;
930
+ }
931
+ parent.childCount++;
932
+ const g = new Group(layout);
933
+ const ul = new Union(g);
934
+ mi = member(parent, codeOrder.v++, m, true);
935
+ all.push(mi);
936
+ mi.unionScope = ul;
937
+ traverseUnion(m, m.body, mi, ul, { v: 0 });
938
+ if (m.ordinal) ordinal = m.ordinal;
939
+ } else if (m.kind === "group") {
940
+ parent.childCount++;
941
+ const g = new Group(layout);
942
+ mi = member(parent, codeOrder.v++, m, true);
943
+ all.push(mi);
944
+ traverseGroup(m.body, mi, g);
945
+ }
946
+ if (ordinal) byOrdinal.push([ordinal, mi]);
947
+ }
948
+ };
949
+ const traverseGroup = (members, parent, layout) => {
950
+ if (members.length < 1) err(parent.decl, `group ${parent.decl.name} needs at least one member`);
951
+ traverseTopOrGroup(members, parent, layout);
952
+ };
953
+ const traverseTopOrGroup = (members, parent, layout) => {
954
+ const codeOrder = { v: 0 };
955
+ names(members, parent.kind === "root" ? `struct ${decl.name}` : `group ${parent.decl.name}`);
956
+ for (const m of members) {
957
+ let mi = null;
958
+ let ordinal;
959
+ if (m.kind === "field") {
960
+ parent.childCount++;
961
+ mi = member(parent, codeOrder.v++, m, false, layout);
962
+ all.push(mi);
963
+ ordinal = m.ordinal;
964
+ } else if (m.kind === "union") {
965
+ const ul = new Union(layout);
966
+ let sub = { v: 0 };
967
+ if (!m.name) {
968
+ if (parent.unionScope) err(m, "a struct or group has at most one unnamed union");
969
+ if (m.ordinal) err(m, "an unnamed union can't have an ordinal here: name it, like kind @3 :union { … }");
970
+ mi = parent;
971
+ sub = codeOrder;
972
+ } else {
973
+ parent.childCount++;
974
+ mi = member(parent, codeOrder.v++, m, false);
975
+ all.push(mi);
976
+ if (m.ordinal) ordinal = m.ordinal;
977
+ }
978
+ mi.unionScope = ul;
979
+ traverseUnion(m, m.body, mi, ul, sub);
980
+ } else if (m.kind === "group") {
981
+ parent.childCount++;
982
+ mi = member(parent, codeOrder.v++, m, false);
983
+ all.push(mi);
984
+ traverseGroup(m.body, mi, layout);
985
+ }
986
+ if (ordinal) byOrdinal.push([ordinal, mi]);
987
+ }
988
+ };
989
+ traverseTopOrGroup(decl.body, root, top);
990
+
991
+ byOrdinal.sort((a, b) => a[0].value - b[0].value); // stable: equal ordinals keep their order, as in a multimap
992
+ let expected = 0;
993
+ for (const [ord, m] of byOrdinal) {
994
+ if (ord.value < expected) err({ line: ord.line, col: ord.col }, `ordinal @${ord.value} is used twice in struct ${decl.name}`);
995
+ else if (ord.value > expected) {
996
+ err({ line: ord.line, col: ord.col }, `skipped ordinal @${expected} in struct ${decl.name}: ordinals must be sequential with no holes`);
997
+ expected = ord.value + 1;
998
+ } else expected++;
999
+ const f = getSchema(m);
1000
+ if (m.kind === "field") {
1001
+ fieldCount++;
1002
+ let type;
1003
+ try {
1004
+ type = resolveType(m.decl.type, decl);
1005
+ } catch (e) {
1006
+ if (!(e instanceof CapnpError)) throw e;
1007
+ err({ line: e.line, col: e.column }, e.message);
1008
+ type = PRIMS.Void;
1009
+ }
1010
+ f.type = type;
1011
+ if (type.lg === -2) f.offset = m.fieldScope.addPointer();
1012
+ else if (type.lg === -1) {
1013
+ m.fieldScope.addVoid();
1014
+ f.offset = 0;
1015
+ } else f.offset = m.fieldScope.addData(type.lg);
1016
+ if (m.decl.def) pending.push({ member: f, expr: m.decl.def });
1017
+ } else if (m.kind === "union") {
1018
+ if (!m.unionScope.addDiscriminant()) err({ line: ord.line, col: ord.col }, "a union's ordinal, if it has one, must be greater than no more than one of its members' ordinals (only one field can be made into a union later)");
1019
+ }
1020
+ }
1021
+ const finishGroup = (m) => {
1022
+ if (m.unionScope) {
1023
+ m.unionScope.addDiscriminant();
1024
+ m.discriminantOffset = m.unionScope.discriminantOffset;
1025
+ }
1026
+ if (m.parent) getSchema(m).group = m;
1027
+ };
1028
+ finishGroup(root);
1029
+ for (const m of all) if (m.kind !== "field") finishGroup(m);
1030
+
1031
+ const scopeOf = (m) => {
1032
+ const list = [...(m.fields ?? [])].sort((a, b) => a.codeOrder - b.codeOrder);
1033
+ const scope = { fields: [], union: null };
1034
+ for (const f of list) {
1035
+ const out = { name: f.name, line: f.line, ...(f.disc !== undefined ? { disc: f.disc } : {}) };
1036
+ if (f.group) out.group = scopeOf(f.group);
1037
+ else {
1038
+ out.type = f.type;
1039
+ out.offset = f.offset;
1040
+ out.def = 0n; // the bits a primitive is stored XORed with; a pointer's default message is `defMsg`
1041
+ }
1042
+ f.out = out;
1043
+ scope.fields.push(out);
1044
+ }
1045
+ if (m.unionScope) {
1046
+ const members = scope.fields.filter((f) => f.disc !== undefined);
1047
+ scope.union = { offset: m.discriminantOffset, members, byDisc: new Map(members.map((f) => [f.disc, f])) };
1048
+ }
1049
+ return scope;
1050
+ };
1051
+ const scope = scopeOf(root);
1052
+ // the defaults are set on the scope's records
1053
+ for (const p of pending) if (p.member.out) p.member = p.member.out;
1054
+ return { name: fullName(decl), dataWords: top.dataWordCount, pointers: top.pointerCount, scope, fieldCount, line: decl.line };
1055
+ }
1056
+
1057
+ /** A default's literal as the value `encode` takes. */
1058
+ function literal(expr) {
1059
+ switch (expr.k) {
1060
+ case "int":
1061
+ return expr.v >= BigInt(Number.MIN_SAFE_INTEGER) && expr.v <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(expr.v) : expr.v;
1062
+ case "float":
1063
+ case "str":
1064
+ case "data":
1065
+ return expr.v;
1066
+ case "id":
1067
+ if (expr.path.length === 1 && (expr.path[0] === "true" || expr.path[0] === "false")) return expr.path[0] === "true";
1068
+ if (expr.path.length === 1 && expr.path[0] === "void") return null;
1069
+ if (expr.path.length === 1) return { $enumerant: expr.path[0], line: expr.line, col: expr.col };
1070
+ throw new CapnpError(`${expr.path.join(".")}: a default that names a constant isn't supported: write the value`, { line: expr.line, column: expr.col });
1071
+ case "struct": {
1072
+ const out = {};
1073
+ for (const f of expr.fields) out[f.name] = literal(f.value);
1074
+ return out;
1075
+ }
1076
+ case "list":
1077
+ return expr.items.map(literal);
1078
+ default:
1079
+ throw new CapnpError("this value isn't one a default can be");
1080
+ }
1081
+ }
1082
+
1083
+ /** A literal against a type, as `encode` would check it: throws a CapnpError on the first problem. */
1084
+ function checkLiteral(value, type) {
1085
+ const problems = [];
1086
+ if (type.lg === -1) {
1087
+ if (value !== null) throw new CapnpError(`a Void value is void, got ${got(value)}`);
1088
+ return null;
1089
+ }
1090
+ if (type.lg >= 0) {
1091
+ primitiveBits(type, value, { problems, literal: true }, "value");
1092
+ if (problems.length) throw new CapnpError(problems[0].message.replace(/^value: /, ""));
1093
+ return null;
1094
+ }
1095
+ const w = writer(1 << 20);
1096
+ const root = w.alloc(1);
1097
+ writePointerValue(w, root, type, value, { problems, binary: "base64", bytesIn: literalBytes, literal: true, items: { n: 0, max: 1e6 }, depth: 64 }, "value", 0);
1098
+ if (problems.length) throw new CapnpError(problems[0].message.replace(/^value: /, "").replace(/^value\./, ""));
1099
+ return w;
1100
+ }
1101
+ const literalBytes = (v) => (v instanceof Uint8Array ? v : typeof v === "string" ? new TextEncoder().encode(v) : Array.isArray(v) && v.every((x) => Number.isInteger(x) && x >= 0 && x <= 255) ? Uint8Array.from(v) : undefined);
1102
+
1103
+ function setDefault(f, expr) {
1104
+ if (f.group) throw new CapnpError("a group has no default");
1105
+ const value = literal(expr);
1106
+ if (f.type.lg === -1) {
1107
+ if (value !== null) throw new CapnpError("a Void field's default is void");
1108
+ return;
1109
+ }
1110
+ if (f.type.lg >= 0) {
1111
+ const problems = [];
1112
+ const bits = primitiveBits(f.type, value, { problems, literal: true }, "value");
1113
+ if (problems.length) throw new CapnpError(problems[0].message.replace(/^value: /, ""));
1114
+ f.def = bits;
1115
+ return;
1116
+ }
1117
+ if (f.type.k === "any" || f.type.k === "interface") throw new CapnpError(`a ${typeWords(f.type)} field can't have a default`);
1118
+ const w = checkLiteral(value, f.type);
1119
+ f.defMsg = w.finish(); // a message whose root pointer is the default
1120
+ }
1121
+
1122
+ // ── primitives ───────────────────────────────────────────────────────────────
1123
+
1124
+ const scratch = new DataView(new ArrayBuffer(8));
1125
+ const RANGES = { int8: [-128, 127], int16: [-32768, 32767], int32: [-2147483648, 2147483647], uint8: [0, 255], uint16: [0, 65535], uint32: [0, 4294967295] };
1126
+ const RANGES64 = { int64: [-(2n ** 63n), 2n ** 63n - 1n], uint64: [0n, 2n ** 64n - 1n] };
1127
+ const got = (v) => (v === null ? "null" : v === undefined ? "nothing" : Array.isArray(v) ? "a list" : v instanceof Uint8Array ? "bytes" : typeof v === "object" ? "an object" : typeof v === "string" ? `text ${JSON.stringify(v.length > 24 ? `${v.slice(0, 24)}…` : v)}` : typeof v === "bigint" ? `${v}` : String(v));
1128
+
1129
+ /** A value as the bits it is stored as (before the XOR with the field's default): a BigInt. Problems are pushed. */
1130
+ function primitiveBits(type, value, ctx, path) {
1131
+ const bad = (message) => {
1132
+ ctx.problems.push({ path, message: `${path}: ${message}` });
1133
+ return 0n;
1134
+ };
1135
+ const enumName = value && typeof value === "object" && "$enumerant" in value ? value.$enumerant : undefined;
1136
+ switch (type.k) {
1137
+ case "bool":
1138
+ return typeof value === "boolean" ? (value ? 1n : 0n) : bad(`expected true or false, got ${got(enumName ?? value)}`);
1139
+ case "int8":
1140
+ case "int16":
1141
+ case "int32":
1142
+ case "uint8":
1143
+ case "uint16":
1144
+ case "uint32": {
1145
+ const [lo, hi] = RANGES[type.k];
1146
+ const n = typeof value === "bigint" && value >= BigInt(lo) && value <= BigInt(hi) ? Number(value) : value;
1147
+ if (typeof n !== "number" || !Number.isInteger(n) || n < lo || n > hi) return bad(`expected a whole number from ${lo} to ${hi} (${TYPE_WORDS[type.k]}), got ${got(enumName ?? value)}`);
1148
+ const bits = { int8: 8, int16: 16, int32: 32, uint8: 8, uint16: 16, uint32: 32 }[type.k];
1149
+ return BigInt.asUintN(bits, BigInt(n));
1150
+ }
1151
+ case "int64":
1152
+ case "uint64": {
1153
+ const [lo, hi] = RANGES64[type.k];
1154
+ let n;
1155
+ if (typeof value === "number" && Number.isInteger(value)) n = BigInt(value);
1156
+ else if (typeof value === "bigint") n = value;
1157
+ else if (typeof value === "string" && /^-?\d+$/.test(value)) n = BigInt(value);
1158
+ if (n === undefined || n < lo || n > hi) return bad(`expected a whole number from ${lo} to ${hi} (${TYPE_WORDS[type.k]}; larger ones as text), got ${got(enumName ?? value)}`);
1159
+ return BigInt.asUintN(64, n);
1160
+ }
1161
+ case "float32":
1162
+ case "float64": {
1163
+ let n = value;
1164
+ if (typeof value === "bigint") n = Number(value);
1165
+ if (typeof n !== "number") return bad(`expected a number (${TYPE_WORDS[type.k]}), got ${got(enumName ?? value)}`);
1166
+ if (type.k === "float32") {
1167
+ scratch.setFloat32(0, n, true);
1168
+ return BigInt(scratch.getUint32(0, true));
1169
+ }
1170
+ scratch.setFloat64(0, n, true);
1171
+ return scratch.getBigUint64(0, true);
1172
+ }
1173
+ case "enum": {
1174
+ const name = enumName ?? value;
1175
+ if (typeof name === "string" && type.byName.has(name)) return BigInt(type.byName.get(name));
1176
+ if (!ctx.literal && Number.isInteger(value) && type.byValue.has(value)) return BigInt(value);
1177
+ return bad(`expected one of ${[...type.byName.keys()].join(", ")} (enum ${type.name}), got ${got(name)}`);
1178
+ }
1179
+ default:
1180
+ return bad(`has the unsupported type ${typeWords(type)}`);
1181
+ }
1182
+ }
1183
+
1184
+ /** Stored bits (a BigInt, already XORed back with the default) as the value. */
1185
+ function primitiveValue(type, bits) {
1186
+ switch (type.k) {
1187
+ case "bool":
1188
+ return bits !== 0n;
1189
+ case "int8":
1190
+ return Number(BigInt.asIntN(8, bits));
1191
+ case "int16":
1192
+ return Number(BigInt.asIntN(16, bits));
1193
+ case "int32":
1194
+ return Number(BigInt.asIntN(32, bits));
1195
+ case "uint8":
1196
+ case "uint16":
1197
+ case "uint32":
1198
+ return Number(bits);
1199
+ case "int64": {
1200
+ const n = BigInt.asIntN(64, bits);
1201
+ return n >= BigInt(Number.MIN_SAFE_INTEGER) && n <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(n) : String(n);
1202
+ }
1203
+ case "uint64":
1204
+ return bits <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(bits) : String(bits);
1205
+ case "float32":
1206
+ scratch.setUint32(0, Number(bits), true);
1207
+ return scratch.getFloat32(0, true);
1208
+ case "float64":
1209
+ scratch.setBigUint64(0, bits, true);
1210
+ return scratch.getFloat64(0, true);
1211
+ case "enum": {
1212
+ const n = Number(bits);
1213
+ return type.byValue.get(n) ?? n;
1214
+ }
1215
+ }
1216
+ return null;
1217
+ }
1218
+
1219
+ const BITS = { bool: 1, int8: 8, uint8: 8, int16: 16, uint16: 16, enum: 16, int32: 32, uint32: 32, float32: 32, int64: 64, uint64: 64, float64: 64 };
1220
+
1221
+ // ── the wire format: reading ─────────────────────────────────────────────────
1222
+
1223
+ const ELEMENT_WORDS = ["no data (Void)", "bits", "1-byte values", "2-byte values", "4-byte values", "8-byte values", "pointers", "structs"];
1224
+ const ELEMENT_BITS = [0, 1, 8, 16, 32, 64, 64];
1225
+ const elementSizeOf = (t) => (t.k === "void" ? 0 : t.k === "bool" ? 1 : t.lg === 3 ? 2 : t.lg === 4 ? 3 : t.lg === 5 ? 4 : t.lg === 6 ? 5 : t.k === "struct" ? 7 : 6);
1226
+ const step = (path, key) => (typeof key === "number" ? `${path}[${key}]` : path ? `${path}.${key}` : key);
1227
+
1228
+ /** The segments of a message in the standard stream framing: [{ start (byte), words }]. */
1229
+ function segmentsOf(b) {
1230
+ const fail = (message, offset) => {
1231
+ throw new CapnpError(message, { offset });
1232
+ };
1233
+ if (b.length < 8) fail(b.length ? `the message ends inside its segment table (${b.length} bytes; a message is at least 8)` : "the message is empty", b.length);
1234
+ const v = new DataView(b.buffer, b.byteOffset, b.byteLength);
1235
+ const count = v.getUint32(0, true) + 1;
1236
+ if (count > 512) fail(`the segment table says ${count} segments; a message has at most 512 (are these bytes Cap'n Proto?)`, 0);
1237
+ const headerBytes = Math.ceil((4 + 4 * count) / 8) * 8;
1238
+ if (headerBytes > b.length) fail(`the message ends inside its segment table (${count} segments need ${headerBytes} bytes of table)`, b.length);
1239
+ const segs = [];
1240
+ let at = headerBytes;
1241
+ for (let i = 0; i < count; i++) {
1242
+ const words = v.getUint32(4 + 4 * i, true);
1243
+ if (at + words * 8 > b.length) fail(`segment ${i} is ${words} words, but the message ends inside it (at byte ${b.length}; are these bytes Cap'n Proto${count > 1 ? "" : ", or packed"}?)`, at);
1244
+ segs.push({ start: at, words });
1245
+ at += words * 8;
1246
+ }
1247
+ if (at < b.length) fail(`${b.length - at} bytes follow the message's ${count === 1 ? "segment" : `${count} segments`} (a stream of messages: frame it first${count === 1 ? "; or the message is packed" : ""})`, at);
1248
+ if (!segs[0].words) fail("the first segment is empty, so there is no root pointer", headerBytes);
1249
+ return { view: v, segs, words: (at - headerBytes) / 8 };
1250
+ }
1251
+
1252
+ /**
1253
+ * Bytes (a message in the standard framing, or packed) as the value of struct `typeName`.
1254
+ * opts: { packed?, depth, items, maxBytes, tick?, bytesOut?(u8) }.
1255
+ * Throws a CapnpError with `path` (the field, like readings[2].sensor) and `offset` (the byte of the unpacked message).
1256
+ */
1257
+ export function decode(schema, typeName, input, opts = {}) {
1258
+ const node = schema.structs.get(typeName);
1259
+ if (!node) throw new CapnpError(`the schema has no struct ${typeName}`);
1260
+ const bytes = opts.packed ? unpack(input, opts.maxBytes ?? 1 << 24) : input;
1261
+ const msg = segmentsOf(bytes);
1262
+ const r = reader(msg, opts);
1263
+ return r.root(node);
1264
+ }
1265
+
1266
+ function reader(msg, opts) {
1267
+ const { view, segs } = msg;
1268
+ const maxDepth = opts.depth ?? 32;
1269
+ const maxItems = opts.items ?? 100000;
1270
+ const tick = opts.tick ?? (() => {});
1271
+ const bytesOut = opts.bytesOut ?? ((u8) => u8);
1272
+ let items = 0;
1273
+ let budget = msg.words * 8 + 64; // words read: a pointer that points at the same data again and again is stopped here
1274
+ const at = (seg, word) => segs[seg].start + word * 8;
1275
+ const fail = (message, path, offset, kind) => {
1276
+ throw new CapnpError(message, { path: path || undefined, offset, kind });
1277
+ };
1278
+ const count = (n, path, offset) => {
1279
+ items += n;
1280
+ if (items > maxItems) fail(`the message has more than ${maxItems} values (the items limit)`, path, offset, "items");
1281
+ tick();
1282
+ };
1283
+ const charge = (words, path, offset) => {
1284
+ budget -= words;
1285
+ if (budget < 0) fail(`the message points at the same data again and again (it reads as far more than its ${msg.words} words)`, path, offset, "items");
1286
+ };
1287
+ const deep = (depth, path, offset) => {
1288
+ if (depth > maxDepth) fail(`the message nests deeper than ${maxDepth} levels (the depth limit)`, path, offset, "depth");
1289
+ };
1290
+ const inSeg = (seg, from, words, path, offset, what) => {
1291
+ if (from < 0 || from + words > segs[seg].words) fail(`${what} points outside its segment (segment ${seg} is ${segs[seg].words} words; it points at words ${from} to ${from + words})`, path, offset);
1292
+ };
1293
+
1294
+ /** The pointer at (seg, word), far pointers followed: null for a null pointer, else { kind, lo, hi, seg, target, where }. */
1295
+ const pointer = (seg, word, path) => {
1296
+ const where = at(seg, word);
1297
+ const lo = view.getUint32(where, true);
1298
+ const hi = view.getUint32(where + 4, true);
1299
+ if (lo === 0 && hi === 0) return null;
1300
+ const kind = lo & 3;
1301
+ if (kind !== 2) return { kind, lo, hi, seg, target: word + 1 + ((lo | 0) >> 2), where };
1302
+ const double = (lo >>> 2) & 1;
1303
+ const pad = lo >>> 3;
1304
+ const tseg = hi;
1305
+ if (tseg >= segs.length) fail(`a far pointer names segment ${tseg}, and the message has ${segs.length}`, path, where);
1306
+ inSeg(tseg, pad, double ? 2 : 1, path, where, "a far pointer's landing pad");
1307
+ const padAt = at(tseg, pad);
1308
+ const plo = view.getUint32(padAt, true);
1309
+ const phi = view.getUint32(padAt + 4, true);
1310
+ if (!double) {
1311
+ if ((plo & 3) === 2) fail("a far pointer lands on another far pointer", path, padAt);
1312
+ if (plo === 0 && phi === 0) return null;
1313
+ return { kind: plo & 3, lo: plo, hi: phi, seg: tseg, target: pad + 1 + ((plo | 0) >> 2), where: padAt };
1314
+ }
1315
+ if ((plo & 7) !== 2) fail("a double-far pointer's landing pad doesn't start with a single far pointer", path, padAt);
1316
+ const cseg = phi;
1317
+ if (cseg >= segs.length) fail(`a far pointer names segment ${cseg}, and the message has ${segs.length}`, path, padAt);
1318
+ const tlo = view.getUint32(padAt + 8, true);
1319
+ const thi = view.getUint32(padAt + 12, true);
1320
+ if ((tlo & 3) === 2) fail("a double-far pointer's tag is another far pointer", path, padAt + 8);
1321
+ return { kind: tlo & 3, lo: tlo, hi: thi, seg: cseg, target: plo >>> 3, where: padAt + 8 };
1322
+ };
1323
+
1324
+ /** A struct's sections: { seg, data (byte), dataBytes, ptr (word), ptrs }. */
1325
+ const structAt = (p, path) => {
1326
+ if (p.kind !== 0) fail(`expected a struct pointer, found a ${p.kind === 1 ? "list" : "capability"} pointer`, path, p.where);
1327
+ const dw = p.hi & 0xffff;
1328
+ const pc = p.hi >>> 16;
1329
+ inSeg(p.seg, p.target, dw + pc, path, p.where, "a struct pointer");
1330
+ charge(dw + pc, path, p.where);
1331
+ return { seg: p.seg, data: at(p.seg, p.target), dataBytes: dw * 8, dataBits: dw * 64, ptr: p.target + dw, ptrs: pc };
1332
+ };
1333
+
1334
+ const readBits = (s, lg, offset) => {
1335
+ if (lg === 0) return offset < s.dataBits ? BigInt((view.getUint8(s.data + (offset >>> 3)) >>> (offset & 7)) & 1) : 0n;
1336
+ const size = 2 ** (lg - 3);
1337
+ const byte = offset * size;
1338
+ if (byte + size > s.dataBytes) return 0n;
1339
+ const a = s.data + byte;
1340
+ return size === 1 ? BigInt(view.getUint8(a)) : size === 2 ? BigInt(view.getUint16(a, true)) : size === 4 ? BigInt(view.getUint32(a, true)) : view.getBigUint64(a, true);
1341
+ };
1342
+
1343
+ const struct = (node, s, path, depth) => {
1344
+ deep(depth, path, s.data);
1345
+ count(1, path, s.data);
1346
+ return scopeValue(node.scope, s, path, depth);
1347
+ };
1348
+ const scopeValue = (scope, s, path, depth) => {
1349
+ const out = {};
1350
+ const active = scope.union ? Number(readBits(s, 4, scope.union.offset)) : -1;
1351
+ for (const f of scope.fields) {
1352
+ if (f.disc !== undefined && f.disc !== active) continue;
1353
+ const where = step(path, f.name);
1354
+ let v;
1355
+ if (f.group) v = scopeValue(f.group, s, where, depth);
1356
+ else v = field(f, s, where, depth);
1357
+ if (f.name === "__proto__") Object.defineProperty(out, f.name, { value: v, enumerable: true, writable: true, configurable: true });
1358
+ else out[f.name] = v;
1359
+ }
1360
+ return out;
1361
+ };
1362
+ const field = (f, s, path, depth) => {
1363
+ const t = f.type;
1364
+ if (t.lg === -1) return null;
1365
+ if (t.lg >= 0) return primitiveValue(t, readBits(s, t.lg, f.offset) ^ f.def);
1366
+ if (f.offset >= s.ptrs) return nullValue(f, path, depth);
1367
+ const p = pointer(s.seg, s.ptr + f.offset, path);
1368
+ if (!p) return nullValue(f, path, depth);
1369
+ return pointerValue(t, p, path, depth);
1370
+ };
1371
+ const nullValue = (f, path, depth) => {
1372
+ if (f.defMsg) {
1373
+ // the field's default, read from the small message the schema made for it (its words don't count against this message)
1374
+ const d = reader({ ...segmentsOf(f.defMsg) }, { ...opts, depth: maxDepth - depth, items: maxItems - items, tick, bytesOut });
1375
+ const v = d.pointerAt(f.type, path);
1376
+ count(d.items(), path);
1377
+ return v;
1378
+ }
1379
+ return emptyOf(f.type);
1380
+ };
1381
+ const emptyOf = (t) => (t.k === "text" ? "" : t.k === "data" ? bytesOut(new Uint8Array(0)) : t.k === "list" ? [] : null);
1382
+
1383
+ const pointerValue = (t, p, path, depth) => {
1384
+ switch (t.k) {
1385
+ case "struct":
1386
+ return struct(t.node, structAt(p, path), path, depth + 1);
1387
+ case "text":
1388
+ case "data": {
1389
+ const l = listAt(p, path, depth);
1390
+ if (l.es !== 2) fail(`expected ${t.k === "text" ? "Text" : "Data"} (a list of bytes), found a list of ${ELEMENT_WORDS[l.es]}`, path, p.where);
1391
+ count(1, path, l.start);
1392
+ if (t.k === "data") return bytesOut(new Uint8Array(view.buffer.slice(view.byteOffset + l.start, view.byteOffset + l.start + l.count)));
1393
+ if (l.count === 0 || view.getUint8(l.start + l.count - 1) !== 0) fail("the text doesn't end with a NUL byte", path, l.start + Math.max(0, l.count - 1));
1394
+ return new TextDecoder().decode(new Uint8Array(view.buffer, view.byteOffset + l.start, l.count - 1));
1395
+ }
1396
+ case "list":
1397
+ return list(t.of, listAt(p, path, depth), path, depth + 1);
1398
+ case "interface":
1399
+ case "any":
1400
+ if (p.kind === 3) {
1401
+ if (p.lo !== 3) fail("a capability pointer with bits it shouldn't have", path, p.where);
1402
+ count(1, path, p.where);
1403
+ return { capability: p.hi };
1404
+ }
1405
+ fail(`${typeWords(t)} points at a ${p.kind === 0 ? "struct" : "list"}, which has no schema here to read it with`, path, p.where);
1406
+ }
1407
+ return null;
1408
+ };
1409
+
1410
+ /** A list pointer's elements: { es, count, start (byte), seg, word, stride? (composite: words per element), dw, pc }. */
1411
+ const listAt = (p, path, depth) => {
1412
+ deep(depth + 1, path, p.where);
1413
+ if (p.kind !== 1) fail(`expected a list pointer, found a ${p.kind === 0 ? "struct" : "capability"} pointer`, path, p.where);
1414
+ const es = p.hi & 7;
1415
+ const n = p.hi >>> 3;
1416
+ if (es === 7) {
1417
+ inSeg(p.seg, p.target, n + 1, path, p.where, "a list pointer");
1418
+ const tagAt = at(p.seg, p.target);
1419
+ const tlo = view.getUint32(tagAt, true);
1420
+ const thi = view.getUint32(tagAt + 4, true);
1421
+ if ((tlo & 3) !== 0) fail("a list of structs doesn't start with a struct tag", path, tagAt);
1422
+ const elements = (tlo | 0) >> 2;
1423
+ if (elements < 0) fail(`a list of structs says it has ${elements} elements`, path, tagAt);
1424
+ const dw = thi & 0xffff;
1425
+ const pc = thi >>> 16;
1426
+ if (elements * (dw + pc) > n) fail(`a list of ${elements} structs of ${dw + pc} words doesn't fit in its ${n} words`, path, tagAt);
1427
+ charge(elements * (dw + pc) + 1, path, p.where);
1428
+ return { es, count: elements, seg: p.seg, word: p.target + 1, start: at(p.seg, p.target + 1), dw, pc, where: p.where };
1429
+ }
1430
+ const words = Math.ceil((n * ELEMENT_BITS[es]) / 64);
1431
+ inSeg(p.seg, p.target, words, path, p.where, "a list pointer");
1432
+ charge(words, path, p.where); // a list of voids takes no words: the items limit bounds it
1433
+ return { es, count: n, seg: p.seg, word: p.target, start: at(p.seg, p.target), where: p.where };
1434
+ };
1435
+
1436
+ const list = (of, l, path, depth) => {
1437
+ count(1, path, l.start);
1438
+ if (l.count > maxItems - items) fail(`the message has more than ${maxItems} values (the items limit): a list of ${l.count}`, path, l.start, "items");
1439
+ const want = elementSizeOf(of);
1440
+ const out = new Array(l.count);
1441
+ const composite = l.es === 7;
1442
+ if (want === 7) {
1443
+ if (l.es === 1) fail(`expected a list of structs (${typeWords(of)}), found a list of bits`, path, l.where);
1444
+ for (let i = 0; i < l.count; i++) {
1445
+ const at_ = step(path, i);
1446
+ let s;
1447
+ if (composite) s = { seg: l.seg, data: l.start + i * (l.dw + l.pc) * 8, dataBytes: l.dw * 8, dataBits: l.dw * 64, ptr: l.word + i * (l.dw + l.pc) + l.dw, ptrs: l.pc };
1448
+ else if (l.es === 6) s = { seg: l.seg, data: l.start, dataBytes: 0, dataBits: 0, ptr: l.word + i, ptrs: 1 };
1449
+ else {
1450
+ const size = ELEMENT_BITS[l.es] / 8;
1451
+ s = { seg: l.seg, data: l.start + i * size, dataBytes: size, dataBits: size * 8, ptr: 0, ptrs: 0 };
1452
+ }
1453
+ out[i] = struct(of.node, s, at_, depth);
1454
+ }
1455
+ return out;
1456
+ }
1457
+ if (composite) {
1458
+ // a list of structs read as a list of primitives or pointers: each struct's first data word or first pointer
1459
+ if (want === 1) fail(`expected a list of bits (${typeWords(of)}), found a list of structs`, path, l.where);
1460
+ for (let i = 0; i < l.count; i++) {
1461
+ const s = { seg: l.seg, data: l.start + i * (l.dw + l.pc) * 8, dataBytes: l.dw * 8, dataBits: l.dw * 64, ptr: l.word + i * (l.dw + l.pc) + l.dw, ptrs: l.pc };
1462
+ out[i] = element(of, s, 0, step(path, i), depth);
1463
+ }
1464
+ count(l.count, path, l.start);
1465
+ return out;
1466
+ }
1467
+ if (want !== l.es && !(want === 0)) fail(`expected a list of ${ELEMENT_WORDS[want]} (${typeWords({ k: "list", of })}), found a list of ${ELEMENT_WORDS[l.es]}`, path, l.where);
1468
+ if (want === 6) {
1469
+ for (let i = 0; i < l.count; i++) {
1470
+ const where = step(path, i);
1471
+ const p = pointer(l.seg, l.word + i, where);
1472
+ out[i] = p ? pointerValue(of, p, where, depth) : emptyOf(of);
1473
+ }
1474
+ return out;
1475
+ }
1476
+ count(l.count, path, l.start);
1477
+ if (want === 0) return out.fill(null);
1478
+ const s = { seg: l.seg, data: l.start, dataBytes: Math.ceil((l.count * ELEMENT_BITS[want]) / 8), dataBits: l.count * ELEMENT_BITS[want], ptr: 0, ptrs: 0 };
1479
+ for (let i = 0; i < l.count; i++) out[i] = primitiveValue(of, readBits(s, of.lg, i));
1480
+ return out;
1481
+ };
1482
+ const element = (of, s, index, path, depth) => {
1483
+ if (of.lg === -1) return null;
1484
+ if (of.lg >= 0) return primitiveValue(of, readBits(s, of.lg, index));
1485
+ if (s.ptrs < 1) return emptyOf(of);
1486
+ const p = pointer(s.seg, s.ptr, path);
1487
+ return p ? pointerValue(of, p, path, depth) : emptyOf(of);
1488
+ };
1489
+
1490
+ return {
1491
+ root(node) {
1492
+ const p = pointer(0, 0, "");
1493
+ if (!p) {
1494
+ count(1, "", segs[0].start);
1495
+ return scopeValue(node.scope, { seg: 0, data: 0, dataBytes: 0, dataBits: 0, ptr: 0, ptrs: 0 }, "", 0);
1496
+ }
1497
+ return struct(node, structAt(p, ""), "", 0);
1498
+ },
1499
+ /** The default message's root pointer, read as `type`. */
1500
+ pointerAt(type, path) {
1501
+ const p = pointer(0, 0, path);
1502
+ return p ? pointerValue(type, p, path, 0) : emptyOf(type);
1503
+ },
1504
+ items: () => items,
1505
+ };
1506
+ }
1507
+
1508
+ // ── the wire format: writing ─────────────────────────────────────────────────
1509
+
1510
+ /** One segment, grown as it is written; `finish()` frames it. */
1511
+ function writer(maxBytes) {
1512
+ let buf = new Uint8Array(256);
1513
+ let view = new DataView(buf.buffer);
1514
+ let words = 0;
1515
+ return {
1516
+ get view() {
1517
+ return view;
1518
+ },
1519
+ alloc(n) {
1520
+ const at = words;
1521
+ words += n;
1522
+ if (words * 8 + 8 > maxBytes) throw new CapnpError(`the encoded message is over ${maxBytes} bytes (the bytes limit)`, { kind: "size" });
1523
+ if (words * 8 > buf.length) {
1524
+ let size = buf.length;
1525
+ while (size < words * 8) size *= 2;
1526
+ const bigger = new Uint8Array(size);
1527
+ bigger.set(buf);
1528
+ buf = bigger;
1529
+ view = new DataView(buf.buffer);
1530
+ }
1531
+ return at;
1532
+ },
1533
+ finish() {
1534
+ const out = new Uint8Array(8 + words * 8);
1535
+ const v = new DataView(out.buffer);
1536
+ v.setUint32(0, 0, true);
1537
+ v.setUint32(4, words, true);
1538
+ out.set(buf.subarray(0, words * 8), 8);
1539
+ return out;
1540
+ },
1541
+ };
1542
+ }
1543
+
1544
+ const setStructPointer = (w, at, target, dw, pc) => {
1545
+ const lo = dw + pc === 0 ? 0xfffffffc : ((target - at - 1) * 4) >>> 0;
1546
+ w.view.setUint32(at * 8, lo, true);
1547
+ w.view.setUint32(at * 8 + 4, (dw | (pc << 16)) >>> 0, true);
1548
+ };
1549
+ const setListPointer = (w, at, target, es, n) => {
1550
+ w.view.setUint32(at * 8, (((target - at - 1) * 4) | 1) >>> 0, true);
1551
+ w.view.setUint32(at * 8 + 4, (es | (n << 3)) >>> 0, true);
1552
+ };
1553
+ const writeBits = (w, dataWord, lg, offset, bits) => {
1554
+ const v = w.view;
1555
+ const base = dataWord * 8;
1556
+ if (lg === 0) {
1557
+ const a = base + (offset >>> 3);
1558
+ if (bits) v.setUint8(a, v.getUint8(a) | (1 << (offset & 7)));
1559
+ else v.setUint8(a, v.getUint8(a) & ~(1 << (offset & 7)));
1560
+ return;
1561
+ }
1562
+ const size = 2 ** (lg - 3);
1563
+ const a = base + offset * size;
1564
+ if (size === 1) v.setUint8(a, Number(bits));
1565
+ else if (size === 2) v.setUint16(a, Number(bits), true);
1566
+ else if (size === 4) v.setUint32(a, Number(bits), true);
1567
+ else v.setBigUint64(a, bits, true);
1568
+ };
1569
+
1570
+ const isPlainObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && !ArrayBuffer.isView(v) && !(v instanceof ArrayBuffer) && !("$enumerant" in v);
1571
+
1572
+ /** Write `value` as struct `node`'s sections at (dataWord, ptrWord). */
1573
+ function writeStruct(w, node, dataWord, ptrWord, value, ctx, path, depth) {
1574
+ writeScope(w, node.scope, dataWord, ptrWord, value, ctx, path, depth, node.name);
1575
+ }
1576
+ function writeScope(w, scope, dataWord, ptrWord, value, ctx, path, depth, name) {
1577
+ const bad = (p, message) => ctx.problems.length < 20 && ctx.problems.push({ path: p, message: `${p}: ${message}` });
1578
+ if (!isPlainObject(value)) return bad(path, `expected an object (${name}), got ${got(value?.$enumerant ?? value)}`);
1579
+ ctx.items.n++;
1580
+ if (ctx.items.n > ctx.items.max) throw new CapnpError(`the value has more than ${ctx.items.max} values (the items limit)`, { kind: "items" });
1581
+ const byName = new Map(scope.fields.map((f) => [f.name, f]));
1582
+ for (const key of Object.keys(value)) {
1583
+ if (!byName.has(key)) bad(step(path, key), `${name} has no field "${key}" (fields: ${scope.fields.map((f) => f.name).join(", ") || "none"})`);
1584
+ }
1585
+ if (scope.union) {
1586
+ const chosen = scope.union.members.filter((f) => Object.hasOwn(value, f.name) && value[f.name] !== undefined);
1587
+ if (chosen.length > 1) bad(path, `${chosen.map((f) => f.name).join(" and ")} are members of the same union: set only one`);
1588
+ const pick = chosen[0];
1589
+ if (pick) writeBits(w, dataWord, 4, scope.union.offset, BigInt(pick.disc));
1590
+ }
1591
+ for (const f of scope.fields) {
1592
+ const v = value[f.name];
1593
+ const where = step(path, f.name);
1594
+ if (f.disc !== undefined && !(Object.hasOwn(value, f.name) && v !== undefined)) continue;
1595
+ if (f.group) {
1596
+ if (v === undefined || v === null) continue;
1597
+ writeScope(w, f.group, dataWord, ptrWord, v, ctx, where, depth, `group ${f.name}`);
1598
+ continue;
1599
+ }
1600
+ const t = f.type;
1601
+ if (t.lg === -1) {
1602
+ if (v !== undefined && v !== null) bad(where, `is Void: leave it out or set it to null, got ${got(v)}`);
1603
+ continue;
1604
+ }
1605
+ if (t.lg >= 0) {
1606
+ if (v === undefined || v === null) {
1607
+ // left out: the default, which is stored as all zeros
1608
+ continue;
1609
+ }
1610
+ writeBits(w, dataWord, t.lg, f.offset, primitiveBits(t, v, ctx, where) ^ f.def);
1611
+ continue;
1612
+ }
1613
+ if (v === undefined || v === null) continue; // a null pointer: reads as the field's default
1614
+ writePointerValue(w, ptrWord + f.offset, t, v, ctx, where, depth);
1615
+ }
1616
+ }
1617
+
1618
+ /** Write `value` of pointer type `t` and point the pointer at word `at` to it. */
1619
+ function writePointerValue(w, at, t, value, ctx, path, depth) {
1620
+ const bad = (message) => ctx.problems.length < 20 && ctx.problems.push({ path, message: `${path}: ${message}` });
1621
+ if (depth > ctx.depth) throw new CapnpError(`${path}: nests deeper than ${ctx.depth} levels (the depth limit)`, { path, kind: "depth" });
1622
+ switch (t.k) {
1623
+ case "struct": {
1624
+ const n = t.node;
1625
+ if (!isPlainObject(value)) return bad(`expected an object (${t.name}), got ${got(value?.$enumerant ?? value)}`);
1626
+ const target = w.alloc(n.dataWords + n.pointers);
1627
+ setStructPointer(w, at, target, n.dataWords, n.pointers);
1628
+ writeStruct(w, n, target, target + n.dataWords, value, ctx, path, depth + 1);
1629
+ return;
1630
+ }
1631
+ case "text": {
1632
+ if (typeof value !== "string") return bad(`expected text, got ${got(value?.$enumerant ?? value)}`);
1633
+ const u8 = new TextEncoder().encode(value);
1634
+ const target = w.alloc(Math.ceil((u8.length + 1) / 8));
1635
+ setListPointer(w, at, target, 2, u8.length + 1);
1636
+ new Uint8Array(w.view.buffer, target * 8, u8.length).set(u8);
1637
+ return;
1638
+ }
1639
+ case "data": {
1640
+ const u8 = ctx.bytesIn(value);
1641
+ if (!u8) return bad(`expected bytes (a Uint8Array, a list of numbers 0 to 255${ctx.literal ? ", or text" : `, or ${ctx.binary === "hex" ? "hex" : "base64"} text`}), got ${got(value)}`);
1642
+ const target = w.alloc(Math.ceil(u8.length / 8));
1643
+ setListPointer(w, at, target, 2, u8.length);
1644
+ new Uint8Array(w.view.buffer, target * 8, u8.length).set(u8);
1645
+ return;
1646
+ }
1647
+ case "list": {
1648
+ if (!Array.isArray(value)) return bad(`expected a list (${typeWords(t)}), got ${got(value?.$enumerant ?? value)}`);
1649
+ if (value.length > 2 ** 29 - 1) return bad("a list has at most 536870911 elements");
1650
+ ctx.items.n += value.length + 1;
1651
+ if (ctx.items.n > ctx.items.max) throw new CapnpError(`the value has more than ${ctx.items.max} values (the items limit)`, { kind: "items" });
1652
+ const of = t.of;
1653
+ const es = elementSizeOf(of);
1654
+ if (es === 7) {
1655
+ const n = of.node;
1656
+ const per = n.dataWords + n.pointers;
1657
+ const tag = w.alloc(1 + value.length * per);
1658
+ setListPointer(w, at, tag, 7, value.length * per);
1659
+ w.view.setUint32(tag * 8, (value.length * 4) >>> 0, true);
1660
+ w.view.setUint32(tag * 8 + 4, (n.dataWords | (n.pointers << 16)) >>> 0, true);
1661
+ for (let i = 0; i < value.length; i++) {
1662
+ const el = tag + 1 + i * per;
1663
+ writeStruct(w, n, el, el + n.dataWords, value[i], ctx, step(path, i), depth + 1);
1664
+ }
1665
+ return;
1666
+ }
1667
+ if (es === 6) {
1668
+ const target = w.alloc(value.length);
1669
+ setListPointer(w, at, target, 6, value.length);
1670
+ for (let i = 0; i < value.length; i++) {
1671
+ if (value[i] === null || value[i] === undefined) continue;
1672
+ if (of.k === "any" || of.k === "interface") {
1673
+ ctx.problems.push({ path: step(path, i), message: `${step(path, i)}: a ${typeWords(of)} can only be null here` });
1674
+ continue;
1675
+ }
1676
+ writePointerValue(w, target + i, of, value[i], ctx, step(path, i), depth + 1);
1677
+ }
1678
+ return;
1679
+ }
1680
+ const target = w.alloc(Math.ceil((value.length * ELEMENT_BITS[es]) / 64));
1681
+ setListPointer(w, at, target, es, value.length);
1682
+ if (es === 0) {
1683
+ value.forEach((x, i) => x !== null && x !== undefined && ctx.problems.push({ path: step(path, i), message: `${step(path, i)}: is Void: set it to null, got ${got(x)}` }));
1684
+ return;
1685
+ }
1686
+ for (let i = 0; i < value.length; i++) {
1687
+ const x = value[i];
1688
+ if (x === null || x === undefined) continue;
1689
+ writeBits(w, target, of.lg, i, primitiveBits(of, x, ctx, step(path, i)));
1690
+ }
1691
+ return;
1692
+ }
1693
+ default:
1694
+ return bad(`a ${typeWords(t)} can only be null here (it has no schema to write it with)`);
1695
+ }
1696
+ }
1697
+
1698
+ /**
1699
+ * A value as a message of struct `typeName` (one segment, the standard framing; packed when `opts.packed`).
1700
+ * opts: { packed?, depth, items, maxBytes, binary?, bytesIn(value) -> Uint8Array | undefined }.
1701
+ * Throws a CapnpError whose `problems` are [{ path, message }] (paths like value.readings[2].sensor).
1702
+ */
1703
+ export function encode(schema, typeName, value, opts = {}) {
1704
+ const node = schema.structs.get(typeName);
1705
+ if (!node) throw new CapnpError(`the schema has no struct ${typeName}`);
1706
+ const ctx = { problems: [], bytesIn: opts.bytesIn ?? literalBytes, binary: opts.binary, items: { n: 0, max: opts.items ?? 100000 }, depth: opts.depth ?? 32 };
1707
+ const w = writer(opts.maxBytes ?? 1 << 24);
1708
+ const root = w.alloc(1);
1709
+ if (!isPlainObject(value)) throw new CapnpError(`value: expected an object (${node.name}), got ${got(value)}`, { path: "value", problems: [{ path: "value", message: `value: expected an object (${node.name}), got ${got(value)}` }] });
1710
+ writePointerValue(w, root, { k: "struct", name: node.name, node }, value, ctx, "value", 0);
1711
+ if (ctx.problems.length) {
1712
+ const [first, ...rest] = ctx.problems;
1713
+ throw new CapnpError(`${first.message}${rest.length ? ` (and ${rest.length} more: ${rest.slice(0, 3).map((p) => p.message).join("; ")}${rest.length > 3 ? "; …" : ""})` : ""}`, { path: first.path, problems: ctx.problems });
1714
+ }
1715
+ const bytes = w.finish();
1716
+ return opts.packed ? pack(bytes) : bytes;
1717
+ }
1718
+
1719
+ // ── the packed encoding ──────────────────────────────────────────────────────
1720
+
1721
+ /** Packed bytes as the message they hold; at most `maxBytes` of it. */
1722
+ export function unpack(b, maxBytes = 1 << 24) {
1723
+ let out = new Uint8Array(Math.min(Math.max(b.length * 2, 64), maxBytes + 8));
1724
+ let o = 0;
1725
+ let i = 0;
1726
+ const room = (n) => {
1727
+ if (o + n > maxBytes) throw new CapnpError(`the packed message unpacks to more than ${maxBytes} bytes (the bytes limit)`, { offset: i, kind: "size" });
1728
+ if (o + n > out.length) {
1729
+ let size = out.length;
1730
+ while (size < o + n) size *= 2;
1731
+ const bigger = new Uint8Array(Math.min(size, maxBytes + 8));
1732
+ bigger.set(out.subarray(0, o));
1733
+ out = bigger;
1734
+ }
1735
+ };
1736
+ const ends = () => {
1737
+ throw new CapnpError(`the packed message ends inside a word (at byte ${b.length} of the packed bytes)`, { offset: b.length });
1738
+ };
1739
+ while (i < b.length) {
1740
+ const tag = b[i++];
1741
+ room(8);
1742
+ for (let bit = 0; bit < 8; bit++) {
1743
+ if (tag & (1 << bit)) {
1744
+ if (i >= b.length) ends();
1745
+ out[o++] = b[i++];
1746
+ } else out[o++] = 0;
1747
+ }
1748
+ if (tag === 0) {
1749
+ if (i >= b.length) ends();
1750
+ const n = b[i++] * 8;
1751
+ room(n);
1752
+ out.fill(0, o, o + n);
1753
+ o += n;
1754
+ } else if (tag === 0xff) {
1755
+ if (i >= b.length) ends();
1756
+ const n = b[i++] * 8;
1757
+ if (i + n > b.length) ends();
1758
+ room(n);
1759
+ out.set(b.subarray(i, i + n), o);
1760
+ o += n;
1761
+ i += n;
1762
+ }
1763
+ }
1764
+ return out.slice(0, o);
1765
+ }
1766
+
1767
+ /** A message (whole words) packed the way capnp's PackedOutputStream packs it. */
1768
+ export function pack(b) {
1769
+ const out = [];
1770
+ const words = b.length >>> 3;
1771
+ let w = 0;
1772
+ while (w < words) {
1773
+ const a = w * 8;
1774
+ let tag = 0;
1775
+ const kept = [];
1776
+ for (let k = 0; k < 8; k++) {
1777
+ if (b[a + k] !== 0) {
1778
+ tag |= 1 << k;
1779
+ kept.push(b[a + k]);
1780
+ }
1781
+ }
1782
+ out.push(tag, ...kept);
1783
+ w++;
1784
+ if (tag === 0) {
1785
+ let n = 0;
1786
+ while (w < words && n < 255 && b.subarray(w * 8, w * 8 + 8).every((x) => x === 0)) {
1787
+ n++;
1788
+ w++;
1789
+ }
1790
+ out.push(n);
1791
+ } else if (tag === 0xff) {
1792
+ const start = w;
1793
+ while (w < words && w - start < 255) {
1794
+ let zeros = 0;
1795
+ for (let k = 0; k < 8; k++) if (b[w * 8 + k] === 0) zeros++;
1796
+ if (zeros >= 2) break;
1797
+ w++;
1798
+ }
1799
+ out.push(w - start);
1800
+ for (let k = start * 8; k < w * 8; k++) out.push(b[k]);
1801
+ }
1802
+ }
1803
+ return Uint8Array.from(out);
1804
+ }