@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,1410 @@
1
+ // DSP modules and the patch between them: the pure side (docs/guide/media-and-audio.md, "Patching DSP
2
+ // modules"). An audio pane normally holds Web Audio code; with a `dsp` patch it
3
+ // is built from modules instead: oscillators, filters, gains, envelopes,
4
+ // samples, delays and the person's own factories, wired by typed ports.
5
+ //
6
+ // This file decides everything that does not touch an AudioContext: what a
7
+ // module is, which ports it has, which connections are allowed (audio goes to
8
+ // audio, control to control; no instantaneous cycle: feedback needs a delay
9
+ // module), how a patch is cleaned and checked, how an edit is classified (a
10
+ // parameter value changes in place, anything else rebuilds) and a few edits
11
+ // as pure functions (the editor and the commands use them). The Web Audio
12
+ // side is src/audio/modules.js. Also loaded into the pane's frame as a module
13
+ // (`mallory:audio-patch`), so the frame and the tests share one
14
+ // implementation. No imports.
15
+ //
16
+ // A patch (the pane's `dsp`, JSON, saved with the pane):
17
+ //
18
+ // {
19
+ // version: 1,
20
+ // modules: [{ id, kind, label?, params?, options?, x?, y?,
21
+ // ports?, code?, breaksCycle? }], // ports/code/breaksCycle: kind "custom"
22
+ // connections: [{ from: "osc.out", to: "filt.in" }], // "<module id>.<port>"
23
+ // controls: [{ name: "cutoff", module: "filt", param: "frequency" }],
24
+ // meters: [{ name: "level", from: "env.out", every?: ms }], // values going out of the pane as events
25
+ // }
26
+ //
27
+ // A module of kind "macro" carries a sub-patch (`macro`); a custom or macro module may say where it was imported from (`from`).
28
+ //
29
+ // Port types: "audio" (a signal: node to node) and "control" (a value that
30
+ // drives an AudioParam: an envelope, an LFO, a constant). A numeric parameter
31
+ // of a module is also a control INPUT port of the same name, so
32
+ // `lfo.out -> filt.frequency` modulates the cutoff; the parameter's own value
33
+ // is its base, and what is connected adds to it.
34
+ //
35
+ // `controls` expose parameters to the outer canvas: a control named `cutoff`
36
+ // takes the pane's input of that name (a wire from a slider pane, say) and
37
+ // sets the parameter to it, clamped to its range, in place while playing.
38
+
39
+ export const DSP_VERSION = 1;
40
+
41
+ /** Sizes a patch may have. */
42
+ export const DSP_LIMITS = { modules: 64, connections: 256, controls: 32, code: 8000, label: 40, from: 80, meters: 8 };
43
+
44
+ const ID = /^[A-Za-z][A-Za-z0-9_-]{0,31}$/;
45
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]{0,31}$/; // a control's name: also a pane input's name
46
+ const PORT = /^[A-Za-z][A-Za-z0-9_]{0,31}$/;
47
+
48
+ // ── port types and channel counts ────────────────────────────────────────
49
+ // "audio" ordinary Web Audio (mono or stereo: the node's usual up/down-mixing)
50
+ // "audio:N" a bundle of exactly N discrete mono channels (N from 2 to MAX_CHANNELS), made by
51
+ // a combine module and taken apart by split or folded by mix; the channels are
52
+ // never mixed implicitly, so a connection must name the same N on both sides
53
+ // "control" a value that drives an AudioParam
54
+ // A patch without bundles uses only "audio" and "control", exactly as before.
55
+
56
+ /** The most channels a bundle may have. Web Audio guarantees 32 per node; the browser may allow more, but a patch can't rely on it. */
57
+ export const MAX_CHANNELS = 32;
58
+
59
+ /**
60
+ * The most voices a patch may ask for, and the most note events one delivery may carry (list items: a note with a
61
+ * `dur` is an on and an off, so up to twice as many are scheduled). Past `events` the rest are dropped and the pane's
62
+ * console says so; nothing else truncates. What bounds a long score is not this number but the pool: live, an event
63
+ * waits in a time-ordered queue and its graph is built LOOKAHEAD before it sounds (at most 2 x count graphs exist);
64
+ * offline, every note's graph is kept until the render ends (notes that start after the render's end are not built), and
65
+ * that is the real cost of one pass: measured, 1,500 notes over 46 s render in about 50 s and 3,000 over 152 s took 191 s on a loaded
66
+ * machine. So a render past plan.RENDER.over seconds is made in windows (src/audio/plan.js windowEvents), each holding only the notes
67
+ * that can be heard in it, and may be up to plan.LIMITS.duration long.
68
+ * 16,384 notes is about 45 minutes at 6 notes a second, past any song a canvas carries.
69
+ *
70
+ * `count` is 32 (it was 16 until the music follow-up, #1041 SYN-01): music-studio sounds 24 at once. A voice is native Web Audio
71
+ * nodes, and measured in headless Chromium (docs/grand-plan/music-studio-parity.md, SYN-01) 32 full synth voices with a
72
+ * chorus, an EQ and a reverb send per track render at about 12% of real time on one core; a voice built in an AudioWorklet
73
+ * instead cost 9 times as much, so the synth stays native.
74
+ */
75
+ export const VOICE_LIMITS = { count: 32, events: 16384 };
76
+
77
+ const TYPE = /^(audio|control|audio:([2-9]|[12][0-9]|3[0-2]))$/;
78
+
79
+ /** Is `type` a port type this mallory knows? */
80
+ export const isPortType = (type) => typeof type === "string" && TYPE.test(type);
81
+
82
+ /** The channel count of a bundle type, 0 for ordinary audio and for control. */
83
+ export const channelsOf = (type) => (typeof type === "string" && type.startsWith("audio:") ? Number(type.slice(6)) : 0);
84
+
85
+ /** The type of a bundle of `n` channels (n < 2 is ordinary audio). */
86
+ export const bundleType = (n) => (n >= 2 ? `audio:${n}` : "audio");
87
+
88
+ const perChannel = (n) => ({ in: { in: bundleType(n.channels) }, out: { out: bundleType(n.channels) } });
89
+ const processWhy = `1 is ordinary audio; 2 to ${MAX_CHANNELS} makes the module process a bundle of that many channels, each on its own`;
90
+ const channelWhy = `bundles run from 2 to ${MAX_CHANNELS} channels (Web Audio guarantees ${MAX_CHANNELS} channels per node; a browser may allow more but a patch can't rely on it)`;
91
+
92
+ /** Why a connection from a `from` type to a `to` type is refused ("" when the types fit). `a`, `b`: the endpoints, for the message. */
93
+ export function typeProblem(out, inn, a, b) {
94
+ if (out === inn) return "";
95
+ const co = channelsOf(out);
96
+ const ci = channelsOf(inn);
97
+ if (out === "control" || inn === "control") return `can't connect ${out} ${a} to ${inn} ${b}: audio goes to audio inputs and control to control inputs (parameters)`;
98
+ if (co && ci) return `can't connect ${a} (${co} channels) to ${b} (${ci} channels): channels are never mixed implicitly, so put a mix module (from ${co} to ${ci}) between them`;
99
+ if (co) return `can't connect ${a} (a bundle of ${co} channels) to ${b} (ordinary audio): take the bundle apart with a split module, or fold it down with a mix module set to 1`;
100
+ return `can't connect ${a} (ordinary audio) to ${b} (a bundle of ${ci} channels): join mono signals into a bundle with a combine module`;
101
+ }
102
+
103
+ const OSC_TYPES = ["sine", "square", "sawtooth", "triangle"];
104
+ const FILTER_TYPES = ["lowpass", "highpass", "bandpass", "notch", "allpass", "peaking", "lowshelf", "highshelf"];
105
+
106
+ // The ZzFX numbers a `zzfx` module has as parameters, in ZzFX order: [name, default, min, max]. src/audio/zzfx.js (the generator)
107
+ // holds the same table with the same ranges; a test checks they agree (this file has no imports: it loads into a frame as a module).
108
+ const ZZFX_PARAMS = [
109
+ ["volume", 1, 0, 10], ["randomness", 0.05, 0, 1], ["frequency", 220, 0, 20000], ["attack", 0, 0, 10], ["sustain", 0, 0, 10], ["release", 0.1, 0, 10], ["shape", 0, 0, 4],
110
+ ["shapeCurve", 1, 0, 10], ["slide", 0, -100, 100], ["deltaSlide", 0, -100, 100], ["pitchJump", 0, -5000, 5000], ["pitchJumpTime", 0, 0, 10], ["repeatTime", 0, 0, 10],
111
+ ["noise", 0, 0, 10], ["modulation", 0, 0, 1000], ["bitCrush", 0, 0, 1], ["delay", 0, 0, 10], ["sustainVolume", 1, 0, 10], ["decay", 0, 0, 10], ["tremolo", 0, 0, 1], ["filter", 0, -20000, 20000],
112
+ ];
113
+
114
+ /**
115
+ * The built-in kinds. `in` / `out`: ports by name -> type. `params`: numeric
116
+ * parameters, `{ def, min, max, control }` (control: also a control input port
117
+ * of the same name). `options`: `{ values }` (a choice), `{ bool }` or `{ text }`.
118
+ * `breaksCycle`: a feedback path through this module is allowed (it delays).
119
+ */
120
+ export const KINDS = {
121
+ oscillator: {
122
+ title: "oscillator",
123
+ help: "a tone: sine, square, sawtooth or triangle",
124
+ in: {},
125
+ out: { out: "audio" },
126
+ params: { frequency: { def: 440, min: 0.01, max: 24000, control: true }, detune: { def: 0, min: -4800, max: 4800, control: true } },
127
+ options: { type: { values: OSC_TYPES, def: "sine" } },
128
+ },
129
+ lfo: {
130
+ title: "LFO",
131
+ help: "a slow oscillator whose output is a control (depth × wave): connect it to a parameter",
132
+ in: {},
133
+ out: { out: "control" },
134
+ params: { frequency: { def: 2, min: 0.01, max: 200, control: true }, depth: { def: 1, min: 0, max: 20000, control: true } },
135
+ options: { type: { values: OSC_TYPES, def: "sine" } },
136
+ },
137
+ constant: {
138
+ title: "constant",
139
+ help: "a steady control value",
140
+ in: {},
141
+ out: { out: "control" },
142
+ params: { value: { def: 1, min: -20000, max: 20000, control: true } },
143
+ options: {},
144
+ },
145
+ noise: {
146
+ title: "noise",
147
+ help: "white noise from a seeded generator: the same seed gives the same samples, live and offline (each voice of a voiced patch gets its own sequence from it)",
148
+ in: {},
149
+ out: { out: "audio" },
150
+ params: { level: { def: 0.5, min: 0, max: 1, control: true } },
151
+ options: { seed: { int: { min: 0, max: 2147483647 }, def: 1, why: "a seed is a whole number from 0 to 2147483647" } },
152
+ },
153
+ envelope: {
154
+ title: "envelope",
155
+ help: "an ADSR control: rises when the sound starts, releases when it stops",
156
+ in: {},
157
+ out: { out: "control" },
158
+ params: { attack: { def: 0.01, min: 0, max: 20 }, decay: { def: 0.15, min: 0, max: 20 }, sustain: { def: 0.6, min: 0, max: 1 }, release: { def: 0.3, min: 0, max: 20 }, peak: { def: 1, min: -20000, max: 20000 } },
159
+ options: {},
160
+ },
161
+ filter: {
162
+ title: "filter",
163
+ help: "a biquad filter",
164
+ in: { in: "audio" },
165
+ out: { out: "audio" },
166
+ params: { frequency: { def: 1000, min: 10, max: 24000, control: true }, q: { def: 1, min: 0.0001, max: 1000, control: true }, gain: { def: 0, min: -40, max: 40, control: true } },
167
+ options: { type: { values: FILTER_TYPES, def: "lowpass" }, channels: { int: { min: 1, max: MAX_CHANNELS }, def: 1, why: processWhy } },
168
+ shape: perChannel,
169
+ },
170
+ gain: {
171
+ title: "gain",
172
+ help: "multiplies the signal (a control connected to gain moves it)",
173
+ in: { in: "audio" },
174
+ out: { out: "audio" },
175
+ params: { gain: { def: 1, min: -10, max: 10, control: true } },
176
+ options: { channels: { int: { min: 1, max: MAX_CHANNELS }, def: 1, why: processWhy } },
177
+ shape: perChannel,
178
+ },
179
+ delay: {
180
+ title: "delay",
181
+ help: "delays the signal; the only module a feedback path may go through",
182
+ in: { in: "audio" },
183
+ out: { out: "audio" },
184
+ params: { time: { def: 0.25, min: 0, max: 5, control: true } },
185
+ options: { channels: { int: { min: 1, max: MAX_CHANNELS }, def: 1, why: processWhy } },
186
+ shape: perChannel,
187
+ breaksCycle: true,
188
+ },
189
+ combine: {
190
+ title: "combine",
191
+ help: "joins N mono signals into one bundle of N discrete channels (in1 … inN → out)",
192
+ in: {},
193
+ out: {},
194
+ params: {},
195
+ options: { channels: { int: { min: 2, max: MAX_CHANNELS }, def: 2, why: channelWhy } },
196
+ shape: (n) => ({ in: Object.fromEntries(Array.from({ length: n.channels }, (_, i) => [`in${i + 1}`, "audio"])), out: { out: bundleType(n.channels) } }),
197
+ },
198
+ split: {
199
+ title: "split",
200
+ help: "takes a bundle of N channels apart into N mono outputs (in → out1 … outN)",
201
+ in: {},
202
+ out: {},
203
+ params: {},
204
+ options: { channels: { int: { min: 2, max: MAX_CHANNELS }, def: 2, why: channelWhy } },
205
+ shape: (n) => ({ in: { in: bundleType(n.channels) }, out: Object.fromEntries(Array.from({ length: n.channels }, (_, i) => [`out${i + 1}`, "audio"])) }),
206
+ },
207
+ mix: {
208
+ title: "mix",
209
+ help: "turns a bundle of `from` channels into `to` channels: channel i goes to output i mod `to` (folding down averages the channels that share an output; widening repeats channels); `to` 1 gives ordinary audio",
210
+ in: {},
211
+ out: {},
212
+ params: { gain: { def: 1, min: 0, max: 4, control: true } },
213
+ options: { from: { int: { min: 2, max: MAX_CHANNELS }, def: 4, why: channelWhy }, to: { int: { min: 1, max: MAX_CHANNELS }, def: 2, why: channelWhy } },
214
+ shape: (n) => ({ in: { in: bundleType(n.from) }, out: { out: bundleType(n.to) } }),
215
+ },
216
+ sample: {
217
+ title: "sample",
218
+ help: "plays an audio value (a WAV from another pane) that the pane takes as the input named in `input`; with `loop`, it repeats from `loopStart` to `loopEnd` (milliseconds; 0 and 0 repeat all of it)",
219
+ in: {},
220
+ out: { out: "audio" },
221
+ params: { rate: { def: 1, min: 0.0625, max: 16, control: true } },
222
+ options: { input: { text: true, def: "" }, loop: { bool: true, def: false }, loopStart: { int: { min: 0, max: 600000 }, def: 0, why: "a loop point is whole milliseconds from 0 to 600000" }, loopEnd: { int: { min: 0, max: 600000 }, def: 0, why: "a loop point is whole milliseconds from 0 to 600000 (0 loops to the end)" } },
223
+ },
224
+ zzfx: {
225
+ title: "ZzFX",
226
+ help: "a sound effect made from ZzFX's numbers (a pickup, a laser, an explosion): it plays once when the sound starts and again at every note; a changed number takes effect at the next play. The seed drives the randomness number: the same numbers and seed give the same samples",
227
+ in: {},
228
+ out: { out: "audio" },
229
+ params: Object.fromEntries(ZZFX_PARAMS.map(([name, def, min, max]) => [name, { def, min, max }])),
230
+ options: { seed: { int: { min: 0, max: 2147483647 }, def: 1, why: "a seed is a whole number from 0 to 2147483647" } },
231
+ },
232
+ output: {
233
+ title: "output",
234
+ help: "the pane's sound: the speakers, the scope and the render",
235
+ in: { in: "audio" },
236
+ out: {},
237
+ params: { gain: { def: 1, min: 0, max: 4, control: false } },
238
+ options: { channels: { int: { min: 1, max: 2 }, def: 1, why: "the pane's sound goes out on a mono or stereo bus: 1 is ordinary audio and 2 sends a two-channel bundle's channels to the left and the right; fold a larger bundle down with a mix module first" } },
239
+ shape: (n) => ({ in: { in: bundleType(n.channels) }, out: {} }),
240
+ },
241
+ custom: {
242
+ title: "custom",
243
+ help: "a factory written in JavaScript that runs in the pane's frame: its code returns the nodes behind the ports it declares",
244
+ in: {},
245
+ out: {},
246
+ params: {},
247
+ options: {},
248
+ dynamic: true,
249
+ },
250
+ macro: {
251
+ title: "macro",
252
+ help: "a module whose definition is a sub-patch: its ports and exposed parameters stand for modules inside it (macros nest)",
253
+ in: {},
254
+ out: {},
255
+ params: {},
256
+ options: {},
257
+ dynamic: true,
258
+ macro: true,
259
+ },
260
+ };
261
+
262
+ export const KIND_NAMES = Object.keys(KINDS);
263
+
264
+ /** The starting code of a new custom module. */
265
+ export const CUSTOM_CODE = `// A module factory. \`ctx\` is the AudioContext; \`params\` are this module's numbers.
266
+ // Return the nodes behind the ports you declared (audio ports are AudioNodes,
267
+ // control ports AudioParams), and optionally start/stop/update/dispose.
268
+ const amp = ctx.createGain();
269
+ amp.gain.value = params.gain;
270
+ return {
271
+ inputs: { in: amp },
272
+ outputs: { out: amp },
273
+ params: { gain: amp.gain },
274
+ };`;
275
+
276
+ /** A new macro's starting definition: a gain inside, its in / out and gain exposed. */
277
+ export const MACRO_STARTER = { modules: [{ id: "amp", kind: "gain" }], connections: [], ports: { in: { in: "amp.in" }, out: { out: "amp.out" } }, params: { gain: "amp.gain" } };
278
+
279
+ /** A new custom module's declaration. */
280
+ export const CUSTOM_PORTS = { in: { in: "audio" }, out: { out: "audio" } };
281
+
282
+ const isObject = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
283
+ const clamp = (n, min, max) => Math.min(max, Math.max(min, n)); // a copy on purpose: this module is loaded as text into the audio frame, and may import nothing
284
+
285
+ /** An integer option's value: the one given if it is a whole number inside its range, else the default. */
286
+ const intOption = (o, v) => (Number.isInteger(v) && v >= o.int.min && v <= o.int.max ? v : o.def);
287
+
288
+ /** A module's spec: its kind's, or for a custom module the one its declaration makes. */
289
+ export function specOf(module) {
290
+ const spec = KINDS[module?.kind];
291
+ if (!spec) return undefined;
292
+ if (spec.shape) {
293
+ const n = {};
294
+ for (const [name, o] of Object.entries(spec.options)) if (o.int) n[name] = intOption(o, module.options?.[name]);
295
+ return { ...spec, ...spec.shape(n) };
296
+ }
297
+ if (!spec.dynamic) return spec;
298
+ if (spec.macro) return macroSpec(spec, module);
299
+ const params = {};
300
+ for (const [name, v] of Object.entries(module.params ?? {})) params[name] = { def: Number(v) || 0, min: -1e6, max: 1e6, control: false };
301
+ return { ...spec, in: { ...(module.ports?.in ?? {}) }, out: { ...(module.ports?.out ?? {}) }, params, breaksCycle: Boolean(module.breaksCycle) };
302
+ }
303
+
304
+ /**
305
+ * A module's ports, `{ in: { name: type }, out: { name: type } }`: the spec's
306
+ * audio and control ports, plus a control input for every numeric parameter
307
+ * that takes one.
308
+ */
309
+ export function portsOf(module) {
310
+ const spec = specOf(module);
311
+ if (!spec) return { in: {}, out: {} };
312
+ const inPorts = { ...spec.in };
313
+ for (const [name, p] of Object.entries(spec.params)) if (p.control && !(name in inPorts)) inPorts[name] = "control";
314
+ return { in: inPorts, out: { ...spec.out } };
315
+ }
316
+
317
+ /** Does a path through this module delay (so a feedback cycle through it is fine)? */
318
+ export const breaksCycle = (module) => Boolean(specOf(module)?.breaksCycle);
319
+
320
+ /** `"osc.out"` -> `{ module: "osc", port: "out" }`, or null. */
321
+ export function parseEndpoint(text) {
322
+ const m = /^([A-Za-z][A-Za-z0-9_-]{0,31})\.([A-Za-z][A-Za-z0-9_]{0,31})$/.exec(String(text));
323
+ return m ? { module: m[1], port: m[2] } : null;
324
+ }
325
+
326
+ const moduleById = (dsp, id) => dsp.modules.find((m) => m.id === id);
327
+
328
+ /** The value of a module's parameter: the one it has, or its default. */
329
+ export function paramValue(module, name) {
330
+ const p = specOf(module)?.params[name];
331
+ if (!p) return undefined;
332
+ const n = Number(module.params?.[name]);
333
+ return Number.isFinite(n) ? clamp(n, p.min, p.max) : p.def;
334
+ }
335
+
336
+ /** The value of a module's option: the one it has (if valid), or its default. */
337
+ export function optionValue(module, name) {
338
+ const o = specOf(module)?.options[name];
339
+ if (!o) return undefined;
340
+ const v = module.options?.[name];
341
+ if (o.values) return o.values.includes(v) ? v : o.def;
342
+ if (o.int) return intOption(o, v);
343
+ if (o.bool) return typeof v === "boolean" ? v : o.def;
344
+ return typeof v === "string" ? v.slice(0, 64) : o.def;
345
+ }
346
+
347
+ // ── voices ───────────────────────────────────────────────────────────────
348
+ // `voices` turns the whole patch into a voice template: each note builds its own
349
+ // copy of the patch (envelopes, oscillators, custom modules and all), so every voice
350
+ // has independent state. docs/guide/media-and-audio.md, "Voices". Pure here: the allocation policy and the
351
+ // note events; the Web Audio side (building, gating and disposing copies) is the voice
352
+ // pool in src/audio/modules.js.
353
+ //
354
+ // voices: { count: 4, steal: "oldest", repeat: "retrigger", input: "notes",
355
+ // note: "osc.frequency", velocity: "amp.gain", mix: "mix" }
356
+ // `instruments` names the pane input that carries a score's own instruments (`score.mallory.instruments`, a score pane's `instruments` output):
357
+ // with it set, a note event's `instrument` picks the sound (src/audio/instruments.js) and the patch itself plays notes that name none.
358
+ // `mix` names the pane input that carries an effects-rack mix (src/audio/rack.js; a score pane's `mix` output): a note event with a
359
+ // `track` is then played through that track's strip (volume, pan, inserts, sends), live and in a render.
360
+
361
+ export const STEAL = {
362
+ oldest: "when every voice is busy, take the one whose note began first (a voice that is already releasing is taken before any held one)",
363
+ quietest: "when every voice is busy, take the quietest (a voice that is already releasing first, then the lowest velocity; ties go to the oldest)",
364
+ none: "when every voice is held, drop the new note (a voice that is only releasing is still taken)",
365
+ };
366
+ export const REPEAT = {
367
+ retrigger: "a note that is already held restarts its own voice (the envelope attacks again)",
368
+ stack: "a note that is already held gets another voice; each note-off releases the oldest held voice of that note",
369
+ ignore: "a note that is already held is dropped",
370
+ };
371
+ export const VOICE_DEFAULTS = { count: 4, steal: "oldest", repeat: "retrigger", input: "notes" };
372
+
373
+ /** The first problem with a `voices` setting ("" when it is fine). `modules`: the patch's, to check the targets. */
374
+ export function voicesProblem(v, modules) {
375
+ if (!isObject(v)) return "voices must be an object { count, steal?, repeat?, input?, note?, velocity? }";
376
+ for (const key of Object.keys(v)) if (!["count", "steal", "repeat", "input", "note", "velocity", "mix", "instruments"].includes(key)) return `voices has no field "${key}"`;
377
+ if (!Number.isInteger(v.count) || v.count < 1 || v.count > VOICE_LIMITS.count) return `voices.count must be a whole number from 1 to ${VOICE_LIMITS.count} (each voice is a full copy of the patch, so the number is bounded)`;
378
+ if (v.steal !== undefined && !(v.steal in STEAL)) return `voices.steal must be one of ${Object.keys(STEAL).join(", ")}`;
379
+ if (v.repeat !== undefined && !(v.repeat in REPEAT)) return `voices.repeat must be one of ${Object.keys(REPEAT).join(", ")}`;
380
+ if (v.input !== undefined && (typeof v.input !== "string" || !NAME.test(v.input))) return "voices.input must be a plain name (the pane input that carries the note events)";
381
+ if (v.mix !== undefined && (typeof v.mix !== "string" || !NAME.test(v.mix))) return "voices.mix must be a plain name (the pane input that carries the effects-rack mix)";
382
+ if (v.instruments !== undefined && (typeof v.instruments !== "string" || !NAME.test(v.instruments))) return "voices.instruments must be a plain name (the pane input that carries the score's instruments)";
383
+ for (const key of ["note", "velocity"]) {
384
+ if (v[key] === undefined) continue;
385
+ const e = typeof v[key] === "string" ? parseEndpoint(v[key]) : null;
386
+ if (!e) return `voices.${key} must be "<module>.<parameter>"`;
387
+ const m = (modules ?? []).find((x) => x.id === e.module);
388
+ if (!m) return `voices.${key}: no module "${e.module}"`;
389
+ if (!(e.port in specOf(m).params)) return `voices.${key}: ${m.kind} "${m.id}" has no parameter "${e.port}" (it has ${Object.keys(specOf(m).params).join(", ") || "none"})`;
390
+ }
391
+ return "";
392
+ }
393
+
394
+ /** `voices` with defaults filled in and a fixed key order. */
395
+ export function cleanVoices(v) {
396
+ const out = { count: v.count, steal: v.steal ?? VOICE_DEFAULTS.steal, repeat: v.repeat ?? VOICE_DEFAULTS.repeat, input: v.input ?? VOICE_DEFAULTS.input };
397
+ if (v.note) out.note = v.note;
398
+ if (v.velocity) out.velocity = v.velocity;
399
+ if (v.mix) out.mix = v.mix;
400
+ if (v.instruments) out.instruments = v.instruments;
401
+ return out;
402
+ }
403
+
404
+ /** The frequency of MIDI note `n` (A4 = 69 = 440 Hz, equal temperament). */
405
+ export const noteToHz = (n) => 440 * 2 ** ((n - 69) / 12);
406
+
407
+ /**
408
+ * How long a voice keeps sounding after its note-off: the longest envelope release
409
+ * in the patch (×1.5 for the exponential tail, as the envelope's own stop) plus 50 ms;
410
+ * with no envelope the voice fades in 50 ms. Seconds.
411
+ */
412
+ export function voiceTail(dsp) {
413
+ let release = 0;
414
+ for (const m of dsp.modules) if (m.kind === "envelope") release = Math.max(release, paramValue(m, "release"));
415
+ let tail = release * 1.5 + 0.05;
416
+ for (const m of dsp.modules) if (m.kind === "zzfx") tail = Math.max(tail, zzfxSeconds(m) + 0.05); // a ZzFX sound ends by itself: the voice waits for it
417
+ return tail;
418
+ }
419
+
420
+ /** Does any module of the patch release by itself (an envelope)? Otherwise a voice's output fades. */
421
+ export const hasEnvelope = (dsp) => dsp.modules.some((m) => m.kind === "envelope" || m.kind === "zzfx");
422
+
423
+ /** How long a zzfx module's sound is, in seconds (its envelope's lengths added up; 9 samples of attack are ignored). */
424
+ export const zzfxSeconds = (m) => ["attack", "decay", "sustain", "release", "delay"].reduce((n, name) => n + paramValue(m, name), 0);
425
+
426
+ const SEMITONES = { c: 0, d: 2, e: 4, f: 5, g: 7, a: 9, b: 11 };
427
+
428
+ /** A note as a MIDI number: a number (or numeric text) as it is, a name such as "C4", "F#3" or "Bb2" (C4 is 60, A4 is 69); anything else is NaN. */
429
+ export function noteNumber(value) {
430
+ if (typeof value === "string") {
431
+ const m = /^\s*([A-Ga-g])([#b]?)(-?\d{1,2})\s*$/.exec(value);
432
+ if (m) return 12 * (Number(m[3]) + 1) + SEMITONES[m[1].toLowerCase()] + (m[2] === "#" ? 1 : m[2] === "b" ? -1 : 0);
433
+ }
434
+ return Number(value);
435
+ }
436
+
437
+ /**
438
+ * The note events in a value delivered to the pane's `voices.input`, as a sorted
439
+ * list `[{ type: "on" | "off" | "allOff", note, velocity, time }]` plus the problems
440
+ * found (a bad event is skipped, never guessed). An event is one of
441
+ * { note, velocity?, time?, dur?, params? } a note (a number, or a name such as "C4"): on at `time`, off after `dur` (if given); `params`:
442
+ * { "module.param": number } sets parameters for this voice alone (per-voice modulation)
443
+ * { on: true|false, note, velocity?, time? } a note-on / note-off
444
+ * { type: "on" | "off" | "allOff", … } the same, spelled out
445
+ * { type: "bend", value, track?, time? } pitch bend of a score track's voices, value -1..1 of the wheel (0 centred)
446
+ * or an array of them. `time`: seconds, from when the pane starts sounding
447
+ * (offline: from 0); an event without one happens at once. Velocity 0..1 (a
448
+ * note-on with velocity 0 is a note-off, as in MIDI). Events are ordered by time,
449
+ * then offs before ons, then as given: the same events always give the same order.
450
+ */
451
+ export function noteEvents(value) {
452
+ const list = Array.isArray(value) ? value : value === undefined || value === null ? [] : [value];
453
+ const events = [];
454
+ const problems = [];
455
+ if (list.length > VOICE_LIMITS.events) problems.push(`more than ${VOICE_LIMITS.events} note events at once: the rest are ignored`);
456
+ const at = (e, i, extra) => ({ ...extra, order: i });
457
+ for (const [i, e] of list.slice(0, VOICE_LIMITS.events).entries()) {
458
+ if (!isObject(e)) {
459
+ problems.push(`event ${i + 1} is not an object`);
460
+ continue;
461
+ }
462
+ const ghost = e.ghost === true ? { ghost: true } : {}; // a window of a render: this note is only for the allocator (src/audio/plan.js windowEvents)
463
+ const time = e.time === undefined ? 0 : Number(e.time);
464
+ if (!Number.isFinite(time) || time < 0) {
465
+ problems.push(`event ${i + 1}: time must be seconds, 0 or more`);
466
+ continue;
467
+ }
468
+ if (e.type === "bend") {
469
+ const value = Number(e.value);
470
+ if (!Number.isFinite(value) || value < -1 || value > 1) {
471
+ problems.push(`event ${i + 1}: a bend's value must be from -1 to 1`);
472
+ continue;
473
+ }
474
+ const track = typeof e.track === "string" && e.track && e.track.length <= 64 ? { track: e.track } : {};
475
+ events.push(at(e, i, { type: "bend", value, time, ...track, ...ghost }));
476
+ continue;
477
+ }
478
+ let type = e.type === "allOff" || e.type === "allNotesOff" ? "allOff" : e.type === "off" || e.type === "noteOff" || e.on === false ? "off" : e.type === "on" || e.type === "noteOn" || e.on === true || e.type === undefined ? "on" : null;
479
+ if (!type) {
480
+ problems.push(`event ${i + 1}: type must be on, off or allOff`);
481
+ continue;
482
+ }
483
+ if (type === "allOff") {
484
+ events.push(at(e, i, { type, time, ...ghost }));
485
+ continue;
486
+ }
487
+ const note = noteNumber(e.note ?? e.pitch);
488
+ if (!Number.isFinite(note) || note < 0 || note > 127 || e.note === null) {
489
+ problems.push(`event ${i + 1}: note must be a number from 0 to 127`);
490
+ continue;
491
+ }
492
+ const velocity = e.velocity === undefined ? 1 : Number(e.velocity);
493
+ if (!Number.isFinite(velocity) || velocity < 0 || velocity > 1) {
494
+ problems.push(`event ${i + 1}: velocity must be from 0 to 1`);
495
+ continue;
496
+ }
497
+ if (type === "on" && velocity === 0) type = "off";
498
+ let params;
499
+ if (type === "on" && e.params !== undefined) {
500
+ const entries = isObject(e.params) ? Object.entries(e.params) : null;
501
+ if (!entries || entries.length > 8 || entries.some(([k, v]) => !parseEndpoint(k) || typeof v !== "number" || !Number.isFinite(v))) {
502
+ problems.push(`event ${i + 1}: params must be up to 8 of { "module.param": number }`);
503
+ continue;
504
+ }
505
+ params = Object.fromEntries(entries);
506
+ }
507
+ const track = typeof e.track === "string" && e.track && e.track.length <= 64 ? { track: e.track } : {}; // the score track a note belongs to: its strip in the effects rack (src/audio/rack.js)
508
+ const instrument = type === "on" && typeof e.instrument === "string" && e.instrument && e.instrument.length <= 64 ? { instrument: e.instrument } : {}; // its track's instrument (src/audio/instruments.js)
509
+ const serial = type === "on" && Number.isSafeInteger(e.serial) && e.serial >= 0 ? { serial: e.serial } : {}; // a render's window says which note of the whole render this is (src/audio/plan.js windowEvents)
510
+ events.push(at(e, i, { type, note, velocity: type === "on" ? velocity : 0, time, ...track, ...instrument, ...serial, ...ghost, ...(params ? { params } : {}) }));
511
+ if (type === "on" && e.dur !== undefined) {
512
+ const dur = Number(e.dur);
513
+ if (!Number.isFinite(dur) || dur <= 0) problems.push(`event ${i + 1}: dur must be seconds above 0`);
514
+ else events.push(at(e, i, { type: "off", note, velocity: 0, time: time + dur, ...track, ...ghost, order: i + 0.5 }));
515
+ }
516
+ }
517
+ const rank = { allOff: 0, off: 0, bend: 0.5, on: 1 };
518
+ events.sort((a, b) => a.time - b.time || rank[a.type] - rank[b.type] || a.order - b.order);
519
+ return { events: events.map(({ order, ...e }) => e), problems };
520
+ }
521
+
522
+ /**
523
+ * The voice allocator: which of `count` voices a note takes, decided by the declared
524
+ * policy and nothing else (no clock, no randomness), so the same events in the same
525
+ * order always give the same voices, live and offline. Voices are slots 0..count-1,
526
+ * each `free`, `held` (its note is down) or `releasing` (its note-off came less than
527
+ * `tail` seconds ago). Methods take the event's time (seconds, never going back).
528
+ *
529
+ * noteOn -> { action: "start" | "retrigger" | "ignored", voice, stole? }
530
+ * `start`: the voice must be built (or rebuilt) for the note; `stole`: { voice, note }
531
+ * the voice it took from; `retrigger`: the held voice plays its note again;
532
+ * `ignored`: the repeat rule or a full "none" policy dropped it (with `why`).
533
+ * Free voices go to the lowest slot first.
534
+ */
535
+ export function createAllocator({ count, steal = "oldest", repeat = "retrigger", tail = 0.05 }) {
536
+ const voices = Array.from({ length: count }, (_, voice) => ({ voice, state: "free", note: null, velocity: 0, seq: 0, startedAt: 0, releasedAt: 0 }));
537
+ let seq = 0;
538
+ let tailNow = tail;
539
+ const sweep = (time) => {
540
+ const freed = [];
541
+ for (const v of voices) {
542
+ if (v.state === "releasing" && time >= v.releasedAt + tailNow) {
543
+ Object.assign(v, { note: null, velocity: 0, state: "free" });
544
+ freed.push(v.voice);
545
+ }
546
+ }
547
+ return freed;
548
+ };
549
+ const take = (v, note, velocity, time) => Object.assign(v, { state: "held", note, velocity, seq: ++seq, startedAt: time });
550
+ const victim = () => {
551
+ const busy = voices.filter((v) => v.state !== "free");
552
+ const releasing = busy.filter((v) => v.state === "releasing").sort((a, b) => a.releasedAt - b.releasedAt || a.seq - b.seq);
553
+ if (releasing.length) return releasing[0];
554
+ if (steal === "quietest") return [...busy].sort((a, b) => a.velocity - b.velocity || a.seq - b.seq)[0];
555
+ return [...busy].sort((a, b) => a.seq - b.seq)[0];
556
+ };
557
+ return {
558
+ sweep,
559
+ noteOn(note, velocity, time) {
560
+ sweep(time);
561
+ const same = voices.filter((v) => v.note === note && v.state === "held");
562
+ if (same.length && repeat === "ignore") return { action: "ignored", why: `note ${note} is already held (repeat: ignore)` };
563
+ if (same.length && repeat === "retrigger") {
564
+ const v = same.sort((a, b) => a.seq - b.seq)[0];
565
+ take(v, note, velocity, time);
566
+ return { action: "retrigger", voice: v.voice };
567
+ }
568
+ // A releasing voice of the same note can't be restarted (its sources are already scheduled to stop): it is replaced.
569
+ const free = voices.find((v) => v.state === "free");
570
+ if (free) {
571
+ take(free, note, velocity, time);
572
+ return { action: "start", voice: free.voice };
573
+ }
574
+ if (steal === "none" && !voices.some((x) => x.state === "releasing")) return { action: "ignored", why: `all ${count} voices are held (steal: none)` };
575
+ const v = victim();
576
+ const stole = { voice: v.voice, note: v.note };
577
+ take(v, note, velocity, time);
578
+ return { action: "start", voice: v.voice, stole };
579
+ },
580
+ /** Release the oldest held voice of `note`: { voice } or null (no such note is held). */
581
+ noteOff(note, time) {
582
+ sweep(time);
583
+ const v = voices.filter((x) => x.note === note && x.state === "held").sort((a, b) => a.seq - b.seq)[0];
584
+ if (!v) return null;
585
+ Object.assign(v, { state: "releasing", releasedAt: time });
586
+ return { voice: v.voice };
587
+ },
588
+ /** Every busy voice, back to free at once (stop, a rebuild): the voices that were busy. */
589
+ reset() {
590
+ const busy = voices.filter((v) => v.state !== "free").map((v) => v.voice);
591
+ for (const v of voices) Object.assign(v, { note: null, velocity: 0, state: "free" });
592
+ return busy;
593
+ },
594
+ /** Every held voice released (all notes off): the voices released. */
595
+ allOff(time) {
596
+ sweep(time);
597
+ const out = [];
598
+ for (const v of voices) if (v.state === "held") (Object.assign(v, { state: "releasing", releasedAt: time }), out.push(v.voice));
599
+ return out;
600
+ },
601
+ /** A voice may ring longer than the patch's own envelopes say (another instrument's release): the tail only grows. */
602
+ setTail(t) {
603
+ if (t > tailNow) tailNow = t;
604
+ },
605
+ get snapshot() {
606
+ return voices.map((v) => ({ voice: v.voice, state: v.state, note: v.note, velocity: v.velocity }));
607
+ },
608
+ get busy() {
609
+ return voices.filter((v) => v.state !== "free").length;
610
+ },
611
+ };
612
+ }
613
+
614
+ // ── macro modules: a module whose definition is a sub-patch ───────────────
615
+ // A `macro` module carries `macro: { modules, connections, ports, params }`, a patch of its own:
616
+ // ports.in / ports.out { name: "<inner module>.<port>" } the macro's ports stand for inner ports (their types are the inner ports')
617
+ // params { name: "<inner module>.<param>" } parameters the macro exposes (and, when the inner one takes a
618
+ // control, a control input port of the same name)
619
+ // The macro module's own `params` set those exposed parameters per use; everything else inside is the definition's. A
620
+ // definition may hold macros (to MACRO_LIMITS.depth). Nothing but this file knows about macros: before a patch is built,
621
+ // `flattenDsp` replaces every macro with its modules (ids `<macro>__<inner>`) and rewrites the connections, controls, voices
622
+ // and meters that named the macro's ports, so the graph, the build order and the change classification are the ones of the
623
+ // flat patch. A loop through a macro needs its delay outside the macro (the macro counts as one module without a delay).
624
+
625
+ /** How deep macros nest, how big a patch may be once they are expanded, and how many ports a macro may have. */
626
+ export const MACRO_LIMITS = { depth: 3, modules: 256, connections: 1024, ports: 32 };
627
+ const FLAT_SEP = "__";
628
+ const splitEndpoint = (endpoint) => [endpoint.slice(0, endpoint.lastIndexOf(".")), endpoint.slice(endpoint.lastIndexOf(".") + 1)];
629
+
630
+ /** A macro module's spec: ports and parameters read through its definition. */
631
+ function macroSpec(spec, module) {
632
+ const def = module.macro;
633
+ const inner = new Map((def?.modules ?? []).map((m) => [m.id, m]));
634
+ const side = (map, dir) => {
635
+ const out = {};
636
+ for (const [name, endpoint] of Object.entries(map ?? {})) {
637
+ const e = parseEndpoint(endpoint);
638
+ const t = e && inner.has(e.module) ? portsOf(inner.get(e.module))[dir][e.port] : undefined;
639
+ if (t) out[name] = t;
640
+ }
641
+ return out;
642
+ };
643
+ const params = {};
644
+ for (const [name, endpoint] of Object.entries(def?.params ?? {})) {
645
+ const e = parseEndpoint(endpoint);
646
+ const m = e && inner.get(e.module);
647
+ const p = m && specOf(m)?.params[e.port];
648
+ if (p) params[name] = { def: paramValue(m, e.port), min: p.min, max: p.max, control: p.control };
649
+ }
650
+ return { ...spec, in: side(def?.ports?.in, "in"), out: side(def?.ports?.out, "out"), params, breaksCycle: false };
651
+ }
652
+
653
+ /** The first problem with a macro module's definition ("" when it is fine). `depth`: 1 for a macro in the patch itself. */
654
+ function macroProblem(m, depth) {
655
+ const where = `macro "${m.id}"`;
656
+ const def = m.macro;
657
+ if (!isObject(def)) return `${where}: needs a definition { modules, connections, ports, params }`;
658
+ if (depth > MACRO_LIMITS.depth) return `${where}: macros nest at most ${MACRO_LIMITS.depth} deep`;
659
+ for (const key of Object.keys(def)) if (!["modules", "connections", "ports", "params"].includes(key)) return `${where}: the definition has no field "${key}"`;
660
+ const modules = def.modules ?? [];
661
+ const connections = def.connections ?? [];
662
+ if (!Array.isArray(modules) || !Array.isArray(connections)) return `${where}: modules and connections must be lists`;
663
+ if (modules.length > DSP_LIMITS.modules) return `${where}: at most ${DSP_LIMITS.modules} modules inside`;
664
+ if (connections.length > DSP_LIMITS.connections) return `${where}: at most ${DSP_LIMITS.connections} connections inside`;
665
+ const ids = new Set();
666
+ for (const [i, x] of modules.entries()) {
667
+ const p = moduleProblem(x, i, depth);
668
+ if (p) return `${where}: ${p}`;
669
+ if (x.kind === "output") return `${where}: an output module stays outside a macro (its sound leaves through an out port)`;
670
+ if (ids.has(x.id)) return `${where}: two modules are called "${x.id}"`;
671
+ ids.add(x.id);
672
+ }
673
+ const c = connectionsProblem(modules, connections);
674
+ if (c) return `${where}: ${c}`;
675
+ const ports = def.ports ?? {};
676
+ if (!isObject(ports)) return `${where}: ports must be { in: { name: "<module>.<port>" }, out: {…} }`;
677
+ for (const key of Object.keys(ports)) if (key !== "in" && key !== "out") return `${where}: ports has no "${key}" (only in and out)`;
678
+ const byId = new Map(modules.map((x) => [x.id, x]));
679
+ const names = new Set();
680
+ let count = 0;
681
+ for (const dir of ["in", "out"]) {
682
+ const side = ports[dir] ?? {};
683
+ if (!isObject(side)) return `${where}: ports.${dir} must be an object of name -> "<module>.<port>"`;
684
+ for (const [name, endpoint] of Object.entries(side)) {
685
+ if (!PORT.test(name)) return `${where}: port name "${name}" is not a plain name`;
686
+ const e = typeof endpoint === "string" ? parseEndpoint(endpoint) : null;
687
+ if (!e) return `${where}: port "${name}" must name an inner port as "<module>.<port>"`;
688
+ const x = byId.get(e.module);
689
+ if (!x) return `${where}: port "${name}": no module "${e.module}" inside`;
690
+ if (!portsOf(x)[dir][e.port]) return `${where}: port "${name}": "${endpoint}" is not ${dir === "in" ? "an input" : "an output"} of ${x.kind} "${x.id}"`;
691
+ if (dir === "in") names.add(name);
692
+ count += 1;
693
+ }
694
+ }
695
+ const exposed = def.params ?? {};
696
+ if (!isObject(exposed)) return `${where}: params must be an object of name -> "<module>.<parameter>"`;
697
+ for (const [name, endpoint] of Object.entries(exposed)) {
698
+ if (!PORT.test(name)) return `${where}: parameter name "${name}" is not a plain name`;
699
+ if (names.has(name)) return `${where}: "${name}" is both an in port and a parameter`;
700
+ const e = typeof endpoint === "string" ? parseEndpoint(endpoint) : null;
701
+ const x = e && byId.get(e.module);
702
+ if (!x) return `${where}: parameter "${name}" must name an inner parameter as "<module>.<parameter>"`;
703
+ if (!(e.port in specOf(x).params)) return `${where}: parameter "${name}": ${x.kind} "${x.id}" has no parameter "${e.port}"`;
704
+ count += 1;
705
+ }
706
+ if (count > MACRO_LIMITS.ports) return `${where}: at most ${MACRO_LIMITS.ports} ports and parameters`;
707
+ return "";
708
+ }
709
+
710
+ /** One macro module expanded: its modules (ids `<macro id>__<inner id>`), connections and where its ports and parameters land. `deep`: macros inside expand too. */
711
+ function expandMacro(m, deep) {
712
+ const def = m.macro;
713
+ const modules = [];
714
+ const connections = [];
715
+ const sub = new Map(); // inner macro id -> its expansion (deep only)
716
+ for (const inner of def.modules ?? []) {
717
+ const id = `${m.id}${FLAT_SEP}${inner.id}`;
718
+ if (inner.kind === "macro" && deep) {
719
+ const x = expandMacro({ ...inner, id }, true);
720
+ modules.push(...x.modules);
721
+ connections.push(...x.connections);
722
+ sub.set(inner.id, x);
723
+ } else {
724
+ const { x: _x, y: _y, ...rest } = inner;
725
+ modules.push({ ...rest, id, ...(rest.params ? { params: { ...rest.params } } : {}) });
726
+ }
727
+ }
728
+ const flat = (endpoint, kind) => {
729
+ const [module, port] = splitEndpoint(endpoint);
730
+ const x = sub.get(module);
731
+ if (!x) return `${m.id}${FLAT_SEP}${module}.${port}`;
732
+ return kind === "out" ? x.outs[port] : (x.ins[port] ?? x.params[port]);
733
+ };
734
+ for (const c of def.connections ?? []) connections.push({ from: flat(c.from, "out"), to: flat(c.to, "in") });
735
+ const ins = {};
736
+ const outs = {};
737
+ const params = {};
738
+ for (const [name, endpoint] of Object.entries(def.ports?.in ?? {})) ins[name] = flat(endpoint, "in");
739
+ for (const [name, endpoint] of Object.entries(def.ports?.out ?? {})) outs[name] = flat(endpoint, "out");
740
+ for (const [name, endpoint] of Object.entries(def.params ?? {})) {
741
+ const [module, port] = splitEndpoint(endpoint);
742
+ params[name] = sub.get(module) ? sub.get(module).params[port] : `${m.id}${FLAT_SEP}${module}.${port}`;
743
+ }
744
+ // The values this use of the macro gives its exposed parameters become the inner modules' own.
745
+ for (const name of Object.keys(m.params ?? {})) {
746
+ if (!(name in params)) continue;
747
+ const [module, port] = splitEndpoint(params[name]);
748
+ const target = modules.find((x) => x.id === module);
749
+ if (target) target.params = { ...(target.params ?? {}), [port]: paramValue(m, name) };
750
+ }
751
+ return { modules, connections, ins, outs, params };
752
+ }
753
+
754
+ /** `dsp` with the macro `onlyId` (or, without it, every macro) expanded; `deep`: macros inside expand too. The same object when there is nothing to expand. */
755
+ function expand(dsp, onlyId, deep) {
756
+ const wanted = (m) => m.kind === "macro" && (!onlyId || m.id === onlyId);
757
+ if (!dsp.modules.some(wanted)) return dsp;
758
+ const expansions = new Map();
759
+ const modules = [];
760
+ const connections = [];
761
+ for (const m of dsp.modules) {
762
+ if (!wanted(m)) {
763
+ modules.push(m);
764
+ continue;
765
+ }
766
+ const x = expandMacro(m, deep);
767
+ expansions.set(m.id, x);
768
+ modules.push(...x.modules);
769
+ connections.push(...x.connections);
770
+ }
771
+ const through = (endpoint, kind) => {
772
+ const [module, port] = splitEndpoint(endpoint);
773
+ const x = expansions.get(module);
774
+ if (!x) return endpoint;
775
+ return (kind === "out" ? x.outs[port] : (x.ins[port] ?? x.params[port])) ?? endpoint;
776
+ };
777
+ const param = (endpoint) => {
778
+ const [module, port] = splitEndpoint(endpoint);
779
+ return expansions.get(module)?.params[port] ?? endpoint;
780
+ };
781
+ for (const c of dsp.connections ?? []) connections.push({ from: through(c.from, "out"), to: through(c.to, "in") });
782
+ const controls = (dsp.controls ?? []).map((c) => {
783
+ const target = expansions.get(c.module)?.params[c.param];
784
+ if (!target) return c;
785
+ const [module, port] = splitEndpoint(target);
786
+ return { ...c, module, param: port };
787
+ });
788
+ const out = { ...dsp, modules, connections, controls };
789
+ if (dsp.meters) out.meters = dsp.meters.map((x) => ({ ...x, from: through(x.from, "out") }));
790
+ if (dsp.voices) out.voices = Object.fromEntries(Object.entries(dsp.voices).map(([k, v]) => [k, k === "note" || k === "velocity" ? param(v) : v]));
791
+ const aliases = { ...(dsp.aliases ?? {}) };
792
+ for (const [id, x] of expansions) for (const [name, target] of Object.entries(x.params)) aliases[`${id}.${name}`] = target;
793
+ out.aliases = aliases;
794
+ return out;
795
+ }
796
+
797
+ /**
798
+ * The patch with every macro replaced by its modules, ids `<macro>__<inner>`, and the connections, controls, voices and meters that
799
+ * named a macro's ports rewritten to the modules behind them (`aliases`: "macro.param" -> the flat parameter, for automation and per-note
800
+ * parameters). Not a patch to save: the one the builders (src/audio/modules.js) and the change classification work on. The same object when
801
+ * there are no macros.
802
+ */
803
+ export const flattenDsp = (dsp) => expand(dsp, null, true);
804
+
805
+ /** The problem with the flat form of a patch that has macros ("" when it is fine): every id still a name, nothing too big. */
806
+ function flatProblem(modules, connections, controls) {
807
+ let flat;
808
+ try {
809
+ flat = flattenDsp({ modules, connections, controls });
810
+ } catch (error) {
811
+ return `a macro can't be expanded: ${error.message}`;
812
+ }
813
+ if (flat.modules.length > MACRO_LIMITS.modules) return `the patch has ${flat.modules.length} modules once its macros are expanded (at most ${MACRO_LIMITS.modules})`;
814
+ if (flat.connections.length > MACRO_LIMITS.connections) return `the patch has ${flat.connections.length} connections once its macros are expanded (at most ${MACRO_LIMITS.connections})`;
815
+ const ids = new Set();
816
+ for (const m of flat.modules) {
817
+ if (!ID.test(m.id)) return `a macro's inner module becomes "${m.id}" (ids inside a macro are written <macro>${FLAT_SEP}<inner>), which is longer than 32 characters or not a name: shorten the ids`;
818
+ if (ids.has(m.id)) return `two modules end up called "${m.id}" once the macros are expanded: rename one`;
819
+ ids.add(m.id);
820
+ }
821
+ return "";
822
+ }
823
+
824
+ /** A new patch with the modules `ids` grouped into one macro; throws why not. Connections that cross the boundary become the macro's ports; a control on a grouped parameter becomes a parameter of the macro. */
825
+ export function groupModules(dsp, ids, { id, label } = {}) {
826
+ const picked = new Set(ids);
827
+ if (!picked.size) throw new Error("pick the modules to group first");
828
+ for (const i of picked) {
829
+ const m = moduleById(dsp, i);
830
+ if (!m) throw new Error(`no module "${i}"`);
831
+ if (m.kind === "output") throw new Error("the output module stays outside a macro (its sound leaves through an out port)");
832
+ }
833
+ const made = id ?? freshId(dsp, "macro");
834
+ const inside = dsp.modules.filter((m) => picked.has(m.id));
835
+ const ports = { in: {}, out: {} };
836
+ const exposed = {};
837
+ const taken = new Set();
838
+ const nameFor = (endpoint) => {
839
+ const base = endpoint.replace(/[^A-Za-z0-9_]/g, "_").slice(0, 28);
840
+ let name = base;
841
+ for (let n = 2; taken.has(name); n++) name = `${base}${n}`;
842
+ taken.add(name);
843
+ return name;
844
+ };
845
+ const once = (map, endpoint, into) => {
846
+ if (!map.has(endpoint)) {
847
+ const name = nameFor(endpoint);
848
+ map.set(endpoint, name);
849
+ into[name] = endpoint;
850
+ }
851
+ return map.get(endpoint);
852
+ };
853
+ const inPort = new Map();
854
+ const outPort = new Map();
855
+ const paramOf = new Map();
856
+ const innerConnections = [];
857
+ const connections = [];
858
+ for (const c of dsp.connections) {
859
+ const a = parseEndpoint(c.from);
860
+ const b = parseEndpoint(c.to);
861
+ const aIn = picked.has(a.module);
862
+ const bIn = picked.has(b.module);
863
+ if (aIn && bIn) innerConnections.push({ from: c.from, to: c.to });
864
+ else if (bIn) connections.push({ from: c.from, to: `${made}.${once(inPort, c.to, ports.in)}` });
865
+ else if (aIn) connections.push({ from: `${made}.${once(outPort, c.from, ports.out)}`, to: c.to });
866
+ else connections.push(c);
867
+ }
868
+ const controls = dsp.controls.map((c) => (picked.has(c.module) ? { ...c, module: made, param: once(paramOf, `${c.module}.${c.param}`, exposed) } : c));
869
+ const meters = (dsp.meters ?? []).map((x) => (picked.has(parseEndpoint(x.from).module) ? { ...x, from: `${made}.${once(outPort, x.from, ports.out)}` } : x));
870
+ const voices = dsp.voices ? Object.fromEntries(Object.entries(dsp.voices).map(([k, v]) => [k, (k === "note" || k === "velocity") && picked.has(parseEndpoint(v)?.module) ? `${made}.${once(paramOf, v, exposed)}` : v])) : undefined;
871
+ const first = inside.find((m) => Number.isFinite(m.x) && Number.isFinite(m.y));
872
+ const macro = { id: made, kind: "macro", ...(label ? { label } : {}), macro: { modules: inside.map(({ x: _x, y: _y, ...m }) => m), connections: innerConnections, ports, params: exposed }, ...(first ? { x: first.x, y: first.y } : {}) };
873
+ const at = dsp.modules.findIndex((m) => picked.has(m.id));
874
+ const modules = dsp.modules.filter((m) => !picked.has(m.id));
875
+ modules.splice(at, 0, macro);
876
+ return cleanDsp({ ...dsp, modules, connections, controls, ...(dsp.meters ? { meters } : {}), ...(voices ? { voices } : {}) });
877
+ }
878
+
879
+ /** A new patch with macro `id` replaced by the modules inside it (ids `<macro>__<inner>`; macros inside stay macros); its connections, controls and voices follow. */
880
+ export function ungroupMacro(dsp, id) {
881
+ const m = moduleById(dsp, id);
882
+ if (!m) throw new Error(`no module "${id}"`);
883
+ if (m.kind !== "macro") throw new Error(`${m.kind} "${id}" is not a macro`);
884
+ const { aliases: _aliases, ...rest } = expand(dsp, id, false);
885
+ return cleanDsp(rest);
886
+ }
887
+
888
+ // ── checking and cleaning ─────────────────────────────────────────────────
889
+
890
+ function portsProblem(ports, where) {
891
+ if (!isObject(ports)) return `${where}: ports must be { in: {name: "audio"|"control"|"audio:N"}, out: {…} }`;
892
+ for (const dir of ["in", "out"]) {
893
+ const side = ports[dir] ?? {};
894
+ if (!isObject(side)) return `${where}: ports.${dir} must be an object of name -> "audio", "control" or "audio:N"`;
895
+ for (const [name, type] of Object.entries(side)) {
896
+ if (!PORT.test(name)) return `${where}: port name "${name}" is not a plain name`;
897
+ if (!isPortType(type)) return `${where}: port "${name}" is "${type}", not "audio", "control" or "audio:N" (${channelWhy})`;
898
+ }
899
+ }
900
+ return "";
901
+ }
902
+
903
+ /** The first problem with one module as written ("" when it is fine). */
904
+ function moduleProblem(m, index, depth = 0) {
905
+ const where = `module ${index + 1}`;
906
+ if (!isObject(m)) return `${where} is not an object`;
907
+ if (typeof m.id !== "string" || !ID.test(m.id)) return `${where}: id must be a name of letters, digits, - and _ (starting with a letter)`;
908
+ if (!KINDS[m.kind]) return `module "${m.id}": unknown kind "${m.kind}" (one of ${KIND_NAMES.join(", ")})`;
909
+ if (m.label !== undefined && (typeof m.label !== "string" || m.label.length > DSP_LIMITS.label)) return `module "${m.id}": label must be text up to ${DSP_LIMITS.label} characters`;
910
+ for (const key of ["x", "y"]) if (m[key] !== undefined && !Number.isFinite(m[key])) return `module "${m.id}": ${key} must be a number`;
911
+ if (m.params !== undefined && !isObject(m.params)) return `module "${m.id}": params must be an object of numbers`;
912
+ if (m.options !== undefined && !isObject(m.options)) return `module "${m.id}": options must be an object`;
913
+ const custom = m.kind === "custom";
914
+ if (!custom && (m.ports !== undefined || m.code !== undefined || m.breaksCycle !== undefined)) return `module "${m.id}": ports, code and breaksCycle belong to a custom module`;
915
+ if (m.kind !== "macro" && m.macro !== undefined) return `module "${m.id}": a definition (macro) belongs to a macro module`;
916
+ if (m.from !== undefined && !(custom || m.kind === "macro")) return `module "${m.id}": from (where a shared module came from) belongs to a custom or macro module`;
917
+ if (m.from !== undefined && (typeof m.from !== "string" || !m.from.trim() || m.from.length > DSP_LIMITS.from)) return `module "${m.id}": from must be text up to ${DSP_LIMITS.from} characters`;
918
+ if (m.kind === "macro") {
919
+ const p = macroProblem(m, depth + 1);
920
+ if (p) return p;
921
+ }
922
+ if (custom) {
923
+ if (typeof m.code !== "string" || !m.code.trim()) return `module "${m.id}": a custom module needs code`;
924
+ if (m.code.length > DSP_LIMITS.code) return `module "${m.id}": code is longer than ${DSP_LIMITS.code} characters`;
925
+ const p = portsProblem(m.ports ?? { in: {}, out: {} }, `module "${m.id}"`);
926
+ if (p) return p;
927
+ if (m.breaksCycle !== undefined && typeof m.breaksCycle !== "boolean") return `module "${m.id}": breaksCycle must be true or false`;
928
+ }
929
+ const spec = specOf(m);
930
+ for (const [name, v] of Object.entries(m.params ?? {})) {
931
+ if (!(name in spec.params)) return `module "${m.id}" (${m.kind}) has no parameter "${name}" (it has ${Object.keys(spec.params).join(", ") || "none"})`;
932
+ if (typeof v !== "number" || !Number.isFinite(v)) return `module "${m.id}": parameter "${name}" must be a finite number`;
933
+ }
934
+ for (const [name, v] of Object.entries(m.options ?? {})) {
935
+ const o = spec.options[name];
936
+ if (!o) return `module "${m.id}" (${m.kind}) has no option "${name}" (it has ${Object.keys(spec.options).join(", ") || "none"})`;
937
+ if (o.values && !o.values.includes(v)) return `module "${m.id}": option "${name}" must be one of ${o.values.join(", ")}`;
938
+ if (o.int && !(Number.isInteger(v) && v >= o.int.min && v <= o.int.max)) return `module "${m.id}": option "${name}" is ${JSON.stringify(v)}, not a whole number from ${o.int.min} to ${o.int.max}: ${o.why}`;
939
+ if (o.bool && typeof v !== "boolean") return `module "${m.id}": option "${name}" must be true or false`;
940
+ if (o.text && (typeof v !== "string" || v.length > 64)) return `module "${m.id}": option "${name}" must be text up to 64 characters`;
941
+ }
942
+ return "";
943
+ }
944
+
945
+ /**
946
+ * Why `from` -> `to` can't be added to `dsp` ("" when it can): unknown module
947
+ * or port, wrong direction, audio into control (or the other way round), the
948
+ * same connection twice, or an instantaneous cycle (feedback needs a delay).
949
+ */
950
+ export function connectionProblem(dsp, from, to) {
951
+ const a = parseEndpoint(from);
952
+ const b = parseEndpoint(to);
953
+ if (!a) return `"${from}" is not a port (write <module>.<port>)`;
954
+ if (!b) return `"${to}" is not a port (write <module>.<port>)`;
955
+ const ma = moduleById(dsp, a.module);
956
+ const mb = moduleById(dsp, b.module);
957
+ if (!ma) return `no module "${a.module}"`;
958
+ if (!mb) return `no module "${b.module}"`;
959
+ const out = portsOf(ma).out[a.port];
960
+ if (!out) return `"${from}" is not an output of ${ma.kind} "${ma.id}" (its outputs: ${Object.keys(portsOf(ma).out).join(", ") || "none"})`;
961
+ const inn = portsOf(mb).in[b.port];
962
+ if (!inn) return `"${to}" is not an input of ${mb.kind} "${mb.id}" (its inputs: ${Object.keys(portsOf(mb).in).join(", ") || "none"})`;
963
+ const mismatch = typeProblem(out, inn, from, to);
964
+ if (mismatch) return mismatch;
965
+ if ((dsp.connections ?? []).some((c) => c.from === from && c.to === to)) return `${from} -> ${to} is already connected`;
966
+ const cycle = findCycle({ ...dsp, connections: [...(dsp.connections ?? []), { from, to }] });
967
+ if (cycle) return cycleMessage(cycle);
968
+ return "";
969
+ }
970
+
971
+ const cycleMessage = (cycle) => `${cycle.join(" -> ")} is a cycle with no delay: signals can't feed back instantly, so route the feedback through a delay module`;
972
+
973
+ /**
974
+ * An instantaneous cycle in the patch, as a list of module ids (the first
975
+ * repeated at the end), or null. A connection that leaves a delay module
976
+ * isn't followed (a delay is what makes feedback legal, as in Pure Data).
977
+ */
978
+ export function findCycle(dsp) {
979
+ const mods = new Map((dsp.modules ?? []).map((m) => [m.id, m]));
980
+ const next = new Map();
981
+ for (const c of dsp.connections ?? []) {
982
+ const a = parseEndpoint(c.from);
983
+ const b = parseEndpoint(c.to);
984
+ if (!a || !b || !mods.has(a.module) || !mods.has(b.module)) continue;
985
+ if (breaksCycle(mods.get(a.module))) continue;
986
+ if (!next.has(a.module)) next.set(a.module, []);
987
+ next.get(a.module).push(b.module);
988
+ }
989
+ const state = new Map(); // 1: on the path, 2: done
990
+ const path = [];
991
+ const visit = (id) => {
992
+ state.set(id, 1);
993
+ path.push(id);
994
+ for (const to of next.get(id) ?? []) {
995
+ if (state.get(to) === 1) return [...path.slice(path.indexOf(to)), to];
996
+ if (!state.has(to)) {
997
+ const found = visit(to);
998
+ if (found) return found;
999
+ }
1000
+ }
1001
+ path.pop();
1002
+ state.set(id, 2);
1003
+ return null;
1004
+ };
1005
+ for (const m of dsp.modules ?? []) if (!state.has(m.id)) {
1006
+ const found = visit(m.id);
1007
+ if (found) return found;
1008
+ }
1009
+ return null;
1010
+ }
1011
+
1012
+ /** The first problem with a list of connections between `modules` ("" when it is fine): one at a time, so it names the first bad one (and a cycle, the connection that closes it). */
1013
+ function connectionsProblem(modules, connections) {
1014
+ const so_far = { modules, connections: [] };
1015
+ for (const [i, c] of connections.entries()) {
1016
+ if (!isObject(c) || typeof c.from !== "string" || typeof c.to !== "string") return `connection ${i + 1} must be { from: "<module>.<port>", to: "<module>.<port>" }`;
1017
+ const p = connectionProblem(so_far, c.from, c.to);
1018
+ if (p) return `connection ${i + 1}: ${p}`;
1019
+ so_far.connections.push({ from: c.from, to: c.to });
1020
+ }
1021
+ return "";
1022
+ }
1023
+
1024
+ /** The first problem with a patch as written ("" when it is fine): its shape, then every connection and control, then cycles. */
1025
+ export function dspProblem(raw) {
1026
+ if (!isObject(raw)) return "dsp must be an object { modules, connections, controls }";
1027
+ for (const key of Object.keys(raw)) if (!["version", "modules", "connections", "controls", "meters", "voices"].includes(key)) return `dsp has no field "${key}"`;
1028
+ if (raw.version !== undefined && raw.version !== DSP_VERSION) return `dsp version ${raw.version} isn't one this mallory reads (it reads ${DSP_VERSION})`;
1029
+ const modules = raw.modules ?? [];
1030
+ const connections = raw.connections ?? [];
1031
+ const controls = raw.controls ?? [];
1032
+ if (!Array.isArray(modules)) return "dsp.modules must be a list";
1033
+ if (!Array.isArray(connections)) return "dsp.connections must be a list";
1034
+ if (!Array.isArray(controls)) return "dsp.controls must be a list";
1035
+ if (modules.length > DSP_LIMITS.modules) return `a patch has at most ${DSP_LIMITS.modules} modules`;
1036
+ if (connections.length > DSP_LIMITS.connections) return `a patch has at most ${DSP_LIMITS.connections} connections`;
1037
+ if (controls.length > DSP_LIMITS.controls) return `a patch has at most ${DSP_LIMITS.controls} controls`;
1038
+ const ids = new Set();
1039
+ for (const [i, m] of modules.entries()) {
1040
+ const p = moduleProblem(m, i);
1041
+ if (p) return p;
1042
+ if (ids.has(m.id)) return `two modules are called "${m.id}"`;
1043
+ ids.add(m.id);
1044
+ }
1045
+ const wiring = connectionsProblem(modules, connections);
1046
+ if (wiring) return wiring;
1047
+ const names = new Set();
1048
+ for (const [i, c] of controls.entries()) {
1049
+ if (!isObject(c)) return `control ${i + 1} must be { name, module, param }`;
1050
+ if (typeof c.name !== "string" || !NAME.test(c.name)) return `control ${i + 1}: name must be a plain name (it is also the pane input that sets it)`;
1051
+ if (names.has(c.name)) return `two controls are called "${c.name}"`;
1052
+ names.add(c.name);
1053
+ const m = modules.find((x) => x.id === c.module);
1054
+ if (!m) return `control "${c.name}": no module "${c.module}"`;
1055
+ if (!(c.param in specOf(m).params)) return `control "${c.name}": ${m.kind} "${m.id}" has no parameter "${c.param}"`;
1056
+ }
1057
+ if (modules.some((m) => m.kind === "macro")) {
1058
+ const flat = flatProblem(modules, connections, controls);
1059
+ if (flat) return flat;
1060
+ }
1061
+ if (raw.meters !== undefined) {
1062
+ const p = metersProblem(raw.meters, modules);
1063
+ if (p) return p;
1064
+ if (raw.voices !== undefined && raw.meters.length) return "meters read one graph, and a voiced patch builds a copy per note: remove the voices or the meters";
1065
+ }
1066
+ if (raw.voices !== undefined) return voicesProblem(raw.voices, modules);
1067
+ return "";
1068
+ }
1069
+
1070
+ // ── meters: values going out of the pane ──────────────────────────────────
1071
+ // `meters: [{ name, from: "<module>.<output port>", every?: ms }]` tap an output port (an envelope's level, a filter's output) and
1072
+ // send what it carries out of the pane as an event named `name`, `{ value, peak, rms }`, at most every `every` ms (50 by default)
1073
+ // and only when it changed. The pane needs an event output of that name (the editor adds one with the meter). Live only: a render
1074
+ // has no listeners. docs/guide/media-and-audio.md, "Patching DSP modules".
1075
+
1076
+ export const METER_EVERY = { min: 20, max: 1000, def: 50 };
1077
+
1078
+ function metersProblem(meters, modules) {
1079
+ if (!Array.isArray(meters)) return "dsp.meters must be a list";
1080
+ if (meters.length > DSP_LIMITS.meters) return `a patch has at most ${DSP_LIMITS.meters} meters`;
1081
+ const names = new Set();
1082
+ for (const [i, x] of meters.entries()) {
1083
+ if (!isObject(x)) return `meter ${i + 1} must be { name, from, every? }`;
1084
+ for (const key of Object.keys(x)) if (!["name", "from", "every"].includes(key)) return `meter ${i + 1} has no field "${key}"`;
1085
+ if (typeof x.name !== "string" || !NAME.test(x.name)) return `meter ${i + 1}: name must be a plain name (it is also the pane's event output)`;
1086
+ if (names.has(x.name)) return `two meters are called "${x.name}"`;
1087
+ names.add(x.name);
1088
+ const e = typeof x.from === "string" ? parseEndpoint(x.from) : null;
1089
+ if (!e) return `meter "${x.name}": from must be "<module>.<output port>"`;
1090
+ const m = modules.find((y) => y.id === e.module);
1091
+ if (!m) return `meter "${x.name}": no module "${e.module}"`;
1092
+ if (!portsOf(m).out[e.port]) return `meter "${x.name}": "${x.from}" is not an output of ${m.kind} "${m.id}" (its outputs: ${Object.keys(portsOf(m).out).join(", ") || "none"})`;
1093
+ if (x.every !== undefined && !(Number.isInteger(x.every) && x.every >= METER_EVERY.min && x.every <= METER_EVERY.max)) return `meter "${x.name}": every must be a whole number of milliseconds from ${METER_EVERY.min} to ${METER_EVERY.max}`;
1094
+ }
1095
+ return "";
1096
+ }
1097
+
1098
+ /** One module cleaned (a macro's inner modules too): only the known fields, every number inside its range, in a fixed key order. */
1099
+ function cleanModule(m) {
1100
+ const spec = specOf(m);
1101
+ const out = { id: m.id, kind: m.kind };
1102
+ if (m.label) out.label = m.label;
1103
+ const params = {};
1104
+ for (const name of Object.keys(spec.params)) if (m.params && name in m.params) params[name] = paramValue(m, name);
1105
+ if (Object.keys(params).length) out.params = params;
1106
+ const options = {};
1107
+ for (const name of Object.keys(spec.options)) if (m.options && name in m.options) options[name] = optionValue(m, name);
1108
+ if (Object.keys(options).length) out.options = options;
1109
+ if (m.kind === "custom") {
1110
+ out.ports = { in: { ...(m.ports?.in ?? {}) }, out: { ...(m.ports?.out ?? {}) } };
1111
+ out.code = m.code;
1112
+ if (m.breaksCycle) out.breaksCycle = true;
1113
+ }
1114
+ if (m.kind === "macro") {
1115
+ out.macro = {
1116
+ modules: (m.macro.modules ?? []).map(cleanModule),
1117
+ connections: (m.macro.connections ?? []).map((c) => ({ from: c.from, to: c.to })),
1118
+ ports: { in: { ...(m.macro.ports?.in ?? {}) }, out: { ...(m.macro.ports?.out ?? {}) } },
1119
+ params: { ...(m.macro.params ?? {}) },
1120
+ };
1121
+ }
1122
+ if (m.from) out.from = m.from;
1123
+ if (Number.isFinite(m.x)) out.x = Math.round(m.x);
1124
+ if (Number.isFinite(m.y)) out.y = Math.round(m.y);
1125
+ return out;
1126
+ }
1127
+
1128
+ /** A patch cleaned: only the known fields, every number inside its range, in a fixed key order. Throws what `dspProblem` says. */
1129
+ export function cleanDsp(raw) {
1130
+ const problem = dspProblem(raw);
1131
+ if (problem) throw new Error(problem);
1132
+ const modules = (raw.modules ?? []).map(cleanModule);
1133
+ const out = {
1134
+ version: DSP_VERSION,
1135
+ modules,
1136
+ connections: (raw.connections ?? []).map((c) => ({ from: c.from, to: c.to })),
1137
+ controls: (raw.controls ?? []).map((c) => ({ name: c.name, module: c.module, param: c.param })),
1138
+ };
1139
+ if (raw.meters?.length) out.meters = raw.meters.map((x) => ({ name: x.name, from: x.from, ...(x.every !== undefined && x.every !== METER_EVERY.def ? { every: x.every } : {}) }));
1140
+ if (raw.voices !== undefined) out.voices = cleanVoices(raw.voices);
1141
+ return out;
1142
+ }
1143
+
1144
+ // ── what a patch sounds like: values, structure, topology ────────────────
1145
+
1146
+ /**
1147
+ * Every parameter's value now, `{ "<module>.<param>": number }`: the module's
1148
+ * own, with each control replaced by the pane's input of its name when that is
1149
+ * a finite number (clamped to the parameter's range).
1150
+ */
1151
+ export function effectiveParams(dsp, inputs = {}) {
1152
+ const out = {};
1153
+ for (const m of dsp.modules) for (const name of Object.keys(specOf(m).params)) out[`${m.id}.${name}`] = paramValue(m, name);
1154
+ for (const c of dsp.controls ?? []) {
1155
+ const m = moduleById(dsp, c.module);
1156
+ const p = m && specOf(m).params[c.param];
1157
+ const v = inputs?.[c.name];
1158
+ if (p && typeof v === "number" && Number.isFinite(v)) out[`${c.module}.${c.param}`] = clamp(v, p.min, p.max);
1159
+ }
1160
+ return out;
1161
+ }
1162
+
1163
+ /**
1164
+ * What makes two patches the same graph: modules (kind, options, a custom
1165
+ * module's code and ports; not parameter values, positions or labels),
1166
+ * connections and controls. A different key means the graph is rebuilt; the
1167
+ * same key with other parameter values is changed in place.
1168
+ */
1169
+ export function structureKey(dsp) {
1170
+ if (!dsp) return "";
1171
+ return JSON.stringify([
1172
+ dsp.modules.map((m) => [m.id, m.kind, specOf(m) ? Object.keys(specOf(m).options).map((o) => optionValue(m, o)) : [], m.kind === "custom" ? [m.code, m.ports, Boolean(m.breaksCycle), Object.keys(m.params ?? {}).sort()] : m.kind === "macro" ? [m.macro] : 0]),
1173
+ [...dsp.connections].map((c) => `${c.from}>${c.to}`).sort(),
1174
+ (dsp.controls ?? []).map((c) => [c.name, c.module, c.param]),
1175
+ ...(dsp.meters?.length ? [dsp.meters] : []), // a patch without meters keeps the key it always had
1176
+ ...(dsp.voices ? [dsp.voices] : []), // a patch without voices keeps the key it always had
1177
+ ]);
1178
+ }
1179
+
1180
+ /**
1181
+ * What changed from patch `a` (with inputs `ia`) to patch `b` (`ib`):
1182
+ * `{ structure: true }` when the graph differs (rebuild), else `{ structure:
1183
+ * false, params: [{ module, param, value }] }`, the parameters whose value
1184
+ * differs (set in place), possibly none.
1185
+ */
1186
+ export function dspChange(a, ia, b, ib) {
1187
+ if (structureKey(a) !== structureKey(b)) return { structure: true, params: [] };
1188
+ const before = effectiveParams(a, ia);
1189
+ const after = effectiveParams(b, ib);
1190
+ const params = [];
1191
+ for (const [key, value] of Object.entries(after)) {
1192
+ if (Object.is(before[key], value)) continue;
1193
+ const dot = key.indexOf(".");
1194
+ params.push({ module: key.slice(0, dot), param: key.slice(dot + 1), value });
1195
+ }
1196
+ return { structure: false, params };
1197
+ }
1198
+
1199
+ /**
1200
+ * What the live graph depends on besides its structure: every parameter's value
1201
+ * now, and for a voiced patch the note events the pane was given. A different key
1202
+ * means `apply` has something to do.
1203
+ */
1204
+ export const liveKey = (dsp, inputs = {}) => JSON.stringify([effectiveParams(dsp, inputs), dsp.voices ? (inputs?.[dsp.voices.input] ?? null) : null, ...(dsp.voices?.mix ? [inputs?.[dsp.voices.mix] ?? null] : []), ...(dsp.voices?.instruments ? [inputs?.[dsp.voices.instruments] ?? null] : [])]);
1205
+
1206
+ /** The connections as sorted "from>to" lines: a build's intended topology, the same live and offline. */
1207
+ export const topology = (dsp) => dsp.connections.map((c) => `${c.from}>${c.to}`).sort();
1208
+
1209
+ /**
1210
+ * The connections in the order a build makes them: by destination, then by source. Several outputs into one input
1211
+ * are summed by Web Audio, and floating-point addition depends on the order (a+b)+c versus (a+c)+b, so the order
1212
+ * is fixed here instead of left to how the patch happens to list them (structureKey sorts them too: a reordered
1213
+ * list is the same patch, is not rebuilt, and must also sound the same).
1214
+ */
1215
+ export const connectionOrder = (dsp) => [...dsp.connections].sort((x, y) => (x.to < y.to ? -1 : x.to > y.to ? 1 : x.from < y.from ? -1 : x.from > y.from ? 1 : 0));
1216
+
1217
+ /**
1218
+ * The order to build modules in: sources first, following the connections that
1219
+ * aren't feedback (those leaving a delay are ignored), ties in the patch's own
1220
+ * order. Deterministic, so a live and an offline build make the same nodes in
1221
+ * the same order.
1222
+ */
1223
+ export function buildOrder(dsp) {
1224
+ const mods = dsp.modules;
1225
+ const index = new Map(mods.map((m, i) => [m.id, i]));
1226
+ const indegree = new Map(mods.map((m) => [m.id, 0]));
1227
+ const next = new Map(mods.map((m) => [m.id, []]));
1228
+ for (const c of dsp.connections) {
1229
+ const a = parseEndpoint(c.from);
1230
+ const b = parseEndpoint(c.to);
1231
+ if (breaksCycle(mods[index.get(a.module)])) continue;
1232
+ next.get(a.module).push(b.module);
1233
+ indegree.set(b.module, indegree.get(b.module) + 1);
1234
+ }
1235
+ const ready = mods.filter((m) => indegree.get(m.id) === 0).map((m) => m.id);
1236
+ const out = [];
1237
+ while (ready.length) {
1238
+ ready.sort((x, y) => index.get(x) - index.get(y));
1239
+ const id = ready.shift();
1240
+ out.push(id);
1241
+ for (const to of next.get(id)) {
1242
+ indegree.set(to, indegree.get(to) - 1);
1243
+ if (indegree.get(to) === 0) ready.push(to);
1244
+ }
1245
+ }
1246
+ // Modules left (only possible past a delay that closes a loop): in the patch's order.
1247
+ for (const m of mods) if (!out.includes(m.id)) out.push(m.id);
1248
+ return out;
1249
+ }
1250
+
1251
+ /** A warning (not an error: it renders silence) for a patch with no output module. */
1252
+ export function outputProblem(dsp) {
1253
+ if (!dsp.modules.some((m) => m.kind === "output")) return "the patch has no output module: nothing would be heard (add one and connect it)";
1254
+ return "";
1255
+ }
1256
+
1257
+ // ── editing, as pure functions ────────────────────────────────────────────
1258
+
1259
+ /** An unused module id for `kind`: "oscillator", "oscillator2", … */
1260
+ export function freshId(dsp, kind) {
1261
+ const taken = new Set(dsp.modules.map((m) => m.id));
1262
+ if (!taken.has(kind)) return kind;
1263
+ for (let n = 2; ; n++) if (!taken.has(`${kind}${n}`)) return `${kind}${n}`;
1264
+ }
1265
+
1266
+ /** A new patch with a module added (default parameters); returns `{ dsp, id }`. */
1267
+ export function addModule(dsp, kind, { id, label, params, options } = {}) {
1268
+ if (!KINDS[kind]) throw new Error(`unknown module kind "${kind}" (one of ${KIND_NAMES.join(", ")})`);
1269
+ const made = id ?? freshId(dsp, kind);
1270
+ const module = { id: made, kind };
1271
+ if (label) module.label = label;
1272
+ if (params) module.params = { ...params };
1273
+ if (options) module.options = { ...options };
1274
+ if (kind === "custom") Object.assign(module, { ports: structuredClone(CUSTOM_PORTS), code: CUSTOM_CODE, params: params ?? { gain: 0.5 } });
1275
+ if (kind === "macro") module.macro = structuredClone(MACRO_STARTER);
1276
+ return { dsp: cleanDsp({ ...dsp, modules: [...dsp.modules, module] }), id: made };
1277
+ }
1278
+
1279
+ /** A new patch without a module, and without its connections and controls. */
1280
+ export function removeModule(dsp, id) {
1281
+ const gone = (endpoint) => parseEndpoint(endpoint)?.module === id;
1282
+ return cleanDsp({
1283
+ ...dsp,
1284
+ modules: dsp.modules.filter((m) => m.id !== id),
1285
+ connections: dsp.connections.filter((c) => !gone(c.from) && !gone(c.to)),
1286
+ controls: dsp.controls.filter((c) => c.module !== id),
1287
+ ...(dsp.meters ? { meters: dsp.meters.filter((x) => !gone(x.from)) } : {}),
1288
+ ...(dsp.voices ? { voices: Object.fromEntries(Object.entries(dsp.voices).filter(([k, v]) => !(["note", "velocity"].includes(k) && parseEndpoint(v)?.module === id))) } : {}),
1289
+ });
1290
+ }
1291
+
1292
+ /** A new patch with its voices set (`null` removes them: the patch is monophonic again). */
1293
+ export function setVoices(dsp, voices) {
1294
+ const { voices: _gone, ...rest } = dsp;
1295
+ return cleanDsp(voices ? { ...rest, voices } : rest);
1296
+ }
1297
+
1298
+ /** A new patch with one more connection, or an Error saying why not. */
1299
+ export function connect(dsp, from, to) {
1300
+ const problem = connectionProblem(dsp, from, to);
1301
+ if (problem) throw new Error(problem);
1302
+ return cleanDsp({ ...dsp, connections: [...dsp.connections, { from, to }] });
1303
+ }
1304
+
1305
+ /** A new patch without a connection (a connection that isn't there changes nothing). */
1306
+ export const disconnect = (dsp, from, to) => cleanDsp({ ...dsp, connections: dsp.connections.filter((c) => !(c.from === from && c.to === to)) });
1307
+
1308
+ /** A new patch with one parameter set (clamped to its range). */
1309
+ export function setParam(dsp, id, name, value) {
1310
+ const m = moduleById(dsp, id);
1311
+ const p = m && specOf(m).params[name];
1312
+ if (!m) throw new Error(`no module "${id}"`);
1313
+ if (!p) throw new Error(`${m.kind} "${id}" has no parameter "${name}"`);
1314
+ if (!Number.isFinite(Number(value))) throw new Error(`${name} must be a number`);
1315
+ return cleanDsp({ ...dsp, modules: dsp.modules.map((x) => (x.id === id ? { ...x, params: { ...(x.params ?? {}), [name]: clamp(Number(value), p.min, p.max) } } : x)) });
1316
+ }
1317
+
1318
+ /** A new patch with one option set. */
1319
+ export function setOption(dsp, id, name, value) {
1320
+ const m = moduleById(dsp, id);
1321
+ if (!m) throw new Error(`no module "${id}"`);
1322
+ return cleanDsp({ ...dsp, modules: dsp.modules.map((x) => (x.id === id ? { ...x, options: { ...(x.options ?? {}), [name]: value } } : x)) });
1323
+ }
1324
+
1325
+ /** A new patch with a module changed by `patch` (label, code, ports, breaksCycle, x, y). */
1326
+ export function updateModule(dsp, id, patch) {
1327
+ if (!moduleById(dsp, id)) throw new Error(`no module "${id}"`);
1328
+ return cleanDsp({ ...dsp, modules: dsp.modules.map((x) => (x.id === id ? { ...x, ...patch } : x)) });
1329
+ }
1330
+
1331
+ /** A new patch with module `id` drawn at (x, y) in the diagram (never negative). The sound doesn't change. */
1332
+ export function moveModule(dsp, id, x, y) {
1333
+ if (!Number.isFinite(x) || !Number.isFinite(y)) throw new Error("a position is two numbers");
1334
+ return updateModule(dsp, id, { x: Math.max(0, x), y: Math.max(0, y) });
1335
+ }
1336
+
1337
+ /** A new patch with every module back at its automatic place in the diagram. */
1338
+ export const clearPositions = (dsp) => cleanDsp({ ...dsp, modules: dsp.modules.map(({ x: _x, y: _y, ...m }) => m) });
1339
+
1340
+ /** A new patch with a meter on an output port (or replaced, when the name exists); `every`: milliseconds between values. */
1341
+ export function addMeter(dsp, name, from, every = METER_EVERY.def) {
1342
+ return cleanDsp({ ...dsp, meters: [...(dsp.meters ?? []).filter((x) => x.name !== name), { name, from, every }] });
1343
+ }
1344
+
1345
+ /** A new patch without the meter `name`. */
1346
+ export const removeMeter = (dsp, name) => cleanDsp({ ...dsp, meters: (dsp.meters ?? []).filter((x) => x.name !== name) });
1347
+
1348
+ /** A new patch with a control exposed (or replaced, when the name exists). */
1349
+ export function exposeControl(dsp, name, module, param) {
1350
+ return cleanDsp({ ...dsp, controls: [...dsp.controls.filter((c) => c.name !== name), { name, module, param }] });
1351
+ }
1352
+
1353
+ /** A new patch without the control `name`. */
1354
+ export const unexposeControl = (dsp, name) => cleanDsp({ ...dsp, controls: dsp.controls.filter((c) => c.name !== name) });
1355
+
1356
+ /** The patch a pane gets when it is first turned into one: oscillator -> filter -> gain -> output, the cutoff exposed. */
1357
+ export function starterDsp() {
1358
+ return cleanDsp({
1359
+ modules: [
1360
+ { id: "osc", kind: "oscillator", params: { frequency: 110 }, options: { type: "sawtooth" } },
1361
+ { id: "filter", kind: "filter", params: { frequency: 900, q: 4 }, options: { type: "lowpass" } },
1362
+ { id: "amp", kind: "gain", params: { gain: 0.25 } },
1363
+ { id: "out", kind: "output" },
1364
+ ],
1365
+ connections: [
1366
+ { from: "osc.out", to: "filter.in" },
1367
+ { from: "filter.out", to: "amp.in" },
1368
+ { from: "amp.out", to: "out.in" },
1369
+ ],
1370
+ controls: [{ name: "cutoff", module: "filter", param: "frequency" }],
1371
+ });
1372
+ }
1373
+
1374
+ /** An empty patch. */
1375
+ export const emptyDsp = () => ({ version: DSP_VERSION, modules: [], connections: [], controls: [] });
1376
+
1377
+ /**
1378
+ * Where to draw each module when it has no position of its own: columns by
1379
+ * depth along the connections (sources left), rows within a column. `{ id:
1380
+ * { col, row } }` in grid units.
1381
+ */
1382
+ export function layout(dsp) {
1383
+ const depth = new Map(dsp.modules.map((m) => [m.id, 0]));
1384
+ const order = buildOrder(dsp);
1385
+ for (let pass = 0; pass < order.length; pass++) {
1386
+ let moved = false;
1387
+ for (const c of dsp.connections) {
1388
+ const a = parseEndpoint(c.from).module;
1389
+ const b = parseEndpoint(c.to).module;
1390
+ if (breaksCycle(moduleById(dsp, a))) continue;
1391
+ if (depth.get(b) < depth.get(a) + 1) (depth.set(b, depth.get(a) + 1), (moved = true));
1392
+ }
1393
+ if (!moved) break;
1394
+ }
1395
+ const rows = new Map();
1396
+ const out = {};
1397
+ for (const id of order) {
1398
+ const col = depth.get(id);
1399
+ const row = rows.get(col) ?? 0;
1400
+ rows.set(col, row + 1);
1401
+ out[id] = { col, row };
1402
+ }
1403
+ return out;
1404
+ }
1405
+
1406
+ /** A line about the patch for the status row and for agents: "4 modules, 3 connections, 1 control". */
1407
+ export function describeDsp(dsp) {
1408
+ const n = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
1409
+ return `${n(dsp.modules.length, "module")}, ${n(dsp.connections.length, "connection")}, ${n((dsp.controls?.length ?? 0), "control")}${dsp.voices ? `, ${n(dsp.voices.count, "voice")}` : ""}`;
1410
+ }