@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,1557 @@
|
|
|
1
|
+
// Branching narratives from linked local passages: `narrative` in pane code.
|
|
2
|
+
//
|
|
3
|
+
// One story is one value: text with `@passage Name` header lines, each followed by
|
|
4
|
+
// that passage's text. Its explicit links are [[text]], [[text->target]] and
|
|
5
|
+
// [[target<-text]] (the Twine/Harlowe-like forms; nothing else is a link). The
|
|
6
|
+
// navigation graph is *derived* from the text here, never wires between panes, so a
|
|
7
|
+
// story that loops back to a hub is not a dataflow cycle and the dataflow graph
|
|
8
|
+
// stays about data.
|
|
9
|
+
//
|
|
10
|
+
// Pure and self-contained (no imports, no network, storage or eval): the Worker loads
|
|
11
|
+
// this file as the virtual module "mallory:narrative", the page and the tests import it.
|
|
12
|
+
//
|
|
13
|
+
// Safety: author text is never HTML. Every renderer here escapes the text first and
|
|
14
|
+
// then adds a small fixed set of tags of its own (paragraphs, <em>, <strong>, <code>,
|
|
15
|
+
// and the links and buttons it makes), so a <script>, an onerror= or a javascript:
|
|
16
|
+
// link in a passage is shown as text. Twine dialects (Harlowe, SugarCube, Chapbook
|
|
17
|
+
// macros, variables, `[[a|b]]` pipe links, setter links, images) are NOT supported;
|
|
18
|
+
// they are reported where they are noticed, never silently half-run.
|
|
19
|
+
|
|
20
|
+
/** What one story may hold. A story over a limit is refused with a problem, not truncated quietly. */
|
|
21
|
+
export const LIMITS = Object.freeze({ passages: 2000, name: 120, passageChars: 100_000, storyChars: 2_000_000, choices: 100, assets: 30, assetChars: 1_500_000, exprChars: 500, vars: 100, valueChars: 1000, depth: 20, states: 1000, exportChars: 8_000_000 });
|
|
22
|
+
|
|
23
|
+
/** The header that starts an image the story carries (a raster data URI on the line after it). */
|
|
24
|
+
export const ASSET_HEADER = "@asset";
|
|
25
|
+
const ASSET_URI = /^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/;
|
|
26
|
+
const HEADER_LINE = /^@(passage|asset)(?:[ \t]+(.*))?$/;
|
|
27
|
+
|
|
28
|
+
/** The header that starts a passage. Twee uses `:: Name`; this is deliberately different (no Twee compatibility is claimed). */
|
|
29
|
+
export const HEADER = "@passage";
|
|
30
|
+
|
|
31
|
+
const CONTROL = /[\u0000-\u001f\u007f]/;
|
|
32
|
+
const nfc = (s) => String(s).normalize("NFC");
|
|
33
|
+
const ESC = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
|
|
34
|
+
/** Escape text for HTML (text content and quoted attribute values). */
|
|
35
|
+
export const escapeHtml = (text) => String(text ?? "").replace(/[&<>"']/g, (c) => ESC[c]);
|
|
36
|
+
|
|
37
|
+
const problem = (severity, code, message, extra = {}) => ({ severity, code, message, ...extra });
|
|
38
|
+
|
|
39
|
+
/** Why a passage name is refused, or null. A name is addressed by links, so it can't hold what splits a link. */
|
|
40
|
+
export function nameProblem(name) {
|
|
41
|
+
if (typeof name !== "string" || !name.trim()) return "a passage needs a name";
|
|
42
|
+
if (name !== name.trim()) return "a passage name can't start or end with a space";
|
|
43
|
+
if (name.length > LIMITS.name) return `a passage name is at most ${LIMITS.name} characters`;
|
|
44
|
+
if (CONTROL.test(name)) return "a passage name can't hold control characters";
|
|
45
|
+
for (const bad of ["[[", "]]", "->", "<-", "|"]) if (name.includes(bad)) return `a passage name can't contain "${bad}" (it would split a link)`;
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// ── parsing ────────────────────────────────────────────────────────────────
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Split a story into passages. Strict: a header with no name or an unusable one, a
|
|
53
|
+
* name used twice, text before the first header and a story over a limit are errors.
|
|
54
|
+
* @returns {{ passages: Array<{ name: string, text: string, line: number, bodyLine: number }>, problems: object[] }}
|
|
55
|
+
*/
|
|
56
|
+
export function parseStory(source) {
|
|
57
|
+
const problems = [];
|
|
58
|
+
if (typeof source !== "string") return { passages: [], assets: [], problems: [problem("error", "not-text", "A story is text with @passage headers.")] };
|
|
59
|
+
if (source.length > LIMITS.storyChars) return { passages: [], assets: [], problems: [problem("error", "story-too-large", `The story is over ${LIMITS.storyChars} characters.`)] };
|
|
60
|
+
const lines = source.replace(/^\ufeff/, "").replace(/\r\n?/g, "\n").split("\n");
|
|
61
|
+
const passages = [];
|
|
62
|
+
const assets = [];
|
|
63
|
+
const seen = new Map();
|
|
64
|
+
const seenAssets = new Map();
|
|
65
|
+
let current = null;
|
|
66
|
+
let stray = 0;
|
|
67
|
+
let overflow = false;
|
|
68
|
+
const close = () => {
|
|
69
|
+
if (!current) return;
|
|
70
|
+
if (current.asset) {
|
|
71
|
+
const uri = current.body.join("").replace(/\s+/g, "");
|
|
72
|
+
if (current.keep) {
|
|
73
|
+
if (uri.length > LIMITS.assetChars) problems.push(problem("error", "bad-asset", `Asset "${current.name}" is over ${LIMITS.assetChars} characters.`, { line: current.line }));
|
|
74
|
+
else if (!ASSET_URI.test(uri)) problems.push(problem("error", "bad-asset", `Line ${current.line}: asset "${current.name}" must be a PNG, JPEG, GIF or WebP data URI ("data:image/png;base64,…") on the line after the header.`, { line: current.line }));
|
|
75
|
+
else assets.push({ name: current.name, uri, mime: /^data:([^;]+);/.exec(uri)[1], line: current.line });
|
|
76
|
+
}
|
|
77
|
+
current = null;
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
current.text = current.body.join("\n").replace(/^\n+|\s+$/g, "");
|
|
81
|
+
if (current.text.length > LIMITS.passageChars) {
|
|
82
|
+
problems.push(problem("error", "passage-too-large", `Passage "${current.name}" is over ${LIMITS.passageChars} characters.`, { passage: current.name, line: current.line }));
|
|
83
|
+
current.text = current.text.slice(0, LIMITS.passageChars);
|
|
84
|
+
}
|
|
85
|
+
delete current.body;
|
|
86
|
+
delete current.asset;
|
|
87
|
+
if (current.keep) passages.push(current);
|
|
88
|
+
current = null;
|
|
89
|
+
};
|
|
90
|
+
lines.forEach((line, i) => {
|
|
91
|
+
const m = HEADER_LINE.exec(line);
|
|
92
|
+
if (!m) {
|
|
93
|
+
if (current) current.body.push(line);
|
|
94
|
+
else if (line.trim()) stray++;
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
close();
|
|
98
|
+
const asset = m[1] === "asset";
|
|
99
|
+
const name = nfc((m[2] ?? "").trim());
|
|
100
|
+
current = { name, text: "", line: i + 1, bodyLine: i + 2, body: [], keep: false, asset };
|
|
101
|
+
const bad = nameProblem(name);
|
|
102
|
+
if (bad) problems.push(problem("error", name ? "bad-name" : "empty-name", `Line ${i + 1}: ${bad}.`, { line: i + 1 }));
|
|
103
|
+
else if (asset) {
|
|
104
|
+
if (seenAssets.has(name)) problems.push(problem("error", "duplicate-asset", `Line ${i + 1}: asset "${name}" is already defined on line ${seenAssets.get(name)}; the second is ignored.`, { line: i + 1 }));
|
|
105
|
+
else if (assets.length >= LIMITS.assets) problems.push(problem("error", "too-many-assets", `A story has at most ${LIMITS.assets} assets; the rest are ignored.`, { line: i + 1 }));
|
|
106
|
+
else (seenAssets.set(name, i + 1), (current.keep = true));
|
|
107
|
+
} else if (seen.has(name)) problems.push(problem("error", "duplicate-passage", `Line ${i + 1}: passage "${name}" is already defined on line ${seen.get(name)}; the second is ignored.`, { passage: name, line: i + 1 }));
|
|
108
|
+
else if (passages.length >= LIMITS.passages) {
|
|
109
|
+
if (!overflow) problems.push(problem("error", "too-many-passages", `A story has at most ${LIMITS.passages} passages; the rest are ignored.`, { line: i + 1 }));
|
|
110
|
+
overflow = true;
|
|
111
|
+
} else {
|
|
112
|
+
seen.set(name, i + 1);
|
|
113
|
+
current.keep = true;
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
close();
|
|
117
|
+
if (stray) problems.push(problem("error", "text-before-passage", `${stray} line${stray === 1 ? "" : "s"} of text before the first "${HEADER} Name" header ${stray === 1 ? "is" : "are"} ignored.`, { line: 1 }));
|
|
118
|
+
return { passages, assets, problems };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* The explicit links in one passage's text: [[text]], [[text->target]], [[target<-text]].
|
|
123
|
+
* `->` splits at its last occurrence and `<-` at its first (as Harlowe does), a link with
|
|
124
|
+
* both is ambiguous and refused, `\[[` is the literal text. A link is on one line.
|
|
125
|
+
* @returns {{ links: Array<{ label: string, target: string, form: "simple"|"arrow"|"back", start: number, end: number, line: number }>, problems: object[] }}
|
|
126
|
+
*/
|
|
127
|
+
export function parseLinks(text) {
|
|
128
|
+
const links = [];
|
|
129
|
+
const problems = [];
|
|
130
|
+
const lineAt = (index) => {
|
|
131
|
+
let n = 1;
|
|
132
|
+
for (let i = text.indexOf("\n"); i >= 0 && i < index; i = text.indexOf("\n", i + 1)) n++;
|
|
133
|
+
return n;
|
|
134
|
+
};
|
|
135
|
+
let i = 0;
|
|
136
|
+
while (i < text.length) {
|
|
137
|
+
const open = text.indexOf("[[", i);
|
|
138
|
+
if (open < 0) break;
|
|
139
|
+
if (open > 0 && text[open - 1] === "\\") {
|
|
140
|
+
i = open + 2;
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
const end = text.indexOf("]]", open + 2);
|
|
144
|
+
const newline = text.indexOf("\n", open + 2);
|
|
145
|
+
const inner = end < 0 ? "" : text.slice(open + 2, end);
|
|
146
|
+
if (end < 0 || (newline >= 0 && newline < end) || inner.includes("[[")) {
|
|
147
|
+
problems.push(problem("error", "unclosed-link", `Line ${lineAt(open)}: "[[" has no closing "]]" on the same line.`, { line: lineAt(open) }));
|
|
148
|
+
i = open + 2;
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
i = end + 2;
|
|
152
|
+
const line = lineAt(open);
|
|
153
|
+
const arrow = inner.lastIndexOf("->");
|
|
154
|
+
const back = inner.indexOf("<-");
|
|
155
|
+
if (arrow >= 0 && back >= 0) {
|
|
156
|
+
problems.push(problem("error", "ambiguous-link", `Line ${line}: [[${inner}]] has both "->" and "<-"; use one.`, { line }));
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
let form = "simple";
|
|
160
|
+
let label = inner;
|
|
161
|
+
let target = inner;
|
|
162
|
+
if (arrow >= 0) [form, label, target] = ["arrow", inner.slice(0, arrow), inner.slice(arrow + 2)];
|
|
163
|
+
else if (back >= 0) [form, target, label] = ["back", inner.slice(0, back), inner.slice(back + 2)];
|
|
164
|
+
if (form === "simple" && inner.includes("|")) {
|
|
165
|
+
problems.push(problem("error", "unsupported-syntax", `Line ${line}: Twine's [[text|target]] isn't supported; write [[text->target]].`, { line }));
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
label = nfc(label.trim());
|
|
169
|
+
target = nfc(target.trim());
|
|
170
|
+
if (!target) {
|
|
171
|
+
problems.push(problem("error", "empty-target", `Line ${line}: [[${inner}]] names no passage.`, { line }));
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
const bad = nameProblem(target);
|
|
175
|
+
if (bad) {
|
|
176
|
+
problems.push(problem("error", "bad-target", `Line ${line}: [[${inner}]]: ${bad}.`, { line }));
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
if (!label) {
|
|
180
|
+
label = target;
|
|
181
|
+
problems.push(problem("warning", "empty-label", `Line ${line}: [[${inner}]] has no link text; "${target}" is shown.`, { line }));
|
|
182
|
+
}
|
|
183
|
+
if (inner.includes("][")) problems.push(problem("warning", "unsupported-syntax", `Line ${line}: setter links ([[a][code]]) aren't supported; this links to "${target}".`, { line }));
|
|
184
|
+
links.push({ label, target, form, start: open, end: i, line });
|
|
185
|
+
}
|
|
186
|
+
return { links, problems };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// ── variables and conditionals ─────────────────────────────────────────────
|
|
190
|
+
//
|
|
191
|
+
// A small, closed macro set in the SugarCube spelling: <<set $x to 1>>, <<if $x > 1>>…
|
|
192
|
+
// <<elseif …>>…<<else>>…<</if>> and <<print $x + 1>>. Nothing is evaluated as JavaScript:
|
|
193
|
+
// expressions are read by the parser below (numbers, strings, true/false, $variables,
|
|
194
|
+
// arithmetic, comparisons, and/or/not) and cannot call anything or reach anything.
|
|
195
|
+
// Variables are not stored: they are rebuilt by running the passages along the reader's
|
|
196
|
+
// path, so the path stays the only reader state. A variable nobody set reads as 0.
|
|
197
|
+
|
|
198
|
+
const SUPPORTED_MACROS = new Set(["set", "if", "elseif", "else", "endif", "print"]);
|
|
199
|
+
const MACRO_TAG = /<<(\/?)([A-Za-z]+)((?:(?!>>)[^\n])*)>>/g;
|
|
200
|
+
const WORDS = { and: "&&", or: "||", not: "!", is: "==", eq: "==", isnot: "!=", neq: "!=", gt: ">", gte: ">=", lt: "<", lte: "<=" };
|
|
201
|
+
|
|
202
|
+
const lineIn = (text, index) => {
|
|
203
|
+
let n = 1;
|
|
204
|
+
for (let i = text.indexOf("\n"); i >= 0 && i < index; i = text.indexOf("\n", i + 1)) n++;
|
|
205
|
+
return n;
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
function tokenize(src) {
|
|
209
|
+
if (src.length > LIMITS.exprChars) throw new Error(`an expression is at most ${LIMITS.exprChars} characters`);
|
|
210
|
+
const tokens = [];
|
|
211
|
+
const re = /\s*(?:(\d+(?:\.\d+)?)|"((?:[^"\\\n]|\\.)*)"|'((?:[^'\\\n]|\\.)*)'|\$([A-Za-z_][A-Za-z0-9_]*)|([A-Za-z]+)|(===|!==|==|!=|<=|>=|&&|\|\||[+\-*/%<>!()]))/y;
|
|
212
|
+
let at = 0;
|
|
213
|
+
while (at < src.length) {
|
|
214
|
+
if (/^\s*$/.test(src.slice(at))) break;
|
|
215
|
+
re.lastIndex = at;
|
|
216
|
+
const m = re.exec(src);
|
|
217
|
+
if (!m) throw new Error(`can't read "${src.slice(at).trim().slice(0, 20)}"`);
|
|
218
|
+
at = re.lastIndex;
|
|
219
|
+
const unescape = (s) => s.replace(/\\(.)/g, (_, c) => (c === "n" ? "\n" : c));
|
|
220
|
+
if (m[1] !== undefined) tokens.push({ k: "num", v: Number(m[1]) });
|
|
221
|
+
else if (m[2] !== undefined) tokens.push({ k: "str", v: unescape(m[2]) });
|
|
222
|
+
else if (m[3] !== undefined) tokens.push({ k: "str", v: unescape(m[3]) });
|
|
223
|
+
else if (m[4] !== undefined) tokens.push({ k: "var", v: m[4] });
|
|
224
|
+
else if (m[5] !== undefined) {
|
|
225
|
+
const w = m[5].toLowerCase();
|
|
226
|
+
if (w === "true" || w === "false") tokens.push({ k: "bool", v: w === "true" });
|
|
227
|
+
else if (Object.hasOwn(WORDS, w)) tokens.push({ k: "op", v: WORDS[w] });
|
|
228
|
+
else throw new Error(`"${m[5]}" isn't something an expression can use (variables start with $)`);
|
|
229
|
+
} else tokens.push({ k: "op", v: m[6] === "===" ? "==" : m[6] === "!==" ? "!=" : m[6] });
|
|
230
|
+
}
|
|
231
|
+
return tokens;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Parse an expression into a tree; throws an Error that says what is wrong. */
|
|
235
|
+
function parseExpr(src) {
|
|
236
|
+
const t = tokenize(src);
|
|
237
|
+
let i = 0;
|
|
238
|
+
const peek = () => t[i];
|
|
239
|
+
const isOp = (...ops) => t[i]?.k === "op" && ops.includes(t[i].v);
|
|
240
|
+
const level = (next, ops) => () => {
|
|
241
|
+
let left = next();
|
|
242
|
+
while (isOp(...ops)) {
|
|
243
|
+
const op = t[i++].v;
|
|
244
|
+
left = { n: "bin", op, l: left, r: next() };
|
|
245
|
+
}
|
|
246
|
+
return left;
|
|
247
|
+
};
|
|
248
|
+
const primary = () => {
|
|
249
|
+
const x = t[i++];
|
|
250
|
+
if (!x) throw new Error("the expression ends too early");
|
|
251
|
+
if (x.k === "num" || x.k === "str" || x.k === "bool") return { n: "lit", v: x.v };
|
|
252
|
+
if (x.k === "var") return { n: "var", name: x.v };
|
|
253
|
+
if (x.k === "op" && x.v === "(") {
|
|
254
|
+
const e = or();
|
|
255
|
+
if (!isOp(")")) throw new Error('missing ")"');
|
|
256
|
+
i++;
|
|
257
|
+
return e;
|
|
258
|
+
}
|
|
259
|
+
throw new Error(`unexpected "${x.v}"`);
|
|
260
|
+
};
|
|
261
|
+
const unary = () => {
|
|
262
|
+
if (isOp("!", "-")) {
|
|
263
|
+
const op = t[i++].v;
|
|
264
|
+
return { n: "un", op, e: unary() };
|
|
265
|
+
}
|
|
266
|
+
return primary();
|
|
267
|
+
};
|
|
268
|
+
const mul = level(unary, ["*", "/", "%"]);
|
|
269
|
+
const add = level(mul, ["+", "-"]);
|
|
270
|
+
const rel = level(add, ["<", ">", "<=", ">="]);
|
|
271
|
+
const eq = level(rel, ["==", "!="]);
|
|
272
|
+
const and = level(eq, ["&&"]);
|
|
273
|
+
const or = level(and, ["||"]);
|
|
274
|
+
const tree = or();
|
|
275
|
+
if (peek()) throw new Error(`unexpected "${peek().v}"`);
|
|
276
|
+
return tree;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const show = (v) => (typeof v === "string" ? v : String(v));
|
|
280
|
+
|
|
281
|
+
function evalExpr(node, vars, depth = 0) {
|
|
282
|
+
if (depth > LIMITS.depth * 5) throw new Error("the expression is nested too deeply");
|
|
283
|
+
const go = (n) => evalExpr(n, vars, depth + 1);
|
|
284
|
+
switch (node.n) {
|
|
285
|
+
case "lit":
|
|
286
|
+
return node.v;
|
|
287
|
+
case "var":
|
|
288
|
+
return vars.has(node.name) ? vars.get(node.name) : 0;
|
|
289
|
+
case "un": {
|
|
290
|
+
const v = go(node.e);
|
|
291
|
+
if (node.op === "!") return !v;
|
|
292
|
+
if (typeof v !== "number") throw new Error("only a number can be negated");
|
|
293
|
+
return -v;
|
|
294
|
+
}
|
|
295
|
+
case "bin": {
|
|
296
|
+
if (node.op === "&&") return Boolean(go(node.l)) && Boolean(go(node.r));
|
|
297
|
+
if (node.op === "||") return Boolean(go(node.l)) || Boolean(go(node.r));
|
|
298
|
+
const a = go(node.l);
|
|
299
|
+
const b = go(node.r);
|
|
300
|
+
switch (node.op) {
|
|
301
|
+
case "==":
|
|
302
|
+
return a === b;
|
|
303
|
+
case "!=":
|
|
304
|
+
return a !== b;
|
|
305
|
+
case "+":
|
|
306
|
+
if (typeof a === "number" && typeof b === "number") return finite(a + b);
|
|
307
|
+
if (typeof a === "string" || typeof b === "string") return limitText(show(a) + show(b));
|
|
308
|
+
throw new Error("can't add these values");
|
|
309
|
+
case "<":
|
|
310
|
+
case ">":
|
|
311
|
+
case "<=":
|
|
312
|
+
case ">=":
|
|
313
|
+
if (!((typeof a === "number" && typeof b === "number") || (typeof a === "string" && typeof b === "string"))) throw new Error(`"${node.op}" compares two numbers or two texts`);
|
|
314
|
+
return node.op === "<" ? a < b : node.op === ">" ? a > b : node.op === "<=" ? a <= b : a >= b;
|
|
315
|
+
default: {
|
|
316
|
+
if (typeof a !== "number" || typeof b !== "number") throw new Error(`"${node.op}" needs two numbers`);
|
|
317
|
+
if ((node.op === "/" || node.op === "%") && b === 0) throw new Error("can't divide by zero");
|
|
318
|
+
return finite(node.op === "-" ? a - b : node.op === "*" ? a * b : node.op === "/" ? a / b : a % b);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
throw new Error("unreadable expression");
|
|
324
|
+
}
|
|
325
|
+
const finite = (n) => {
|
|
326
|
+
if (!Number.isFinite(n)) throw new Error("the number is too large");
|
|
327
|
+
return n;
|
|
328
|
+
};
|
|
329
|
+
const limitText = (s) => {
|
|
330
|
+
if (s.length > LIMITS.valueChars) throw new Error(`a value is at most ${LIMITS.valueChars} characters`);
|
|
331
|
+
return s;
|
|
332
|
+
};
|
|
333
|
+
|
|
334
|
+
/** Split `$a to 1; $b to "x;y"` at the semicolons outside quotes. */
|
|
335
|
+
function splitStatements(src) {
|
|
336
|
+
const out = [];
|
|
337
|
+
let quote = null;
|
|
338
|
+
let from = 0;
|
|
339
|
+
for (let i = 0; i < src.length; i++) {
|
|
340
|
+
const c = src[i];
|
|
341
|
+
if (quote) {
|
|
342
|
+
if (c === "\\") i++;
|
|
343
|
+
else if (c === quote) quote = null;
|
|
344
|
+
} else if (c === '"' || c === "'") quote = c;
|
|
345
|
+
else if (c === ";") (out.push(src.slice(from, i)), (from = i + 1));
|
|
346
|
+
}
|
|
347
|
+
out.push(src.slice(from));
|
|
348
|
+
return out.filter((s) => s.trim());
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Read a passage's macros into a tree. `errors` says what is wrong (`{ message, line }`),
|
|
353
|
+
* `unsupported` is the text outside the supported macros (other macros stay text), `reads`
|
|
354
|
+
* and `writes` are the variable names used.
|
|
355
|
+
*/
|
|
356
|
+
function parseMacros(text) {
|
|
357
|
+
const errors = [];
|
|
358
|
+
const reads = new Set();
|
|
359
|
+
const writes = new Set();
|
|
360
|
+
const root = [];
|
|
361
|
+
const stack = [{ body: root }];
|
|
362
|
+
const top = () => stack[stack.length - 1];
|
|
363
|
+
let at = 0;
|
|
364
|
+
let plain = "";
|
|
365
|
+
const pushText = (s) => {
|
|
366
|
+
if (!s) return;
|
|
367
|
+
const body = top().body;
|
|
368
|
+
if (body.length && body[body.length - 1].t === "text") body[body.length - 1].s += s;
|
|
369
|
+
else body.push({ t: "text", s });
|
|
370
|
+
};
|
|
371
|
+
const expr = (src, line) => {
|
|
372
|
+
try {
|
|
373
|
+
const tree = parseExpr(src);
|
|
374
|
+
const walk = (n) => (n.n === "var" ? reads.add(n.name) : n.n === "bin" ? (walk(n.l), walk(n.r)) : n.n === "un" ? walk(n.e) : null);
|
|
375
|
+
walk(tree);
|
|
376
|
+
return tree;
|
|
377
|
+
} catch (e) {
|
|
378
|
+
errors.push({ message: `Line ${line}: ${e.message}.`, line });
|
|
379
|
+
return null;
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
MACRO_TAG.lastIndex = 0;
|
|
383
|
+
for (let m; (m = MACRO_TAG.exec(text)); ) {
|
|
384
|
+
const closing = m[1] === "/";
|
|
385
|
+
const name = m[2].toLowerCase();
|
|
386
|
+
const known = SUPPORTED_MACROS.has(name) || (closing && name === "if");
|
|
387
|
+
if (!known || (closing && name !== "if")) continue; // another macro: left as text
|
|
388
|
+
const line = lineIn(text, m.index);
|
|
389
|
+
const args = m[3].trim();
|
|
390
|
+
const block = name !== "print";
|
|
391
|
+
// A tag alone on its line takes the line with it (no empty paragraph left behind).
|
|
392
|
+
let before = text.slice(at, m.index);
|
|
393
|
+
let next = m.index + m[0].length;
|
|
394
|
+
if (block) {
|
|
395
|
+
const lineStart = text.lastIndexOf("\n", m.index - 1) + 1;
|
|
396
|
+
const alone = /^[ \t]*$/.test(text.slice(lineStart, m.index)) && /^[ \t]*(\n|$)/.test(text.slice(next));
|
|
397
|
+
if (alone) {
|
|
398
|
+
before = before.replace(/[ \t]*$/, "");
|
|
399
|
+
next += /^[ \t]*\n?/.exec(text.slice(next))[0].length;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
pushText(before);
|
|
403
|
+
plain += before;
|
|
404
|
+
at = next;
|
|
405
|
+
MACRO_TAG.lastIndex = next;
|
|
406
|
+
if (name === "print") {
|
|
407
|
+
const e = expr(args, line);
|
|
408
|
+
if (e) top().body.push({ t: "print", e, line });
|
|
409
|
+
} else if (name === "set") {
|
|
410
|
+
const stmts = [];
|
|
411
|
+
for (const s of splitStatements(args)) {
|
|
412
|
+
const sm = /^\s*\$([A-Za-z_][A-Za-z0-9_]*)\s*(to|\+=|-=|\*=|\/=|=)\s*([^]+)$/.exec(s);
|
|
413
|
+
if (!sm) {
|
|
414
|
+
errors.push({ message: `Line ${line}: "<<set ${s.trim()}>>" should look like <<set $name to value>>.`, line });
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
417
|
+
const e = expr(sm[3], line);
|
|
418
|
+
writes.add(sm[1]);
|
|
419
|
+
if (sm[2] !== "to" && sm[2] !== "=") reads.add(sm[1]);
|
|
420
|
+
if (e) stmts.push({ name: sm[1], op: sm[2] === "to" ? "=" : sm[2], e });
|
|
421
|
+
}
|
|
422
|
+
top().body.push({ t: "set", stmts, line });
|
|
423
|
+
} else if (name === "if" && !closing) {
|
|
424
|
+
if (stack.length > LIMITS.depth) {
|
|
425
|
+
errors.push({ message: `Line ${line}: <<if>> blocks are nested more than ${LIMITS.depth} deep.`, line });
|
|
426
|
+
continue;
|
|
427
|
+
}
|
|
428
|
+
const node = { t: "if", branches: [{ cond: expr(args, line), body: [] }], line };
|
|
429
|
+
top().body.push(node);
|
|
430
|
+
stack.push({ node, body: node.branches[0].body });
|
|
431
|
+
} else if (name === "elseif" || name === "else") {
|
|
432
|
+
const t = top();
|
|
433
|
+
if (!t.node || t.node.branches.some((b) => b.cond === "else")) {
|
|
434
|
+
errors.push({ message: `Line ${line}: <<${name}>> without a matching <<if>>.`, line });
|
|
435
|
+
continue;
|
|
436
|
+
}
|
|
437
|
+
const branch = { cond: name === "else" ? "else" : expr(args, line), body: [] };
|
|
438
|
+
t.node.branches.push(branch);
|
|
439
|
+
t.body = branch.body;
|
|
440
|
+
} else {
|
|
441
|
+
// <</if>> or <<endif>>
|
|
442
|
+
if (!top().node) errors.push({ message: `Line ${line}: <<${closing ? "/if" : name}>> without a matching <<if>>.`, line });
|
|
443
|
+
else stack.pop();
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
const rest = text.slice(at);
|
|
447
|
+
pushText(rest);
|
|
448
|
+
plain += rest;
|
|
449
|
+
for (const s of stack.slice(1)) errors.push({ message: `Line ${s.node.line}: <<if>> is never closed with <</if>>.`, line: s.node.line });
|
|
450
|
+
return { nodes: root, errors, reads, writes, plain, has: root.some((n) => n.t !== "text") };
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
const macroCache = new WeakMap();
|
|
454
|
+
/** The macros of a passage object, read once. */
|
|
455
|
+
function macrosOf(passage) {
|
|
456
|
+
let m = macroCache.get(passage);
|
|
457
|
+
if (!m || m.source !== passage.text) {
|
|
458
|
+
m = parseMacros(passage.text);
|
|
459
|
+
m.source = passage.text;
|
|
460
|
+
macroCache.set(passage, m);
|
|
461
|
+
}
|
|
462
|
+
return m;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/** Run a passage's macros over variables. Returns the text that is shown, the variables after it and any run-time errors. */
|
|
466
|
+
function runMacros(parsed, vars) {
|
|
467
|
+
const map = new Map(Object.entries(vars));
|
|
468
|
+
const errors = [];
|
|
469
|
+
let out = "";
|
|
470
|
+
const run = (nodes) => {
|
|
471
|
+
for (const n of nodes) {
|
|
472
|
+
if (n.t === "text") out += n.s;
|
|
473
|
+
else if (n.t === "print") {
|
|
474
|
+
try {
|
|
475
|
+
out += show(evalExpr(n.e, map)).replace(/\[\[/g, "\\[[");
|
|
476
|
+
} catch (e) {
|
|
477
|
+
errors.push({ message: `Line ${n.line}: ${e.message}.`, line: n.line });
|
|
478
|
+
}
|
|
479
|
+
} else if (n.t === "set") {
|
|
480
|
+
for (const s of n.stmts) {
|
|
481
|
+
try {
|
|
482
|
+
const rhs = evalExpr(s.e, map);
|
|
483
|
+
const old = map.has(s.name) ? map.get(s.name) : 0;
|
|
484
|
+
let v = rhs;
|
|
485
|
+
if (s.op !== "=") {
|
|
486
|
+
if (typeof old !== "number" || typeof rhs !== "number") {
|
|
487
|
+
if (s.op === "+=" && (typeof old === "string" || typeof rhs === "string")) v = limitText(show(old) + show(rhs));
|
|
488
|
+
else throw new Error(`"${s.op}" needs numbers`);
|
|
489
|
+
} else v = finite(s.op === "+=" ? old + rhs : s.op === "-=" ? old - rhs : s.op === "*=" ? old * rhs : rhs === 0 ? (() => { throw new Error("can't divide by zero"); })() : old / rhs);
|
|
490
|
+
}
|
|
491
|
+
if (!map.has(s.name) && map.size >= LIMITS.vars) throw new Error(`a story has at most ${LIMITS.vars} variables`);
|
|
492
|
+
map.set(s.name, v);
|
|
493
|
+
} catch (e) {
|
|
494
|
+
errors.push({ message: `Line ${n.line}: ${e.message}.`, line: n.line });
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
} else if (n.t === "if") {
|
|
498
|
+
for (const b of n.branches) {
|
|
499
|
+
let yes = b.cond === "else";
|
|
500
|
+
if (!yes && b.cond) {
|
|
501
|
+
try {
|
|
502
|
+
yes = Boolean(evalExpr(b.cond, map));
|
|
503
|
+
} catch (e) {
|
|
504
|
+
errors.push({ message: `Line ${n.line}: ${e.message}.`, line: n.line });
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
if (yes) {
|
|
508
|
+
run(b.body);
|
|
509
|
+
break;
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
};
|
|
515
|
+
run(parsed.nodes);
|
|
516
|
+
return { text: out, vars: Object.fromEntries(map), errors };
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// ── analysis ───────────────────────────────────────────────────────────────
|
|
520
|
+
|
|
521
|
+
const MACRO = /<<|>>|\$\{|\{\{|\(\s*[a-z-]+\s*:/i;
|
|
522
|
+
|
|
523
|
+
/**
|
|
524
|
+
* Parse a story and check its navigation: passages, edges, missing targets,
|
|
525
|
+
* unreachable passages and endings. Missing targets and a missing start passage
|
|
526
|
+
* are errors; unreachable passages and unsupported syntax are warnings.
|
|
527
|
+
* @param {string} source
|
|
528
|
+
* @param {{ start?: string }} [options] start: the passage to begin at (default: the first)
|
|
529
|
+
*/
|
|
530
|
+
export function analyze(source, options = {}) {
|
|
531
|
+
const { passages, assets, problems: all } = parseStory(source);
|
|
532
|
+
const problems = [...all];
|
|
533
|
+
const names = new Map(passages.map((p) => [p.name, p]));
|
|
534
|
+
const assetNames = new Set(assets.map((x) => x.name));
|
|
535
|
+
const edges = [];
|
|
536
|
+
const setAnywhere = new Set();
|
|
537
|
+
const readAt = new Map();
|
|
538
|
+
for (const p of passages) {
|
|
539
|
+
const { links, problems: lp } = parseLinks(p.text);
|
|
540
|
+
p.links = links;
|
|
541
|
+
for (const q of lp) problems.push({ ...q, passage: p.name, line: q.line + p.bodyLine - 1 });
|
|
542
|
+
if (links.length > LIMITS.choices) problems.push(problem("error", "too-many-choices", `Passage "${p.name}" has ${links.length} links; at most ${LIMITS.choices} are read.`, { passage: p.name, line: p.line }));
|
|
543
|
+
for (const l of links.slice(0, LIMITS.choices)) {
|
|
544
|
+
const exists = names.has(l.target);
|
|
545
|
+
edges.push({ from: p.name, to: l.target, label: l.label, line: l.line + p.bodyLine - 1, missing: !exists });
|
|
546
|
+
if (!exists) problems.push(problem("error", "missing-target", `Passage "${p.name}" (line ${l.line + p.bodyLine - 1}) links to "${l.target}", which doesn't exist.${suggest(l.target, names)}`, { passage: p.name, line: l.line + p.bodyLine - 1, target: l.target }));
|
|
547
|
+
}
|
|
548
|
+
const m = macrosOf(p);
|
|
549
|
+
for (const q of m.errors) problems.push(problem("error", "bad-macro", q.message, { passage: p.name, line: q.line + p.bodyLine - 1 }));
|
|
550
|
+
for (const w of m.writes) setAnywhere.add(w);
|
|
551
|
+
for (const r of m.reads) if (!readAt.has(r)) readAt.set(r, p);
|
|
552
|
+
if (MACRO.test(m.plain)) problems.push(problem("warning", "macro-syntax", `Passage "${p.name}" holds macro-like syntax ("<<", "\${", "(name:") that isn't <<set>>, <<if>>, <<elseif>>, <<else>> or <<print>>. It isn't run; only [[links]] and those macros are followed.`, { passage: p.name, line: p.line }));
|
|
553
|
+
for (const im of p.text.matchAll(/!\[[^\]\n]*\]\(([^)\n]+)\)/g)) {
|
|
554
|
+
const ref = nfc(im[1].trim());
|
|
555
|
+
if (!assetNames.has(ref)) problems.push(problem("warning", "missing-asset", `Passage "${p.name}" shows the image "${ref}", which isn't an @asset of the story; it is shown as text.`, { passage: p.name, line: p.bodyLine + lineIn(p.text, im.index) - 1 }));
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
for (const [name, p] of readAt) if (!setAnywhere.has(name)) problems.push(problem("warning", "unset-variable", `Passage "${p.name}" reads $${name}, which no passage sets; it reads as 0.`, { passage: p.name, line: p.line }));
|
|
559
|
+
let start = null;
|
|
560
|
+
if (!passages.length) problems.push(problem("error", "no-passages", `The story has no passages: start one with "${HEADER} Name".`));
|
|
561
|
+
else if (options.start !== undefined && String(options.start).trim() !== "") {
|
|
562
|
+
start = nfc(String(options.start).trim());
|
|
563
|
+
if (!names.has(start)) {
|
|
564
|
+
problems.push(problem("error", "missing-start", `The start passage "${start}" doesn't exist.${suggest(start, names)}`));
|
|
565
|
+
start = null;
|
|
566
|
+
}
|
|
567
|
+
} else start = passages[0].name;
|
|
568
|
+
const out = new Map();
|
|
569
|
+
for (const p of passages) out.set(p.name, []);
|
|
570
|
+
for (const e of edges) if (!e.missing) out.get(e.from).push(e.to);
|
|
571
|
+
const depth = new Map();
|
|
572
|
+
if (start) {
|
|
573
|
+
depth.set(start, 0);
|
|
574
|
+
const queue = [start];
|
|
575
|
+
for (let q = 0; q < queue.length; q++) for (const to of out.get(queue[q])) if (!depth.has(to)) (depth.set(to, depth.get(queue[q]) + 1), queue.push(to));
|
|
576
|
+
}
|
|
577
|
+
const unreachable = start ? passages.filter((p) => !depth.has(p.name)).map((p) => p.name) : [];
|
|
578
|
+
for (const name of unreachable) problems.push(problem("warning", "unreachable", `Passage "${name}" can't be reached from "${start}".`, { passage: name, line: names.get(name).line }));
|
|
579
|
+
const endings = passages.filter((p) => !p.links.length).map((p) => p.name);
|
|
580
|
+
problems.sort((a, b) => (a.severity === b.severity ? 0 : a.severity === "error" ? -1 : 1));
|
|
581
|
+
const errors = problems.filter((p) => p.severity === "error").length;
|
|
582
|
+
const missing = edges.filter((e) => e.missing);
|
|
583
|
+
const plural = (n, w) => `${n} ${w}${n === 1 ? "" : "s"}`;
|
|
584
|
+
return {
|
|
585
|
+
passages,
|
|
586
|
+
assets,
|
|
587
|
+
variables: [...new Set([...setAnywhere, ...readAt.keys()])].sort(),
|
|
588
|
+
start,
|
|
589
|
+
edges,
|
|
590
|
+
missing: missing.map((e) => ({ from: e.from, target: e.to, label: e.label, line: e.line })),
|
|
591
|
+
unreachable,
|
|
592
|
+
reachable: passages.filter((p) => depth.has(p.name)).map((p) => p.name),
|
|
593
|
+
endings,
|
|
594
|
+
depth: Object.fromEntries(depth),
|
|
595
|
+
problems,
|
|
596
|
+
ok: errors === 0,
|
|
597
|
+
summary: `${plural(passages.length, "passage")}, ${plural(edges.length, "link")}, ${plural(missing.length, "missing target")}, ${plural(unreachable.length, "unreachable passage")}, ${plural(endings.length, "ending")}`,
|
|
598
|
+
};
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/** ` Did you mean "X"?` for a target that differs only in case or space from a passage, else "". */
|
|
602
|
+
function suggest(target, names) {
|
|
603
|
+
const key = (s) => s.toLowerCase().replace(/\s+/g, " ");
|
|
604
|
+
for (const n of names.keys()) if (key(n) === key(target)) return ` Did you mean "${n}"? (names are exact, case and spacing included)`;
|
|
605
|
+
return "";
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
// ── rename ─────────────────────────────────────────────────────────────────
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* Rename a passage and the standard links that point at it, as Twine does. A link
|
|
612
|
+
* keeps its form: [[Old]] becomes [[New]], [[text->Old]] becomes [[text->New]]. What
|
|
613
|
+
* isn't a standard link is left alone and reported: the name inside quotes, a macro
|
|
614
|
+
* or a `${…}` is a computed or custom-code reference this can't follow.
|
|
615
|
+
* @returns {{ text: string, ok: boolean, renamed: boolean, changed: Array<{ passage: string, links: number }>, warnings: object[], errors: object[], start?: string }}
|
|
616
|
+
*/
|
|
617
|
+
export function renamePassage(source, from, to, options = {}) {
|
|
618
|
+
const result = { text: String(source ?? ""), ok: false, renamed: false, changed: [], warnings: [], errors: [] };
|
|
619
|
+
from = nfc(String(from ?? "").trim());
|
|
620
|
+
to = nfc(String(to ?? "").trim());
|
|
621
|
+
const { passages, problems } = parseStory(source);
|
|
622
|
+
const fatal = problems.filter((p) => p.severity === "error" && p.code !== "text-before-passage");
|
|
623
|
+
if (fatal.length) result.errors.push(problem("error", "story-invalid", `Fix the story first: ${fatal[0].message}`));
|
|
624
|
+
if (!passages.some((p) => p.name === from)) result.errors.push(problem("error", "unknown-passage", `There is no passage "${from}".`));
|
|
625
|
+
const bad = nameProblem(to);
|
|
626
|
+
if (bad) result.errors.push(problem("error", "bad-name", `The new name: ${bad}.`));
|
|
627
|
+
else if (to !== from && passages.some((p) => p.name === to)) result.errors.push(problem("error", "name-taken", `A passage called "${to}" already exists.`));
|
|
628
|
+
if (result.errors.length) return result;
|
|
629
|
+
result.ok = true;
|
|
630
|
+
if (from === to) return result;
|
|
631
|
+
const lines = String(source).replace(/^/, "").replace(/\r\n?/g, "\n").split("\n");
|
|
632
|
+
// Every header line of the source, ignored duplicates included (those are kept as written).
|
|
633
|
+
const headers = [];
|
|
634
|
+
lines.forEach((line, n) => {
|
|
635
|
+
if (HEADER_LINE.test(line)) headers.push(n);
|
|
636
|
+
});
|
|
637
|
+
const kept = new Set(passages.map((p) => p.line - 1));
|
|
638
|
+
const out = lines.slice(0, headers[0] ?? lines.length);
|
|
639
|
+
for (let k = 0; k < headers.length; k++) {
|
|
640
|
+
const stop = k + 1 < headers.length ? headers[k + 1] : lines.length;
|
|
641
|
+
const hm = HEADER_LINE.exec(lines[headers[k]]);
|
|
642
|
+
const body = lines.slice(headers[k] + 1, stop);
|
|
643
|
+
if (hm[1] === "asset") {
|
|
644
|
+
out.push(lines[headers[k]], ...body);
|
|
645
|
+
continue;
|
|
646
|
+
}
|
|
647
|
+
const name = nfc((hm[2] ?? "").trim());
|
|
648
|
+
const { text: rewritten, count } = rewriteLinks(body.join("\n"), from, to);
|
|
649
|
+
const renames = name === from && kept.has(headers[k]);
|
|
650
|
+
const owner = renames ? to : name;
|
|
651
|
+
out.push(renames ? `${HEADER} ${to}` : lines[headers[k]]);
|
|
652
|
+
if (body.length) out.push(...rewritten.split("\n"));
|
|
653
|
+
if (count) result.changed.push({ passage: owner, links: count });
|
|
654
|
+
if (renames) result.renamed = true;
|
|
655
|
+
for (const w of computedReferences(body.join("\n"), from)) result.warnings.push(problem("warning", "computed-reference", `Passage "${owner}" (line ${headers[k] + 1 + w.line}) mentions "${from}" in ${w.where}. That is a computed or custom-code reference, so it was NOT changed; check it by hand.`, { passage: owner, line: headers[k] + 1 + w.line }));
|
|
656
|
+
}
|
|
657
|
+
result.text = out.join("\n");
|
|
658
|
+
if (options.start !== undefined && nfc(String(options.start).trim()) === from) result.start = to;
|
|
659
|
+
return result;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/** Rewrite the targets of standard links in a body. */
|
|
663
|
+
function rewriteLinks(text, from, to) {
|
|
664
|
+
const { links } = parseLinks(text);
|
|
665
|
+
let out = "";
|
|
666
|
+
let at = 0;
|
|
667
|
+
let count = 0;
|
|
668
|
+
for (const l of links) {
|
|
669
|
+
if (l.target !== from) continue;
|
|
670
|
+
const raw = text.slice(l.start, l.end);
|
|
671
|
+
const inner = raw.slice(2, -2);
|
|
672
|
+
let next;
|
|
673
|
+
if (l.form === "simple") next = to;
|
|
674
|
+
else if (l.form === "arrow") next = `${inner.slice(0, inner.lastIndexOf("->"))}->${to}`;
|
|
675
|
+
else next = `${to}<-${inner.slice(inner.indexOf("<-") + 2)}`;
|
|
676
|
+
// keep the spaces around the old target, if any
|
|
677
|
+
out += text.slice(at, l.start) + `[[${next}]]`;
|
|
678
|
+
at = l.end;
|
|
679
|
+
count++;
|
|
680
|
+
}
|
|
681
|
+
return { text: out + text.slice(at), count };
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
/** Places where a passage's name appears outside a standard link: in quotes, or inside macro-like code. */
|
|
685
|
+
function computedReferences(text, name) {
|
|
686
|
+
const found = [];
|
|
687
|
+
const { links } = parseLinks(text);
|
|
688
|
+
let masked = text;
|
|
689
|
+
for (const l of [...links].reverse()) masked = masked.slice(0, l.start) + " ".repeat(l.end - l.start) + masked.slice(l.end);
|
|
690
|
+
const lineOf = (index) => masked.slice(0, index).split("\n").length;
|
|
691
|
+
const esc = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
692
|
+
for (const m of masked.matchAll(new RegExp(`(["'\`])${esc}\\1`, "g"))) if (!found.some((f) => f.line === lineOf(m.index))) found.push({ line: lineOf(m.index), where: "quotes" });
|
|
693
|
+
for (const m of masked.matchAll(/<<[^]*?>>|\$\{[^}]*\}|\{\{[^]*?\}\}/g)) if (m[0].includes(name) && !found.some((f) => f.line === lineOf(m.index))) found.push({ line: lineOf(m.index), where: "a macro or ${…} expression" });
|
|
694
|
+
return found;
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
// ── playback: replay, step, play ───────────────────────────────────────────
|
|
698
|
+
|
|
699
|
+
const namesCache = new WeakMap();
|
|
700
|
+
const nameSetOf = (a) => {
|
|
701
|
+
let set = namesCache.get(a);
|
|
702
|
+
if (!set) namesCache.set(a, (set = new Set(a.passages.map((x) => x.name))));
|
|
703
|
+
return set;
|
|
704
|
+
};
|
|
705
|
+
|
|
706
|
+
/**
|
|
707
|
+
* Enter a passage with the variables the reader has: run its macros, and give the text
|
|
708
|
+
* that is shown, the variables after it and its choices (the links that are shown now,
|
|
709
|
+
* each marked missing or not).
|
|
710
|
+
*/
|
|
711
|
+
function enter(a, name, vars) {
|
|
712
|
+
const p = a.passages.find((x) => x.name === name);
|
|
713
|
+
const m = macrosOf(p);
|
|
714
|
+
const ran = m.has && !m.errors.length ? runMacros(m, vars) : { text: p.text, vars, errors: [] };
|
|
715
|
+
const links = m.has && !m.errors.length ? parseLinks(ran.text).links : p.links;
|
|
716
|
+
const names = nameSetOf(a);
|
|
717
|
+
const choices = links.slice(0, LIMITS.choices).map((l, index) => ({ index, label: l.label, target: l.target, exists: names.has(l.target) }));
|
|
718
|
+
return { name, text: ran.text, vars: ran.vars, errors: ran.errors, choices };
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/** Turn what a person (or a test) chose into a target name: an index, a target name, `{ index }` or `{ target }`. */
|
|
722
|
+
function resolveChoice(choices, event) {
|
|
723
|
+
const value = event !== null && typeof event === "object" ? (event.index ?? event.target) : event;
|
|
724
|
+
if (typeof value === "number" || (typeof value === "string" && /^\d+$/.test(value) && event?.index !== undefined)) {
|
|
725
|
+
const c = choices[Number(value)];
|
|
726
|
+
return c ? { choice: c } : { error: problem("error", "no-such-choice", `There is no choice ${value} here (${choices.length} choice${choices.length === 1 ? "" : "s"}).`) };
|
|
727
|
+
}
|
|
728
|
+
if (typeof value === "string") {
|
|
729
|
+
const c = choices.find((x) => x.target === nfc(value));
|
|
730
|
+
return c ? { choice: c } : { error: problem("error", "no-such-choice", `No choice here leads to "${value}".`) };
|
|
731
|
+
}
|
|
732
|
+
return { error: problem("error", "bad-choice", "A choice is an index, a passage name, { index } or { target }.") };
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
/** Walk a list of choices from the start. Returns the replay result and the entry the walk ended in. */
|
|
736
|
+
function walk(a, events) {
|
|
737
|
+
const out = { ok: false, start: a.start, at: a.start, path: [], steps: [], errors: [], ending: false, vars: {} };
|
|
738
|
+
if (!a.start) {
|
|
739
|
+
out.errors.push(problem("error", "no-start", "There is no start passage to play from."));
|
|
740
|
+
return { out, cur: null };
|
|
741
|
+
}
|
|
742
|
+
let cur = enter(a, a.start, {});
|
|
743
|
+
for (let n = 0; n < events.length; n++) {
|
|
744
|
+
const { choice, error } = resolveChoice(cur.choices, events[n]);
|
|
745
|
+
if (error) {
|
|
746
|
+
out.errors.push({ ...error, step: n, passage: cur.name });
|
|
747
|
+
break;
|
|
748
|
+
}
|
|
749
|
+
if (!choice.exists) {
|
|
750
|
+
out.errors.push(problem("error", "missing-target", `Step ${n}: "${cur.name}" links to "${choice.target}", which doesn't exist.`, { step: n, passage: cur.name, target: choice.target }));
|
|
751
|
+
break;
|
|
752
|
+
}
|
|
753
|
+
out.steps.push({ from: cur.name, label: choice.label, to: choice.target });
|
|
754
|
+
out.path.push(choice.target);
|
|
755
|
+
cur = enter(a, choice.target, cur.vars);
|
|
756
|
+
}
|
|
757
|
+
out.at = cur.name;
|
|
758
|
+
out.ending = cur.choices.length === 0;
|
|
759
|
+
out.vars = cur.vars;
|
|
760
|
+
out.ok = out.errors.length === 0;
|
|
761
|
+
return { out, cur };
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
/**
|
|
765
|
+
* Replay a sequence of choices from the start: the engine behind "replayable
|
|
766
|
+
* event-sequence tests". A choice that doesn't exist or whose target is missing stops
|
|
767
|
+
* the replay with an error saying where. A choice index counts the links that are
|
|
768
|
+
* shown at that moment (a link in a false <<if>> isn't one).
|
|
769
|
+
* @returns {{ ok: boolean, start: string|null, at: string|null, path: string[], steps: Array<{ from: string, label: string, to: string }>, errors: object[], ending: boolean, vars: object }}
|
|
770
|
+
*/
|
|
771
|
+
export function replay(source, options = {}) {
|
|
772
|
+
const a = typeof source === "string" ? analyze(source, options) : source;
|
|
773
|
+
return walk(a, Array.isArray(options.choices) ? options.choices : []).out;
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
const stateKey = (name, vars) => `${name}\u0000${JSON.stringify(Object.keys(vars).sort().map((k) => [k, vars[k]]))}`;
|
|
777
|
+
|
|
778
|
+
/**
|
|
779
|
+
* The shortest list of passages that takes a reader from the start to `target`, through
|
|
780
|
+
* the variables (a locked door is only passed with its key). It is a path, so it replays
|
|
781
|
+
* like any other. This is what clicking a passage on the map does.
|
|
782
|
+
* @returns {{ ok: boolean, path: string[], error?: string }}
|
|
783
|
+
*/
|
|
784
|
+
export function pathTo(source, target, options = {}) {
|
|
785
|
+
const a = typeof source === "string" ? analyze(source, options) : source;
|
|
786
|
+
const goal = nfc(String(target ?? "").trim());
|
|
787
|
+
if (!a.start) return { ok: false, path: [], error: "There is no start passage to jump from." };
|
|
788
|
+
if (!nameSetOf(a).has(goal)) return { ok: false, path: [], error: `There is no passage "${goal}".` };
|
|
789
|
+
const first = enter(a, a.start, {});
|
|
790
|
+
const seen = new Map([[stateKey(first.name, first.vars), null]]);
|
|
791
|
+
const queue = [{ entry: first, path: [] }];
|
|
792
|
+
const cap = options.maxStates ?? LIMITS.states * 5;
|
|
793
|
+
for (let q = 0; q < queue.length; q++) {
|
|
794
|
+
const { entry, path } = queue[q];
|
|
795
|
+
if (entry.name === goal) return { ok: true, path };
|
|
796
|
+
for (const c of entry.choices) {
|
|
797
|
+
if (!c.exists) continue;
|
|
798
|
+
const next = enter(a, c.target, entry.vars);
|
|
799
|
+
const key = stateKey(next.name, next.vars);
|
|
800
|
+
if (seen.has(key) || seen.size >= cap) continue;
|
|
801
|
+
seen.set(key, true);
|
|
802
|
+
queue.push({ entry: next, path: [...path, c.target] });
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
return { ok: false, path: [], error: `"${goal}" can't be reached from "${a.start}".` };
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
/**
|
|
809
|
+
* The reader's next path after an event. `path` is the targets visited after the start
|
|
810
|
+
* (the only per-reader state: a list of passage names). Events: a choice (an index or
|
|
811
|
+
* target name, `{ index }`, `{ target }`), `{ back: true }`, `{ restart: true }` and
|
|
812
|
+
* `{ jump: "Passage" }` (the shortest way there).
|
|
813
|
+
* @returns {{ path: string[], error?: string }}
|
|
814
|
+
*/
|
|
815
|
+
export function step(source, state, event) {
|
|
816
|
+
const a = typeof source === "string" ? analyze(source, state ?? {}) : source;
|
|
817
|
+
const path = Array.isArray(state?.path) ? state.path.map(String) : [];
|
|
818
|
+
if (event !== null && typeof event === "object" && event.restart) return { path: [] };
|
|
819
|
+
if (event !== null && typeof event === "object" && event.back) return { path: path.slice(0, -1) };
|
|
820
|
+
if (event !== null && typeof event === "object" && event.jump !== undefined) {
|
|
821
|
+
const j = pathTo(a, event.jump);
|
|
822
|
+
return j.ok ? { path: j.path } : { path: walk(a, path).out.path, error: j.error };
|
|
823
|
+
}
|
|
824
|
+
const { out: now, cur } = walk(a, path);
|
|
825
|
+
if (!cur) return { path: now.path, error: now.errors[0].message };
|
|
826
|
+
const { choice, error } = resolveChoice(cur.choices, event);
|
|
827
|
+
if (error) return { path: now.path, error: error.message };
|
|
828
|
+
if (!choice.exists) return { path: now.path, error: `"${choice.target}" doesn't exist.` };
|
|
829
|
+
return { path: [...now.path, choice.target] };
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
const fnv = (text) => {
|
|
833
|
+
let h = 0x811c9dc5;
|
|
834
|
+
for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 0x01000193) >>> 0;
|
|
835
|
+
return h.toString(36);
|
|
836
|
+
};
|
|
837
|
+
const b64 = (text) => btoa(unescape(encodeURIComponent(text))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
838
|
+
const unb64 = (text) => decodeURIComponent(escape(atob(text.replace(/-/g, "+").replace(/_/g, "/"))));
|
|
839
|
+
|
|
840
|
+
/**
|
|
841
|
+
* A saved game as a short text a person can keep: the path (the passages after the start)
|
|
842
|
+
* and a fingerprint of the story. The variables are not in it: they are rebuilt by
|
|
843
|
+
* replaying the path, so a save can't hold a value the story couldn't have made.
|
|
844
|
+
*/
|
|
845
|
+
export function save(source, state = {}) {
|
|
846
|
+
const text = typeof source === "string" ? source : "";
|
|
847
|
+
const path = Array.isArray(state?.path) ? state.path.map(String) : [];
|
|
848
|
+
return { code: `nv1:${fnv(text)}:${b64(JSON.stringify(path))}`, path };
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
/**
|
|
852
|
+
* Read a saved game. `changed` says the story is not the one the save was made in; the
|
|
853
|
+
* path is then cut at the first step the story no longer has (`stale` says where), as `play` does.
|
|
854
|
+
* @returns {{ ok: boolean, path: string[], changed?: boolean, stale?: object|null, error?: string }}
|
|
855
|
+
*/
|
|
856
|
+
export function load(source, code, options = {}) {
|
|
857
|
+
const m = /^nv1:([0-9a-z]+):([A-Za-z0-9_-]*)$/.exec(String(code ?? "").trim());
|
|
858
|
+
if (!m) return { ok: false, path: [], error: "That isn't a saved game from this reader." };
|
|
859
|
+
let path;
|
|
860
|
+
try {
|
|
861
|
+
path = JSON.parse(unb64(m[2]));
|
|
862
|
+
} catch {
|
|
863
|
+
return { ok: false, path: [], error: "That saved game can't be read." };
|
|
864
|
+
}
|
|
865
|
+
if (!Array.isArray(path) || path.length > 10_000 || !path.every((x) => typeof x === "string")) return { ok: false, path: [], error: "That saved game can't be read." };
|
|
866
|
+
const a = typeof source === "string" ? analyze(source, options) : source;
|
|
867
|
+
const text = typeof source === "string" ? source : "";
|
|
868
|
+
const { out } = walk(a, path);
|
|
869
|
+
return { ok: true, path: out.path, changed: fnv(text) !== m[1], stale: out.ok ? null : { step: out.errors[0].step, passage: out.errors[0].passage, message: out.errors[0].message } };
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
/**
|
|
873
|
+
* What a reader sees: the current passage as safe HTML, its choices, and the path
|
|
874
|
+
* (healed: if the story changed under a saved path, the path is cut at the first step
|
|
875
|
+
* that no longer exists and `stale` says so).
|
|
876
|
+
*/
|
|
877
|
+
export function play(source, state = {}) {
|
|
878
|
+
const a = typeof source === "string" ? analyze(source, state) : source;
|
|
879
|
+
const out = { ok: a.ok, at: null, passage: null, html: "", choices: [], path: [], vars: {}, stale: null, ending: false, problems: a.problems.filter((p) => p.severity === "error") };
|
|
880
|
+
if (!a.start) return { ...out, html: '<p class="empty">Nothing to play: fix the story first.</p>' };
|
|
881
|
+
const want = Array.isArray(state?.path) ? state.path.map(String) : [];
|
|
882
|
+
const { out: r, cur } = walk(a, want);
|
|
883
|
+
if (!r.ok) out.stale = { step: r.errors[0].step, passage: r.errors[0].passage, message: r.errors[0].message };
|
|
884
|
+
out.path = r.path;
|
|
885
|
+
out.at = r.at;
|
|
886
|
+
out.vars = cur.vars;
|
|
887
|
+
out.passage = { name: cur.name, text: cur.text };
|
|
888
|
+
out.choices = cur.choices;
|
|
889
|
+
out.ending = cur.choices.length === 0;
|
|
890
|
+
for (const e of cur.errors) out.problems.push(problem("error", "macro-error", e.message, { passage: cur.name }));
|
|
891
|
+
out.html = viewHtml(a, cur, { path: r.path, stale: out.stale });
|
|
892
|
+
return out;
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
function viewHtml(a, cur, { path, stale }) {
|
|
896
|
+
const choiceButtons = cur.choices.map((c) => c.exists
|
|
897
|
+
? `<li><button type="button" class="choice" data-choice="${escapeHtml(JSON.stringify({ index: c.index }))}">${escapeHtml(c.label)}</button></li>`
|
|
898
|
+
: `<li><span class="choice broken" title="no passage called ${escapeHtml(c.target)}">${escapeHtml(c.label)} (missing: ${escapeHtml(c.target)})</span></li>`).join("");
|
|
899
|
+
const nav = `<p class="nav"><button type="button" class="back" data-choice='{"back":true}'>back</button> <button type="button" class="restart" data-choice='{"restart":true}'>start over</button></p>`;
|
|
900
|
+
const errors = cur.errors.map((e) => `<p class="macro-error">${escapeHtml(e.message)}</p>`).join("");
|
|
901
|
+
const ending = cur.choices.length === 0;
|
|
902
|
+
return `<article class="passage" data-passage="${escapeHtml(cur.name)}"><h3>${escapeHtml(cur.name)}</h3>${renderText(cur.text, { assets: a.assets, link: (l) => `<span class="inline-link">${escapeHtml(l.label)}</span>` })}${errors}${ending ? '<p class="ending"><em>The end.</em></p>' : `<ul class="choices">${choiceButtons}</ul>`}${path.length ? nav : ""}${stale ? `<p class="stale">${escapeHtml(stale.message)} The saved path was cut here.</p>` : ""}</article>`;
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
// ── safe rendering ─────────────────────────────────────────────────────────
|
|
906
|
+
|
|
907
|
+
/**
|
|
908
|
+
* A passage's text as safe HTML: paragraphs (blank lines), line breaks, `**strong**`,
|
|
909
|
+
* `*emphasis*` and `` `code` `` over ESCAPED text, with `link(link)` rendering each
|
|
910
|
+
* [[link]] (it is given the parsed link and must return HTML it made itself; its
|
|
911
|
+
* label goes through escapeHtml). Nothing else of the author's is HTML.
|
|
912
|
+
*/
|
|
913
|
+
export function renderText(text, { link, assets } = {}) {
|
|
914
|
+
const { links } = parseLinks(text);
|
|
915
|
+
const byName = new Map((assets ?? []).map((x) => [escapeHtml(x.name), x]));
|
|
916
|
+
const inline = (segment) => {
|
|
917
|
+
// Images first, as placeholders: a story's own @asset data URI, shown with escaped alt text.
|
|
918
|
+
const images = [];
|
|
919
|
+
let html = escapeHtml(segment.replace(/\u0000/g, "")).replace(/\\(\[\[)/g, "$1");
|
|
920
|
+
if (byName.size) html = html.replace(/!\[([^\]\n]*)\]\(([^)\n]+)\)/g, (whole, alt, ref) => {
|
|
921
|
+
const asset = byName.get(nfc(ref.trim()));
|
|
922
|
+
if (!asset) return whole;
|
|
923
|
+
images.push(`<img src="${asset.uri}" alt="${alt}">`);
|
|
924
|
+
return `\u0000${images.length - 1}\u0000`;
|
|
925
|
+
});
|
|
926
|
+
html = html.replace(/`([^`\n]+)`/g, "<code>$1</code>");
|
|
927
|
+
html = html.replace(/\*\*([^*\n]+)\*\*/g, "<strong>$1</strong>").replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g, "$1<em>$2</em>");
|
|
928
|
+
return html.replace(/\n/g, "<br>").replace(/\u0000(\d+)\u0000/g, (_, n) => images[Number(n)]);
|
|
929
|
+
};
|
|
930
|
+
// Cut the text at links, render each piece, and keep paragraphs by splitting the pieces on blank lines.
|
|
931
|
+
const parts = [];
|
|
932
|
+
let at = 0;
|
|
933
|
+
for (const l of links) {
|
|
934
|
+
parts.push({ text: text.slice(at, l.start) }, { link: l });
|
|
935
|
+
at = l.end;
|
|
936
|
+
}
|
|
937
|
+
parts.push({ text: text.slice(at) });
|
|
938
|
+
const paragraphs = [[]];
|
|
939
|
+
for (const part of parts) {
|
|
940
|
+
if (part.link) {
|
|
941
|
+
paragraphs[paragraphs.length - 1].push(link ? link(part.link) : escapeHtml(part.link.label));
|
|
942
|
+
continue;
|
|
943
|
+
}
|
|
944
|
+
const pieces = part.text.split(/\n{2,}/);
|
|
945
|
+
pieces.forEach((piece, i) => {
|
|
946
|
+
if (i > 0) paragraphs.push([]);
|
|
947
|
+
if (piece) paragraphs[paragraphs.length - 1].push(inline(piece));
|
|
948
|
+
});
|
|
949
|
+
}
|
|
950
|
+
return paragraphs.map((p) => p.join("").trim()).filter(Boolean).map((p) => `<p>${p}</p>`).join("");
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
// ── navigation graph ───────────────────────────────────────────────────────
|
|
954
|
+
|
|
955
|
+
/**
|
|
956
|
+
* The navigation graph as a static SVG string (a layer of its own: teal arrows for
|
|
957
|
+
* links, dashed red for missing targets, grey nodes for passages the start can't
|
|
958
|
+
* reach; the canvas's data wires are a different thing and look different).
|
|
959
|
+
*/
|
|
960
|
+
export function graphSvg(source, options = {}) {
|
|
961
|
+
const a = typeof source === "string" ? analyze(source, options) : source;
|
|
962
|
+
const W = 150;
|
|
963
|
+
const H = 34;
|
|
964
|
+
const GX = 70;
|
|
965
|
+
const GY = 22;
|
|
966
|
+
const cols = new Map(); // name -> column
|
|
967
|
+
const column = (name) => cols.get(name);
|
|
968
|
+
const reach = a.depth ?? {};
|
|
969
|
+
let maxCol = 0;
|
|
970
|
+
for (const p of a.passages) if (Object.hasOwn(reach, p.name)) (cols.set(p.name, reach[p.name]), (maxCol = Math.max(maxCol, reach[p.name])));
|
|
971
|
+
const missingTargets = [...new Set(a.edges.filter((e) => e.missing).map((e) => e.to))];
|
|
972
|
+
const loose = a.passages.filter((p) => !cols.has(p.name));
|
|
973
|
+
const nodes = []; // { id, label, col, kind }
|
|
974
|
+
const byCol = new Map();
|
|
975
|
+
const place = (id, label, col, kind) => {
|
|
976
|
+
const n = byCol.get(col) ?? 0;
|
|
977
|
+
byCol.set(col, n + 1);
|
|
978
|
+
nodes.push({ id, label, col, row: n, kind });
|
|
979
|
+
};
|
|
980
|
+
for (const p of a.passages) if (cols.has(p.name)) place(p.name, p.name, column(p.name), p.name === a.start ? "start" : a.endings.includes(p.name) ? "ending" : "passage");
|
|
981
|
+
const missingCol = maxCol + 1;
|
|
982
|
+
for (const t of missingTargets) place(`?${t}`, t, missingCol, "missing");
|
|
983
|
+
const looseCol = missingTargets.length ? missingCol + 1 : maxCol + 1;
|
|
984
|
+
for (const p of loose) place(p.name, p.name, looseCol, "unreachable");
|
|
985
|
+
const pos = new Map(nodes.map((n) => [n.id, { ...n, x: 20 + n.col * (W + GX), y: 36 + n.row * (H + GY) }]));
|
|
986
|
+
const rows = Math.max(1, ...[...byCol.values()]);
|
|
987
|
+
const width = 40 + (Math.max(0, ...nodes.map((n) => n.col)) + 1) * (W + GX) - GX;
|
|
988
|
+
const height = 56 + rows * (H + GY);
|
|
989
|
+
const seen = new Set();
|
|
990
|
+
const edgeSvg = [];
|
|
991
|
+
for (const e of a.edges) {
|
|
992
|
+
const from = pos.get(e.from);
|
|
993
|
+
const to = pos.get(e.missing ? `?${e.to}` : e.to);
|
|
994
|
+
if (!from || !to) continue;
|
|
995
|
+
const key = `${from.id}\u0000${to.id}`;
|
|
996
|
+
if (seen.has(key)) continue;
|
|
997
|
+
seen.add(key);
|
|
998
|
+
let d;
|
|
999
|
+
if (from === to) {
|
|
1000
|
+
const cx = from.x + W / 2;
|
|
1001
|
+
d = `M${cx - 18} ${from.y} C${cx - 18} ${from.y - 30} ${cx + 18} ${from.y - 30} ${cx + 18} ${from.y}`;
|
|
1002
|
+
} else if (to.col > from.col) {
|
|
1003
|
+
const sx = from.x + W;
|
|
1004
|
+
const sy = from.y + H / 2;
|
|
1005
|
+
const tx = to.x;
|
|
1006
|
+
const ty = to.y + H / 2;
|
|
1007
|
+
d = `M${sx} ${sy} C${sx + GX / 2} ${sy} ${tx - GX / 2} ${ty} ${tx} ${ty}`;
|
|
1008
|
+
} else {
|
|
1009
|
+
const sx = from.x + W / 2;
|
|
1010
|
+
const tx = to.x + W / 2;
|
|
1011
|
+
const lift = 28 + 8 * Math.abs(from.col - to.col);
|
|
1012
|
+
d = `M${sx} ${from.y} C${sx} ${from.y - lift} ${tx} ${to.y - lift} ${tx} ${to.y - 2}`;
|
|
1013
|
+
}
|
|
1014
|
+
edgeSvg.push(`<path class="nav-edge${e.missing ? " missing" : ""}" d="${d}" marker-end="url(#nav-arrow${e.missing ? "-missing" : ""})"><title>${escapeHtml(`${e.from} -> ${e.to}${e.missing ? " (missing)" : ""}: ${e.label}`)}</title></path>`);
|
|
1015
|
+
}
|
|
1016
|
+
const short = (s) => (s.length > 20 ? `${s.slice(0, 19)}…` : s);
|
|
1017
|
+
const jumpable = (n) => options.clickable && ["start", "ending", "passage"].includes(n.kind);
|
|
1018
|
+
const current = options.current === undefined ? null : nfc(String(options.current));
|
|
1019
|
+
const nodeSvg = [...pos.values()].map((n) => `<g class="nav-node ${n.kind}${n.id === current && n.kind !== "missing" ? " current" : ""}"${jumpable(n) ? ` data-jump="${escapeHtml(n.id)}" tabindex="0" role="button" aria-label="${escapeHtml(`Go to ${n.label}`)}"` : ""} transform="translate(${n.x} ${n.y})"><title>${escapeHtml(`${n.label} (${n.kind})`)}</title><rect width="${W}" height="${H}" rx="6"/><text x="${W / 2}" y="${H / 2 + 4}" text-anchor="middle">${escapeHtml(short(n.label))}</text></g>`);
|
|
1020
|
+
const style = ".nav-node rect{fill:#e8f4f6;stroke:#1a7f8e;stroke-width:1.5}.nav-node text{font:12px system-ui,sans-serif;fill:#10343a}.nav-node.start rect{fill:#c6e9ee;stroke-width:3}.nav-node.ending rect{stroke-dasharray:none;fill:#f1ecd9;stroke:#8a7a2e}.nav-node.unreachable rect{fill:#eee;stroke:#999;stroke-dasharray:4 3}.nav-node.unreachable text{fill:#666}.nav-node.current rect{stroke:#0b4f59;stroke-width:3.5}.nav-node[data-jump]{cursor:pointer}.nav-node[data-jump]:focus{outline:none}.nav-node[data-jump]:focus rect{stroke:#0b4f59;stroke-width:3.5}.nav-node[data-jump]:hover rect{fill:#d6eef2}.nav-node.missing rect{fill:#fdeaea;stroke:#c0392b;stroke-dasharray:4 3}.nav-edge{fill:none;stroke:#1a7f8e;stroke-width:1.8}.nav-edge.missing{stroke:#c0392b;stroke-dasharray:5 4}";
|
|
1021
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" class="narrative-map" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}" role="img" aria-label="${escapeHtml(`Story map: ${a.summary}`)}"><style>${style}</style><defs><marker id="nav-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#1a7f8e"/></marker><marker id="nav-arrow-missing" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#c0392b"/></marker></defs><text x="20" y="20" class="nav-legend" font-family="system-ui,sans-serif" font-size="11" fill="#555">navigation: links between passages (not data wires)</text>${edgeSvg.join("")}${nodeSvg.join("")}</svg>`;
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
// ── local HTML playback export ─────────────────────────────────────────────
|
|
1025
|
+
|
|
1026
|
+
/** The CSP of an exported page: no network, no script, no frame, no form, nothing but its own inline style. */
|
|
1027
|
+
export const EXPORT_CSP = "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'";
|
|
1028
|
+
|
|
1029
|
+
const EXPORT_CSS = "body{font:18px/1.55 Georgia,serif;max-width:40rem;margin:2rem auto;padding:0 1rem;color:#222;background:#fbfaf7}h1{font:600 .85rem system-ui,sans-serif;letter-spacing:.08em;text-transform:uppercase;color:#777}h2{font-size:1.5rem}.passage{display:none}.passage:target{display:block}.passage.start{display:block}.passage:target~.start{display:none}ul.choices{list-style:none;padding:0}ul.choices li{margin:.5rem 0}a.choice{display:block;padding:.5rem .8rem;border:1px solid #1a7f8e;border-radius:6px;color:#1a5f6a;text-decoration:none}a.choice:hover,a.choice:focus{background:#e8f4f6}a.inline{color:#1a5f6a}.broken{color:#a33;text-decoration:line-through}p.ending{color:#777}p.restart a{color:#777;font:.8rem system-ui,sans-serif}";
|
|
1030
|
+
|
|
1031
|
+
/**
|
|
1032
|
+
* One self-contained HTML file that plays the story with no script and no network:
|
|
1033
|
+
* each passage is a <section id="p-N">, a choice is an <a href="#p-N"> and the CSS
|
|
1034
|
+
* :target rule shows the section the address names (the start passage when none is
|
|
1035
|
+
* named; it is the LAST section so the `~` rule can hide it). The only reader state
|
|
1036
|
+
* is the URL fragment in that browser. Refuses a story with errors unless `allowBroken`.
|
|
1037
|
+
* @returns {{ ok: boolean, html: string|null, bytes: number, report: object[], notes: string[] }}
|
|
1038
|
+
*/
|
|
1039
|
+
export function exportHtml(source, options = {}) {
|
|
1040
|
+
const a = typeof source === "string" ? analyze(source, options) : source;
|
|
1041
|
+
const notes = ["Plays with no script and no network: the address bar's #fragment is the only reader state (and the saved game: bookmark it), kept in that browser.", "Twine macros other than set, if and print, and other dialect features aren't supported."];
|
|
1042
|
+
if (!a.ok && !options.allowBroken) return { ok: false, html: null, bytes: 0, report: a.problems, notes: ["Not exported: fix the errors in the report first (or export with allowBroken)."] };
|
|
1043
|
+
const report = [...a.problems];
|
|
1044
|
+
const maxStates = options.maxStates ?? LIMITS.states;
|
|
1045
|
+
const title = String(options.title ?? "A story").slice(0, 120);
|
|
1046
|
+
// One section per state a reader can be in: a passage with the variables it was entered with.
|
|
1047
|
+
// A story with no variables has one state per passage; a flag or two adds a few; a counter
|
|
1048
|
+
// that grows forever has no end, so the export is refused rather than cut.
|
|
1049
|
+
const index = new Map(a.passages.map((p, i) => [p.name, i]));
|
|
1050
|
+
const states = new Map();
|
|
1051
|
+
const order = [];
|
|
1052
|
+
const idOf = new Map(); // passage -> states seen
|
|
1053
|
+
const stateFor = (entry) => {
|
|
1054
|
+
const key = stateKey(entry.name, entry.vars);
|
|
1055
|
+
let st = states.get(key);
|
|
1056
|
+
if (!st) {
|
|
1057
|
+
const n = (idOf.get(entry.name) ?? 0) + 1;
|
|
1058
|
+
idOf.set(entry.name, n);
|
|
1059
|
+
st = { id: n === 1 ? `p-${index.get(entry.name)}` : `p-${index.get(entry.name)}-${n}`, entry, next: [] };
|
|
1060
|
+
states.set(key, st);
|
|
1061
|
+
order.push(st);
|
|
1062
|
+
}
|
|
1063
|
+
return st;
|
|
1064
|
+
};
|
|
1065
|
+
let overflow = false;
|
|
1066
|
+
let q = 0;
|
|
1067
|
+
const expand = () => {
|
|
1068
|
+
for (; q < order.length && !overflow; q++) {
|
|
1069
|
+
const st = order[q];
|
|
1070
|
+
for (const c of st.entry.choices) {
|
|
1071
|
+
if (!c.exists) {
|
|
1072
|
+
st.next.push(null);
|
|
1073
|
+
continue;
|
|
1074
|
+
}
|
|
1075
|
+
const e = enter(a, c.target, st.entry.vars);
|
|
1076
|
+
if (order.length >= maxStates && !states.has(stateKey(e.name, e.vars))) {
|
|
1077
|
+
overflow = true;
|
|
1078
|
+
break;
|
|
1079
|
+
}
|
|
1080
|
+
st.next.push(stateFor(e));
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
};
|
|
1084
|
+
if (a.start) {
|
|
1085
|
+
stateFor(enter(a, a.start, {}));
|
|
1086
|
+
expand();
|
|
1087
|
+
}
|
|
1088
|
+
// A passage nothing reaches is still in the file (the check warned about it), entered with no variables.
|
|
1089
|
+
for (const p of a.passages) {
|
|
1090
|
+
if (overflow) break;
|
|
1091
|
+
if (!idOf.has(p.name)) {
|
|
1092
|
+
stateFor(enter(a, p.name, {}));
|
|
1093
|
+
expand();
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
if (overflow) {
|
|
1097
|
+
report.push(problem("error", "state-space", `The story can be in more than ${maxStates} different states (a passage with the variables it was entered with), so it can't become a page without a script. Use fewer or smaller variables (flags, not counters).`));
|
|
1098
|
+
return { ok: false, html: null, bytes: 0, report, notes: ["Not exported: too many reader states."] };
|
|
1099
|
+
}
|
|
1100
|
+
for (const st of order) for (const e of st.entry.errors) report.push(problem("error", "macro-error", `Passage "${st.entry.name}": ${e.message}`, { passage: st.entry.name }));
|
|
1101
|
+
const ok = !report.some((p) => p.severity === "error");
|
|
1102
|
+
if (!ok && !options.allowBroken) return { ok: false, html: null, bytes: 0, report, notes: ["Not exported: fix the errors in the report first (or export with allowBroken)."] };
|
|
1103
|
+
let usesImages = false;
|
|
1104
|
+
const section = (st) => {
|
|
1105
|
+
const { entry } = st;
|
|
1106
|
+
const lis = entry.choices.map((c, i) => st.next[i] ? `<li><a class="choice" href="#${st.next[i].id}">${escapeHtml(c.label)}</a></li>` : `<li><span class="choice broken">${escapeHtml(c.label)}</span></li>`).join("");
|
|
1107
|
+
const labelLink = new Map(entry.choices.map((c, i) => [i, st.next[i]]));
|
|
1108
|
+
let n = 0;
|
|
1109
|
+
const html = renderText(entry.text, { assets: a.assets, link: (l) => {
|
|
1110
|
+
const next = labelLink.get(n++);
|
|
1111
|
+
return next ? `<a class="inline" href="#${next.id}">${escapeHtml(l.label)}</a>` : `<span class="broken">${escapeHtml(l.label)}</span>`;
|
|
1112
|
+
} });
|
|
1113
|
+
if (html.includes("<img ")) usesImages = true;
|
|
1114
|
+
return `<section class="passage${st === order[0] ? " start" : ""}" id="${st.id}"><h2>${escapeHtml(entry.name)}</h2>${html}${entry.choices.length ? `<ul class="choices">${lis}</ul>` : '<p class="ending"><em>The end.</em></p>'}<p class="restart"><a href="#">start over</a></p></section>`;
|
|
1115
|
+
};
|
|
1116
|
+
// The start section is last so the `~` rule can hide it when another section is the target.
|
|
1117
|
+
const sections = [...order.slice(1), ...order.slice(0, 1)].map(section);
|
|
1118
|
+
const csp = usesImages ? `${EXPORT_CSP}; img-src data:` : EXPORT_CSP;
|
|
1119
|
+
const html = `<!doctype html>
|
|
1120
|
+
<html lang="en">
|
|
1121
|
+
<head>
|
|
1122
|
+
<meta charset="utf-8">
|
|
1123
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1124
|
+
<meta http-equiv="Content-Security-Policy" content="${csp}">
|
|
1125
|
+
<meta name="referrer" content="no-referrer">
|
|
1126
|
+
<meta name="generator" content="mallory narrative">
|
|
1127
|
+
<title>${escapeHtml(title)}</title>
|
|
1128
|
+
<style>${EXPORT_CSS}</style>
|
|
1129
|
+
</head>
|
|
1130
|
+
<body>
|
|
1131
|
+
<h1>${escapeHtml(title)}</h1>
|
|
1132
|
+
${sections.join("\n")}
|
|
1133
|
+
</body>
|
|
1134
|
+
</html>
|
|
1135
|
+
`;
|
|
1136
|
+
if (html.length > LIMITS.exportChars) return { ok: false, html: null, bytes: 0, report: [...report, problem("error", "export-too-large", `The page would be over ${LIMITS.exportChars} characters.`)], notes: ["Not exported: the page is too large."] };
|
|
1137
|
+
return { ok, html, bytes: html.length, report, notes };
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
// ── Twine, Twee and Godot dialogue interchange ─────────────────────────────
|
|
1141
|
+
//
|
|
1142
|
+
// Reading is a conversion to this story format, never an engine: what maps onto the
|
|
1143
|
+
// supported subset (links, set/if/print, the SugarCube spelling and Harlowe's set, if,
|
|
1144
|
+
// else-if, else hooks) is converted, and everything else (tags, positions, scripts,
|
|
1145
|
+
// stylesheets, other macros) is dropped or left as text, and said so in `dropped`,
|
|
1146
|
+
// `renamed` and `problems`. Nothing here runs the input.
|
|
1147
|
+
|
|
1148
|
+
const SPECIAL = new Set(["StoryTitle", "StoryData", "StoryInit", "StoryAuthor", "StoryCaption", "StoryBanner", "StoryFooter", "StoryMenu", "StoryInterface", "StoryShare", "StorySettings", "StoryDisplayTitle", "PassageHeader", "PassageFooter", "PassageReady", "PassageDone", "StoryIncludes"]);
|
|
1149
|
+
|
|
1150
|
+
const unEntity = (s) => s.replace(/&(lt|gt|amp|quot|#39|apos|#x27);/g, (_, e) => ({ lt: "<", gt: ">", amp: "&", quot: '"', "#39": "'", apos: "'", "#x27": "'" })[e]);
|
|
1151
|
+
|
|
1152
|
+
/** A name this format can hold: `->`, `<-`, `|`, `[[`, `]]` and control characters become safe ones. */
|
|
1153
|
+
function safeName(raw) {
|
|
1154
|
+
let name = nfc(String(raw)).replace(CONTROL_G, " ").replace(/->/g, "-").replace(/<-/g, "-").replace(/\|/g, "/").replace(/\[\[/g, "(").replace(/\]\]/g, ")").replace(/\s+/g, " ").trim();
|
|
1155
|
+
if (name.length > LIMITS.name) name = name.slice(0, LIMITS.name).trim();
|
|
1156
|
+
return name || "Untitled";
|
|
1157
|
+
}
|
|
1158
|
+
const CONTROL_G = /[\u0000-\u001f\u007f]/g;
|
|
1159
|
+
|
|
1160
|
+
/** Find the end of a Harlowe hook starting at `open` (a "["); `[[` … `]]` links inside are atomic. Returns the index of the closing "]" or -1. */
|
|
1161
|
+
function hookEnd(text, open) {
|
|
1162
|
+
let depth = 0;
|
|
1163
|
+
for (let i = open; i < text.length; i++) {
|
|
1164
|
+
if (text.startsWith("[[", i)) {
|
|
1165
|
+
const close = text.indexOf("]]", i + 2);
|
|
1166
|
+
if (close < 0) return -1;
|
|
1167
|
+
i = close + 1;
|
|
1168
|
+
continue;
|
|
1169
|
+
}
|
|
1170
|
+
if (text[i] === "[") depth++;
|
|
1171
|
+
else if (text[i] === "]" && --depth === 0) return i;
|
|
1172
|
+
}
|
|
1173
|
+
return -1;
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
/** The index just past the ")" that closes the "(" at `open`, honouring quotes; -1 when it doesn't close. */
|
|
1177
|
+
function parenEnd(text, open) {
|
|
1178
|
+
let depth = 0;
|
|
1179
|
+
let quote = null;
|
|
1180
|
+
for (let i = open; i < text.length; i++) {
|
|
1181
|
+
const c = text[i];
|
|
1182
|
+
if (quote) {
|
|
1183
|
+
if (c === "\\") i++;
|
|
1184
|
+
else if (c === quote) quote = null;
|
|
1185
|
+
} else if (c === '"' || c === "'") quote = c;
|
|
1186
|
+
else if (c === "(") depth++;
|
|
1187
|
+
else if (c === ")" && --depth === 0) return i + 1;
|
|
1188
|
+
}
|
|
1189
|
+
return -1;
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
const exprOk = (src) => {
|
|
1193
|
+
try {
|
|
1194
|
+
parseExpr(src);
|
|
1195
|
+
return true;
|
|
1196
|
+
} catch {
|
|
1197
|
+
return false;
|
|
1198
|
+
}
|
|
1199
|
+
};
|
|
1200
|
+
/** Harlowe's `is not`, `is in` and `contains` spellings; only the first has a counterpart here. */
|
|
1201
|
+
const harloweExpr = (src) => src.replace(/\bis\s+not\b/g, "isnot").replace(/\bis\s+a\b/g, "is a").trim();
|
|
1202
|
+
|
|
1203
|
+
/** Convert Harlowe's (set:), (print:) and (if:)[…](else-if:)[…](else:)[…] to macros. Anything else stays text. */
|
|
1204
|
+
function fromHarlowe(text, notes) {
|
|
1205
|
+
let out = "";
|
|
1206
|
+
let i = 0;
|
|
1207
|
+
while (i < text.length) {
|
|
1208
|
+
if (text.startsWith("[[", i)) {
|
|
1209
|
+
const close = text.indexOf("]]", i + 2);
|
|
1210
|
+
const end = close < 0 ? text.length : close + 2;
|
|
1211
|
+
out += text.slice(i, end);
|
|
1212
|
+
i = end;
|
|
1213
|
+
continue;
|
|
1214
|
+
}
|
|
1215
|
+
const m = /^\((set|print|if|else-if|elseif|else):\s?/i.exec(text.slice(i, i + 20));
|
|
1216
|
+
if (!m) {
|
|
1217
|
+
out += text[i++];
|
|
1218
|
+
continue;
|
|
1219
|
+
}
|
|
1220
|
+
const kind = m[1].toLowerCase();
|
|
1221
|
+
const end = parenEnd(text, i);
|
|
1222
|
+
if (end < 0) {
|
|
1223
|
+
out += text[i++];
|
|
1224
|
+
continue;
|
|
1225
|
+
}
|
|
1226
|
+
const arg = text.slice(i + m[0].length, end - 1).trim();
|
|
1227
|
+
if (kind === "set") {
|
|
1228
|
+
const stmt = arg.replace(/^\$/, "$");
|
|
1229
|
+
if (/^\$[A-Za-z_]\w*\s+to\s+/.test(stmt) && exprOk(harloweExpr(stmt.replace(/^\$\w+\s+to\s+/, "")))) out += `<<set ${harloweExpr(stmt)}>>`;
|
|
1230
|
+
else (out += text.slice(i, end), notes.add("a (set:) that isn't a single $variable to value"));
|
|
1231
|
+
i = end;
|
|
1232
|
+
} else if (kind === "print") {
|
|
1233
|
+
if (exprOk(harloweExpr(arg))) out += `<<print ${harloweExpr(arg)}>>`;
|
|
1234
|
+
else (out += text.slice(i, end), notes.add("a (print:) that isn't a simple expression"));
|
|
1235
|
+
i = end;
|
|
1236
|
+
} else if (kind === "if") {
|
|
1237
|
+
// a chain: (if:)[…] then any (else-if:)[…] and one (else:)[…], separated by spaces only
|
|
1238
|
+
const branches = [];
|
|
1239
|
+
let at = i;
|
|
1240
|
+
let ok = true;
|
|
1241
|
+
for (;;) {
|
|
1242
|
+
const mm = /^\((if|else-if|elseif|else):\s?/i.exec(text.slice(at, at + 20));
|
|
1243
|
+
if (!mm || (branches.length === 0 && mm[1].toLowerCase() !== "if") || (branches.length > 0 && mm[1].toLowerCase() === "if")) break;
|
|
1244
|
+
const pe = parenEnd(text, at);
|
|
1245
|
+
if (pe < 0 || text[pe] !== "[") break;
|
|
1246
|
+
const he = hookEnd(text, pe);
|
|
1247
|
+
if (he < 0) break;
|
|
1248
|
+
const k = mm[1].toLowerCase();
|
|
1249
|
+
const cond = text.slice(at + mm[0].length, pe - 1).trim();
|
|
1250
|
+
if (k !== "else" && !exprOk(harloweExpr(cond))) ok = false;
|
|
1251
|
+
branches.push({ k, cond: harloweExpr(cond), body: fromHarlowe(text.slice(pe + 1, he), notes) });
|
|
1252
|
+
at = he + 1;
|
|
1253
|
+
const gap = /^[ \t]*/.exec(text.slice(at))[0].length;
|
|
1254
|
+
if (!/^\((else-if|elseif|else):/i.test(text.slice(at + gap, at + gap + 12))) break;
|
|
1255
|
+
at += gap;
|
|
1256
|
+
if (branches[branches.length - 1].k === "else") break;
|
|
1257
|
+
}
|
|
1258
|
+
if (!ok || !branches.length) (out += text[i], notes.add("an (if:) hook that isn't a plain comparison"), (at = i + 1));
|
|
1259
|
+
else out += branches.map((b, n) => `${n === 0 ? `<<if ${b.cond}>>` : b.k === "else" ? "<<else>>" : `<<elseif ${b.cond}>>`}${b.body}`).join("") + "<</if>>";
|
|
1260
|
+
i = at;
|
|
1261
|
+
} else {
|
|
1262
|
+
out += text.slice(i, end); // an else with no if before it
|
|
1263
|
+
i = end;
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
return out;
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
/** SugarCube spellings that differ from the supported ones: `<<else if>>`, `<<=expr>>`. */
|
|
1270
|
+
function fromSugarCube(text) {
|
|
1271
|
+
return text.replace(/<<else\s+if\b/gi, "<<elseif").replace(/<<-?=\s*([^>]*?)\s*>>/g, "<<print $1>>");
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
/** Twine's own markup (`''bold''`, `//italic//`) outside links and macros, as this format's. */
|
|
1275
|
+
function fromTwineMarkup(text) {
|
|
1276
|
+
return text.split(/(\[\[[^\]\n]*\]\]|<<[^\n]*?>>)/).map((seg, i) => (i % 2 ? seg : seg.replace(/''([^'\n]+)''/g, "**$1**").replace(/(^|[\s(])\/\/([^/\n]+)\/\/(?=$|[\s.,;:!?)])/g, "$1*$2*"))).join("");
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
/** Pipe links and setter links to this format's. Targets go through `nameMap`. */
|
|
1280
|
+
function fromTwineLinks(text, nameMap, dropped) {
|
|
1281
|
+
let out = "";
|
|
1282
|
+
let i = 0;
|
|
1283
|
+
while (i < text.length) {
|
|
1284
|
+
const open = text.indexOf("[[", i);
|
|
1285
|
+
if (open < 0) break;
|
|
1286
|
+
const close = text.indexOf("]]", open + 2);
|
|
1287
|
+
const nl = text.indexOf("\n", open);
|
|
1288
|
+
if (close < 0 || (nl >= 0 && nl < close)) break;
|
|
1289
|
+
let inner = text.slice(open + 2, close);
|
|
1290
|
+
let end = close + 2;
|
|
1291
|
+
const setter = inner.indexOf("][");
|
|
1292
|
+
if (setter >= 0) {
|
|
1293
|
+
// [[text|target][$x to 1]]: the setter's code is Twine's, not run here
|
|
1294
|
+
dropped.add("a setter link's code (the link itself was kept)");
|
|
1295
|
+
inner = inner.slice(0, setter);
|
|
1296
|
+
}
|
|
1297
|
+
let label;
|
|
1298
|
+
let target;
|
|
1299
|
+
const arrow = inner.lastIndexOf("->");
|
|
1300
|
+
const back = inner.indexOf("<-");
|
|
1301
|
+
const pipe = inner.indexOf("|");
|
|
1302
|
+
if (pipe >= 0 && arrow < 0 && back < 0) [label, target] = [inner.slice(0, pipe), inner.slice(pipe + 1)];
|
|
1303
|
+
else if (arrow >= 0 && back < 0) [label, target] = [inner.slice(0, arrow), inner.slice(arrow + 2)];
|
|
1304
|
+
else if (back >= 0 && arrow < 0) [target, label] = [inner.slice(0, back), inner.slice(back + 2)];
|
|
1305
|
+
else (label = target = inner.replace(/->|<-|\|/g, "-"));
|
|
1306
|
+
label = label.trim();
|
|
1307
|
+
target = target.trim();
|
|
1308
|
+
const mapped = nameMap.get(nfc(target)) ?? safeName(target);
|
|
1309
|
+
const lab = label.replace(/\|/g, "/").replace(/->|<-/g, "-").replace(/\]\]|\[\[/g, "");
|
|
1310
|
+
out += text.slice(i, open) + (lab && lab !== mapped ? `[[${lab}->${mapped}]]` : `[[${mapped}]]`);
|
|
1311
|
+
i = end;
|
|
1312
|
+
}
|
|
1313
|
+
return out + text.slice(i);
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
/** Make `passages` ([{ name, tags, body }]) into a story: specials, renames, conversions. */
|
|
1317
|
+
function twineToStory(passages, meta) {
|
|
1318
|
+
const dropped = new Set();
|
|
1319
|
+
const notes = new Set();
|
|
1320
|
+
const renamed = [];
|
|
1321
|
+
let title = meta.title ?? "";
|
|
1322
|
+
let start = meta.start ?? null;
|
|
1323
|
+
let init = "";
|
|
1324
|
+
const keep = [];
|
|
1325
|
+
for (const p of passages) {
|
|
1326
|
+
const tags = (p.tags ?? []).filter(Boolean);
|
|
1327
|
+
if (tags.includes("script") || tags.includes("stylesheet")) {
|
|
1328
|
+
dropped.add(`the ${tags.includes("script") ? "script" : "stylesheet"} passage "${p.name}" (nothing here runs a story's script or style)`);
|
|
1329
|
+
continue;
|
|
1330
|
+
}
|
|
1331
|
+
if (p.name === "StoryTitle") title = p.body.trim();
|
|
1332
|
+
else if (p.name === "StoryData") {
|
|
1333
|
+
try {
|
|
1334
|
+
const d = JSON.parse(p.body);
|
|
1335
|
+
if (typeof d?.start === "string") start = d.start;
|
|
1336
|
+
} catch {
|
|
1337
|
+
dropped.add("a StoryData passage that isn't JSON");
|
|
1338
|
+
}
|
|
1339
|
+
} else if (p.name === "StoryInit") init = p.body.trim();
|
|
1340
|
+
else if (SPECIAL.has(p.name)) dropped.add(`the special passage "${p.name}"`);
|
|
1341
|
+
else keep.push({ ...p, tags });
|
|
1342
|
+
}
|
|
1343
|
+
if (keep.some((p) => p.tags.length)) dropped.add("passage tags");
|
|
1344
|
+
if (keep.some((p) => p.position)) dropped.add("passage positions and sizes");
|
|
1345
|
+
const nameMap = new Map();
|
|
1346
|
+
const used = new Set();
|
|
1347
|
+
for (const p of keep) {
|
|
1348
|
+
let name = safeName(p.name);
|
|
1349
|
+
if (name !== p.name) renamed.push({ from: p.name, to: name });
|
|
1350
|
+
for (let n = 2; used.has(name); n++) name = `${safeName(p.name)} (${n})`.slice(0, LIMITS.name);
|
|
1351
|
+
used.add(name);
|
|
1352
|
+
nameMap.set(nfc(p.name), name);
|
|
1353
|
+
p.safe = name;
|
|
1354
|
+
}
|
|
1355
|
+
const startSafe = start !== null ? nameMap.get(nfc(start)) : undefined;
|
|
1356
|
+
if (start !== null && !startSafe) dropped.add(`the start "${start}" (no such passage; the first passage starts)`);
|
|
1357
|
+
let list = keep.slice(0, LIMITS.passages);
|
|
1358
|
+
if (keep.length > list.length) dropped.add(`${keep.length - list.length} passages over the limit of ${LIMITS.passages}`);
|
|
1359
|
+
if (startSafe) list = [...list.filter((p) => p.safe === startSafe), ...list.filter((p) => p.safe !== startSafe)];
|
|
1360
|
+
const chunks = list.map((p, n) => {
|
|
1361
|
+
let body = p.body.replace(/\r\n?/g, "\n");
|
|
1362
|
+
body = fromTwineLinks(body, nameMap, dropped);
|
|
1363
|
+
body = fromHarlowe(fromSugarCube(body), notes);
|
|
1364
|
+
body = fromTwineMarkup(body);
|
|
1365
|
+
if (n === 0 && init) body = `${fromSugarCube(init)}\n${body}`;
|
|
1366
|
+
body = body.split("\n").map((l) => (/^@(passage|asset)\b/.test(l) ? ` ${l}` : l)).join("\n").trim();
|
|
1367
|
+
return `${HEADER} ${p.safe}\n${body}`;
|
|
1368
|
+
});
|
|
1369
|
+
const story = chunks.join("\n");
|
|
1370
|
+
const problems = list.length ? analyze(story).problems : [problem("error", "no-passages", "There is nothing to read: no passages were found.")];
|
|
1371
|
+
return { ok: list.length > 0 && !problems.some((q) => q.code === "no-passages"), story: list.length ? story : "", title, start: list.length ? list[0].safe : null, renamed, dropped: [...dropped], notes: [...notes], problems };
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
/**
|
|
1375
|
+
* Read Twee 3 (`:: Name [tags] {metadata}` headers) as a story. StoryTitle and StoryData
|
|
1376
|
+
* (the start passage) are used; StoryInit's statements go at the start of the start
|
|
1377
|
+
* passage; scripts, stylesheets, other special passages, tags and positions are dropped.
|
|
1378
|
+
* @returns {{ ok: boolean, story: string, title: string, start: string|null, renamed: object[], dropped: string[], notes: string[], problems: object[] }}
|
|
1379
|
+
*/
|
|
1380
|
+
export function fromTwee(text) {
|
|
1381
|
+
if (typeof text !== "string") return { ok: false, story: "", title: "", start: null, renamed: [], dropped: [], notes: [], problems: [problem("error", "not-text", "Twee is text.")] };
|
|
1382
|
+
const lines = text.replace(/^/, "").replace(/\r\n?/g, "\n").split("\n");
|
|
1383
|
+
const passages = [];
|
|
1384
|
+
let cur = null;
|
|
1385
|
+
for (const line of lines) {
|
|
1386
|
+
if (line.startsWith("::")) {
|
|
1387
|
+
const h = parseTweeHeader(line.slice(2));
|
|
1388
|
+
cur = { ...h, body: [] };
|
|
1389
|
+
passages.push(cur);
|
|
1390
|
+
} else if (cur) cur.body.push(line.startsWith("\\::") ? line.slice(1) : line);
|
|
1391
|
+
}
|
|
1392
|
+
return twineToStory(passages.map((p) => ({ ...p, body: p.body.join("\n").replace(/^\n+|\s+$/g, "") })), {});
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
/** `Name [tag tag] {"position":"1,2"}` after the "::", with Twee's backslash escapes in the name. */
|
|
1396
|
+
function parseTweeHeader(rest) {
|
|
1397
|
+
let name = "";
|
|
1398
|
+
let i = 0;
|
|
1399
|
+
const s = rest.trim();
|
|
1400
|
+
for (; i < s.length; i++) {
|
|
1401
|
+
if (s[i] === "\\" && i + 1 < s.length) name += s[++i];
|
|
1402
|
+
else if (s[i] === "[" || s[i] === "{") break;
|
|
1403
|
+
else name += s[i];
|
|
1404
|
+
}
|
|
1405
|
+
const tail = s.slice(i);
|
|
1406
|
+
const tm = /^\[([^\]]*)\]/.exec(tail);
|
|
1407
|
+
const tags = tm ? tm[1].split(/\s+/).filter(Boolean) : [];
|
|
1408
|
+
const jm = /\{[^]*\}\s*$/.exec(tail.slice(tm ? tm[0].length : 0));
|
|
1409
|
+
let position = null;
|
|
1410
|
+
if (jm) {
|
|
1411
|
+
try {
|
|
1412
|
+
position = JSON.parse(jm[0]).position ?? null;
|
|
1413
|
+
} catch {
|
|
1414
|
+
position = null;
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
return { name: name.trim(), tags, position };
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
// A sandbox module imports nothing, so this is its own copy of src/util/regexp.js escapeRegExp: a name interpolated into a RegExp is text, never syntax.
|
|
1421
|
+
const escapeRegExp = (text) => String(text).replace(/[.*+?^${}()|[\]\\/-]/g, "\\$&");
|
|
1422
|
+
|
|
1423
|
+
/**
|
|
1424
|
+
* Read a published Twine story (the HTML file Twine makes) as a story, from its
|
|
1425
|
+
* `<tw-passagedata>` elements. The page is only read as text: its scripts and styles are
|
|
1426
|
+
* never run or kept.
|
|
1427
|
+
*/
|
|
1428
|
+
export function fromTwineHtml(html) {
|
|
1429
|
+
const bad = { ok: false, story: "", title: "", start: null, renamed: [], dropped: [], notes: [], problems: [problem("error", "not-twine", "This isn't a published Twine story (no <tw-storydata> found).")] };
|
|
1430
|
+
if (typeof html !== "string") return bad;
|
|
1431
|
+
const sd = /<tw-storydata\b([^>]*)>/i.exec(html);
|
|
1432
|
+
if (!sd) return bad;
|
|
1433
|
+
const attr = (tag, name) => {
|
|
1434
|
+
const m = new RegExp(`\\s${escapeRegExp(name)}\\s*=\\s*("([^"]*)"|'([^']*)')`, "i").exec(tag);
|
|
1435
|
+
return m ? unEntity(m[2] ?? m[3]) : null;
|
|
1436
|
+
};
|
|
1437
|
+
const passages = [];
|
|
1438
|
+
let startNode = attr(sd[1], "startnode");
|
|
1439
|
+
let start = null;
|
|
1440
|
+
for (const m of html.matchAll(/<tw-passagedata\b([^>]*)>([^]*?)<\/tw-passagedata>/gi)) {
|
|
1441
|
+
const name = attr(m[1], "name") ?? "";
|
|
1442
|
+
passages.push({ name, tags: (attr(m[1], "tags") ?? "").split(/\s+/).filter(Boolean), position: attr(m[1], "position"), body: unEntity(m[2]) });
|
|
1443
|
+
if (startNode !== null && attr(m[1], "pid") === startNode) start = name;
|
|
1444
|
+
}
|
|
1445
|
+
const result = twineToStory(passages, { title: attr(sd[1], "name") ?? "", start });
|
|
1446
|
+
if (/<script\b/i.test(html)) result.dropped.push("the page's scripts and styles (never run)");
|
|
1447
|
+
return result;
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
const uuidOf = (text) => {
|
|
1451
|
+
const hex = [0, 1, 2, 3].map((n) => Math.imul(parseInt(fnv(`${n}:${text}`), 36) | 1, 2654435761) >>> 0).map((n) => n.toString(16).padStart(8, "0")).join("");
|
|
1452
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-A${hex.slice(17, 20)}-${hex.slice(20, 32)}`.toUpperCase();
|
|
1453
|
+
};
|
|
1454
|
+
|
|
1455
|
+
/** This format's markup as SugarCube's (`''bold''`, `//italic//`), outside links and macros. */
|
|
1456
|
+
function toSugarCubeMarkup(text) {
|
|
1457
|
+
return text.split(/(\[\[[^\]\n]*\]\]|<<[^\n]*?>>)/).map((seg, i) => (i % 2 ? seg : seg.replace(/`([^`\n]+)`/g, "{{{$1}}}").replace(/\*\*([^*\n]+)\*\*/g, "''$1''").replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g, "$1//$2//"))).join("");
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1460
|
+
const tweeEscape = (name) => name.replace(/[\\[\]{}]/g, (c) => `\\${c}`);
|
|
1461
|
+
|
|
1462
|
+
/**
|
|
1463
|
+
* Write a story as Twee 3 for Twine (format SugarCube): StoryTitle, StoryData with a stable
|
|
1464
|
+
* ifid and the start passage, then each passage with a grid position. Links, set/if/print
|
|
1465
|
+
* macros and text carry over (markup becomes SugarCube's); an image becomes an `<img>`. Refused
|
|
1466
|
+
* while the story has errors.
|
|
1467
|
+
* @returns {{ ok: boolean, twee: string|null, report: object[], notes: string[] }}
|
|
1468
|
+
*/
|
|
1469
|
+
export function toTwee(source, options = {}) {
|
|
1470
|
+
const a = typeof source === "string" ? analyze(source, options) : source;
|
|
1471
|
+
if (!a.ok) return { ok: false, twee: null, report: a.problems, notes: ["Not exported: fix the errors in the report first."] };
|
|
1472
|
+
const title = String(options.title ?? "A story").slice(0, 120);
|
|
1473
|
+
const images = new Map(a.assets.map((x) => [x.name, x]));
|
|
1474
|
+
const body = (p) => {
|
|
1475
|
+
let text = p.text.replace(/!\[([^\]\n]*)\]\(([^)\n]+)\)/g, (whole, alt, ref) => (images.has(nfc(ref.trim())) ? `<img src="${images.get(nfc(ref.trim())).uri}" alt="${escapeHtml(alt)}">` : whole));
|
|
1476
|
+
text = toSugarCubeMarkup(text).replace(/\\(\[\[)/g, "$1");
|
|
1477
|
+
return text.split("\n").map((l) => (l.startsWith("::") ? `\\${l}` : l)).join("\n");
|
|
1478
|
+
};
|
|
1479
|
+
const data = JSON.stringify({ ifid: uuidOf(`${title}\n${a.passages.map((p) => p.name).join("\n")}`), format: "SugarCube", "format-version": "2.37.3", start: a.start, zoom: 1 }, null, 2);
|
|
1480
|
+
const blocks = [`:: StoryTitle\n${title}`, `:: StoryData\n${data}`];
|
|
1481
|
+
a.passages.forEach((p, i) => blocks.push(`:: ${tweeEscape(p.name)} ${JSON.stringify({ position: `${100 + (i % 6) * 150},${100 + Math.floor(i / 6) * 150}`, size: "100,100" })}\n${body(p)}`));
|
|
1482
|
+
return { ok: true, twee: `${blocks.join("\n\n")}\n`, report: a.problems, notes: ["Macros other than set, if and print are not part of this format and stay as text.", "Twine reads this as a SugarCube story."] };
|
|
1483
|
+
}
|
|
1484
|
+
|
|
1485
|
+
// Godot Dialogue Manager (.dialogue): `~ title`, lines, `- choice => title`, `=> title`, `=> END`.
|
|
1486
|
+
|
|
1487
|
+
/**
|
|
1488
|
+
* Read a Dialogue Manager resource as a story: each `~ title` is a passage; spoken lines are
|
|
1489
|
+
* text; `- text => target` is a choice and `=> target` a link (`=> END` ends). Comments are
|
|
1490
|
+
* skipped; set, if, do and other logic lines are dropped and listed.
|
|
1491
|
+
*/
|
|
1492
|
+
export function fromGodotDialogue(text) {
|
|
1493
|
+
const fail = (message) => ({ ok: false, story: "", title: "", start: null, renamed: [], dropped: [], notes: [], problems: [problem("error", "not-dialogue", message)] });
|
|
1494
|
+
if (typeof text !== "string") return fail("A dialogue resource is text.");
|
|
1495
|
+
const dropped = new Set();
|
|
1496
|
+
const out = [];
|
|
1497
|
+
let cur = null;
|
|
1498
|
+
const nameMap = (t) => safeName(t.trim());
|
|
1499
|
+
for (const raw of text.replace(/\r\n?/g, "\n").split("\n")) {
|
|
1500
|
+
const line = raw.trim();
|
|
1501
|
+
const title = /^~\s+(\S.*)$/.exec(line);
|
|
1502
|
+
if (title) {
|
|
1503
|
+
cur = { name: nameMap(title[1]), lines: [] };
|
|
1504
|
+
out.push(cur);
|
|
1505
|
+
continue;
|
|
1506
|
+
}
|
|
1507
|
+
if (!cur || !line || line.startsWith("#")) continue;
|
|
1508
|
+
const choice = /^-\s+(.*?)\s*(\[if[^\]]*\])?\s*=>(<)?\s*(\S.*)$/.exec(line);
|
|
1509
|
+
const jump = /^=>(<)?\s*(\S.*)$/.exec(line);
|
|
1510
|
+
if (choice) {
|
|
1511
|
+
if (choice[2]) dropped.add(`a choice condition ${choice[2]}`);
|
|
1512
|
+
const target = choice[4].trim();
|
|
1513
|
+
if (!/^END!?$/.test(target)) cur.lines.push(`[[${choice[1].replace(/->|<-|\||\[\[|\]\]/g, " ").trim() || target}->${nameMap(target)}]]`);
|
|
1514
|
+
} else if (jump) {
|
|
1515
|
+
const target = jump[2].trim();
|
|
1516
|
+
if (!/^END!?$/.test(target)) cur.lines.push(`[[Continue->${nameMap(target)}]]`);
|
|
1517
|
+
} else if (/^(set|if|elif|else|do|using|import|match|when|while|endif)\b/.test(line)) dropped.add(`logic: ${line.slice(0, 40)}`);
|
|
1518
|
+
else if (/^-\s/.test(line)) cur.lines.push(line.replace(/^-\s+/, "").replace(/\[\[/g, "\\[["));
|
|
1519
|
+
else cur.lines.push(line.replace(/\[\[/g, "\\[[").replace(/\[\/?[a-z#][^\]]*\]/gi, (m) => (dropped.add("BBCode and mutation tags in lines"), "")).trim());
|
|
1520
|
+
}
|
|
1521
|
+
if (!out.length) return fail('No "~ title" lines: a dialogue resource has at least one title.');
|
|
1522
|
+
const story = out.map((p) => `${HEADER} ${p.name}\n${p.lines.join("\n")}`).join("\n");
|
|
1523
|
+
const problems = analyze(story).problems;
|
|
1524
|
+
return { ok: true, story, title: "", start: out[0].name, renamed: [], dropped: [...dropped], notes: [], problems };
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
/**
|
|
1528
|
+
* Write a story as a Dialogue Manager resource. Each passage is a `~ title` (spaces become
|
|
1529
|
+
* underscores) with its text (markup and macros removed, a link shown as its label) and a
|
|
1530
|
+
* `- label => title` line per link; an ending is `=> END`. Variables and conditions aren't
|
|
1531
|
+
* carried over (the choices of every branch are listed).
|
|
1532
|
+
*/
|
|
1533
|
+
export function toGodotDialogue(source, options = {}) {
|
|
1534
|
+
const a = typeof source === "string" ? analyze(source, options) : source;
|
|
1535
|
+
if (!a.ok) return { ok: false, dialogue: null, report: a.problems, notes: ["Not exported: fix the errors in the report first."] };
|
|
1536
|
+
const id = (name) => name.replace(/[^\p{L}\p{N}_]+/gu, "_");
|
|
1537
|
+
const seen = new Map();
|
|
1538
|
+
for (const p of a.passages) {
|
|
1539
|
+
let t = id(p.name);
|
|
1540
|
+
for (let n = 2; [...seen.values()].includes(t); n++) t = `${id(p.name)}_${n}`;
|
|
1541
|
+
seen.set(p.name, t);
|
|
1542
|
+
}
|
|
1543
|
+
const plain = (text) => text.replace(/!\[[^\]\n]*\]\([^)\n]+\)/g, "").replace(/\\\[\[/g, "[[").replace(/\[\[([^\]\n]*)\]\]/g, (_, inner) => {
|
|
1544
|
+
const arrow = inner.lastIndexOf("->");
|
|
1545
|
+
const back = inner.indexOf("<-");
|
|
1546
|
+
return (arrow >= 0 ? inner.slice(0, arrow) : back >= 0 ? inner.slice(back + 2) : inner).trim();
|
|
1547
|
+
}).replace(/\*\*([^*\n]+)\*\*/g, "$1").replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g, "$1$2").replace(/`([^`\n]+)`/g, "$1");
|
|
1548
|
+
const blocks = a.passages.map((p) => {
|
|
1549
|
+
const m = macrosOf(p);
|
|
1550
|
+
const lines = (m.errors.length ? p.text : m.plain).split(/\n+/).map((l) => plain(l).trim()).filter(Boolean);
|
|
1551
|
+
const choices = p.links.slice(0, LIMITS.choices).map((l) => `- ${plain(l.label).replace(/=>/g, "-").trim() || l.target} => ${seen.get(l.target)}`);
|
|
1552
|
+
return [`~ ${seen.get(p.name)}`, ...lines.map((l) => (/^[-~=#]/.test(l) ? `\\${l}` : l)), ...(choices.length ? choices : ["=> END"])].join("\n");
|
|
1553
|
+
});
|
|
1554
|
+
return { ok: true, dialogue: `${blocks.join("\n\n")}\n`, report: a.problems, notes: ["Variables, conditions and macros aren't carried over; every branch's choices are listed."] };
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1557
|
+
export default Object.freeze({ LIMITS, HEADER, ASSET_HEADER, EXPORT_CSP, escapeHtml, nameProblem, parseStory, parseLinks, analyze, renamePassage, replay, pathTo, step, save, load, play, renderText, graphSvg, exportHtml, fromTwee, toTwee, fromTwineHtml, fromGodotDialogue, toGodotDialogue });
|