@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.
- package/README.md +60 -2
- package/bin/mallory.mjs +51 -0
- package/package.json +51 -4
- package/src/a2a/client.js +511 -0
- package/src/a2a/demo-agent.js +396 -0
- package/src/a2a/hub.js +578 -0
- package/src/a2a/settings.js +88 -0
- package/src/a2a/task.js +358 -0
- package/src/acp/client.js +573 -0
- package/src/acp/demo-agent.js +332 -0
- package/src/acp/hub.js +632 -0
- package/src/acp/settings.js +78 -0
- package/src/actions/map.js +524 -0
- package/src/agent/cloud.js +77 -0
- package/src/agent/compact.js +84 -0
- package/src/agent/constants.js +39 -0
- package/src/agent/diff.js +101 -0
- package/src/agent/fork.js +159 -0
- package/src/agent/grounding.js +73 -0
- package/src/agent/guards.js +129 -0
- package/src/agent/local-transport.js +152 -0
- package/src/agent/loop.js +479 -0
- package/src/agent/park-store.js +77 -0
- package/src/agent/park.js +76 -0
- package/src/agent/ports.js +28 -0
- package/src/agent/providers.js +591 -0
- package/src/agent/restart.js +51 -0
- package/src/agent/router.js +380 -0
- package/src/agent/run.js +861 -0
- package/src/agent/tools.js +247 -0
- package/src/agent-library/engine.js +43 -0
- package/src/ai/bridge.js +155 -0
- package/src/ai/policy.js +131 -0
- package/src/aimatey/vendor.js +18 -0
- package/src/audio/container-duration.js +35 -0
- package/src/audio/instruments.js +776 -0
- package/src/audio/lanes.js +230 -0
- package/src/audio/patch.js +1410 -0
- package/src/audio/plan.js +276 -0
- package/src/audio/rack.js +1006 -0
- package/src/audio/sample-trim.js +293 -0
- package/src/audio/soundfont.js +243 -0
- package/src/audio/take-store.js +87 -0
- package/src/audio/takes.js +129 -0
- package/src/audio/wav.js +170 -0
- package/src/audio/zzfx.js +333 -0
- package/src/autonomy/bundle.js +207 -0
- package/src/autonomy/confine.js +61 -0
- package/src/autonomy/enforce.js +155 -0
- package/src/autonomy/file-kv.js +88 -0
- package/src/autonomy/ledger.js +203 -0
- package/src/autonomy/pins.js +50 -0
- package/src/autonomy/psl/index.js +32 -0
- package/src/autonomy/psl/suffixes.json +1 -0
- package/src/autonomy/record.js +28 -0
- package/src/autonomy/routines.js +107 -0
- package/src/autonomy/server.js +175 -0
- package/src/autonomy/signer-node.js +167 -0
- package/src/autonomy/store.js +43 -0
- package/src/autonomy/unattended.js +13 -0
- package/src/bytes/bytes.js +378 -0
- package/src/calc/syntax.js +125 -0
- package/src/calc/tex.js +28 -0
- package/src/calendar/vendor.js +2 -0
- package/src/clipboard.js +130 -0
- package/src/clsh/clsh.js +3417 -0
- package/src/codec/capnp.js +1804 -0
- package/src/codec/core.js +2043 -0
- package/src/codec/vendor/avro.js +136 -0
- package/src/codec/vendor/cbor.js +25 -0
- package/src/codec/vendor/flatbuffers.js +206 -0
- package/src/codec/vendor/msgpack.js +9 -0
- package/src/codec/vendor/protobuf.js +53 -0
- package/src/delegation/caps.js +60 -0
- package/src/delegation/config.js +32 -0
- package/src/device/model.js +246 -0
- package/src/device/recording.js +198 -0
- package/src/device/stream-model.js +151 -0
- package/src/documents/documents.js +1224 -0
- package/src/effects/catalog.js +63 -0
- package/src/effects/extras.js +133 -0
- package/src/effects/parse.js +339 -0
- package/src/embed/protocol.js +131 -0
- package/src/env/env.js +159 -0
- package/src/exact/vendor.js +45 -0
- package/src/example-meta.js +164 -0
- package/src/examples.js +94 -0
- package/src/export/canvas-image.js +217 -0
- package/src/export/expr-latex-lazy.js +8 -0
- package/src/export/formats.js +322 -0
- package/src/export/latex.js +183 -0
- package/src/export/pane.js +184 -0
- package/src/export/value.js +452 -0
- package/src/export/zip.js +214 -0
- package/src/ext/access.js +58 -0
- package/src/ext/btasks.js +225 -0
- package/src/ext/client.js +209 -0
- package/src/ext/tools.js +69 -0
- package/src/ext/view.js +105 -0
- package/src/ext/webmcp-tabs.js +299 -0
- package/src/files/archive.js +232 -0
- package/src/files/files.js +317 -0
- package/src/formats/json.js +24 -0
- package/src/formats/jupyter.js +188 -0
- package/src/formats/markdown.js +254 -0
- package/src/formats/n8n.js +276 -0
- package/src/formats/node-red.js +363 -0
- package/src/formats/registry.js +177 -0
- package/src/formats/rivet.js +259 -0
- package/src/formats/shared.js +98 -0
- package/src/formats/structure.js +182 -0
- package/src/formats/yaml.js +127 -0
- package/src/frame/frame.js +962 -0
- package/src/frame/vendor.js +1484 -0
- package/src/gate/audit.js +116 -0
- package/src/gate/gate.js +365 -0
- package/src/gate/policy.js +295 -0
- package/src/gate/scripted.js +110 -0
- package/src/gate/seams.js +32 -0
- package/src/gate/store.js +66 -0
- package/src/geometry/model.js +533 -0
- package/src/grant-key.js +149 -0
- package/src/graph/model.js +381 -0
- package/src/headless/a2a-push.js +123 -0
- package/src/headless/channels/config.js +142 -0
- package/src/headless/channels/connectors.js +283 -0
- package/src/headless/channels/index.js +257 -0
- package/src/headless/channels/mail.js +197 -0
- package/src/headless/channels/mailnet.js +223 -0
- package/src/headless/channels/platforms.js +194 -0
- package/src/headless/channels/replay.js +49 -0
- package/src/headless/cli.js +1397 -0
- package/src/headless/companion-client.js +182 -0
- package/src/headless/cost-cli.js +177 -0
- package/src/headless/deprecations-cli.js +102 -0
- package/src/headless/examples.js +48 -0
- package/src/headless/ffmpeg-exec.js +217 -0
- package/src/headless/gateways/config.js +213 -0
- package/src/headless/gateways/homeassistant.js +159 -0
- package/src/headless/gateways/index.js +121 -0
- package/src/headless/gateways/matter.js +150 -0
- package/src/headless/gateways/mqtt-client.js +177 -0
- package/src/headless/gateways/mqtt.js +70 -0
- package/src/headless/gateways/netway.js +226 -0
- package/src/headless/gateways/serverpod-worker.mjs +16 -0
- package/src/headless/gateways/serverpod.js +71 -0
- package/src/headless/gateways/util.js +27 -0
- package/src/headless/grant-cli.js +208 -0
- package/src/headless/guard.js +125 -0
- package/src/headless/guards.js +124 -0
- package/src/headless/machine-cli.js +853 -0
- package/src/headless/mcp-endpoint.js +287 -0
- package/src/headless/mcp-roots.js +38 -0
- package/src/headless/model-endpoint.js +88 -0
- package/src/headless/net.js +151 -0
- package/src/headless/node.js +263 -0
- package/src/headless/npm-tarball.js +29 -0
- package/src/headless/operator-page.js +112 -0
- package/src/headless/operator.js +242 -0
- package/src/headless/people.js +34 -0
- package/src/headless/pkg-cli.js +1103 -0
- package/src/headless/pkg-serve.js +138 -0
- package/src/headless/process-worker.js +88 -0
- package/src/headless/runner-remote.js +477 -0
- package/src/headless/sandbox-child.mjs +21 -0
- package/src/headless/scheduled.js +557 -0
- package/src/headless/serve-stream.js +97 -0
- package/src/headless/serve.js +2238 -0
- package/src/headless/short-links.js +158 -0
- package/src/headless/static-dirs.js +207 -0
- package/src/headless/trust-file.js +51 -0
- package/src/headless/watch.js +291 -0
- package/src/headless/ws-connect.js +65 -0
- package/src/headless/ws-connections.js +44 -0
- package/src/headless/ws-echo.js +150 -0
- package/src/headless/ws-proxy.js +354 -0
- package/src/headless/ws-ticket.js +48 -0
- package/src/hooks/config.js +50 -0
- package/src/hooks/engine.js +189 -0
- package/src/input/log.js +613 -0
- package/src/input/player.js +217 -0
- package/src/input/replay.js +209 -0
- package/src/jth/vendor.js +28 -0
- package/src/ledger/tx.js +94 -0
- package/src/machine/apply.js +193 -0
- package/src/machine/diff.js +168 -0
- package/src/machine/drive.js +296 -0
- package/src/machine/engine.js +478 -0
- package/src/machine/files-tool.js +76 -0
- package/src/machine/lint.js +139 -0
- package/src/machine/llmtm-trace.js +117 -0
- package/src/machine/llmtm.js +475 -0
- package/src/machine/otel.js +80 -0
- package/src/machine/pane-provider.js +51 -0
- package/src/machine/propose.js +159 -0
- package/src/machine/random.js +52 -0
- package/src/machine/risk.js +107 -0
- package/src/machine/session.js +1017 -0
- package/src/machine/shell-tool.js +45 -0
- package/src/machine/tape.js +349 -0
- package/src/machine/templates.js +104 -0
- package/src/machine/trace.js +664 -0
- package/src/machine/view.js +73 -0
- package/src/machine/vm-tool.js +47 -0
- package/src/machine/watchdog.js +46 -0
- package/src/mcp/app-args.js +51 -0
- package/src/mcp/app-run.js +56 -0
- package/src/mcp/apps.js +468 -0
- package/src/mcp/cache.js +232 -0
- package/src/mcp/client.js +507 -0
- package/src/mcp/demo-app.js +183 -0
- package/src/mcp/demo-server.js +602 -0
- package/src/mcp/elicitation.js +116 -0
- package/src/mcp/hub.js +1326 -0
- package/src/mcp/roots.js +139 -0
- package/src/mcp/sampling.js +105 -0
- package/src/mcp/settings.js +125 -0
- package/src/mcp/tape.js +292 -0
- package/src/mcp/uri-template.js +156 -0
- package/src/mcp/wsh-client.js +164 -0
- package/src/media/animated-codec.js +7 -0
- package/src/media/animated.js +623 -0
- package/src/media/compare-agent.js +70 -0
- package/src/media/compare-job.js +63 -0
- package/src/media/compare-page.js +296 -0
- package/src/media/compare-worker.js +14 -0
- package/src/media/compare.js +600 -0
- package/src/media/contract.js +62 -0
- package/src/media/decode-frame.js +57 -0
- package/src/media/decode-pool.js +188 -0
- package/src/media/ffmpeg-edit.js +344 -0
- package/src/media/ffmpeg-wasm-client.js +121 -0
- package/src/media/ffmpeg-wasm-session.js +79 -0
- package/src/media/ffmpeg-wasm.js +139 -0
- package/src/media/ffmpeg-worker.js +23 -0
- package/src/media/ffmpeg.js +903 -0
- package/src/media/helpers.js +419 -0
- package/src/media/keep.js +108 -0
- package/src/media/metadata-worker.js +16 -0
- package/src/media/metadata.js +2518 -0
- package/src/media/mime.js +102 -0
- package/src/media/page-decode.js +74 -0
- package/src/media/persist.js +114 -0
- package/src/media/png.js +226 -0
- package/src/media/sample-input.js +67 -0
- package/src/media/store.js +86 -0
- package/src/media/wav.js +109 -0
- package/src/midi/mappings.js +250 -0
- package/src/midi/message.js +125 -0
- package/src/model/action-hub.js +143 -0
- package/src/model/adapters.js +284 -0
- package/src/model/agent-runs.js +12 -0
- package/src/model/arrange.js +308 -0
- package/src/model/automation-clock.js +494 -0
- package/src/model/automation.js +653 -0
- package/src/model/batches.js +78 -0
- package/src/model/binary-view.js +195 -0
- package/src/model/breakpoints.js +392 -0
- package/src/model/calc-settings.js +65 -0
- package/src/model/calendar.js +254 -0
- package/src/model/canvas-id.js +5 -0
- package/src/model/canvas.js +5048 -0
- package/src/model/channel-names.js +29 -0
- package/src/model/channels.js +692 -0
- package/src/model/chart-clock.js +631 -0
- package/src/model/chart-code.js +69 -0
- package/src/model/codecs.js +60 -0
- package/src/model/companion-access.js +271 -0
- package/src/model/companion-pane.js +50 -0
- package/src/model/composite.js +324 -0
- package/src/model/context.js +380 -0
- package/src/model/controls.js +231 -0
- package/src/model/converter-presets.js +368 -0
- package/src/model/cost.js +580 -0
- package/src/model/curve-transform.js +122 -0
- package/src/model/cycles.js +176 -0
- package/src/model/debug-log.js +168 -0
- package/src/model/decision-clock.js +100 -0
- package/src/model/decisions.js +265 -0
- package/src/model/desk.js +87 -0
- package/src/model/device-hub.js +400 -0
- package/src/model/diff.js +445 -0
- package/src/model/emit-events.js +179 -0
- package/src/model/errors.js +238 -0
- package/src/model/event-presets.js +297 -0
- package/src/model/events.js +1303 -0
- package/src/model/explicit-setters.js +139 -0
- package/src/model/field-mapping.js +623 -0
- package/src/model/files-pane.js +263 -0
- package/src/model/flow-idle.js +89 -0
- package/src/model/foreach.js +549 -0
- package/src/model/frame-loop.js +71 -0
- package/src/model/frame-pressure.js +180 -0
- package/src/model/function-scaffold.js +1000 -0
- package/src/model/geometry-settings.js +54 -0
- package/src/model/goals.js +176 -0
- package/src/model/graph-settings.js +76 -0
- package/src/model/grid-widget.js +175 -0
- package/src/model/groups.js +332 -0
- package/src/model/hash.js +21 -0
- package/src/model/history.js +259 -0
- package/src/model/http-copy.js +88 -0
- package/src/model/http-send-companion.js +110 -0
- package/src/model/http-send.js +163 -0
- package/src/model/http-tap.js +521 -0
- package/src/model/http-tools.js +1138 -0
- package/src/model/import-lock.js +78 -0
- package/src/model/imports.js +258 -0
- package/src/model/infer-outputs.js +822 -0
- package/src/model/ink-connect.js +150 -0
- package/src/model/ink-diff.js +75 -0
- package/src/model/ink-gone.js +71 -0
- package/src/model/ink-route.js +120 -0
- package/src/model/ink-svg.js +206 -0
- package/src/model/ink.js +739 -0
- package/src/model/input-log-hub.js +456 -0
- package/src/model/input-split.js +69 -0
- package/src/model/json-schema-host.js +9 -0
- package/src/model/json-schema.js +368 -0
- package/src/model/jth.js +78 -0
- package/src/model/latex-expr.js +528 -0
- package/src/model/layout-history.js +120 -0
- package/src/model/lazy-map.js +88 -0
- package/src/model/ledger-pane.js +101 -0
- package/src/model/legacy-viaframe.js +90 -0
- package/src/model/lessons.js +448 -0
- package/src/model/links.js +981 -0
- package/src/model/live.js +411 -0
- package/src/model/math-widget.js +53 -0
- package/src/model/memory-settings.js +33 -0
- package/src/model/midi-controls.js +350 -0
- package/src/model/nl-time.js +408 -0
- package/src/model/notebook.js +137 -0
- package/src/model/pane-view-store.js +15 -0
- package/src/model/partial.js +115 -0
- package/src/model/pause-clock.js +53 -0
- package/src/model/peer-pane.js +32 -0
- package/src/model/persist-state.js +290 -0
- package/src/model/person-only.js +122 -0
- package/src/model/pin.js +209 -0
- package/src/model/plot-3d.js +213 -0
- package/src/model/plot-series.js +157 -0
- package/src/model/plot-settings.js +531 -0
- package/src/model/ports.js +312 -0
- package/src/model/presentation.js +222 -0
- package/src/model/preset-apply.js +316 -0
- package/src/model/preset-banks.js +335 -0
- package/src/model/preset-morph.js +263 -0
- package/src/model/preset-ops.js +205 -0
- package/src/model/preset-player.js +283 -0
- package/src/model/preset-states.js +172 -0
- package/src/model/profile-settings.js +109 -0
- package/src/model/promote.js +103 -0
- package/src/model/protected.js +10 -0
- package/src/model/proxy-log.js +230 -0
- package/src/model/proxy.js +367 -0
- package/src/model/quantity-widget.js +61 -0
- package/src/model/queue-book.js +359 -0
- package/src/model/quick-add.js +224 -0
- package/src/model/rate-limit.js +313 -0
- package/src/model/rate.js +95 -0
- package/src/model/recovery.js +216 -0
- package/src/model/rename-follow.js +113 -0
- package/src/model/repeater.js +1126 -0
- package/src/model/retention.js +664 -0
- package/src/model/route-edit.js +132 -0
- package/src/model/router.js +155 -0
- package/src/model/runaway.js +232 -0
- package/src/model/runlog.js +1033 -0
- package/src/model/runners/a2a.js +2 -0
- package/src/model/runners/acp.js +2 -0
- package/src/model/runners/actions.js +4 -0
- package/src/model/runners/agent.js +4 -0
- package/src/model/runners/audio.js +21 -0
- package/src/model/runners/automation.js +2 -0
- package/src/model/runners/calc.js +23 -0
- package/src/model/runners/catch.js +10 -0
- package/src/model/runners/codec.js +24 -0
- package/src/model/runners/companion-run.js +2 -0
- package/src/model/runners/device.js +7 -0
- package/src/model/runners/dom.js +13 -0
- package/src/model/runners/effects.js +2 -0
- package/src/model/runners/embed.js +11 -0
- package/src/model/runners/eval.js +2 -0
- package/src/model/runners/files.js +19 -0
- package/src/model/runners/geometry.js +23 -0
- package/src/model/runners/goals.js +18 -0
- package/src/model/runners/graph.js +23 -0
- package/src/model/runners/html.js +2 -0
- package/src/model/runners/http-proxy.js +185 -0
- package/src/model/runners/http-send.js +61 -0
- package/src/model/runners/http-static.js +83 -0
- package/src/model/runners/http-tap.js +26 -0
- package/src/model/runners/http.js +40 -0
- package/src/model/runners/import.js +2 -0
- package/src/model/runners/index.js +74 -0
- package/src/model/runners/input.js +14 -0
- package/src/model/runners/inputlog.js +7 -0
- package/src/model/runners/ledger.js +15 -0
- package/src/model/runners/machine.js +4 -0
- package/src/model/runners/mcp.js +2 -0
- package/src/model/runners/mcpapp.js +2 -0
- package/src/model/runners/media.js +18 -0
- package/src/model/runners/memory.js +28 -0
- package/src/model/runners/mesh-inspect.js +13 -0
- package/src/model/runners/peer.js +14 -0
- package/src/model/runners/plot.js +22 -0
- package/src/model/runners/render.js +14 -0
- package/src/model/runners/respond.js +2 -0
- package/src/model/runners/sample-soundfont.js +85 -0
- package/src/model/runners/sample.js +159 -0
- package/src/model/runners/scene.js +8 -0
- package/src/model/runners/score.js +24 -0
- package/src/model/runners/secret.js +10 -0
- package/src/model/runners/select.js +2 -0
- package/src/model/runners/shared.js +4 -0
- package/src/model/runners/shares.js +15 -0
- package/src/model/runners/shell.js +7 -0
- package/src/model/runners/skill.js +26 -0
- package/src/model/runners/state.js +2 -0
- package/src/model/runners/statechart.js +4 -0
- package/src/model/runners/subgraph.js +9 -0
- package/src/model/runners/tabs.js +25 -0
- package/src/model/runners/terminal.js +5 -0
- package/src/model/runners/text.js +4 -0
- package/src/model/runners/timer.js +7 -0
- package/src/model/runners/traffic.js +65 -0
- package/src/model/runners/trigger.js +2 -0
- package/src/model/runners/verdict.js +29 -0
- package/src/model/runners/vm.js +7 -0
- package/src/model/runners/wait.js +4 -0
- package/src/model/runners/ws-client.js +57 -0
- package/src/model/safe-regex.js +719 -0
- package/src/model/sample-settings.js +43 -0
- package/src/model/sample-source.js +47 -0
- package/src/model/saved-mapping.js +153 -0
- package/src/model/score-controllers.js +87 -0
- package/src/model/score-edit.js +399 -0
- package/src/model/score-instruments.js +300 -0
- package/src/model/score-library.js +407 -0
- package/src/model/score-markup.js +235 -0
- package/src/model/score-mix.js +248 -0
- package/src/model/score-patterns.js +276 -0
- package/src/model/score-selection.js +34 -0
- package/src/model/score-time.js +139 -0
- package/src/model/score-transforms.js +336 -0
- package/src/model/score-transport.js +192 -0
- package/src/model/selection.js +351 -0
- package/src/model/serial-controls.js +328 -0
- package/src/model/shares-pane.js +17 -0
- package/src/model/shell-pane.js +106 -0
- package/src/model/signature.js +1122 -0
- package/src/model/size-hints.js +106 -0
- package/src/model/size-ratio.js +12 -0
- package/src/model/skill-settings.js +23 -0
- package/src/model/snapping.js +466 -0
- package/src/model/split.js +375 -0
- package/src/model/spring-player.js +222 -0
- package/src/model/statecharts.js +1369 -0
- package/src/model/states-preset.js +208 -0
- package/src/model/static-route.js +100 -0
- package/src/model/step-words.js +45 -0
- package/src/model/subgraph.js +1042 -0
- package/src/model/switch.js +98 -0
- package/src/model/tabs-store.js +10 -0
- package/src/model/tensor-view.js +146 -0
- package/src/model/timer-clock.js +361 -0
- package/src/model/timers.js +422 -0
- package/src/model/timing.js +212 -0
- package/src/model/traffic-agent.js +111 -0
- package/src/model/traffic-store.js +20 -0
- package/src/model/traffic.js +665 -0
- package/src/model/transport.js +364 -0
- package/src/model/turns.js +86 -0
- package/src/model/types.js +425 -0
- package/src/model/value-path.js +138 -0
- package/src/model/versions.js +535 -0
- package/src/model/view-outputs.js +144 -0
- package/src/model/viewport-bookmarks.js +194 -0
- package/src/model/virtual-clock.js +85 -0
- package/src/model/vm-pane.js +258 -0
- package/src/model/wait-clock.js +715 -0
- package/src/model/wait-persist.js +248 -0
- package/src/model/waits.js +431 -0
- package/src/model/watch.js +80 -0
- package/src/model/webhook.js +496 -0
- package/src/model/when.js +48 -0
- package/src/model/widget-values.js +392 -0
- package/src/model/window-commands.js +278 -0
- package/src/model/windows.js +348 -0
- package/src/model/wire-inspect.js +343 -0
- package/src/model/wire-ops.js +324 -0
- package/src/model/wire-pipeline.js +378 -0
- package/src/model/wire-route.js +637 -0
- package/src/model/workspaces.js +122 -0
- package/src/model/ws-client.js +155 -0
- package/src/model/ws-demo.js +31 -0
- package/src/model/ws-frames.js +141 -0
- package/src/model/ws-hub.js +219 -0
- package/src/model/ws-served.js +13 -0
- package/src/model/xstate.js +374 -0
- package/src/narrative/narrative.js +1557 -0
- package/src/network/auth.js +224 -0
- package/src/network/csp-frame.js +197 -0
- package/src/network/declarative-shadow.js +27 -0
- package/src/network/frame-net-shim.js +962 -0
- package/src/network/hosts.js +157 -0
- package/src/network/policy.js +520 -0
- package/src/network/rtc-shim.js +418 -0
- package/src/network/secret-gate.js +78 -0
- package/src/network/secrets.js +261 -0
- package/src/network/sockets.js +287 -0
- package/src/network/store.js +186 -0
- package/src/network/streams.js +99 -0
- package/src/packages/asset-values.js +50 -0
- package/src/packages/assets.js +99 -0
- package/src/packages/deprecation.js +203 -0
- package/src/packages/fetch.js +152 -0
- package/src/packages/function-canvas.js +73 -0
- package/src/packages/module.js +120 -0
- package/src/packages/package.js +474 -0
- package/src/packages/published.js +27 -0
- package/src/packages/requires.js +83 -0
- package/src/packages/signing.js +145 -0
- package/src/packages/trust.js +107 -0
- package/src/panes/a2a.js +51 -0
- package/src/panes/acp.js +60 -0
- package/src/panes/actions.js +54 -0
- package/src/panes/agent.js +83 -0
- package/src/panes/audio.js +103 -0
- package/src/panes/automation.js +112 -0
- package/src/panes/calc.js +67 -0
- package/src/panes/catch.js +52 -0
- package/src/panes/codec.js +59 -0
- package/src/panes/colors.js +12 -0
- package/src/panes/companion.js +54 -0
- package/src/panes/decision.js +65 -0
- package/src/panes/device.js +56 -0
- package/src/panes/dom.js +37 -0
- package/src/panes/effects.js +118 -0
- package/src/panes/embed.js +30 -0
- package/src/panes/eval.js +186 -0
- package/src/panes/fields.js +299 -0
- package/src/panes/files.js +45 -0
- package/src/panes/gate.js +70 -0
- package/src/panes/geometry.js +64 -0
- package/src/panes/goals.js +75 -0
- package/src/panes/graph.js +66 -0
- package/src/panes/html.js +54 -0
- package/src/panes/http.js +82 -0
- package/src/panes/import.js +38 -0
- package/src/panes/input.js +124 -0
- package/src/panes/inputlog.js +66 -0
- package/src/panes/ledger.js +56 -0
- package/src/panes/machine.js +138 -0
- package/src/panes/mcp.js +85 -0
- package/src/panes/mcpapp.js +64 -0
- package/src/panes/media.js +38 -0
- package/src/panes/memory.js +46 -0
- package/src/panes/mesh-inspect.js +49 -0
- package/src/panes/note.js +38 -0
- package/src/panes/peer.js +44 -0
- package/src/panes/plot.js +196 -0
- package/src/panes/registry.js +475 -0
- package/src/panes/render.js +87 -0
- package/src/panes/respond.js +44 -0
- package/src/panes/router.js +84 -0
- package/src/panes/sample.js +75 -0
- package/src/panes/scene.js +55 -0
- package/src/panes/score.js +87 -0
- package/src/panes/secret.js +38 -0
- package/src/panes/select.js +67 -0
- package/src/panes/shader.js +166 -0
- package/src/panes/shared.js +33 -0
- package/src/panes/shares.js +43 -0
- package/src/panes/shell.js +47 -0
- package/src/panes/skill.js +44 -0
- package/src/panes/state.js +91 -0
- package/src/panes/statechart.js +63 -0
- package/src/panes/story.js +33 -0
- package/src/panes/subgraph.js +94 -0
- package/src/panes/tabs.js +52 -0
- package/src/panes/terminal.js +57 -0
- package/src/panes/text.js +36 -0
- package/src/panes/timer.js +55 -0
- package/src/panes/traffic.js +59 -0
- package/src/panes/verdict.js +62 -0
- package/src/panes/vm.js +46 -0
- package/src/panes/wait.js +61 -0
- package/src/panes/watch.js +57 -0
- package/src/panes/webhook.js +67 -0
- package/src/panes/ws-client.js +67 -0
- package/src/persist.js +281 -0
- package/src/plot/tex.js +19 -0
- package/src/plot/vendor.js +59 -0
- package/src/plot/view-vendor.js +5 -0
- package/src/privacy/levels.js +108 -0
- package/src/protocol/devtools.js +116 -0
- package/src/protocol/inspector.js +368 -0
- package/src/render/time.js +381 -0
- package/src/rooms/mesh-metrics.js +162 -0
- package/src/run/companion.js +355 -0
- package/src/run/describe.js +114 -0
- package/src/run/local-model.js +150 -0
- package/src/run/monitor.js +208 -0
- package/src/run/publish.js +360 -0
- package/src/run/respond-outcome.js +12 -0
- package/src/run/run.js +820 -0
- package/src/run/runner-pairing.js +243 -0
- package/src/run/values.js +122 -0
- package/src/runtime/compile.js +122 -0
- package/src/runtime/console-tag.js +64 -0
- package/src/runtime/frame-signals.js +126 -0
- package/src/runtime/iteration-push.js +19 -0
- package/src/runtime/keys.js +474 -0
- package/src/runtime/midi-input.js +170 -0
- package/src/runtime/person-waits.js +140 -0
- package/src/runtime/resource-timing.js +56 -0
- package/src/runtime/runtime.js +2150 -0
- package/src/runtime/sandbox-modules.js +163 -0
- package/src/runtime/spring.js +246 -0
- package/src/runtime/strict.js +215 -0
- package/src/runtime/transfer.js +75 -0
- package/src/runtime/tween.js +158 -0
- package/src/runtime/wasm-fuel.js +596 -0
- package/src/runtime/worker/00-prelude.js +88 -0
- package/src/runtime/worker/10-helpers.js +295 -0
- package/src/runtime/worker/20-io.js +645 -0
- package/src/runtime/worker/30-previews.js +210 -0
- package/src/runtime/worker/40-profile-lineage.js +278 -0
- package/src/runtime/worker/50-own-worker.js +233 -0
- package/src/runtime/worker/60-timers.js +172 -0
- package/src/runtime/worker/70-state-keyed.js +193 -0
- package/src/runtime/worker/80-each-compile-generators.js +619 -0
- package/src/runtime/worker/90-events-operators.js +655 -0
- package/src/runtime/worker/95-agents-batches.js +1820 -0
- package/src/runtime/worker/96-plot.js +47 -0
- package/src/runtime/worker/97-calc.js +28 -0
- package/src/runtime/worker/98-geometry.js +24 -0
- package/src/runtime/worker/99-graph.js +30 -0
- package/src/runtime/worker/99-shell.js +30 -0
- package/src/safety/config.js +57 -0
- package/src/safety/engine.js +324 -0
- package/src/scene/pixi-scene.js +806 -0
- package/src/scene/scene-assets.js +241 -0
- package/src/scene/scene-edit.js +319 -0
- package/src/secret/settings.js +41 -0
- package/src/security/multipart.js +257 -0
- package/src/security/redact.js +261 -0
- package/src/serial/broker.js +473 -0
- package/src/serial/config.js +185 -0
- package/src/serial/framers.js +389 -0
- package/src/serial/packets.js +64 -0
- package/src/shader/audio-texture.js +87 -0
- package/src/shader/channels.js +496 -0
- package/src/shader/common.js +90 -0
- package/src/shader/model.js +867 -0
- package/src/shader/passes.js +150 -0
- package/src/shader/shadertoy.js +198 -0
- package/src/shell/hub.js +287 -0
- package/src/sim/checkpoints.js +850 -0
- package/src/sim/compile.js +37 -0
- package/src/sim/fixed.js +377 -0
- package/src/sim/headless.js +205 -0
- package/src/sim/physics.js +399 -0
- package/src/smf-helper/vendor.js +2 -0
- package/src/sources/config.js +435 -0
- package/src/storage.js +153 -0
- package/src/table/table-geo.js +2344 -0
- package/src/table/table-lineage.js +808 -0
- package/src/table/table-quality.js +355 -0
- package/src/table/table-schema.js +392 -0
- package/src/table/table-sql.js +1650 -0
- package/src/table/table-stats.js +480 -0
- package/src/table/table.js +2102 -0
- package/src/tensor/tensor.js +1153 -0
- package/src/terminal/hub.js +715 -0
- package/src/terminal/screen.js +516 -0
- package/src/tests/capture.js +88 -0
- package/src/tests/compare.js +480 -0
- package/src/tests/dataset.js +170 -0
- package/src/tests/evaluate.js +286 -0
- package/src/tests/from-runs.js +99 -0
- package/src/tests/judge.js +134 -0
- package/src/tests/matchers.js +263 -0
- package/src/tests/matrix-spec.js +87 -0
- package/src/tests/matrix.js +397 -0
- package/src/tests/metrics.js +369 -0
- package/src/tests/no-value.js +42 -0
- package/src/tests/pane-check.js +45 -0
- package/src/tests/report.js +124 -0
- package/src/tests/reporters.js +140 -0
- package/src/tests/run.js +155 -0
- package/src/tilemap/tilemap.js +1122 -0
- package/src/units/units.js +3 -0
- package/src/util/bytes-text.js +21 -0
- package/src/util/num.js +10 -0
- package/src/util/regexp.js +2 -0
- package/src/util/text.js +38 -0
- package/src/verdict/engine.js +154 -0
- package/src/vm/guest-wsh.js +108 -0
- package/src/vm/hub.js +457 -0
- package/src/vm/image-files.js +4 -0
- package/src/vm/image.js +33 -0
- package/src/vm/image.lock.json +13 -0
- package/src/vm/link.js +266 -0
- package/src/vm/mount.js +212 -0
- package/src/vm/net.js +85 -0
- package/src/vm/pipe-ws.js +187 -0
- package/src/vm/v86-loader.js +11 -0
- package/src/webmcp/args.js +212 -0
- package/src/webmcp/hidden.js +218 -0
- package/src/webmcp/text.js +250 -0
- package/src/webmcp/tools/bookmark-tools.js +106 -0
- package/src/webmcp/tools/breakpoint-tools.js +48 -0
- package/src/webmcp/tools/canvases.js +208 -0
- package/src/webmcp/tools/context-tools.js +84 -0
- package/src/webmcp/tools/core.js +170 -0
- package/src/webmcp/tools/devices.js +41 -0
- package/src/webmcp/tools/edit.js +357 -0
- package/src/webmcp/tools/event-tools.js +145 -0
- package/src/webmcp/tools/image-tools.js +173 -0
- package/src/webmcp/tools/ink-tools.js +247 -0
- package/src/webmcp/tools/input-log-tools.js +163 -0
- package/src/webmcp/tools/live.js +166 -0
- package/src/webmcp/tools/machine-tools.js +74 -0
- package/src/webmcp/tools/media.js +161 -0
- package/src/webmcp/tools/midi-tools.js +32 -0
- package/src/webmcp/tools/preset-tools.js +184 -0
- package/src/webmcp/tools/quick-add-tools.js +95 -0
- package/src/webmcp/tools/reshape.js +152 -0
- package/src/webmcp/tools/run-tools.js +309 -0
- package/src/webmcp/tools/runs.js +101 -0
- package/src/webmcp/tools/scaffold-tools.js +161 -0
- package/src/webmcp/tools/serial-tools.js +36 -0
- package/src/webmcp/tools/shared.js +338 -0
- package/src/webmcp/tools/subgraphs.js +360 -0
- package/src/webmcp/tools/tests.js +170 -0
- package/src/webmcp/tools/traffic-tools.js +70 -0
- package/src/webmcp/tools/transport-tools.js +65 -0
- package/src/webmcp/tools/version-tools.js +126 -0
- package/src/webmcp/tools/versions.js +11 -0
- package/src/webmcp/tools/wire-tools.js +90 -0
- package/src/webmcp/tools/workspace-tools.js +93 -0
- package/src/webmcp/tools.js +1323 -0
- package/src/wsh/connect.js +347 -0
- package/src/wsh/demo-host.js +361 -0
- package/src/wsh/e2e.js +27 -0
- package/src/wsh/keys.js +154 -0
- package/src/wsh/known-hosts.js +39 -0
- package/src/wsh/private-key.js +95 -0
- package/src/wsh/reverse.js +34 -0
- package/src/wsh/settings.js +118 -0
- package/src/wsh/transfer.js +62 -0
- package/src/wsh/vendor.js +5 -0
- package/src/x402/challenge.js +171 -0
- package/src/x402/demo-server.js +127 -0
- package/src/x402/pay.js +125 -0
- package/src/x402/retry.js +95 -0
- package/src/x402/store.js +76 -0
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
// Physics worlds for simulations (docs/guide/graphics.md, "Physics with Rapier"): the pure part. No DOM, no wall
|
|
2
|
+
// clock, no Math.random, so it runs under node --test, in the headless runner's sandbox and, as source
|
|
3
|
+
// text (`.toString()`), inside a render pane's frame (src/render/frame.js), like the checkpoint engine.
|
|
4
|
+
//
|
|
5
|
+
// A simulation's code names `physics`; `physics.world2d(opts)` in the factory body makes a world
|
|
6
|
+
// whose bodies are driven by `world.step()` in `step`. Rapier's own `takeSnapshot()` bytes are part of
|
|
7
|
+
// every checkpoint (the `hooks` below are what createSimulation calls), so seeking back and replaying
|
|
8
|
+
// reach the same bodies the run before had. The determinism is the same machine's: the same Rapier
|
|
9
|
+
// build gives the same numbers, which a frame hash can check.
|
|
10
|
+
//
|
|
11
|
+
// `createPhysics(RAPIER)` takes the loaded, initialised Rapier 2D module (the `-compat` build, whose
|
|
12
|
+
// WebAssembly is embedded, so loading it asks nothing but the CDN for the script) and is
|
|
13
|
+
// self-contained: it uses nothing outside its own body.
|
|
14
|
+
|
|
15
|
+
/** The Rapier build a frame (and the headless runner) loads: an exact version of the `-compat` package, WebAssembly embedded. */
|
|
16
|
+
export const RAPIER_VERSION = "0.21.0";
|
|
17
|
+
export const RAPIER_URL = `https://esm.sh/@dimforge/rapier2d-compat@${RAPIER_VERSION}`;
|
|
18
|
+
/** The host a physics simulation needs the canvas to allow (its network prompt names it). */
|
|
19
|
+
export const RAPIER_HOST = "esm.sh";
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Whether a simulation's code uses `physics` as a name (a comment or a string that says it doesn't count
|
|
23
|
+
* much: a false yes only loads Rapier early, so the check is a plain word search).
|
|
24
|
+
*/
|
|
25
|
+
export function usesPhysics(code) {
|
|
26
|
+
return /(?<![\w$.])physics(?![\w$])/.test(String(code ?? ""));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The physics of one simulation run: `{ world2d, worlds, hooks, tables, takeEvents, dispose, debugDrawAll }`.
|
|
31
|
+
* `world2d` is what the code sees as `physics.world2d`. `hooks` is what createSimulation takes as `extras`
|
|
32
|
+
* (reset / capture / restore / beginStep), so the worlds' snapshots travel in the checkpoints.
|
|
33
|
+
*/
|
|
34
|
+
export function createPhysics(RAPIER) {
|
|
35
|
+
const worlds = [];
|
|
36
|
+
let disposed = false;
|
|
37
|
+
|
|
38
|
+
const num = (v, fallback) => (Number.isFinite(Number(v)) && v !== null && v !== "" && v !== undefined ? Number(v) : fallback);
|
|
39
|
+
const round = (v) => Math.round(v * 1e6) / 1e6 || 0;
|
|
40
|
+
const scratch = new DataView(new ArrayBuffer(8));
|
|
41
|
+
// A handle is a generational index packed in the bits of a float: its low 32 bits are the slot, which a snapshot keeps.
|
|
42
|
+
const slot = (handle) => {
|
|
43
|
+
scratch.setFloat64(0, handle, true);
|
|
44
|
+
return scratch.getUint32(0, true);
|
|
45
|
+
};
|
|
46
|
+
const vec = (v, fallback) => (Array.isArray(v) ? { x: num(v[0], fallback.x), y: num(v[1], fallback.y) } : v && typeof v === "object" ? { x: num(v.x, fallback.x), y: num(v.y, fallback.y) } : fallback);
|
|
47
|
+
const BODY_TYPES = ["dynamic", "fixed", "kinematic", "kinematic"]; // RigidBodyType: Dynamic, Fixed, KinematicPositionBased, KinematicVelocityBased
|
|
48
|
+
const SHAPES = ["ball", "box", "capsule"]; // the ShapeType values 0, 1, 2
|
|
49
|
+
const checksum = (bytes) => {
|
|
50
|
+
let a = 0x811c9dc5;
|
|
51
|
+
let b = 0x9747b28c;
|
|
52
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
53
|
+
a = Math.imul(a ^ bytes[i], 0x01000193);
|
|
54
|
+
b = Math.imul(b ^ bytes[i], 0x85ebca6b);
|
|
55
|
+
b ^= b >>> 13;
|
|
56
|
+
}
|
|
57
|
+
return (a >>> 0).toString(16).padStart(8, "0") + (b >>> 0).toString(16).padStart(8, "0");
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
function make(options = {}) {
|
|
61
|
+
if (disposed) throw new Error("this physics is closed: its pane has gone");
|
|
62
|
+
const o = options && typeof options === "object" ? options : {};
|
|
63
|
+
const gravity = vec(o.gravity, { x: 0, y: -9.81 });
|
|
64
|
+
const config = {
|
|
65
|
+
name: String(o.name ?? (worlds.length ? `world${worlds.length + 1}` : "world")),
|
|
66
|
+
events: o.events === true,
|
|
67
|
+
view: { scale: num(o.view?.scale, 1), x: num(o.view?.x, 0), y: num(o.view?.y, 0), flipY: Boolean(o.view?.flipY) },
|
|
68
|
+
};
|
|
69
|
+
if (worlds.some((w) => w.name === config.name)) throw new Error(`there is already a physics world named "${config.name}": make each world once, in the code's top level (not in init), and give each its own name`);
|
|
70
|
+
let raw = new RAPIER.World(gravity);
|
|
71
|
+
const queue = new RAPIER.EventQueue(true);
|
|
72
|
+
let baseline = null;
|
|
73
|
+
let events = [];
|
|
74
|
+
let steps = 0;
|
|
75
|
+
let bodyIndex = null; // slot -> RigidBody, rebuilt when bodies come or go
|
|
76
|
+
let colliderIndex = null;
|
|
77
|
+
const dirty = () => {
|
|
78
|
+
bodyIndex = null;
|
|
79
|
+
colliderIndex = null;
|
|
80
|
+
};
|
|
81
|
+
const bodies = () => {
|
|
82
|
+
if (!bodyIndex) {
|
|
83
|
+
bodyIndex = new Map();
|
|
84
|
+
raw.bodies.forEach((b) => bodyIndex.set(slot(b.handle), b));
|
|
85
|
+
}
|
|
86
|
+
return bodyIndex;
|
|
87
|
+
};
|
|
88
|
+
const colliders = () => {
|
|
89
|
+
if (!colliderIndex) {
|
|
90
|
+
colliderIndex = new Map();
|
|
91
|
+
raw.colliders.forEach((c) => colliderIndex.set(slot(c.handle), c));
|
|
92
|
+
}
|
|
93
|
+
return colliderIndex;
|
|
94
|
+
};
|
|
95
|
+
const bodyOf = (id) => {
|
|
96
|
+
const b = bodies().get(id);
|
|
97
|
+
if (!b) throw new Error(`world "${config.name}" has no body ${id}`);
|
|
98
|
+
return b;
|
|
99
|
+
};
|
|
100
|
+
const colliderDesc = (c = {}) => {
|
|
101
|
+
const shape = String(c.shape ?? "box");
|
|
102
|
+
let d;
|
|
103
|
+
if (shape === "box") d = RAPIER.ColliderDesc.cuboid(num(c.hx, 0.5), num(c.hy, 0.5));
|
|
104
|
+
else if (shape === "ball") d = RAPIER.ColliderDesc.ball(num(c.r, 0.5));
|
|
105
|
+
else if (shape === "capsule") d = RAPIER.ColliderDesc.capsule(num(c.halfHeight, 0.5), num(c.r, 0.25));
|
|
106
|
+
else throw new Error(`collider shape "${shape}" isn't one of box (hx, hy), ball (r) or capsule (halfHeight, r)`);
|
|
107
|
+
if (c.density !== undefined) d.setDensity(num(c.density, 1));
|
|
108
|
+
if (c.friction !== undefined) d.setFriction(num(c.friction, 0.5));
|
|
109
|
+
if (c.restitution !== undefined) d.setRestitution(num(c.restitution, 0));
|
|
110
|
+
if (c.sensor) d.setSensor(true);
|
|
111
|
+
if (c.ox !== undefined || c.oy !== undefined) d.setTranslation(num(c.ox, 0), num(c.oy, 0));
|
|
112
|
+
if (config.events) d.setActiveEvents(RAPIER.ActiveEvents.COLLISION_EVENTS);
|
|
113
|
+
return d;
|
|
114
|
+
};
|
|
115
|
+
const bodyDesc = (b = {}) => {
|
|
116
|
+
const type = String(b.type ?? "dynamic");
|
|
117
|
+
let d;
|
|
118
|
+
if (type === "dynamic") d = RAPIER.RigidBodyDesc.dynamic();
|
|
119
|
+
else if (type === "fixed") d = RAPIER.RigidBodyDesc.fixed();
|
|
120
|
+
else if (type === "kinematic") d = RAPIER.RigidBodyDesc.kinematicVelocityBased();
|
|
121
|
+
else throw new Error(`body type "${type}" isn't dynamic, fixed or kinematic`);
|
|
122
|
+
d.setTranslation(num(b.x, 0), num(b.y, 0));
|
|
123
|
+
if (b.angle !== undefined) d.setRotation(num(b.angle, 0));
|
|
124
|
+
if (b.vx !== undefined || b.vy !== undefined) d.setLinvel(num(b.vx, 0), num(b.vy, 0));
|
|
125
|
+
if (b.angvel !== undefined) d.setAngvel(num(b.angvel, 0));
|
|
126
|
+
if (b.linearDamping !== undefined) d.setLinearDamping(num(b.linearDamping, 0));
|
|
127
|
+
if (b.angularDamping !== undefined) d.setAngularDamping(num(b.angularDamping, 0));
|
|
128
|
+
if (b.gravityScale !== undefined) d.setGravityScale(num(b.gravityScale, 1));
|
|
129
|
+
if (b.canSleep === false) d.setCanSleep(false);
|
|
130
|
+
if (b.ccd) d.setCcdEnabled(true);
|
|
131
|
+
if (b.fixedRotation) d.lockRotations();
|
|
132
|
+
return d;
|
|
133
|
+
};
|
|
134
|
+
const bodyRow = (b) => {
|
|
135
|
+
const p = b.translation();
|
|
136
|
+
const v = b.linvel();
|
|
137
|
+
return { id: slot(b.handle), type: BODY_TYPES[b.bodyType()] ?? "dynamic", x: p.x, y: p.y, angle: b.rotation(), vx: v.x, vy: v.y, angvel: b.angvel(), sleeping: b.isSleeping() };
|
|
138
|
+
};
|
|
139
|
+
const colliderRow = (c) => {
|
|
140
|
+
const t = c.shapeType();
|
|
141
|
+
const row = { id: slot(c.handle), body: c.parent() ? slot(c.parent().handle) : null, shape: SHAPES[t] ?? String(t), sensor: c.isSensor(), friction: c.friction(), restitution: c.restitution() };
|
|
142
|
+
if (t === 1) {
|
|
143
|
+
const h = c.halfExtents();
|
|
144
|
+
row.hx = h.x;
|
|
145
|
+
row.hy = h.y;
|
|
146
|
+
} else if (t === 0) row.r = c.radius();
|
|
147
|
+
else if (t === 2) {
|
|
148
|
+
row.halfHeight = c.halfHeight();
|
|
149
|
+
row.r = c.radius();
|
|
150
|
+
}
|
|
151
|
+
return row;
|
|
152
|
+
};
|
|
153
|
+
const world = {
|
|
154
|
+
name: config.name,
|
|
155
|
+
get index() {
|
|
156
|
+
return worlds.indexOf(state);
|
|
157
|
+
},
|
|
158
|
+
/** Rapier's own World (replaced when a checkpoint is restored: don't keep it). */
|
|
159
|
+
get raw() {
|
|
160
|
+
return raw;
|
|
161
|
+
},
|
|
162
|
+
get gravity() {
|
|
163
|
+
const g = raw.gravity;
|
|
164
|
+
return { x: g.x, y: g.y };
|
|
165
|
+
},
|
|
166
|
+
setGravity(x, y) {
|
|
167
|
+
const g = vec(typeof x === "object" ? x : [x, y], { x: 0, y: 0 });
|
|
168
|
+
raw.gravity = g;
|
|
169
|
+
},
|
|
170
|
+
/** A body with no collider: its id. Fields: type (dynamic, fixed, kinematic), x, y, angle, vx, vy, angvel, linearDamping, angularDamping, gravityScale, canSleep, ccd, fixedRotation. */
|
|
171
|
+
body(b) {
|
|
172
|
+
const made = raw.createRigidBody(bodyDesc(b));
|
|
173
|
+
dirty();
|
|
174
|
+
return slot(made.handle);
|
|
175
|
+
},
|
|
176
|
+
/** A collider on body `bodyId` (null: on no body, fixed in the world): its id. Fields: shape (box hx hy / ball r / capsule halfHeight r), density, friction, restitution, sensor, ox, oy (the collider's offset from its body). */
|
|
177
|
+
collider(bodyId, c) {
|
|
178
|
+
const made = raw.createCollider(colliderDesc(c), bodyId === null || bodyId === undefined ? undefined : bodyOf(bodyId));
|
|
179
|
+
dirty();
|
|
180
|
+
return slot(made.handle);
|
|
181
|
+
},
|
|
182
|
+
/** A body with one collider: the body's id (the collider's is in `colliders()`). Body fields as for `body`, collider fields as for `collider`. */
|
|
183
|
+
add(spec = {}) {
|
|
184
|
+
const id = world.body(spec);
|
|
185
|
+
world.collider(id, spec);
|
|
186
|
+
return id;
|
|
187
|
+
},
|
|
188
|
+
remove(id) {
|
|
189
|
+
raw.removeRigidBody(bodyOf(id));
|
|
190
|
+
dirty();
|
|
191
|
+
},
|
|
192
|
+
/** Change a body: x, y (move), angle, vx, vy, angvel. */
|
|
193
|
+
set(id, to = {}) {
|
|
194
|
+
const b = bodyOf(id);
|
|
195
|
+
if (to.x !== undefined || to.y !== undefined) b.setTranslation({ x: num(to.x, b.translation().x), y: num(to.y, b.translation().y) }, true);
|
|
196
|
+
if (to.angle !== undefined) b.setRotation(num(to.angle, 0), true);
|
|
197
|
+
if (to.vx !== undefined || to.vy !== undefined) b.setLinvel({ x: num(to.vx, b.linvel().x), y: num(to.vy, b.linvel().y) }, true);
|
|
198
|
+
if (to.angvel !== undefined) b.setAngvel(num(to.angvel, 0), true);
|
|
199
|
+
},
|
|
200
|
+
impulse(id, x, y) {
|
|
201
|
+
bodyOf(id).applyImpulse({ x: num(x, 0), y: num(y, 0) }, true);
|
|
202
|
+
},
|
|
203
|
+
force(id, x, y) {
|
|
204
|
+
bodyOf(id).addForce({ x: num(x, 0), y: num(y, 0) }, true);
|
|
205
|
+
},
|
|
206
|
+
/**
|
|
207
|
+
* Advance the world by `dt` seconds (the simulation's fixed `dt`; the world's own when left out) and
|
|
208
|
+
* return the collision events of this step (`[]` unless the world was made with `events: true`):
|
|
209
|
+
* `{ a, b, started, bodyA, bodyB }`, a and b collider ids.
|
|
210
|
+
*/
|
|
211
|
+
step(dt) {
|
|
212
|
+
if (dt !== undefined) raw.timestep = num(dt, raw.timestep);
|
|
213
|
+
raw.step(config.events ? queue : undefined);
|
|
214
|
+
steps++;
|
|
215
|
+
const out = [];
|
|
216
|
+
if (config.events) {
|
|
217
|
+
queue.drainCollisionEvents((h1, h2, started) => {
|
|
218
|
+
const a = colliders().get(slot(h1));
|
|
219
|
+
const b = colliders().get(slot(h2));
|
|
220
|
+
const pa = a?.parent();
|
|
221
|
+
const pb = b?.parent();
|
|
222
|
+
out.push({ a: slot(h1), b: slot(h2), started, bodyA: pa ? slot(pa.handle) : null, bodyB: pb ? slot(pb.handle) : null });
|
|
223
|
+
});
|
|
224
|
+
events.push(...out);
|
|
225
|
+
}
|
|
226
|
+
return out;
|
|
227
|
+
},
|
|
228
|
+
get steps() {
|
|
229
|
+
return steps;
|
|
230
|
+
},
|
|
231
|
+
/** One body as a row: { id, type, x, y, angle, vx, vy, angvel, sleeping }. */
|
|
232
|
+
get(id) {
|
|
233
|
+
return bodyRow(bodyOf(id));
|
|
234
|
+
},
|
|
235
|
+
/** Every body as a row, in the order they were made. */
|
|
236
|
+
bodies() {
|
|
237
|
+
const rows = [];
|
|
238
|
+
raw.bodies.forEach((b) => rows.push(bodyRow(b)));
|
|
239
|
+
return rows;
|
|
240
|
+
},
|
|
241
|
+
/** Every collider as a row: { id, body, shape, sensor, friction, restitution, hx, hy | r | halfHeight, r }. */
|
|
242
|
+
colliders() {
|
|
243
|
+
const rows = [];
|
|
244
|
+
raw.colliders.forEach((c) => rows.push(colliderRow(c)));
|
|
245
|
+
return rows;
|
|
246
|
+
},
|
|
247
|
+
/** The pairs of colliders touching now: { a, b, bodyA, bodyB, points }. */
|
|
248
|
+
contacts() {
|
|
249
|
+
const rows = [];
|
|
250
|
+
raw.colliders.forEach((c) => {
|
|
251
|
+
raw.contactPairsWith(c, (other) => {
|
|
252
|
+
const ia = slot(c.handle);
|
|
253
|
+
const ib = slot(other.handle);
|
|
254
|
+
if (ia > ib) return;
|
|
255
|
+
let points = 0;
|
|
256
|
+
raw.contactPair(c, other, (manifold) => {
|
|
257
|
+
points += manifold.numContacts();
|
|
258
|
+
});
|
|
259
|
+
if (!points) return;
|
|
260
|
+
const pa = c.parent();
|
|
261
|
+
const pb = other.parent();
|
|
262
|
+
rows.push({ a: ia, b: ib, bodyA: pa ? slot(pa.handle) : null, bodyB: pb ? slot(pb.handle) : null, points });
|
|
263
|
+
});
|
|
264
|
+
});
|
|
265
|
+
rows.sort((x, y) => x.a - y.a || x.b - y.b);
|
|
266
|
+
return rows;
|
|
267
|
+
},
|
|
268
|
+
/** The collision events since the last frame began (see `step`). */
|
|
269
|
+
get events() {
|
|
270
|
+
return events.slice();
|
|
271
|
+
},
|
|
272
|
+
/** A hash of the world's snapshot: two worlds with the same bytes have the same hash. */
|
|
273
|
+
checksum() {
|
|
274
|
+
return checksum(raw.takeSnapshot());
|
|
275
|
+
},
|
|
276
|
+
/** Rapier's snapshot bytes (a copy), the part of a checkpoint this world makes. */
|
|
277
|
+
takeSnapshot() {
|
|
278
|
+
return new Uint8Array(raw.takeSnapshot());
|
|
279
|
+
},
|
|
280
|
+
/** Put the world back as `takeSnapshot` left it (the world's `raw` is replaced; ids stay). */
|
|
281
|
+
restoreSnapshot(bytes) {
|
|
282
|
+
const next = RAPIER.World.restoreSnapshot(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes));
|
|
283
|
+
raw.free();
|
|
284
|
+
raw = next;
|
|
285
|
+
dirty();
|
|
286
|
+
},
|
|
287
|
+
/**
|
|
288
|
+
* The tables the pane shows and publishes (at most `limit` rows each; `counts` says how many there are).
|
|
289
|
+
* `checksum` (a hash of the snapshot, which costs a snapshot) only when asked for.
|
|
290
|
+
*/
|
|
291
|
+
tables(limit = 64, withChecksum = true) {
|
|
292
|
+
const clean = (r) => Object.fromEntries(Object.entries(r).map(([k, v]) => [k, typeof v === "number" ? round(v) : v]));
|
|
293
|
+
const first = (set, make) => {
|
|
294
|
+
const rows = [];
|
|
295
|
+
set.forEach((x) => {
|
|
296
|
+
if (rows.length < limit) rows.push(clean(make(x)));
|
|
297
|
+
});
|
|
298
|
+
return rows;
|
|
299
|
+
};
|
|
300
|
+
const k = world.contacts();
|
|
301
|
+
const out = { bodies: first(raw.bodies, bodyRow), colliders: first(raw.colliders, colliderRow), contacts: k.slice(0, limit), events: events.slice(0, limit), counts: { bodies: raw.bodies.len(), colliders: raw.colliders.len(), contacts: k.length, events: events.length } };
|
|
302
|
+
if (withChecksum) out.checksum = world.checksum();
|
|
303
|
+
return out;
|
|
304
|
+
},
|
|
305
|
+
/**
|
|
306
|
+
* Draw the world's wireframes on a 2D context. `view` maps world coordinates to the canvas
|
|
307
|
+
* (`{ scale, x, y, flipY }`: pixels per unit, the canvas point of the world's origin, y up);
|
|
308
|
+
* the world's own `view` option when left out.
|
|
309
|
+
*/
|
|
310
|
+
debugDraw(ctx, view) {
|
|
311
|
+
const v = view ? { scale: num(view.scale, 1), x: num(view.x, 0), y: num(view.y, 0), flipY: Boolean(view.flipY) } : config.view;
|
|
312
|
+
const { vertices, colors } = raw.debugRender();
|
|
313
|
+
const px = (x) => v.x + x * v.scale;
|
|
314
|
+
const py = (y) => (v.flipY ? v.y - y * v.scale : v.y + y * v.scale);
|
|
315
|
+
ctx.save();
|
|
316
|
+
ctx.lineWidth = 1;
|
|
317
|
+
for (let i = 0; i < vertices.length; i += 4) {
|
|
318
|
+
const c = (i / 4) * 4;
|
|
319
|
+
ctx.strokeStyle = `hsla(${Math.round(colors[c] * 360)}, ${Math.round(colors[c + 1] * 100)}%, ${Math.round(Math.max(colors[c + 2], 0.55) * 100)}%, ${Math.max(colors[c + 3], 0.8)})`;
|
|
320
|
+
ctx.beginPath();
|
|
321
|
+
ctx.moveTo(px(vertices[i]), py(vertices[i + 1]));
|
|
322
|
+
ctx.lineTo(px(vertices[i + 2]), py(vertices[i + 3]));
|
|
323
|
+
ctx.stroke();
|
|
324
|
+
}
|
|
325
|
+
ctx.restore();
|
|
326
|
+
},
|
|
327
|
+
};
|
|
328
|
+
const state = { name: config.name, config, world, gravity, get raw() { return raw; }, clearEvents() { events = []; }, takeEvents() { const out = events; events = []; return out; }, free() { raw.free(); queue.free(); } };
|
|
329
|
+
// The world a reset goes back to: what the code made in its top level, before the first seek (see hooks.seal).
|
|
330
|
+
state.seal = () => {
|
|
331
|
+
baseline = new Uint8Array(raw.takeSnapshot());
|
|
332
|
+
};
|
|
333
|
+
state.reset = () => {
|
|
334
|
+
if (baseline) world.restoreSnapshot(baseline);
|
|
335
|
+
events = [];
|
|
336
|
+
steps = 0;
|
|
337
|
+
};
|
|
338
|
+
worlds.push(state);
|
|
339
|
+
return world;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const hooks = {
|
|
343
|
+
/** Once the code has made its worlds (before the first seek): what they hold now is what every reset goes back to. */
|
|
344
|
+
seal() {
|
|
345
|
+
for (const w of worlds) w.seal();
|
|
346
|
+
},
|
|
347
|
+
/** Before `init` runs: every world goes back to what the code made before its first step. */
|
|
348
|
+
reset() {
|
|
349
|
+
for (const w of worlds) w.reset();
|
|
350
|
+
},
|
|
351
|
+
/** The worlds' snapshots (an array of bytes, in the order the worlds were made) and their size. */
|
|
352
|
+
capture() {
|
|
353
|
+
const data = worlds.map((w) => new Uint8Array(w.raw.takeSnapshot()));
|
|
354
|
+
return { data, bytes: data.reduce((n, d) => n + d.byteLength, 0) };
|
|
355
|
+
},
|
|
356
|
+
/** Put the worlds back as `capture` left them. */
|
|
357
|
+
restore(data) {
|
|
358
|
+
if (!Array.isArray(data) || data.length !== worlds.length) throw new Error(`a checkpoint holds ${Array.isArray(data) ? data.length : 0} physics world(s), the code makes ${worlds.length}`);
|
|
359
|
+
worlds.forEach((w, i) => w.world.restoreSnapshot(data[i]));
|
|
360
|
+
for (const w of worlds) w.clearEvents();
|
|
361
|
+
},
|
|
362
|
+
/** Before each step: the events of the step before are forgotten. */
|
|
363
|
+
beginStep() {
|
|
364
|
+
for (const w of worlds) w.clearEvents();
|
|
365
|
+
},
|
|
366
|
+
};
|
|
367
|
+
|
|
368
|
+
return {
|
|
369
|
+
world2d: make,
|
|
370
|
+
worlds,
|
|
371
|
+
hooks,
|
|
372
|
+
/** `{ [world name]: { bodies, colliders, contacts, events, counts, checksum? } }`, null before a world exists. */
|
|
373
|
+
tables(limit, withChecksum) {
|
|
374
|
+
if (!worlds.length) return null;
|
|
375
|
+
return Object.fromEntries(worlds.map((w) => [w.name, w.world.tables(limit, withChecksum)]));
|
|
376
|
+
},
|
|
377
|
+
/** The collision events of the last step, `{ world, a, b, started, bodyA, bodyB }`; emptied. */
|
|
378
|
+
takeEvents() {
|
|
379
|
+
const out = [];
|
|
380
|
+
for (const w of worlds) for (const e of w.takeEvents()) out.push({ world: w.name, ...e });
|
|
381
|
+
return out;
|
|
382
|
+
},
|
|
383
|
+
/** Draw every world that has a `view` on `ctx` (the pane's wireframe toggle). */
|
|
384
|
+
debugDrawAll(ctx) {
|
|
385
|
+
for (const w of worlds) w.world.debugDraw(ctx);
|
|
386
|
+
},
|
|
387
|
+
get eventful() {
|
|
388
|
+
return worlds.some((w) => w.config.events);
|
|
389
|
+
},
|
|
390
|
+
dispose() {
|
|
391
|
+
disposed = true;
|
|
392
|
+
for (const w of worlds.splice(0)) {
|
|
393
|
+
try {
|
|
394
|
+
w.free();
|
|
395
|
+
} catch {}
|
|
396
|
+
}
|
|
397
|
+
},
|
|
398
|
+
};
|
|
399
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! mallory smf: src/smf-helper/source.js with @johnhenry/score@0.2.0, bundled into one ES module by scripts/build-smf-vendor.mjs. Do not edit. */
|
|
2
|
+
var F=class extends Error{constructor(s){super(s),this.name="SmfError"}},D=Object.freeze({maxBytes:8*1024*1024,maxTracks:256,maxEvents:1e6,maxTick:2147483647,maxSequencerBytes:2*1024*1024}),ht={0:"sequenceNumber",1:"text",2:"copyright",4:"instrumentName",5:"lyric",6:"marker",7:"cuePoint",8:"programName",9:"deviceName",32:"channelPrefix",33:"port",84:"smpteOffset",127:"sequencerSpecific"},gt={160:"polyAftertouch",192:"programChange",208:"channelPressure"},b=e=>{throw new F(e)},Pe=(e,s)=>String.fromCharCode(e[s],e[s+1],e[s+2],e[s+3]),ze=(e,s)=>(e[s]<<24|e[s+1]<<16|e[s+2]<<8|e[s+3])>>>0,$e=(e,s)=>e[s]<<8|e[s+1];function ee(e,s={}){let t={...D,...s},n=e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):b("expected bytes (a Uint8Array or ArrayBuffer).");n.length>t.maxBytes&&b(`the file is ${n.length} bytes, bigger than the ${t.maxBytes}-byte limit.`),n.length<14&&b(n.length?"the file is too short to be a MIDI file.":"the file is empty."),Pe(n,0)!=="MThd"&&b("not a standard MIDI file (it does not start with MThd).");let o=ze(n,4);(o<6||8+o>n.length)&&b("bad MIDI header: its length is wrong.");let r=$e(n,8),c=$e(n,10),l=$e(n,12);r>2&&b(`unknown MIDI file format ${r}.`),l&32768&&b("SMPTE time division is not supported (only ticks per quarter note)."),l===0&&b("bad MIDI header: the division (ticks per quarter note) is 0."),r===0&&c!==1&&b(`a format 0 file has one track, but the header says ${c}.`),c>t.maxTracks&&b(`the file has ${c} tracks, more than the ${t.maxTracks} allowed.`);let u={},f=(a,m=1)=>u[a]=(u[a]??0)+m,i=[],k={events:0},h=8+o;for(;h<n.length;){if(h+8>n.length){if(i.length>=c)break;b("truncated chunk header.")}let a=Pe(n,h),m=ze(n,h+4),g=h+8;if(g+m>n.length&&b(`bad chunk length: the ${JSON.stringify(a)} chunk at byte ${h} claims ${m} bytes but the file has ${n.length-g} left (truncated).`),h=g+m,a!=="MTrk"){f("unknownChunks");continue}i.length>=t.maxTracks&&b(`more than ${t.maxTracks} tracks.`),i.push({events:kt(n,g,g+m,t,k,f)})}return i.length||b("the file has no tracks."),i.length<c&&b(`the header says ${c} tracks but the file has ${i.length} (truncated).`),r===0&&i.length!==1&&b(`a format 0 file has one track, but this has ${i.length}.`),{format:r,ppq:l,tracks:i,skipped:u}}function kt(e,s,t,n,o,r){let c=[],l=s,u=0,f=0,i=(h,a)=>{l+h>t&&b(`truncated ${a} in a track (byte ${l}).`)},k=()=>{let h=0;for(let a=0;a<4;a++){l>=t&&b(`truncated variable-length quantity (byte ${l}).`);let m=e[l++];if(h=h*128+(m&127),!(m&128))return h}return b(`bad variable-length quantity (longer than 4 bytes) at byte ${l}.`)};for(;l<t;){u+=k(),u>n.maxTick&&b("a track is longer than 2147483647 ticks."),i(1,"event");let h=e[l];if(h&128?l++:f?h=f:b(`a data byte with no status and no running status (byte ${l}).`),o.events++,o.events>n.maxEvents&&b(`more than ${n.maxEvents} events.`),h<240){f=h;let a=h&240,m=h&15,g=a===192||a===208?1:2;i(g,"channel message");let v=e[l],d=g===2?e[l+1]:0;(v>127||d>127)&&b(`a data byte over 127 (byte ${l}).`),l+=g,a===144&&d>0?c.push({tick:u,type:"noteOn",channel:m,note:v,velocity:d}):a===144||a===128?c.push({tick:u,type:"noteOff",channel:m,note:v}):a===192?c.push({tick:u,type:"programChange",channel:m,program:v}):a===176?c.push({tick:u,type:"controlChange",channel:m,controller:v,value:d}):a===224?c.push({tick:u,type:"pitchBend",channel:m,value:v|d<<7}):r(gt[a])}else if(h===240||h===247){f=0;let a=k();i(a,"sysex"),l+=a,r("sysex")}else if(h===255){i(1,"meta event");let a=e[l++],m=k();i(m,"meta event");let g=e.subarray(l,l+m);if(l+=m,a===47)return c.push({tick:u,type:"endOfTrack"}),c;if(a===81&&m===3)c.push({tick:u,type:"tempo",microsPerQuarter:g[0]<<16|g[1]<<8|g[2]});else if(a===88&&m>=2&&g[1]<=15)c.push({tick:u,type:"timeSignature",numerator:g[0],denominator:2**g[1],clocksPerClick:g[2]??24,thirtySecondsPerQuarter:g[3]??8});else if(a===89&&m===2){let v=g[0]<<24>>24;v>=-7&&v<=7&&g[1]<=1?c.push({tick:u,type:"keySignature",fifths:v,minor:g[1]===1}):r("malformedMeta")}else a===3?c.push({tick:u,type:"trackName",text:new TextDecoder("utf-8").decode(g)}):a===81||a===88||a===89?r("malformedMeta"):(a===127&&m<=n.maxSequencerBytes&&c.push({tick:u,type:"sequencerSpecific",data:g.slice()}),r(ht[a]??"unknownMeta"))}else b(`unsupported status byte 0x${h.toString(16)} in a track (byte ${l-1}).`)}return c}var j=(e,...s)=>e.push(...s);function Be(e,s){let t=[s&127];for(let n=Math.floor(s/128);n>0;n=Math.floor(n/128))t.push(n&127|128);j(e,...t.reverse())}var V=Number.isInteger,Te={sequencerSpecific:0,endOfTrack:9,noteOff:1,trackName:0,tempo:0,timeSignature:0,keySignature:0,programChange:0,controlChange:0,pitchBend:0,noteOn:2};function te(e,s={}){let t={...D,...s},{ppq:n,tracks:o}=e??{};(!V(n)||n<1||n>32767)&&b("ppq is a whole number from 1 to 32767."),(!Array.isArray(o)||!o.length)&&b("tracks: at least one track."),o.length>Math.min(t.maxTracks,65535)&&b(`at most ${t.maxTracks} tracks.`);let r=[];j(r,...[..."MThd"].map(l=>l.charCodeAt(0)),0,0,0,6,0,1,o.length>>8,o.length&255,n>>8,n&255);let c=0;for(let[l,u]of o.entries()){c+=Array.isArray(u?.events)?u.events.length:0,c>t.maxEvents&&b(`more than ${t.maxEvents} events in all.`);let f=yt(u?.events,l,t);j(r,...[..."MTrk"].map(i=>i.charCodeAt(0)),f.length>>>24&255,f.length>>>16&255,f.length>>>8&255,f.length&255);for(let i=0;i<f.length;i+=8192)j(r,...f.slice(i,i+8192))}return Uint8Array.from(r)}function yt(e,s,t){let n=`track ${s}`;Array.isArray(e)||b(`${n}: events is a list.`),e.length>t.maxEvents&&b(`${n}: more than ${t.maxEvents} events.`);let o=e.map((a,m)=>((!a||!V(a.tick)||a.tick<0||a.tick>t.maxTick)&&b(`${n}, event ${m}: tick is a whole number from 0 to ${t.maxTick}.`),Object.hasOwn(Te,a.type)||b(`${n}, event ${m}: unknown type ${JSON.stringify(a.type)}.`),{e:a,i:m}));o.sort((a,m)=>a.e.tick-m.e.tick||Te[a.e.type]-Te[m.e.type]||a.i-m.i);let r=[],c=0,l=-1,u=!1,f=o.length?o.at(-1).e.tick:0,i=a=>(Be(r,a-c),c=a),k=(a,m)=>{j(r,255,a),Be(r,m.length);for(let g=0;g<m.length;g+=8192)j(r,...m.slice(g,g+8192));l=-1},h=(a,m,g,v)=>((!V(a[m])||a[m]<0||a[m]>g)&&b(`${n}: ${v} is a whole number from 0 to ${g}.`),a[m]);for(let{e:a}of o){if(u)break;if(i(a.tick),a.type==="noteOn"||a.type==="noteOff"){let m=h(a,"channel",15,"channel"),g=h(a,"note",127,"note"),v=(a.type==="noteOn"?144:128)|m,d=a.type==="noteOn"?h(a,"velocity",127,"velocity")||b(`${n}: a note-on velocity is 1..127.`):64;v!==l&&j(r,v),l=v,j(r,g,d)}else if(a.type==="programChange"){let m=h(a,"channel",15,"channel"),g=h(a,"program",127,"program"),v=192|m;v!==l&&j(r,v),l=v,j(r,g)}else if(a.type==="controlChange"){let m=h(a,"channel",15,"channel"),g=h(a,"controller",127,"controller"),v=h(a,"value",127,"value"),d=176|m;d!==l&&j(r,d),l=d,j(r,g,v)}else if(a.type==="pitchBend"){let m=h(a,"channel",15,"channel"),g=h(a,"value",16383,"pitch bend"),v=224|m;v!==l&&j(r,v),l=v,j(r,g&127,g>>7)}else if(a.type==="tempo")(!V(a.microsPerQuarter)||a.microsPerQuarter<1||a.microsPerQuarter>16777215)&&b(`${n}: microsPerQuarter is a whole number from 1 to 16777215.`),k(81,[a.microsPerQuarter>>16,a.microsPerQuarter>>8&255,a.microsPerQuarter&255]);else if(a.type==="timeSignature"){let m=Math.log2(a.denominator);(!V(a.numerator)||a.numerator<1||a.numerator>255||!V(m)||m<0||m>15)&&b(`${n}: a time signature is numerator 1..255 over a power-of-two denominator.`),k(88,[a.numerator,m,a.clocksPerClick??24,a.thirtySecondsPerQuarter??8])}else if(a.type==="keySignature")(!V(a.fifths)||a.fifths<-7||a.fifths>7)&&b(`${n}: fifths is a whole number from -7 to 7.`),k(89,[a.fifths&255,a.minor?1:0]);else if(a.type==="sequencerSpecific")(!(a.data instanceof Uint8Array)||a.data.length>t.maxSequencerBytes)&&b(`${n}: a sequencer-specific event holds at most ${t.maxSequencerBytes} bytes.`),k(127,a.data);else if(a.type==="trackName"){let m=new TextEncoder().encode(String(a.text??"").slice(0,200));k(3,m)}else k(47,[]),u=!0}return u||(i(f),k(47,[])),r}var Q=480;var bt=20,xt=300;function vt(e){let s=/^([0-9]+)\/([0-9]+)$/.exec(e);if(!s)return null;let t=Number(s[1]),n=Number(s[2]);return!(t>0)||!(n>0)?null:{num:t,den:n}}function $t(e){let s=vt(e);return s?s.num*(4/s.den):4}function Tt(e){return Math.round($t(e)*Q)}function ne(e){return Number.isFinite(e)?Math.max(bt,Math.min(xt,e)):120}function Mt(e){return 60/(ne(e)*Q)}function St(e,s){return e[s].ramp==="linear"&&s+1<e.length}function Fe(e,s,t){return e.bpm+(s.bpm-e.bpm)*t/(s.tick-e.tick)}function wt(e,s,t){let n=s.bpm-e.bpm;return(s.tick-e.tick)/(8*n)*Math.log(Fe(e,s,t)/e.bpm)}function De(e){let s=(e.tempoChanges??[]).filter(r=>Number.isFinite(r.tick)&&Number.isFinite(r.bpm)).map(r=>{let c={tick:Math.max(0,Math.round(r.tick)),bpm:ne(r.bpm)};return r.ramp==="linear"&&(c.ramp="linear"),c}).sort((r,c)=>r.tick-c.tick),t=[{tick:0,bpm:ne(e.bpm)}];for(let r of s)t[t.length-1].tick===r.tick?t[t.length-1]=r:t.push(r);let n=[];for(let r=0;r<t.length;r++){let c=t[r],l=t[r+1],u=c.ramp==="linear"&&l!==void 0&&l.bpm!==c.bpm,f=u?c:{tick:c.tick,bpm:c.bpm},i=n[n.length-1];i&&i.bpm===f.bpm&&!u||n.push(f)}let o=[0];for(let r=1;r<n.length;r++){let c=n[r-1],l=n[r],u=c.ramp==="linear"?wt(c,l,l.tick-c.tick):(l.tick-c.tick)*Mt(c.bpm);o.push(o[r-1]+u)}return{points:n,secondsAt:o}}function At(e,s){let t=0,n=e.points.length-1;for(;t<n;){let o=Math.ceil((t+n)/2);e.points[o].tick<=s?t=o:n=o-1}return t}function Ue(e,s){let t=Math.max(0,s),n=At(e,t),o=e.points[n];return St(e.points,n)?Fe(o,e.points[n+1],t-o.tick):o.bpm}function Ot(e,s){let t=Math.max(0,s),n=0,o=e.segments.length-1;for(;n<o;){let r=Math.ceil((n+o)/2);e.segments[r].measure<=t?n=r:o=r-1}return e.segments[n]}function ge(e){let s=(e.meterChanges??[]).filter(r=>Number.isFinite(r.measure)&&typeof r.timeSignature=="string").map(r=>({measure:Math.max(0,Math.round(r.measure)),timeSignature:r.timeSignature})).sort((r,c)=>r.measure-c.measure),t=[{measure:0,timeSignature:e.timeSignature}];for(let r of s){let c=t[t.length-1];c.measure===r.measure?t[t.length-1]=r:c.timeSignature!==r.timeSignature&&t.push(r)}let n=[];for(let r of t){let c=n[n.length-1];c&&c.timeSignature===r.timeSignature||n.push(r)}let o=[];for(let r=0;r<n.length;r++){let c=n[r],l=Tt(c.timeSignature),u=o[r-1],f=u?u.startTick+(c.measure-u.measure)*u.ticks:0;o.push({measure:c.measure,timeSignature:c.timeSignature,ticks:l,startTick:f})}return{segments:o}}function Me(e,s){let t=Math.max(0,Math.round(s)),n=Ot(e,t);return n.startTick+(t-n.measure)*n.ticks}function ke(e,s){let t=Math.max(0,s),n=0,o=e.segments.length-1;for(;n<o;){let l=Math.ceil((n+o)/2);e.segments[l].startTick<=t?n=l:o=l-1}let r=e.segments[n],c=t-r.startTick;return{measure:r.measure+Math.floor(c/r.ticks),offsetTicks:c%r.ticks}}function ye(e,s){if(s<=0)return 0;let t=ke(e,s);return t.offsetTicks>0?t.measure+1:t.measure}function Re(e){return Number.isFinite(e)?Math.max(-7,Math.min(7,Math.round(e))):0}function Ge(e){let s=(e.keyChanges??[]).filter(o=>Number.isFinite(o.measure)&&Number.isFinite(o.fifths)).map(o=>({measure:Math.max(0,Math.round(o.measure)),fifths:Re(o.fifths)})).sort((o,r)=>o.measure-r.measure),t=[{measure:0,fifths:Re(e.keySignature??0)}];for(let o of s){let r=t[t.length-1];r.measure===o.measure?t[t.length-1]=o:r.fifths!==o.fifths&&t.push(o)}let n=[];for(let o of t){let r=n[n.length-1];r&&r.fifths===o.fifths||n.push(o)}return{points:n}}function He(e){return Math.max(0,Math.min(16383,Math.round(Math.max(-1,Math.min(1,e))*8192+8192)))}function Ve(e){return(Math.max(0,Math.min(16383,Math.round(e)))-8192)/8192}var Ke={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://viaframe.johnhenry.me/schemas/score.schema.json",title:"Score (format 1)",description:`A piece of music as data: notes on a tick timeline (480 ticks to the quarter note), tracks, and the tempo, meter and key maps and repeat marks that say how it is read. Ticks are authoritative; seconds are derived through the tempo map (docs/design/score.md, "Interchange"). Modelled on music-studio's Score (src/core/model/types.ts). Unknown fields are ignored by readers and kept by writers that round-trip. Limits below are the schema's bounds; a reader may be stricter.`,type:"object",required:["version","ppq","bpm","timeSignature","tracks"],properties:{version:{const:1,description:"The format. Bumped only by a change an old reader would misread; added optional fields do not bump it."},ppq:{const:480,description:"Ticks per quarter note. Fixed at 480: 1 eighth = 240, 1 sixteenth = 120, a triplet eighth = 160. Another resolution is converted on import (SMF files state their own division)."},title:{type:"string",maxLength:200,default:""},bpm:{$ref:"#/$defs/bpm",description:"Quarter notes a minute at tick 0. A tempoChanges entry at tick 0 overrides it, so the two cannot disagree."},timeSignature:{$ref:"#/$defs/timeSignature",description:"The meter at measure 0."},keySignature:{$ref:"#/$defs/fifths",default:0,description:"The key at measure 0, in fifths: +n sharps, -n flats."},measures:{type:"integer",minimum:1,maximum:4096,description:"How many measures the written grid shows. A reader takes the larger of this and what the notes need."},tempoChanges:{type:"array",maxItems:4096,description:'Tempo after the start, by tick. A step function (each tempo holds until the next change) unless a change has `ramp: "linear"`, which moves the tempo smoothly to the next change. Order does not matter; a reader sorts, and a second change at one tick wins.',items:{$ref:"#/$defs/tempoChange"}},meterChanges:{type:"array",maxItems:4096,description:"Meter changes by 0-based measure, never by tick: a meter taking effect mid-bar is not notatable.",items:{$ref:"#/$defs/meterChange"}},keyChanges:{type:"array",maxItems:4096,description:"Key changes by 0-based measure. A key change moves no barlines; it changes spelling and the signature drawn.",items:{$ref:"#/$defs/keyChange"}},repeats:{type:"array",maxItems:4096,description:'Repeat signs and volta brackets, stated as marks on barlines (what notation and MusicXML state), not as a play order. The play order is derived (docs/design/score.md, "Repeats").',items:{$ref:"#/$defs/repeatMark"}},tracks:{type:"array",maxItems:64,description:"Instruments (parts), not clip lanes. A grand-staff instrument is one track with staffCount 2.",items:{$ref:"#/$defs/track"}},patches:{type:"array",maxItems:64,description:`Synth patches the tracks point at by instrumentId ("patch:<id>"), carried in the score so a shared score is self-contained. Their shape belongs to the audio side (viaframe's DSP patch or music-studio's SynthPatch) and is not constrained here.`,items:{type:"object"}},buses:{type:"array",maxItems:4,description:"Shared send buses (music-studio: at most 4). Shape owned by the effects rack; not constrained here.",items:{type:"object"}}},$defs:{tick:{type:"integer",minimum:0,maximum:2147483647,description:"A position or length in ticks (480 to the quarter note)."},bpm:{type:"number",minimum:20,maximum:300,description:"music-studio clamps and rounds to a whole number from 20 to 300; a reader may do the same."},fifths:{type:"integer",minimum:-7,maximum:7},timeSignature:{type:"string",pattern:"^[1-9][0-9]?/(1|2|4|8|16|32)$",description:'"num/den", e.g. "4/4", "6/8". A measure is num x (4 / den) quarter notes: round(that x 480) ticks.'},tempoChange:{type:"object",required:["tick","bpm"],properties:{tick:{$ref:"#/$defs/tick"},bpm:{$ref:"#/$defs/bpm"},ramp:{enum:["linear"],description:`Absent: the tempo steps here and holds (accelerando/ritardando off). "linear": the tempo moves in a straight line (in bpm, over ticks) from this change's bpm to the next change's bpm, arriving exactly at the next change's tick. Ignored on the last change, or when the next change has the same bpm.`}}},controllerEvent:{type:"object",required:["tick","cc","value"],description:"One MIDI continuous-controller value at a tick (CC 64 sustain, 1 mod wheel, 7 volume, 11 expression ...). Holds until the next event of the same cc on the track.",properties:{tick:{$ref:"#/$defs/tick"},cc:{type:"integer",minimum:0,maximum:127},value:{type:"integer",minimum:0,maximum:127}}},pitchBendEvent:{type:"object",required:["tick","value"],description:"Pitch bend at a tick. Holds until the next event on the track.",properties:{tick:{$ref:"#/$defs/tick"},value:{type:"number",minimum:-1,maximum:1,description:"-1..1 across the wheel's full travel, 0 centred. A reader maps it to the voice's range (General MIDI default +-2 semitones); an SMF writer quantises to 14 bits."}}},meterChange:{type:"object",required:["measure","timeSignature"],properties:{measure:{type:"integer",minimum:0,maximum:4095},timeSignature:{$ref:"#/$defs/timeSignature"}}},keyChange:{type:"object",required:["measure","fifths"],properties:{measure:{type:"integer",minimum:0,maximum:4095},fifths:{$ref:"#/$defs/fifths"}}},repeatMark:{type:"object",required:["measure"],description:"Marks on one measure's barlines. One measure may carry several at once (a first ending closes with a repeat sign on the same barline).",properties:{measure:{type:"integer",minimum:0,maximum:4095},start:{type:"boolean",description:"A repeat sign on the measure's LEFT barline: play from here again."},end:{type:"object",required:["times"],description:"A repeat sign on the RIGHT barline.",properties:{times:{type:"integer",minimum:2,maximum:99,default:2,description:"How many times the section is played in TOTAL: 2 means play it twice."}}},ending:{type:"object",required:["numbers","stop"],description:"A volta bracket beginning at this measure.",properties:{numbers:{type:"array",minItems:1,maxItems:99,uniqueItems:!0,items:{type:"integer",minimum:1,maximum:99},description:"The passes it is played on: [1] a first ending, [2, 3] one bracket shared by two passes."},stop:{type:"boolean",description:"Closes the bracket at this measure's right barline."}}}}},note:{type:"object",required:["id","startTick","durationTicks","pitch","velocity"],description:"The first five fields are all playback needs. The rest are notation-only (they never change what is heard) and may be absent: absent means derive it.",properties:{id:{type:"string",minLength:1,maxLength:64,description:"Unique within the score; edits address notes by it."},startTick:{$ref:"#/$defs/tick"},durationTicks:{type:"integer",minimum:1,maximum:2147483647},pitch:{type:"integer",minimum:0,maximum:127,description:"MIDI note number, 60 = C4 = middle C. music-studio's editor stays inside 12..107."},velocity:{type:"number",minimum:0,maximum:1},lyric:{type:"string",maxLength:100},lyricHyphen:{type:"boolean"},staff:{enum:[1,2]},voice:{type:"integer",minimum:1,maximum:4},accidental:{enum:["sharp","flat","natural","double-sharp","double-flat"],description:"Enharmonic override; absent spells from the key (music-studio score/pitch.ts Accidental)."},tiedToNext:{type:"boolean"},slurStart:{type:"boolean"},slurStop:{type:"boolean"},hairpin:{enum:["cresc","dim"]},hairpinStop:{type:"boolean"},tuplet:{type:"object",required:["num","den"],properties:{num:{type:"integer",minimum:2,maximum:99},den:{type:"integer",minimum:1,maximum:99}},description:"{ num: 3, den: 2 } is a triplet. Notation only: the note's ticks already say how long it sounds."},articulations:{type:"array",maxItems:5,uniqueItems:!0,items:{enum:["staccato","accent","tenuto","marcato","fermata"]}},dynamic:{enum:["pp","p","mp","mf","f","ff"]}}},rest:{type:"object",required:["id","startTick","durationTicks"],description:"An explicit rest. Gaps between notes are filled automatically, so most rests have no object.",properties:{id:{type:"string",minLength:1,maxLength:64},startTick:{$ref:"#/$defs/tick"},durationTicks:{type:"integer",minimum:1,maximum:2147483647},voice:{type:"integer",minimum:1,maximum:4},staff:{enum:[1,2]}}},clef:{enum:["treble","bass","alto","tenor"]},track:{type:"object",required:["id","name","instrumentId","notes"],properties:{id:{type:"string",minLength:1,maxLength:64},name:{type:"string",maxLength:100},instrumentId:{type:"string",maxLength:100,description:`A pointer, not a definition: a General MIDI preset id, "patch:<id>" into the score's patches, or "sample:<id>" into the host's own sample store. A reader that cannot resolve it falls back to a stock voice and says so.`},notes:{type:"array",maxItems:65536,items:{$ref:"#/$defs/note"}},muted:{type:"boolean",default:!1},soloed:{type:"boolean",default:!1},clef:{$ref:"#/$defs/clef",default:"treble"},staffCount:{enum:[1,2],default:1},lowerClef:{$ref:"#/$defs/clef",default:"bass"},clefChanges:{type:"array",maxItems:1024,items:{type:"object",required:["tick","clef"],properties:{tick:{$ref:"#/$defs/tick"},clef:{$ref:"#/$defs/clef"}}}},rests:{type:"array",maxItems:65536,items:{$ref:"#/$defs/rest"}},volume:{type:"number",minimum:0,maximum:1},pan:{type:"number",minimum:-1,maximum:1},effects:{type:"array",maxItems:6,description:"Insert effects in order. Shape owned by the effects rack; not constrained here.",items:{type:"object"}},sends:{type:"array",maxItems:4,items:{type:"object"}},hidden:{type:"boolean",description:"Hidden from editors, independent of muted."},controllers:{type:"array",maxItems:65536,description:"The controller lane: timed CC events (sustain CC 64 and so on), kept as events and never baked into note lengths. Order does not matter; a reader sorts by tick, and a later entry wins at one tick and cc.",items:{$ref:"#/$defs/controllerEvent"}},pitchBend:{type:"array",maxItems:65536,description:"Timed pitch-bend events for the track's voice.",items:{$ref:"#/$defs/pitchBendEvent"}}}}}};var he=class extends Error{},Et=e=>e===null?"null":Array.isArray(e)?"array":typeof e=="number"?Number.isInteger(e)?"integer":"number":typeof e;function qe(e,s){return e===s||JSON.stringify(e)===JSON.stringify(s)}function It(e){if(!e.startsWith("#/"))throw new Error(`unsupported $ref ${e}`);let s=Ke;for(let t of e.slice(2).split("/"))s=s[t];if(!s||typeof s!="object")throw new Error(`unresolved $ref ${e}`);return s}var Le=new Map;function de(e,s,t,n,o){let r=l=>{if(n.push({path:t,message:l}),n.length>=o)throw new he};if(typeof e.$ref=="string"){de(It(e.$ref),s,t,n,o);return}let c=e.type;if(typeof c=="string"){let l=Et(s);if(!(c===l||c==="number"&&l==="integer")){r(`expected ${c}, got ${l}`);return}}if("const"in e&&!qe(s,e.const)&&r(`must equal ${JSON.stringify(e.const)}`),Array.isArray(e.enum)&&!e.enum.some(l=>qe(l,s))&&r(`must be one of ${e.enum.map(l=>JSON.stringify(l)).join(", ")}`),typeof s=="number"&&(Number.isFinite(s)||r("must be finite"),typeof e.minimum=="number"&&s<e.minimum&&r(`must be >= ${e.minimum}`),typeof e.maximum=="number"&&s>e.maximum&&r(`must be <= ${e.maximum}`)),typeof s=="string"&&(typeof e.minLength=="number"&&s.length<e.minLength&&r(`must have length >= ${e.minLength}`),typeof e.maxLength=="number"&&s.length>e.maxLength&&r(`must have length <= ${e.maxLength}`),typeof e.pattern=="string")){let l=Le.get(e.pattern);l||Le.set(e.pattern,l=new RegExp(e.pattern)),l.test(s)||r(`must match ${e.pattern}`)}if(Array.isArray(s)){if(typeof e.minItems=="number"&&s.length<e.minItems&&r(`must have >= ${e.minItems} items`),typeof e.maxItems=="number"&&s.length>e.maxItems){r(`must have <= ${e.maxItems} items`);return}if(e.uniqueItems===!0){let u=new Set;for(let f of s){let i=JSON.stringify(f);if(u.has(i)){r("items must be unique");break}u.add(i)}}let l=e.items;if(l&&typeof l=="object")for(let u=0;u<s.length;u++)de(l,s[u],`${t}/${u}`,n,o)}if(s!==null&&typeof s=="object"&&!Array.isArray(s)){let l=s;if(Array.isArray(e.required)){for(let f of e.required)if((!(f in l)||l[f]===void 0)&&(n.push({path:`${t}/${f}`,message:"is required"}),n.length>=o))throw new he}let u=e.properties;if(u)for(let f of Object.keys(u))f in l&&l[f]!==void 0&&de(u[f],l[f],`${t}/${f}`,n,o)}}function jt(e,s,t){let n=(c,l)=>{if(s.push({path:c,message:l}),s.length>=t)throw new he},o=new Set,r=new Set;e.tracks.forEach((c,l)=>{o.has(c.id)&&n(`/tracks/${l}/id`,`duplicate track id "${c.id}"`),o.add(c.id),c.notes.forEach((u,f)=>{r.has(u.id)&&n(`/tracks/${l}/notes/${f}/id`,`duplicate note id "${u.id}"`),r.add(u.id)}),(c.rests??[]).forEach((u,f)=>{r.has(u.id)&&n(`/tracks/${l}/rests/${f}/id`,`duplicate id "${u.id}"`),r.add(u.id)})})}function se(e,s={}){let t=s.maxErrors??100,n=[];try{de(Ke,e,"",n,t),n.length===0&&s.semantic!==!1&&jt(e,n,t)}catch(o){if(!(o instanceof he))throw o}return n.length===0?{ok:!0,score:e}:{ok:!1,errors:n}}var O=Object.freeze({notes:16384,tracks:64,measures:4095,changes:4096,controllers:65536}),Ct=30,Nt=128,_t=5,Se=Object.freeze({controlChange:"controller events (on a channel with no notes, past the 65536 a track holds, or the mix's volume, pan and effect sends at tick 0)",programChange:"program changes after a track's first note (a track has one instrument)",pitchBend:"pitch bends (on a channel with no notes, or past the 65536 a track holds)",polyAftertouch:"aftertouch events",channelPressure:"channel pressure events",sysex:"system-exclusive messages",text:"text events",copyright:"copyright notices",instrumentName:"instrument names",lyric:"lyrics",marker:"markers",cuePoint:"cue points",programName:"program names",deviceName:"device names",sequenceNumber:"sequence numbers",channelPrefix:"channel prefixes",port:"port events",smpteOffset:"SMPTE offsets",sequencerSpecific:"sequencer-specific events",unknownMeta:"unknown meta events",malformedMeta:"malformed meta events",unknownChunks:"unknown chunks",minorKeys:"minor-key flags (the key signature is kept)",clampedTempos:"tempos outside 20-300 bpm (clamped)",movedMeters:"meter changes inside a bar (moved to the next bar line)",unsupportedMeters:"time signatures a score cannot hold",movedKeys:"key changes inside a bar (moved to the next bar line)",zeroLengthNotes:"zero-length notes (made one tick long)",unclosedNotes:"notes with no note-off (ended with their track)",extraTempoChanges:"tempo changes beyond the 4096 a score holds",extraMeterChanges:"meter changes beyond the 4096 a score holds",extraKeyChanges:"key changes beyond the 4096 a score holds",repeats:"repeat marks (notes are written as notated, not unrolled)",patterns:"pattern layers that could not be carried or no longer matched their notes (the notes are kept as plain notes)",notation:"notation-only fields (lyrics, ties, slurs, articulations, dynamics, rests, clefs)",mixer:"track volume, pan, effects, sends and patches",instruments:"custom synths and samplers (written as their General MIDI program)"});function be(e){let s=Object.entries(e??{}).filter(([,t])=>t>0).map(([t,n])=>`${n} ${Se[t]??t}`);return s.length?`Dropped: ${s.join(", ")}.`:""}var Qe=Object.freeze({forProgram:e=>e===0?"piano":`gm:${e}`,drum:"gm:drums",programOf:e=>{let s=/^gm:(\d{1,3})$/.exec(String(e)),t=!!(s&&Number(s[1])<=127)||e==="piano"||e==="gm:drums";return{program:s&&Number(s[1])<=127?Number(s[1]):0,drums:e==="gm:drums",exact:t}}}),re=e=>{throw new F(e)},We=(e,s)=>Math.round(e*10**s)/10**s,Pt=new Set([1,2,4,8,16,32]);function zt(e){let s=[],t=0,n=0;for(;n<e.length;){let o=n+1;if(o<e.length){let r=e[o].tick-e[n].tick,c=e[o].bpm-e[n].bpm;for(;o+1<e.length;){let l=e[o+1].tick-e[o].tick,u=e[o+1].bpm-e[o].bpm;if(Math.abs(l-r)>1||Math.sign(u)!==Math.sign(c)||Math.abs(u-c)>Math.max(.05,.05*Math.abs(c)))break;o++}}o-n+1>=_t&&e[o].bpm!==e[n].bpm?(s.push({tick:e[n].tick,bpm:e[n].bpm,ramp:"linear"},{tick:e[o].tick,bpm:e[o].bpm}),t++,n=o+1):(s.push({...e[n]}),n++)}return{points:s,ramps:t}}function Ze(e,{instruments:s=Qe}={}){let t={...e.skipped},n=(p,y=1)=>t[p]=(t[p]??0)+y,o=p=>Math.round(p*Q/e.ppq),r=[],c=[],l=0,u=0;for(let[p,y]of e.tracks.entries()){let M=y.events.find($=>$.type==="trackName")?.text.trim(),T=new Map,P=new Map,B=new Map,X=[],H=($,N,Y)=>{let me=o(N.tick),pe=o(Y);pe<=me&&(pe=me+1,n("zeroLengthNotes")),u=Math.max(u,pe),$.notes.push({startTick:me,durationTicks:pe-me,pitch:N.note,velocity:We(N.velocity/127,4)}),++l>O.notes&&re(`the file has more than ${O.notes} notes, more than a score holds.`)},fe=0;for(let $ of y.events)if(fe=Math.max(fe,$.tick),$.type==="programChange")T.has($.channel)?n("programChange"):P.set($.channel,{program:$.program});else if($.type==="controlChange"||$.type==="pitchBend")X.push($);else if($.type==="noteOn"){T.has($.channel)||T.set($.channel,{channel:$.channel,notes:[],name:M,ti:p,program:P.get($.channel)?.program});let N=`${$.channel}:${$.note}`;B.has(N)||B.set(N,[]),B.get(N).push({tick:$.tick,note:$.note,velocity:$.velocity,group:T.get($.channel)})}else if($.type==="noteOff"){let Y=B.get(`${$.channel}:${$.note}`)?.shift();Y&&H(Y.group,Y,$.tick)}for(let $ of B.values())for(let N of $)n("unclosedNotes"),H(N.group,N,Math.max(fe,N.tick));u=Math.max(u,o(fe));for(let $ of T.values())r.push({...$,multi:T.size>1});c.push(...X.map($=>({e:$,ti:p})))}r.length>O.tracks&&re(`the file has ${r.length} note tracks, more than the ${O.tracks} a score holds.`);let f=r.map((p,y)=>({id:`t${y+1}`,name:(p.name?p.multi?`${p.name} ch${p.channel+1}`:p.name:`Track ${y+1}`).slice(0,100),instrumentId:p.channel===9?s.drum:p.program===void 0?"piano":s.forProgram(p.program),notes:p.notes.sort((M,T)=>M.startTick-T.startTick||M.pitch-T.pitch||M.durationTicks-T.durationTicks)})),i=0;for(let p of f)p.notes=p.notes.map(y=>({id:`n${++i}`,...y}));let k=new Set([7,10,91,93]),h=new Map;for(let{e:p,ti:y}of c){let M=r.findIndex(H=>H.ti===y&&H.channel===p.channel),T=M>=0?M:r.findIndex(H=>H.channel===p.channel),P=o(p.tick);if(T<0||p.type==="controlChange"&&P===0&&k.has(p.controller)){n(p.type);continue}let B=h.get(T)??{controllers:[],pitchBend:[]};h.set(T,B);let X=p.type==="controlChange"?B.controllers:B.pitchBend;X.length>=O.controllers?n(p.type):X.push(p.type==="controlChange"?{tick:P,cc:p.controller,value:p.value}:{tick:P,value:Ve(p.value)})}for(let[p,y]of h){let M=(T,P)=>T.tick-P.tick;y.controllers.length&&(f[p].controllers=y.controllers.sort(M)),y.pitchBend.length&&(f[p].pitchBend=y.pitchBend.sort(M)),u=Math.max(u,...y.controllers.map(T=>T.tick),...y.pitchBend.map(T=>T.tick))}f.length||f.push({id:"t1",name:"piano",instrumentId:"piano",notes:[]});let a=p=>e.tracks.flatMap(y=>y.events.filter(M=>M.type===p)).sort((y,M)=>y.tick-M.tick),m=e.tracks[0].events.find(p=>p.type==="trackName")?.text.trim().slice(0,200),g=120,v=new Map;for(let p of a("tempo")){if(!(p.microsPerQuarter>0))continue;let y=We(6e7/p.microsPerQuarter,3),M=ne(y);M!==y&&n("clampedTempos"),v.set(o(p.tick),M)}v.has(0)&&(g=v.get(0),v.delete(0));let d=[],w=g;for(let[p,y]of[...v].sort((M,T)=>M[0]-T[0]))y!==w&&(w=y,d.length>=O.changes?n("extraTempoChanges"):d.push({tick:p,bpm:y}));let S=zt([{tick:0,bpm:g},...d]);S.ramps&&(g=S.points[0].bpm,d=[...S.points[0].ramp?[{tick:0,bpm:g,ramp:"linear"}]:[],...S.points.slice(1)]);let A="4/4",C=[];for(let p of a("timeSignature")){let y=`${p.numerator}/${p.denominator}`;if(!(p.numerator>=1&&p.numerator<=99&&Pt.has(p.denominator))){n("unsupportedMeters");continue}let M=o(p.tick);if(M===0){A=y;continue}let T=ke(ge({timeSignature:A,meterChanges:C}),M),P=T.measure+(T.offsetTicks>0?1:0);T.offsetTicks>0&&n("movedMeters"),!(P>O.measures)&&(C.length>=O.changes?n("extraMeterChanges"):C.push({measure:P,timeSignature:y}))}let x=ge({timeSignature:A,meterChanges:C}),G=0,le=[];for(let p of a("keySignature")){p.minor&&n("minorKeys");let y=o(p.tick);if(y===0){G=p.fifths;continue}let M=ke(x,y),T=M.measure+(M.offsetTicks>0?1:0);M.offsetTicks>0&&n("movedKeys"),!(T>O.measures)&&(le.length>=O.changes?n("extraKeyChanges"):le.push({measure:T,fifths:p.fifths}))}let pt=Math.min(O.measures,Math.max(1,ye(x,u)));ye(x,Math.max(0,...f.flatMap(p=>p.notes.map(y=>y.startTick+y.durationTicks))))>O.measures&&re(`the music runs past measure ${O.measures}.`);let dt=e.tracks.flatMap(p=>p.events.filter(y=>y.type==="sequencerSpecific")).slice(0,16).map(p=>p.data),_e={version:1,ppq:Q,...m?{title:m}:{},bpm:g,timeSignature:A,keySignature:G,measures:pt,...d.length?{tempoChanges:d}:{},...C.length?{meterChanges:C}:{},...le.length?{keyChanges:le}:{},tracks:f},ue=se(_e,{maxErrors:2});ue.ok||re(`the file does not make a valid score: ${ue.errors[0].path?`${ue.errors[0].path}: `:""}${ue.errors[0].message}`);for(let p of Object.keys(t))t[p]||delete t[p];return{score:_e,dropped:t,sequencerData:dt}}var we=(e,s,t)=>Ze(ee(e,s),t),Bt=["lyric","lyricHyphen","staff","voice","accidental","tiedToNext","slurStart","slurStop","hairpin","hairpinStop","tuplet","articulations","dynamic"];function Je(e,{instruments:s=Qe,conductorData:t=[],authoredRepeats:n,controllers:o}={}){let r={},c=(d,w=1)=>w>0&&(r[d]=(r[d]??0)+w),l=ge(e),u=Ge(e),f=De(e),i=e.tracks.flatMap(d=>d.notes),k=Math.max(e.measures??1,1,ye(l,Math.max(0,...i.map(d=>d.startTick+d.durationTicks)))),h=Me(l,k),a=[];e.title&&a.push({tick:0,type:"trackName",text:e.title});let m=(d,w)=>a.push({tick:d,type:"tempo",microsPerQuarter:Math.min(16777215,Math.max(1,Math.round(6e7/w)))});f.points.forEach((d,w)=>{m(d.tick,d.bpm);let S=f.points[w+1];if(d.ramp==="linear"&&S){let A=S.tick-d.tick,C=Math.min(Nt,Math.max(1,Math.ceil(A/Ct)));for(let x=1;x<C;x++){let G=d.tick+Math.round(A*x/C);m(G,Ue(f,G))}}});for(let d of l.segments){let[w,S]=d.timeSignature.split("/").map(Number);a.push({tick:d.startTick,type:"timeSignature",numerator:w,denominator:S,clocksPerClick:Math.max(1,Math.round(96/S)),thirtySecondsPerQuarter:8})}if(e.keySignature!==void 0||u.points.length>1)for(let d of u.points)a.push({tick:Me(l,d.measure),type:"keySignature",fifths:d.fifths,minor:!1});for(let d of t.slice(0,8))a.push({tick:0,type:"sequencerSpecific",data:d});a.push({tick:h,type:"endOfTrack"});let g=[{events:a}],v=0;for(let d of e.tracks){let w=s.programOf(d.instrumentId),S=w.drums?9:[0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][v++%15],A=[{tick:0,type:"trackName",text:d.name}];!w.drums&&d.instrumentId!=="piano"&&A.push({tick:0,type:"programChange",channel:S,program:w.program});let C=new Set;for(let x of o?.(d)??[])A.push({tick:0,type:"controlChange",channel:S,controller:x.controller,value:x.value}),C.add(x.controller);for(let x of d.controllers??[])x.tick===0&&C.has(x.cc)||A.push({tick:x.tick,type:"controlChange",channel:S,controller:x.cc,value:x.value});for(let x of d.pitchBend??[])A.push({tick:x.tick,type:"pitchBend",channel:S,value:He(x.value)});for(let x of d.notes)A.push({tick:x.startTick,type:"noteOn",channel:S,note:x.pitch,velocity:Math.min(127,Math.max(1,Math.round(x.velocity*127)))}),A.push({tick:x.startTick+x.durationTicks,type:"noteOff",channel:S,note:x.pitch}),c("notation",Bt.some(G=>x[G]!==void 0)?1:0);A.push({tick:Math.max(h,...d.notes.map(x=>x.startTick+x.durationTicks),...(d.controllers??[]).map(x=>x.tick),...(d.pitchBend??[]).map(x=>x.tick)),type:"endOfTrack"}),g.push({events:A}),(d.rests?.length||d.clefChanges?.length)&&c("notation"),(d.volume!==void 0||d.pan!==void 0||d.effects?.length||d.sends?.length)&&c("mixer"),d.instrumentId!=="piano"&&!w.exact&&c("instruments")}return c("repeats",n??e.repeats?.length??0),(e.patches?.length||e.buses?.length)&&c("mixer"),{model:{ppq:Q,tracks:g},dropped:r}}function ae(e,s){let t=se(e,{maxErrors:2});t.ok||re(`not a valid score: ${t.errors[0].message}`);let{model:n,dropped:o}=Je(e,s);return{bytes:te(n),dropped:o}}var R=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Rt=/^[A-Za-z][A-Za-z0-9_-]{0,31}$/,q=Object.freeze({tracks:64,inserts:6,busInserts:3,buses:4,volumeMax:1.5,name:40,tailMax:30}),K=Object.freeze({reverb:{title:"reverb",help:"a room: a generated impulse response (no files), so it works offline",params:{seconds:{def:1.8,min:.1,max:10,step:.1,unit:"s",help:"how long the room rings"},decay:{def:3,min:.5,max:8,step:.1,unit:"",help:"how fast it dies away (higher is quicker)"},preDelay:{def:0,min:0,max:.1,step:.005,unit:"s",help:"a gap before the room starts (0 is no gap, as before this setting existed)"},mix:{def:.3,min:0,max:1,step:.01,unit:"",help:"wet share"}}},chorus:{title:"chorus",help:"two short delays swept by a slow oscillator, one to each side",params:{rate:{def:1.5,min:.1,max:10,step:.1,unit:"Hz",help:"sweep speed"},depth:{def:.5,min:0,max:1,step:.01,unit:"",help:"sweep depth"},spread:{def:.02,min:.001,max:.02,step:.001,unit:"s",help:"the delay of the left line (the right is 30% longer); the sweep is kept inside it, so a short delay sweeps less"},mix:{def:.5,min:0,max:1,step:.01,unit:"",help:"wet share"}}},distortion:{title:"distortion",help:"a soft clipper (tanh) on an oversampled waveshaper",params:{drive:{def:.4,min:0,max:1,step:.01,unit:"",help:"how hard the signal is pushed into the clipper"},mix:{def:1,min:0,max:1,step:.01,unit:"",help:"wet share"}}},eq3:{title:"EQ",help:"three bands: a low shelf at 250 Hz, a mid bell at 1 kHz and a high shelf at 4 kHz",params:{low:{def:0,min:-24,max:24,step:.5,unit:"dB",help:"gain below 250 Hz"},mid:{def:0,min:-24,max:24,step:.5,unit:"dB",help:"gain around 1 kHz"},high:{def:0,min:-24,max:24,step:.5,unit:"dB",help:"gain above 4 kHz"}}},delay:{title:"delay",help:"echoes: a delay line fed back on itself through a low-pass, so each repeat is darker",params:{time:{def:.3,min:.01,max:1.5,step:.01,unit:"s",help:"time between echoes"},feedback:{def:.4,min:0,max:.95,step:.01,unit:"",help:"how much of each echo comes back (0.95 rings a very long time)"},tone:{def:5e3,min:400,max:12e3,step:100,unit:"Hz",help:"low-pass in the feedback path: lower is darker repeats"},mix:{def:.35,min:0,max:1,step:.01,unit:"",help:"wet share"}}}}),qt=Object.freeze(Object.keys(K));var oe=e=>typeof e=="number"&&Number.isFinite(e),Ye=e=>Object.fromEntries(Object.entries(K[e].params).map(([s,t])=>[s,t.def]));function et(e,s,t){let n=K[e]?.params[s];if(n)return oe(t)?Math.min(n.max,Math.max(n.min,t)):n.def}var Xe=e=>({id:e.id,kind:e.kind,bypass:!!e.bypass,params:{...Ye(e.kind),...Object.fromEntries(Object.entries(e.params??{}).filter(([s])=>s in K[e.kind].params).map(([s,t])=>[s,et(e.kind,s,t)]))}});function Lt(e,s){let t=R(e)?e.amount:e;return oe(t)?{amount:Math.min(1,Math.max(0,t)),preFader:R(e)&&typeof e.preFader=="boolean"?e.preFader:s}:null}function tt(e){let s={tracks:{},buses:[]};if(!R(e))return s;let t=Array.isArray(e.buses)?e.buses.filter(r=>R(r)&&typeof r.id=="string"&&Rt.test(r.id)):[],n=new Set;for(let r of t.slice(0,q.buses)){if(n.has(r.id))continue;n.add(r.id);let c=new Set,l=(Array.isArray(r.inserts)?r.inserts:[]).filter(u=>R(u)&&K[u.kind]&&typeof u.id=="string"&&!c.has(u.id)&&c.add(u.id)).slice(0,q.busInserts);s.buses.push({id:r.id,name:typeof r.name=="string"?r.name.slice(0,q.name):r.id,level:oe(r.level)?Math.min(q.volumeMax,Math.max(0,r.level)):1,inserts:l.map(Xe)})}let o=R(e.tracks)?e.tracks:{};for(let r of Object.keys(o).slice(0,q.tracks)){let c=o[r];if(!R(c))continue;let l=new Set,u=(Array.isArray(c.inserts)?c.inserts:[]).filter(f=>R(f)&&K[f.kind]&&typeof f.id=="string"&&!l.has(f.id)&&l.add(f.id)).slice(0,q.inserts);s.tracks[r]={volume:oe(c.volume)?Math.min(q.volumeMax,Math.max(0,c.volume)):1,pan:oe(c.pan)?Math.min(1,Math.max(-1,c.pan)):0,inserts:u.map(Xe),sends:Object.fromEntries(Object.entries(R(c.sends)?c.sends:{}).map(([f,i])=>[f,Lt(i,c.preFader===!0)]).filter(([f,i])=>n.has(f)&&i))}}return s}var En=Object.freeze(["setVolume","setPan","setPreFader","addInsert","removeInsert","setInsert","moveInsert","setSend","addBus","removeBus","setBus","clearMix"]),Ft=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);var Dt=e=>Ft(e?.mallory?.mix)?e.mallory.mix:null;var nt=e=>tt(Dt(e));var Ut=[[91,"reverb"],[93,"chorus"]];function st(e){let s=nt(e);return t=>{let n=s.tracks[t.id];if(!n)return[];let o=[];n.volume!==1&&o.push({controller:7,value:Math.min(127,Math.max(0,Math.round(Math.min(1,n.volume)*127)))}),n.pan!==0&&o.push({controller:10,value:Math.min(127,Math.max(0,Math.round(n.pan<0?64+n.pan*64:64+n.pan*63)))});for(let[r,c]of Ut){let l=n.inserts.find(i=>!i.bypass&&i.kind===c),u=Object.entries(n.sends).reduce((i,[k,h])=>s.buses.find(a=>a.id===k)?.inserts.some(a=>!a.bypass&&a.kind===c)?Math.max(i,h.amount):i,0),f=Math.max(l?l.params.mix:0,u);f<=0&&!l||o.push({controller:r,value:Math.min(127,Math.max(0,Math.round(f*127)))})}return o}}var E=Object.freeze({patterns:64,clips:1024,repeats:256,notes:16384,steps:64,lengthTicks:480*4*64,loopTimes:99});var jn=Object.freeze(["makePattern","editPattern","deletePattern","toggleStep","placePattern","updateClip","deleteClip","moveClips","duplicateClips","setLoop","clearLoop","bakePatterns"]),ie=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),z=e=>Number.isInteger(e),Gt=e=>{throw new Error(e)},Ae=e=>({patterns:e.mallory?.patterns??[],clips:e.mallory?.clips??[],loop:e.mallory?.loop??null}),Oe=e=>!!(e.mallory&&(e.mallory.patterns?.length||e.mallory.clips?.length||e.mallory.loop));function Ee(e){let s=e.mallory;if(s===void 0)return null;if(!ie(s))return"mallory: an object { patterns, clips, loop? }";let{patterns:t=[],clips:n=[],loop:o}=s;if(!Array.isArray(t)||t.length>E.patterns)return`mallory.patterns: a list of at most ${E.patterns}`;if(!Array.isArray(n)||n.length>E.clips)return`mallory.clips: a list of at most ${E.clips}`;let r=new Set;for(let[f,i]of t.entries()){let k=`mallory.patterns[${f}]`;if(!ie(i)||typeof i.id!="string"||!i.id||i.id.length>32||r.has(i.id))return`${k}: needs a unique id (text up to 32 characters)`;if(r.add(i.id),typeof i.name!="string"||i.name.length>80)return`${k}.name: text up to 80 characters`;if(!z(i.lengthTicks)||i.lengthTicks<1||i.lengthTicks>E.lengthTicks)return`${k}.lengthTicks: a whole number of ticks from 1 to ${E.lengthTicks}`;if(i.step!==void 0&&(!z(i.step)||i.step<1||i.step>i.lengthTicks))return`${k}.step: a whole number of ticks, at most the length`;if(!Array.isArray(i.notes)||i.notes.length>4096)return`${k}.notes: a list of at most 4096`;for(let[h,a]of i.notes.entries())if(!ie(a)||!z(a.pitch)||a.pitch<0||a.pitch>127||!z(a.startTick)||a.startTick<0||a.startTick>=i.lengthTicks||!z(a.durationTicks)||a.durationTicks<1||typeof a.velocity!="number"||!(a.velocity>=0&&a.velocity<=1))return`${k}.notes[${h}]: { pitch 0..127, startTick inside the pattern, durationTicks >= 1, velocity 0..1 }`}let c=new Set((e.tracks??[]).map(f=>f.id)),l=new Set;for(let[f,i]of n.entries()){let k=`mallory.clips[${f}]`;if(!ie(i)||typeof i.id!="string"||!i.id||i.id.length>32||l.has(i.id))return`${k}: needs a unique id (text up to 32 characters)`;if(l.add(i.id),!r.has(i.pattern))return`${k}.pattern: no pattern "${i.pattern}"`;if(!c.has(i.track))return`${k}.track: no track "${i.track}"`;if(!z(i.startTick)||i.startTick<0||i.startTick>=2**30)return`${k}.startTick: a whole number of ticks from 0`;if(i.repeats!==void 0&&(!z(i.repeats)||i.repeats<1||i.repeats>E.repeats))return`${k}.repeats: a whole number from 1 to ${E.repeats}`}if(o!=null){if(!ie(o)||!z(o.startMeasure)||o.startMeasure<0||!z(o.endMeasure)||o.endMeasure<=o.startMeasure||o.endMeasure>4096)return"mallory.loop: { startMeasure, endMeasure (after it), times? } in whole measures";if(o.times!==void 0&&(!z(o.times)||o.times<2||o.times>E.loopTimes))return`mallory.loop.times: a whole number from 2 to ${E.loopTimes} (the plays in all)`;if((e.repeats??[]).find(i=>i.measure===o.startMeasure&&i.start||i.measure===o.endMeasure-1&&i.end))return"mallory.loop: the score already has a repeat sign on that bar line"}let u=0;for(let f of n)u+=t.find(i=>i.id===f.pattern).notes.length*(f.repeats??1);return u>E.notes?`the clips unroll to ${u} notes, over the ${E.notes} a score holds`:null}function xe(e){if(!Oe(e))return e;let s=Ee(e);s&&Gt(s);let{patterns:t,clips:n,loop:o}=Ae(e),r=new Map(t.map(i=>[i.id,i])),c=new Map;for(let i of n){let k=r.get(i.pattern),h=c.get(i.track)??[];for(let a=0;a<(i.repeats??1);a++)k.notes.forEach((m,g)=>h.push({id:`${i.id}.${a}.${g}`,startTick:i.startTick+a*k.lengthTicks+m.startTick,durationTicks:Math.min(m.durationTicks,k.lengthTicks-m.startTick),pitch:m.pitch,velocity:m.velocity}));c.set(i.track,h)}let{mallory:l,...u}=e,f={...u,tracks:e.tracks.map(i=>c.has(i.id)?{...i,notes:[...i.notes,...c.get(i.id)]}:i)};if(o){let i=[...e.repeats??[]],k=(h,a)=>{let m=i.findIndex(g=>g.measure===h);m>=0?i[m]={...i[m],...a}:i.push({measure:h,...a})};k(o.startMeasure,{start:!0}),k(o.endMeasure-1,{end:{times:o.times??2}}),f.repeats=i.sort((h,a)=>h.measure-a.measure)}return f}var Ht="mallory.patterns.v1:",Z=Object.freeze({prefix:Uint8Array.from([125,...[...Ht].map(e=>e.charCodeAt(0))]),maxBytes:1024*1024}),ce=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Vt=e=>Math.min(127,Math.max(1,Math.round(e*127))),Ie=e=>`${e.pitch}|${e.startTick}|${e.durationTicks}|${Vt(e.velocity)}`,Kt=(e,s)=>e.length>=s.length&&s.every((t,n)=>e[n]===t);function rt({patterns:e,clips:s,loop:t}){return{patterns:e.map(n=>({id:n.id,name:n.name,lengthTicks:n.lengthTicks,...n.step!==void 0?{step:n.step}:{},notes:n.notes.map(o=>({pitch:o.pitch,startTick:o.startTick,durationTicks:o.durationTicks,velocity:o.velocity}))})),clips:s.map(n=>({id:n.id,pattern:n.pattern,track:n.track,startTick:n.startTick,...n.repeats!==void 0?{repeats:n.repeats}:{}})),loop:t?{startMeasure:t.startMeasure,endMeasure:t.endMeasure,...t.times!==void 0?{times:t.times}:{}}:null}}function at(e,s={}){let t={controllers:st(e),...s};if(!Oe(e))return ae(e,t);let n=xe(e),o=rt(Ae(e)),r=new TextEncoder().encode(JSON.stringify({v:1,...o,tracks:n.tracks.filter(l=>l.notes.length).map(l=>l.id)}));if(r.length>Z.maxBytes){let l=ae(n,t);return{bytes:l.bytes,dropped:{...l.dropped,patterns:1}}}let c=Uint8Array.from([...Z.prefix,...r]);return ae(n,{...t,conductorData:[...t.conductorData??[],c],authoredRepeats:e.repeats?.length??0})}var ot=(e,s,t)=>Wt(we(e,s,t));function Wt(e){let s=(e.sequencerData??[]).filter(o=>Kt(o,Z.prefix));if(!s.length)return{score:e.score,dropped:e.dropped};let t={...e.dropped};(t.sequencerSpecific-=s.length)<=0&&delete t.sequencerSpecific;let n=Qt(e.score,s[0]);return n?{score:n,dropped:t}:{score:e.score,dropped:{...t,patterns:1}}}function Qt(e,s){try{if(s.length-Z.prefix.length>Z.maxBytes)return null;let t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s.subarray(Z.prefix.length)));if(!ce(t)||t.v!==1||!Array.isArray(t.patterns)||!Array.isArray(t.clips)||!Array.isArray(t.tracks)||t.patterns.length>E.patterns||t.clips.length>E.clips||t.tracks.length>64||t.loop!==null&&t.loop!==void 0&&!ce(t.loop)||!t.patterns.every(ce)||!t.clips.every(ce)||!t.tracks.every(i=>typeof i=="string")||new Set(t.tracks).size!==t.tracks.length)return null;let n=e.tracks.every(i=>!i.notes.length);if(t.tracks.length!==e.tracks.length&&!(n&&t.tracks.length===0))return null;let o=new Map(t.tracks.map((i,k)=>[i,e.tracks[k].id]));if(t.patterns.some(i=>!Array.isArray(i.notes))||t.patterns.some(i=>i.notes.some(k=>!ce(k))))return null;let r=t.clips.map(i=>({...i,track:o.get(i.track)??""})),c=rt({patterns:t.patterns,clips:r,loop:t.loop??null});if(!c.patterns.length&&!c.clips.length&&!c.loop)return e;let l={...e,mallory:{patterns:c.patterns,clips:c.clips,...c.loop?{loop:c.loop}:{}}};if(Ee(l)!==null||!se(xe(l),{maxErrors:1}).ok)return null;let u=xe({...l,tracks:l.tracks.map(i=>({...i,notes:[]}))}),f=e.tracks.map(i=>{let k=new Map;for(let a of u.tracks.find(m=>m.id===i.id).notes)k.set(Ie(a),(k.get(Ie(a))??0)+1);let h=[];for(let a of i.notes){let m=Ie(a);k.get(m)>0?k.set(m,k.get(m)-1):h.push(a)}if([...k.values()].some(a=>a>0))throw new Error("a clip's notes are not in the file");return h.length===i.notes.length?i:{...i,notes:h}});return{...l,tracks:f}}catch{return null}}var Zt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Jt=e=>typeof e=="number"&&Number.isFinite(e),it=(e,s,t)=>Math.min(t,Math.max(s,e));var Xt=Object.freeze({custom:16,zones:16,name:40});var Rn=Object.freeze(["sine","triangle","sawtooth","square"]),qn=Object.freeze(["white","pink","brown"]),Ln=Object.freeze(["lowpass","highpass","bandpass"]),Fn=Object.freeze(["off","pitch","filter","amp"]),Dn=Object.freeze({octave:{min:-3,max:3,step:1,def:0,unit:"oct"},detune:{min:-100,max:100,step:1,def:0,unit:"cents"},level:{min:0,max:1,step:.01,def:0,unit:""},cutoff:{min:20,max:18e3,step:10,def:18e3,unit:"Hz"},resonance:{min:0,max:20,step:.1,def:.7,unit:""},envAmount:{min:-6,max:6,step:.1,def:0,unit:"oct"},attack:{min:.001,max:4,step:.001,def:.01,unit:"s"},decay:{min:.001,max:8,step:.01,def:.2,unit:"s"},sustain:{min:0,max:1,step:.01,def:.6,unit:""},release:{min:.005,max:8,step:.01,def:.3,unit:"s"},rate:{min:.05,max:24,step:.05,def:5,unit:"Hz"},depth:{min:0,max:1,step:.01,def:0,unit:""},fmRatio:{min:.25,max:16,step:.25,def:2,unit:"x"},fmIndex:{min:0,max:12,step:.1,def:0,unit:""},program:{min:0,max:127,step:1,def:0,unit:""}}),I=(e,s,t={})=>({shape:e,octave:0,detune:0,level:s,...t}),_=(e,s,t,n)=>({attack:e,decay:s,sustain:t,release:n});function Yt(e={}){return{oscA:I("sawtooth",.6),oscB:I("sawtooth",0),fm:{ratio:2,index:0,decay:.4},noise:{color:"white",level:0},filter:{shape:"lowpass",cutoff:18e3,resonance:.7,envAmount:0},filterEnv:_(.01,.3,.5,.3),ampEnv:_(.01,.2,.6,.3),lfo:{target:"off",rate:5,depth:0},...e}}var L=e=>Yt(e),U=Object.freeze({piano:{name:"Piano",set:"Classic",program:0,synth:L({oscA:I("triangle",.55),oscB:I("sine",.25,{octave:1}),filter:{shape:"lowpass",cutoff:5200,resonance:.7,envAmount:0},ampEnv:_(.003,1.4,0,.35)})},strings:{name:"Strings",set:"Classic",program:48,synth:L({oscA:I("sawtooth",.28,{detune:-8}),oscB:I("sawtooth",.28,{detune:8}),filter:{shape:"lowpass",cutoff:3200,resonance:.7,envAmount:0},ampEnv:_(.3,.5,.85,1.5)})},flute:{name:"Flute",set:"Classic",program:73,synth:L({oscA:I("sine",.6),noise:{color:"pink",level:.03},ampEnv:_(.08,.2,.7,.5)})},harpsichord:{name:"Harpsichord",set:"Classic",program:6,synth:L({oscA:I("square",.28),oscB:I("sawtooth",.18,{octave:1}),filter:{shape:"highpass",cutoff:300,resonance:.7,envAmount:0},ampEnv:_(.002,.6,.02,.3)})},"saw-lead":{name:"Saw Lead",set:"Synthwave",program:81,synth:L({oscA:I("sawtooth",.45),ampEnv:_(.01,.2,.5,.4)})},"warm-pad":{name:"Warm Pad",set:"Synthwave",program:89,synth:L({oscA:I("triangle",.5),lfo:{target:"pitch",rate:4.5,depth:.15},ampEnv:_(.4,.4,.8,1.2)})},"fm-epiano":{name:"FM E-Piano",set:"Synthwave",program:4,synth:L({oscA:I("sine",.55),fm:{ratio:3.01,index:1.4,decay:.4},ampEnv:_(.005,1.2,.2,.8)})},"fat-bass":{name:"Fat Bass",set:"Synthwave",program:38,synth:L({oscA:I("sawtooth",.3,{detune:-20}),oscB:I("sawtooth",.3,{detune:20}),filter:{shape:"lowpass",cutoff:900,resonance:2,envAmount:1.5},filterEnv:_(.005,.25,.2,.3),ampEnv:_(.005,.3,.6,.3)})},"arp-pluck":{name:"Arp Pluck",set:"Synthwave",program:80,synth:L({oscA:I("square",.3),ampEnv:_(.002,.15,.05,.2)})},"drum-kit":{name:"Drum Kit",set:"Rhythm",program:0,drums:!0}}),en=Object.freeze(Object.keys(U)),Un=Object.freeze([...new Set(Object.values(U).map(e=>e.set))]);function tn(e){let s=Math.round(it(Number(e)||0,0,127));return en.find(t=>!U[t].drums&&U[t].program===s)??`gm:${s}`}var nn="drum-kit",sn=/^gm:(\d{1,3})$/;function rn(e,s={}){if(U[e])return{program:U[e].program,drums:!!U[e].drums,exact:!0};let t=sn.exec(String(e));if(t&&Number(t[1])<=127)return{program:Number(t[1]),drums:!1,exact:!0};let n=Zt(s)?s[e]:null;return n?{program:Math.round(it(Jt(n.program)?n.program:0,0,127)),drums:!1,exact:!1}:{program:0,drums:!1,exact:!1}}var je=(e={})=>({forProgram:tn,drum:nn,programOf:s=>rn(s,e)});var Gn=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"});var Hn=Object.freeze({bytes:32*1024*1024,seconds:20}),Vn=Object.freeze({salamander_grand:24}),Kn=Object.freeze({salamander_grand:Object.freeze([33,45,57,60,63,66,69,81,93])});var Wn=Object.freeze({salamander_grand:Object.freeze({33:"17fa1e363f9fad67c3357be54a6defc4fca5a5c2aada21de84b30254f9cb2f5b",45:"20601d890f44a3c22499c7b61f52e571795df1fe5a01fac553dded7b6379e1d4",57:"8e108fe228e34e32f6b4e61efff732eec53058a9e6f05a8d8e719598b132c4f9",60:"689eaa4c2fd7f29a2cc0e386eec462156d523a87d701269e5e2458e66056f4f6",63:"663e8bb3e2d0fa23a30526dcd7ab0e42609c193c07025647ef46badcf81ec211",66:"613652f5c96e35736ce6a46bc4ddb6ba1076d1fb16a35a4c22c14e67efdde57c",69:"a62df24a2c84cea8d18c1fa8aca7c18c877ba2b76a00a591256fa74d3ce54ac3",81:"9e5cee1fe9cf68b7193623d46a27c8956e572c1ff234ca0e11599b556050dec6",93:"b6064a657592c63c03561d2ce1092607c14e1d8091445d50065d0ec819ff6fbc"})}),Qn=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);var Zn=Object.freeze({salamander_grand:48*1024*1024});var Jn=1024*1024;var Xn=Object.freeze({salamander_grand:1});var Ce="gleitz.github.io",ct=`https://${Ce}`,an=`${ct}/midi-js-soundfonts/FluidR3_GM`,ve="tonejs.github.io",on=`https://${ve}/audio/salamander`,rs=Object.freeze([Ce,ve]),as=Object.freeze({fileBytes:512*1024,totalBytes:2*1024*1024,fileMs:3e4});var lt=Object.freeze({acoustic_grand_piano:{name:"Grand Piano",program:0},electric_piano_1:{name:"Rhodes",program:4},acoustic_guitar_nylon:{name:"Nylon Guitar",program:24},acoustic_guitar_steel:{name:"Steel Guitar",program:25},acoustic_bass:{name:"Acoustic Bass",program:32,notes:[24,36,48,60]},violin:{name:"Violin",program:40,notes:[55,60,72,84]},viola:{name:"Viola",program:41,notes:[48,60,72]},cello:{name:"Cello",program:42,notes:[36,48,60,72]},string_ensemble_1:{name:"String Ensemble",program:48},choir_aahs:{name:"Choir Aahs",program:52},flute:{name:"Flute",program:73,notes:[60,72,84]},clarinet:{name:"Clarinet",program:71,notes:[48,60,72]},oboe:{name:"Oboe",program:68,notes:[60,72,84]},trumpet:{name:"Trumpet",program:56,notes:[48,60,72]},trombone:{name:"Trombone",program:57,notes:[36,48,60]},alto_sax:{name:"Alto Sax",program:65,notes:[48,60,72]},church_organ:{name:"Church Organ",program:19},vibraphone:{name:"Vibraphone",program:11},orchestral_harp:{name:"Harp",program:46},salamander_grand:{name:"Salamander Grand Piano",program:0,source:"salamander",notes:[33,45,57,60,63,66,69,81,93]}}),cn=Object.freeze(Object.keys(lt)),ln=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],ut=e=>`${ln[e%12]}${Math.floor(e/12)-1}.mp3`,un=e=>ut(e).replace("#","s"),os=Object.freeze({midijs:Object.freeze({host:Ce,origin:ct,url:(e,s)=>`${an}/${e}-mp3/${ut(s)}`}),salamander:Object.freeze({host:ve,origin:`https://${ve}`,url:(e,s)=>`${on}/${un(s)}`})});var is=Object.freeze({midijs:Object.freeze({text:"General MIDI sounds: FluidR3_GM by Frank Wen (MIT licence), via the MIDI.js soundfonts.",url:"https://github.com/gleitz/midi-js-soundfonts",licenseUrl:"https://opensource.org/license/mit",short:"MIT"}),salamander:Object.freeze({text:"Salamander Grand Piano V3 by Alexander Holm, licensed CC BY 3.0 (credit required), hosted by the Tone.js project.",url:"https://archive.org/details/SalamanderGrandPianoV3",licenseUrl:"https://creativecommons.org/licenses/by/3.0/",short:"CC BY 3.0"})});var J=480,ls=Object.freeze(["reverse","invert","diatonicStep","scaleLength","setLength","tuplet","untuplet","paintNotes","pasteNotes","duplicateNotes","addRest","deleteRests"]),us=Object.freeze({1:4*J,"1/2":2*J,"1/4":J,"1/8":J/2,"1/16":J/4,"1/32":J/8}),fn=Object.freeze(["staccato","accent","tenuto","marcato","fermata"]),fs=Object.freeze({notes:16384,perCall:4096}),ms=Number.isInteger;var hs=Object.freeze(["setDynamic","setArticulation","setSlur","setHairpin","setLyric","setLyrics","setAccidental","setClef","setStaffCount","setVoice","setStaff","splitVoices","moveToTrack"]),gs=Object.freeze(["pp","p","mp","mf","f","ff"]),ks=Object.freeze({pp:.25,p:.4,mp:.55,mf:.7,f:.85,ff:1}),ys=Object.freeze(["sharp","flat","natural","double-sharp","double-flat"]),mn=Object.freeze(["treble","bass","alto","tenor"]);var bs=Number.isInteger;var Bs=Object.freeze(["forkInstrument","setSynth","addSampler","addSoundfont","setZones","removeInstrument","useSavedInstrument"]),pn=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);var ft=e=>pn(e?.mallory?.instruments)?e.mallory.instruments:{};var Us=Object.freeze({...D,score:O}),W=e=>{throw new F(e)};function Ne(e){if(e==null)return{...D};(typeof e!="object"||Array.isArray(e))&&W("options.limits must be an object such as { maxBytes: 100000 }.");let s={...D};for(let t of Object.keys(D)){if(e[t]===void 0)continue;let n=e[t];(typeof n!="number"||!Number.isFinite(n)||n<0)&&W(`options.limits.${t} must be a number of at least 0.`),s[t]=Math.min(s[t],Math.floor(n))}return s}async function mt(e,s){let t=e!==null&&typeof e=="object"&&typeof e.$media=="string"?e.blob:e;return typeof Blob<"u"&&t instanceof Blob?(t.size>s&&W(`the file is ${t.size} bytes, bigger than the ${s}-byte limit.`),new Uint8Array(await t.arrayBuffer())):t instanceof ArrayBuffer?new Uint8Array(t):ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):W("expected bytes: a Uint8Array, an ArrayBuffer, a Blob or a media value (not "+(t===null?"null":typeof t)+").")}async function Gs(e,s={}){let t=Ne(s?.limits),n=await mt(e,t.maxBytes),{score:o,dropped:r}=ot(n,t,{instruments:je()});return{score:o,dropped:r,text:be(r)}}async function Hs(e){(e===null||typeof e!="object")&&W("expected a Score (an object with tracks).");let{bytes:s,dropped:t}=at(e,{instruments:je(ft(e))});return{bytes:s,dropped:t,text:be(t)}}async function Vs(e,s={}){let t=Ne(s?.limits);return ee(await mt(e,t.maxBytes),t)}async function Ks(e,s={}){(e===null||typeof e!="object"||!Array.isArray(e.tracks))&&W("expected { ppq, tracks: [{ events }] }.");let t=Ne(s?.limits);return e.tracks.length>t.maxTracks&&W(`the model has ${e.tracks.length} tracks, more than the ${t.maxTracks} allowed.`),te(e,t)}export{Se as DROPPED_TEXT,F as SmfError,Ks as build,be as describeDropped,Us as limits,Vs as parse,Gs as read,Hs as write};
|