@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,1369 @@
|
|
|
1
|
+
// Hierarchical statecharts: a machine as plain JSON, checked strictly and run deterministically.
|
|
2
|
+
// Pure data and functions, no DOM, no timers, no canvas: src/model/chart-clock.js keeps a canvas's
|
|
3
|
+
// charts in step with the dataflow, the canvas clock and the transport, and it is the only place that
|
|
4
|
+
// schedules anything. Everything here runs under node --test, on virtual time.
|
|
5
|
+
//
|
|
6
|
+
// The runtime contract (docs/guide/canvas-basics.md, "Statecharts") is a documented subset of SCXML / XState v5 semantics,
|
|
7
|
+
// written out in this file and pinned by test/statecharts.test.mjs, not an import of either library:
|
|
8
|
+
// mallory's build is static, a chart's guards and actions are declarative JSON (never code, never a
|
|
9
|
+
// closure, so a machine carries no permission, key or secret and nothing of it needs a sandbox to run),
|
|
10
|
+
// and there is no dependency to pin. What is supported:
|
|
11
|
+
//
|
|
12
|
+
// states atomic, compound (`initial` names a child), parallel (every child is a region and all are
|
|
13
|
+
// active), final, and history (shallow or deep, with an optional default `target`)
|
|
14
|
+
// events `on: { NAME: transition(s), "*": … }`, an exact name beating "*" in the same state
|
|
15
|
+
// delays `after: { "5000": transition(s) }`: a timer that starts when the state is entered and is
|
|
16
|
+
// cancelled when it is exited, fired on virtual time (`advance`, the canvas clock)
|
|
17
|
+
// eventless `always: transition(s)`: taken, repeatedly, until none is enabled (at most MAX_MICROSTEPS)
|
|
18
|
+
// done entering a final child raises `done.<state>` (a parallel state when every region is final)
|
|
19
|
+
// guards `guard: condition | [condition, …]` (all must hold), a condition being src/model/waits.js's
|
|
20
|
+
// { path, op, value | startPath } read from { event, context } ("event.amount", "context.n"),
|
|
21
|
+
// or { in: "#a.b" } (that state is active)
|
|
22
|
+
// actions `entry`, `exit` and a transition's `actions`: { emit: "name", payload? } (an event output of
|
|
23
|
+
// the pane), { assign: { key: value } } (the context), { raise: "EVENT" } (to the chart itself)
|
|
24
|
+
// a value a JSON literal, { value }, { event: "path" } (from the event's payload), { context: "path" },
|
|
25
|
+
// { add: n } (assign only: the key's number plus n)
|
|
26
|
+
//
|
|
27
|
+
// Targets: "sibling" (a child of the source's parent; "a.b" goes down from a sibling), ".child" (a
|
|
28
|
+
// descendant of the source), "#a.b.c" (from the top). A transition with no target only runs its actions.
|
|
29
|
+
// A transition to a descendant of its own state does not leave the state unless `reenter: true`.
|
|
30
|
+
//
|
|
31
|
+
// Priority and conflicts (deterministic): for an event, each active leaf state looks for an enabled
|
|
32
|
+
// transition in itself, then in its ancestors, nearest first, in the order written; transitions of
|
|
33
|
+
// different regions fire together unless they would exit the same states, and then the one from the
|
|
34
|
+
// more deeply nested state wins, else the first in document order. The microstep is exit (deepest first),
|
|
35
|
+
// the transition's actions, enter (outermost first); entry actions run after the context was assigned.
|
|
36
|
+
import { holds, conditionProblem, readPath, MAX_CONDITIONS } from "./waits.js";
|
|
37
|
+
|
|
38
|
+
export const MAX_STATES = 200;
|
|
39
|
+
export const MAX_DEPTH = 8;
|
|
40
|
+
export const MAX_TRANSITIONS = 400;
|
|
41
|
+
export const MAX_ACTIONS = 8;
|
|
42
|
+
export const MAX_EMITS = 32;
|
|
43
|
+
export const MAX_AFTER_MS = 366 * 24 * 3600 * 1000;
|
|
44
|
+
export const MAX_MICROSTEPS = 200; // eventless and raised events in one macrostep before it is called a loop
|
|
45
|
+
export const MAX_CONTEXT_CHARS = 8192;
|
|
46
|
+
export const MAX_TESTS = 20;
|
|
47
|
+
export const MAX_TEST_STEPS = 100;
|
|
48
|
+
export const MAX_LOG = 100;
|
|
49
|
+
export const MAX_TARGETS = 8;
|
|
50
|
+
export const MAX_MACHINES = 16; // child machines in a chart, all levels
|
|
51
|
+
export const MAX_MACHINE_DEPTH = 3; // machines inside machines
|
|
52
|
+
export const MAX_CHILD_STATES = 400; // states in all the child machines together
|
|
53
|
+
export const MAX_ACTORS = 16; // running at once
|
|
54
|
+
export const MAX_CODE_CHARS = 400; // a code guard's expression
|
|
55
|
+
/** Event outputs the pane has besides the ones the machine emits. */
|
|
56
|
+
export const CHART_RESERVED = ["transition"];
|
|
57
|
+
export const HISTORY_MODES = ["shallow", "deep"];
|
|
58
|
+
export const STATE_TYPES = ["atomic", "compound", "parallel", "final", "history"];
|
|
59
|
+
|
|
60
|
+
const NAME = /^[A-Za-z_][A-Za-z0-9_-]{0,31}$/;
|
|
61
|
+
const EVENT = /^(?:[A-Za-z_][A-Za-z0-9_-]{0,31}|done\.[A-Za-z_][A-Za-z0-9_.-]{0,120}|\*)$/;
|
|
62
|
+
const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
63
|
+
const clone = (v) => (v === undefined ? undefined : JSON.parse(JSON.stringify(v)));
|
|
64
|
+
const sameJson = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
65
|
+
|
|
66
|
+
// ── reading a machine ────────────────────────────────────────────────────────
|
|
67
|
+
|
|
68
|
+
const STATE_KEYS = ["type", "initial", "states", "on", "always", "after", "entry", "exit", "history", "target", "description", "invoke", "output"];
|
|
69
|
+
const ROOT_KEYS = ["type", "initial", "states", "on", "always", "after", "entry", "exit", "context", "tests", "description", "id", "machines"];
|
|
70
|
+
const INVOKE_KEYS = ["id", "src", "input", "onDone"];
|
|
71
|
+
const ACTION_KINDS = ["emit", "assign", "raise", "spawn", "stop", "sendTo", "sendParent"];
|
|
72
|
+
const TRANSITION_KEYS = ["target", "guard", "actions", "reenter", "description"];
|
|
73
|
+
|
|
74
|
+
const asList = (v) => (v === undefined || v === null ? [] : Array.isArray(v) ? v : [v]);
|
|
75
|
+
|
|
76
|
+
function valueProblem(spec, where, { add = false } = {}) {
|
|
77
|
+
if (spec === undefined) return "";
|
|
78
|
+
if (isObject(spec)) {
|
|
79
|
+
const keys = Object.keys(spec);
|
|
80
|
+
const known = add ? ["value", "event", "context", "add"] : ["value", "event", "context"];
|
|
81
|
+
if (keys.length !== 1 || !known.includes(keys[0])) return `${where}: an object here is { ${known.join(" | ")}: … } with exactly one of them (wrap a literal object as { value: {…} })`;
|
|
82
|
+
const [k] = keys;
|
|
83
|
+
if (k === "event" || k === "context") return typeof spec[k] === "string" && spec[k].length <= 200 && !/\s/.test(spec[k]) ? "" : `${where}: ${k} is a property path like "order.id" ("" for the whole thing)`;
|
|
84
|
+
if (k === "add") return typeof spec.add === "number" && Number.isFinite(spec.add) ? "" : `${where}: add is a number`;
|
|
85
|
+
return jsonProblem(spec.value, where);
|
|
86
|
+
}
|
|
87
|
+
return jsonProblem(spec, where);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function jsonProblem(value, where) {
|
|
91
|
+
let text;
|
|
92
|
+
try {
|
|
93
|
+
text = JSON.stringify(value);
|
|
94
|
+
} catch {
|
|
95
|
+
return `${where}: a value must be JSON`;
|
|
96
|
+
}
|
|
97
|
+
if (text === undefined) return `${where}: a value must be JSON`;
|
|
98
|
+
return text.length > 1000 ? `${where}: a value is at most 1000 characters of JSON` : "";
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function inputProblems(input, where, out) {
|
|
102
|
+
if (input === undefined) return;
|
|
103
|
+
if (!isObject(input)) return void out.push(`${where}: input is { key: value, … } (the child's context starts with these)`);
|
|
104
|
+
for (const [k, v] of Object.entries(input)) {
|
|
105
|
+
if (!NAME.test(k) || k === "__proto__") out.push(`${where}.${k}: not a context key (letters, digits, _ and -)`);
|
|
106
|
+
const p = valueProblem(v, `${where}.${k}`);
|
|
107
|
+
if (p) out.push(p);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** `cx`: { child: this chart is a child machine, refs: [{ kind, name, at }] collects the machine and actor names to check once the chart is read }. */
|
|
112
|
+
function actionProblems(list, where, cx = {}) {
|
|
113
|
+
const out = [];
|
|
114
|
+
if (list === undefined) return out;
|
|
115
|
+
if (!Array.isArray(list) && !isObject(list)) return [`${where}: actions are a list of { emit | assign | raise | spawn | stop | sendTo | sendParent }`];
|
|
116
|
+
const items = asList(list);
|
|
117
|
+
if (items.length > MAX_ACTIONS) out.push(`${where}: at most ${MAX_ACTIONS} actions in a list`);
|
|
118
|
+
items.forEach((a, i) => {
|
|
119
|
+
const at = `${where}[${i}]`;
|
|
120
|
+
if (!isObject(a)) return void out.push(`${at}: an action is { emit: "name" }, { assign: { key: value } }, { raise: "EVENT" }, { spawn: "machine", id }, { stop: "id" }, { sendTo: "id", event } or { sendParent: "EVENT" }`);
|
|
121
|
+
const kinds = ACTION_KINDS.filter((k) => k in a);
|
|
122
|
+
if (kinds.length !== 1) return void out.push(`${at}: an action has exactly one of ${ACTION_KINDS.slice(0, -1).join(", ")} or ${ACTION_KINDS.at(-1)} (got ${Object.keys(a).join(", ") || "nothing"})`);
|
|
123
|
+
const [kind] = kinds;
|
|
124
|
+
if (kind === "emit") {
|
|
125
|
+
const extra = Object.keys(a).filter((k) => !["emit", "payload"].includes(k));
|
|
126
|
+
if (extra.length) out.push(`${at}: emit has emit and payload (not ${extra.join(", ")})`);
|
|
127
|
+
if (cx.child) out.push(`${at}: a child machine can't emit; send the event up with { sendParent: "EVENT" } and let the chart that runs it emit`);
|
|
128
|
+
if (typeof a.emit !== "string" || !NAME.test(a.emit)) out.push(`${at}: emit names an event output: letters, digits, _ and -, starting with a letter or _ (at most 32)`);
|
|
129
|
+
else if (CHART_RESERVED.includes(a.emit)) out.push(`${at}: "${a.emit}" is the pane's own output (every transition); emit another name`);
|
|
130
|
+
const p = valueProblem(a.payload, `${at}.payload`);
|
|
131
|
+
if (p) out.push(p);
|
|
132
|
+
} else if (kind === "raise") {
|
|
133
|
+
if (Object.keys(a).length !== 1) out.push(`${at}: raise has only the event's name`);
|
|
134
|
+
if (typeof a.raise !== "string" || !EVENT.test(a.raise) || a.raise === "*") out.push(`${at}: raise names an event: letters, digits, _ and -`);
|
|
135
|
+
} else if (kind === "spawn") {
|
|
136
|
+
const extra = Object.keys(a).filter((k) => !["spawn", "id", "input"].includes(k));
|
|
137
|
+
if (extra.length) out.push(`${at}: spawn has spawn (the machine), id and input (not ${extra.join(", ")})`);
|
|
138
|
+
if (typeof a.spawn !== "string" || !NAME.test(a.spawn)) out.push(`${at}: spawn names one of the chart's machines`);
|
|
139
|
+
else cx.refs?.push({ kind: "machine", name: a.spawn, at });
|
|
140
|
+
if (typeof a.id !== "string" || !NAME.test(a.id)) out.push(`${at}: spawn needs an id for the actor: letters, digits, _ and -`);
|
|
141
|
+
else cx.refs?.push({ kind: "spawned", name: a.id, at });
|
|
142
|
+
inputProblems(a.input, `${at}.input`, out);
|
|
143
|
+
} else if (kind === "stop") {
|
|
144
|
+
if (Object.keys(a).length !== 1) out.push(`${at}: stop has only the actor's id`);
|
|
145
|
+
if (typeof a.stop !== "string" || !NAME.test(a.stop)) out.push(`${at}: stop names an actor's id`);
|
|
146
|
+
else cx.refs?.push({ kind: "actor", name: a.stop, at });
|
|
147
|
+
} else if (kind === "sendTo") {
|
|
148
|
+
const extra = Object.keys(a).filter((k) => !["sendTo", "event", "payload"].includes(k));
|
|
149
|
+
if (extra.length) out.push(`${at}: sendTo has sendTo (the actor's id), event and payload (not ${extra.join(", ")})`);
|
|
150
|
+
if (typeof a.sendTo !== "string" || !NAME.test(a.sendTo)) out.push(`${at}: sendTo names an actor's id`);
|
|
151
|
+
else cx.refs?.push({ kind: "actor", name: a.sendTo, at });
|
|
152
|
+
if (typeof a.event !== "string" || !EVENT.test(a.event) || a.event === "*") out.push(`${at}: event names the event to send: letters, digits, _ and -`);
|
|
153
|
+
const p = valueProblem(a.payload, `${at}.payload`);
|
|
154
|
+
if (p) out.push(p);
|
|
155
|
+
} else if (kind === "sendParent") {
|
|
156
|
+
const extra = Object.keys(a).filter((k) => !["sendParent", "payload"].includes(k));
|
|
157
|
+
if (extra.length) out.push(`${at}: sendParent has sendParent (the event) and payload (not ${extra.join(", ")})`);
|
|
158
|
+
if (!cx.child) out.push(`${at}: sendParent is for a child machine, to tell the chart that runs it`);
|
|
159
|
+
if (typeof a.sendParent !== "string" || !EVENT.test(a.sendParent) || a.sendParent === "*") out.push(`${at}: sendParent names an event: letters, digits, _ and -`);
|
|
160
|
+
const p = valueProblem(a.payload, `${at}.payload`);
|
|
161
|
+
if (p) out.push(p);
|
|
162
|
+
} else {
|
|
163
|
+
if (Object.keys(a).length !== 1) out.push(`${at}: assign has only the keys to set`);
|
|
164
|
+
if (!isObject(a.assign) || !Object.keys(a.assign).length) out.push(`${at}: assign is { key: value, … }`);
|
|
165
|
+
else
|
|
166
|
+
for (const [k, v] of Object.entries(a.assign)) {
|
|
167
|
+
if (!NAME.test(k) || k === "__proto__") out.push(`${at}.assign: "${k}" is not a context key (letters, digits, _ and -)`);
|
|
168
|
+
const p = valueProblem(v, `${at}.assign.${k}`, { add: true });
|
|
169
|
+
if (p) out.push(p);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
return out;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function guardProblems(guard, where) {
|
|
177
|
+
if (guard === undefined) return [];
|
|
178
|
+
const items = asList(guard);
|
|
179
|
+
if (!items.length || items.length > MAX_CONDITIONS) return [`${where}: a guard is a condition or a list of 1 to ${MAX_CONDITIONS} (all must hold)`];
|
|
180
|
+
const out = [];
|
|
181
|
+
items.forEach((c, i) => {
|
|
182
|
+
const at = items.length > 1 || Array.isArray(guard) ? `${where}[${i}]` : where;
|
|
183
|
+
if (isObject(c) && "in" in c) {
|
|
184
|
+
if (Object.keys(c).length !== 1 || typeof c.in !== "string" || !c.in.startsWith("#")) out.push(`${at}: { in: "#state.path" } says a state is active`);
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
if (isObject(c) && "code" in c) {
|
|
188
|
+
if (Object.keys(c).length !== 1 || typeof c.code !== "string" || !c.code.trim() || c.code.length > MAX_CODE_CHARS) out.push(`${at}: { code: "event.amount > context.limit" } is a JavaScript expression (at most ${MAX_CODE_CHARS} characters) that reads event (the payload) and context`);
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
const p = conditionProblem(c);
|
|
192
|
+
if (p) return void out.push(`${at}: ${p}`);
|
|
193
|
+
if (!/^(event|context)(\.|$)/.test(c.path ?? "")) out.push(`${at}: a guard reads "event.…" (the event's payload) or "context.…", not "${c.path ?? ""}"`);
|
|
194
|
+
if (c.startPath !== undefined && !/^(event|context)(\.|$)/.test(c.startPath)) out.push(`${at}: startPath reads "event.…" or "context.…"`);
|
|
195
|
+
});
|
|
196
|
+
return out;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const targetShape = (t) => (typeof t === "string" && t !== "") || (Array.isArray(t) && t.length >= 2 && t.length <= MAX_TARGETS && t.every((x) => typeof x === "string" && x !== ""));
|
|
200
|
+
|
|
201
|
+
/** One transition as written (a string, an object) → its pieces, or a problem. */
|
|
202
|
+
function readTransition(raw, where, problems, cx) {
|
|
203
|
+
if (typeof raw === "string") return { target: raw, guard: [], actions: [], reenter: false };
|
|
204
|
+
if (!isObject(raw)) {
|
|
205
|
+
problems.push(`${where}: a transition is a target name or { target, guard, actions }`);
|
|
206
|
+
return null;
|
|
207
|
+
}
|
|
208
|
+
const extra = Object.keys(raw).filter((k) => !TRANSITION_KEYS.includes(k));
|
|
209
|
+
if (extra.length) problems.push(`${where}: a transition has ${TRANSITION_KEYS.join(", ")} (not ${extra.join(", ")})`);
|
|
210
|
+
if (raw.target !== undefined && !targetShape(raw.target)) problems.push(`${where}: target is a state name or a list of 2 to ${MAX_TARGETS} state names (one in each of several regions)`);
|
|
211
|
+
if (raw.reenter !== undefined && typeof raw.reenter !== "boolean") problems.push(`${where}: reenter is true or false`);
|
|
212
|
+
problems.push(...guardProblems(raw.guard, `${where}.guard`));
|
|
213
|
+
problems.push(...actionProblems(raw.actions, `${where}.actions`, cx));
|
|
214
|
+
return { target: raw.target, guard: asList(raw.guard).filter(isObject), actions: asList(raw.actions).filter(isObject), reenter: raw.reenter === true };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Read the machine `raw` (as written) and say, in full, what is wrong with it. `{ ok, problems: [text], machine }`;
|
|
219
|
+
* `machine` is the compiled form `initialSnapshot`, `send` and `advance` run (only when `ok`). Every problem names
|
|
220
|
+
* where it is (`states.work.states.a.on.GO[1]`), so a person or an agent can fix several at once.
|
|
221
|
+
*/
|
|
222
|
+
export function compileChart(raw, cx0 = {}) {
|
|
223
|
+
const problems = [];
|
|
224
|
+
if (!isObject(raw)) return { ok: false, problems: ["a chart is { initial, states, … }"], machine: null };
|
|
225
|
+
const cx = { child: Boolean(cx0.child), depth: cx0.depth ?? 0, budget: cx0.budget ?? { machines: 0, states: 0 }, refs: [] };
|
|
226
|
+
for (const k of Object.keys(raw)) if (!ROOT_KEYS.includes(k)) problems.push(`${k}: not a chart key (${ROOT_KEYS.join(", ")})`);
|
|
227
|
+
if (cx.child && raw.tests !== undefined) problems.push("tests: a child machine has no saved tests; they belong to the chart that runs it");
|
|
228
|
+
// child machines: charts of their own that a state can invoke or an action can spawn (a tree, so no machine can start itself)
|
|
229
|
+
const machines = new Map();
|
|
230
|
+
if (raw.machines !== undefined) {
|
|
231
|
+
if (!isObject(raw.machines)) problems.push("machines: an object of name → chart");
|
|
232
|
+
else if (cx.depth >= MAX_MACHINE_DEPTH) problems.push(`machines: child machines are nested at most ${MAX_MACHINE_DEPTH} deep`);
|
|
233
|
+
else
|
|
234
|
+
for (const [name, child] of Object.entries(raw.machines)) {
|
|
235
|
+
if (!NAME.test(name) || name === "__proto__") {
|
|
236
|
+
problems.push(`machines.${name}: not a machine name (letters, digits, _ and -; at most 32)`);
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
if (++cx.budget.machines > MAX_MACHINES) {
|
|
240
|
+
if (cx.budget.machines === MAX_MACHINES + 1) problems.push(`machines: at most ${MAX_MACHINES} child machines in a chart`);
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
const r = compileChart(child, { child: true, depth: cx.depth + 1, budget: cx.budget });
|
|
244
|
+
problems.push(...r.problems.map((p) => `machines.${name}.${p}`));
|
|
245
|
+
if (r.ok) {
|
|
246
|
+
cx.budget.states += r.machine.nodes.length - 1;
|
|
247
|
+
if (cx.budget.states > MAX_CHILD_STATES && cx.budget.states - (r.machine.nodes.length - 1) <= MAX_CHILD_STATES) problems.push(`machines: at most ${MAX_CHILD_STATES} states in all the child machines together`);
|
|
248
|
+
machines.set(name, r.machine);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
if (raw.context !== undefined) {
|
|
253
|
+
if (!isObject(raw.context)) problems.push("context: an object of JSON values");
|
|
254
|
+
else {
|
|
255
|
+
for (const k of Object.keys(raw.context)) if (!NAME.test(k) || k === "__proto__") problems.push(`context.${k}: not a context key (letters, digits, _ and -)`);
|
|
256
|
+
const p = jsonProblem(raw.context, "context");
|
|
257
|
+
if (!p && JSON.stringify(raw.context).length > MAX_CONTEXT_CHARS) problems.push(`context: at most ${MAX_CONTEXT_CHARS} characters of JSON`);
|
|
258
|
+
else if (p.includes("must be JSON")) problems.push(p);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
const nodes = []; // preorder
|
|
262
|
+
const actorIds = new Set(); // ids of the actors the chart's invoke settings and spawn actions start
|
|
263
|
+
const byPath = new Map();
|
|
264
|
+
const transitions = [];
|
|
265
|
+
let tooMany = false;
|
|
266
|
+
|
|
267
|
+
const walk = (rawState, path, parent, depth, where) => {
|
|
268
|
+
const key = path === "" ? "" : path.slice(path.lastIndexOf(".") + 1);
|
|
269
|
+
const node = { path, key, parent, depth, children: [], order: nodes.length, entry: [], exit: [], transitions: [], type: "atomic", initial: undefined, history: undefined, defaultTarget: undefined };
|
|
270
|
+
nodes.push(node);
|
|
271
|
+
byPath.set(path, node);
|
|
272
|
+
if (!isObject(rawState)) {
|
|
273
|
+
problems.push(`${where}: a state is an object ({ on, states, … }), not ${rawState === null ? "null" : typeof rawState}`);
|
|
274
|
+
return node;
|
|
275
|
+
}
|
|
276
|
+
if (path !== "") for (const k of Object.keys(rawState)) if (!STATE_KEYS.includes(k)) problems.push(`${where}.${k}: not a state key (${STATE_KEYS.join(", ")})`);
|
|
277
|
+
const states = rawState.states;
|
|
278
|
+
const hasStates = states !== undefined;
|
|
279
|
+
if (hasStates && (!isObject(states) || !Object.keys(states).length)) problems.push(`${where}.states: an object of at least one state`);
|
|
280
|
+
let type = rawState.type;
|
|
281
|
+
if (type !== undefined && (typeof type !== "string" || !STATE_TYPES.includes(type))) {
|
|
282
|
+
problems.push(`${where}.type: one of ${STATE_TYPES.join(", ")}`);
|
|
283
|
+
type = undefined;
|
|
284
|
+
}
|
|
285
|
+
if (type === undefined) type = hasStates ? "compound" : "atomic";
|
|
286
|
+
if (path === "" && !["compound", "parallel"].includes(type)) problems.push(`type: the chart is compound or parallel`);
|
|
287
|
+
if (type === "atomic" && hasStates) problems.push(`${where}: an atomic state has no states (type is compound or parallel)`);
|
|
288
|
+
if (["compound", "parallel"].includes(type) && !hasStates) problems.push(`${where}: a ${type} state needs states`);
|
|
289
|
+
node.type = type;
|
|
290
|
+
if (type === "compound") {
|
|
291
|
+
if (typeof rawState.initial !== "string" || !rawState.initial) problems.push(`${where}.initial: a compound state names the child it starts in${isObject(states) ? ` (${Object.keys(states).join(", ")})` : ""}`);
|
|
292
|
+
} else if (rawState.initial !== undefined) problems.push(`${where}.initial: only a compound state has an initial child (${type} states ${type === "parallel" ? "start in all their regions" : "have no children"})`);
|
|
293
|
+
if (rawState.output !== undefined) {
|
|
294
|
+
if (type !== "final") problems.push(`${where}.output: only a final state has an output (what the machine or the compound state around it is done with)`);
|
|
295
|
+
else {
|
|
296
|
+
const p = valueProblem(rawState.output, `${where}.output`);
|
|
297
|
+
if (p) problems.push(p);
|
|
298
|
+
else node.output = rawState.output;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
if (rawState.invoke !== undefined && (type === "final" || type === "history")) problems.push(`${where}.invoke: a ${type} state starts no machine`);
|
|
302
|
+
if (type === "final" || type === "history") {
|
|
303
|
+
for (const k of ["on", "always", "after", "entry", "exit"]) if (rawState[k] !== undefined && !(type === "final" && (k === "entry" || k === "exit"))) problems.push(`${where}.${k}: a ${type} state has no ${k}`);
|
|
304
|
+
}
|
|
305
|
+
if (type === "history") {
|
|
306
|
+
node.history = rawState.history === undefined ? "shallow" : rawState.history;
|
|
307
|
+
if (!HISTORY_MODES.includes(node.history)) {
|
|
308
|
+
problems.push(`${where}.history: shallow or deep`);
|
|
309
|
+
node.history = "shallow";
|
|
310
|
+
}
|
|
311
|
+
if (rawState.target !== undefined && typeof rawState.target !== "string") problems.push(`${where}.target: the state to enter when there is no history yet`);
|
|
312
|
+
node.defaultRaw = rawState.target;
|
|
313
|
+
} else {
|
|
314
|
+
if (rawState.history !== undefined) problems.push(`${where}.history: only a history state has history`);
|
|
315
|
+
if (rawState.target !== undefined) problems.push(`${where}.target: only a history state has a default target`);
|
|
316
|
+
}
|
|
317
|
+
if (depth > MAX_DEPTH) problems.push(`${where}: states are nested at most ${MAX_DEPTH} deep`);
|
|
318
|
+
node.initialRaw = rawState.initial;
|
|
319
|
+
// actions
|
|
320
|
+
for (const [k, list] of [["entry", rawState.entry], ["exit", rawState.exit]]) {
|
|
321
|
+
problems.push(...actionProblems(list, `${where}.${k}`, cx));
|
|
322
|
+
node[k] = asList(list).filter(isObject);
|
|
323
|
+
}
|
|
324
|
+
// transitions, in the order they are tried: events, then "*"; eventless; delays
|
|
325
|
+
const addTransitions = (event, value, at, extra) => {
|
|
326
|
+
if (value === undefined) return;
|
|
327
|
+
const list = Array.isArray(value) ? value : [value];
|
|
328
|
+
if (!list.length) problems.push(`${at}: a list of transitions is not empty`);
|
|
329
|
+
list.forEach((r, i) => {
|
|
330
|
+
const here = Array.isArray(value) ? `${at}[${i}]` : at;
|
|
331
|
+
const t = readTransition(r, here, problems, cx);
|
|
332
|
+
if (!t) return;
|
|
333
|
+
const tr = { id: transitions.length, source: path, event, ...extra, ...t, where: here, index: i, count: list.length, raw: r, targets: [] };
|
|
334
|
+
transitions.push(tr);
|
|
335
|
+
node.transitions.push(tr);
|
|
336
|
+
if (transitions.length > MAX_TRANSITIONS && !tooMany) {
|
|
337
|
+
tooMany = true;
|
|
338
|
+
problems.push(`transitions: at most ${MAX_TRANSITIONS} in a chart`);
|
|
339
|
+
}
|
|
340
|
+
});
|
|
341
|
+
};
|
|
342
|
+
if (rawState.on !== undefined) {
|
|
343
|
+
if (!isObject(rawState.on)) problems.push(`${where}.on: an object of event name → transition(s)`);
|
|
344
|
+
else {
|
|
345
|
+
const names = Object.keys(rawState.on);
|
|
346
|
+
for (const name of [...names.filter((n) => n !== "*"), ...names.filter((n) => n === "*")]) {
|
|
347
|
+
if (!EVENT.test(name)) problems.push(`${where}.on.${name}: not an event name (letters, digits, _ and -, at most 32; "*" for any other)`);
|
|
348
|
+
else if (/^after\./.test(name)) problems.push(`${where}.on.${name}: delays go in "after"`);
|
|
349
|
+
addTransitions(name, rawState.on[name], `${where}.on.${name}`);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
addTransitions(null, rawState.always, `${where}.always`);
|
|
354
|
+
if (rawState.after !== undefined) {
|
|
355
|
+
if (!isObject(rawState.after)) problems.push(`${where}.after: an object of delay in ms → transition(s)`);
|
|
356
|
+
else
|
|
357
|
+
for (const [delay, value] of Object.entries(rawState.after)) {
|
|
358
|
+
const ms = Number(delay);
|
|
359
|
+
if (!/^[1-9][0-9]*$/.test(delay) || !Number.isSafeInteger(ms) || ms > MAX_AFTER_MS) problems.push(`${where}.after.${delay}: a delay is a whole number of ms from 1 to ${MAX_AFTER_MS}`);
|
|
360
|
+
else addTransitions(`after.${ms}.${path}`, value, `${where}.after.${delay}`, { delay: ms });
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
// a machine this state runs while it is active: started on entry, stopped on exit, its result is the done.invoke.<id> event
|
|
364
|
+
if (rawState.invoke !== undefined && type !== "final" && type !== "history") {
|
|
365
|
+
const inv = rawState.invoke;
|
|
366
|
+
const at = `${where}.invoke`;
|
|
367
|
+
if (!isObject(inv)) problems.push(`${at}: { src: "machine", id?, input?, onDone? }`);
|
|
368
|
+
else {
|
|
369
|
+
for (const k of Object.keys(inv)) if (!INVOKE_KEYS.includes(k)) problems.push(`${at}.${k}: invoke has ${INVOKE_KEYS.join(", ")} (not ${k})`);
|
|
370
|
+
const id = inv.id === undefined ? key : inv.id;
|
|
371
|
+
if (typeof inv.src !== "string" || !NAME.test(inv.src)) problems.push(`${at}.src: the name of one of the chart's machines`);
|
|
372
|
+
else cx.refs.push({ kind: "machine", name: inv.src, at: `${at}.src` });
|
|
373
|
+
if (typeof id !== "string" || !NAME.test(id)) problems.push(`${at}.id: the actor's id: letters, digits, _ and -`);
|
|
374
|
+
else {
|
|
375
|
+
if (actorIds.has(id)) problems.push(`${at}: actor id "${id}" is used twice; give one of them an id`);
|
|
376
|
+
actorIds.add(id);
|
|
377
|
+
node.invoke = { id, src: inv.src, input: isObject(inv.input) ? inv.input : undefined };
|
|
378
|
+
addTransitions(`done.invoke.${id}`, inv.onDone, `${at}.onDone`);
|
|
379
|
+
}
|
|
380
|
+
inputProblems(inv.input, `${at}.input`, problems);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
// children
|
|
384
|
+
if (isObject(states)) {
|
|
385
|
+
for (const [name, child] of Object.entries(states)) {
|
|
386
|
+
if (!NAME.test(name) || name === "__proto__") {
|
|
387
|
+
problems.push(`${where}.states.${name}: not a state name (letters, digits, _ and -; no dots; at most 32)`);
|
|
388
|
+
continue;
|
|
389
|
+
}
|
|
390
|
+
const c = walk(child, path === "" ? name : `${path}.${name}`, node, depth + 1, `${where}.states.${name}`);
|
|
391
|
+
node.children.push(c);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
return node;
|
|
395
|
+
};
|
|
396
|
+
|
|
397
|
+
const root = walk(raw, "", null, 0, "chart");
|
|
398
|
+
for (const r of cx.refs) if (r.kind === "spawned") actorIds.add(r.name);
|
|
399
|
+
for (const r of cx.refs) {
|
|
400
|
+
if (r.kind === "machine" && !machines.has(r.name)) problems.push(`${r.at}: "${r.name}" is not one of this chart's machines (${machines.size ? [...machines.keys()].join(", ") : "it has none: add them under machines"})`);
|
|
401
|
+
else if (r.kind === "actor" && !actorIds.has(r.name)) problems.push(`${r.at}: "${r.name}" is not the id of an actor this chart starts (${actorIds.size ? [...actorIds].join(", ") : "none"})`);
|
|
402
|
+
}
|
|
403
|
+
if (nodes.length - 1 > MAX_STATES) problems.push(`states: at most ${MAX_STATES} in a chart`);
|
|
404
|
+
if (nodes.length === 1 && !problems.length) problems.push("states: a chart has at least one state");
|
|
405
|
+
|
|
406
|
+
// ── resolve initial, history defaults and targets ──
|
|
407
|
+
const find = (path) => byPath.get(path);
|
|
408
|
+
const siblingsText = (n) => (n.children.length ? n.children.map((c) => c.key).join(", ") : "none");
|
|
409
|
+
for (const n of nodes) {
|
|
410
|
+
if (n.type === "compound" && typeof n.initialRaw === "string" && n.initialRaw) {
|
|
411
|
+
const child = n.children.find((c) => c.key === n.initialRaw);
|
|
412
|
+
if (!child) problems.push(`${labelOf(n, "initial")}: "${n.initialRaw}" is not a child of ${n.path === "" ? "the chart" : `"${n.path}"`} (${siblingsText(n)})`);
|
|
413
|
+
else if (child.type === "history") problems.push(`${labelOf(n, "initial")}: the initial state can't be a history state`);
|
|
414
|
+
else n.initial = child.path;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
const resolve = (t, target) => {
|
|
418
|
+
const src = find(t.source);
|
|
419
|
+
let path;
|
|
420
|
+
if (target.startsWith("#")) path = target.slice(1);
|
|
421
|
+
else if (target.startsWith(".")) path = t.source === "" ? target.slice(1) : `${t.source}.${target.slice(1)}`;
|
|
422
|
+
else {
|
|
423
|
+
const base = src.parent ?? src;
|
|
424
|
+
path = base.path === "" ? target : `${base.path}.${target}`;
|
|
425
|
+
}
|
|
426
|
+
const to = path === "" ? undefined : find(path);
|
|
427
|
+
if (!to) {
|
|
428
|
+
const base = target.startsWith("#") ? root : target.startsWith(".") ? src : (src.parent ?? src);
|
|
429
|
+
problems.push(`${t.where}: target "${target}" is not a state${target.startsWith("#") ? " from the top of the chart" : target.startsWith(".") ? ` inside "${t.source || "the chart"}"` : ` next to "${src.key || "the chart"}"`}${target.startsWith("#") ? "" : ` (${siblingsText(base)})`}`);
|
|
430
|
+
return null;
|
|
431
|
+
}
|
|
432
|
+
return to;
|
|
433
|
+
};
|
|
434
|
+
function labelOf(n, what) {
|
|
435
|
+
return n.path === "" ? what : `states.${n.path.split(".").join(".states.")}.${what}`;
|
|
436
|
+
}
|
|
437
|
+
for (const t of transitions) {
|
|
438
|
+
if (t.target === undefined || !targetShape(t.target)) continue;
|
|
439
|
+
const written = Array.isArray(t.target) ? t.target : [t.target];
|
|
440
|
+
const tos = written.map((target) => resolve(t, target));
|
|
441
|
+
if (tos.some((to) => !to)) continue;
|
|
442
|
+
t.targets = tos.map((to) => to.path);
|
|
443
|
+
if (tos.length === 1 && tos[0].path === t.source && t.reenter === false) t.self = true;
|
|
444
|
+
// Several targets are entered together: one state in each of several regions of a parallel state, nothing twice, nothing inside another.
|
|
445
|
+
for (let i = 0; i < tos.length; i++)
|
|
446
|
+
for (let j = i + 1; j < tos.length; j++) {
|
|
447
|
+
const a = tos[i];
|
|
448
|
+
const b = tos[j];
|
|
449
|
+
if (a === b) problems.push(`${t.where}: target names "${a.path}" twice`);
|
|
450
|
+
else if (isInside(a, b) || isInside(b, a)) {
|
|
451
|
+
const [outer, inner] = isInside(a, b) ? [b, a] : [a, b];
|
|
452
|
+
problems.push(`${t.where}: "${outer.path}" holds "${inner.path}"; a transition with several targets enters one state each, in different regions of a parallel state`);
|
|
453
|
+
} else {
|
|
454
|
+
const lc = lcaOf(a, b);
|
|
455
|
+
if (!lc || lc.type !== "parallel") problems.push(`${t.where}: "${a.path}" and "${b.path}" are in the same region (of ${lc?.path ? `"${lc.path}"` : "the chart"}); a transition with several targets enters one state each, in different regions of a parallel state`);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
for (const n of nodes) {
|
|
460
|
+
if (n.type !== "history") continue;
|
|
461
|
+
if (!n.parent || !["compound", "parallel"].includes(n.parent.type)) problems.push(`${labelOf(n, "type")}: a history state sits inside a compound or parallel state`);
|
|
462
|
+
if (typeof n.defaultRaw === "string") {
|
|
463
|
+
const base = n.parent;
|
|
464
|
+
const path = base ? (base.path === "" ? n.defaultRaw : `${base.path}.${n.defaultRaw}`) : n.defaultRaw;
|
|
465
|
+
const to = find(path);
|
|
466
|
+
if (!to || to === n) problems.push(`${labelOf(n, "target")}: "${n.defaultRaw}" is not a state next to this history state (${base ? siblingsText(base) : "none"})`);
|
|
467
|
+
else n.defaultTarget = to.path;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
{
|
|
471
|
+
// ── conflicts among the alternatives of one event, and reachability (only worth saying once the chart reads) ──
|
|
472
|
+
for (const n of nodes) {
|
|
473
|
+
const groups = new Map();
|
|
474
|
+
for (const t of n.transitions) groups.set(t.event ?? "\u0000always", [...(groups.get(t.event ?? "\u0000always") ?? []), t]);
|
|
475
|
+
for (const [event, list] of groups) {
|
|
476
|
+
const label = event === "\u0000always" ? "always" : /^after\./.test(event) ? `after ${list[0].delay}` : `on ${event}`;
|
|
477
|
+
const seenSame = new Map();
|
|
478
|
+
list.forEach((t, i) => {
|
|
479
|
+
const sig = JSON.stringify([t.guard, t.targets, t.reenter]);
|
|
480
|
+
if (seenSame.has(sig) && !t.actions.length) problems.push(`${t.where}: the same transition as ${seenSame.get(sig)} (${label} in "${n.path || "the chart"}")`);
|
|
481
|
+
else seenSame.set(sig, t.where);
|
|
482
|
+
const shadow = list.slice(0, i).find((u) => !u.guard.length);
|
|
483
|
+
if (shadow) problems.push(`${t.where}: never taken: ${shadow.where} (${label} in "${n.path || "the chart"}") has no guard, so it always wins; give it a guard or put it last`);
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
// events handled by two regions of a parallel state in ways that conflict: one of them leaves the parallel state
|
|
488
|
+
for (const n of nodes) {
|
|
489
|
+
if (n.type !== "parallel") continue;
|
|
490
|
+
const byEvent = new Map();
|
|
491
|
+
for (const region of n.children) for (const t of collectTransitions(region)) if (t.event !== null && !/^after\./.test(t.event)) byEvent.set(t.event, [...(byEvent.get(t.event) ?? []), { region: region.key, t }]);
|
|
492
|
+
for (const [event, list] of byEvent) {
|
|
493
|
+
const regions = new Set(list.map((l) => l.region));
|
|
494
|
+
if (regions.size < 2) continue;
|
|
495
|
+
const leaving = list.filter((l) => l.t.targets.length && !l.t.guard.length && leavesState(domainOf({ byPath, root }, l.t), n));
|
|
496
|
+
if (leaving.length) {
|
|
497
|
+
const others = list.filter((l) => l.region !== leaving[0].region && !l.t.guard.length);
|
|
498
|
+
if (others.length) problems.push(`${leaving[0].t.where}: conflicts with ${others[0].t.where}: "${event}" leaves parallel state "${n.path}" from region "${leaving[0].region}" and is also handled in region "${others[0].region}"; only one can win. Guard one of them`);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
if (!problems.length) {
|
|
503
|
+
const reach = reachable(root, transitions, find);
|
|
504
|
+
for (const n of nodes) if (n.path !== "" && !reach.has(n.path)) problems.push(`state "${n.path}" is unreachable: it is not an initial state and no transition leads to it`);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
// tests (saved event sequences)
|
|
508
|
+
problems.push(...testProblems(raw.tests, byPath, actorIds));
|
|
509
|
+
if (problems.length) return { ok: false, problems: problems.map((p) => p.replace(/\bchart\.(?=states|on\.|after|always|entry|exit|initial|tests|context|type|history|target|description)/g, "")), machine: null };
|
|
510
|
+
const emits = [...new Set(allActions(nodes, transitions).flatMap((a) => (typeof a.emit === "string" ? [a.emit] : [])))];
|
|
511
|
+
if (emits.length > MAX_EMITS) return { ok: false, problems: [`emit: at most ${MAX_EMITS} different events are emitted`], machine: null };
|
|
512
|
+
return {
|
|
513
|
+
ok: true,
|
|
514
|
+
problems: [],
|
|
515
|
+
machine: { root, nodes, byPath, transitions, machines, actors: [...actorIds], usesCode: transitions.some((t) => t.guard.some((c) => "code" in c)) || [...machines.values()].some((m) => m.usesCode), context: clone(raw.context ?? {}), emits, tests: clone(raw.tests ?? []), id: typeof raw.id === "string" ? raw.id : "", events: [...new Set(transitions.flatMap((t) => (t.event !== null && t.event !== "*" && !/^after\./.test(t.event) && !/^done\./.test(t.event) ? [t.event] : [])))].sort() },
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
const allActions = (nodes, transitions) => [...nodes.flatMap((n) => [...n.entry, ...n.exit]), ...transitions.flatMap((t) => t.actions)];
|
|
520
|
+
const isInside = (node, ancestor) => {
|
|
521
|
+
for (let n = node; n; n = n.parent) if (n === ancestor) return true;
|
|
522
|
+
return false;
|
|
523
|
+
};
|
|
524
|
+
const leavesState = (domain, node) => Boolean(domain) && isInside(node, domain);
|
|
525
|
+
const collectTransitions = (node) => [...node.transitions, ...node.children.flatMap(collectTransitions)];
|
|
526
|
+
|
|
527
|
+
function lcaOf(a, b) {
|
|
528
|
+
const ancestors = new Set();
|
|
529
|
+
for (let n = a; n; n = n.parent) ancestors.add(n);
|
|
530
|
+
for (let n = b; n; n = n.parent) if (ancestors.has(n) && n !== a && n !== b) return n;
|
|
531
|
+
return null;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/** Every state a chart can be in, by following the initial states and the transitions out of states it can be in. */
|
|
535
|
+
function reachable(root, transitions, find) {
|
|
536
|
+
const seen = new Set([""]);
|
|
537
|
+
const down = (n) => {
|
|
538
|
+
seen.add(n.path);
|
|
539
|
+
if (n.type === "history") {
|
|
540
|
+
const to = n.defaultTarget ? find(n.defaultTarget) : n.parent?.initial ? find(n.parent.initial) : null;
|
|
541
|
+
if (to) enter(to);
|
|
542
|
+
} else if (n.type === "compound" && n.initial) down(find(n.initial));
|
|
543
|
+
else if (n.type === "parallel") for (const c of n.children) if (c.type !== "history") down(c);
|
|
544
|
+
};
|
|
545
|
+
const enter = (node) => {
|
|
546
|
+
for (let n = node; n && n.parent; n = n.parent) {
|
|
547
|
+
seen.add(n.path);
|
|
548
|
+
if (n.parent.type === "parallel") for (const s of n.parent.children) if (s !== n && s.type !== "history") down(s);
|
|
549
|
+
}
|
|
550
|
+
down(node);
|
|
551
|
+
};
|
|
552
|
+
if (root.type === "parallel") for (const c of root.children) down(c);
|
|
553
|
+
else enter(find(root.initial));
|
|
554
|
+
for (let before = -1; before !== seen.size; ) {
|
|
555
|
+
before = seen.size;
|
|
556
|
+
for (const t of transitions) if (seen.has(t.source)) for (const target of t.targets) enter(find(target));
|
|
557
|
+
}
|
|
558
|
+
return seen;
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
function testProblems(tests, byPath, actorIds = new Set()) {
|
|
562
|
+
if (tests === undefined) return [];
|
|
563
|
+
if (!Array.isArray(tests)) return ["tests: a list of { name, steps, expect }"];
|
|
564
|
+
const out = [];
|
|
565
|
+
if (tests.length > MAX_TESTS) out.push(`tests: at most ${MAX_TESTS}`);
|
|
566
|
+
const names = new Set();
|
|
567
|
+
tests.slice(0, MAX_TESTS).forEach((t, i) => {
|
|
568
|
+
const at = `tests[${i}]`;
|
|
569
|
+
if (!isObject(t)) return void out.push(`${at}: { name, steps, expect }`);
|
|
570
|
+
for (const k of Object.keys(t)) if (!["name", "steps", "expect"].includes(k)) out.push(`${at}.${k}: a test has name, steps and expect`);
|
|
571
|
+
if (typeof t.name !== "string" || !t.name.trim() || t.name.length > 80) out.push(`${at}.name: text, at most 80 characters`);
|
|
572
|
+
else if (names.has(t.name)) out.push(`${at}.name: "${t.name}" is a test already`);
|
|
573
|
+
else names.add(t.name);
|
|
574
|
+
if (!Array.isArray(t.steps) || t.steps.length > MAX_TEST_STEPS) out.push(`${at}.steps: a list of at most ${MAX_TEST_STEPS} steps`);
|
|
575
|
+
else
|
|
576
|
+
t.steps.forEach((s, j) => {
|
|
577
|
+
const here = `${at}.steps[${j}]`;
|
|
578
|
+
if (!isObject(s)) return void out.push(`${here}: { send: "EVENT", payload? } or { advance: ms }`);
|
|
579
|
+
const kinds = ["send", "advance"].filter((k) => k in s);
|
|
580
|
+
if (kinds.length !== 1) return void out.push(`${here}: exactly one of send or advance`);
|
|
581
|
+
for (const k of Object.keys(s)) if (!["send", "advance", "payload"].includes(k)) out.push(`${here}.${k}: a step has send (with payload) or advance`);
|
|
582
|
+
if (kinds[0] === "send" && (typeof s.send !== "string" || !EVENT.test(s.send) || s.send === "*")) out.push(`${here}.send: an event name`);
|
|
583
|
+
if (kinds[0] === "advance" && !(Number.isSafeInteger(s.advance) && s.advance >= 0 && s.advance <= MAX_AFTER_MS)) out.push(`${here}.advance: a whole number of ms`);
|
|
584
|
+
if (s.payload !== undefined && kinds[0] === "advance") out.push(`${here}.payload: only a send has a payload`);
|
|
585
|
+
if (s.payload !== undefined) {
|
|
586
|
+
const p = jsonProblem(s.payload, `${here}.payload`);
|
|
587
|
+
if (p) out.push(p);
|
|
588
|
+
}
|
|
589
|
+
});
|
|
590
|
+
if (!isObject(t.expect)) out.push(`${at}.expect: { configuration?, context?, emitted?, output?, actors? }`);
|
|
591
|
+
else {
|
|
592
|
+
for (const k of Object.keys(t.expect)) if (!["configuration", "context", "emitted", "output", "actors"].includes(k)) out.push(`${at}.expect.${k}: configuration, context, emitted, output or actors`);
|
|
593
|
+
if (t.expect.output !== undefined) {
|
|
594
|
+
const p = jsonProblem(t.expect.output, `${at}.expect.output`);
|
|
595
|
+
if (p) out.push(p);
|
|
596
|
+
}
|
|
597
|
+
if (t.expect.actors !== undefined) {
|
|
598
|
+
if (!isObject(t.expect.actors)) out.push(`${at}.expect.actors: { actorId: [innermost states] }`);
|
|
599
|
+
else
|
|
600
|
+
for (const [id, want] of Object.entries(t.expect.actors)) {
|
|
601
|
+
if (!actorIds.has(id)) out.push(`${at}.expect.actors: "${id}" is not the id of an actor this chart starts (${actorIds.size ? [...actorIds].join(", ") : "none"})`);
|
|
602
|
+
else if (!Array.isArray(want) || want.some((x) => typeof x !== "string")) out.push(`${at}.expect.actors.${id}: a list of the actor's innermost states`);
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
if (t.expect.configuration !== undefined) {
|
|
606
|
+
if (!Array.isArray(t.expect.configuration) || t.expect.configuration.some((p) => typeof p !== "string")) out.push(`${at}.expect.configuration: a list of the leaf states that should be active ("work.a.idle")`);
|
|
607
|
+
else
|
|
608
|
+
for (const p of t.expect.configuration) {
|
|
609
|
+
const node = byPath.get(p);
|
|
610
|
+
if (!node || p === "") out.push(`${at}.expect.configuration: "${p}" is not a state`);
|
|
611
|
+
else if (node.children.length) out.push(`${at}.expect.configuration: "${p}" has states inside it; name the innermost state(s)`);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
if (t.expect.context !== undefined && !isObject(t.expect.context)) out.push(`${at}.expect.context: an object (the keys that should have these values)`);
|
|
615
|
+
if (t.expect.emitted !== undefined && (!Array.isArray(t.expect.emitted) || t.expect.emitted.some((n) => typeof n !== "string"))) out.push(`${at}.expect.emitted: the event names emitted, in order`);
|
|
616
|
+
}
|
|
617
|
+
});
|
|
618
|
+
return out;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/** Why `raw` can't be a chart, as one text (every problem), or "". */
|
|
622
|
+
export function chartProblem(raw) {
|
|
623
|
+
if (raw === undefined || raw === null) return "";
|
|
624
|
+
const { problems } = compileChartCached(raw);
|
|
625
|
+
return problems.length ? problems.join("; ") : "";
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
const LINTS = new WeakMap();
|
|
629
|
+
/**
|
|
630
|
+
* Warnings about a compiled machine (never refusals; the chart still runs), found on its innermost states:
|
|
631
|
+
* - dead ends: a non-final state with no transition out of it, or out of a state around it, that goes anywhere;
|
|
632
|
+
* - traps: reachable states from which no sequence of transitions reaches a final state, even though the chart
|
|
633
|
+
* has final states (a chart without any is one that runs forever, so nothing is called trapped in it).
|
|
634
|
+
* Guards and delays are taken as possible, so a finding means "no path at all", not "no path under these inputs".
|
|
635
|
+
* Entering a state means entering the innermost states it starts in (every region of a parallel one), and a region
|
|
636
|
+
* counts as having a way to finish if any of them has, which errs towards saying nothing.
|
|
637
|
+
* Returns { finals, deadEnds, traps, byState: { path: "final" | "dead-end" | "trap" }, halts, findings } (paths sorted by chart order).
|
|
638
|
+
*/
|
|
639
|
+
export function lintChart(machine) {
|
|
640
|
+
const hit = LINTS.get(machine);
|
|
641
|
+
if (hit) return hit;
|
|
642
|
+
const { nodes, byPath, root } = machine;
|
|
643
|
+
const find = (path) => byPath.get(path);
|
|
644
|
+
const leaves = nodes.filter((n) => n.path !== "" && !n.children.some((c) => c.type !== "history") && n.type !== "history");
|
|
645
|
+
const enters = (n, into = new Set(), seen = new Set()) => {
|
|
646
|
+
if (seen.has(n)) return into;
|
|
647
|
+
seen.add(n);
|
|
648
|
+
if (n.type === "history") {
|
|
649
|
+
const parent = n.parent;
|
|
650
|
+
if (n.defaultTarget) enters(find(n.defaultTarget), into, seen);
|
|
651
|
+
for (const c of parent?.children ?? []) if (c.type !== "history") enters(c, into, seen); // what it last held is not known
|
|
652
|
+
} else if (n.type === "compound") enters(find(n.initial), into, seen);
|
|
653
|
+
else if (n.type === "parallel") {
|
|
654
|
+
for (const c of n.children) if (c.type !== "history") enters(c, into, seen);
|
|
655
|
+
} else into.add(n);
|
|
656
|
+
return into;
|
|
657
|
+
};
|
|
658
|
+
const out = new Map(leaves.map((l) => [l, new Set()]));
|
|
659
|
+
const exits = new Map(leaves.map((l) => [l, 0]));
|
|
660
|
+
for (const leaf of leaves) {
|
|
661
|
+
for (let n = leaf; n; n = n.parent) {
|
|
662
|
+
for (const t of n.transitions) {
|
|
663
|
+
if (!t.targets.length) continue;
|
|
664
|
+
exits.set(leaf, exits.get(leaf) + 1);
|
|
665
|
+
for (const target of t.targets) for (const to of enters(find(target))) out.get(leaf).add(to);
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
// what the chart starts in, then everything reachable from there
|
|
670
|
+
const live = enters(root.type === "parallel" ? root : find(root.initial));
|
|
671
|
+
for (const l of live) for (const to of out.get(l) ?? []) live.add(to);
|
|
672
|
+
const finals = leaves.filter((l) => l.type === "final");
|
|
673
|
+
// backwards from the final states: who can still get there
|
|
674
|
+
const back = new Map(leaves.map((l) => [l, []]));
|
|
675
|
+
for (const [from, tos] of out) for (const to of tos) back.get(to).push(from);
|
|
676
|
+
const canFinish = new Set(finals);
|
|
677
|
+
for (const l of canFinish) for (const from of back.get(l)) canFinish.add(from);
|
|
678
|
+
const deadEnds = leaves.filter((l) => l.type !== "final" && exits.get(l) === 0 && live.has(l));
|
|
679
|
+
const traps = finals.length ? leaves.filter((l) => l.type !== "final" && exits.get(l) > 0 && live.has(l) && !canFinish.has(l)) : [];
|
|
680
|
+
const byState = {};
|
|
681
|
+
for (const l of finals) byState[l.path] = "final";
|
|
682
|
+
for (const l of deadEnds) byState[l.path] = "dead-end";
|
|
683
|
+
for (const l of traps) byState[l.path] = "trap";
|
|
684
|
+
const list = (xs) => xs.map((l) => l.path).join(", ");
|
|
685
|
+
const findings = [
|
|
686
|
+
...(deadEnds.length ? [`dead end${deadEnds.length === 1 ? "" : "s"}: ${list(deadEnds)} (not final, and no transition leaves ${deadEnds.length === 1 ? "it" : "them"})`] : []),
|
|
687
|
+
...(traps.length ? [`trapped: ${list(traps)} (${traps.length === 1 ? "it" : "they"} can never reach a final state, although ${list(finals)} can be reached from elsewhere)`] : []),
|
|
688
|
+
];
|
|
689
|
+
const result = { halts: finals.length > 0, finals: finals.map((l) => l.path), deadEnds: deadEnds.map((l) => l.path), traps: traps.map((l) => l.path), byState, findings };
|
|
690
|
+
LINTS.set(machine, result);
|
|
691
|
+
return result;
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
const CACHE = new Map();
|
|
695
|
+
/** compileChart, remembered by the text of the chart (panes re-read their settings a lot). */
|
|
696
|
+
export function compileChartCached(raw) {
|
|
697
|
+
let key;
|
|
698
|
+
try {
|
|
699
|
+
key = JSON.stringify(raw ?? null);
|
|
700
|
+
} catch {
|
|
701
|
+
return compileChart(raw);
|
|
702
|
+
}
|
|
703
|
+
let hit = CACHE.get(key);
|
|
704
|
+
if (!hit) {
|
|
705
|
+
hit = compileChart(raw ?? {});
|
|
706
|
+
CACHE.set(key, hit);
|
|
707
|
+
if (CACHE.size > 64) CACHE.delete(CACHE.keys().next().value);
|
|
708
|
+
}
|
|
709
|
+
return hit;
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
export const DEFAULT_CHART = {
|
|
713
|
+
initial: "idle",
|
|
714
|
+
context: { count: 0 },
|
|
715
|
+
states: {
|
|
716
|
+
idle: { on: { start: { target: "running", actions: [{ assign: { count: { add: 1 } } }] } } },
|
|
717
|
+
running: { entry: [{ emit: "started" }], after: { 5000: "idle" }, on: { stop: "idle" } },
|
|
718
|
+
},
|
|
719
|
+
};
|
|
720
|
+
|
|
721
|
+
/** A chart in words, for the pane, agents and the Markdown format. */
|
|
722
|
+
export function describeChart(raw) {
|
|
723
|
+
const { ok, machine } = compileChartCached(raw ?? {});
|
|
724
|
+
if (!ok) return "a statechart that can't run yet";
|
|
725
|
+
const leaves = machine.nodes.filter((n) => n.path !== "" && !n.children.length).length;
|
|
726
|
+
const parallel = machine.nodes.filter((n) => n.type === "parallel").length;
|
|
727
|
+
const timers = machine.transitions.filter((t) => t.delay !== undefined).length;
|
|
728
|
+
const histories = machine.nodes.filter((n) => n.type === "history").length;
|
|
729
|
+
const children = machine.machines.size;
|
|
730
|
+
return `${children ? `${children} child machine${children === 1 ? "" : "s"}, ` : ""}${machine.nodes.length - 1} state${machine.nodes.length === 2 ? "" : "s"} (${leaves} innermost${parallel ? `, ${parallel} parallel` : ""}${histories ? `, ${histories} with history` : ""}), ${machine.transitions.length} transition${machine.transitions.length === 1 ? "" : "s"}${timers ? `, ${timers} delayed` : ""}; starts in ${machine.root.type === "parallel" ? "every region" : machine.root.initial}`;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/** A short stable string for what a chart means (a change restarts it). */
|
|
734
|
+
export const chartPrint = (raw) => {
|
|
735
|
+
const { tests: _tests, ...rest } = isObject(raw) ? raw : {};
|
|
736
|
+
return JSON.stringify(rest);
|
|
737
|
+
};
|
|
738
|
+
|
|
739
|
+
// ── running a machine ────────────────────────────────────────────────────────
|
|
740
|
+
|
|
741
|
+
/** An error a macrostep throws and `send` turns into a refused event (the snapshot is left as it was). */
|
|
742
|
+
class ChartError extends Error {}
|
|
743
|
+
|
|
744
|
+
function working(machine, snap, code) {
|
|
745
|
+
return {
|
|
746
|
+
machine,
|
|
747
|
+
code,
|
|
748
|
+
conf: new Set(snap.configuration),
|
|
749
|
+
context: clone(snap.context),
|
|
750
|
+
history: clone(snap.history ?? {}),
|
|
751
|
+
timers: clone(snap.timers ?? []),
|
|
752
|
+
seq: snap.seq ?? 0,
|
|
753
|
+
now: snap.time ?? 0,
|
|
754
|
+
done: Boolean(snap.done),
|
|
755
|
+
output: clone(snap.output),
|
|
756
|
+
actors: clone(snap.actors ?? {}),
|
|
757
|
+
outbox: [],
|
|
758
|
+
toParent: [],
|
|
759
|
+
emitted: [],
|
|
760
|
+
log: [],
|
|
761
|
+
queue: [],
|
|
762
|
+
warnings: [],
|
|
763
|
+
steps: 0,
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
function freeze(w) {
|
|
768
|
+
const order = (set) => [...set].sort((a, b) => w.machine.byPath.get(a).order - w.machine.byPath.get(b).order);
|
|
769
|
+
return {
|
|
770
|
+
configuration: order(w.conf),
|
|
771
|
+
context: w.context,
|
|
772
|
+
history: w.history,
|
|
773
|
+
timers: w.timers,
|
|
774
|
+
seq: w.seq,
|
|
775
|
+
time: w.now,
|
|
776
|
+
done: w.done,
|
|
777
|
+
...(w.output !== undefined ? { output: w.output } : {}),
|
|
778
|
+
...(Object.keys(w.actors).length ? { actors: w.actors } : {}),
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
// ── actors: child machines this chart runs ──────────────────────────────────
|
|
783
|
+
// An invoked actor lives while its state is active; a spawned one until `stop` or the chart is reset. Each has a
|
|
784
|
+
// snapshot of its own in `snapshot.actors[id]`, on the same clock. The parent reaches it with `sendTo`, it reaches
|
|
785
|
+
// the parent with `sendParent`, and when it reaches a final state of its own the parent gets `done.invoke.<id>`
|
|
786
|
+
// carrying `{ output }`. Messages are delivered between steps, in order, so a run is the same every time.
|
|
787
|
+
|
|
788
|
+
/** Start actor `id` of machine `src` (input evaluated now). Returns false when it could not start (a warning says why). */
|
|
789
|
+
function startActor(w, id, src, input, owner, event) {
|
|
790
|
+
const child = w.machine.machines.get(src);
|
|
791
|
+
if (w.actors[id]) return void w.warnings.push(`actor "${id}" is already running; it was not started again`) ?? false;
|
|
792
|
+
if (Object.keys(w.actors).length >= MAX_ACTORS) return void w.warnings.push(`actor "${id}" was not started: ${MAX_ACTORS} are running`) ?? false;
|
|
793
|
+
const values = {};
|
|
794
|
+
for (const [k, spec] of Object.entries(input ?? {})) values[k] = readValue(w, spec, event);
|
|
795
|
+
const start = initialSnapshot(child, w.now, { input: values, code: w.code });
|
|
796
|
+
if (!start.snapshot) return void w.warnings.push(`actor "${id}" could not start: ${start.error}`) ?? false;
|
|
797
|
+
w.actors[id] = { src, ...(owner ? { owner } : {}), snapshot: start.snapshot };
|
|
798
|
+
takeFromActor(w, id, start);
|
|
799
|
+
return true;
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
/** What an actor's step returned: its new snapshot, what it sent up, and whether it is now done. */
|
|
803
|
+
function takeFromActor(w, id, r) {
|
|
804
|
+
const actor = w.actors[id];
|
|
805
|
+
if (!actor) return;
|
|
806
|
+
actor.snapshot = r.snapshot;
|
|
807
|
+
for (const m of r.toParent ?? []) w.queue.push({ name: m.name, payload: clone(m.payload ?? null), internal: true, actor: id });
|
|
808
|
+
for (const text of r.warnings ?? []) w.warnings.push(`actor "${id}": ${text}`);
|
|
809
|
+
if (r.snapshot.done && !actor.finished) {
|
|
810
|
+
actor.finished = true;
|
|
811
|
+
w.queue.push({ name: `done.invoke.${id}`, payload: { output: clone(r.snapshot.output ?? null) }, internal: true, actor: id });
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
function deliverOutbox(w) {
|
|
816
|
+
const batch = w.outbox.splice(0);
|
|
817
|
+
for (const m of batch) {
|
|
818
|
+
const actor = w.actors[m.to];
|
|
819
|
+
if (!actor) {
|
|
820
|
+
w.warnings.push(`sendTo: no actor "${m.to}" is running; "${m.name}" was dropped`);
|
|
821
|
+
continue;
|
|
822
|
+
}
|
|
823
|
+
if (actor.finished) continue;
|
|
824
|
+
if (++w.steps > MAX_MICROSTEPS) throw new ChartError(`more than ${MAX_MICROSTEPS} steps in a row for one event (actors sending each other events forever?)`);
|
|
825
|
+
const r = send(w.machine.machines.get(actor.src), actor.snapshot, m.name, m.payload, w.now, { code: w.code });
|
|
826
|
+
if (r.error) w.warnings.push(`actor "${m.to}" refused "${m.name}": ${r.error}`);
|
|
827
|
+
else {
|
|
828
|
+
if (!r.handled) w.warnings.push(`actor "${m.to}" ignored "${m.name}"`);
|
|
829
|
+
takeFromActor(w, m.to, r);
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
/** The actors of a snapshot, for a pane's value: `{ id: { machine, configuration, context, done, output? } }`. */
|
|
835
|
+
export function actorsOf(machine, snapshot) {
|
|
836
|
+
const out = {};
|
|
837
|
+
for (const [id, a] of Object.entries(snapshot.actors ?? {})) {
|
|
838
|
+
const child = machine.machines.get(a.src);
|
|
839
|
+
out[id] = { machine: a.src, configuration: child ? activeLeaves(child, a.snapshot) : [], context: a.snapshot.context, done: Boolean(a.snapshot.done), ...(a.snapshot.output !== undefined ? { output: a.snapshot.output } : {}), ...(Object.keys(a.snapshot.actors ?? {}).length ? { actors: actorsOf(child, a.snapshot) } : {}) };
|
|
840
|
+
}
|
|
841
|
+
return out;
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
const leavesOf = (w) => [...w.conf].filter((p) => p !== "" && !w.machine.byPath.get(p).children.some((c) => w.conf.has(c.path))).sort((a, b) => w.machine.byPath.get(a).order - w.machine.byPath.get(b).order);
|
|
845
|
+
export const activeLeaves = (machine, snapshot) => snapshot.configuration.filter((p) => p !== "" && !machine.byPath.get(p).children.some((c) => snapshot.configuration.includes(c.path)));
|
|
846
|
+
|
|
847
|
+
const ancestorsOf = (n) => {
|
|
848
|
+
const out = [];
|
|
849
|
+
for (let x = n.parent; x; x = x.parent) out.push(x);
|
|
850
|
+
return out;
|
|
851
|
+
};
|
|
852
|
+
const isDescendant = (n, of) => n !== of && isInside(n, of);
|
|
853
|
+
|
|
854
|
+
function readValue(w, spec, event, current) {
|
|
855
|
+
if (isObject(spec)) {
|
|
856
|
+
if ("value" in spec) return clone(spec.value);
|
|
857
|
+
if ("event" in spec) return clone(readPath(event.payload ?? null, spec.event).value) ?? null;
|
|
858
|
+
if ("context" in spec) return clone(readPath(w.context, spec.context).value) ?? null;
|
|
859
|
+
if ("add" in spec) return (typeof current === "number" ? current : 0) + spec.add;
|
|
860
|
+
}
|
|
861
|
+
return clone(spec);
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
function guardsHold(w, t, event) {
|
|
865
|
+
if (!t.guard.length) return true;
|
|
866
|
+
const data = { event: event.payload ?? null, context: w.context };
|
|
867
|
+
// a code guard is decided outside this pure module (`code(source, data)`: true, or false when it is unknown or fails); see resolveCode
|
|
868
|
+
return t.guard.every((c) => ("in" in c ? w.conf.has(c.in.slice(1)) : "code" in c ? w.code?.(c.code, clone(data)) === true : holds(c, data, data)));
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
function runActions(w, actions, event, from) {
|
|
872
|
+
for (const a of actions) {
|
|
873
|
+
if (a.emit !== undefined) {
|
|
874
|
+
const payload = a.payload === undefined ? clone(event.payload ?? null) : readValue(w, a.payload, event);
|
|
875
|
+
w.emitted.push({ name: a.emit, payload, at: w.now, event: event.name, from });
|
|
876
|
+
} else if (a.raise !== undefined) {
|
|
877
|
+
w.queue.push({ name: a.raise, payload: clone(event.payload ?? null), internal: true });
|
|
878
|
+
} else if (a.spawn !== undefined) {
|
|
879
|
+
startActor(w, a.id, a.spawn, a.input, null, event);
|
|
880
|
+
} else if (a.stop !== undefined) {
|
|
881
|
+
delete w.actors[a.stop];
|
|
882
|
+
} else if (a.sendTo !== undefined) {
|
|
883
|
+
w.outbox.push({ to: a.sendTo, name: a.event, payload: a.payload === undefined ? clone(event.payload ?? null) : readValue(w, a.payload, event) });
|
|
884
|
+
} else if (a.sendParent !== undefined) {
|
|
885
|
+
w.toParent.push({ name: a.sendParent, payload: a.payload === undefined ? clone(event.payload ?? null) : readValue(w, a.payload, event) });
|
|
886
|
+
} else if (a.assign) {
|
|
887
|
+
const next = { ...w.context };
|
|
888
|
+
for (const [k, v] of Object.entries(a.assign)) next[k] = readValue(w, v, event, next[k]);
|
|
889
|
+
if (JSON.stringify(next).length > MAX_CONTEXT_CHARS) {
|
|
890
|
+
w.warnings.push(`an assign was refused: the context would pass ${MAX_CONTEXT_CHARS} characters`);
|
|
891
|
+
continue;
|
|
892
|
+
}
|
|
893
|
+
w.context = next;
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
/** Transitions enabled by `event` (or none-named when `eventless`), as the SCXML selection: nearest state first, an exact name before "*". */
|
|
899
|
+
function selectTransitions(w, event, eventless) {
|
|
900
|
+
const out = [];
|
|
901
|
+
const seen = new Set();
|
|
902
|
+
for (const leaf of leavesOf(w)) {
|
|
903
|
+
const node = w.machine.byPath.get(leaf);
|
|
904
|
+
for (const s of [node, ...ancestorsOf(node)]) {
|
|
905
|
+
const pool = eventless ? s.transitions.filter((t) => t.event === null) : [...s.transitions.filter((t) => t.event === event.name), ...s.transitions.filter((t) => t.event === "*")];
|
|
906
|
+
const t = pool.find((x) => guardsHold(w, x, event));
|
|
907
|
+
if (t) {
|
|
908
|
+
if (!seen.has(t.id)) {
|
|
909
|
+
seen.add(t.id);
|
|
910
|
+
out.push(t);
|
|
911
|
+
}
|
|
912
|
+
break;
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
return out.sort((a, b) => w.machine.byPath.get(a.source).order - w.machine.byPath.get(b.source).order || a.id - b.id);
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
/** The state a transition happens inside (nothing outside it is left or entered), or null for a transition that only runs actions. */
|
|
920
|
+
function domainOf(machine, t) {
|
|
921
|
+
if (!t.targets.length || (t.self && !t.reenter)) return null;
|
|
922
|
+
const src = machine.byPath.get(t.source);
|
|
923
|
+
const targets = t.targets.map((p) => machine.byPath.get(p));
|
|
924
|
+
if (!t.reenter && src.type === "compound" && targets.every((x) => isDescendant(x, src))) return src; // internal: the source stays
|
|
925
|
+
for (const a of ancestorsOf(src)) if (a.type === "compound" && targets.every((x) => isDescendant(x, a))) return a;
|
|
926
|
+
return machine.root;
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
function exitSetOf(w, t) {
|
|
930
|
+
const domain = domainOf(w.machine, t);
|
|
931
|
+
if (!domain) return [];
|
|
932
|
+
return [...w.conf].filter((p) => p !== "" && isDescendant(w.machine.byPath.get(p), domain));
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
function removeConflicts(w, enabled) {
|
|
936
|
+
const kept = [];
|
|
937
|
+
for (const t1 of enabled) {
|
|
938
|
+
const exits1 = new Set(exitSetOf(w, t1));
|
|
939
|
+
let preempted = false;
|
|
940
|
+
const drop = [];
|
|
941
|
+
for (const t2 of kept) {
|
|
942
|
+
const overlap = exitSetOf(w, t2).some((p) => exits1.has(p));
|
|
943
|
+
if (!overlap) continue;
|
|
944
|
+
if (isDescendant(w.machine.byPath.get(t1.source), w.machine.byPath.get(t2.source))) drop.push(t2);
|
|
945
|
+
else {
|
|
946
|
+
preempted = true;
|
|
947
|
+
break;
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
if (!preempted) {
|
|
951
|
+
for (const d of drop) kept.splice(kept.indexOf(d), 1);
|
|
952
|
+
kept.push(t1);
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
return kept;
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
/** The states entered by default when `node` is entered: collects into `into`. */
|
|
959
|
+
function addDescendants(w, node, into, explicit) {
|
|
960
|
+
const m = w.machine;
|
|
961
|
+
if (node.type === "history") {
|
|
962
|
+
const saved = w.history[node.parent.path];
|
|
963
|
+
if (saved) {
|
|
964
|
+
for (const p of saved[node.history]) addDescendants(w, m.byPath.get(p), into, explicit);
|
|
965
|
+
for (const p of saved[node.history]) addAncestors(w, m.byPath.get(p), node.parent, into, explicit);
|
|
966
|
+
} else {
|
|
967
|
+
const to = node.defaultTarget ? m.byPath.get(node.defaultTarget) : node.parent.initial ? m.byPath.get(node.parent.initial) : null;
|
|
968
|
+
if (to) {
|
|
969
|
+
addDescendants(w, to, into, explicit);
|
|
970
|
+
addAncestors(w, to, node.parent, into, explicit);
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
return;
|
|
974
|
+
}
|
|
975
|
+
into.add(node.path);
|
|
976
|
+
if (node.type === "compound") {
|
|
977
|
+
const first = m.byPath.get(node.initial);
|
|
978
|
+
if (![...explicit].some((p) => isInside(m.byPath.get(p), node) && p !== node.path)) {
|
|
979
|
+
addDescendants(w, first, into, explicit);
|
|
980
|
+
addAncestors(w, first, node, into);
|
|
981
|
+
}
|
|
982
|
+
} else if (node.type === "parallel") {
|
|
983
|
+
for (const c of node.children) if (c.type !== "history" && ![...into].some((p) => isInside(m.byPath.get(p), c)) && ![...explicit].some((p) => isInside(m.byPath.get(p), c))) addDescendants(w, c, into, explicit);
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
function addAncestors(w, node, stop, into, explicit = new Set()) {
|
|
988
|
+
for (const a of ancestorsOf(node)) {
|
|
989
|
+
if (a === stop) break;
|
|
990
|
+
into.add(a.path);
|
|
991
|
+
if (a.type === "parallel") for (const c of a.children) if (c.type !== "history" && ![...into].some((p) => isInside(w.machine.byPath.get(p), c)) && ![...explicit].some((p) => isInside(w.machine.byPath.get(p), c))) addDescendants(w, c, into, new Set());
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
function entrySetOf(w, transitions, exited) {
|
|
996
|
+
const m = w.machine;
|
|
997
|
+
const into = new Set();
|
|
998
|
+
const explicit = new Set(transitions.flatMap((t) => t.targets));
|
|
999
|
+
for (const t of transitions) {
|
|
1000
|
+
const domain = domainOf(m, t);
|
|
1001
|
+
if (!domain) continue;
|
|
1002
|
+
for (const target of t.targets) {
|
|
1003
|
+
const to = m.byPath.get(target);
|
|
1004
|
+
addDescendants(w, to, into, explicit);
|
|
1005
|
+
if (to.type === "history") {
|
|
1006
|
+
// what it restores is entered with the history state's parent (and that parent's ancestors, below the domain)
|
|
1007
|
+
if (to.parent !== domain) into.add(to.parent.path);
|
|
1008
|
+
addAncestors(w, to.parent, domain, into, explicit);
|
|
1009
|
+
} else addAncestors(w, to, domain, into, explicit);
|
|
1010
|
+
}
|
|
1011
|
+
// a parallel domain (the chart itself) was left whole: every region is entered again, unless a target says where
|
|
1012
|
+
if (domain.type === "parallel") for (const c of domain.children) if (c.type !== "history" && ![...into].some((p) => isInside(m.byPath.get(p), c))) addDescendants(w, c, into, explicit);
|
|
1013
|
+
}
|
|
1014
|
+
void exited;
|
|
1015
|
+
// a state entered that is already active and not leaving stays as it is
|
|
1016
|
+
return [...into].filter((p) => p !== "" && (!w.conf.has(p) || exited.has(p))).sort((a, b) => m.byPath.get(a).order - m.byPath.get(b).order);
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
function microstep(w, transitions, event) {
|
|
1020
|
+
const m = w.machine;
|
|
1021
|
+
const before = leavesOf(w);
|
|
1022
|
+
const exitSet = new Set(transitions.flatMap((t) => exitSetOf(w, t)));
|
|
1023
|
+
// history is recorded as the state goes
|
|
1024
|
+
const exitOrder = [...exitSet].sort((a, b) => m.byPath.get(b).order - m.byPath.get(a).order);
|
|
1025
|
+
for (const p of exitSet) {
|
|
1026
|
+
const node = m.byPath.get(p);
|
|
1027
|
+
if (node.children.some((c) => c.type === "history")) {
|
|
1028
|
+
const active = [...w.conf].filter((q) => isDescendant(m.byPath.get(q), node));
|
|
1029
|
+
w.history[p] = {
|
|
1030
|
+
shallow: active.filter((q) => m.byPath.get(q).parent === node),
|
|
1031
|
+
deep: active.filter((q) => m.byPath.get(q).type !== "history" && !m.byPath.get(q).children.some((c) => w.conf.has(c.path))),
|
|
1032
|
+
};
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
const entry = entrySetOf(w, transitions, exitSet);
|
|
1036
|
+
const emittedFrom = w.emitted.length;
|
|
1037
|
+
for (const p of exitOrder) {
|
|
1038
|
+
const node = m.byPath.get(p);
|
|
1039
|
+
runActions(w, node.exit, event, before);
|
|
1040
|
+
if (node.invoke) delete w.actors[node.invoke.id];
|
|
1041
|
+
w.conf.delete(p);
|
|
1042
|
+
w.timers = w.timers.filter((tm) => tm.state !== p);
|
|
1043
|
+
}
|
|
1044
|
+
for (const t of transitions) runActions(w, t.actions, event, before);
|
|
1045
|
+
const finals = [];
|
|
1046
|
+
for (const p of entry) {
|
|
1047
|
+
const node = m.byPath.get(p);
|
|
1048
|
+
w.conf.add(p);
|
|
1049
|
+
for (const t of node.transitions) {
|
|
1050
|
+
if (t.delay === undefined || w.timers.some((tm) => tm.event === t.event)) continue;
|
|
1051
|
+
w.timers.push({ id: ++w.seq, state: p, delay: t.delay, event: t.event, dueAt: w.now + t.delay });
|
|
1052
|
+
}
|
|
1053
|
+
runActions(w, node.entry, event, before);
|
|
1054
|
+
if (node.invoke) startActor(w, node.invoke.id, node.invoke.src, node.invoke.input, p, event);
|
|
1055
|
+
if (node.type === "final") finals.push({ node, output: node.output === undefined ? undefined : readValue(w, node.output, event) });
|
|
1056
|
+
}
|
|
1057
|
+
for (const { node: f, output } of finals) {
|
|
1058
|
+
const parent = f.parent;
|
|
1059
|
+
if (!parent) continue;
|
|
1060
|
+
if (parent.path === "") {
|
|
1061
|
+
w.done = true;
|
|
1062
|
+
if (output !== undefined) w.output = output;
|
|
1063
|
+
continue;
|
|
1064
|
+
}
|
|
1065
|
+
if (parent.type === "compound") w.queue.push({ name: `done.${parent.path}`, payload: output === undefined ? null : { output }, internal: true });
|
|
1066
|
+
const grand = parent.parent;
|
|
1067
|
+
if (grand && grand.type === "parallel" && grand.children.every((r) => r.children.some((c) => c.type === "final" && w.conf.has(c.path)) || (r.type === "final" && w.conf.has(r.path)))) w.queue.push({ name: `done.${grand.path}`, payload: null, internal: true });
|
|
1068
|
+
}
|
|
1069
|
+
w.steps++;
|
|
1070
|
+
if (w.steps > MAX_MICROSTEPS) throw new ChartError(`more than ${MAX_MICROSTEPS} transitions in a row for one event (a loop of eventless or raised transitions?)`);
|
|
1071
|
+
w.log.push({
|
|
1072
|
+
at: w.now,
|
|
1073
|
+
event: event.name,
|
|
1074
|
+
...(event.internal ? { internal: true } : {}),
|
|
1075
|
+
from: before,
|
|
1076
|
+
to: leavesOf(w),
|
|
1077
|
+
transitions: transitions.map((t) => ({ source: t.source, ...(t.targets.length ? { target: t.targets[0] } : {}), ...(t.targets.length > 1 ? { targets: t.targets } : {}), where: t.where })),
|
|
1078
|
+
emitted: w.emitted.slice(emittedFrom).map((e) => e.name),
|
|
1079
|
+
});
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
function settle(w) {
|
|
1083
|
+
for (;;) {
|
|
1084
|
+
if (w.outbox.length) {
|
|
1085
|
+
deliverOutbox(w);
|
|
1086
|
+
continue;
|
|
1087
|
+
}
|
|
1088
|
+
let enabled = selectTransitions(w, { name: "", payload: null }, true);
|
|
1089
|
+
if (enabled.length) {
|
|
1090
|
+
microstep(w, removeConflicts(w, enabled), { name: "always", payload: null, internal: true });
|
|
1091
|
+
continue;
|
|
1092
|
+
}
|
|
1093
|
+
const next = w.queue.shift();
|
|
1094
|
+
if (!next) return;
|
|
1095
|
+
enabled = selectTransitions(w, next, false);
|
|
1096
|
+
if (enabled.length) microstep(w, removeConflicts(w, enabled), next);
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
/** Put the machine in its initial configuration: entry actions run, eventless transitions are taken. `{ snapshot, emitted, log, warnings }`. */
|
|
1101
|
+
export function initialSnapshot(machine, now = 0, { input, code } = {}) {
|
|
1102
|
+
const w = {
|
|
1103
|
+
machine,
|
|
1104
|
+
code,
|
|
1105
|
+
conf: new Set(),
|
|
1106
|
+
context: { ...clone(machine.context), ...clone(input ?? {}) },
|
|
1107
|
+
actors: {},
|
|
1108
|
+
outbox: [],
|
|
1109
|
+
toParent: [],
|
|
1110
|
+
history: {},
|
|
1111
|
+
timers: [],
|
|
1112
|
+
seq: 0,
|
|
1113
|
+
now,
|
|
1114
|
+
done: false,
|
|
1115
|
+
emitted: [],
|
|
1116
|
+
log: [],
|
|
1117
|
+
queue: [],
|
|
1118
|
+
warnings: [],
|
|
1119
|
+
steps: 0,
|
|
1120
|
+
};
|
|
1121
|
+
const event = { name: "init", payload: null, internal: true };
|
|
1122
|
+
const into = new Set();
|
|
1123
|
+
const root = machine.root;
|
|
1124
|
+
if (root.type === "parallel") addDescendants(w, root, into, new Set());
|
|
1125
|
+
else addDescendants(w, machine.byPath.get(root.initial), into, new Set()), addAncestors(w, machine.byPath.get(root.initial), root, into);
|
|
1126
|
+
const entry = [...into].filter((p) => p !== "").sort((a, b) => machine.byPath.get(a).order - machine.byPath.get(b).order);
|
|
1127
|
+
w.conf.add("");
|
|
1128
|
+
runActions(w, root.entry, event, []);
|
|
1129
|
+
for (const t of root.transitions) if (t.delay !== undefined) w.timers.push({ id: ++w.seq, state: "", delay: t.delay, event: t.event, dueAt: now + t.delay });
|
|
1130
|
+
const finals = [];
|
|
1131
|
+
for (const p of entry) {
|
|
1132
|
+
const node = machine.byPath.get(p);
|
|
1133
|
+
w.conf.add(p);
|
|
1134
|
+
for (const t of node.transitions) if (t.delay !== undefined && !w.timers.some((tm) => tm.event === t.event)) w.timers.push({ id: ++w.seq, state: p, delay: t.delay, event: t.event, dueAt: now + t.delay });
|
|
1135
|
+
runActions(w, node.entry, event, []);
|
|
1136
|
+
if (node.invoke) startActor(w, node.invoke.id, node.invoke.src, node.invoke.input, p, event);
|
|
1137
|
+
if (node.type === "final") finals.push({ node, output: node.output === undefined ? undefined : readValue(w, node.output, event) });
|
|
1138
|
+
}
|
|
1139
|
+
for (const { node: f, output } of finals) {
|
|
1140
|
+
if (f.parent?.path === "") {
|
|
1141
|
+
w.done = true;
|
|
1142
|
+
if (output !== undefined) w.output = output;
|
|
1143
|
+
} else if (f.parent?.type === "compound") w.queue.push({ name: `done.${f.parent.path}`, payload: output === undefined ? null : { output }, internal: true });
|
|
1144
|
+
}
|
|
1145
|
+
w.log.push({ at: now, event: "init", internal: true, from: [], to: leavesOf(w), transitions: [], emitted: w.emitted.map((e) => e.name) });
|
|
1146
|
+
try {
|
|
1147
|
+
settle(w);
|
|
1148
|
+
} catch (error) {
|
|
1149
|
+
if (error instanceof ChartError) return { snapshot: null, emitted: [], log: [], warnings: [], toParent: [], error: error.message };
|
|
1150
|
+
throw error;
|
|
1151
|
+
}
|
|
1152
|
+
return { snapshot: freeze(w), emitted: w.emitted, log: w.log, warnings: w.warnings, toParent: w.toParent };
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
/**
|
|
1156
|
+
* Send event `name` (with `payload`) to the machine at `snapshot`, at time `at` (never earlier than the snapshot's own).
|
|
1157
|
+
* `{ snapshot, emitted: [{ name, payload, at, event }], log: [one entry per transition], handled, warnings }`. An event
|
|
1158
|
+
* nothing handles changes nothing (`handled: false`). A loop of eventless transitions refuses the event (`error`).
|
|
1159
|
+
* The input snapshot is never changed.
|
|
1160
|
+
*/
|
|
1161
|
+
export function send(machine, snapshot, name, payload = null, at = snapshot.time, { code } = {}) {
|
|
1162
|
+
const w = working(machine, snapshot, code);
|
|
1163
|
+
w.now = Math.max(w.now, at);
|
|
1164
|
+
return runEvent(w, snapshot, { name, payload: clone(payload ?? null) });
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
function runEvent(w, snapshot, event) {
|
|
1168
|
+
return runWork(w, snapshot, () => {
|
|
1169
|
+
// the external event first (an unhandled external event is dropped), then whatever it raised
|
|
1170
|
+
const enabled = selectTransitions(w, event, false);
|
|
1171
|
+
if (!enabled.length) return false;
|
|
1172
|
+
microstep(w, removeConflicts(w, enabled), event);
|
|
1173
|
+
return true;
|
|
1174
|
+
});
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
/** Run `first` on the working copy, then everything it set going; the result, or the refusal with the snapshot as it was. */
|
|
1178
|
+
function runWork(w, snapshot, first) {
|
|
1179
|
+
let handled = false;
|
|
1180
|
+
try {
|
|
1181
|
+
handled = first() === true;
|
|
1182
|
+
settle(w);
|
|
1183
|
+
} catch (error) {
|
|
1184
|
+
if (error instanceof ChartError) return { snapshot, emitted: [], log: [], handled: false, warnings: [], toParent: [], error: error.message };
|
|
1185
|
+
throw error;
|
|
1186
|
+
}
|
|
1187
|
+
return { snapshot: freeze(w), emitted: w.emitted, log: w.log, handled, warnings: w.warnings, toParent: w.toParent };
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
/**
|
|
1191
|
+
* Every delay pending in the snapshot, a running actor's included (`actor`: the path of ids down to it, `[]` for this chart's own).
|
|
1192
|
+
* The id of an actor's delay is text (`"timer:3"`), unique within the snapshot.
|
|
1193
|
+
*/
|
|
1194
|
+
export function timersIn(snapshot, path = []) {
|
|
1195
|
+
const own = (snapshot.timers ?? []).map((t) => ({ ...t, actor: path, id: path.length ? `${path.join("/")}:${t.id}` : t.id }));
|
|
1196
|
+
const nested = Object.entries(snapshot.actors ?? {}).flatMap(([id, a]) => (a.finished ? [] : timersIn(a.snapshot, [...path, id])));
|
|
1197
|
+
return [...own, ...nested];
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
/** The time of the next delay that will fire, or null. */
|
|
1201
|
+
export const nextDue = (snapshot) => {
|
|
1202
|
+
const all = timersIn(snapshot);
|
|
1203
|
+
return all.length ? Math.min(...all.map((t) => t.dueAt)) : null;
|
|
1204
|
+
};
|
|
1205
|
+
|
|
1206
|
+
/** The timers in the order they fire (a chart's own before an actor's due at the same time). */
|
|
1207
|
+
export const timersInOrder = (snapshot) => timersIn(snapshot).sort((a, b) => a.dueAt - b.dueAt || a.actor.length - b.actor.length || a.actor.join("/").localeCompare(b.actor.join("/")) || (typeof a.id === "number" && typeof b.id === "number" ? a.id - b.id : String(a.id).localeCompare(String(b.id))));
|
|
1208
|
+
|
|
1209
|
+
/**
|
|
1210
|
+
* Let time pass to `to`: every delay due by then fires, earliest first (one macrostep each, at its own due time, so a chain
|
|
1211
|
+
* of delays plays out as if watched). `{ snapshot, emitted, log, fired: n }`. `limit`: stop after that many (a single step).
|
|
1212
|
+
*/
|
|
1213
|
+
export function advance(machine, snapshot, to, { limit = Infinity, at, code } = {}) {
|
|
1214
|
+
let snap = snapshot;
|
|
1215
|
+
const out = { emitted: [], log: [], fired: 0, warnings: [], toParent: [] };
|
|
1216
|
+
while (out.fired < limit) {
|
|
1217
|
+
const next = timersInOrder(snap)[0];
|
|
1218
|
+
if (!next || next.dueAt > to) break;
|
|
1219
|
+
const w = working(machine, snap, code);
|
|
1220
|
+
w.now = Math.max(w.now, at ?? next.dueAt);
|
|
1221
|
+
let r;
|
|
1222
|
+
if (next.actor.length) {
|
|
1223
|
+
// an actor's delay: it fires inside the actor, which then tells this chart what it sent up and whether it is done
|
|
1224
|
+
const id = next.actor[0];
|
|
1225
|
+
const actor = w.actors[id];
|
|
1226
|
+
const child = actor && machine.machines.get(actor.src);
|
|
1227
|
+
if (!child) {
|
|
1228
|
+
snap = { ...snap, actors: Object.fromEntries(Object.entries(snap.actors ?? {}).filter(([k]) => k !== id)) };
|
|
1229
|
+
out.fired++;
|
|
1230
|
+
continue;
|
|
1231
|
+
}
|
|
1232
|
+
const inner = advance(child, actor.snapshot, next.dueAt, { limit: 1, at: w.now, code });
|
|
1233
|
+
r = runWork(w, snap, () => takeFromActor(w, id, { snapshot: inner.snapshot, toParent: inner.toParent, warnings: inner.warnings }));
|
|
1234
|
+
} else {
|
|
1235
|
+
w.timers = w.timers.filter((t) => t.id !== next.id);
|
|
1236
|
+
r = runEvent(w, snap, { name: next.event, payload: null, timer: true });
|
|
1237
|
+
}
|
|
1238
|
+
if (r.error) {
|
|
1239
|
+
// the loop is refused: the timer is spent, nothing else changed
|
|
1240
|
+
snap = next.actor.length ? snap : { ...snap, timers: snap.timers.filter((t) => t.id !== next.id) };
|
|
1241
|
+
out.error = r.error;
|
|
1242
|
+
out.fired++;
|
|
1243
|
+
continue;
|
|
1244
|
+
}
|
|
1245
|
+
snap = r.snapshot;
|
|
1246
|
+
out.emitted.push(...r.emitted);
|
|
1247
|
+
out.log.push(...r.log);
|
|
1248
|
+
out.warnings.push(...r.warnings);
|
|
1249
|
+
out.toParent.push(...r.toParent);
|
|
1250
|
+
out.fired++;
|
|
1251
|
+
}
|
|
1252
|
+
snap = { ...snap, time: Math.max(snap.time, to === Infinity ? snap.time : to) };
|
|
1253
|
+
return { snapshot: snap, ...out };
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
/** The active state as a nested value (XState's `value`): "idle", or { work: { a: "x" } }; a parallel state is an object by region. */
|
|
1257
|
+
export function valueOf(machine, snapshot) {
|
|
1258
|
+
const conf = new Set(snapshot.configuration);
|
|
1259
|
+
const inside = (node) => {
|
|
1260
|
+
const active = node.children.filter((c) => conf.has(c.path));
|
|
1261
|
+
if (!active.length) return undefined;
|
|
1262
|
+
if (node.type === "parallel") return Object.fromEntries(active.map((c) => [c.key, inside(c) ?? {}]));
|
|
1263
|
+
const inner = inside(active[0]);
|
|
1264
|
+
return inner === undefined ? active[0].key : { [active[0].key]: inner };
|
|
1265
|
+
};
|
|
1266
|
+
return inside(machine.root) ?? null;
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
/** Is state `path` ("work.a") active? */
|
|
1270
|
+
export const matches = (snapshot, path) => snapshot.configuration.includes(path);
|
|
1271
|
+
|
|
1272
|
+
// ── saved event-sequence tests, on virtual time ──────────────────────────────
|
|
1273
|
+
|
|
1274
|
+
const subset = (want, have) => Object.entries(want).every(([k, v]) => sameJson(v, have?.[k]));
|
|
1275
|
+
|
|
1276
|
+
/**
|
|
1277
|
+
* Run the machine's saved tests: each starts from the initial configuration at time 0, plays its steps (`send` an event,
|
|
1278
|
+
* `advance` virtual time) and compares what it ends in. `[{ name, ok, reasons: [text], configuration, context, emitted, steps }]`.
|
|
1279
|
+
* Nothing waits for real time and nothing outside the machine is touched.
|
|
1280
|
+
*/
|
|
1281
|
+
export function runChartTests(machine, tests = machine.tests, { code } = {}) {
|
|
1282
|
+
return tests.map((test) => {
|
|
1283
|
+
const start = initialSnapshot(machine, 0, { code });
|
|
1284
|
+
if (!start.snapshot) return { name: test.name, ok: false, reasons: [start.error], configuration: [], context: {}, emitted: [], steps: 0 };
|
|
1285
|
+
let snap = start.snapshot;
|
|
1286
|
+
const emitted = start.emitted.map((e) => e.name);
|
|
1287
|
+
let unhandled = 0;
|
|
1288
|
+
let now = 0;
|
|
1289
|
+
for (const step of test.steps) {
|
|
1290
|
+
if ("advance" in step) {
|
|
1291
|
+
now += step.advance;
|
|
1292
|
+
const r = advance(machine, snap, now, { code });
|
|
1293
|
+
snap = r.snapshot;
|
|
1294
|
+
emitted.push(...r.emitted.map((e) => e.name));
|
|
1295
|
+
} else {
|
|
1296
|
+
const r = send(machine, snap, step.send, step.payload ?? null, now, { code });
|
|
1297
|
+
snap = r.snapshot;
|
|
1298
|
+
if (!r.handled) unhandled++;
|
|
1299
|
+
emitted.push(...r.emitted.map((e) => e.name));
|
|
1300
|
+
if (r.error) return { name: test.name, ok: false, reasons: [r.error], configuration: activeLeaves(machine, snap), context: snap.context, emitted, steps: test.steps.length };
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
const configuration = activeLeaves(machine, snap);
|
|
1304
|
+
const reasons = [];
|
|
1305
|
+
const want = test.expect ?? {};
|
|
1306
|
+
if (want.configuration && !sameJson([...want.configuration].sort(), [...configuration].sort())) reasons.push(`configuration is ${configuration.join(", ") || "empty"}, expected ${want.configuration.join(", ") || "empty"}`);
|
|
1307
|
+
if (want.context && !subset(want.context, snap.context)) reasons.push(`context is ${JSON.stringify(snap.context)}, expected it to have ${JSON.stringify(want.context)}`);
|
|
1308
|
+
if (want.emitted && !sameJson(want.emitted, emitted)) reasons.push(`emitted ${emitted.join(", ") || "nothing"}, expected ${want.emitted.join(", ") || "nothing"}`);
|
|
1309
|
+
if ("output" in want && !sameJson(want.output, snap.output)) reasons.push(`output is ${snap.output === undefined ? "nothing" : JSON.stringify(snap.output)}, expected ${JSON.stringify(want.output)}`);
|
|
1310
|
+
if (want.actors) {
|
|
1311
|
+
const have = actorsOf(machine, snap);
|
|
1312
|
+
for (const [id, leavesWanted] of Object.entries(want.actors)) {
|
|
1313
|
+
if (!have[id]) reasons.push(`actor ${id} is not running, expected ${leavesWanted.join(", ") || "empty"}`);
|
|
1314
|
+
else if (!sameJson([...leavesWanted].sort(), [...have[id].configuration].sort())) reasons.push(`actor ${id} is in ${have[id].configuration.join(", ") || "empty"}, expected ${leavesWanted.join(", ") || "empty"}`);
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
return { name: test.name, ok: reasons.length === 0, reasons, configuration, context: snap.context, emitted, steps: test.steps.length, ...(unhandled ? { ignoredEvents: unhandled } : {}) };
|
|
1318
|
+
});
|
|
1319
|
+
}
|
|
1320
|
+
|
|
1321
|
+
// ── in words (the inspector, the Markdown format, agents) ───────────────────
|
|
1322
|
+
|
|
1323
|
+
/** A guard in words: "event.amount gt context.limit and in #b.ready". */
|
|
1324
|
+
export const guardText = (guard) =>
|
|
1325
|
+
(guard ?? [])
|
|
1326
|
+
.map((c) => ("in" in c ? `in ${c.in}` : "code" in c ? `code ${JSON.stringify(c.code)}` : `${c.path || "(value)"} ${c.op}${c.startPath !== undefined ? ` ${c.startPath}` : c.value !== undefined ? ` ${JSON.stringify(c.value)}` : ""}`))
|
|
1327
|
+
.join(" and ");
|
|
1328
|
+
|
|
1329
|
+
/** An action in words: "emit started", "assign count", "raise NEXT". */
|
|
1330
|
+
export const actionText = (a) => (a.emit !== undefined ? `emit ${a.emit}` : a.raise !== undefined ? `raise ${a.raise}` : `assign ${Object.keys(a.assign ?? {}).join(", ")}`);
|
|
1331
|
+
|
|
1332
|
+
/** Can a person or an agent send this transition's event by hand (not a delay, an eventless or a done transition, nor the wildcard)? */
|
|
1333
|
+
export const sendable = (t) => t.event !== null && t.delay === undefined && t.event !== "*" && !t.event.startsWith("done.");
|
|
1334
|
+
|
|
1335
|
+
/** A compiled transition in words: `on GO → yellow if event.x exists / emit a, assign n`. */
|
|
1336
|
+
export function transitionText(t) {
|
|
1337
|
+
const when = t.event === null ? "always" : t.delay !== undefined ? `after ${t.delay} ms` : t.event === "*" ? "on any other event" : `on ${t.event}`;
|
|
1338
|
+
const target = t.targets.length ? ` → ${t.targets.join(", ")}` : "";
|
|
1339
|
+
const guard = t.guard.length ? ` if ${guardText(t.guard)}` : "";
|
|
1340
|
+
const actions = t.actions.length ? ` / ${t.actions.map(actionText).join(", ")}` : "";
|
|
1341
|
+
return `${when}${target}${guard}${actions}`;
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
/** Does the canvas doc have a statechart with saved tests? */
|
|
1345
|
+
export const hasChartTests = (doc) => (doc?.panes ?? []).some((p) => p?.type === "statechart" && Array.isArray(p.chart?.tests) && p.chart.tests.length > 0);
|
|
1346
|
+
|
|
1347
|
+
/** A saved chart test's identity: its pane and position. Names repeat (two panes called "light", two tests called "t"); this doesn't. */
|
|
1348
|
+
export const chartTestKey = (paneId, index) => `${paneId}#${index}`;
|
|
1349
|
+
|
|
1350
|
+
/**
|
|
1351
|
+
* The saved tests of every statechart pane in `doc`, run on virtual time, as test results (`mallory test`): one per saved
|
|
1352
|
+
* test, named "<pane>: <test>" (`only`: those names, or keys: chartTestKey). Each result carries its `key` and `pane`. A chart that can't run is one failing result that says why.
|
|
1353
|
+
*/
|
|
1354
|
+
export function docChartTests(doc, only = []) {
|
|
1355
|
+
const results = [];
|
|
1356
|
+
for (const pane of doc?.panes ?? []) {
|
|
1357
|
+
if (pane?.type !== "statechart" || !Array.isArray(pane.chart?.tests) || !pane.chart.tests.length) continue;
|
|
1358
|
+
const label = pane.name || pane.id;
|
|
1359
|
+
const compiled = compileChart(pane.chart);
|
|
1360
|
+
const { machine } = compiled;
|
|
1361
|
+
// a chart whose guards run JavaScript is run by the page's sandbox (the pane's Run tests), not here
|
|
1362
|
+
const ok = compiled.ok && !machine.usesCode;
|
|
1363
|
+
const problems = compiled.ok && machine.usesCode ? ["its guards run JavaScript, which only the open canvas's sandbox runs: use the pane's Run tests"] : compiled.problems;
|
|
1364
|
+
const found = ok ? runChartTests(machine) : [];
|
|
1365
|
+
const list = ok ? found.map((r, index) => ({ key: chartTestKey(pane.id, index), pane: pane.id, name: `${label}: ${r.name}`, pass: r.ok, checks: r.reasons.length ? r.reasons.map((message) => ({ pane: label, pass: false, message })) : [{ pane: label, pass: true, message: "as expected" }] })) : [{ key: chartTestKey(pane.id, "run"), pane: pane.id, name: `${label}: the chart can't run`, pass: false, checks: [], error: problems.join("; ") }];
|
|
1366
|
+
for (const r of list) if (!only.length || only.includes(r.name) || only.includes(r.key)) results.push({ ...r, ms: 0, chart: true });
|
|
1367
|
+
}
|
|
1368
|
+
return results;
|
|
1369
|
+
}
|