@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,2043 @@
1
+ // The codec engine: MessagePack, CBOR, Protocol Buffers (a .proto read at run time, no code generation), FlatBuffers (a .fbs compiled by flatc, the
2
+ // schema compiler itself, running as WebAssembly), Cap'n Proto (a .capnp read and laid out at run time by src/codec/capnp.js), Avro (a JSON schema,
3
+ // read by avsc) and custom binary structs (a layout like "u8 id, u16le len, f32le x[3]", the `bytes` helper's struct), with
4
+ // the bounds that make hostile bytes harmless. One self-contained module: it has no imports, because the sandbox
5
+ // Worker loads it as a virtual module (mallory:codec/core; virtual modules can't import each other), and the page,
6
+ // the headless runner and the tests import it as a plain file. The libraries (src/codec/vendor/*.js) are
7
+ // handed in through `load(name)` (the struct format loads the `bytes` helper): the Worker loads them lazily, only for a canvas that has a codec pane.
8
+ //
9
+ // A codec is plain data, the pane's `codec` setting:
10
+ // { format: "msgpack" | "cbor" | "protobuf" | "flatbuffers" | "capnp" | "avro" | "struct", schema?: ".proto, .fbs or .capnp text", the Avro schema as JSON text, or the struct layout,
11
+ // type?: "pkg.Message" (a message, a FlatBuffers root table, a Cap'n Proto struct, or a named Avro type; the whole Avro schema when left out), binary?: "bytes" | "hex" | "base64",
12
+ // packed?: true (Cap'n Proto's packed encoding), limits?: { bytes?, depth?, items?, ms? } }
13
+ //
14
+ // BOUNDS (src/codec/core.js DEFAULT_LIMITS, MAX_LIMITS): a message is at most `bytes` long, nests at most `depth` deep and holds
15
+ // at most `items` values (list entries, map entries, fields), and one decode or encode may take at most `ms`. MessagePack and
16
+ // CBOR are checked by a scan of the bytes themselves before a library sees them (a header that claims more entries than the
17
+ // message has bytes for, a nesting a million deep, trailing bytes, a truncated message are refused there); Protocol Buffers are
18
+ // checked on the decoded value, and so are FlatBuffers (flatc verifies a buffer against its schema first, and the module's memory is
19
+ // capped, which ends a buffer that prints as far more than it holds); Cap'n Proto is read by src/codec/capnp.js, which checks every pointer against its
20
+ // segment and counts the words it reads (a pointer can point at the same data again and again); Avro is read by this file's own bounded reader (an array of nulls takes no bytes, so a library
21
+ // could be told to loop for ever), and a struct has a fixed size. A library call cannot be interrupted from inside the thread, so the time cap is checked
22
+ // between the steps and after the call: the bounds above keep each step linear in the message, and the sandbox's own timeout is
23
+ // the backstop.
24
+ //
25
+ // Decoded values are plain data: numbers, strings, booleans, null, lists and objects. A 64-bit integer is a number when it is a
26
+ // safe integer and a decimal string when it is not; a Date is an ISO string; a map is an object; binary data is a Uint8Array
27
+ // (or hex or base64 text, `binary`). Pure and deterministic: no clock but the injected `now`, no random.
28
+
29
+ export const FORMATS = ["msgpack", "cbor", "protobuf", "flatbuffers", "capnp", "avro", "struct"];
30
+ export const FORMAT_LABELS = { msgpack: "MessagePack", cbor: "CBOR", protobuf: "Protocol Buffers", flatbuffers: "FlatBuffers", capnp: "Cap'n Proto", avro: "Avro", struct: "binary struct" };
31
+ /** The formats that have a schema (text), and what that text is called. */
32
+ export const SCHEMA_FORMATS = ["protobuf", "flatbuffers", "capnp", "avro", "struct"];
33
+ export const SCHEMA_WORDS = { protobuf: ".proto", flatbuffers: ".fbs", capnp: ".capnp", avro: "JSON schema", struct: "struct layout" };
34
+ /** What a format calls the type a codec reads and writes (codec.type). */
35
+ export const TYPE_WORDS = { protobuf: "message", flatbuffers: "root table", capnp: "struct", avro: "type" };
36
+ export const BINARY_MODES = ["bytes", "hex", "base64"];
37
+ export const DEFAULT_LIMITS = Object.freeze({ bytes: 1048576, depth: 32, items: 100000, ms: 2000 });
38
+ export const MAX_LIMITS = Object.freeze({ bytes: 16777216, depth: 64, items: 1000000, ms: 10000 });
39
+ export const MAX_SCHEMA_CHARS = 65536;
40
+ export const MAX_TYPES = 500;
41
+ export const MAX_FIELDS = 1000;
42
+ const MAX_ERRORS = 20;
43
+
44
+ export const SAMPLE_PROTO = `syntax = "proto3";
45
+
46
+ // A sensor reading: edit the schema, then pick the message type.
47
+ message Reading {
48
+ string sensor = 1;
49
+ float celsius = 2;
50
+ uint32 seconds = 3;
51
+ }
52
+ `;
53
+
54
+ export const SAMPLE_AVRO = `{
55
+ "type": "record",
56
+ "name": "Reading",
57
+ "fields": [
58
+ { "name": "sensor", "type": "string" },
59
+ { "name": "celsius", "type": "float" },
60
+ { "name": "seconds", "type": "long" },
61
+ { "name": "note", "type": ["null", "string"], "default": null }
62
+ ]
63
+ }
64
+ `;
65
+
66
+ export const SAMPLE_FBS = `// A sensor reading: edit the schema, then pick the root table.
67
+ table Reading {
68
+ sensor:string;
69
+ celsius:float;
70
+ seconds:uint;
71
+ }
72
+
73
+ root_type Reading;
74
+ `;
75
+
76
+ export const SAMPLE_CAPNP = `@0xb5a0c2c4f1e3d7a9;
77
+
78
+ # A sensor reading: edit the schema, then pick the struct.
79
+ struct Reading {
80
+ sensor @0 :Text;
81
+ celsius @1 :Float32;
82
+ seconds @2 :UInt32;
83
+ }
84
+ `;
85
+
86
+ export const SAMPLE_STRUCT = `// One field per line or comma-separated: a type and a name, like u16le len or f32le x[3].
87
+ // Types: u8 i8, u16 i16 u32 i32 u64 i64 f32 f64 (the ones over a byte end in le or be). No padding.
88
+ u8 id
89
+ u16le len
90
+ f32le x[3]
91
+ `;
92
+
93
+ /** The sample schema a format starts with. */
94
+ export const SAMPLE_SCHEMAS = { protobuf: SAMPLE_PROTO, flatbuffers: SAMPLE_FBS, capnp: SAMPLE_CAPNP, avro: SAMPLE_AVRO, struct: SAMPLE_STRUCT };
95
+
96
+ /** A new pane's setting: Protocol Buffers with a small schema, which decodes a framed sensor reading. */
97
+ export const DEFAULT_CODEC = Object.freeze({ format: "protobuf", schema: SAMPLE_PROTO, type: "Reading" });
98
+
99
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
100
+ const isInt = (v) => Number.isInteger(v);
101
+
102
+ /** An error with the details a pane shows: `errors` is [{ line?, message }] for a schema, `path` names the field of a value, `offset` the byte a decode stopped at. */
103
+ export class CodecError extends Error {
104
+ constructor(message, { errors, path, offset } = {}) {
105
+ super(message);
106
+ this.name = "CodecError";
107
+ if (errors) this.errors = errors;
108
+ if (path !== undefined) this.path = path;
109
+ if (offset !== undefined) this.offset = offset;
110
+ }
111
+ }
112
+
113
+ // ── the setting ──────────────────────────────────────────────────────────────
114
+
115
+ /** The limits with defaults filled in. */
116
+ export function limitsOf(codec) {
117
+ const l = codec?.limits ?? {};
118
+ return { bytes: l.bytes ?? DEFAULT_LIMITS.bytes, depth: l.depth ?? DEFAULT_LIMITS.depth, items: l.items ?? DEFAULT_LIMITS.items, ms: l.ms ?? DEFAULT_LIMITS.ms };
119
+ }
120
+
121
+ /** Why `codec` isn't a valid codec setting (a sentence), or "". */
122
+ export function codecProblem(codec) {
123
+ if (!isObject(codec)) return "codec is an object { format, schema?, type?, binary?, packed?, limits? }";
124
+ const extra = Object.keys(codec).find((k) => !["format", "schema", "type", "binary", "packed", "limits"].includes(k));
125
+ if (extra) return `"${extra}" isn't a field of codec (format, schema, type, binary, packed, limits)`;
126
+ if (!FORMATS.includes(codec.format)) return `format is ${FORMATS.join(", ")}`;
127
+ if (codec.schema !== undefined) {
128
+ if (typeof codec.schema !== "string") return "schema is text (a .proto, .fbs or .capnp file, an Avro JSON schema or a struct layout)";
129
+ if (codec.schema.length > MAX_SCHEMA_CHARS) return `a schema is at most ${MAX_SCHEMA_CHARS} characters (this one is ${codec.schema.length})`;
130
+ }
131
+ if (codec.type !== undefined && (typeof codec.type !== "string" || codec.type.length > 200 || !/^[A-Za-z_][\w.]*$/.test(codec.type) && codec.type !== "")) return "type is the name of a message in the schema (like Reading or pkg.Reading)";
132
+ if (codec.binary !== undefined && !BINARY_MODES.includes(codec.binary)) return `binary is ${BINARY_MODES.join(", ")}`;
133
+ if (codec.packed !== undefined && typeof codec.packed !== "boolean") return "packed is true or false (Cap'n Proto's packed encoding)";
134
+ if (codec.limits !== undefined) {
135
+ if (!isObject(codec.limits)) return "limits is an object { bytes, depth, items, ms }";
136
+ for (const [k, v] of Object.entries(codec.limits)) {
137
+ if (!(k in MAX_LIMITS)) return `"${k}" isn't a limit (bytes, depth, items, ms)`;
138
+ if (!isInt(v) || v < 1 || v > MAX_LIMITS[k]) return `limits.${k} is a whole number from 1 to ${MAX_LIMITS[k]}`;
139
+ }
140
+ }
141
+ return "";
142
+ }
143
+
144
+ /** The setting as a pane keeps it: known fields only, empty ones left out. */
145
+ export function cleanCodec(codec) {
146
+ if (codecProblem(codec)) return structuredClone(DEFAULT_CODEC);
147
+ // The schema and message stay when the format changes to one that has none, so switching back finds them.
148
+ const out = { format: codec.format };
149
+ if (SCHEMA_FORMATS.includes(codec.format) || codec.schema) out.schema = codec.schema ?? "";
150
+ if (codec.type) out.type = codec.type;
151
+ if (codec.binary && codec.binary !== "bytes") out.binary = codec.binary;
152
+ if (codec.packed === true) out.packed = true; // kept when the format changes, like the schema: only Cap'n Proto reads it
153
+ if (codec.limits && Object.keys(codec.limits).length) out.limits = { ...codec.limits };
154
+ return out;
155
+ }
156
+
157
+ /** The settings a state change has to restart on: what the codec means, hashed by the caller. */
158
+ export const codecPrint = (codec) => JSON.stringify([codec?.format, codec?.schema, codec?.type, codec?.binary, codec?.limits, codec?.packed === true]);
159
+
160
+ /** A short sentence of what a codec does, for the add menu's results, a markdown export and a status line. */
161
+ export function describeCodec(codec) {
162
+ const label = FORMAT_LABELS[codec?.format] ?? "a codec";
163
+ const packed = codec?.format === "capnp" && codec.packed === true ? ", packed" : "";
164
+ return SCHEMA_FORMATS.includes(codec?.format) && codec.format !== "struct" ? `${label}${codec.type ? `, ${TYPE_WORDS[codec.format]} ${codec.type}` : ""}${packed}` : label;
165
+ }
166
+
167
+ // ── bytes in ─────────────────────────────────────────────────────────────────
168
+
169
+ /**
170
+ * Bytes from what pane code passes: a Uint8Array, another typed array or a DataView, an ArrayBuffer, a list of numbers 0 to 255,
171
+ * or a serial packet's `{ bytes: [...] }`. Anything else is a CodecError that says what to pass.
172
+ */
173
+ export function toBytes(input) {
174
+ if (input instanceof Uint8Array) return input;
175
+ if (ArrayBuffer.isView(input)) return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
176
+ if (input instanceof ArrayBuffer) return new Uint8Array(input);
177
+ if (isObject(input) && input.bytes !== undefined && !(input instanceof Map)) return toBytes(input.bytes);
178
+ if (Array.isArray(input)) {
179
+ for (let i = 0; i < input.length; i++) if (!isInt(input[i]) || input[i] < 0 || input[i] > 255) throw new CodecError(`bytes: entry ${i} isn't a byte (a whole number from 0 to 255)`);
180
+ return Uint8Array.from(input);
181
+ }
182
+ if (typeof input === "string") throw new CodecError("bytes: pass a Uint8Array, an ArrayBuffer or a list of numbers, not text (bytes.fromHex(text) or bytes.fromBase64(text) makes bytes from text)");
183
+ throw new CodecError(`bytes: pass a Uint8Array, an ArrayBuffer or a list of numbers (got ${input === null ? "null" : typeof input})`);
184
+ }
185
+
186
+ const hexOf = (b) => {
187
+ let s = "";
188
+ for (let i = 0; i < b.length; i++) s += (b[i] < 16 ? "0" : "") + b[i].toString(16);
189
+ return s;
190
+ };
191
+ const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
192
+ function base64Of(b) {
193
+ let s = "";
194
+ for (let i = 0; i < b.length; i += 3) {
195
+ const n = (b[i] << 16) | ((b[i + 1] ?? 0) << 8) | (b[i + 2] ?? 0);
196
+ s += B64[(n >> 18) & 63] + B64[(n >> 12) & 63] + (i + 1 < b.length ? B64[(n >> 6) & 63] : "=") + (i + 2 < b.length ? B64[n & 63] : "=");
197
+ }
198
+ return s;
199
+ }
200
+ function fromBase64(text) {
201
+ const t = text.replace(/\s+/g, "");
202
+ if (!/^[A-Za-z0-9+/_-]*={0,2}$/.test(t)) return null;
203
+ const clean = t.replace(/-/g, "+").replace(/_/g, "/").replace(/=+$/, "");
204
+ if (clean.length % 4 === 1) return null;
205
+ const out = new Uint8Array(Math.floor((clean.length * 3) / 4));
206
+ let o = 0;
207
+ for (let i = 0; i < clean.length; i += 4) {
208
+ const n = (B64.indexOf(clean[i]) << 18) | (B64.indexOf(clean[i + 1]) << 12) | ((B64.indexOf(clean[i + 2] ?? "A")) << 6) | B64.indexOf(clean[i + 3] ?? "A");
209
+ out[o++] = (n >> 16) & 255;
210
+ if (i + 2 < clean.length) out[o++] = (n >> 8) & 255;
211
+ if (i + 3 < clean.length) out[o++] = n & 255;
212
+ }
213
+ return out;
214
+ }
215
+ function fromHex(text) {
216
+ const t = text.replace(/[\s:]+/g, "").replace(/^0x/i, "");
217
+ if (t.length % 2 || /[^0-9a-f]/i.test(t)) return null;
218
+ const out = new Uint8Array(t.length / 2);
219
+ for (let i = 0; i < out.length; i++) out[i] = parseInt(t.slice(i * 2, i * 2 + 2), 16);
220
+ return out;
221
+ }
222
+
223
+ // ── the budget one decode or encode runs on ──────────────────────────────────
224
+
225
+ function budget(limits, now) {
226
+ const start = now();
227
+ let steps = 0;
228
+ return {
229
+ limits,
230
+ elapsed: () => now() - start,
231
+ /** Called as work goes on: cheap, and checks the clock every 512 steps. */
232
+ tick() {
233
+ if ((++steps & 511) === 0) this.check();
234
+ },
235
+ check() {
236
+ const ms = now() - start;
237
+ if (ms > limits.ms) throw new CodecError(`took longer than the ${limits.ms} ms limit`);
238
+ },
239
+ };
240
+ }
241
+
242
+ // ── scanning MessagePack and CBOR before a library sees them ─────────────────
243
+
244
+ const tooDeep = (limits) => new CodecError(`the message nests deeper than ${limits.depth} levels (the depth limit)`);
245
+ const tooMany = (limits) => new CodecError(`the message has more than ${limits.items} values (the items limit)`);
246
+ const truncated = (at) => new CodecError(`the message ends early (at byte ${at})`);
247
+
248
+ /** MessagePack: the number of bytes each type byte's header takes beyond itself, the length field's size, and what follows. */
249
+ function scanMsgpack(b, limits, bud) {
250
+ let i = 0;
251
+ const need = (n) => {
252
+ if (i + n > b.length) throw truncated(b.length);
253
+ };
254
+ const uint = (n) => {
255
+ need(n);
256
+ let v = 0;
257
+ for (let k = 0; k < n; k++) v = v * 256 + b[i + k];
258
+ i += n;
259
+ return v;
260
+ };
261
+ const stack = []; // values still to read in each open array or map
262
+ let depth = 0;
263
+ let items = 0;
264
+ let pending = 1;
265
+ for (;;) {
266
+ while (pending === 0 && stack.length) {
267
+ pending = stack.pop();
268
+ depth--;
269
+ }
270
+ if (pending === 0) break;
271
+ pending--;
272
+ need(1);
273
+ if (++items > limits.items) throw tooMany(limits);
274
+ bud.tick();
275
+ const t = b[i++];
276
+ let skip = 0;
277
+ let children = 0;
278
+ if (t <= 0x7f || t >= 0xe0) skip = 0;
279
+ else if (t <= 0x8f) children = (t & 15) * 2;
280
+ else if (t <= 0x9f) children = t & 15;
281
+ else if (t <= 0xbf) skip = t & 31;
282
+ else
283
+ switch (t) {
284
+ case 0xc0: case 0xc2: case 0xc3: break;
285
+ case 0xc1: throw new CodecError(`byte ${i - 1} is 0xc1, which MessagePack never uses`);
286
+ case 0xc4: case 0xd9: skip = uint(1); break;
287
+ case 0xc5: case 0xda: skip = uint(2); break;
288
+ case 0xc6: case 0xdb: skip = uint(4); break;
289
+ case 0xc7: skip = uint(1) + 1; break;
290
+ case 0xc8: skip = uint(2) + 1; break;
291
+ case 0xc9: skip = uint(4) + 1; break;
292
+ case 0xca: skip = 4; break;
293
+ case 0xcb: skip = 8; break;
294
+ case 0xcc: case 0xd0: skip = 1; break;
295
+ case 0xcd: case 0xd1: skip = 2; break;
296
+ case 0xce: case 0xd2: skip = 4; break;
297
+ case 0xcf: case 0xd3: skip = 8; break;
298
+ case 0xd4: skip = 2; break;
299
+ case 0xd5: skip = 3; break;
300
+ case 0xd6: skip = 5; break;
301
+ case 0xd7: skip = 9; break;
302
+ case 0xd8: skip = 17; break;
303
+ case 0xdc: children = uint(2); break;
304
+ case 0xdd: children = uint(4); break;
305
+ case 0xde: children = uint(2) * 2; break;
306
+ default: children = uint(4) * 2; // 0xdf
307
+ }
308
+ if (skip) {
309
+ need(skip);
310
+ i += skip;
311
+ }
312
+ if (children) {
313
+ // Every entry takes at least a byte: a header that claims more than the rest of the message can hold is hostile.
314
+ if (children > b.length - i) throw truncated(b.length);
315
+ if (++depth > limits.depth) throw tooDeep(limits);
316
+ stack.push(pending);
317
+ pending = children;
318
+ }
319
+ }
320
+ if (i !== b.length) throw new CodecError(`${b.length - i} bytes follow the message (a stream of messages: frame it first)`);
321
+ return { items };
322
+ }
323
+
324
+ /** CBOR (RFC 8949), including indefinite lengths and tags. */
325
+ function scanCbor(b, limits, bud) {
326
+ let i = 0;
327
+ const need = (n) => {
328
+ if (i + n > b.length) throw truncated(b.length);
329
+ };
330
+ const arg = (info) => {
331
+ if (info < 24) return info;
332
+ const n = info === 24 ? 1 : info === 25 ? 2 : info === 26 ? 4 : info === 27 ? 8 : 0;
333
+ if (!n) throw new CodecError(`byte ${i - 1} has the reserved additional information ${info}`);
334
+ need(n);
335
+ let v = 0;
336
+ for (let k = 0; k < n; k++) v = v * 256 + b[i + k];
337
+ i += n;
338
+ return v;
339
+ };
340
+ const stack = []; // { left, indefinite, kind }
341
+ let top = { left: 1, indefinite: false, kind: "top" };
342
+ let depth = 0;
343
+ let items = 0;
344
+ for (;;) {
345
+ while (!top.indefinite && top.left === 0 && stack.length) {
346
+ top = stack.pop();
347
+ depth--;
348
+ }
349
+ if (!top.indefinite && top.left === 0) break;
350
+ need(1);
351
+ const t = b[i++];
352
+ const major = t >> 5;
353
+ const info = t & 31;
354
+ if (t === 0xff) {
355
+ if (!top.indefinite) throw new CodecError(`byte ${i - 1} is a "break" outside an indefinite-length value`);
356
+ top = stack.pop();
357
+ depth--;
358
+ continue;
359
+ }
360
+ if (++items > limits.items) throw tooMany(limits);
361
+ bud.tick();
362
+ if (!top.indefinite) top.left--;
363
+ else if (top.kind === "string" && major !== top.major) throw new CodecError(`byte ${i - 1}: a chunk of an indefinite-length string must be a string of the same kind`);
364
+ if (major === 0 || major === 1) {
365
+ arg(info);
366
+ } else if (major === 2 || major === 3) {
367
+ if (info === 31) {
368
+ if (++depth > limits.depth) throw tooDeep(limits);
369
+ stack.push(top);
370
+ top = { left: 0, indefinite: true, kind: "string", major };
371
+ } else {
372
+ const n = arg(info);
373
+ need(n);
374
+ i += n;
375
+ }
376
+ } else if (major === 4 || major === 5) {
377
+ const mult = major === 5 ? 2 : 1;
378
+ if (info === 31) {
379
+ if (major === 5) throw new CodecError("indefinite-length maps aren't supported here (use a definite-length map)");
380
+ if (++depth > limits.depth) throw tooDeep(limits);
381
+ stack.push(top);
382
+ top = { left: 0, indefinite: true, kind: "array" };
383
+ } else {
384
+ const n = arg(info) * mult;
385
+ if (n > b.length - i) throw truncated(b.length);
386
+ if (n > 0) {
387
+ if (++depth > limits.depth) throw tooDeep(limits);
388
+ stack.push(top);
389
+ top = { left: n, indefinite: false, kind: "array" };
390
+ }
391
+ }
392
+ } else if (major === 6) {
393
+ arg(info);
394
+ if (++depth > limits.depth) throw tooDeep(limits);
395
+ stack.push(top);
396
+ top = { left: 1, indefinite: false, kind: "tag" };
397
+ } else if (info < 24) {
398
+ /* a simple value */
399
+ } else if (info === 24) {
400
+ need(1);
401
+ i += 1;
402
+ } else if (info === 25) {
403
+ need(2);
404
+ i += 2;
405
+ } else if (info === 26) {
406
+ need(4);
407
+ i += 4;
408
+ } else if (info === 27) {
409
+ need(8);
410
+ i += 8;
411
+ } else {
412
+ throw new CodecError(`byte ${i - 1} is not a CBOR value`);
413
+ }
414
+ }
415
+ if (i !== b.length) throw new CodecError(`${b.length - i} bytes follow the message (a sequence of messages: frame it first)`);
416
+ return { items };
417
+ }
418
+
419
+ /** Check the bytes of a MessagePack or CBOR message against the limits. Returns { items }, or throws a CodecError. */
420
+ export function scan(format, bytes, limits = DEFAULT_LIMITS, now = defaultNow) {
421
+ if (bytes.length === 0) throw new CodecError("the message is empty");
422
+ const bud = budget({ ...DEFAULT_LIMITS, ...limits }, now);
423
+ return format === "cbor" ? scanCbor(bytes, bud.limits, bud) : scanMsgpack(bytes, bud.limits, bud);
424
+ }
425
+
426
+ function defaultNow() {
427
+ return globalThis.performance?.now?.() ?? Date.now();
428
+ }
429
+
430
+ // ── decoded values as plain data ─────────────────────────────────────────────
431
+
432
+ const proto = Object.prototype;
433
+ function setKey(out, key, value) {
434
+ if (key === "__proto__") Object.defineProperty(out, key, { value, enumerable: true, writable: true, configurable: true });
435
+ else out[key] = value;
436
+ }
437
+ const binaryOf = (view, mode) => {
438
+ const u8 = new Uint8Array(view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength));
439
+ return mode === "hex" ? hexOf(u8) : mode === "base64" ? base64Of(u8) : u8;
440
+ };
441
+ const numberOrString = (n) => (n >= Number.MIN_SAFE_INTEGER && n <= Number.MAX_SAFE_INTEGER ? Number(n) : String(n));
442
+
443
+ /** A decoded value as plain data (see the top of this file), bounded by depth, items and time. */
444
+ function plain(value, spec, bud, depth = 0) {
445
+ bud.tick();
446
+ if (value === null || value === undefined) return null;
447
+ switch (typeof value) {
448
+ case "bigint":
449
+ return numberOrString(value);
450
+ case "number":
451
+ case "string":
452
+ case "boolean":
453
+ return value;
454
+ case "object":
455
+ break;
456
+ default:
457
+ return null;
458
+ }
459
+ if (depth > bud.limits.depth) throw tooDeep(bud.limits);
460
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value.toISOString();
461
+ if (ArrayBuffer.isView(value)) return binaryOf(value, spec.binary ?? "bytes");
462
+ if (value instanceof ArrayBuffer) return binaryOf(new Uint8Array(value), spec.binary ?? "bytes");
463
+ if (Array.isArray(value)) return value.map((v) => plain(v, spec, bud, depth + 1));
464
+ if (value instanceof Map) {
465
+ const out = {};
466
+ for (const [k, v] of value) setKey(out, String(k), plain(v, spec, bud, depth + 1));
467
+ return out;
468
+ }
469
+ // MessagePack's unknown extension types ({ type, data }) and CBOR's unknown tags ({ tag, value }).
470
+ if (typeof value.type === "number" && value.data instanceof Uint8Array && Object.keys(value).length === 2) return { ext: value.type, data: binaryOf(value.data, spec.binary ?? "bytes") };
471
+ if (typeof value.tag === "number" && "value" in value && value.constructor?.name === "Tag") return { tag: value.tag, value: plain(value.value, spec, bud, depth + 1) };
472
+ const out = {};
473
+ for (const k of Object.keys(value)) setKey(out, k, plain(value[k], spec, bud, depth + 1));
474
+ return out;
475
+ }
476
+
477
+ // ── checking a value before it is encoded ────────────────────────────────────
478
+
479
+ const step = (path, key) => (typeof key === "number" ? `${path}[${key}]` : path ? `${path}.${key}` : key);
480
+
481
+ /** Walk a value that is about to be encoded: refuse what can't be (a function, a symbol, a cycle) and count depth and items. */
482
+ function checkInput(value, bud, path = "value", depth = 0, seen = new Set()) {
483
+ bud.tick();
484
+ const t = typeof value;
485
+ if (value === null || value === undefined || t === "number" || t === "string" || t === "boolean" || t === "bigint") return;
486
+ if (t !== "object") throw new CodecError(`${path}: a ${t} can't be encoded`, { path });
487
+ if (depth > bud.limits.depth) throw new CodecError(`${path}: nests deeper than ${bud.limits.depth} levels (the depth limit)`, { path });
488
+ if (value instanceof Date || ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return;
489
+ if (seen.has(value)) throw new CodecError(`${path}: refers back to a value that contains it`, { path });
490
+ seen.add(value);
491
+ bud.items = (bud.items ?? 0) + 1;
492
+ if (Array.isArray(value)) {
493
+ bud.items += value.length;
494
+ if (bud.items > bud.limits.items) throw tooMany(bud.limits);
495
+ for (let i = 0; i < value.length; i++) checkInput(value[i], bud, step(path, i), depth + 1, seen);
496
+ } else {
497
+ const keys = Object.keys(value);
498
+ bud.items += keys.length;
499
+ if (bud.items > bud.limits.items) throw tooMany(bud.limits);
500
+ for (const k of keys) checkInput(value[k], bud, step(path, k), depth + 1, seen);
501
+ }
502
+ seen.delete(value);
503
+ }
504
+
505
+ // ── Protocol Buffers: the schema ─────────────────────────────────────────────
506
+
507
+ // A sandbox module imports nothing, so this is its own copy of src/util/regexp.js escapeRegExp: a name from parsed code (a `$` in it) is text, not an anchor.
508
+ const escapeRegExp = (text) => String(text).replace(/[.*+?^${}()|[\]\\/-]/g, "\\$&");
509
+
510
+ const lineOfName = (lines, name, from = 0) => {
511
+ const word = new RegExp(`(^|[^\\w.])${escapeRegExp(name)}([^\\w]|$)`);
512
+ for (let i = from; i < lines.length; i++) if (word.test(lines[i])) return i + 1;
513
+ return 0;
514
+ };
515
+
516
+ /** The line of `field` in `message Type { … }` (1-based), the message's own line, or 0. */
517
+ export function lineOfField(lines, typeName, fieldName, typeKeyword = "message") {
518
+ const short = typeName.split(".").pop();
519
+ const startRe = new RegExp(`(?<![\\w$])${escapeRegExp(typeKeyword)}\\s+${escapeRegExp(short)}(?![\\w$])`);
520
+ const start = lines.findIndex((l) => startRe.test(l));
521
+ if (start < 0) return 0;
522
+ const fieldRe = fieldName ? new RegExp(`(?<![\\w$])${escapeRegExp(fieldName)}\\s*=`) : null;
523
+ let depth = 0;
524
+ for (let i = start; i < lines.length; i++) {
525
+ if (fieldRe && i > start && fieldRe.test(lines[i])) return i + 1;
526
+ for (const ch of lines[i].replace(/\/\/.*$/, "")) depth += ch === "{" ? 1 : ch === "}" ? -1 : 0;
527
+ if (i > start && depth <= 0) break;
528
+ }
529
+ return start + 1;
530
+ }
531
+
532
+ /** What protobufjs says when a field's type isn't declared, in a sentence. */
533
+ function unresolved(e) {
534
+ const m = /no such (?:type|Type or Enum)(?: or Enum)?:? '?([\w.]+)'?/i.exec(String(e?.message ?? e));
535
+ return m ? `the type ${m[1]} isn't declared in the schema` : String(e?.message ?? e);
536
+ }
537
+
538
+ /** A protobufjs parse or resolve error as `{ line?, message }`: it writes "… (line 3)" or none at all. */
539
+ function schemaError(error, lines) {
540
+ let message = String(error?.message ?? error);
541
+ let line = 0;
542
+ const m = / \(line (\d+)(?::(\d+))?\)\s*$/.exec(message);
543
+ if (m) {
544
+ line = Number(m[1]);
545
+ message = message.slice(0, m.index);
546
+ }
547
+ if (!line) {
548
+ const named = /(?:name|id|type|extend|service|method|field)[: ]+'?([\w.]+)'?/i.exec(message);
549
+ if (named) line = lineOfName(lines, named[1].split(".").pop());
550
+ }
551
+ return { ...(line ? { line } : {}), message };
552
+ }
553
+
554
+
555
+ /** Every message type under a namespace, in declaration order: [{ name, type }]. */
556
+ function messageTypes(ns, pb, out = []) {
557
+ for (const obj of ns.nestedArray ?? []) {
558
+ if (obj instanceof pb.Type) {
559
+ out.push({ name: obj.fullName.replace(/^\./, ""), type: obj });
560
+ messageTypes(obj, pb, out);
561
+ } else if (obj instanceof pb.Namespace) {
562
+ messageTypes(obj, pb, out);
563
+ }
564
+ }
565
+ return out;
566
+ }
567
+
568
+ /** Parse and resolve a .proto: `{ ok, errors, types, root, byName }` (root and byName only when ok). */
569
+ function compileProto(pb, schema) {
570
+ const lines = schema.split("\n");
571
+ const errors = [];
572
+ if (!schema.trim()) return { ok: false, errors: [{ line: 1, message: "the schema is empty: declare a message, like message Reading { string sensor = 1; }" }], types: [] };
573
+ let parsed;
574
+ try {
575
+ parsed = pb.parse(schema, new pb.Root(), { keepCase: true });
576
+ } catch (e) {
577
+ return { ok: false, errors: [schemaError(e, lines)], types: [] };
578
+ }
579
+ const root = parsed.root;
580
+ for (const imp of [...(parsed.imports ?? []), ...(parsed.weakImports ?? [])]) {
581
+ const common = pb.common?.[imp];
582
+ if (common?.nested) {
583
+ try {
584
+ root.addJSON(common.nested);
585
+ } catch {
586
+ /* declared twice: the schema defines it itself */
587
+ }
588
+ continue;
589
+ }
590
+ errors.push({ line: lineOfName(lines, imp) || lineOfName(lines, "import"), message: `import "${imp}" can't be loaded: a schema here is one piece of text, so put the messages it needs in this schema` });
591
+ }
592
+ const found = messageTypes(root, pb);
593
+ if (found.length > MAX_TYPES) errors.push({ message: `a schema has at most ${MAX_TYPES} message types (this one has ${found.length})` });
594
+ for (const { name, type } of found) {
595
+ for (const f of type.fieldsArray) {
596
+ try {
597
+ f.resolve();
598
+ } catch (e) {
599
+ const line = lineOfField(lines, name, f.name);
600
+ errors.push({ ...(line ? { line } : {}), message: `${name}.${f.name}: ${unresolved(e)}` });
601
+ }
602
+ }
603
+ }
604
+ if (errors.length) return { ok: false, errors: errors.slice(0, MAX_ERRORS), types: [] };
605
+ try {
606
+ root.resolveAll();
607
+ } catch (e) {
608
+ return { ok: false, errors: [schemaError(e, lines)], types: [] };
609
+ }
610
+ const types = found.map((f) => f.name);
611
+ if (!types.length) return { ok: false, errors: [{ line: 1, message: "the schema declares no message types" }], types: [] };
612
+ return { ok: true, errors: [], types, root, byName: new Map(found.map((f) => [f.name, f.type])) };
613
+ }
614
+
615
+ /** The message type a spec names, or the first one; a CodecError that lists the choices. */
616
+ function pickType(compiled, spec, requested) {
617
+ const name = (requested ?? spec.type ?? "").trim();
618
+ if (!name) return compiled.byName.get(compiled.types[0]);
619
+ const exact = compiled.byName.get(name);
620
+ if (exact) return exact;
621
+ const tail = compiled.types.filter((t) => t === name || t.endsWith(`.${name}`));
622
+ if (tail.length === 1) return compiled.byName.get(tail[0]);
623
+ throw new CodecError(tail.length > 1 ? `"${name}" names ${tail.length} messages (${tail.join(", ")}): use the full name` : `the schema has no message "${name}" (messages: ${compiled.types.join(", ")})`);
624
+ }
625
+
626
+ // ── Protocol Buffers: the wire format checked against the schema ────────────
627
+
628
+ const WIRE_WORDS = { 0: "varint", 1: "64-bit", 2: "length-delimited", 5: "32-bit" };
629
+ const VARINT_TYPES = new Set(["int32", "int64", "uint32", "uint64", "sint32", "sint64", "bool"]);
630
+ const FIXED64_TYPES = new Set(["fixed64", "sfixed64", "double"]);
631
+ const FIXED32_TYPES = new Set(["fixed32", "sfixed32", "float"]);
632
+
633
+ /** The wire type a protobufjs field's values have (an enum is a varint, a message, string or bytes length-delimited). */
634
+ function wireOfField(f) {
635
+ if (f.map) return 2;
636
+ if (f.resolvedType && f.resolvedType.values) return 0; // an enum
637
+ if (VARINT_TYPES.has(f.type)) return 0;
638
+ if (FIXED64_TYPES.has(f.type)) return 1;
639
+ if (FIXED32_TYPES.has(f.type)) return 5;
640
+ return 2;
641
+ }
642
+ const isPackable = (f) => !f.map && f.repeated && wireOfField(f) !== 2;
643
+ const typeWords = (f) => (f.map ? `map<${f.keyType}, ${f.type}>` : f.resolvedType && f.resolvedType.values ? `enum ${f.resolvedType.name}` : f.type);
644
+
645
+ /**
646
+ * Walk a Protocol Buffers message's wire format against message type `T` (a protobufjs Type; null reads every field as unknown)
647
+ * before protobufjs reads it: protobufjs doesn't check a field's wire type (a string sent as a 32-bit value reads as an empty
648
+ * string) and says "index out of range: 2 + 16 > 3" for a truncated length. Every error here names the field path
649
+ * (`points[1].x`, `named["a"].y`), its number and the byte its tag starts at, as `path` and `offset` on the CodecError.
650
+ * Unknown fields are skipped, as protobuf readers do. Bounded by `depth` and `items`. Returns { items }.
651
+ */
652
+ export function scanProto(T, b, limits = DEFAULT_LIMITS, now = defaultNow) {
653
+ const bud = budget({ ...DEFAULT_LIMITS, ...limits }, now);
654
+ const L = bud.limits;
655
+ let items = 0;
656
+ const fail = (message, path, offset) => {
657
+ throw new CodecError(`${path ? `${path} ` : ""}${message}`, { path, offset });
658
+ };
659
+ const at = (path, num, tagAt) => (path ? `(field ${num}) at byte ${tagAt}` : `at byte ${tagAt}`);
660
+ /** A varint at i (up to `end`): [value as a Number (exact up to 2^53), next i], or null when it runs past `end`. */
661
+ const varint = (i, end) => {
662
+ let v = 0;
663
+ let mul = 1;
664
+ for (let k = 0; k < 10; k++) {
665
+ if (i >= end) return null;
666
+ const c = b[i++];
667
+ v += (c & 127) * mul;
668
+ mul *= 128;
669
+ if (!(c & 128)) return [v, i];
670
+ }
671
+ return [-1, i]; // more than 10 bytes
672
+ };
673
+ const message = (type, start, end, path, depth) => {
674
+ if (depth > L.depth) throw tooDeep(L);
675
+ const counts = new Map(); // field number -> occurrences so far (a repeated field's index)
676
+ let i = start;
677
+ while (i < end) {
678
+ const tagAt = i;
679
+ const tag = varint(i, end);
680
+ if (!tag) fail(`at byte ${tagAt}: the message ends inside a field's tag`, "", tagAt);
681
+ if (tag[0] < 0) fail(`at byte ${tagAt}: a field's tag runs on for more than 10 bytes`, "", tagAt);
682
+ i = tag[1];
683
+ const num = Math.floor(tag[0] / 8);
684
+ const wire = tag[0] % 8;
685
+ if (num === 0) fail(`at byte ${tagAt}: field number 0 isn't allowed`, "", tagAt);
686
+ if (num > 536870911) fail(`at byte ${tagAt}: field number ${num} is over the largest (536870911)`, "", tagAt);
687
+ if (wire === 3 || wire === 4) fail(`at byte ${tagAt}: field ${num} is a group (wire type ${wire}), which proto3 and this reader don't support`, "", tagAt);
688
+ if (wire > 5) fail(`at byte ${tagAt}: wire type ${wire} isn't a Protocol Buffers wire type`, "", tagAt);
689
+ if (++items > L.items) throw tooMany(L);
690
+ bud.tick();
691
+ const f = type?.fieldsById?.[num] ?? null;
692
+ const n = counts.get(num) ?? 0;
693
+ counts.set(num, n + 1);
694
+ const base = f ? `${path}${path ? "." : ""}${f.name}` : "";
695
+ const where = f ? base : "";
696
+ if (f) {
697
+ const want = wireOfField(f);
698
+ if (wire !== want && !(wire === 2 && isPackable(f)))
699
+ fail(`${at(where, num, tagAt)}: wire type ${wire} (${WIRE_WORDS[wire]}), but ${f.name} is ${typeWords(f)}, which is wire type ${want} (${WIRE_WORDS[want]})`, where, tagAt);
700
+ }
701
+ if (wire === 0) {
702
+ const v = varint(i, end);
703
+ if (!v) fail(`${at(where, num, tagAt)}: the number runs past the end of its message`, where, tagAt);
704
+ if (v[0] < 0) fail(`${at(where, num, tagAt)}: a number runs on for more than 10 bytes`, where, tagAt);
705
+ i = v[1];
706
+ } else if (wire === 1 || wire === 5) {
707
+ const size = wire === 1 ? 8 : 4;
708
+ if (i + size > end) fail(`${at(where, num, tagAt)}: the message ends inside its ${size}-byte value`, where, tagAt);
709
+ i += size;
710
+ } else {
711
+ const len = varint(i, end);
712
+ if (!len) fail(`${at(where, num, tagAt)}: the message ends inside its length`, where, tagAt);
713
+ i = len[1];
714
+ const left = end - i;
715
+ if (len[0] < 0 || len[0] > left) fail(`${at(where, num, tagAt)}: a length of ${len[0] < 0 ? "more than 10 bytes" : len[0]} runs past the end of the message (${left} byte${left === 1 ? "" : "s"} left)`, where, tagAt);
716
+ const from = i;
717
+ i += len[0];
718
+ if (!f) continue;
719
+ if (f.map) {
720
+ // an entry: key = 1, value = 2
721
+ let key = `${n}`;
722
+ const k = varint(from, i);
723
+ const keyIsText = f.keyType === "string";
724
+ if (k && k[0] === (keyIsText ? 10 : 8)) {
725
+ const kv = varint(k[1], i);
726
+ if (kv && kv[0] >= 0) {
727
+ if (keyIsText && kv[1] + kv[0] <= i) key = JSON.stringify(new TextDecoder().decode(b.subarray(kv[1], kv[1] + kv[0])));
728
+ else if (!keyIsText) key = String(kv[0]);
729
+ }
730
+ }
731
+ const entryPath = `${base}[${key}]`;
732
+ const valueType = f.resolvedType && !f.resolvedType.values ? f.resolvedType : null;
733
+ const entryType = { fieldsById: { 1: { name: "key", type: f.keyType, map: false, repeated: false }, 2: { name: "value", type: f.type, resolvedType: f.resolvedType, map: false, repeated: false } } };
734
+ // the entry's own fields; the value, a message, is read with its type and the entry's path
735
+ scanEntry(entryType, valueType, from, i, entryPath, depth + 1);
736
+ } else if (f.resolvedType && !f.resolvedType.values) {
737
+ message(f.resolvedType, from, i, f.repeated ? `${base}[${n}]` : base, depth + 1);
738
+ }
739
+ }
740
+ }
741
+ if (i !== end) fail(`at byte ${end}: the message ends inside a field`, path, end);
742
+ };
743
+ const scanEntry = (entryType, valueType, start, end, path, depth) => {
744
+ if (depth > L.depth) throw tooDeep(L);
745
+ let i = start;
746
+ while (i < end) {
747
+ const tagAt = i;
748
+ const tag = varint(i, end);
749
+ if (!tag || tag[0] < 0) fail(`at byte ${tagAt}: the map entry ends inside a field's tag`, path, tagAt);
750
+ i = tag[1];
751
+ const num = Math.floor(tag[0] / 8);
752
+ const wire = tag[0] % 8;
753
+ if (++items > L.items) throw tooMany(L);
754
+ const f = entryType.fieldsById[num];
755
+ if (num === 2 && valueType) {
756
+ if (wire !== 2) fail(`(map value) at byte ${tagAt}: wire type ${wire} (${WIRE_WORDS[wire] ?? "unknown"}), but the value is ${valueType.name}, which is wire type 2 (length-delimited)`, path, tagAt);
757
+ const len = varint(i, end);
758
+ if (!len || len[0] < 0 || len[0] > end - len[1]) fail(`(map value) at byte ${tagAt}: a length runs past the end of the entry`, path, tagAt);
759
+ message(valueType, len[1], len[1] + len[0], path, depth + 1);
760
+ i = len[1] + len[0];
761
+ continue;
762
+ }
763
+ const want = f ? wireOfField(f) : wire;
764
+ if (f && wire !== want) fail(`(map ${f.name}) at byte ${tagAt}: wire type ${wire} (${WIRE_WORDS[wire] ?? "unknown"}), but the ${f.name} is ${f.type}, which is wire type ${want} (${WIRE_WORDS[want]})`, path, tagAt);
765
+ if (wire === 0) {
766
+ const v = varint(i, end);
767
+ if (!v || v[0] < 0) fail(`(map ${f?.name ?? num}) at byte ${tagAt}: the number runs past the end of the entry`, path, tagAt);
768
+ i = v[1];
769
+ } else if (wire === 1 || wire === 5) {
770
+ i += wire === 1 ? 8 : 4;
771
+ if (i > end) fail(`(map ${f?.name ?? num}) at byte ${tagAt}: the entry ends inside its value`, path, tagAt);
772
+ } else if (wire === 2) {
773
+ const len = varint(i, end);
774
+ if (!len || len[0] < 0 || len[0] > end - len[1]) fail(`(map ${f?.name ?? num}) at byte ${tagAt}: a length runs past the end of the entry`, path, tagAt);
775
+ i = len[1] + len[0];
776
+ } else fail(`(map entry) at byte ${tagAt}: wire type ${wire} isn't allowed here`, path, tagAt);
777
+ }
778
+ };
779
+ message(T, 0, b.length, "", 0);
780
+ return { items };
781
+ }
782
+
783
+ // ── Protocol Buffers: values ─────────────────────────────────────────────────
784
+
785
+ const INT32 = { int32: [-2147483648, 2147483647], sint32: [-2147483648, 2147483647], sfixed32: [-2147483648, 2147483647], uint32: [0, 4294967295], fixed32: [0, 4294967295] };
786
+ const INT64 = { int64: [-(2n ** 63n), 2n ** 63n - 1n], sint64: [-(2n ** 63n), 2n ** 63n - 1n], sfixed64: [-(2n ** 63n), 2n ** 63n - 1n], uint64: [0n, 2n ** 64n - 1n], fixed64: [0n, 2n ** 64n - 1n] };
787
+ const FLOATS = new Set(["float", "double"]);
788
+ const got = (v) => (v === null ? "null" : Array.isArray(v) ? "a list" : typeof v === "object" ? "an object" : typeof v === "string" ? `text ${JSON.stringify(v.length > 24 ? `${v.slice(0, 24)}…` : v)}` : String(v));
789
+
790
+ /** One scalar of a field's declared type, or an error string. Returns [ok, value]. */
791
+ function prepareScalar(type, value, spec) {
792
+ if (type in INT32) {
793
+ const [lo, hi] = INT32[type];
794
+ if (typeof value === "number" && isInt(value) && value >= lo && value <= hi) return [true, value];
795
+ return [false, `expected a whole number from ${lo} to ${hi} (${type}), got ${got(value)}`];
796
+ }
797
+ if (type in INT64) {
798
+ const [lo, hi] = INT64[type];
799
+ let n;
800
+ if (typeof value === "number" && isInt(value)) n = BigInt(value);
801
+ else if (typeof value === "bigint") n = value;
802
+ else if (typeof value === "string" && /^-?\d+$/.test(value)) n = BigInt(value);
803
+ if (n !== undefined && n >= lo && n <= hi) return [true, n.toString()];
804
+ return [false, `expected a whole number from ${lo} to ${hi} (${type}; larger ones as text), got ${got(value)}`];
805
+ }
806
+ if (FLOATS.has(type)) return typeof value === "number" ? [true, value] : [false, `expected a number (${type}), got ${got(value)}`];
807
+ if (type === "bool") return typeof value === "boolean" ? [true, value] : [false, `expected true or false, got ${got(value)}`];
808
+ if (type === "string") return typeof value === "string" ? [true, value] : [false, `expected text, got ${got(value)}`];
809
+ if (type === "bytes") {
810
+ if (value instanceof Uint8Array) return [true, value];
811
+ if (ArrayBuffer.isView(value)) return [true, new Uint8Array(value.buffer, value.byteOffset, value.byteLength)];
812
+ if (Array.isArray(value) && value.every((x) => isInt(x) && x >= 0 && x <= 255)) return [true, Uint8Array.from(value)];
813
+ if (typeof value === "string") {
814
+ const b = spec.binary === "hex" ? fromHex(value) : fromBase64(value);
815
+ if (b) return [true, b];
816
+ return [false, `expected ${spec.binary === "hex" ? "hex text" : "base64 text"} for bytes, got ${got(value)}`];
817
+ }
818
+ return [false, `expected bytes (a Uint8Array, a list of numbers 0 to 255, or ${spec.binary === "hex" ? "hex" : "base64"} text), got ${got(value)}`];
819
+ }
820
+ return [false, `has the unsupported type ${type}`];
821
+ }
822
+
823
+ /**
824
+ * A value for message `T` checked against its fields and turned into what protobufjs's fromObject takes: every problem is
825
+ * collected with the path of the field it is about (`readings[2].celsius`), up to MAX_ERRORS.
826
+ */
827
+ function prepareMessage(T, value, spec, bud, path, problems, depth = 0) {
828
+ bud.tick();
829
+ if (depth > bud.limits.depth) {
830
+ problems.push(`${path}: nests deeper than ${bud.limits.depth} levels (the depth limit)`);
831
+ return undefined;
832
+ }
833
+ if (!isObject(value) || ArrayBuffer.isView(value) || value instanceof Date) {
834
+ problems.push(`${path}: expected an object (${T.name}), got ${got(value)}`);
835
+ return undefined;
836
+ }
837
+ const out = {};
838
+ const fields = new Map(T.fieldsArray.map((f) => [f.name, f]));
839
+ const oneofs = new Map();
840
+ for (const key of Object.keys(value)) {
841
+ const f = fields.get(key);
842
+ const where = step(path, key);
843
+ if (!f) {
844
+ problems.push(`${where}: ${T.name} has no field "${key}" (fields: ${[...fields.keys()].join(", ") || "none"})`);
845
+ continue;
846
+ }
847
+ const v = value[key];
848
+ if (v === undefined || v === null) continue; // unset
849
+ if (f.partOf) {
850
+ const set = oneofs.get(f.partOf.name) ?? [];
851
+ set.push(key);
852
+ oneofs.set(f.partOf.name, set);
853
+ }
854
+ bud.items = (bud.items ?? 0) + 1;
855
+ if (bud.items > bud.limits.items) throw tooMany(bud.limits);
856
+ const one = (x, at) => prepareValue(f, f.map ? f.type : f.type, x, spec, bud, at, problems, depth);
857
+ if (f.map) {
858
+ if (!isObject(v) || ArrayBuffer.isView(v)) {
859
+ problems.push(`${where}: expected an object for the map<${f.keyType}, ${f.type}>, got ${got(v)}`);
860
+ continue;
861
+ }
862
+ const m = {};
863
+ for (const mk of Object.keys(v)) {
864
+ bud.items++;
865
+ if (bud.items > bud.limits.items) throw tooMany(bud.limits);
866
+ const [kok, kmsg] = mapKeyOk(f.keyType, mk);
867
+ if (!kok) problems.push(`${step(where, mk)}: map key ${kmsg}`);
868
+ const r = one(v[mk], step(where, mk));
869
+ if (r !== undefined) setKey(m, mk, r);
870
+ }
871
+ out[key] = m;
872
+ } else if (f.repeated) {
873
+ if (!Array.isArray(v)) {
874
+ problems.push(`${where}: expected a list (repeated ${f.type}), got ${got(v)}`);
875
+ continue;
876
+ }
877
+ bud.items += v.length;
878
+ if (bud.items > bud.limits.items) throw tooMany(bud.limits);
879
+ out[key] = v.map((x, i) => one(x, `${where}[${i}]`));
880
+ } else {
881
+ const r = one(v, where);
882
+ if (r !== undefined) out[key] = r;
883
+ }
884
+ }
885
+ for (const [name, set] of oneofs) if (set.length > 1) problems.push(`${path}: ${set.join(" and ")} are in the same oneof "${name}": set only one`);
886
+ return out;
887
+ }
888
+
889
+ function mapKeyOk(keyType, key) {
890
+ if (keyType === "string") return [true];
891
+ if (keyType === "bool") return key === "true" || key === "false" ? [true] : [false, `${JSON.stringify(key)} isn't true or false`];
892
+ return /^-?\d+$/.test(key) ? [true] : [false, `${JSON.stringify(key)} isn't a whole number`];
893
+ }
894
+
895
+ function prepareValue(f, typeName, value, spec, bud, path, problems, depth) {
896
+ const resolved = f.resolvedType;
897
+ if (resolved && resolved.values) {
898
+ // an enum: a value's name, or its number
899
+ if (typeof value === "string" && value in resolved.values) return value;
900
+ if (isInt(value) && Object.values(resolved.values).includes(value)) return value;
901
+ problems.push(`${path}: expected one of ${Object.keys(resolved.values).join(", ")} (enum ${resolved.name}), got ${got(value)}`);
902
+ return undefined;
903
+ }
904
+ if (resolved) return prepareMessage(resolved, value, spec, bud, path, problems, depth + 1);
905
+ const [ok, result] = prepareScalar(typeName, value, spec);
906
+ if (!ok) {
907
+ problems.push(`${path}: ${result}`);
908
+ return undefined;
909
+ }
910
+ return result;
911
+ }
912
+
913
+ /** Fix a decoded message's 64-bit integers (decimal strings from protobufjs) to numbers when they are safe. */
914
+ function fixLongs(T, obj) {
915
+ if (!obj || typeof obj !== "object") return;
916
+ for (const f of T.fieldsArray) {
917
+ const v = obj[f.name];
918
+ if (v === undefined || v === null) continue;
919
+ const long = f.type in INT64;
920
+ const sub = f.resolvedType && !f.resolvedType.values ? f.resolvedType : null;
921
+ if (!long && !sub) continue;
922
+ const fix = (x) => (long ? (typeof x === "string" ? numberOrString(BigInt(x)) : x) : (fixLongs(sub, x), x));
923
+ if (f.map) for (const k of Object.keys(v)) v[k] = fix(v[k]);
924
+ else if (f.repeated) for (let i = 0; i < v.length; i++) v[i] = fix(v[i]);
925
+ else obj[f.name] = fix(v);
926
+ }
927
+ }
928
+
929
+ // ── Avro: the schema ─────────────────────────────────────────────────────────
930
+
931
+ /** A JSON.parse error as `{ line?, message }`: V8 says where ("at position 12 (line 2 column 3)"). */
932
+ function jsonError(e, text) {
933
+ let message = String(e?.message ?? e);
934
+ let line = 0;
935
+ const lc = / ?\(line (\d+) column \d+\)/.exec(message);
936
+ if (lc) {
937
+ line = Number(lc[1]);
938
+ message = message.replace(lc[0], "");
939
+ } else {
940
+ const pos = /position (\d+)/.exec(message);
941
+ // Without a position V8 quotes the text around the character: find that text in the schema.
942
+ const around = /Unexpected token '(.)', (?:\.\.\.)?"([\s\S]*?)"(?:\.\.\.)? is not valid JSON/.exec(message);
943
+ const at = pos ? Number(pos[1]) : around && text.indexOf(around[2]) >= 0 ? text.indexOf(around[2]) + Math.max(0, around[2].indexOf(around[1])) : /Unexpected end of JSON/.test(message) ? text.length : -1;
944
+ if (at >= 0) line = (at === text.length ? text.trimEnd() : text.slice(0, at)).split("\n").length;
945
+ }
946
+ return { ...(line ? { line } : {}), message: `the schema isn't JSON: ${message}` };
947
+ }
948
+
949
+ /** The line of the first quoted name in `message` that the schema text writes, or 0. */
950
+ function lineOfQuoted(lines, message) {
951
+ const names = [...String(message).matchAll(/"([^"]{1,80})"/g)].map((m) => m[1]);
952
+ const tail = /: ([\w.]+)$/.exec(message);
953
+ if (tail) names.push(tail[1]);
954
+ for (const name of names) {
955
+ const i = lines.findIndex((l) => l.includes(`"${name}"`));
956
+ if (i >= 0) return i + 1;
957
+ }
958
+ return 0;
959
+ }
960
+
961
+ /** What kind of Avro type an avsc type is: null, boolean, int, long, float, double, bytes, string, record, enum, fixed, array, map or union. */
962
+ function avroKind(t) {
963
+ const n = t.typeName;
964
+ if (n.startsWith("logical:")) return avroKind(t.underlyingType);
965
+ if (n.startsWith("union")) return "union";
966
+ if (n === "abstract:long") return "long";
967
+ return n;
968
+ }
969
+ const AVRO_NAMED = new Set(["record", "enum", "fixed"]);
970
+
971
+ const INT64_MIN = -(2n ** 63n);
972
+ const INT64_MAX = 2n ** 63n - 1n;
973
+ /** A 64-bit integer from a value pane code passes: a BigInt, a safe integer or a decimal string. */
974
+ function longOf(v) {
975
+ let n;
976
+ if (typeof v === "bigint") n = v;
977
+ else if (typeof v === "number" && Number.isSafeInteger(v)) n = BigInt(v);
978
+ else if (typeof v === "string" && /^-?\d{1,20}$/.test(v)) n = BigInt(v);
979
+ return n !== undefined && n >= INT64_MIN && n <= INT64_MAX ? n : undefined;
980
+ }
981
+
982
+ /** Parse a JSON schema with avsc: `{ ok, errors, types, root, byName }` (root and byName only when ok). */
983
+ function compileAvro(library, schema) {
984
+ const avro = library.default;
985
+ const lines = schema.split("\n");
986
+ if (!schema.trim()) return { ok: false, errors: [{ line: 1, message: 'the schema is empty: write an Avro schema as JSON, like { "type": "record", "name": "Reading", "fields": [ … ] }' }], types: [] };
987
+ let parsed;
988
+ try {
989
+ parsed = JSON.parse(schema);
990
+ } catch (e) {
991
+ return { ok: false, errors: [jsonError(e, schema)], types: [] };
992
+ }
993
+ // A 64-bit `long` is a BigInt inside avsc, so a default past 2^53 isn't rounded (the reader and the writer below read and write the bytes themselves).
994
+ const long = avro.types.LongType.__with({
995
+ fromBuffer: (b) => b.readBigInt64LE(0),
996
+ toBuffer: (n) => {
997
+ const b = library.Buf.alloc(8);
998
+ b.writeBigInt64LE(n, 0);
999
+ return b;
1000
+ },
1001
+ fromJSON: (n) => BigInt(n),
1002
+ toJSON: (n) => Number(n),
1003
+ isValid: (n) => typeof n === "bigint",
1004
+ compare: (a, b) => (a < b ? -1 : a > b ? 1 : 0),
1005
+ });
1006
+ const registry = { long };
1007
+ let root;
1008
+ try {
1009
+ root = avro.Type.forSchema(parsed, { registry });
1010
+ } catch (e) {
1011
+ const message = e instanceof RangeError ? "the schema nests too deeply" : String(e?.message ?? e).replace(/\s+/g, " ").slice(0, 300);
1012
+ const line = lineOfQuoted(lines, message);
1013
+ return { ok: false, errors: [{ ...(line ? { line } : {}), message }], types: [] };
1014
+ }
1015
+ const found = Object.entries(registry).filter(([, t]) => t && typeof t.typeName === "string" && AVRO_NAMED.has(avroKind(t)) && t.name);
1016
+ if (found.length > MAX_TYPES) return { ok: false, errors: [{ message: `a schema has at most ${MAX_TYPES} named types (this one has ${found.length})` }], types: [] };
1017
+ return { ok: true, errors: [], types: found.map(([name]) => name), root, byName: new Map(found) };
1018
+ }
1019
+
1020
+ /** The Avro type a spec names, or the whole schema; a CodecError that lists the choices. */
1021
+ function pickAvroType(compiled, spec, requested) {
1022
+ const name = (requested ?? spec.type ?? "").trim();
1023
+ if (!name) return compiled.root;
1024
+ const exact = compiled.byName.get(name);
1025
+ if (exact) return exact;
1026
+ const tail = compiled.types.filter((t) => t.endsWith(`.${name}`));
1027
+ if (tail.length === 1) return compiled.byName.get(tail[0]);
1028
+ throw new CodecError(tail.length > 1 ? `"${name}" names ${tail.length} types (${tail.join(", ")}): use the full name` : `the schema has no named type "${name}"${compiled.types.length ? ` (types: ${compiled.types.join(", ")})` : ""}`);
1029
+ }
1030
+
1031
+ // ── Avro: bytes in ───────────────────────────────────────────────────────────
1032
+
1033
+ /**
1034
+ * A datum of Avro binary (no container file, no framing) read as plain data. The reader is this file's own, because a library
1035
+ * reads `{ "type": "array", "items": "null" }` with a count of two billion for ever (an item of null takes no bytes): every value
1036
+ * counts against the `items` limit, nesting against `depth`, and the clock is checked as it goes.
1037
+ */
1038
+ function readAvro(type, b, limits, bud, spec) {
1039
+ let i = 0;
1040
+ let items = 0;
1041
+ const trail = []; // the field path being read: names, [index] and ["key"]
1042
+ const pathText = () => trail.reduce((s, p) => (typeof p === "string" ? `${s}${s ? "." : ""}${p}` : `${s}[${p.key ?? p.index}]`), "");
1043
+ const fail = (message, at = i) => {
1044
+ const path = pathText();
1045
+ throw new CodecError(`not Avro for this schema: ${path ? `${path}: ` : ""}${message} (at byte ${at})`, { ...(path ? { path } : {}), offset: at });
1046
+ };
1047
+ const byte = () => {
1048
+ if (i >= b.length) throw truncated(b.length);
1049
+ return b[i++];
1050
+ };
1051
+ const varint = () => {
1052
+ let n = 0n;
1053
+ for (let shift = 0n, k = 0; k < 10; k++, shift += 7n) {
1054
+ const c = byte();
1055
+ n |= BigInt(c & 127) << shift;
1056
+ if (!(c & 128)) return (n >> 1n) ^ -(n & 1n);
1057
+ }
1058
+ return fail("a number runs on for more than 10 bytes");
1059
+ };
1060
+ const length = () => {
1061
+ const n = varint();
1062
+ if (n < 0n || n > BigInt(b.length - i)) return fail(n < 0n ? "a length is negative" : `a length of ${n} runs past the end of the message`);
1063
+ return Number(n);
1064
+ };
1065
+ const utf8 = (n, what) => {
1066
+ i += n;
1067
+ try {
1068
+ return new TextDecoder("utf-8", { fatal: true }).decode(b.subarray(i - n, i));
1069
+ } catch {
1070
+ return fail(`${what} isn't UTF-8 text`);
1071
+ }
1072
+ };
1073
+ const view = new DataView(b.buffer, b.byteOffset, b.byteLength);
1074
+ const blocks = (each) => {
1075
+ for (;;) {
1076
+ let count = varint();
1077
+ if (count === 0n) return;
1078
+ if (count < 0n) {
1079
+ count = -count;
1080
+ varint(); // the block's size in bytes: the items are read one by one, so it isn't needed
1081
+ }
1082
+ if (count > BigInt(limits.items)) throw tooMany(limits);
1083
+ for (let k = 0n; k < count; k++) each();
1084
+ }
1085
+ };
1086
+ const read = (t, depth) => {
1087
+ if (depth > limits.depth) throw tooDeep(limits);
1088
+ if (++items > limits.items) throw tooMany(limits);
1089
+ bud.tick();
1090
+ switch (avroKind(t)) {
1091
+ case "null":
1092
+ return null;
1093
+ case "boolean": {
1094
+ const c = byte();
1095
+ if (c > 1) return fail(`a boolean is 0 or 1, not ${c}`, i - 1);
1096
+ return c === 1;
1097
+ }
1098
+ case "int": {
1099
+ const at = i;
1100
+ const n = varint();
1101
+ if (n < -2147483648n || n > 2147483647n) return fail(`${n} is outside int`, at);
1102
+ return Number(n);
1103
+ }
1104
+ case "long": {
1105
+ const at = i;
1106
+ const n = varint();
1107
+ if (n < INT64_MIN || n > INT64_MAX) return fail(`${n} is outside long`, at);
1108
+ return numberOrString(n);
1109
+ }
1110
+ case "float":
1111
+ case "double": {
1112
+ const size = t.typeName === "float" ? 4 : 8;
1113
+ if (i + size > b.length) throw truncated(b.length);
1114
+ const v = size === 4 ? view.getFloat32(i, true) : view.getFloat64(i, true);
1115
+ i += size;
1116
+ return v;
1117
+ }
1118
+ case "bytes": {
1119
+ const n = length();
1120
+ i += n;
1121
+ return binaryOf(b.subarray(i - n, i), spec.binary ?? "bytes");
1122
+ }
1123
+ case "fixed": {
1124
+ if (i + t.size > b.length) throw truncated(b.length);
1125
+ i += t.size;
1126
+ return binaryOf(b.subarray(i - t.size, i), spec.binary ?? "bytes");
1127
+ }
1128
+ case "string":
1129
+ return utf8(length(), "a string");
1130
+ case "enum": {
1131
+ const at = i;
1132
+ const n = varint();
1133
+ if (n < 0n || n >= BigInt(t.symbols.length)) return fail(`${n} isn't a symbol of enum ${t.name} (0 to ${t.symbols.length - 1})`, at);
1134
+ return t.symbols[Number(n)];
1135
+ }
1136
+ case "array": {
1137
+ const out = [];
1138
+ blocks(() => {
1139
+ trail.push({ index: out.length });
1140
+ out.push(read(t.itemsType, depth + 1));
1141
+ trail.pop();
1142
+ });
1143
+ return out;
1144
+ }
1145
+ case "map": {
1146
+ const out = {};
1147
+ blocks(() => {
1148
+ const key = utf8(length(), "a map key");
1149
+ trail.push({ key: JSON.stringify(key) });
1150
+ setKey(out, key, read(t.valuesType, depth + 1));
1151
+ trail.pop();
1152
+ });
1153
+ return out;
1154
+ }
1155
+ case "record": {
1156
+ const out = {};
1157
+ for (const f of t.fields) {
1158
+ trail.push(f.name);
1159
+ setKey(out, f.name, read(f.type, depth + 1));
1160
+ trail.pop();
1161
+ }
1162
+ return out;
1163
+ }
1164
+ case "union": {
1165
+ const at = i;
1166
+ const n = varint();
1167
+ if (n < 0n || n >= BigInt(t.types.length)) return fail(`${n} isn't a branch of the union (0 to ${t.types.length - 1})`, at);
1168
+ return read(t.types[Number(n)], depth + 1);
1169
+ }
1170
+ default:
1171
+ return fail(`the type ${t.typeName} can't be read`);
1172
+ }
1173
+ };
1174
+ let value;
1175
+ try {
1176
+ value = read(type, 0);
1177
+ } catch (e) {
1178
+ // the message ending early, or a limit: say which field it was reading
1179
+ const path = pathText();
1180
+ if (e instanceof CodecError && e.path === undefined && path) throw new CodecError(`${path}: ${e.message}`, { path, offset: i });
1181
+ throw e;
1182
+ }
1183
+ if (i !== b.length) throw new CodecError(`${b.length - i} bytes follow the value (a stream of values: frame it first)`, { offset: i });
1184
+ return value;
1185
+ }
1186
+
1187
+ // ── Avro: values out ─────────────────────────────────────────────────────────
1188
+
1189
+ /** A growable run of bytes with a mark to go back to (a union tries its branches one by one). */
1190
+ function sink(max) {
1191
+ let buf = new Uint8Array(256);
1192
+ let len = 0;
1193
+ const room = (n) => {
1194
+ if (len + n > max) throw new CodecError(`the encoded message is more than ${max} bytes (the bytes limit)`);
1195
+ if (len + n > buf.length) {
1196
+ const next = new Uint8Array(Math.min(Math.max(buf.length * 2, len + n), max));
1197
+ next.set(buf.subarray(0, len));
1198
+ buf = next;
1199
+ }
1200
+ };
1201
+ const self = {
1202
+ get length() {
1203
+ return len;
1204
+ },
1205
+ reset: (to) => {
1206
+ len = to;
1207
+ },
1208
+ byte(c) {
1209
+ room(1);
1210
+ buf[len++] = c;
1211
+ },
1212
+ bytes(u8) {
1213
+ room(u8.length);
1214
+ buf.set(u8, len);
1215
+ len += u8.length;
1216
+ },
1217
+ varint(n) {
1218
+ let z = n < 0n ? ((-n) << 1n) - 1n : n << 1n; // zigzag
1219
+ while (z >= 128n) {
1220
+ self.byte(Number(z & 127n) | 128);
1221
+ z >>= 7n;
1222
+ }
1223
+ self.byte(Number(z));
1224
+ },
1225
+ finish: () => buf.slice(0, len),
1226
+ };
1227
+ return self;
1228
+ }
1229
+
1230
+ const describeAvro = (t) => {
1231
+ const k = avroKind(t);
1232
+ return AVRO_NAMED.has(k) ? `${k} ${t.name}` : k === "union" ? `one of ${t.types.map(describeAvro).join(", ")}` : k === "array" ? `a list of ${describeAvro(t.itemsType)}` : k === "map" ? `a map of ${describeAvro(t.valuesType)}` : k;
1233
+ };
1234
+
1235
+ /** Bytes from what pane code writes for an Avro bytes or fixed value, or undefined. */
1236
+ function bytesValue(v, spec) {
1237
+ if (v instanceof Uint8Array) return v;
1238
+ if (ArrayBuffer.isView(v)) return new Uint8Array(v.buffer, v.byteOffset, v.byteLength);
1239
+ if (v instanceof ArrayBuffer) return new Uint8Array(v);
1240
+ if (Array.isArray(v) && v.every((x) => isInt(x) && x >= 0 && x <= 255)) return Uint8Array.from(v);
1241
+ if (typeof v === "string") return (spec.binary === "hex" ? fromHex(v) : fromBase64(v)) ?? undefined;
1242
+ return undefined;
1243
+ }
1244
+
1245
+ /**
1246
+ * A value written as Avro binary against `type`. Problems are collected with the path of the value they are about
1247
+ * (`value.readings[2].celsius`), up to MAX_ERRORS; a union tries its branches in order and takes the first that takes the value.
1248
+ * Returns whether the value was fine.
1249
+ */
1250
+ function writeAvro(type, value, spec, bud, out, problems) {
1251
+ const bad = (path, message) => {
1252
+ if (problems.length < MAX_ERRORS) problems.push({ path, message: `${path}: ${message}` });
1253
+ return false;
1254
+ };
1255
+ const text = new TextEncoder();
1256
+ const write = (t, v, path, depth) => {
1257
+ bud.tick();
1258
+ if (depth > bud.limits.depth) throw new CodecError(`${path}: nests deeper than ${bud.limits.depth} levels (the depth limit)`, { path });
1259
+ const kind = avroKind(t);
1260
+ switch (kind) {
1261
+ case "null":
1262
+ return v === null || v === undefined ? true : bad(path, `expected null, got ${got(v)}`);
1263
+ case "boolean":
1264
+ if (typeof v !== "boolean") return bad(path, `expected true or false, got ${got(v)}`);
1265
+ out.byte(v ? 1 : 0);
1266
+ return true;
1267
+ case "int":
1268
+ if (typeof v !== "number" || !isInt(v) || v < -2147483648 || v > 2147483647) return bad(path, `expected a whole number from -2147483648 to 2147483647 (int), got ${got(v)}`);
1269
+ out.varint(BigInt(v));
1270
+ return true;
1271
+ case "long": {
1272
+ const n = longOf(v);
1273
+ if (n === undefined) return bad(path, `expected a whole number from ${INT64_MIN} to ${INT64_MAX} (long; larger ones as text), got ${got(v)}`);
1274
+ out.varint(n);
1275
+ return true;
1276
+ }
1277
+ case "float":
1278
+ case "double": {
1279
+ if (typeof v !== "number") return bad(path, `expected a number (${kind}), got ${got(v)}`);
1280
+ const u8 = new Uint8Array(kind === "float" ? 4 : 8);
1281
+ if (kind === "float") new DataView(u8.buffer).setFloat32(0, v, true);
1282
+ else new DataView(u8.buffer).setFloat64(0, v, true);
1283
+ out.bytes(u8);
1284
+ return true;
1285
+ }
1286
+ case "string": {
1287
+ if (typeof v !== "string") return bad(path, `expected text, got ${got(v)}`);
1288
+ const u8 = text.encode(v);
1289
+ out.varint(BigInt(u8.length));
1290
+ out.bytes(u8);
1291
+ return true;
1292
+ }
1293
+ case "bytes":
1294
+ case "fixed": {
1295
+ const u8 = bytesValue(v, spec);
1296
+ if (!u8) return bad(path, `expected bytes (a Uint8Array, a list of numbers 0 to 255, or ${spec.binary === "hex" ? "hex" : "base64"} text), got ${got(v)}`);
1297
+ if (kind === "fixed") {
1298
+ if (u8.length !== t.size) return bad(path, `expected ${t.size} bytes (fixed ${t.name}), got ${u8.length}`);
1299
+ } else out.varint(BigInt(u8.length));
1300
+ out.bytes(u8);
1301
+ return true;
1302
+ }
1303
+ case "enum": {
1304
+ const at = typeof v === "string" ? t.symbols.indexOf(v) : isInt(v) && v >= 0 && v < t.symbols.length ? v : -1;
1305
+ if (at < 0) return bad(path, `expected one of ${t.symbols.join(", ")} (enum ${t.name}), got ${got(v)}`);
1306
+ out.varint(BigInt(at));
1307
+ return true;
1308
+ }
1309
+ case "array": {
1310
+ if (!Array.isArray(v)) return bad(path, `expected a list (${describeAvro(t)}), got ${got(v)}`);
1311
+ let ok = true;
1312
+ if (v.length) {
1313
+ out.varint(BigInt(v.length));
1314
+ for (let k = 0; k < v.length; k++) ok = write(t.itemsType, v[k], `${path}[${k}]`, depth + 1) && ok;
1315
+ }
1316
+ out.byte(0);
1317
+ return ok;
1318
+ }
1319
+ case "map": {
1320
+ if (!isObject(v) || ArrayBuffer.isView(v) || v instanceof Date) return bad(path, `expected an object (${describeAvro(t)}), got ${got(v)}`);
1321
+ const keys = Object.keys(v);
1322
+ let ok = true;
1323
+ if (keys.length) {
1324
+ out.varint(BigInt(keys.length));
1325
+ for (const k of keys) {
1326
+ const u8 = text.encode(k);
1327
+ out.varint(BigInt(u8.length));
1328
+ out.bytes(u8);
1329
+ ok = write(t.valuesType, v[k], step(path, k), depth + 1) && ok;
1330
+ }
1331
+ }
1332
+ out.byte(0);
1333
+ return ok;
1334
+ }
1335
+ case "record": {
1336
+ if (!isObject(v) || ArrayBuffer.isView(v) || v instanceof Date) return bad(path, `expected an object (${t.name}), got ${got(v)}`);
1337
+ let ok = true;
1338
+ const names = new Set(t.fields.map((f) => f.name));
1339
+ for (const f of t.fields) {
1340
+ let x = v[f.name];
1341
+ if (x === undefined) {
1342
+ const d = f.defaultValue();
1343
+ if (d !== undefined) x = d;
1344
+ else if (avroKind(f.type) !== "null" && !(avroKind(f.type) === "union" && f.type.types.some((u) => avroKind(u) === "null"))) {
1345
+ ok = bad(step(path, f.name), `is missing (${describeAvro(f.type)})`);
1346
+ continue;
1347
+ }
1348
+ }
1349
+ ok = write(f.type, x, step(path, f.name), depth + 1) && ok;
1350
+ }
1351
+ for (const key of Object.keys(v)) if (!names.has(key)) ok = bad(step(path, key), `${t.name} has no field "${key}" (fields: ${[...names].join(", ") || "none"})`);
1352
+ return ok;
1353
+ }
1354
+ case "union": {
1355
+ const mark = out.length;
1356
+ const saved = problems.length;
1357
+ for (let k = 0; k < t.types.length; k++) {
1358
+ out.varint(BigInt(k));
1359
+ if (write(t.types[k], v, path, depth + 1)) return true;
1360
+ problems.length = saved;
1361
+ out.reset(mark);
1362
+ }
1363
+ return bad(path, `expected ${describeAvro(t)}, got ${got(v)}`);
1364
+ }
1365
+ default:
1366
+ return bad(path, `the type ${t.typeName} can't be written`);
1367
+ }
1368
+ };
1369
+ return write(type, value, "value", 0);
1370
+ }
1371
+
1372
+ // ── custom structs ───────────────────────────────────────────────────────────
1373
+
1374
+ /** A whole number from a BigInt, a safe integer or a decimal string, with no range (a field checks its own), or undefined. */
1375
+ function intOf(v) {
1376
+ if (typeof v === "bigint") return v;
1377
+ if (typeof v === "number" && Number.isSafeInteger(v)) return BigInt(v);
1378
+ if (typeof v === "string" && /^-?\d{1,20}$/.test(v)) return BigInt(v);
1379
+ return undefined;
1380
+ }
1381
+
1382
+ /** A struct layout (fields on lines or between commas, `//` comments) as parts `{ text, line }`. */
1383
+ function structParts(schema) {
1384
+ const parts = [];
1385
+ schema.split("\n").forEach((raw, n) => {
1386
+ for (const piece of raw.replace(/\/\/.*$/, "").split(",")) if (piece.trim()) parts.push({ text: piece.trim(), line: n + 1 });
1387
+ });
1388
+ return parts;
1389
+ }
1390
+
1391
+ /** Read a struct layout with the `bytes` helper's struct: `{ ok, errors, types, struct, singles }`. */
1392
+ function compileStruct(lib, schema) {
1393
+ const parts = structParts(schema);
1394
+ if (!parts.length) return { ok: false, errors: [{ line: 1, message: "the layout is empty: list the fields, like u8 id, u16le len, f32le x[3]" }], types: [] };
1395
+ const errors = [];
1396
+ if (parts.length > MAX_FIELDS) errors.push({ line: parts[MAX_FIELDS].line, message: `a layout has at most ${MAX_FIELDS} fields (this one has ${parts.length})` });
1397
+ const clean = (e) => String(e?.message ?? e).replace(/^struct: /, "");
1398
+ for (const { text, line } of parts.slice(0, MAX_FIELDS)) {
1399
+ try {
1400
+ lib.struct(text);
1401
+ } catch (e) {
1402
+ errors.push({ line, message: clean(e) });
1403
+ }
1404
+ }
1405
+ if (errors.length) return { ok: false, errors: errors.slice(0, MAX_ERRORS), types: [] };
1406
+ const seen = new Map();
1407
+ for (const { text, line } of parts) {
1408
+ const name = /^\S+\s+([A-Za-z_$][\w$]*)/.exec(text)[1];
1409
+ if (seen.has(name)) errors.push({ line, message: `the name "${name}" is used twice (first on line ${seen.get(name)})` });
1410
+ else seen.set(name, line);
1411
+ }
1412
+ if (errors.length) return { ok: false, errors: errors.slice(0, MAX_ERRORS), types: [] };
1413
+ let struct;
1414
+ try {
1415
+ struct = lib.struct(parts.map((p) => p.text).join(", "));
1416
+ } catch (e) {
1417
+ return { ok: false, errors: [{ message: clean(e) }], types: [] };
1418
+ }
1419
+ const singles = new Map(struct.fields.map((f) => [f.name, lib.struct(`${f.type} ${f.name}${f.length ? `[${f.length}]` : ""}`)]));
1420
+ return { ok: true, errors: [], types: [], struct, singles };
1421
+ }
1422
+
1423
+ /** The field (an array's element by index) that byte `at` of a struct record falls in: `{ name, from, to }` (inclusive), or null. */
1424
+ function structFieldAt(fields, size, at) {
1425
+ for (let k = 0; k < fields.length; k++) {
1426
+ const f = fields[k];
1427
+ const end = k + 1 < fields.length ? fields[k + 1].offset : size;
1428
+ if (at < f.offset || at >= end) continue;
1429
+ if (!f.length) return { name: f.name, from: f.offset, to: end - 1 };
1430
+ const each = (end - f.offset) / f.length;
1431
+ const n = Math.floor((at - f.offset) / each);
1432
+ return { name: `${f.name}[${n}]`, from: f.offset + n * each, to: f.offset + (n + 1) * each - 1 };
1433
+ }
1434
+ return null;
1435
+ }
1436
+
1437
+ /** A struct's own complaint about one value, said as the other formats say it: `{ name, text }`. */
1438
+ function structComplaint(message) {
1439
+ const m = String(message).replace(/^struct: /, "");
1440
+ const named = /^([\w$]+(?:\[\d+\])?) (.*)$/.exec(m);
1441
+ if (!named) return { name: "", text: m.replace(/\.$/, "") };
1442
+ const [, name, rest] = named;
1443
+ let r = /^is (.+?), outside (.+)\.$/.exec(rest);
1444
+ if (r) return { name, text: `${r[1]} is outside ${r[2]}` };
1445
+ r = /^is (.+?), and (\S+) holds whole numbers\.$/.exec(rest);
1446
+ if (r) return { name, text: `expected a whole number (${r[2]}), got ${r[1]}` };
1447
+ r = /^\((\S+)\) takes (.+?), not (.+)\.$/.exec(rest);
1448
+ if (r) return { name, text: `expected ${r[2]} (${r[1]}), got ${r[3]}` };
1449
+ return { name, text: rest.replace(/\.$/, "") };
1450
+ }
1451
+
1452
+ /** A struct record read as plain data (64-bit fields as numbers when safe, decimal text when not). */
1453
+ function plainStruct(record) {
1454
+ const out = {};
1455
+ for (const [k, v] of Object.entries(record)) setKey(out, k, Array.isArray(v) ? v.map((x) => (typeof x === "bigint" ? numberOrString(x) : x)) : typeof v === "bigint" ? numberOrString(v) : v);
1456
+ return out;
1457
+ }
1458
+
1459
+ // ── FlatBuffers: the schema ──────────────────────────────────────────────────
1460
+
1461
+ /** A .fbs with its comments and string literals blanked (newlines kept, so a line is still a line). */
1462
+ const blankFbs = (schema) => schema.replace(/\/\/[^\n]*|\/\*[\s\S]*?\*\/|"(?:[^"\\\n]|\\.)*"/g, (m) => m.replace(/[^\n]/g, " "));
1463
+
1464
+ /** The tables of a .fbs, as `[{ name (with its namespace), short }]` in declaration order, and the `root_type` it declares (or ""). */
1465
+ export function scanFbs(schema) {
1466
+ const tables = [];
1467
+ let namespace = "";
1468
+ let root = "";
1469
+ for (const m of blankFbs(schema).matchAll(/\bnamespace\s+([\w.]+)\s*;|\btable\s+(\w+)|\broot_type\s+([\w.]+)\s*;/g)) {
1470
+ if (m[1] !== undefined) namespace = m[1];
1471
+ else if (m[2] !== undefined) tables.push({ name: namespace ? `${namespace}.${m[2]}` : m[2], short: m[2] });
1472
+ else root = m[3];
1473
+ }
1474
+ return { tables, root };
1475
+ }
1476
+
1477
+ /** flatc's complaint, `file:line: column: error: text` (or `line: column: error: text` from the JSON side), as `{ line?, column?, message }`. */
1478
+ function flatcError(text) {
1479
+ const m = /^(?:[^\n]*?:)?\s*(\d+):\s*(\d+):\s*(?:error:\s*)?([\s\S]*)$/.exec(String(text).trim());
1480
+ if (!m) return { message: String(text).replace(/^[^\s:]+\.fbs:\s*/, "").trim() };
1481
+ return { line: Number(m[1]), column: Number(m[2]), message: m[3].trim() };
1482
+ }
1483
+
1484
+ /** The table a spec or call names (the full name or the last part), or the schema's own `root_type`, or the first table. */
1485
+ function fbsRoot(scan, requested) {
1486
+ const want = (requested ?? "").trim() || scan.root;
1487
+ if (!want) return scan.tables[0] ?? null;
1488
+ const exact = scan.tables.find((t) => t.name === want);
1489
+ if (exact) return exact;
1490
+ const tail = scan.tables.filter((t) => t.name.endsWith(`.${want}`) || t.short === want);
1491
+ if (tail.length === 1) return tail[0];
1492
+ if (tail.length > 1) throw new CodecError(`"${want}" names ${tail.length} tables (${tail.map((t) => t.name).join(", ")}): use the full name`);
1493
+ throw new CodecError(`the schema has no table "${want}"${scan.tables.length ? ` (tables: ${scan.tables.map((t) => t.name).join(", ")})` : ""}`);
1494
+ }
1495
+
1496
+ // ── FlatBuffers: values ──────────────────────────────────────────────────────
1497
+
1498
+ /** A value as the JSON text flatc reads: a 64-bit BigInt as digits, NaN and the infinities as flatc spells them, bytes as a list. */
1499
+ function fbsJson(value) {
1500
+ switch (typeof value) {
1501
+ case "bigint":
1502
+ return value.toString();
1503
+ case "number":
1504
+ return Number.isNaN(value) ? "nan" : value === Infinity ? "inf" : value === -Infinity ? "-inf" : JSON.stringify(value);
1505
+ case "string":
1506
+ case "boolean":
1507
+ return JSON.stringify(value);
1508
+ case "object":
1509
+ break;
1510
+ default:
1511
+ return "null";
1512
+ }
1513
+ if (value === null) return "null";
1514
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? "null" : JSON.stringify(value.toISOString());
1515
+ if (ArrayBuffer.isView(value)) return `[${Array.from(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)).join(",")}]`;
1516
+ if (value instanceof ArrayBuffer) return `[${Array.from(new Uint8Array(value)).join(",")}]`;
1517
+ if (Array.isArray(value)) return `[${value.map((v) => (v === undefined ? "null" : fbsJson(v))).join(",")}]`;
1518
+ const parts = [];
1519
+ for (const k of Object.keys(value)) if (value[k] !== undefined && value[k] !== null) parts.push(`${JSON.stringify(k)}:${fbsJson(value[k])}`); // unset
1520
+ return `{${parts.join(",")}}`;
1521
+ }
1522
+
1523
+ /** Where the path of a value is, in compact JSON text, at character `offset`: the last key or list entry that begins at or before it. */
1524
+ function pathAtOffset(json, offset) {
1525
+ const stack = []; // { array: boolean, index: number, key: string }
1526
+ const path = () => stack.reduce((p, f) => (f.array ? `${p}[${f.index}]` : f.key === undefined ? p : `${p}.${f.key}`), "value");
1527
+ let best = "value";
1528
+ const begin = (i) => {
1529
+ const top = stack[stack.length - 1];
1530
+ if (top?.array) top.index++;
1531
+ if (i <= offset) best = path();
1532
+ };
1533
+ for (let i = 0; i < json.length; i++) {
1534
+ const ch = json[i];
1535
+ if (ch === '"') {
1536
+ let j = i + 1;
1537
+ while (j < json.length && json[j] !== '"') j += json[j] === "\\" ? 2 : 1;
1538
+ const top = stack[stack.length - 1];
1539
+ if (top && !top.array && json[j + 1] === ":") {
1540
+ top.key = JSON.parse(json.slice(i, j + 1));
1541
+ if (i <= offset) best = path();
1542
+ } else begin(i);
1543
+ i = j;
1544
+ } else if (ch === "{" || ch === "[") {
1545
+ begin(i);
1546
+ stack.push({ array: ch === "[", index: -1, key: undefined });
1547
+ } else if (ch === "}" || ch === "]") stack.pop();
1548
+ else if (ch !== "," && ch !== ":") {
1549
+ begin(i);
1550
+ while (i + 1 < json.length && !",]}".includes(json[i + 1])) i++;
1551
+ }
1552
+ }
1553
+ return best;
1554
+ }
1555
+
1556
+ /**
1557
+ * flatc's JSON as a value. flatc prints NaN and the infinities bare and a control character raw in a string, which JSON refuses:
1558
+ * both are rewritten first. A 64-bit integer that doesn't fit a safe integer comes back as its decimal text, as protocol buffers' do.
1559
+ */
1560
+ function parseFbsJson(text) {
1561
+ const fixed = text.replace(/"(?:[^"\\]|\\.)*"|(?<![\w.+-])-?(?:nan|inf)(?![\w.])/g, (m) => {
1562
+ if (m[0] === '"') return m.replace(/[\u0000-\u001f]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
1563
+ return m.endsWith("nan") ? "7e9999" : m[0] === "-" ? "-1e999" : "1e999";
1564
+ });
1565
+ return JSON.parse(fixed, (_, v, context) => {
1566
+ if (typeof v !== "number") return v;
1567
+ const source = context?.source;
1568
+ if (source === "7e9999") return NaN;
1569
+ return source !== undefined && !Number.isSafeInteger(v) && /^-?\d+$/.test(source) ? source : v;
1570
+ });
1571
+ }
1572
+
1573
+ /** Count a decoded value against the depth and items limits (a buffer can point at one table many times). */
1574
+ function boundedJson(value, bud, depth = 0) {
1575
+ bud.tick();
1576
+ if (value === null || typeof value !== "object") return value;
1577
+ if (depth > bud.limits.depth) throw tooDeep(bud.limits);
1578
+ const keys = Array.isArray(value) ? null : Object.keys(value);
1579
+ bud.items = (bud.items ?? 0) + (keys ? keys.length : value.length) + 1;
1580
+ if (bud.items > bud.limits.items) throw tooMany(bud.limits);
1581
+ if (keys) for (const k of keys) boundedJson(value[k], bud, depth + 1);
1582
+ else for (const v of value) boundedJson(v, bud, depth + 1);
1583
+ return value;
1584
+ }
1585
+
1586
+ // ── Cap'n Proto (src/codec/capnp.js, loaded as the library "capnp") ─────────
1587
+
1588
+ function compileCapnp(l, schema) {
1589
+ if (!schema.trim()) return { ok: false, errors: [{ line: 1, message: "the schema is empty: declare a struct, like struct Reading { sensor @0 :Text; }" }], types: [] };
1590
+ const c = l.compile(schema, { maxTypes: MAX_TYPES, maxFields: MAX_FIELDS });
1591
+ const errors = c.errors.slice(0, MAX_ERRORS).map((e) => ({ ...(e.line ? { line: e.line } : {}), message: e.message }));
1592
+ if (c.ok && !c.types.length) return { ok: false, errors: [{ line: 1, message: "the schema declares no struct: a message is a struct, like struct Reading { sensor @0 :Text; }" }], types: [] };
1593
+ return { ...c, errors, types: c.ok ? c.types : [] };
1594
+ }
1595
+
1596
+ /** The struct a spec names, or the schema's first one. */
1597
+ function pickCapnpType(compiled, spec, requested) {
1598
+ const name = (requested ?? spec.type ?? "").trim();
1599
+ if (!name) return compiled.first;
1600
+ if (compiled.structs.has(name)) return name;
1601
+ const tail = compiled.types.filter((t) => t.endsWith(`.${name}`));
1602
+ if (tail.length === 1) return tail[0];
1603
+ throw new CodecError(tail.length > 1 ? `"${name}" names ${tail.length} structs (${tail.join(", ")}): use the full name` : `the schema has no struct "${name}" (structs: ${compiled.types.join(", ")})`);
1604
+ }
1605
+
1606
+ /** The reader's or writer's complaint as a CodecError: a decode's says the field and the byte, an encode's the field path. */
1607
+ function capnpError(e, prefix, limits) {
1608
+ if (e?.name !== "CapnpError") {
1609
+ if (isOverflow(e)) return tooDeep(limits);
1610
+ return e;
1611
+ }
1612
+ if (e.problems) return new CodecError(e.message, { path: e.path, errors: e.problems.slice(0, MAX_ERRORS).map((p) => ({ message: p.message })) });
1613
+ if (e.kind === "depth" || e.kind === "items" || e.kind === "size") return new CodecError(`${prefix}${e.path ? `${e.path}: ` : ""}${e.message}`, { ...(e.path ? { path: e.path } : {}), ...(e.offset !== undefined ? { offset: e.offset } : {}) });
1614
+ const where = `${e.path ? `${e.path} ` : ""}${e.offset !== undefined ? `at byte ${e.offset}` : ""}`.trim();
1615
+ return new CodecError(`${prefix}${where ? `${where}: ` : ""}${e.message}`, { ...(e.path ? { path: e.path } : {}), ...(e.offset !== undefined ? { offset: e.offset } : {}) });
1616
+ }
1617
+
1618
+ // ── the engine ───────────────────────────────────────────────────────────────
1619
+
1620
+ /**
1621
+ * @param {{ load: (name: "msgpack" | "cbor" | "protobuf" | "flatbuffers" | "capnp" | "avro" | "struct") => Promise<object>, now?: () => number }} options
1622
+ * `load` hands over a vendored library as a module namespace (protobufjs as its `default`, the flatc module's `default` makes an instance).
1623
+ */
1624
+ export function createEngine({ load, now = defaultNow } = {}) {
1625
+ const libs = new Map();
1626
+ const lib = async (name) => {
1627
+ if (!libs.has(name)) libs.set(name, Promise.resolve().then(() => load(name)).catch((e) => (libs.delete(name), Promise.reject(new CodecError(`the ${FORMAT_LABELS[name] ?? name} library couldn't be loaded${e?.message ? `: ${e.message}` : ""}`)))));
1628
+ return libs.get(name);
1629
+ };
1630
+ const compiled = new Map(); // format and schema text -> the schema read (bounded)
1631
+ async function schemaOf(spec) {
1632
+ const schema = spec.schema ?? "";
1633
+ const key = `${spec.format}\u0000${schema}`;
1634
+ if (compiled.has(key)) {
1635
+ const hit = compiled.get(key);
1636
+ compiled.delete(key);
1637
+ compiled.set(key, hit);
1638
+ return hit;
1639
+ }
1640
+ const library = await lib(spec.format);
1641
+ const result = spec.format === "avro" ? compileAvro(library, schema) : spec.format === "struct" ? compileStruct(library, schema) : spec.format === "capnp" ? compileCapnp(library, schema) : compileProto(library.default, schema);
1642
+ compiled.set(key, result);
1643
+ if (compiled.size > 16) compiled.delete(compiled.keys().next().value);
1644
+ return result;
1645
+ }
1646
+
1647
+ // FlatBuffers: one flatc instance per engine, made when a FlatBuffers codec is first used, and the schemas it has parsed (by the
1648
+ // schema text and the root table). A trap in the module (it ran out of its capped memory) drops the instance with its schemas.
1649
+ let flatc = null; // Promise of the instance
1650
+ const fbsSchemas = new Map(); // key -> Promise of { ok, errors, types, root, id }
1651
+ const flatcInstance = () =>
1652
+ (flatc ??= lib("flatbuffers").then((l) => l.default()).catch((e) => {
1653
+ flatc = null;
1654
+ throw e instanceof CodecError ? e : new CodecError(`the FlatBuffers compiler couldn't start: ${e?.message ?? e}`);
1655
+ }));
1656
+ const flatcTrapped = (e) => {
1657
+ if (!(e instanceof WebAssembly.RuntimeError)) return false;
1658
+ flatc = null;
1659
+ fbsSchemas.clear();
1660
+ return true;
1661
+ };
1662
+ const ranOut = () => new CodecError("the message can't be read: it prints as far more than it holds (the converter ran out of memory)");
1663
+ async function fbsSchemaOf(spec, requested) {
1664
+ const schema = spec.schema ?? "";
1665
+ if (!schema.trim()) return { ok: false, errors: [{ line: 1, message: "the schema is empty: declare a table and a root_type, like table Reading { sensor:string; } root_type Reading;" }], types: [] };
1666
+ const scan = scanFbs(schema);
1667
+ if (scan.tables.length > MAX_TYPES) return { ok: false, errors: [{ message: `a schema has at most ${MAX_TYPES} tables (this one has ${scan.tables.length})` }], types: [] };
1668
+ const types = scan.tables.map((t) => t.name);
1669
+ let root = null;
1670
+ try {
1671
+ root = fbsRoot(scan, requested ?? spec.type);
1672
+ } catch (e) {
1673
+ if (requested === undefined && spec.type && scan.tables.length) {
1674
+ // the pane's chosen table is gone from the schema: say so on the schema's status, and read the schema with its own root
1675
+ root = fbsRoot(scan, "");
1676
+ const found = await fbsCompile(schema, root, types);
1677
+ return { ...found, ok: false, errors: [{ message: e.message }, ...found.errors] };
1678
+ }
1679
+ if (requested !== undefined) throw e;
1680
+ }
1681
+ return fbsCompile(schema, root, types);
1682
+ }
1683
+ function fbsCompile(schema, root, types) {
1684
+ const key = `${root?.name ?? ""}\0${schema}`;
1685
+ if (!fbsSchemas.has(key)) {
1686
+ const made = flatcInstance().then((f) => {
1687
+ // flatc reads the last root_type: the one asked for goes after the schema's text, so no line moves
1688
+ const text = root ? `${schema}\nroot_type ${root.name};\n` : schema;
1689
+ try {
1690
+ return { ok: true, errors: [], types, root: root?.name, id: f.addSchema("schema.fbs", text) };
1691
+ } catch (e) {
1692
+ if (flatcTrapped(e)) throw ranOut();
1693
+ const err = flatcError(e?.message);
1694
+ if (e?.flatcStatus === -4) return { ok: false, errors: [{ line: 1, message: "the schema declares no table: a FlatBuffer is a table, like table Reading { sensor:string; }" }], types };
1695
+ // a type that is never defined is found at the end of the schema; flatc says where it was used ("originally at: schema.fbs:2")
1696
+ const origin = /originally at: [^\s:]+:(\d+)/.exec(err.message);
1697
+ const line = origin ? Number(origin[1]) : err.line;
1698
+ const message = err.message.replace(/, originally at: .*$/, "").replace(/^unable to load include file: (.*)$/, 'include "$1" can\'t be loaded: a schema here is one piece of text, so put the tables it needs in this schema');
1699
+ return { ok: false, errors: [{ ...(line && line <= schema.split("\n").length ? { line } : {}), message }], types };
1700
+ }
1701
+ });
1702
+ fbsSchemas.set(key, made);
1703
+ made.catch(() => fbsSchemas.delete(key));
1704
+ if (fbsSchemas.size > 16) {
1705
+ // keep the sixteen most recent: the oldest schema is dropped from the module too
1706
+ const [oldKey, old] = fbsSchemas.entries().next().value;
1707
+ fbsSchemas.delete(oldKey);
1708
+ old.then((v) => v.id !== undefined && flatcInstance().then((f) => f.removeSchema(v.id)), () => {}).catch(() => {});
1709
+ }
1710
+ } else {
1711
+ const hit = fbsSchemas.get(key);
1712
+ fbsSchemas.delete(key);
1713
+ fbsSchemas.set(key, hit);
1714
+ }
1715
+ return fbsSchemas.get(key);
1716
+ }
1717
+ const needFbs = async (spec, requested) => {
1718
+ const c = await fbsSchemaOf(spec, requested);
1719
+ if (!c.ok) {
1720
+ const first = c.errors[0];
1721
+ throw new CodecError(`schema${first.line ? ` line ${first.line}` : ""}: ${first.message}${c.errors.length > 1 ? ` (and ${c.errors.length - 1} more)` : ""}`, { errors: c.errors });
1722
+ }
1723
+ return c;
1724
+ };
1725
+ const check = (spec) => {
1726
+ const bad = codecProblem(spec);
1727
+ if (bad) throw new CodecError(`codec: ${bad}`);
1728
+ };
1729
+ const needSchema = async (spec) => {
1730
+ const c = await schemaOf(spec);
1731
+ if (!c.ok) {
1732
+ const first = c.errors[0];
1733
+ throw new CodecError(`schema${first.line ? ` line ${first.line}` : ""}: ${first.message}${c.errors.length > 1 ? ` (and ${c.errors.length - 1} more)` : ""}`, { errors: c.errors });
1734
+ }
1735
+ return c;
1736
+ };
1737
+
1738
+ return {
1739
+ /** The schema's problems and message types: `{ ok, errors: [{ line?, message }], types }`. Schemaless formats are always fine. */
1740
+ async analyze(spec) {
1741
+ check(spec);
1742
+ if (spec.format === "flatbuffers") {
1743
+ const c = await fbsSchemaOf(spec);
1744
+ return { ok: c.ok, errors: c.errors, types: c.types };
1745
+ }
1746
+ if (!SCHEMA_FORMATS.includes(spec.format)) {
1747
+ await lib(spec.format);
1748
+ return { ok: true, errors: [], types: [] };
1749
+ }
1750
+ const c = await schemaOf(spec);
1751
+ return { ok: c.ok, errors: c.errors, types: c.types };
1752
+ },
1753
+
1754
+ /** Bytes in, a plain value out. `type` picks a message other than the setting's. */
1755
+ async decode(spec, input, { type } = {}) {
1756
+ check(spec);
1757
+ const bytes = toBytes(input);
1758
+ const limits = limitsOf(spec);
1759
+ if (bytes.length > limits.bytes) throw new CodecError(`the message is ${bytes.length} bytes; the limit is ${limits.bytes}`);
1760
+ const bud = budget(limits, now);
1761
+ if (spec.format === "flatbuffers") {
1762
+ const c = await needFbs(spec, type);
1763
+ const f = await flatcInstance();
1764
+ let text;
1765
+ try {
1766
+ text = f.binaryToJson(c.id, bytes);
1767
+ } catch (e) {
1768
+ if (flatcTrapped(e)) throw ranOut();
1769
+ throw new CodecError(`not a ${c.root} message: ${flatcError(e?.message).message}`);
1770
+ }
1771
+ bud.check();
1772
+ let value;
1773
+ try {
1774
+ value = parseFbsJson(text);
1775
+ } catch (e) {
1776
+ throw new CodecError(`the message can't be read as JSON: ${e?.message ?? e}`);
1777
+ }
1778
+ bud.check();
1779
+ const out = boundedJson(value, bud);
1780
+ bud.check();
1781
+ return out;
1782
+ }
1783
+ if (spec.format === "protobuf") {
1784
+ const c = await needSchema(spec);
1785
+ const T = pickType(c, spec, type);
1786
+ const pb = (await lib("protobuf")).default;
1787
+ try {
1788
+ scanProto(T, bytes, limits, now);
1789
+ } catch (e) {
1790
+ if (isOverflow(e)) throw tooDeep(limits);
1791
+ if (e instanceof CodecError && e.offset !== undefined) throw new CodecError(`not a ${T.name} message: ${e.message}`, { path: e.path || undefined, offset: e.offset });
1792
+ throw e;
1793
+ }
1794
+ let message;
1795
+ try {
1796
+ message = T.decode(bytes);
1797
+ } catch (e) {
1798
+ if (isOverflow(e)) throw tooDeep(limits);
1799
+ throw new CodecError(`not a ${T.name} message: ${String(e?.message ?? e).replace(/^illegal buffer$/, "the bytes end early")}`);
1800
+ }
1801
+ bud.check();
1802
+ const obj = T.toObject(message, { longs: String, enums: String, bytes: Array, defaults: true, arrays: true, objects: true, oneofs: true });
1803
+ fixLongs(T, obj);
1804
+ const out = plainProto(T, obj, spec, bud);
1805
+ void pb;
1806
+ bud.check();
1807
+ return out;
1808
+ }
1809
+ if (spec.format === "capnp") {
1810
+ const c = await needSchema(spec);
1811
+ const name = pickCapnpType(c, spec, type);
1812
+ const l = await lib("capnp");
1813
+ let value;
1814
+ try {
1815
+ value = l.decode(c, name, bytes, { packed: spec.packed === true, depth: limits.depth, items: limits.items, maxBytes: limits.bytes, tick: () => bud.tick(), bytesOut: (u8) => binaryOf(u8, spec.binary ?? "bytes") });
1816
+ } catch (e) {
1817
+ throw capnpError(e, `not a ${name} message${spec.packed ? " (packed)" : ""}: `, limits);
1818
+ }
1819
+ bud.check();
1820
+ return value;
1821
+ }
1822
+ if (spec.format === "avro") {
1823
+ const c = await needSchema(spec);
1824
+ const value = readAvro(pickAvroType(c, spec, type), bytes, limits, bud, spec);
1825
+ bud.check();
1826
+ return value;
1827
+ }
1828
+ if (spec.format === "struct") {
1829
+ const c = await needSchema(spec);
1830
+ const { size, fields } = c.struct;
1831
+ if (bytes.length > size) throw new CodecError(`the layout is ${size} bytes and ${bytes.length - size} bytes follow the record (a stream of records: frame it first)`, { offset: size });
1832
+ if (bytes.length < size) {
1833
+ const inside = structFieldAt(fields, size, bytes.length);
1834
+ throw new CodecError(`the layout is ${size} bytes and the message has only ${bytes.length}${inside ? `: it ends inside ${inside.name} (bytes ${inside.from} to ${inside.to})` : ""}`, { ...(inside ? { path: inside.name } : {}), offset: bytes.length });
1835
+ }
1836
+ if (fields.reduce((n, f) => n + (f.length ?? 1), 0) > limits.items) throw tooMany(limits);
1837
+ const out = plainStruct(c.struct.decode(bytes));
1838
+ bud.check();
1839
+ return out;
1840
+ }
1841
+ await lib(spec.format);
1842
+ scan(spec.format, bytes, limits, now);
1843
+ bud.check();
1844
+ const l = await lib(spec.format);
1845
+ let value;
1846
+ try {
1847
+ value = spec.format === "msgpack" ? l.decode(bytes, { useBigInt64: true, maxStrLength: bytes.length, maxBinLength: bytes.length, maxExtLength: bytes.length, maxArrayLength: limits.items, maxMapLength: limits.items }) : cborDecoder(l).decode(bytes);
1848
+ } catch (e) {
1849
+ if (isOverflow(e)) throw tooDeep(limits);
1850
+ throw new CodecError(`not a ${FORMAT_LABELS[spec.format]} message: ${String(e?.message ?? e)}`);
1851
+ }
1852
+ bud.check();
1853
+ const out = plain(value, spec, bud);
1854
+ bud.check();
1855
+ return out;
1856
+ },
1857
+
1858
+ /** A value in, bytes (a Uint8Array) out; an error names the field path. */
1859
+ async encode(spec, value, { type } = {}) {
1860
+ check(spec);
1861
+ const limits = limitsOf(spec);
1862
+ const bud = budget(limits, now);
1863
+ let bytes;
1864
+ if (spec.format === "flatbuffers") {
1865
+ const c = await needFbs(spec, type);
1866
+ checkInput(value, bud);
1867
+ if (!isObject(value) || ArrayBuffer.isView(value) || value instanceof Date) throw new CodecError(`value: expected an object (${c.root}), got ${got(value)}`, { path: "value" });
1868
+ const json = fbsJson(value);
1869
+ const f = await flatcInstance();
1870
+ try {
1871
+ bytes = f.jsonToBinary(c.id, json);
1872
+ } catch (e) {
1873
+ if (flatcTrapped(e)) throw ranOut();
1874
+ const err = flatcError(e?.message);
1875
+ const path = err.column ? pathAtOffset(json, err.column - 1) : "value";
1876
+ throw new CodecError(`${path}: ${err.message}`, { path, errors: [{ message: `${path}: ${err.message}` }] });
1877
+ }
1878
+ } else if (spec.format === "protobuf") {
1879
+ const c = await needSchema(spec);
1880
+ const T = pickType(c, spec, type);
1881
+ const problems = [];
1882
+ const prepared = prepareMessage(T, value, spec, bud, "value", problems);
1883
+ if (problems.length) throw new CodecError(`${problems[0]}${problems.length > 1 ? ` (and ${problems.length - 1} more: ${problems.slice(1, 4).join("; ")}${problems.length > 4 ? "; …" : ""})` : ""}`, { path: problems[0].split(":")[0], errors: problems.slice(0, MAX_ERRORS).map((message) => ({ message })) });
1884
+ const message = T.fromObject(prepared);
1885
+ const bad = T.verify(message);
1886
+ if (bad) throw new CodecError(`value: ${bad}`);
1887
+ bytes = T.encode(message).finish();
1888
+ bytes = new Uint8Array(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength));
1889
+ } else if (spec.format === "capnp") {
1890
+ const c = await needSchema(spec);
1891
+ const name = pickCapnpType(c, spec, type);
1892
+ checkInput(value, bud);
1893
+ const l = await lib("capnp");
1894
+ try {
1895
+ bytes = l.encode(c, name, value, { packed: spec.packed === true, depth: limits.depth, items: limits.items, maxBytes: limits.bytes, binary: spec.binary ?? "bytes", bytesIn: (v) => bytesValue(v, spec) });
1896
+ } catch (e) {
1897
+ throw capnpError(e, "", limits);
1898
+ }
1899
+ } else if (spec.format === "avro") {
1900
+ const c = await needSchema(spec);
1901
+ const T = pickAvroType(c, spec, type);
1902
+ checkInput(value, bud);
1903
+ const problems = [];
1904
+ const out = sink(limits.bytes);
1905
+ if (!writeAvro(T, value, spec, bud, out, problems)) {
1906
+ const first = problems[0] ?? { path: "value", message: "value: can't be written for this schema" };
1907
+ throw new CodecError(`${first.message}${problems.length > 1 ? ` (and ${problems.length - 1} more: ${problems.slice(1, 4).map((p) => p.message).join("; ")}${problems.length > 4 ? "; …" : ""})` : ""}`, { path: first.path, errors: problems.map((p) => ({ message: p.message })) });
1908
+ }
1909
+ bytes = out.finish();
1910
+ } else if (spec.format === "struct") {
1911
+ const c = await needSchema(spec);
1912
+ const { size, fields } = c.struct;
1913
+ if (size > limits.bytes) throw new CodecError(`the layout is ${size} bytes; the limit is ${limits.bytes}`);
1914
+ if (fields.reduce((n, f) => n + (f.length ?? 1), 0) > limits.items) throw tooMany(limits);
1915
+ const problems = [];
1916
+ const known = new Set(fields.map((f) => f.name));
1917
+ if (!isObject(value) || ArrayBuffer.isView(value)) problems.push({ path: "value", message: `value: expected an object (the layout's fields), got ${got(value)}` });
1918
+ else {
1919
+ for (const key of Object.keys(value)) if (!known.has(key)) problems.push({ path: step("value", key), message: `${step("value", key)}: the layout has no field "${key}" (fields: ${[...known].join(", ")})` });
1920
+ for (const f of fields) {
1921
+ let v = value[f.name];
1922
+ if (v === undefined || v === null) {
1923
+ problems.push({ path: step("value", f.name), message: `${step("value", f.name)}: is missing (${f.type}${f.length ? `[${f.length}]` : ""})` });
1924
+ continue;
1925
+ }
1926
+ const longs = /^[iu]64/.test(f.type);
1927
+ const fix = (x) => (longs ? (intOf(x) ?? x) : x);
1928
+ v = f.length && Array.isArray(v) ? v.map(fix) : fix(v);
1929
+ try {
1930
+ c.singles.get(f.name).encode({ [f.name]: v });
1931
+ } catch (e) {
1932
+ const { name, text } = structComplaint(e.message);
1933
+ const path = step("value", name || f.name);
1934
+ problems.push({ path, message: `${path}: ${text}` });
1935
+ }
1936
+ }
1937
+ }
1938
+ if (problems.length) throw new CodecError(`${problems[0].message}${problems.length > 1 ? ` (and ${problems.length - 1} more: ${problems.slice(1, 4).map((p) => p.message).join("; ")}${problems.length > 4 ? "; …" : ""})` : ""}`, { path: problems[0].path, errors: problems.slice(0, MAX_ERRORS).map((p) => ({ message: p.message })) });
1939
+ const prepared = {};
1940
+ for (const f of fields) {
1941
+ const v = value[f.name];
1942
+ prepared[f.name] = /^[iu]64/.test(f.type) ? (f.length ? v.map((x) => intOf(x)) : intOf(v)) : v;
1943
+ }
1944
+ bytes = c.struct.encode(prepared);
1945
+ } else {
1946
+ checkInput(value, bud);
1947
+ const l = await lib(spec.format);
1948
+ try {
1949
+ const out = spec.format === "msgpack" ? l.encode(value, { ignoreUndefined: true, useBigInt64: true, maxDepth: limits.depth + 1 }) : cborEncoder(l).encode(value);
1950
+ bytes = new Uint8Array(out.buffer.slice(out.byteOffset, out.byteOffset + out.byteLength));
1951
+ } catch (e) {
1952
+ throw new CodecError(`value can't be encoded as ${FORMAT_LABELS[spec.format]}: ${String(e?.message ?? e)}`);
1953
+ }
1954
+ }
1955
+ if (bytes.length > limits.bytes) throw new CodecError(`the encoded message is ${bytes.length} bytes; the limit is ${limits.bytes}`);
1956
+ bud.check();
1957
+ return bytes;
1958
+ },
1959
+ };
1960
+ }
1961
+
1962
+ /** Did the engine run out of stack (a message nested far deeper than the limit that got past a scan)? */
1963
+ const isOverflow = (e) => e instanceof RangeError && /call stack/i.test(e.message);
1964
+
1965
+ const cborCache = new WeakMap();
1966
+ function cborDecoder(l) {
1967
+ if (!cborCache.has(l)) cborCache.set(l, { dec: new l.Decoder({ mapsAsObjects: true, useRecords: false }), enc: new l.Encoder({ useRecords: false, mapsAsObjects: true, variableMapSize: true }) });
1968
+ return cborCache.get(l).dec;
1969
+ }
1970
+ function cborEncoder(l) {
1971
+ cborDecoder(l);
1972
+ return cborCache.get(l).enc;
1973
+ }
1974
+
1975
+ /** A decoded protobuf message as plain data: bytes (a list of numbers from toObject) to the chosen binary form. */
1976
+ function plainProto(T, obj, spec, bud, depth = 0) {
1977
+ bud.tick();
1978
+ if (depth > bud.limits.depth) throw tooDeep(bud.limits);
1979
+ const out = {};
1980
+ for (const f of T.fieldsArray) {
1981
+ if (!(f.name in obj)) continue;
1982
+ const v = obj[f.name];
1983
+ const bytes = f.type === "bytes";
1984
+ const sub = f.resolvedType && !f.resolvedType.values ? f.resolvedType : null;
1985
+ const one = (x) => (x === null || x === undefined ? null : bytes ? binaryOf(Uint8Array.from(x), spec.binary ?? "bytes") : sub ? plainProto(sub, x, spec, bud, depth + 1) : x);
1986
+ if (v === null || v === undefined) setKey(out, f.name, null);
1987
+ else if (f.map) {
1988
+ const m = {};
1989
+ for (const k of Object.keys(v)) setKey(m, k, one(v[k]));
1990
+ setKey(out, f.name, m);
1991
+ } else if (f.repeated) setKey(out, f.name, v.map(one));
1992
+ else setKey(out, f.name, one(v));
1993
+ }
1994
+ return out;
1995
+ }
1996
+
1997
+ // ── codecs.<name> for pane code ──────────────────────────────────────────────
1998
+
1999
+ /**
2000
+ * The `codecs` object pane code sees: `codecs.<paneName>.decode(bytes)` / `.encode(value)` / `.analyze()` for each codec pane,
2001
+ * each returning a promise. `table()` is the current { name: spec | null } (null: two codec panes share the name); the
2002
+ * Worker replaces it when the canvas changes.
2003
+ */
2004
+ export function createCodecsObject(engine, table) {
2005
+ const api = (name, spec) =>
2006
+ Object.freeze({
2007
+ name,
2008
+ format: spec.format,
2009
+ type: spec.type ?? "",
2010
+ decode: (bytes, options) => engine.decode(spec, bytes, options),
2011
+ encode: (value, options) => engine.encode(spec, value, options),
2012
+ analyze: () => engine.analyze(spec),
2013
+ });
2014
+ const cache = new Map();
2015
+ const get = (name) => {
2016
+ const t = table();
2017
+ if (!Object.hasOwn(t, name)) throw new TypeError(`codecs.${name}: no codec pane is named "${name}"${Object.keys(t).length ? ` (codec panes: ${Object.keys(t).join(", ")})` : " (add a codec pane with + add)"}`);
2018
+ const spec = t[name];
2019
+ if (spec === null) throw new TypeError(`codecs.${name}: two codec panes are named "${name}": rename one`);
2020
+ const hit = cache.get(name);
2021
+ if (hit?.spec === spec) return hit.api;
2022
+ const made = api(name, spec);
2023
+ cache.set(name, { spec, api: made });
2024
+ return made;
2025
+ };
2026
+ const refuse = () => {
2027
+ throw new TypeError("codecs is read-only: a codec is a pane, change the pane");
2028
+ };
2029
+ return new Proxy(
2030
+ {},
2031
+ {
2032
+ set: refuse,
2033
+ defineProperty: refuse,
2034
+ deleteProperty: refuse,
2035
+ get: (_, key) => (typeof key === "string" ? get(key) : undefined),
2036
+ has: (_, key) => typeof key === "string" && Object.hasOwn(table(), key),
2037
+ ownKeys: () => Object.keys(table()),
2038
+ getOwnPropertyDescriptor: (_, key) => (typeof key === "string" && Object.hasOwn(table(), key) ? { enumerable: true, configurable: true, writable: false, value: table()[key] === null ? undefined : get(key) } : undefined),
2039
+ },
2040
+ );
2041
+ }
2042
+
2043
+ void proto;