@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,776 @@
1
+ // The instrument registry: what a score track's `instrumentId` means (docs/design/score-instruments.md). Pure: no Web Audio, no DOM,
2
+ // no imports, so the audio pane's frame loads it as ONE module (`mallory:audio-instruments`) and mallory's page (the score editor,
3
+ // the MIDI codec) imports the same file. Every instrument is a DSP patch (src/audio/patch.js) built from the modules the audio pane
4
+ // already has, so a preset can be opened, forked and edited as a patch, and a render is as deterministic as any voiced patch.
5
+ //
6
+ // An instrument id is one of
7
+ // a preset "piano", "strings", "drum-kit", ... (PRESETS: synth presets and the drum kit)
8
+ // a General MIDI "gm:<0..127>" the nearest preset by family (a MIDI import that has no exact preset)
9
+ // a user synth "patch:<name>" a SynthSpec the score holds in `score.mallory.instruments`
10
+ // a user sampler "sample:<name>" zones over audio inputs, held there too
11
+ // Nothing is fetched: a sampler plays audio values the canvas wires in (a recorder take, a WAV from a files pane).
12
+ //
13
+ // `resolveInstrument(id, note, custom)` is what the voice pool asks for each note: `{ dsp, notes, velocity, tail, inputs }`, where
14
+ // `notes` lists the `module.param` targets that get the pitch (Hz times `mul`), and `velocity` the targets multiplied by the velocity.
15
+ // A sampler or a drum voice depends on the note (the zone, the drum), so the answer is per note.
16
+
17
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
18
+ const num = (v) => typeof v === "number" && Number.isFinite(v);
19
+ const clamp = (n, min, max) => Math.min(max, Math.max(min, n));
20
+ const NAME = /^[A-Za-z][A-Za-z0-9_-]{0,31}$/;
21
+ const INPUT = /^[A-Za-z_][A-Za-z0-9_]{0,31}$/; // a pane input's name
22
+
23
+ /** Sizes a score's instrument layer may have (a sampler's bytes are the canvas values', bounded by the frame's own sample limits). */
24
+ export const INSTRUMENT_LIMITS = Object.freeze({ custom: 16, zones: 16, name: 40 });
25
+
26
+ /** The default instrument of a track: the audio pane's own patch plays it (no instrument layer unless a track picks another). */
27
+ export const DEFAULT_INSTRUMENT = "piano";
28
+
29
+ // ── the synth designer's model ───────────────────────────────────────────────
30
+
31
+ export const OSC_SHAPES = Object.freeze(["sine", "triangle", "sawtooth", "square"]);
32
+ export const NOISE_COLORS = Object.freeze(["white", "pink", "brown"]);
33
+ export const FILTER_SHAPES = Object.freeze(["lowpass", "highpass", "bandpass"]);
34
+ export const LFO_TARGETS = Object.freeze(["off", "pitch", "filter", "amp"]);
35
+
36
+ /** Every numeric field of a SynthSpec: limits, steps and units (the designer's sliders and the clamping read this one table). */
37
+ export const SYNTH_RANGES = Object.freeze({
38
+ octave: { min: -3, max: 3, step: 1, def: 0, unit: "oct" },
39
+ detune: { min: -100, max: 100, step: 1, def: 0, unit: "cents" },
40
+ level: { min: 0, max: 1, step: 0.01, def: 0, unit: "" },
41
+ cutoff: { min: 20, max: 18000, step: 10, def: 18000, unit: "Hz" },
42
+ resonance: { min: 0, max: 20, step: 0.1, def: 0.7, unit: "" },
43
+ envAmount: { min: -6, max: 6, step: 0.1, def: 0, unit: "oct" },
44
+ attack: { min: 0.001, max: 4, step: 0.001, def: 0.01, unit: "s" },
45
+ decay: { min: 0.001, max: 8, step: 0.01, def: 0.2, unit: "s" },
46
+ sustain: { min: 0, max: 1, step: 0.01, def: 0.6, unit: "" },
47
+ release: { min: 0.005, max: 8, step: 0.01, def: 0.3, unit: "s" },
48
+ rate: { min: 0.05, max: 24, step: 0.05, def: 5, unit: "Hz" },
49
+ depth: { min: 0, max: 1, step: 0.01, def: 0, unit: "" },
50
+ fmRatio: { min: 0.25, max: 16, step: 0.25, def: 2, unit: "x" },
51
+ fmIndex: { min: 0, max: 12, step: 0.1, def: 0, unit: "" },
52
+ program: { min: 0, max: 127, step: 1, def: 0, unit: "" },
53
+ });
54
+
55
+ const osc = (shape, level, extra = {}) => ({ shape, octave: 0, detune: 0, level, ...extra });
56
+ const env = (attack, decay, sustain, release) => ({ attack, decay, sustain, release });
57
+
58
+ /** A SynthSpec with every field present (the shape music-studio's SynthPatch has, plus an FM pair). */
59
+ export function defaultSynth(extra = {}) {
60
+ return {
61
+ oscA: osc("sawtooth", 0.6),
62
+ oscB: osc("sawtooth", 0),
63
+ fm: { ratio: 2, index: 0, decay: 0.4 },
64
+ noise: { color: "white", level: 0 },
65
+ filter: { shape: "lowpass", cutoff: 18000, resonance: 0.7, envAmount: 0 },
66
+ filterEnv: env(0.01, 0.3, 0.5, 0.3),
67
+ ampEnv: env(0.01, 0.2, 0.6, 0.3),
68
+ lfo: { target: "off", rate: 5, depth: 0 },
69
+ ...extra,
70
+ };
71
+ }
72
+
73
+ const pick = (v, list, def) => (list.includes(v) ? v : def);
74
+ const range = (v, key) => {
75
+ const r = SYNTH_RANGES[key];
76
+ return clamp(num(v) ? v : r.def, r.min, r.max);
77
+ };
78
+ const cleanOsc = (o, base) => ({ shape: pick(o?.shape, OSC_SHAPES, base.shape), octave: Math.round(range(o?.octave ?? base.octave, "octave")), detune: range(o?.detune ?? base.detune, "detune"), level: range(o?.level ?? base.level, "level") });
79
+ const cleanEnv = (e, base) => ({ attack: range(e?.attack ?? base.attack, "attack"), decay: range(e?.decay ?? base.decay, "decay"), sustain: range(e?.sustain ?? base.sustain, "sustain"), release: range(e?.release ?? base.release, "release") });
80
+
81
+ /** A SynthSpec limited to its ranges, unknown fields dropped, missing ones defaulted. Never throws: it is what the graph reads. */
82
+ export function cleanSynth(spec) {
83
+ const base = defaultSynth();
84
+ const s = isObject(spec) ? spec : {};
85
+ return {
86
+ oscA: cleanOsc(s.oscA, base.oscA),
87
+ oscB: cleanOsc(s.oscB, base.oscB),
88
+ fm: { ratio: range(s.fm?.ratio ?? base.fm.ratio, "fmRatio"), index: range(s.fm?.index ?? base.fm.index, "fmIndex"), decay: range(s.fm?.decay ?? base.fm.decay, "decay") },
89
+ noise: { color: pick(s.noise?.color, NOISE_COLORS, "white"), level: range(s.noise?.level ?? 0, "level") },
90
+ filter: { shape: pick(s.filter?.shape, FILTER_SHAPES, "lowpass"), cutoff: range(s.filter?.cutoff ?? base.filter.cutoff, "cutoff"), resonance: range(s.filter?.resonance ?? base.filter.resonance, "resonance"), envAmount: range(s.filter?.envAmount ?? 0, "envAmount") },
91
+ filterEnv: cleanEnv(s.filterEnv, base.filterEnv),
92
+ ampEnv: cleanEnv(s.ampEnv, base.ampEnv),
93
+ lfo: { target: pick(s.lfo?.target, LFO_TARGETS, "off"), rate: range(s.lfo?.rate ?? base.lfo.rate, "rate"), depth: range(s.lfo?.depth ?? 0, "depth") },
94
+ };
95
+ }
96
+
97
+ /** Why a SynthSpec can't be used (a field outside its range or of the wrong kind), or "". Stricter than cleanSynth, for what is saved. */
98
+ export function synthProblem(spec, at = "synth") {
99
+ if (!isObject(spec)) return `${at}: an object { oscA, oscB, noise, filter, filterEnv, ampEnv, lfo, fm? }`;
100
+ const allowed = ["oscA", "oscB", "fm", "noise", "filter", "filterEnv", "ampEnv", "lfo"];
101
+ for (const key of Object.keys(spec)) if (!allowed.includes(key)) return `${at} has no field "${key}"`;
102
+ const checks = [
103
+ ["oscA", { shape: OSC_SHAPES, octave: "octave", detune: "detune", level: "level" }],
104
+ ["oscB", { shape: OSC_SHAPES, octave: "octave", detune: "detune", level: "level" }],
105
+ ["fm", { ratio: "fmRatio", index: "fmIndex", decay: "decay" }],
106
+ ["noise", { color: NOISE_COLORS, level: "level" }],
107
+ ["filter", { shape: FILTER_SHAPES, cutoff: "cutoff", resonance: "resonance", envAmount: "envAmount" }],
108
+ ["filterEnv", { attack: "attack", decay: "decay", sustain: "sustain", release: "release" }],
109
+ ["ampEnv", { attack: "attack", decay: "decay", sustain: "sustain", release: "release" }],
110
+ ["lfo", { target: LFO_TARGETS, rate: "rate", depth: "depth" }],
111
+ ];
112
+ for (const [group, fields] of checks) {
113
+ const g = spec[group];
114
+ if (g === undefined) continue;
115
+ if (!isObject(g)) return `${at}.${group}: an object`;
116
+ for (const [k, v] of Object.entries(g)) {
117
+ const f = fields[k];
118
+ if (f === undefined) return `${at}.${group} has no field "${k}"`;
119
+ if (Array.isArray(f)) {
120
+ if (!f.includes(v)) return `${at}.${group}.${k}: one of ${f.join(", ")}`;
121
+ } else if (!num(v) || v < SYNTH_RANGES[f].min || v > SYNTH_RANGES[f].max) return `${at}.${group}.${k}: a number from ${SYNTH_RANGES[f].min} to ${SYNTH_RANGES[f].max}`;
122
+ }
123
+ }
124
+ return "";
125
+ }
126
+
127
+ const round = (n) => Math.round(n * 1e6) / 1e6;
128
+ const SYNTH_OUT = 0.35; // the output gain of a synth voice: a few notes and a few tracks together stay under full scale
129
+ const DRUM_OUT = 0.6;
130
+
131
+ /**
132
+ * A SynthSpec as a DSP patch: `{ dsp, notes, velocity }`. Two oscillators (or an FM pair), seeded noise, a filter with its own
133
+ * envelope, an amplitude envelope and an LFO, wired from the modules a patch already has. `notes`: the parameters that get the
134
+ * pitch; `velocity`: the envelope peak a note's velocity scales.
135
+ */
136
+ export function synthDsp(raw) {
137
+ const s = cleanSynth(raw);
138
+ const modules = [];
139
+ const connections = [];
140
+ const notes = [];
141
+ const add = (id, kind, params, options) => modules.push({ id, kind, ...(params ? { params } : {}), ...(options ? { options } : {}) });
142
+ const wire = (from, to) => connections.push({ from, to });
143
+ // A filter that is wide open and moves nowhere is not built (an 18 kHz low-pass is above the Nyquist of a 22 kHz render, and does nothing).
144
+ const openFilter = s.filter.shape === "lowpass" && s.filter.cutoff >= SYNTH_RANGES.cutoff.max && s.filter.envAmount === 0 && s.lfo.target !== "filter";
145
+ const filterIn = openFilter ? "amp.in" : "filt.in";
146
+ const fm = s.fm.index > 0 && s.oscB.level === 0;
147
+ // oscillator A: the carrier (or the plain first layer)
148
+ add("oscA", "oscillator", { frequency: 440, detune: s.oscA.detune }, { type: s.oscA.shape });
149
+ add("gainA", "gain", { gain: s.oscA.level });
150
+ wire("oscA.out", "gainA.in");
151
+ wire("gainA.out", filterIn);
152
+ notes.push({ target: "oscA.frequency", mul: 2 ** s.oscA.octave });
153
+ if (fm) {
154
+ // The e-piano's "FM": a patch connection can't modulate a frequency with audio (audio goes to audio inputs), so the bell-like
155
+ // sideband is an inharmonic sine partial at ratio x the pitch that fades with its own decay: the same ear-catching attack, additive.
156
+ add("mod", "oscillator", { frequency: 440 }, { type: "sine" });
157
+ add("modAmp", "gain", { gain: 0 });
158
+ add("modEnv", "envelope", { attack: 0.001, decay: s.fm.decay, sustain: 0.05, release: s.fm.decay, peak: round(Math.min(1, s.fm.index * 0.18)) });
159
+ wire("mod.out", "modAmp.in");
160
+ wire("modEnv.out", "modAmp.gain");
161
+ wire("modAmp.out", filterIn);
162
+ notes.push({ target: "mod.frequency", mul: 2 ** s.oscA.octave * s.fm.ratio });
163
+ } else if (s.oscB.level > 0) {
164
+ add("oscB", "oscillator", { frequency: 440, detune: s.oscB.detune }, { type: s.oscB.shape });
165
+ add("gainB", "gain", { gain: s.oscB.level });
166
+ wire("oscB.out", "gainB.in");
167
+ wire("gainB.out", filterIn);
168
+ notes.push({ target: "oscB.frequency", mul: 2 ** s.oscB.octave });
169
+ }
170
+ if (s.noise.level > 0) {
171
+ add("noise", "noise", { level: 1 }, { seed: 7 });
172
+ add("gainN", "gain", { gain: s.noise.level });
173
+ wire("noise.out", s.noise.color === "white" ? "gainN.in" : "tone.in");
174
+ if (s.noise.color !== "white") {
175
+ add("tone", "filter", { frequency: s.noise.color === "pink" ? 1500 : 320, q: 0.7 }, { type: "lowpass" });
176
+ wire("tone.out", "gainN.in");
177
+ }
178
+ wire("gainN.out", filterIn);
179
+ }
180
+ if (!openFilter) add("filt", "filter", { frequency: s.filter.cutoff, q: s.filter.resonance }, { type: s.filter.shape });
181
+ if (s.filter.envAmount !== 0) {
182
+ add("fenv", "envelope", { attack: s.filterEnv.attack, decay: s.filterEnv.decay, sustain: s.filterEnv.sustain, release: s.filterEnv.release, peak: round(s.filter.cutoff * (2 ** s.filter.envAmount - 1)) });
183
+ wire("fenv.out", "filt.frequency");
184
+ }
185
+ add("amp", "gain", { gain: 0 });
186
+ add("aenv", "envelope", { attack: s.ampEnv.attack, decay: s.ampEnv.decay, sustain: s.ampEnv.sustain, release: s.ampEnv.release, peak: 1 });
187
+ add("out", "output", { gain: SYNTH_OUT });
188
+ if (!openFilter) wire("filt.out", "amp.in");
189
+ wire("aenv.out", "amp.gain");
190
+ wire("amp.out", "out.in");
191
+ if (s.lfo.target !== "off" && s.lfo.depth > 0) {
192
+ const t = s.lfo.target;
193
+ const depth = t === "pitch" ? s.lfo.depth * 50 : t === "filter" ? s.lfo.depth * s.filter.cutoff * 0.5 : s.lfo.depth * 0.5;
194
+ add("lfo", "lfo", { frequency: s.lfo.rate, depth: round(depth) }, { type: "sine" });
195
+ if (t === "pitch") {
196
+ wire("lfo.out", "oscA.detune");
197
+ if (modules.some((m) => m.id === "oscB")) wire("lfo.out", "oscB.detune");
198
+ } else if (t === "filter") wire("lfo.out", "filt.frequency");
199
+ else {
200
+ add("trem", "gain", { gain: 1 }); // tremolo: the LFO moves a gain that sits after the amplitude envelope
201
+ connections.splice(connections.findIndex((c) => c.from === "amp.out"), 1);
202
+ wire("amp.out", "trem.in");
203
+ wire("trem.out", "out.in");
204
+ wire("lfo.out", "trem.gain");
205
+ }
206
+ }
207
+ return { dsp: { version: 1, modules, connections, controls: [] }, notes, velocity: ["aenv.peak"] };
208
+ }
209
+
210
+ // ── the synth presets (music-studio's set, as DSP patches) ───────────────────
211
+
212
+ const synth = (extra) => defaultSynth(extra);
213
+
214
+ /**
215
+ * The presets. `program`: the General MIDI program a MIDI export writes (0-based). Names, oscillator shapes and envelopes follow
216
+ * music-studio's presets; the sampled grand piano and the 18 soundfont instruments are not here (they need a network fetch: #929).
217
+ */
218
+ export const PRESETS = Object.freeze({
219
+ piano: { name: "Piano", set: "Classic", program: 0, synth: synth({ oscA: osc("triangle", 0.55), oscB: osc("sine", 0.25, { octave: 1 }), filter: { shape: "lowpass", cutoff: 5200, resonance: 0.7, envAmount: 0 }, ampEnv: env(0.003, 1.4, 0.0, 0.35) }) },
220
+ strings: { name: "Strings", set: "Classic", program: 48, synth: synth({ oscA: osc("sawtooth", 0.28, { detune: -8 }), oscB: osc("sawtooth", 0.28, { detune: 8 }), filter: { shape: "lowpass", cutoff: 3200, resonance: 0.7, envAmount: 0 }, ampEnv: env(0.3, 0.5, 0.85, 1.5) }) },
221
+ flute: { name: "Flute", set: "Classic", program: 73, synth: synth({ oscA: osc("sine", 0.6), noise: { color: "pink", level: 0.03 }, ampEnv: env(0.08, 0.2, 0.7, 0.5) }) },
222
+ harpsichord: { name: "Harpsichord", set: "Classic", program: 6, synth: synth({ oscA: osc("square", 0.28), oscB: osc("sawtooth", 0.18, { octave: 1 }), filter: { shape: "highpass", cutoff: 300, resonance: 0.7, envAmount: 0 }, ampEnv: env(0.002, 0.6, 0.02, 0.3) }) },
223
+ "saw-lead": { name: "Saw Lead", set: "Synthwave", program: 81, synth: synth({ oscA: osc("sawtooth", 0.45), ampEnv: env(0.01, 0.2, 0.5, 0.4) }) },
224
+ "warm-pad": { name: "Warm Pad", set: "Synthwave", program: 89, synth: synth({ oscA: osc("triangle", 0.5), lfo: { target: "pitch", rate: 4.5, depth: 0.15 }, ampEnv: env(0.4, 0.4, 0.8, 1.2) }) },
225
+ "fm-epiano": { name: "FM E-Piano", set: "Synthwave", program: 4, synth: synth({ oscA: osc("sine", 0.55), fm: { ratio: 3.01, index: 1.4, decay: 0.4 }, ampEnv: env(0.005, 1.2, 0.2, 0.8) }) },
226
+ "fat-bass": { name: "Fat Bass", set: "Synthwave", program: 38, synth: synth({ oscA: osc("sawtooth", 0.3, { detune: -20 }), oscB: osc("sawtooth", 0.3, { detune: 20 }), filter: { shape: "lowpass", cutoff: 900, resonance: 2, envAmount: 1.5 }, filterEnv: env(0.005, 0.25, 0.2, 0.3), ampEnv: env(0.005, 0.3, 0.6, 0.3) }) },
227
+ "arp-pluck": { name: "Arp Pluck", set: "Synthwave", program: 80, synth: synth({ oscA: osc("square", 0.3), ampEnv: env(0.002, 0.15, 0.05, 0.2) }) },
228
+ "drum-kit": { name: "Drum Kit", set: "Rhythm", program: 0, drums: true },
229
+ });
230
+
231
+ export const PRESET_IDS = Object.freeze(Object.keys(PRESETS));
232
+ export const INSTRUMENT_SETS = Object.freeze([...new Set(Object.values(PRESETS).map((p) => p.set))]);
233
+ export const presetsBySet = (set) => PRESET_IDS.filter((id) => PRESETS[id].set === set);
234
+
235
+ // ── General MIDI ─────────────────────────────────────────────────────────────
236
+
237
+ /** The preset a General MIDI program (0-based) sounds like: the exact one if there is, else by family. */
238
+ export function presetForProgram(program) {
239
+ const p = Math.round(clamp(Number(program) || 0, 0, 127));
240
+ const exact = PRESET_IDS.find((id) => !PRESETS[id].drums && PRESETS[id].program === p);
241
+ if (exact) return exact;
242
+ const family = Math.floor(p / 8);
243
+ return ["piano", "arp-pluck", "warm-pad", "arp-pluck", "fat-bass", "strings", "strings", "saw-lead", "flute", "flute", "saw-lead", "warm-pad", "warm-pad", "arp-pluck", "arp-pluck", "warm-pad"][family];
244
+ }
245
+
246
+ /** The instrument id a MIDI import gives a program: the preset when one has exactly that program, else `gm:<program>` (exported back as that program). */
247
+ export function instrumentForProgram(program) {
248
+ const p = Math.round(clamp(Number(program) || 0, 0, 127));
249
+ return PRESET_IDS.find((id) => !PRESETS[id].drums && PRESETS[id].program === p) ?? `gm:${p}`;
250
+ }
251
+
252
+ /** The instrument id of a drum channel in an import. */
253
+ export const DRUM_INSTRUMENT = "drum-kit";
254
+
255
+ const GM_ID = /^gm:(\d{1,3})$/;
256
+ const CUSTOM_ID = /^(patch|sample):[A-Za-z0-9_-]{1,32}$/;
257
+
258
+ /** Is `id` a name this module can sound (a preset, a gm: id or a well-formed custom id)? Custom ones also need their definition. */
259
+ export const isInstrumentId = (id) => typeof id === "string" && (Object.hasOwn(PRESETS, id) || (GM_ID.test(id) && Number(id.slice(3)) <= 127) || CUSTOM_ID.test(id));
260
+
261
+ /** The General MIDI program a track plays as in an export, and whether it is the drum channel. `custom`: the score's `mallory.instruments`. */
262
+ export function midiOf(id, custom = {}) {
263
+ if (PRESETS[id]) return { program: PRESETS[id].program, drums: Boolean(PRESETS[id].drums), exact: true };
264
+ const gm = GM_ID.exec(String(id));
265
+ if (gm && Number(gm[1]) <= 127) return { program: Number(gm[1]), drums: false, exact: true };
266
+ const c = isObject(custom) ? custom[id] : null;
267
+ if (c) return { program: Math.round(clamp(num(c.program) ? c.program : 0, 0, 127)), drums: false, exact: false }; // a custom sound is written as its nearest program
268
+ return { program: 0, drums: false, exact: false };
269
+ }
270
+
271
+ /** The hook the MIDI codec (src/smf/score.js, which imports nothing of mallory) takes: programs <-> instrument ids. `custom`: the score's own instruments. */
272
+ export const midiInstruments = (custom = {}) => ({ forProgram: instrumentForProgram, drum: DRUM_INSTRUMENT, programOf: (id) => midiOf(id, custom) });
273
+
274
+ /** A readable name for an instrument id. */
275
+ export function instrumentName(id, custom = {}) {
276
+ if (PRESETS[id]) return PRESETS[id].name;
277
+ if (GM_ID.test(String(id))) return `GM ${Number(String(id).slice(3)) + 1}`;
278
+ const c = isObject(custom) ? custom[id] : null;
279
+ return c?.name ?? String(id);
280
+ }
281
+
282
+ // ── the drum kit ─────────────────────────────────────────────────────────────
283
+
284
+ /** Which drum a General MIDI percussion note is. */
285
+ export function drumOf(note) {
286
+ if (note === 35 || note === 36) return "kick";
287
+ if (note === 37) return "rim";
288
+ if (note === 38 || note === 40) return "snare";
289
+ if (note === 39) return "clap";
290
+ if (note === 42 || note === 44) return "hat";
291
+ if (note === 46) return "openhat";
292
+ if ([41, 43, 45, 47, 48, 50].includes(note)) return "tom";
293
+ if ([49, 52, 55, 57].includes(note)) return "crash";
294
+ if ([51, 53, 59].includes(note)) return "ride";
295
+ if (note === 54) return "tambourine";
296
+ if (note === 56) return "cowbell";
297
+ return "perc";
298
+ }
299
+
300
+ /** The General MIDI percussion notes the kit sounds on its own (everything else is a short click), for the picker's labels. */
301
+ export const DRUM_NAMES = Object.freeze({ 35: "kick 2", 36: "kick", 37: "side stick", 38: "snare", 39: "clap", 40: "snare 2", 41: "low floor tom", 42: "closed hat", 43: "high floor tom", 44: "pedal hat", 45: "low tom", 46: "open hat", 47: "low-mid tom", 48: "hi-mid tom", 49: "crash", 50: "high tom", 51: "ride", 52: "china", 53: "ride bell", 54: "tambourine", 55: "splash", 56: "cowbell", 57: "crash 2", 59: "ride 2" });
302
+ const TOM_HZ = { 41: 78, 43: 98, 45: 118, 47: 140, 48: 165, 50: 195 };
303
+
304
+ /** A drum as a patch: noise or tones through an envelope that ends by itself (sustain 0). `velocity`: the envelope peaks a hit's velocity scales. */
305
+ function drumDsp(name, note) {
306
+ const modules = [];
307
+ const connections = [];
308
+ const add = (id, kind, params, options) => modules.push({ id, kind, ...(params ? { params } : {}), ...(options ? { options } : {}) });
309
+ const wire = (a, b) => connections.push({ from: a, to: b });
310
+ const velocity = [];
311
+ let hold = 0;
312
+ /** A layer: source -> optional filter -> amp (enveloped by its own decay) -> out. */
313
+ const layer = (id, source, { filter, decay, level, release = Math.min(decay, 0.15), pitch }) => {
314
+ add(`${id}`, source.kind, source.params, source.options);
315
+ let last = `${id}.out`;
316
+ if (filter) {
317
+ add(`${id}f`, "filter", { frequency: filter.frequency, q: filter.q ?? 0.8 }, { type: filter.type });
318
+ wire(last, `${id}f.in`);
319
+ last = `${id}f.out`;
320
+ }
321
+ add(`${id}a`, "gain", { gain: 0 });
322
+ add(`${id}e`, "envelope", { attack: 0.001, decay, sustain: 0, release, peak: level });
323
+ wire(last, `${id}a.in`);
324
+ wire(`${id}e.out`, `${id}a.gain`);
325
+ wire(`${id}a.out`, "out.in");
326
+ velocity.push(`${id}e.peak`);
327
+ hold = Math.max(hold, decay);
328
+ if (pitch) {
329
+ add(`${id}p`, "envelope", { attack: 0, decay: pitch.decay, sustain: 0, release: 0.02, peak: pitch.hz });
330
+ wire(`${id}p.out`, `${id}.frequency`);
331
+ }
332
+ };
333
+ const tone = (frequency, type) => ({ kind: "oscillator", params: { frequency }, options: { type } });
334
+ const hiss = (seed) => ({ kind: "noise", params: { level: 1 }, options: { seed } });
335
+ add("out", "output", { gain: DRUM_OUT });
336
+ switch (name) {
337
+ case "kick":
338
+ layer("body", tone(48, "sine"), { decay: 0.32, level: 0.95, pitch: { hz: 150, decay: 0.09 } });
339
+ layer("click", hiss(3), { filter: { type: "lowpass", frequency: 2400 }, decay: 0.012, level: 0.25 });
340
+ break;
341
+ case "snare":
342
+ layer("snap", hiss(5), { filter: { type: "highpass", frequency: 1400 }, decay: 0.19, level: 0.65 });
343
+ layer("tone", tone(190, "triangle"), { decay: 0.1, level: 0.4, pitch: { hz: 60, decay: 0.04 } });
344
+ break;
345
+ case "rim":
346
+ layer("rim", tone(420, "square"), { filter: { type: "highpass", frequency: 800 }, decay: 0.03, level: 0.4 });
347
+ layer("snap", hiss(11), { filter: { type: "bandpass", frequency: 2800, q: 1.5 }, decay: 0.03, level: 0.3 });
348
+ break;
349
+ case "clap":
350
+ layer("clap", hiss(13), { filter: { type: "bandpass", frequency: 1500, q: 1.2 }, decay: 0.13, level: 0.7 });
351
+ break;
352
+ case "hat":
353
+ layer("hat", hiss(17), { filter: { type: "highpass", frequency: 7500 }, decay: 0.04, level: 0.45 });
354
+ break;
355
+ case "openhat":
356
+ layer("hat", hiss(19), { filter: { type: "highpass", frequency: 7000 }, decay: 0.34, level: 0.42, release: 0.12 });
357
+ break;
358
+ case "tom": {
359
+ const f = TOM_HZ[note] ?? 120;
360
+ layer("tom", tone(f, "sine"), { decay: 0.28, level: 0.85, pitch: { hz: f * 0.7, decay: 0.08 } });
361
+ layer("skin", hiss(23), { filter: { type: "bandpass", frequency: f * 6, q: 1 }, decay: 0.02, level: 0.2 });
362
+ break;
363
+ }
364
+ case "crash":
365
+ layer("wash", hiss(29), { filter: { type: "highpass", frequency: 5200 }, decay: 1.3, level: 0.42, release: 0.5 });
366
+ break;
367
+ case "ride":
368
+ layer("wash", hiss(31), { filter: { type: "bandpass", frequency: 8200, q: 0.9 }, decay: 0.7, level: 0.3, release: 0.3 });
369
+ layer("ping", tone(5400, "square"), { filter: { type: "bandpass", frequency: 5400, q: 4 }, decay: 0.35, level: 0.12 });
370
+ break;
371
+ case "tambourine":
372
+ layer("jingle", hiss(37), { filter: { type: "highpass", frequency: 8500 }, decay: 0.12, level: 0.4 });
373
+ break;
374
+ case "cowbell":
375
+ layer("a", tone(540, "square"), { filter: { type: "bandpass", frequency: 700, q: 2 }, decay: 0.18, level: 0.3 });
376
+ layer("b", tone(810, "square"), { filter: { type: "bandpass", frequency: 800, q: 2 }, decay: 0.18, level: 0.25 });
377
+ break;
378
+ default:
379
+ layer("tick", hiss(41), { filter: { type: "bandpass", frequency: 2500, q: 1 }, decay: 0.03, level: 0.3 });
380
+ }
381
+ // A drum is a one-shot: its note-off does not cut it (a sixteenth-note hat or a crash rings out as a drummer's would).
382
+ return { dsp: { version: 1, modules, connections, controls: [] }, notes: [], velocity, hold: hold + 0.01 };
383
+ }
384
+
385
+ // ── the sampler ──────────────────────────────────────────────────────────────
386
+
387
+ const SAMPLE_RATE_RANGE = { min: 0.0625, max: 16 }; // the sample module's rate: four octaves either way from the root
388
+
389
+ /** The longest loop point (milliseconds): the sample pane's recordings are at most a minute. */
390
+ const LOOP_MS_MAX = 600000;
391
+
392
+ /**
393
+ * A zone of a sampler: `{ input, lo, hi, root, loop?, loopStart?, loopEnd?, gain?, bank? }`: the audio input it plays, the notes it answers to (lo..hi, MIDI)
394
+ * and the note the recording is. `loop` repeats the recording (from `loopStart` to `loopEnd`, in milliseconds; 0 and 0 is all of it). With `bank`,
395
+ * the input carries a bank of recordings by pitch (`{ bank: { <root>: audio } }`, a soundfont) and the zone plays the one at its `root`.
396
+ */
397
+ export function cleanZone(z) {
398
+ const root = Math.round(clamp(num(z?.root) ? z.root : 60, 0, 127));
399
+ const lo = Math.round(clamp(num(z?.lo) ? z.lo : 0, 0, 127));
400
+ const hi = Math.round(clamp(num(z?.hi) ? z.hi : 127, 0, 127));
401
+ const ms = (v) => Math.round(clamp(num(v) ? v : 0, 0, LOOP_MS_MAX));
402
+ const out = { input: String(z?.input ?? ""), lo: Math.min(lo, hi), hi: Math.max(lo, hi), root, loop: z?.loop === true, loopStart: ms(z?.loopStart), loopEnd: ms(z?.loopEnd), gain: clamp(num(z?.gain) ? z.gain : 1, 0, 2) };
403
+ if (out.loopEnd !== 0 && out.loopEnd <= out.loopStart) out.loopEnd = 0;
404
+ return { ...out, bank: z?.bank === true };
405
+ }
406
+
407
+ /** What a sampler's decoded recordings may add up to (bytes of 32-bit float samples), and the longest one (seconds). */
408
+ export const DECODED_LIMITS = Object.freeze({ bytes: 32 * 1024 * 1024, seconds: 20 });
409
+
410
+ /**
411
+ * The longest one recording may be (seconds) for the few soundfonts whose real files are longer than DECODED_LIMITS.seconds, by font id (src/audio/soundfont.js
412
+ * FONTS): the Salamander grand's lowest sample, A1, is 23.38 s. A font id a canvas names that is not in this table gets the default, so this is a fixed
413
+ * allowance, never a number from canvas text.
414
+ */
415
+ export const SAMPLE_SECONDS = Object.freeze({ salamander_grand: 24 });
416
+
417
+ /**
418
+ * The pitches (MIDI notes) of each font that has a longer allowance above, as src/audio/soundfont.js sets them (a test holds the two tables equal). The
419
+ * allowance is for the font's own set: see `allowanceFont`.
420
+ */
421
+ export const FONT_PITCHES = Object.freeze({ salamander_grand: Object.freeze([33, 45, 57, 60, 63, 66, 69, 81, 93]) });
422
+
423
+ /**
424
+ * The font whose allowances (SAMPLE_SECONDS, SAMPLE_BYTES) a bank value gets, #1023. A bank value (`{ font, name, bank }`) says its font in a field any pane can
425
+ * write, so the field alone is not trusted: a font with a longer allowance counts only while the bank holds exactly that font's pitches (the files the fixed host
426
+ * list gave it), else the bank gets the default limits. A font without an allowance of its own, or none, is returned as it was (the default applies anyway).
427
+ */
428
+ export function allowanceFont(value) {
429
+ const font = value?.font;
430
+ if (typeof font !== "string" || !Object.hasOwn(FONT_PITCHES, font)) return font;
431
+ const have = isObject(value.bank) ? Object.keys(value.bank).map(Number).sort((a, b) => a - b) : [];
432
+ const want = FONT_PITCHES[font];
433
+ return have.length === want.length && have.every((n, i) => n === want[i]) ? font : undefined;
434
+ }
435
+
436
+ /**
437
+ * The SHA-256 of each file of a font that has a longer allowance above, by pitch (#1023): the files the fixed host list serves (Tone.js's audio/salamander, measured
438
+ * 2026-11-09). A bank value is plain data any pane can write, so its `font` field and its pitches prove nothing about where its bytes came from; the allowance is
439
+ * given to a recording whose own bytes are the pinned ones (`sampleOfFont`). If the host re-encodes a file, the font keeps the default limits until this table is
440
+ * updated (it fails closed: the Salamander grand's lowest note then says it is over the 20 second limit).
441
+ */
442
+ export const SAMPLE_DIGESTS = Object.freeze({
443
+ salamander_grand: Object.freeze({
444
+ 33: "17fa1e363f9fad67c3357be54a6defc4fca5a5c2aada21de84b30254f9cb2f5b",
445
+ 45: "20601d890f44a3c22499c7b61f52e571795df1fe5a01fac553dded7b6379e1d4",
446
+ 57: "8e108fe228e34e32f6b4e61efff732eec53058a9e6f05a8d8e719598b132c4f9",
447
+ 60: "689eaa4c2fd7f29a2cc0e386eec462156d523a87d701269e5e2458e66056f4f6",
448
+ 63: "663e8bb3e2d0fa23a30526dcd7ab0e42609c193c07025647ef46badcf81ec211",
449
+ 66: "613652f5c96e35736ce6a46bc4ddb6ba1076d1fb16a35a4c22c14e67efdde57c",
450
+ 69: "a62df24a2c84cea8d18c1fa8aca7c18c877ba2b76a00a591256fa74d3ce54ac3",
451
+ 81: "9e5cee1fe9cf68b7193623d46a27c8956e572c1ff234ca0e11599b556050dec6",
452
+ 93: "b6064a657592c63c03561d2ce1092607c14e1d8091445d50065d0ec819ff6fbc",
453
+ }),
454
+ });
455
+
456
+ const K256 = new Uint32Array([
457
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
458
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
459
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
460
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
461
+ ]);
462
+
463
+ /** The SHA-256 of `bytes` (a Uint8Array) as hex. Synchronous and self-contained, so the frame that decodes a bank can check a file without a secure context. */
464
+ export function sha256Hex(bytes) {
465
+ const n = bytes.length;
466
+ const padded = new Uint8Array(((n + 9 + 63) >> 6) << 6);
467
+ padded.set(bytes);
468
+ padded[n] = 0x80;
469
+ const view = new DataView(padded.buffer);
470
+ view.setUint32(padded.length - 8, Math.floor((n * 8) / 0x100000000));
471
+ view.setUint32(padded.length - 4, (n * 8) >>> 0);
472
+ const h = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);
473
+ const w = new Uint32Array(64);
474
+ const rotr = (x, k) => (x >>> k) | (x << (32 - k));
475
+ for (let off = 0; off < padded.length; off += 64) {
476
+ for (let i = 0; i < 16; i++) w[i] = view.getUint32(off + i * 4);
477
+ for (let i = 16; i < 64; i++) {
478
+ const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3);
479
+ const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10);
480
+ w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0;
481
+ }
482
+ let [a, b, c, d, e, f, g, hh] = h;
483
+ for (let i = 0; i < 64; i++) {
484
+ const t1 = (hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K256[i] + w[i]) | 0;
485
+ const t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) | 0;
486
+ hh = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0;
487
+ }
488
+ h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
489
+ }
490
+ return [...h].map((x) => x.toString(16).padStart(8, "0")).join("");
491
+ }
492
+
493
+ /**
494
+ * Are `bytes` the pinned file of `font` at `pitch` (SAMPLE_DIGESTS)? The longer allowances above are given to a recording only when this says yes: the allowance follows
495
+ * the file that was actually loaded from the fixed host list, never the `font` field a bank value says (#1023). `bytes`: an ArrayBuffer or a typed array; anything else is no.
496
+ */
497
+ export function sampleOfFont(font, pitch, bytes, digests = SAMPLE_DIGESTS) {
498
+ if (typeof font !== "string" || !Object.hasOwn(digests, font)) return false;
499
+ const want = Object.hasOwn(digests[font], String(pitch)) ? digests[font][String(pitch)] : undefined;
500
+ const view = bytes instanceof ArrayBuffer ? new Uint8Array(bytes) : ArrayBuffer.isView(bytes) ? new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength) : null;
501
+ return Boolean(want && view && sha256Hex(view) === want);
502
+ }
503
+
504
+ /**
505
+ * What one soundfont's decoded recordings may add up to (bytes), for the few fonts whose real sets decode to more than DECODED_LIMITS.bytes, by font id (the
506
+ * same kind of fixed table as SAMPLE_SECONDS; every other font, and a name that is not in it, keeps 32 MB). The Salamander grand's nine files (INS-03, the
507
+ * nine music-studio loads: A1 to A6, C4, D#4, F#4) decode to 44.69 MB of float samples, measured 2026-11-09; 48 MB leaves room for a re-encode of the set and
508
+ * not for a tenth file. The cap is per bank (per input), so a second bank on the canvas has its own budget.
509
+ */
510
+ export const SAMPLE_BYTES = Object.freeze({ salamander_grand: 48 * 1024 * 1024 });
511
+
512
+ /**
513
+ * Whether what the browser decoded recordings to is within DECODED_LIMITS: `samples` is `[{ frames, channels, sampleRate }]`, `font` the soundfont they belong
514
+ * to (its entry in SAMPLE_SECONDS lets a sample be longer, its entry in SAMPLE_BYTES lets the set be bigger). "" when it is, else the sentence for the person.
515
+ */
516
+ export function decodedProblem(samples, font) {
517
+ const longest = typeof font === "string" && Object.hasOwn(SAMPLE_SECONDS, font) ? SAMPLE_SECONDS[font] : DECODED_LIMITS.seconds;
518
+ const limit = typeof font === "string" && Object.hasOwn(SAMPLE_BYTES, font) ? SAMPLE_BYTES[font] : DECODED_LIMITS.bytes;
519
+ let bytes = 0;
520
+ for (const s of samples) {
521
+ const seconds = s.frames / (s.sampleRate || 44100);
522
+ if (seconds > longest) return `a sample decodes to ${Math.round(seconds)} seconds, over the ${longest} second limit`;
523
+ bytes += s.frames * s.channels * 4;
524
+ }
525
+ return bytes > limit ? `the samples decode to ${Math.round(bytes / 1048576)} MB, over the ${limit / 1048576} MB limit` : "";
526
+ }
527
+
528
+ /** The name a zone's recording has in the frame's decoded buffers: the input's own name, or `input@root` for a bank. */
529
+ export const bankKey = (input, root) => `${input}@${root}`;
530
+ export const zoneBuffer = (z) => (z.bank ? bankKey(z.input, z.root) : z.input);
531
+
532
+ /** Why a zone list can't be used, or "". */
533
+ export function zonesProblem(zones, at = "zones") {
534
+ if (!Array.isArray(zones) || !zones.length || zones.length > INSTRUMENT_LIMITS.zones) return `${at}: a list of 1 to ${INSTRUMENT_LIMITS.zones} zones { input, lo, hi, root }`;
535
+ for (const [i, z] of zones.entries()) {
536
+ const w = `${at}[${i}]`;
537
+ if (!isObject(z)) return `${w}: an object { input, lo, hi, root, loop?, loopStart?, loopEnd?, gain?, bank? }`;
538
+ for (const k of Object.keys(z)) if (!["input", "lo", "hi", "root", "loop", "loopStart", "loopEnd", "gain", "bank"].includes(k)) return `${w} has no field "${k}"`;
539
+ if (typeof z.input !== "string" || !INPUT.test(z.input)) return `${w}.input: the name of an audio input of the voices pane (letters, digits, _)`;
540
+ for (const k of ["lo", "hi", "root"]) if (!Number.isInteger(z[k]) || z[k] < 0 || z[k] > 127) return `${w}.${k}: a MIDI note from 0 to 127`;
541
+ if (z.lo > z.hi) return `${w}: lo is above hi`;
542
+ if (z.loop !== undefined && typeof z.loop !== "boolean") return `${w}.loop: true or false`;
543
+ if (z.bank !== undefined && typeof z.bank !== "boolean") return `${w}.bank: true or false`;
544
+ for (const k of ["loopStart", "loopEnd"]) if (z[k] !== undefined && (!Number.isInteger(z[k]) || z[k] < 0 || z[k] > LOOP_MS_MAX)) return `${w}.${k}: whole milliseconds from 0 to ${LOOP_MS_MAX}`;
545
+ if (z.loopEnd > 0 && z.loopEnd <= (z.loopStart ?? 0)) return `${w}: loopEnd is not after loopStart (0 and 0 loop the whole recording)`;
546
+ if (z.gain !== undefined && (!num(z.gain) || z.gain < 0 || z.gain > 2)) return `${w}.gain: a number from 0 to 2`;
547
+ }
548
+ return "";
549
+ }
550
+
551
+ /** The zone that answers to `note` (the narrowest range that holds it; the first on a tie), or null. */
552
+ export function zoneFor(zones, note) {
553
+ let best = null;
554
+ for (const z of (zones ?? []).map(cleanZone)) if (note >= z.lo && note <= z.hi && (!best || z.hi - z.lo < best.hi - best.lo)) best = z;
555
+ return best;
556
+ }
557
+
558
+ /** The playback rate that takes a recording of `root` to `note` (equal temperament), limited to what the sample module accepts. */
559
+ export const pitchRate = (note, root) => clamp(2 ** ((note - root) / 12), SAMPLE_RATE_RANGE.min, SAMPLE_RATE_RANGE.max);
560
+
561
+ /** A sampler's patch for one note: the zone's sample at the shifted rate through an amplitude envelope; null when no zone answers. */
562
+ function samplerDsp(def, note) {
563
+ const zone = zoneFor(def.zones, note);
564
+ if (!zone) return null;
565
+ const ampEnv = cleanEnv(def.ampEnv, env(0.005, 0.1, 1, 0.25));
566
+ const dsp = {
567
+ version: 1,
568
+ modules: [
569
+ { id: "smp", kind: "sample", params: { rate: round(pitchRate(note, zone.root)) }, options: { input: zoneBuffer(zone), loop: zone.loop, loopStart: zone.loopStart, loopEnd: zone.loopEnd } },
570
+ { id: "zoneGain", kind: "gain", params: { gain: zone.gain } },
571
+ { id: "amp", kind: "gain", params: { gain: 0 } },
572
+ { id: "aenv", kind: "envelope", params: { attack: ampEnv.attack, decay: ampEnv.decay, sustain: ampEnv.sustain, release: ampEnv.release, peak: 1 } },
573
+ { id: "out", kind: "output" },
574
+ ],
575
+ connections: [
576
+ { from: "smp.out", to: "zoneGain.in" },
577
+ { from: "zoneGain.out", to: "amp.in" },
578
+ { from: "aenv.out", to: "amp.gain" },
579
+ { from: "amp.out", to: "out.in" },
580
+ ],
581
+ controls: [],
582
+ };
583
+ return { dsp, notes: [], velocity: ["aenv.peak"], inputs: [zoneBuffer(zone)] };
584
+ }
585
+
586
+ // ── the score's own instruments ──────────────────────────────────────────────
587
+
588
+ /** Why `score.mallory.instruments` can't be used, or "". `{ <id>: { name?, program?, synth } | { name?, program?, zones, ampEnv? } }`. */
589
+ export function instrumentsProblem(map) {
590
+ if (!isObject(map)) return "mallory.instruments: an object keyed by instrument id (patch:<name> or sample:<name>)";
591
+ const ids = Object.keys(map);
592
+ if (ids.length > INSTRUMENT_LIMITS.custom) return `mallory.instruments: at most ${INSTRUMENT_LIMITS.custom} instruments`;
593
+ for (const id of ids) {
594
+ const at = `mallory.instruments.${id}`;
595
+ if (!CUSTOM_ID.test(id)) return `${at}: an id of the form patch:<name> or sample:<name> (letters, digits, - and _, up to 32 characters)`;
596
+ const d = map[id];
597
+ if (!isObject(d)) return `${at}: an object`;
598
+ for (const k of Object.keys(d)) if (!["name", "program", "synth", "zones", "ampEnv"].includes(k)) return `${at} has no field "${k}"`;
599
+ if (d.name !== undefined && (typeof d.name !== "string" || !d.name.trim() || d.name.length > INSTRUMENT_LIMITS.name)) return `${at}.name: text up to ${INSTRUMENT_LIMITS.name} characters`;
600
+ if (d.program !== undefined && (!Number.isInteger(d.program) || d.program < 0 || d.program > 127)) return `${at}.program: a General MIDI program from 0 to 127`;
601
+ if (id.startsWith("patch:")) {
602
+ if (d.zones !== undefined) return `${at}: a patch instrument has a synth, not zones`;
603
+ const p = synthProblem(d.synth, `${at}.synth`);
604
+ if (p) return p;
605
+ } else {
606
+ if (d.synth !== undefined) return `${at}: a sample instrument has zones, not a synth`;
607
+ const p = zonesProblem(d.zones, `${at}.zones`);
608
+ if (p) return p;
609
+ if (d.ampEnv !== undefined) {
610
+ const e = synthProblem({ ampEnv: d.ampEnv }, at);
611
+ if (e) return e;
612
+ }
613
+ }
614
+ }
615
+ return "";
616
+ }
617
+
618
+ const MP3_BITRATES = { 1: [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320], 2: [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160] };
619
+ const MP3_RATES = { 1: [44100, 48000, 32000], 2: [22050, 24000, 16000], 3: [11025, 12000, 8000] };
620
+ const MP3_VERSION = [3, 0, 2, 1]; // the header's two version bits -> MPEG 2.5, (reserved), 2, 1; the table is made once, not per byte scanned
621
+ /** The most bytes of junk (tags, padding, cut frames) between an MP3's frames that are skipped over before the file is called no MP3. */
622
+ const MP3_JUNK_MAX = 1024 * 1024;
623
+
624
+ /** The Layer III frame header at `i`: `{ length, samples, sampleRate, channels }`, or null when the four bytes are not one (free-format, reserved values and other layers included). */
625
+ function mp3Frame(b, i) {
626
+ if (i + 4 > b.length || b[i] !== 0xff || (b[i + 1] & 0xe0) !== 0xe0) return null;
627
+ const version = MP3_VERSION[(b[i + 1] >> 3) & 3]; // MPEG-1, MPEG-2, MPEG-2.5 (1 is reserved)
628
+ if (!version || ((b[i + 1] >> 1) & 3) !== 1) return null; // Layer III only
629
+ const bitrate = MP3_BITRATES[version === 1 ? 1 : 2][b[i + 2] >> 4];
630
+ const sampleRate = MP3_RATES[version][(b[i + 2] >> 2) & 3];
631
+ if (!bitrate || !sampleRate) return null;
632
+ const samples = version === 1 ? 1152 : 576;
633
+ const length = Math.floor(((samples / 8) * bitrate * 1000) / sampleRate) + ((b[i + 2] >> 1) & 1);
634
+ return { length, samples, sampleRate, channels: (b[i + 3] >> 6) === 3 ? 1 : 2 };
635
+ }
636
+
637
+ /**
638
+ * The length of the ID3v2 tag at `at` (header, body, and a footer when its flag says so), or 0 when there is none. It is a tag only as the browser reads
639
+ * one: "ID3", a version and a revision below 0xFF, and four size bytes each below 0x80; anything else the browser does not skip, so neither does this.
640
+ */
641
+ export function id3Length(b, at = 0) {
642
+ if (b.length < at + 10 || b[at] !== 0x49 || b[at + 1] !== 0x44 || b[at + 2] !== 0x33) return 0;
643
+ if (b[at + 3] === 0xff || b[at + 4] === 0xff || (b[at + 6] | b[at + 7] | b[at + 8] | b[at + 9]) & 0x80) return 0;
644
+ return 10 + (b[at + 6] << 21) + (b[at + 7] << 14) + (b[at + 8] << 7) + b[at + 9] + (b[at + 5] & 0x10 ? 10 : 0);
645
+ }
646
+
647
+ /**
648
+ * What an MP3's own bytes say before anything decodes it: `{ problem, seconds, sampleRate, channels }`. The file must start with an ID3 tag or an
649
+ * MPEG audio frame (a file labelled audio/mpeg can be Ogg, FLAC or WAV, which a browser decodes just the same), and its length is the sum of its
650
+ * Layer III frames, every one counted (a low bitrate packs minutes into a few kilobytes, and a first frame says nothing of the rest).
651
+ * `problem` is "" or the sentence for the person.
652
+ */
653
+ export function mp3Info(bytes) {
654
+ const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
655
+ const no = { problem: "isn't an MP3 (no ID3 tag or MPEG audio frame at the start)", seconds: 0, sampleRate: 0, channels: 0 };
656
+ let at = 0;
657
+ // ID3v2 tags (one or more) are skipped, and then the first frame must be exactly there: what the browser decodes behind a tag is whatever it
658
+ // recognises (a FLAC or Ogg too), so junk between the tag and a frame is not looked through.
659
+ for (let n = id3Length(b, at); n; n = id3Length(b, at)) at += n;
660
+ const first = mp3Frame(b, at);
661
+ if (!first || (at + first.length < b.length && !mp3Frame(b, at + first.length))) return no; // a file starts with a frame, and a second follows it
662
+ let seconds = 0;
663
+ let junk = 0;
664
+ // Every frame header that parses is counted, with or without a frame right behind it (a decoder resyncs through junk between frames, and a file that
665
+ // puts a byte of junk after each frame is decoded in full): a count too high only refuses a sound, a count too low lets a long one through.
666
+ while (at + 4 <= b.length) {
667
+ const f = mp3Frame(b, at);
668
+ if (f) {
669
+ seconds += f.samples / f.sampleRate;
670
+ at += f.length;
671
+ } else {
672
+ at += 1; // a trailing tag, a cut frame, something that is not one: look for the next
673
+ if (++junk > MP3_JUNK_MAX) return { ...no, problem: "isn't an MP3 (too much that is not audio between its frames)" };
674
+ }
675
+ }
676
+ return { problem: "", seconds, sampleRate: first.sampleRate, channels: first.channels };
677
+ }
678
+
679
+ /** The audio input names the sampler instruments in `custom` read as audio values (the voices pane must take these as inputs). A bank's input is not one: see `bankPitchesOf`. */
680
+ export function sampleInputsOf(custom) {
681
+ const names = new Set();
682
+ if (isObject(custom)) for (const d of Object.values(custom)) if (isObject(d) && Array.isArray(d.zones)) for (const z of d.zones) if (typeof z?.input === "string" && INPUT.test(z.input) && z.bank !== true) names.add(z.input);
683
+ return [...names];
684
+ }
685
+
686
+ /** The recordings the bank zones in `custom` read: `[{ input, root, key }]`, each pitch of each bank once (`key` is the decoded buffer's name). */
687
+ export function bankPitchesOf(custom) {
688
+ const seen = new Map();
689
+ if (isObject(custom)) for (const d of Object.values(custom)) if (isObject(d) && Array.isArray(d.zones)) for (const z of d.zones) {
690
+ if (z?.bank !== true || typeof z.input !== "string" || !INPUT.test(z.input) || !Number.isInteger(z.root) || z.root < 0 || z.root > 127) continue;
691
+ const key = bankKey(z.input, z.root);
692
+ if (!seen.has(key)) seen.set(key, { input: z.input, root: z.root, key });
693
+ }
694
+ return [...seen.values()];
695
+ }
696
+
697
+ /**
698
+ * The release (seconds a note rings on after it is let go) of a soundfont sampler, by font id, as music-studio's Tone.Sampler sets it: 0.8 for every General
699
+ * MIDI font (src/audio/soundfont.ts:90) and 1 for the Salamander grand (instruments.ts:99). A fixed table keyed by font id (src/audio/soundfont.js FONTS), like
700
+ * SAMPLE_SECONDS; a name that is not in it gets the General MIDI one.
701
+ */
702
+ export const FONT_RELEASE = Object.freeze({ salamander_grand: 1 });
703
+ export const GM_RELEASE = 0.8;
704
+ export const fontRelease = (font) => (typeof font === "string" && Object.hasOwn(FONT_RELEASE, font) ? FONT_RELEASE[font] : GM_RELEASE);
705
+
706
+ /**
707
+ * The score's instruments as they play against the banks the voices pane holds. A soundfont instrument was made (addSoundfont) for the font that was chosen
708
+ * then, with that font's zones and release, but the bank wired to its input can be another font by now (the sample pane's font was changed, or the canvas
709
+ * came from a file made for another font). So a sampler whose zones are all bank zones on one input, when that input holds a loaded bank (`{ font, bank }`
710
+ * with a known font and at least one pitch), plays with that bank: zones from the pitches it holds (the midpoints between roots, like fontZones) and that
711
+ * font's own release. A bank that isn't there (not loaded, refused) changes nothing. The score itself is not changed.
712
+ */
713
+ export function followFonts(custom, inputs) {
714
+ if (!isObject(custom) || !isObject(inputs)) return isObject(custom) ? custom : {};
715
+ let out = null;
716
+ for (const [id, def] of Object.entries(custom)) {
717
+ if (!isObject(def) || !Array.isArray(def.zones) || !def.zones.length || !def.zones.every((z) => z?.bank === true && z.input === def.zones[0].input)) continue;
718
+ const held = inputs[def.zones[0].input];
719
+ const font = isObject(held) ? held.font : undefined;
720
+ if (typeof font !== "string" || !isObject(held.bank)) continue;
721
+ const roots = Object.keys(held.bank).map(Number).filter((n) => Number.isInteger(n) && n >= 0 && n <= 127).sort((a, b) => a - b);
722
+ if (!roots.length) continue;
723
+ const input = def.zones[0].input;
724
+ const zones = roots.map((root, i) => ({ input, bank: true, lo: i === 0 ? 0 : Math.floor((roots[i - 1] + root) / 2) + 1, hi: i === roots.length - 1 ? 127 : Math.floor((root + roots[i + 1]) / 2), root }));
725
+ (out ??= { ...custom })[id] = { ...def, zones, ampEnv: { ...(isObject(def.ampEnv) ? def.ampEnv : {}), release: fontRelease(font) } };
726
+ }
727
+ return out ?? custom;
728
+ }
729
+
730
+ /**
731
+ * What to build for a note on instrument `id`: `{ dsp, notes, velocity, inputs }` or null (an id this module doesn't know, a sampler
732
+ * with no zone for the note, or a custom id the score doesn't define: the pool then plays the voices pane's own patch).
733
+ */
734
+ export function resolveInstrument(id, note, custom = {}) {
735
+ const preset = PRESETS[id];
736
+ if (preset) return preset.drums ? drumDsp(drumOf(note), note) : synthDsp(preset.synth);
737
+ const gm = GM_ID.exec(String(id));
738
+ if (gm) return Number(gm[1]) <= 127 ? synthDsp(PRESETS[presetForProgram(Number(gm[1]))].synth) : null;
739
+ const def = isObject(custom) ? custom[id] : null;
740
+ if (!isObject(def)) return null;
741
+ if (String(id).startsWith("patch:")) return isObject(def.synth) ? synthDsp(def.synth) : null;
742
+ if (String(id).startsWith("sample:")) return Array.isArray(def.zones) ? samplerDsp(def, note) : null;
743
+ return null;
744
+ }
745
+
746
+ /** The key under which a note's patch can be cached (a drum or a sampler zone differs per note; a synth doesn't). */
747
+ export function resolveKey(id, note, custom = {}) {
748
+ if (PRESETS[id]?.drums) return `${id}|${drumOf(note)}|${drumOf(note) === "tom" ? note : ""}`;
749
+ if (String(id).startsWith("sample:")) {
750
+ const zone = zoneFor(custom?.[id]?.zones, note);
751
+ return `${id}|${zone ? `${zoneBuffer(zone)}|${zone.root}|${zone.loop}|${zone.loopStart}|${zone.loopEnd}|${note}` : "none"}`;
752
+ }
753
+ return id;
754
+ }
755
+
756
+ /** A user synth made from a preset (SYN-03: fork a preset into an editable patch): the spec, a name and the preset's program. */
757
+ export function forkPreset(id) {
758
+ const p = PRESETS[id];
759
+ if (!p || p.drums) return null;
760
+ return { name: `${p.name} copy`.slice(0, INSTRUMENT_LIMITS.name), program: p.program, synth: cleanSynth(p.synth) };
761
+ }
762
+
763
+ /** The release (seconds) of a person's own recording played as an instrument: music-studio's 0.4 (INS-10/11). A sampler's `ampEnv.release` sets it; one saved with 0.25 keeps it. */
764
+ export const SAMPLER_RELEASE = 0.4;
765
+
766
+ /** A sampler definition over one audio input, the whole keyboard mapped to it (the common "one recording, played as an instrument"). */
767
+ export function singleZoneSampler(input, root = 60, name = "sampler", release = SAMPLER_RELEASE) {
768
+ return { name, zones: [{ input, lo: 0, hi: 127, root }], ampEnv: { attack: 0.005, decay: 0.1, sustain: 1, release } };
769
+ }
770
+
771
+ /** A colour index for an instrument id (the roll's colour-by-instrument option): stable per id, spread over the palette. */
772
+ export function instrumentHue(id) {
773
+ let h = 2166136261;
774
+ for (const c of String(id)) h = Math.imul(h ^ c.charCodeAt(0), 16777619) >>> 0;
775
+ return h % 360;
776
+ }