@johnhenry/mallory-cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (760) hide show
  1. package/README.md +60 -2
  2. package/bin/mallory.mjs +51 -0
  3. package/package.json +51 -4
  4. package/src/a2a/client.js +511 -0
  5. package/src/a2a/demo-agent.js +396 -0
  6. package/src/a2a/hub.js +578 -0
  7. package/src/a2a/settings.js +88 -0
  8. package/src/a2a/task.js +358 -0
  9. package/src/acp/client.js +573 -0
  10. package/src/acp/demo-agent.js +332 -0
  11. package/src/acp/hub.js +632 -0
  12. package/src/acp/settings.js +78 -0
  13. package/src/actions/map.js +524 -0
  14. package/src/agent/cloud.js +77 -0
  15. package/src/agent/compact.js +84 -0
  16. package/src/agent/constants.js +39 -0
  17. package/src/agent/diff.js +101 -0
  18. package/src/agent/fork.js +159 -0
  19. package/src/agent/grounding.js +73 -0
  20. package/src/agent/guards.js +129 -0
  21. package/src/agent/local-transport.js +152 -0
  22. package/src/agent/loop.js +479 -0
  23. package/src/agent/park-store.js +77 -0
  24. package/src/agent/park.js +76 -0
  25. package/src/agent/ports.js +28 -0
  26. package/src/agent/providers.js +591 -0
  27. package/src/agent/restart.js +51 -0
  28. package/src/agent/router.js +380 -0
  29. package/src/agent/run.js +861 -0
  30. package/src/agent/tools.js +247 -0
  31. package/src/agent-library/engine.js +43 -0
  32. package/src/ai/bridge.js +155 -0
  33. package/src/ai/policy.js +131 -0
  34. package/src/aimatey/vendor.js +18 -0
  35. package/src/audio/container-duration.js +35 -0
  36. package/src/audio/instruments.js +776 -0
  37. package/src/audio/lanes.js +230 -0
  38. package/src/audio/patch.js +1410 -0
  39. package/src/audio/plan.js +276 -0
  40. package/src/audio/rack.js +1006 -0
  41. package/src/audio/sample-trim.js +293 -0
  42. package/src/audio/soundfont.js +243 -0
  43. package/src/audio/take-store.js +87 -0
  44. package/src/audio/takes.js +129 -0
  45. package/src/audio/wav.js +170 -0
  46. package/src/audio/zzfx.js +333 -0
  47. package/src/autonomy/bundle.js +207 -0
  48. package/src/autonomy/confine.js +61 -0
  49. package/src/autonomy/enforce.js +155 -0
  50. package/src/autonomy/file-kv.js +88 -0
  51. package/src/autonomy/ledger.js +203 -0
  52. package/src/autonomy/pins.js +50 -0
  53. package/src/autonomy/psl/index.js +32 -0
  54. package/src/autonomy/psl/suffixes.json +1 -0
  55. package/src/autonomy/record.js +28 -0
  56. package/src/autonomy/routines.js +107 -0
  57. package/src/autonomy/server.js +175 -0
  58. package/src/autonomy/signer-node.js +167 -0
  59. package/src/autonomy/store.js +43 -0
  60. package/src/autonomy/unattended.js +13 -0
  61. package/src/bytes/bytes.js +378 -0
  62. package/src/calc/syntax.js +125 -0
  63. package/src/calc/tex.js +28 -0
  64. package/src/calendar/vendor.js +2 -0
  65. package/src/clipboard.js +130 -0
  66. package/src/clsh/clsh.js +3417 -0
  67. package/src/codec/capnp.js +1804 -0
  68. package/src/codec/core.js +2043 -0
  69. package/src/codec/vendor/avro.js +136 -0
  70. package/src/codec/vendor/cbor.js +25 -0
  71. package/src/codec/vendor/flatbuffers.js +206 -0
  72. package/src/codec/vendor/msgpack.js +9 -0
  73. package/src/codec/vendor/protobuf.js +53 -0
  74. package/src/delegation/caps.js +60 -0
  75. package/src/delegation/config.js +32 -0
  76. package/src/device/model.js +246 -0
  77. package/src/device/recording.js +198 -0
  78. package/src/device/stream-model.js +151 -0
  79. package/src/documents/documents.js +1224 -0
  80. package/src/effects/catalog.js +63 -0
  81. package/src/effects/extras.js +133 -0
  82. package/src/effects/parse.js +339 -0
  83. package/src/embed/protocol.js +131 -0
  84. package/src/env/env.js +159 -0
  85. package/src/exact/vendor.js +45 -0
  86. package/src/example-meta.js +164 -0
  87. package/src/examples.js +94 -0
  88. package/src/export/canvas-image.js +217 -0
  89. package/src/export/expr-latex-lazy.js +8 -0
  90. package/src/export/formats.js +322 -0
  91. package/src/export/latex.js +183 -0
  92. package/src/export/pane.js +184 -0
  93. package/src/export/value.js +452 -0
  94. package/src/export/zip.js +214 -0
  95. package/src/ext/access.js +58 -0
  96. package/src/ext/btasks.js +225 -0
  97. package/src/ext/client.js +209 -0
  98. package/src/ext/tools.js +69 -0
  99. package/src/ext/view.js +105 -0
  100. package/src/ext/webmcp-tabs.js +299 -0
  101. package/src/files/archive.js +232 -0
  102. package/src/files/files.js +317 -0
  103. package/src/formats/json.js +24 -0
  104. package/src/formats/jupyter.js +188 -0
  105. package/src/formats/markdown.js +254 -0
  106. package/src/formats/n8n.js +276 -0
  107. package/src/formats/node-red.js +363 -0
  108. package/src/formats/registry.js +177 -0
  109. package/src/formats/rivet.js +259 -0
  110. package/src/formats/shared.js +98 -0
  111. package/src/formats/structure.js +182 -0
  112. package/src/formats/yaml.js +127 -0
  113. package/src/frame/frame.js +962 -0
  114. package/src/frame/vendor.js +1484 -0
  115. package/src/gate/audit.js +116 -0
  116. package/src/gate/gate.js +365 -0
  117. package/src/gate/policy.js +295 -0
  118. package/src/gate/scripted.js +110 -0
  119. package/src/gate/seams.js +32 -0
  120. package/src/gate/store.js +66 -0
  121. package/src/geometry/model.js +533 -0
  122. package/src/grant-key.js +149 -0
  123. package/src/graph/model.js +381 -0
  124. package/src/headless/a2a-push.js +123 -0
  125. package/src/headless/channels/config.js +142 -0
  126. package/src/headless/channels/connectors.js +283 -0
  127. package/src/headless/channels/index.js +257 -0
  128. package/src/headless/channels/mail.js +197 -0
  129. package/src/headless/channels/mailnet.js +223 -0
  130. package/src/headless/channels/platforms.js +194 -0
  131. package/src/headless/channels/replay.js +49 -0
  132. package/src/headless/cli.js +1397 -0
  133. package/src/headless/companion-client.js +182 -0
  134. package/src/headless/cost-cli.js +177 -0
  135. package/src/headless/deprecations-cli.js +102 -0
  136. package/src/headless/examples.js +48 -0
  137. package/src/headless/ffmpeg-exec.js +217 -0
  138. package/src/headless/gateways/config.js +213 -0
  139. package/src/headless/gateways/homeassistant.js +159 -0
  140. package/src/headless/gateways/index.js +121 -0
  141. package/src/headless/gateways/matter.js +150 -0
  142. package/src/headless/gateways/mqtt-client.js +177 -0
  143. package/src/headless/gateways/mqtt.js +70 -0
  144. package/src/headless/gateways/netway.js +226 -0
  145. package/src/headless/gateways/serverpod-worker.mjs +16 -0
  146. package/src/headless/gateways/serverpod.js +71 -0
  147. package/src/headless/gateways/util.js +27 -0
  148. package/src/headless/grant-cli.js +208 -0
  149. package/src/headless/guard.js +125 -0
  150. package/src/headless/guards.js +124 -0
  151. package/src/headless/machine-cli.js +853 -0
  152. package/src/headless/mcp-endpoint.js +287 -0
  153. package/src/headless/mcp-roots.js +38 -0
  154. package/src/headless/model-endpoint.js +88 -0
  155. package/src/headless/net.js +151 -0
  156. package/src/headless/node.js +263 -0
  157. package/src/headless/npm-tarball.js +29 -0
  158. package/src/headless/operator-page.js +112 -0
  159. package/src/headless/operator.js +242 -0
  160. package/src/headless/people.js +34 -0
  161. package/src/headless/pkg-cli.js +1103 -0
  162. package/src/headless/pkg-serve.js +138 -0
  163. package/src/headless/process-worker.js +88 -0
  164. package/src/headless/runner-remote.js +477 -0
  165. package/src/headless/sandbox-child.mjs +21 -0
  166. package/src/headless/scheduled.js +557 -0
  167. package/src/headless/serve-stream.js +97 -0
  168. package/src/headless/serve.js +2238 -0
  169. package/src/headless/short-links.js +158 -0
  170. package/src/headless/static-dirs.js +207 -0
  171. package/src/headless/trust-file.js +51 -0
  172. package/src/headless/watch.js +291 -0
  173. package/src/headless/ws-connect.js +65 -0
  174. package/src/headless/ws-connections.js +44 -0
  175. package/src/headless/ws-echo.js +150 -0
  176. package/src/headless/ws-proxy.js +354 -0
  177. package/src/headless/ws-ticket.js +48 -0
  178. package/src/hooks/config.js +50 -0
  179. package/src/hooks/engine.js +189 -0
  180. package/src/input/log.js +613 -0
  181. package/src/input/player.js +217 -0
  182. package/src/input/replay.js +209 -0
  183. package/src/jth/vendor.js +28 -0
  184. package/src/ledger/tx.js +94 -0
  185. package/src/machine/apply.js +193 -0
  186. package/src/machine/diff.js +168 -0
  187. package/src/machine/drive.js +296 -0
  188. package/src/machine/engine.js +478 -0
  189. package/src/machine/files-tool.js +76 -0
  190. package/src/machine/lint.js +139 -0
  191. package/src/machine/llmtm-trace.js +117 -0
  192. package/src/machine/llmtm.js +475 -0
  193. package/src/machine/otel.js +80 -0
  194. package/src/machine/pane-provider.js +51 -0
  195. package/src/machine/propose.js +159 -0
  196. package/src/machine/random.js +52 -0
  197. package/src/machine/risk.js +107 -0
  198. package/src/machine/session.js +1017 -0
  199. package/src/machine/shell-tool.js +45 -0
  200. package/src/machine/tape.js +349 -0
  201. package/src/machine/templates.js +104 -0
  202. package/src/machine/trace.js +664 -0
  203. package/src/machine/view.js +73 -0
  204. package/src/machine/vm-tool.js +47 -0
  205. package/src/machine/watchdog.js +46 -0
  206. package/src/mcp/app-args.js +51 -0
  207. package/src/mcp/app-run.js +56 -0
  208. package/src/mcp/apps.js +468 -0
  209. package/src/mcp/cache.js +232 -0
  210. package/src/mcp/client.js +507 -0
  211. package/src/mcp/demo-app.js +183 -0
  212. package/src/mcp/demo-server.js +602 -0
  213. package/src/mcp/elicitation.js +116 -0
  214. package/src/mcp/hub.js +1326 -0
  215. package/src/mcp/roots.js +139 -0
  216. package/src/mcp/sampling.js +105 -0
  217. package/src/mcp/settings.js +125 -0
  218. package/src/mcp/tape.js +292 -0
  219. package/src/mcp/uri-template.js +156 -0
  220. package/src/mcp/wsh-client.js +164 -0
  221. package/src/media/animated-codec.js +7 -0
  222. package/src/media/animated.js +623 -0
  223. package/src/media/compare-agent.js +70 -0
  224. package/src/media/compare-job.js +63 -0
  225. package/src/media/compare-page.js +296 -0
  226. package/src/media/compare-worker.js +14 -0
  227. package/src/media/compare.js +600 -0
  228. package/src/media/contract.js +62 -0
  229. package/src/media/decode-frame.js +57 -0
  230. package/src/media/decode-pool.js +188 -0
  231. package/src/media/ffmpeg-edit.js +344 -0
  232. package/src/media/ffmpeg-wasm-client.js +121 -0
  233. package/src/media/ffmpeg-wasm-session.js +79 -0
  234. package/src/media/ffmpeg-wasm.js +139 -0
  235. package/src/media/ffmpeg-worker.js +23 -0
  236. package/src/media/ffmpeg.js +903 -0
  237. package/src/media/helpers.js +419 -0
  238. package/src/media/keep.js +108 -0
  239. package/src/media/metadata-worker.js +16 -0
  240. package/src/media/metadata.js +2518 -0
  241. package/src/media/mime.js +102 -0
  242. package/src/media/page-decode.js +74 -0
  243. package/src/media/persist.js +114 -0
  244. package/src/media/png.js +226 -0
  245. package/src/media/sample-input.js +67 -0
  246. package/src/media/store.js +86 -0
  247. package/src/media/wav.js +109 -0
  248. package/src/midi/mappings.js +250 -0
  249. package/src/midi/message.js +125 -0
  250. package/src/model/action-hub.js +143 -0
  251. package/src/model/adapters.js +284 -0
  252. package/src/model/agent-runs.js +12 -0
  253. package/src/model/arrange.js +308 -0
  254. package/src/model/automation-clock.js +494 -0
  255. package/src/model/automation.js +653 -0
  256. package/src/model/batches.js +78 -0
  257. package/src/model/binary-view.js +195 -0
  258. package/src/model/breakpoints.js +392 -0
  259. package/src/model/calc-settings.js +65 -0
  260. package/src/model/calendar.js +254 -0
  261. package/src/model/canvas-id.js +5 -0
  262. package/src/model/canvas.js +5048 -0
  263. package/src/model/channel-names.js +29 -0
  264. package/src/model/channels.js +692 -0
  265. package/src/model/chart-clock.js +631 -0
  266. package/src/model/chart-code.js +69 -0
  267. package/src/model/codecs.js +60 -0
  268. package/src/model/companion-access.js +271 -0
  269. package/src/model/companion-pane.js +50 -0
  270. package/src/model/composite.js +324 -0
  271. package/src/model/context.js +380 -0
  272. package/src/model/controls.js +231 -0
  273. package/src/model/converter-presets.js +368 -0
  274. package/src/model/cost.js +580 -0
  275. package/src/model/curve-transform.js +122 -0
  276. package/src/model/cycles.js +176 -0
  277. package/src/model/debug-log.js +168 -0
  278. package/src/model/decision-clock.js +100 -0
  279. package/src/model/decisions.js +265 -0
  280. package/src/model/desk.js +87 -0
  281. package/src/model/device-hub.js +400 -0
  282. package/src/model/diff.js +445 -0
  283. package/src/model/emit-events.js +179 -0
  284. package/src/model/errors.js +238 -0
  285. package/src/model/event-presets.js +297 -0
  286. package/src/model/events.js +1303 -0
  287. package/src/model/explicit-setters.js +139 -0
  288. package/src/model/field-mapping.js +623 -0
  289. package/src/model/files-pane.js +263 -0
  290. package/src/model/flow-idle.js +89 -0
  291. package/src/model/foreach.js +549 -0
  292. package/src/model/frame-loop.js +71 -0
  293. package/src/model/frame-pressure.js +180 -0
  294. package/src/model/function-scaffold.js +1000 -0
  295. package/src/model/geometry-settings.js +54 -0
  296. package/src/model/goals.js +176 -0
  297. package/src/model/graph-settings.js +76 -0
  298. package/src/model/grid-widget.js +175 -0
  299. package/src/model/groups.js +332 -0
  300. package/src/model/hash.js +21 -0
  301. package/src/model/history.js +259 -0
  302. package/src/model/http-copy.js +88 -0
  303. package/src/model/http-send-companion.js +110 -0
  304. package/src/model/http-send.js +163 -0
  305. package/src/model/http-tap.js +521 -0
  306. package/src/model/http-tools.js +1138 -0
  307. package/src/model/import-lock.js +78 -0
  308. package/src/model/imports.js +258 -0
  309. package/src/model/infer-outputs.js +822 -0
  310. package/src/model/ink-connect.js +150 -0
  311. package/src/model/ink-diff.js +75 -0
  312. package/src/model/ink-gone.js +71 -0
  313. package/src/model/ink-route.js +120 -0
  314. package/src/model/ink-svg.js +206 -0
  315. package/src/model/ink.js +739 -0
  316. package/src/model/input-log-hub.js +456 -0
  317. package/src/model/input-split.js +69 -0
  318. package/src/model/json-schema-host.js +9 -0
  319. package/src/model/json-schema.js +368 -0
  320. package/src/model/jth.js +78 -0
  321. package/src/model/latex-expr.js +528 -0
  322. package/src/model/layout-history.js +120 -0
  323. package/src/model/lazy-map.js +88 -0
  324. package/src/model/ledger-pane.js +101 -0
  325. package/src/model/legacy-viaframe.js +90 -0
  326. package/src/model/lessons.js +448 -0
  327. package/src/model/links.js +981 -0
  328. package/src/model/live.js +411 -0
  329. package/src/model/math-widget.js +53 -0
  330. package/src/model/memory-settings.js +33 -0
  331. package/src/model/midi-controls.js +350 -0
  332. package/src/model/nl-time.js +408 -0
  333. package/src/model/notebook.js +137 -0
  334. package/src/model/pane-view-store.js +15 -0
  335. package/src/model/partial.js +115 -0
  336. package/src/model/pause-clock.js +53 -0
  337. package/src/model/peer-pane.js +32 -0
  338. package/src/model/persist-state.js +290 -0
  339. package/src/model/person-only.js +122 -0
  340. package/src/model/pin.js +209 -0
  341. package/src/model/plot-3d.js +213 -0
  342. package/src/model/plot-series.js +157 -0
  343. package/src/model/plot-settings.js +531 -0
  344. package/src/model/ports.js +312 -0
  345. package/src/model/presentation.js +222 -0
  346. package/src/model/preset-apply.js +316 -0
  347. package/src/model/preset-banks.js +335 -0
  348. package/src/model/preset-morph.js +263 -0
  349. package/src/model/preset-ops.js +205 -0
  350. package/src/model/preset-player.js +283 -0
  351. package/src/model/preset-states.js +172 -0
  352. package/src/model/profile-settings.js +109 -0
  353. package/src/model/promote.js +103 -0
  354. package/src/model/protected.js +10 -0
  355. package/src/model/proxy-log.js +230 -0
  356. package/src/model/proxy.js +367 -0
  357. package/src/model/quantity-widget.js +61 -0
  358. package/src/model/queue-book.js +359 -0
  359. package/src/model/quick-add.js +224 -0
  360. package/src/model/rate-limit.js +313 -0
  361. package/src/model/rate.js +95 -0
  362. package/src/model/recovery.js +216 -0
  363. package/src/model/rename-follow.js +113 -0
  364. package/src/model/repeater.js +1126 -0
  365. package/src/model/retention.js +664 -0
  366. package/src/model/route-edit.js +132 -0
  367. package/src/model/router.js +155 -0
  368. package/src/model/runaway.js +232 -0
  369. package/src/model/runlog.js +1033 -0
  370. package/src/model/runners/a2a.js +2 -0
  371. package/src/model/runners/acp.js +2 -0
  372. package/src/model/runners/actions.js +4 -0
  373. package/src/model/runners/agent.js +4 -0
  374. package/src/model/runners/audio.js +21 -0
  375. package/src/model/runners/automation.js +2 -0
  376. package/src/model/runners/calc.js +23 -0
  377. package/src/model/runners/catch.js +10 -0
  378. package/src/model/runners/codec.js +24 -0
  379. package/src/model/runners/companion-run.js +2 -0
  380. package/src/model/runners/device.js +7 -0
  381. package/src/model/runners/dom.js +13 -0
  382. package/src/model/runners/effects.js +2 -0
  383. package/src/model/runners/embed.js +11 -0
  384. package/src/model/runners/eval.js +2 -0
  385. package/src/model/runners/files.js +19 -0
  386. package/src/model/runners/geometry.js +23 -0
  387. package/src/model/runners/goals.js +18 -0
  388. package/src/model/runners/graph.js +23 -0
  389. package/src/model/runners/html.js +2 -0
  390. package/src/model/runners/http-proxy.js +185 -0
  391. package/src/model/runners/http-send.js +61 -0
  392. package/src/model/runners/http-static.js +83 -0
  393. package/src/model/runners/http-tap.js +26 -0
  394. package/src/model/runners/http.js +40 -0
  395. package/src/model/runners/import.js +2 -0
  396. package/src/model/runners/index.js +74 -0
  397. package/src/model/runners/input.js +14 -0
  398. package/src/model/runners/inputlog.js +7 -0
  399. package/src/model/runners/ledger.js +15 -0
  400. package/src/model/runners/machine.js +4 -0
  401. package/src/model/runners/mcp.js +2 -0
  402. package/src/model/runners/mcpapp.js +2 -0
  403. package/src/model/runners/media.js +18 -0
  404. package/src/model/runners/memory.js +28 -0
  405. package/src/model/runners/mesh-inspect.js +13 -0
  406. package/src/model/runners/peer.js +14 -0
  407. package/src/model/runners/plot.js +22 -0
  408. package/src/model/runners/render.js +14 -0
  409. package/src/model/runners/respond.js +2 -0
  410. package/src/model/runners/sample-soundfont.js +85 -0
  411. package/src/model/runners/sample.js +159 -0
  412. package/src/model/runners/scene.js +8 -0
  413. package/src/model/runners/score.js +24 -0
  414. package/src/model/runners/secret.js +10 -0
  415. package/src/model/runners/select.js +2 -0
  416. package/src/model/runners/shared.js +4 -0
  417. package/src/model/runners/shares.js +15 -0
  418. package/src/model/runners/shell.js +7 -0
  419. package/src/model/runners/skill.js +26 -0
  420. package/src/model/runners/state.js +2 -0
  421. package/src/model/runners/statechart.js +4 -0
  422. package/src/model/runners/subgraph.js +9 -0
  423. package/src/model/runners/tabs.js +25 -0
  424. package/src/model/runners/terminal.js +5 -0
  425. package/src/model/runners/text.js +4 -0
  426. package/src/model/runners/timer.js +7 -0
  427. package/src/model/runners/traffic.js +65 -0
  428. package/src/model/runners/trigger.js +2 -0
  429. package/src/model/runners/verdict.js +29 -0
  430. package/src/model/runners/vm.js +7 -0
  431. package/src/model/runners/wait.js +4 -0
  432. package/src/model/runners/ws-client.js +57 -0
  433. package/src/model/safe-regex.js +719 -0
  434. package/src/model/sample-settings.js +43 -0
  435. package/src/model/sample-source.js +47 -0
  436. package/src/model/saved-mapping.js +153 -0
  437. package/src/model/score-controllers.js +87 -0
  438. package/src/model/score-edit.js +399 -0
  439. package/src/model/score-instruments.js +300 -0
  440. package/src/model/score-library.js +407 -0
  441. package/src/model/score-markup.js +235 -0
  442. package/src/model/score-mix.js +248 -0
  443. package/src/model/score-patterns.js +276 -0
  444. package/src/model/score-selection.js +34 -0
  445. package/src/model/score-time.js +139 -0
  446. package/src/model/score-transforms.js +336 -0
  447. package/src/model/score-transport.js +192 -0
  448. package/src/model/selection.js +351 -0
  449. package/src/model/serial-controls.js +328 -0
  450. package/src/model/shares-pane.js +17 -0
  451. package/src/model/shell-pane.js +106 -0
  452. package/src/model/signature.js +1122 -0
  453. package/src/model/size-hints.js +106 -0
  454. package/src/model/size-ratio.js +12 -0
  455. package/src/model/skill-settings.js +23 -0
  456. package/src/model/snapping.js +466 -0
  457. package/src/model/split.js +375 -0
  458. package/src/model/spring-player.js +222 -0
  459. package/src/model/statecharts.js +1369 -0
  460. package/src/model/states-preset.js +208 -0
  461. package/src/model/static-route.js +100 -0
  462. package/src/model/step-words.js +45 -0
  463. package/src/model/subgraph.js +1042 -0
  464. package/src/model/switch.js +98 -0
  465. package/src/model/tabs-store.js +10 -0
  466. package/src/model/tensor-view.js +146 -0
  467. package/src/model/timer-clock.js +361 -0
  468. package/src/model/timers.js +422 -0
  469. package/src/model/timing.js +212 -0
  470. package/src/model/traffic-agent.js +111 -0
  471. package/src/model/traffic-store.js +20 -0
  472. package/src/model/traffic.js +665 -0
  473. package/src/model/transport.js +364 -0
  474. package/src/model/turns.js +86 -0
  475. package/src/model/types.js +425 -0
  476. package/src/model/value-path.js +138 -0
  477. package/src/model/versions.js +535 -0
  478. package/src/model/view-outputs.js +144 -0
  479. package/src/model/viewport-bookmarks.js +194 -0
  480. package/src/model/virtual-clock.js +85 -0
  481. package/src/model/vm-pane.js +258 -0
  482. package/src/model/wait-clock.js +715 -0
  483. package/src/model/wait-persist.js +248 -0
  484. package/src/model/waits.js +431 -0
  485. package/src/model/watch.js +80 -0
  486. package/src/model/webhook.js +496 -0
  487. package/src/model/when.js +48 -0
  488. package/src/model/widget-values.js +392 -0
  489. package/src/model/window-commands.js +278 -0
  490. package/src/model/windows.js +348 -0
  491. package/src/model/wire-inspect.js +343 -0
  492. package/src/model/wire-ops.js +324 -0
  493. package/src/model/wire-pipeline.js +378 -0
  494. package/src/model/wire-route.js +637 -0
  495. package/src/model/workspaces.js +122 -0
  496. package/src/model/ws-client.js +155 -0
  497. package/src/model/ws-demo.js +31 -0
  498. package/src/model/ws-frames.js +141 -0
  499. package/src/model/ws-hub.js +219 -0
  500. package/src/model/ws-served.js +13 -0
  501. package/src/model/xstate.js +374 -0
  502. package/src/narrative/narrative.js +1557 -0
  503. package/src/network/auth.js +224 -0
  504. package/src/network/csp-frame.js +197 -0
  505. package/src/network/declarative-shadow.js +27 -0
  506. package/src/network/frame-net-shim.js +962 -0
  507. package/src/network/hosts.js +157 -0
  508. package/src/network/policy.js +520 -0
  509. package/src/network/rtc-shim.js +418 -0
  510. package/src/network/secret-gate.js +78 -0
  511. package/src/network/secrets.js +261 -0
  512. package/src/network/sockets.js +287 -0
  513. package/src/network/store.js +186 -0
  514. package/src/network/streams.js +99 -0
  515. package/src/packages/asset-values.js +50 -0
  516. package/src/packages/assets.js +99 -0
  517. package/src/packages/deprecation.js +203 -0
  518. package/src/packages/fetch.js +152 -0
  519. package/src/packages/function-canvas.js +73 -0
  520. package/src/packages/module.js +120 -0
  521. package/src/packages/package.js +474 -0
  522. package/src/packages/published.js +27 -0
  523. package/src/packages/requires.js +83 -0
  524. package/src/packages/signing.js +145 -0
  525. package/src/packages/trust.js +107 -0
  526. package/src/panes/a2a.js +51 -0
  527. package/src/panes/acp.js +60 -0
  528. package/src/panes/actions.js +54 -0
  529. package/src/panes/agent.js +83 -0
  530. package/src/panes/audio.js +103 -0
  531. package/src/panes/automation.js +112 -0
  532. package/src/panes/calc.js +67 -0
  533. package/src/panes/catch.js +52 -0
  534. package/src/panes/codec.js +59 -0
  535. package/src/panes/colors.js +12 -0
  536. package/src/panes/companion.js +54 -0
  537. package/src/panes/decision.js +65 -0
  538. package/src/panes/device.js +56 -0
  539. package/src/panes/dom.js +37 -0
  540. package/src/panes/effects.js +118 -0
  541. package/src/panes/embed.js +30 -0
  542. package/src/panes/eval.js +186 -0
  543. package/src/panes/fields.js +299 -0
  544. package/src/panes/files.js +45 -0
  545. package/src/panes/gate.js +70 -0
  546. package/src/panes/geometry.js +64 -0
  547. package/src/panes/goals.js +75 -0
  548. package/src/panes/graph.js +66 -0
  549. package/src/panes/html.js +54 -0
  550. package/src/panes/http.js +82 -0
  551. package/src/panes/import.js +38 -0
  552. package/src/panes/input.js +124 -0
  553. package/src/panes/inputlog.js +66 -0
  554. package/src/panes/ledger.js +56 -0
  555. package/src/panes/machine.js +138 -0
  556. package/src/panes/mcp.js +85 -0
  557. package/src/panes/mcpapp.js +64 -0
  558. package/src/panes/media.js +38 -0
  559. package/src/panes/memory.js +46 -0
  560. package/src/panes/mesh-inspect.js +49 -0
  561. package/src/panes/note.js +38 -0
  562. package/src/panes/peer.js +44 -0
  563. package/src/panes/plot.js +196 -0
  564. package/src/panes/registry.js +475 -0
  565. package/src/panes/render.js +87 -0
  566. package/src/panes/respond.js +44 -0
  567. package/src/panes/router.js +84 -0
  568. package/src/panes/sample.js +75 -0
  569. package/src/panes/scene.js +55 -0
  570. package/src/panes/score.js +87 -0
  571. package/src/panes/secret.js +38 -0
  572. package/src/panes/select.js +67 -0
  573. package/src/panes/shader.js +166 -0
  574. package/src/panes/shared.js +33 -0
  575. package/src/panes/shares.js +43 -0
  576. package/src/panes/shell.js +47 -0
  577. package/src/panes/skill.js +44 -0
  578. package/src/panes/state.js +91 -0
  579. package/src/panes/statechart.js +63 -0
  580. package/src/panes/story.js +33 -0
  581. package/src/panes/subgraph.js +94 -0
  582. package/src/panes/tabs.js +52 -0
  583. package/src/panes/terminal.js +57 -0
  584. package/src/panes/text.js +36 -0
  585. package/src/panes/timer.js +55 -0
  586. package/src/panes/traffic.js +59 -0
  587. package/src/panes/verdict.js +62 -0
  588. package/src/panes/vm.js +46 -0
  589. package/src/panes/wait.js +61 -0
  590. package/src/panes/watch.js +57 -0
  591. package/src/panes/webhook.js +67 -0
  592. package/src/panes/ws-client.js +67 -0
  593. package/src/persist.js +281 -0
  594. package/src/plot/tex.js +19 -0
  595. package/src/plot/vendor.js +59 -0
  596. package/src/plot/view-vendor.js +5 -0
  597. package/src/privacy/levels.js +108 -0
  598. package/src/protocol/devtools.js +116 -0
  599. package/src/protocol/inspector.js +368 -0
  600. package/src/render/time.js +381 -0
  601. package/src/rooms/mesh-metrics.js +162 -0
  602. package/src/run/companion.js +355 -0
  603. package/src/run/describe.js +114 -0
  604. package/src/run/local-model.js +150 -0
  605. package/src/run/monitor.js +208 -0
  606. package/src/run/publish.js +360 -0
  607. package/src/run/respond-outcome.js +12 -0
  608. package/src/run/run.js +820 -0
  609. package/src/run/runner-pairing.js +243 -0
  610. package/src/run/values.js +122 -0
  611. package/src/runtime/compile.js +122 -0
  612. package/src/runtime/console-tag.js +64 -0
  613. package/src/runtime/frame-signals.js +126 -0
  614. package/src/runtime/iteration-push.js +19 -0
  615. package/src/runtime/keys.js +474 -0
  616. package/src/runtime/midi-input.js +170 -0
  617. package/src/runtime/person-waits.js +140 -0
  618. package/src/runtime/resource-timing.js +56 -0
  619. package/src/runtime/runtime.js +2150 -0
  620. package/src/runtime/sandbox-modules.js +163 -0
  621. package/src/runtime/spring.js +246 -0
  622. package/src/runtime/strict.js +215 -0
  623. package/src/runtime/transfer.js +75 -0
  624. package/src/runtime/tween.js +158 -0
  625. package/src/runtime/wasm-fuel.js +596 -0
  626. package/src/runtime/worker/00-prelude.js +88 -0
  627. package/src/runtime/worker/10-helpers.js +295 -0
  628. package/src/runtime/worker/20-io.js +645 -0
  629. package/src/runtime/worker/30-previews.js +210 -0
  630. package/src/runtime/worker/40-profile-lineage.js +278 -0
  631. package/src/runtime/worker/50-own-worker.js +233 -0
  632. package/src/runtime/worker/60-timers.js +172 -0
  633. package/src/runtime/worker/70-state-keyed.js +193 -0
  634. package/src/runtime/worker/80-each-compile-generators.js +619 -0
  635. package/src/runtime/worker/90-events-operators.js +655 -0
  636. package/src/runtime/worker/95-agents-batches.js +1820 -0
  637. package/src/runtime/worker/96-plot.js +47 -0
  638. package/src/runtime/worker/97-calc.js +28 -0
  639. package/src/runtime/worker/98-geometry.js +24 -0
  640. package/src/runtime/worker/99-graph.js +30 -0
  641. package/src/runtime/worker/99-shell.js +30 -0
  642. package/src/safety/config.js +57 -0
  643. package/src/safety/engine.js +324 -0
  644. package/src/scene/pixi-scene.js +806 -0
  645. package/src/scene/scene-assets.js +241 -0
  646. package/src/scene/scene-edit.js +319 -0
  647. package/src/secret/settings.js +41 -0
  648. package/src/security/multipart.js +257 -0
  649. package/src/security/redact.js +261 -0
  650. package/src/serial/broker.js +473 -0
  651. package/src/serial/config.js +185 -0
  652. package/src/serial/framers.js +389 -0
  653. package/src/serial/packets.js +64 -0
  654. package/src/shader/audio-texture.js +87 -0
  655. package/src/shader/channels.js +496 -0
  656. package/src/shader/common.js +90 -0
  657. package/src/shader/model.js +867 -0
  658. package/src/shader/passes.js +150 -0
  659. package/src/shader/shadertoy.js +198 -0
  660. package/src/shell/hub.js +287 -0
  661. package/src/sim/checkpoints.js +850 -0
  662. package/src/sim/compile.js +37 -0
  663. package/src/sim/fixed.js +377 -0
  664. package/src/sim/headless.js +205 -0
  665. package/src/sim/physics.js +399 -0
  666. package/src/smf-helper/vendor.js +2 -0
  667. package/src/sources/config.js +435 -0
  668. package/src/storage.js +153 -0
  669. package/src/table/table-geo.js +2344 -0
  670. package/src/table/table-lineage.js +808 -0
  671. package/src/table/table-quality.js +355 -0
  672. package/src/table/table-schema.js +392 -0
  673. package/src/table/table-sql.js +1650 -0
  674. package/src/table/table-stats.js +480 -0
  675. package/src/table/table.js +2102 -0
  676. package/src/tensor/tensor.js +1153 -0
  677. package/src/terminal/hub.js +715 -0
  678. package/src/terminal/screen.js +516 -0
  679. package/src/tests/capture.js +88 -0
  680. package/src/tests/compare.js +480 -0
  681. package/src/tests/dataset.js +170 -0
  682. package/src/tests/evaluate.js +286 -0
  683. package/src/tests/from-runs.js +99 -0
  684. package/src/tests/judge.js +134 -0
  685. package/src/tests/matchers.js +263 -0
  686. package/src/tests/matrix-spec.js +87 -0
  687. package/src/tests/matrix.js +397 -0
  688. package/src/tests/metrics.js +369 -0
  689. package/src/tests/no-value.js +42 -0
  690. package/src/tests/pane-check.js +45 -0
  691. package/src/tests/report.js +124 -0
  692. package/src/tests/reporters.js +140 -0
  693. package/src/tests/run.js +155 -0
  694. package/src/tilemap/tilemap.js +1122 -0
  695. package/src/units/units.js +3 -0
  696. package/src/util/bytes-text.js +21 -0
  697. package/src/util/num.js +10 -0
  698. package/src/util/regexp.js +2 -0
  699. package/src/util/text.js +38 -0
  700. package/src/verdict/engine.js +154 -0
  701. package/src/vm/guest-wsh.js +108 -0
  702. package/src/vm/hub.js +457 -0
  703. package/src/vm/image-files.js +4 -0
  704. package/src/vm/image.js +33 -0
  705. package/src/vm/image.lock.json +13 -0
  706. package/src/vm/link.js +266 -0
  707. package/src/vm/mount.js +212 -0
  708. package/src/vm/net.js +85 -0
  709. package/src/vm/pipe-ws.js +187 -0
  710. package/src/vm/v86-loader.js +11 -0
  711. package/src/webmcp/args.js +212 -0
  712. package/src/webmcp/hidden.js +218 -0
  713. package/src/webmcp/text.js +250 -0
  714. package/src/webmcp/tools/bookmark-tools.js +106 -0
  715. package/src/webmcp/tools/breakpoint-tools.js +48 -0
  716. package/src/webmcp/tools/canvases.js +208 -0
  717. package/src/webmcp/tools/context-tools.js +84 -0
  718. package/src/webmcp/tools/core.js +170 -0
  719. package/src/webmcp/tools/devices.js +41 -0
  720. package/src/webmcp/tools/edit.js +357 -0
  721. package/src/webmcp/tools/event-tools.js +145 -0
  722. package/src/webmcp/tools/image-tools.js +173 -0
  723. package/src/webmcp/tools/ink-tools.js +247 -0
  724. package/src/webmcp/tools/input-log-tools.js +163 -0
  725. package/src/webmcp/tools/live.js +166 -0
  726. package/src/webmcp/tools/machine-tools.js +74 -0
  727. package/src/webmcp/tools/media.js +161 -0
  728. package/src/webmcp/tools/midi-tools.js +32 -0
  729. package/src/webmcp/tools/preset-tools.js +184 -0
  730. package/src/webmcp/tools/quick-add-tools.js +95 -0
  731. package/src/webmcp/tools/reshape.js +152 -0
  732. package/src/webmcp/tools/run-tools.js +309 -0
  733. package/src/webmcp/tools/runs.js +101 -0
  734. package/src/webmcp/tools/scaffold-tools.js +161 -0
  735. package/src/webmcp/tools/serial-tools.js +36 -0
  736. package/src/webmcp/tools/shared.js +338 -0
  737. package/src/webmcp/tools/subgraphs.js +360 -0
  738. package/src/webmcp/tools/tests.js +170 -0
  739. package/src/webmcp/tools/traffic-tools.js +70 -0
  740. package/src/webmcp/tools/transport-tools.js +65 -0
  741. package/src/webmcp/tools/version-tools.js +126 -0
  742. package/src/webmcp/tools/versions.js +11 -0
  743. package/src/webmcp/tools/wire-tools.js +90 -0
  744. package/src/webmcp/tools/workspace-tools.js +93 -0
  745. package/src/webmcp/tools.js +1323 -0
  746. package/src/wsh/connect.js +347 -0
  747. package/src/wsh/demo-host.js +361 -0
  748. package/src/wsh/e2e.js +27 -0
  749. package/src/wsh/keys.js +154 -0
  750. package/src/wsh/known-hosts.js +39 -0
  751. package/src/wsh/private-key.js +95 -0
  752. package/src/wsh/reverse.js +34 -0
  753. package/src/wsh/settings.js +118 -0
  754. package/src/wsh/transfer.js +62 -0
  755. package/src/wsh/vendor.js +5 -0
  756. package/src/x402/challenge.js +171 -0
  757. package/src/x402/demo-server.js +127 -0
  758. package/src/x402/pay.js +125 -0
  759. package/src/x402/retry.js +95 -0
  760. package/src/x402/store.js +76 -0
@@ -0,0 +1,981 @@
1
+ // Linked subgraphs: a subgraph pane that refers to a saved canvas
2
+ // instead of holding a copy of it. Editing that canvas offers every pane that
3
+ // links to it an update ("updated · use new version"); accepting it replaces
4
+ // the pane's graph, keeps its wiring by port name, and reruns it.
5
+ //
6
+ // A linked subgraph pane's content is an ordinary subgraph pane's (see
7
+ // src/model/subgraph.js) plus
8
+ //
9
+ // ref: { canvas: "<canvas id>", name, hash, tag }
10
+ // params: { <port name>: widget value } (any subgraph pane, linked or not)
11
+ //
12
+ // `graph` is always there: a cached copy of the linked canvas, so the pane
13
+ // runs where that canvas isn't saved (another browser, a headless run, an
14
+ // older mallory, which ignores `ref`). `hash` is the linked canvas's definition
15
+ // (linkHash) when it was inserted or last updated. `tag` makes the copy's
16
+ // pane ids this instance's own: the linked canvas's pane `x` is `x_<tag>`
17
+ // here (tagId), so two instances of one canvas on a canvas never share an id
18
+ // (and so never share a timer, a kept state value or a run history), and the
19
+ // same pane keeps its id across updates (a kept value stays kept). The
20
+ // linked canvas's own panes come back by removing the tag (sourceGraph).
21
+ // Tags compose: a linked subgraph inside the linked canvas has its own tag,
22
+ // which gets this instance's tag after it, like its ids (`g_<t1>_<t2>`).
23
+ //
24
+ // `params` are a subgraph pane's parameter form: a value for a port (an input
25
+ // pane inside) that has no wire, in place of that input pane's own widget
26
+ // value (src/model/canvas.js, the "input" case; bindPorts in subgraph.js).
27
+ //
28
+ // A canvas file or link carries every canvas its panes link to, at the
29
+ // version they use, in a top-level `library: { <canvas id>: { name, hash,
30
+ // graph } }` (buildLibrary). Opening one never writes those into the person's
31
+ // saved canvases; "Save linked canvases to my canvases" does, on request.
32
+ //
33
+ // Pane packages (src/packages/): a linked pane can follow a pane of an
34
+ // installed package instead of a saved canvas. Its `ref.canvas` is then
35
+ // `pkg:<package>/<pane>` and `ref` also has `package`, `version`, `pane` and
36
+ // `integrity` (the sha256 of the package as installed); where it resolves is
37
+ // the `loadPackage` lookup the page passes beside `loadCanvas`. Its library
38
+ // entry carries `package: { name, version, pane, integrity }`, so whoever
39
+ // opens the file can install that pane from it after a review.
40
+ //
41
+ // A repeater's templates (src/model/repeater.js `each.templates`) are
42
+ // links too: `{ name, ref, graph }`, a linked subgraph's ref and cached graph
43
+ // per value of its template field. They get the same updates:
44
+ // ownLinkedPanes lists them (a path to the repeater plus the template's key),
45
+ // planTemplateUpdate / acceptTemplateUpdate review and take a new version,
46
+ // "follow automatically" and resolveLinks see them. Accepting one changes the
47
+ // repeater's `each`, and its instances of that template follow in place.
48
+ //
49
+ // Pure: no DOM and no storage (the page passes persist.loadCanvas), so it
50
+ // runs under node --test and in the headless runner (resolveLinks).
51
+ import { isSafeCanvasId } from "./canvas-id.js";
52
+ import { graphPanes, graphIds, portsOf, outputIds, renameGraph, disposeInner, innerCanvas, tagId, untagId, insertName, insertCanvas, exposedPath } from "./subgraph.js";
53
+ import { outputsOf, cleanOutputs, cleanExpose, EVENT_TYPE } from "./ports.js";
54
+ import { typeText, coerceValue, unitsEngine } from "./types.js";
55
+ import { portRenames, followRenames } from "./controls.js";
56
+ import { hashContent } from "./versions.js";
57
+ import { checkDeprecation, removalState } from "../packages/deprecation.js";
58
+ import { moduleKey } from "../packages/module.js";
59
+ import { byType } from "../panes/registry.js";
60
+ import { stripPins } from "./pin.js";
61
+ import { stripPersonOnlyList } from "./person-only.js";
62
+ import { validatePresentation } from "./presentation.js";
63
+
64
+ const DEFAULTS = byType((r) => r.defaults);
65
+
66
+ /** A package pane's canvas id (`pkg:<package>/<pane>`, src/packages/package.js). */
67
+ const isPackageId = (id) => String(id ?? "").startsWith("pkg:");
68
+
69
+ /** The package fields of a ref, from a doc's (or a library entry's) `package` note: { package, version, pane, integrity? }, or {}. */
70
+ const packageFields = (meta) =>
71
+ meta && typeof meta.name === "string" ? { package: meta.name, version: meta.version, pane: meta.pane, ...(meta.integrity ? { integrity: meta.integrity } : {}) } : {};
72
+
73
+ /** What a package pane's library entry may carry besides its ids: the pane's description, icon, tests and declared hosts, so installing it from a canvas gives a whole pane. */
74
+ const PANE_INFO = ["description", "icon", "tests", "hosts", "deprecated"];
75
+
76
+ /**
77
+ * A ref's package note for its library entry, or {}. `kept`: the entry the
78
+ * canvas already carries for it; its pane details (PANE_INFO) stay when it is
79
+ * the same package version.
80
+ */
81
+ const packageNote = (ref, kept) => {
82
+ if (!ref?.package) return {};
83
+ const same = kept?.package?.name === ref.package && kept.package.version === ref.version && kept.package.pane === ref.pane;
84
+ const info = same ? Object.fromEntries(PANE_INFO.filter((k) => kept.package[k] !== undefined).map((k) => [k, structuredClone(kept.package[k])])) : {};
85
+ return { package: { name: ref.package, version: ref.version, pane: ref.pane, ...(ref.integrity ? { integrity: ref.integrity } : {}), ...info } };
86
+ };
87
+
88
+ /** A library entry as a canvas doc a link can follow. */
89
+ const entryDoc = (id, entry, ref) => ({ id, name: entry.name ?? ref?.name, viewport: entry.graph.viewport, panes: entry.graph.panes, ...(entry.graph.groups ? { groups: entry.graph.groups } : {}), ...(entry.graph.presentation ? { presentation: entry.graph.presentation } : {}), ...(entry.package ? { package: entry.package } : {}) });
90
+
91
+ // ── the definition of a canvas, and its hash ───────────────────────────────
92
+
93
+ /**
94
+ * The part of a list of panes that decides what they do: every pane with its
95
+ * type's defaults filled in (as the canvas model normalizes it), without its
96
+ * place (rect, width) or a subgraph's view (viewport), in id order at every
97
+ * level.
98
+ */
99
+ export function definition(panes) {
100
+ return [...(panes ?? [])]
101
+ .map((p) => {
102
+ // A pinned value (src/model/pin.js) is a way to work on a canvas, not part of what it does.
103
+ const { rect, width, pin, pinned, sticky, stashed, layer, ...rest } = { inputs: [], name: "", ...(DEFAULTS[p?.type]?.() ?? {}), ...p };
104
+ if (rest.type === "subgraph") rest.graph = { panes: definition(graphPanes(rest)), ...offIn(rest.graph?.groups) };
105
+ return rest;
106
+ })
107
+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
108
+ }
109
+
110
+ /** Of a canvas's groups (frames, src/model/groups.js), only what changes what runs: the panes a deactivated group switches off. */
111
+ export const offIn = (groups) => {
112
+ const off = [...new Set((Array.isArray(groups) ? groups : []).filter((g) => g?.disabled).flatMap((g) => g.panes ?? []))].sort();
113
+ return off.length ? { off } : {};
114
+ };
115
+
116
+ /**
117
+ * Of a canvas's presentation (its composite view), what an instance draws: the panes it
118
+ * shows and their docking tree. Which one has focus is a person's moment, not the function's.
119
+ */
120
+ export const viewIn = (presentation) => (presentation?.panes?.length ? { view: { panes: presentation.panes, tree: presentation.tree ?? null } } : {});
121
+
122
+ /**
123
+ * The hash of a canvas as a link sees it: what its panes do (and which groups switch some off)
124
+ * and what an instance of it shows (its composite view). Moving a pane, a group's name or
125
+ * color, or the editor's view don't change it: an instance never shows those, so a change to
126
+ * them offers no update. A canvas with no composite view hashes as it always did.
127
+ */
128
+ export const linkHash = (panes, groups, presentation) => hashContent({ panes: definition(panes), ...offIn(groups), ...viewIn(presentation) });
129
+
130
+ // ── ids ────────────────────────────────────────────────────────────────────
131
+
132
+ /**
133
+ * A repeater's templates (src/model/repeater.js, `each.templates`) as the
134
+ * linked subgraph contents they are: `{ type: "subgraph", id, name, ref, graph }`,
135
+ * so the library a file carries, the loop check and the tags count them.
136
+ */
137
+ export const templatePanes = (p) => templatesOf(p).map((t) => t.content);
138
+
139
+ /** A repeater's linked templates: [{ key, content }] (`key` its value of the template field, `content` as templatePanes). */
140
+ export const templatesOf = (p) =>
141
+ Object.entries(p?.type === "subgraph" ? (p.each?.templates ?? {}) : {})
142
+ .filter(([, t]) => t?.ref?.canvas && Array.isArray(t.graph?.panes))
143
+ .map(([key, t]) => ({ key, content: { type: "subgraph", id: `${p.id}@${key}`, name: t.name ?? key, ref: t.ref, graph: t.graph } }));
144
+
145
+ /**
146
+ * The templates of repeater pane `p` a canvas can update, as
147
+ * ownLinkedPanes entries: `{ pane, path, template, repeater }` (`pane` the
148
+ * template as a linked subgraph's content, `path` the ids down to the
149
+ * repeater pane, `template` its key). Only while for each is on.
150
+ */
151
+ export const templateLinks = (p, path = []) => (p?.each?.on ? templatesOf(p).map(({ key, content }) => ({ pane: content, path: [...path, p.id], template: key, repeater: p })) : []);
152
+
153
+ /** Every link tag used on a canvas (in its panes, nested ones too), so a new one is unique. */
154
+ export function tagsIn(panes, out = new Set()) {
155
+ for (const p of panes ?? []) {
156
+ if (p?.type !== "subgraph") continue;
157
+ if (p.ref?.tag) out.add(p.ref.tag);
158
+ tagsIn(graphPanes(p), out);
159
+ tagsIn(templatePanes(p), out);
160
+ }
161
+ return out;
162
+ }
163
+
164
+ /** A new link tag: `k` and five letters or digits, not in `taken`. */
165
+ export function newTag(taken = new Set(), random = Math.random) {
166
+ for (;;) {
167
+ const tag = `k${random().toString(36).slice(2, 7).padEnd(5, "0")}`;
168
+ if (!taken.has(tag)) return tag;
169
+ }
170
+ }
171
+
172
+ /** A canvas's panes and viewport as one instance's graph: every id tagged, and without the canvas's pinned values (they stay with it). */
173
+ export function instanceGraph(source, tag, { from } = {}) {
174
+ const graph = renameGraph({ panes: stripPins(source?.panes ?? []), viewport: source?.viewport, ...(source?.groups ? { groups: source.groups } : {}), ...(source?.presentation ? { presentation: source.presentation } : {}) }, (id) => tagId(id, tag), { retag: (t) => tagId(t, tag) }); // the presentation is the function's composite view
175
+ // Settings only the person turns on come back at their defaults, or stay as the pane being updated (`from`, ids tagged alike) has them (src/model/person-only.js).
176
+ return { ...graph, panes: stripPersonOnlyList(graph.panes, { from }) };
177
+ }
178
+
179
+ /** An instance's graph as the linked canvas's own panes: the tag removed (ids without it stay). */
180
+ export const sourceGraph = (graph, tag) => renameGraph(graph ?? { panes: [] }, (id) => untagId(id, tag) ?? id, { retag: (t) => untagId(t, tag) ?? t });
181
+
182
+ // ── what links to what ─────────────────────────────────────────────────────
183
+
184
+ /** Every canvas id the panes link to, through linked subgraphs and the graphs inside every subgraph. */
185
+ export function refsIn(panes, out = new Set()) {
186
+ for (const p of panes ?? []) {
187
+ if (p?.type !== "subgraph") continue;
188
+ if (p.ref?.canvas) out.add(p.ref.canvas);
189
+ refsIn(graphPanes(p), out);
190
+ refsIn(templatePanes(p), out); // a repeater's templates
191
+ }
192
+ return out;
193
+ }
194
+
195
+ /** The linked subgraph panes among `panes`, nested ones too: [{ pane, path }] (path: the ids down to it). */
196
+ export function linkedPanes(panes, path = []) {
197
+ const out = [];
198
+ for (const p of panes ?? []) {
199
+ if (p?.type !== "subgraph") continue;
200
+ if (p.ref?.canvas) out.push({ pane: p, path: [...path, p.id] });
201
+ out.push(...linkedPanes(graphPanes(p), [...path, p.id]));
202
+ out.push(...linkedPanes(templatePanes(p), [...path, p.id])); // a repeater's templates (their path ends at a template, not a pane)
203
+ }
204
+ return out;
205
+ }
206
+
207
+ /**
208
+ * The linked panes a canvas can update itself: its own, and those
209
+ * inside its copy subgraphs at any depth, but not those inside a linked pane
210
+ * (they belong to the canvas that pane links to, and change with it).
211
+ * [{ pane, path }] (path: the ids down to it). A repeater's linked templates
212
+ * are its pane's own (`each` is the pane's, linked or not): they come
213
+ * as `{ pane, path, template, repeater }`, the path ending at the repeater.
214
+ */
215
+ export function ownLinkedPanes(panes, path = []) {
216
+ const out = [];
217
+ for (const p of panes ?? []) {
218
+ if (p?.type !== "subgraph") continue;
219
+ if (p.ref?.canvas) out.push({ pane: p, path: [...path, p.id] });
220
+ out.push(...templateLinks(p, path));
221
+ if (!p.ref?.canvas) out.push(...ownLinkedPanes(graphPanes(p), [...path, p.id]));
222
+ }
223
+ return out;
224
+ }
225
+
226
+ /**
227
+ * Why `doc` can't go inside canvas `rootId` (as a link or a copy), or null:
228
+ * a canvas can't contain itself, directly or through the canvases it links
229
+ * to (as Node-RED's subflows refuse).
230
+ */
231
+ export function insertProblem(rootId, doc) {
232
+ if (!doc) return "That canvas isn't saved in this browser.";
233
+ if (doc.id === rootId) return "A canvas can't contain itself.";
234
+ if (refsIn(doc.panes).has(rootId) || refsIn(Object.values(doc.library ?? {}).flatMap((e) => graphPanes(e))).has(rootId)) {
235
+ return `"${doc.name || "That canvas"}" uses this canvas (through a linked subgraph), so it can't go inside it: that would be a loop.`;
236
+ }
237
+ return null;
238
+ }
239
+
240
+ // ── ports ──────────────────────────────────────────────────────────────────
241
+
242
+ /**
243
+ * The subgraph pane's wires that feed no port: an input whose name no input
244
+ * pane inside has any more (the linked canvas renamed or removed it). They are
245
+ * kept, and flagged, never dropped: [{ index, name, source }].
246
+ */
247
+ export function portProblems(content) {
248
+ const names = new Set(portsOf(content).map((p) => p.name));
249
+ return (content?.inputs ?? []).flatMap((input, index) => (names.has(input.name) ? [] : [{ index, name: input.name, source: input.source }]));
250
+ }
251
+
252
+ /**
253
+ * The subgraph pane's own named outputs (format 3, src/model/ports.js) that
254
+ * its graph no longer makes: with several leaves its value is keyed by their
255
+ * names, so an output no leaf is named like; with one, an output that leaf
256
+ * declares no more (when it declares any). Kept, and flagged: [{ name }].
257
+ */
258
+ export function outputProblems(content) {
259
+ const declared = (content?.outputs ?? []).map((o) => o.name);
260
+ if (!declared.length) return [];
261
+ const panes = graphPanes(content);
262
+ const leaves = outputIds(content).map((id) => panes.find((p) => p.id === id)).filter(Boolean);
263
+ let made;
264
+ if (leaves.length > 1) made = new Set(leaves.map((p) => p.name || p.id));
265
+ else if (leaves.length === 1 && leaves[0].outputs?.length) made = new Set(outputsOf(leaves[0]).map((o) => o.name));
266
+ else return [];
267
+ return declared.filter((name) => !made.has(name)).map((name) => ({ name }));
268
+ }
269
+
270
+ /**
271
+ * The named outputs a newly inserted linked pane declares: with one leaf
272
+ * that declares outputs, those (`[{ name, type?, description? }]`), so a wire
273
+ * can take `rows` from the pane at once instead of the pane's `outputs` being
274
+ * set by hand. Several leaves (a value keyed by their names) declare one
275
+ * output per leaf, named like it; a leaf with no declared outputs
276
+ * declares none: undefined.
277
+ */
278
+ export function leafOutputs(content) {
279
+ const panes = graphPanes(content);
280
+ const leaves = outputIds(content, panes).map((id) => panes.find((p) => p.id === id)).filter(Boolean);
281
+ if (leaves.length > 1) return cleanOutputs(leaves.map((p) => ({ name: p.name || p.id })));
282
+ return leaves.length === 1 ? cleanOutputs(leaves[0].outputs) : undefined;
283
+ }
284
+
285
+ /**
286
+ * The leaf outputs an update adds: those the new graph's leaves declare
287
+ * (leafOutputs) that the old graph's did not and the pane doesn't already have.
288
+ * One an earlier version made and the pane's author since removed stays removed.
289
+ * Returns the pane's outputs with them added, or undefined when none are new.
290
+ */
291
+ function withNewLeafOutputs(content, changed) {
292
+ const had = new Set([...(leafOutputs(content) ?? []), ...(content.outputs ?? [])].map((o) => o.name));
293
+ const added = (leafOutputs(changed) ?? []).filter((o) => !had.has(o.name));
294
+ return added.length ? cleanOutputs([...(content.outputs ?? []), ...added]) : undefined;
295
+ }
296
+
297
+ /**
298
+ * How the ports change from `before` to `after` (subgraph contents): added,
299
+ * removed and renamed (the same input pane, a new name), and retyped (a port
300
+ * whose type changed, src/model/types.js: what a wire into it must now carry).
301
+ */
302
+ export function portChanges(before, after) {
303
+ const a = portsOf(before);
304
+ const b = portsOf(after);
305
+ const names = (list) => new Set(list.map((p) => p.name));
306
+ const [na, nb] = [names(a), names(b)];
307
+ const byId = new Map(b.map((p) => [p.id, p.name]));
308
+ const renamed = a.filter((p) => byId.has(p.id) && byId.get(p.id) !== p.name).map((p) => ({ from: p.name, to: byId.get(p.id) }));
309
+ const renamedFrom = new Set(renamed.map((r) => r.from));
310
+ const renamedTo = new Set(renamed.map((r) => r.to));
311
+ const typeOf = (p) => typeText(p.type);
312
+ const was = new Map(a.map((p) => [p.name, p]));
313
+ const retyped = b.filter((p) => was.has(p.name) && typeOf(was.get(p.name)) !== typeOf(p)).map((p) => ({ name: p.name, from: typeOf(was.get(p.name)), to: typeOf(p) }));
314
+ return {
315
+ added: b.filter((p) => !na.has(p.name) && !renamedTo.has(p.name)).map((p) => p.name),
316
+ removed: a.filter((p) => !nb.has(p.name) && !renamedFrom.has(p.name)).map((p) => p.name),
317
+ renamed,
318
+ retyped,
319
+ };
320
+ }
321
+
322
+ // ── where a link's newer version comes from ────────────────────────────────
323
+
324
+ /**
325
+ * The canvas a linked pane follows, as it is now: for a package pane, that
326
+ * pane of the installed package (`from: "package"`, through `loadPackage`);
327
+ * else the person's own saved canvas with that id (`from: "canvas"`); else
328
+ * the entry the open canvas carries in its library (`from: "library"`, it
329
+ * came with a file or link); else null. `hash` is its definition's hash: an
330
+ * update is available when it differs from `ref.hash`.
331
+ *
332
+ * `loadPackage(ref)` returns `{ doc, flagged? }` for an installed package's
333
+ * pane (src/packages/package.js paneDoc), where `flagged` says why that
334
+ * library entry isn't to be trusted (its integrity changed outside an update).
335
+ * @param {{ canvas: string, package?: string }} ref
336
+ * @param {{ loadCanvas?: (id: string) => object | undefined, loadPackage?: (ref: object) => { doc: object, flagged?: string } | undefined, library?: object }} where
337
+ */
338
+ export function linkSource(ref, { loadCanvas, loadPackage, library } = {}) {
339
+ if (!ref?.canvas) return null;
340
+ if (ref.package || isPackageId(ref.canvas)) {
341
+ // Never a saved canvas: a package pane resolves only to the installed package, or the copy the canvas carries.
342
+ const found = ref.package ? loadPackage?.(ref) : undefined;
343
+ if (found?.doc && Array.isArray(found.doc.panes)) {
344
+ return { from: "package", doc: found.doc, hash: linkHash(found.doc.panes, found.doc.groups, found.doc.presentation), trusted: !found.flagged, ...(found.flagged ? { flagged: found.flagged } : {}) };
345
+ }
346
+ } else {
347
+ const own = loadCanvas?.(ref.canvas);
348
+ if (own && Array.isArray(own.panes)) return { from: "canvas", doc: own, hash: linkHash(own.panes, own.groups, own.presentation), trusted: own.trusted !== false };
349
+ }
350
+ const entry = library?.[ref.canvas];
351
+ if (entry && Array.isArray(entry.graph?.panes)) {
352
+ const doc = entryDoc(ref.canvas, entry, ref);
353
+ return { from: "library", doc, hash: linkHash(doc.panes, doc.groups, doc.presentation), trusted: false };
354
+ }
355
+ return null;
356
+ }
357
+
358
+ /** The deprecation notice a package pane's doc (installed, or from a library entry) carries, or undefined. */
359
+ export const deprecationOfDoc = (doc) => doc?.paneInfo?.deprecated ?? doc?.package?.deprecated;
360
+
361
+ /**
362
+ * A linked pane's state, for its summary and agents: `{ canvas, name, source,
363
+ * update, sourceTrusted, deprecated? }` (`deprecated`: the author's notice,
364
+ * from the installed package, else the copy this canvas carries) (source: "package", "canvas", "library" or null).
365
+ * A package pane also has `package: { name, version, installed? }` and, when
366
+ * something doesn't add up, `integrity`: "mismatch" (the installed package
367
+ * has this pane's version but different panes: it was changed without a new
368
+ * version) or the reason its library entry is flagged.
369
+ */
370
+ export function linkStatus(content, where) {
371
+ if (!content?.ref?.canvas) return null;
372
+ const { ref } = content;
373
+ const source = linkSource(ref, where);
374
+ // A package version whose panes are the same but whose shared module isn't (src/packages/module.js) is an update too: its panes would run other code.
375
+ const moduleMoved = Boolean(ref.package && source?.from === "package" && where?.packageModules && source.doc.package?.version !== ref.version && (source.doc.packageModule?.integrity ?? null) !== (where.packageModules[moduleKey(ref.package, ref.version)]?.integrity ?? null));
376
+ const update = Boolean(source && (source.hash !== ref.hash || moduleMoved));
377
+ const out = { canvas: ref.canvas, name: source?.doc?.name ?? ref.name, source: source?.from ?? null, update, sourceTrusted: source?.trusted ?? null };
378
+ const deprecated = deprecationOfDoc(source?.doc);
379
+ if (deprecated) out.deprecated = deprecated;
380
+ if (ref.package) {
381
+ const installed = source?.from === "package" ? source.doc.package?.version : undefined;
382
+ out.package = { name: ref.package, version: ref.version, ...(installed ? { installed } : {}) };
383
+ if (source?.flagged) out.integrity = source.flagged;
384
+ else if (installed && installed === ref.version && update) out.integrity = "mismatch";
385
+ }
386
+ return out;
387
+ }
388
+
389
+ // ── accepting an update ────────────────────────────────────────────────────
390
+
391
+ /**
392
+ * What accepting `source` (a canvas doc: { id, name, panes, viewport }) on
393
+ * linked subgraph content would make, without changing anything:
394
+ * `{ content, graph, output, ref, ports, flagged, lostOutputs }`. The pane's
395
+ * name, wiring, parameters and named outputs stay; wires to ports that are
396
+ * gone are `flagged`, and its outputs the new graph no longer makes are
397
+ * `lostOutputs` (what is wired to them skips).
398
+ * Throws when `source` would make a loop inside canvas `rootId`.
399
+ */
400
+ export function planUpdate(content, source, { rootId, follow = true, keepPersonOnly = true } = {}) {
401
+ if (!content?.ref?.canvas) throw new Error("That subgraph pane isn't linked to a canvas.");
402
+ const problem = rootId === undefined ? null : insertProblem(rootId, source);
403
+ if (problem) throw new Error(problem);
404
+ const { tag } = content.ref;
405
+ const graph = instanceGraph(source, tag, { from: keepPersonOnly ? content.graph?.panes : undefined }); // the settings only the person turns on stay as this pane has them
406
+ const output = content.output && graphIds(graph.panes).has(content.output) ? content.output : null;
407
+ const ref = { ...content.ref, name: source.name ?? content.ref.name, hash: linkHash(source.panes ?? [], source.groups, source.presentation), ...packageFields(source.package) };
408
+ const changed = { ...content, graph, output, ref };
409
+ // An input pane the new version renamed (same pane, new name) takes this pane's wires and parameters with it: the review lists it ("renamed"), so it is reviewed, not silent.
410
+ const renames = follow ? portRenames(content, changed, portsOf) : [];
411
+ const moved = followRenames(content, renames);
412
+ const outputs = withNewLeafOutputs(content, changed); // a leaf the new version made is declared at once
413
+ const next = { ...changed, ...moved, ...(outputs ? { outputs } : {}) };
414
+ return { content: next, graph, output, ref, moved, followed: renames, ports: portChanges(content, changed), flagged: portProblems(next), lostOutputs: outputProblems(next), ...(outputs ? { outputs } : {}) };
415
+ }
416
+
417
+ /**
418
+ * Accept an update on subgraph pane `id` of `canvas`: its inner canvas (if
419
+ * it has one) goes, the new graph takes its place, and it reruns (once the
420
+ * canvas is running: a paused canvas stays paused). Panes inside that are in
421
+ * both versions keep their ids, so their kept values and paused timers stay.
422
+ * Returns the plan (see planUpdate).
423
+ */
424
+ export function acceptUpdate(canvas, id, source) {
425
+ const pane = canvas.panes.get(id);
426
+ if (pane?.type !== "subgraph" || !canvas.attached.has(id)) throw new Error("That isn't a subgraph pane on this canvas.");
427
+ const plan = planUpdate(pane, source, { rootId: canvas.root.id });
428
+ disposeInner(canvas, id); // before the new graph: disposing saves the inner canvas into the pane
429
+ canvas.update(id, { graph: plan.graph, output: plan.output, ref: plan.ref, ...plan.moved, ...(plan.outputs ? { outputs: plan.outputs } : {}) });
430
+ const root = canvas.root;
431
+ if (root.library?.[plan.ref.canvas]) delete root.library[plan.ref.canvas]; // the version carried with a file: this pane has moved on
432
+ carryPackagePane(root, source);
433
+ canvas.flow.invalidate(id);
434
+ return plan;
435
+ }
436
+
437
+ // ── replacing a deprecated pane ─────────────────────────────────────
438
+
439
+ /** Can a value of port type `from` go into a port of type `to`? The same type, or a port that takes anything. */
440
+ const portFits = (from, to) => from === to || to === "any";
441
+
442
+ /**
443
+ * What moving linked subgraph content to another package pane `source` (a
444
+ * canvas doc: the replacement a deprecation notice names) would make, without
445
+ * changing anything. Unlike planUpdate this is a different canvas, so its ports
446
+ * are matched by *name and type*, never by the pane ids inside:
447
+ *
448
+ * ports: [{ name, wired, status, from, to? }] every port the old pane has
449
+ * "same" the new one has that name and takes the same type: its wire and parameter stay
450
+ * "retyped" the name is there but takes another type (`from` → `to`): the wire stays, a value of the old type may now be an error
451
+ * "gone" no port of that name: a wire into it stays, flagged, like an update's
452
+ * added: [{ name, type }] inputs only the replacement has (unwired: they use their default)
453
+ * droppedParams: [name] parameter-form values for ports that are gone (removed with the move, undone with it)
454
+ *
455
+ * settings: [{ name, status, to?, reason? }] every parameter-form value: "kept", "dropped" (its port is gone) or "unfit" (its port now takes `to`, which the value can't be converted to)
456
+ * a port's wire also says `wireType`/`wireFits` when its source declares the type it carries (a typed named output);
457
+ * `panes` (the canvas's pane contents) lets it name what reads the pane: `readers`, `outputsAdded`, `outputsRemoved`, see replaceOutputs.
458
+ *
459
+ * plus planUpdate's `{ content, graph, output, ref, flagged, lostOutputs }`.
460
+ * Nothing is rewired for the person: a port with another name is "gone" and
461
+ * the new one is "added", for them to connect. Throws when `source` would make a loop.
462
+ */
463
+ export function planReplace(content, source, { rootId, panes = [] } = {}) {
464
+ if (!content?.ref?.canvas) throw new Error("That subgraph pane isn't linked to a canvas.");
465
+ if (!source?.id) throw new Error("The replacement isn't a canvas.");
466
+ const base = planUpdate({ ...content, ref: { ...content.ref, canvas: source.id } }, source, { rootId, keepPersonOnly: false }); // another canvas: nothing of the old one's settings carries over
467
+ const old = portsOf(content);
468
+ const next = portsOf(base.content);
469
+ const byName = new Map(next.map((p) => [p.name, p]));
470
+ const type = (p) => typeText(p.type);
471
+ const byId = new Map(panes.map((p) => [p.id, p]));
472
+ // What a wire into a port carries, as far as its source declares it (a named output with a type); null when it doesn't say.
473
+ const wireType = (p) => {
474
+ const src = p.bound === undefined ? undefined : byId.get(p.bound);
475
+ const out = src ? outputsOf(src).find((o) => o.name === (p.boundOutput ?? "")) : undefined;
476
+ return out?.type && out.type !== EVENT_TYPE ? typeText(out.type) : null;
477
+ };
478
+ const ports = old.map((p) => {
479
+ const q = byName.get(p.name);
480
+ const carried = wireType(p);
481
+ if (!q) return { name: p.name, wired: p.bound !== undefined, status: "gone", from: type(p), ...(carried ? { wireType: carried } : {}) };
482
+ const to = type(q);
483
+ return { name: p.name, wired: p.bound !== undefined, status: portFits(type(p), to) ? "same" : "retyped", from: type(p), to, ...(carried ? { wireType: carried, wireFits: portFits(carried, to) } : {}) };
484
+ });
485
+ const had = new Set(old.map((p) => p.name));
486
+ const added = next.filter((p) => !had.has(p.name)).map((p) => ({ name: p.name, type: type(p) }));
487
+ const droppedParams = Object.keys(content.params ?? {}).filter((name) => !byName.has(name));
488
+ const params = content.params ? Object.fromEntries(Object.entries(content.params).filter(([name]) => byName.has(name))) : undefined;
489
+ // Each parameter-form value: kept, dropped with its port, or no longer a value its port takes.
490
+ const settings = Object.entries(content.params ?? {}).map(([name, value]) => {
491
+ const q = byName.get(name);
492
+ if (!q) return { name, status: "dropped" };
493
+ try {
494
+ coerceValue(value, q.type, unitsEngine);
495
+ return { name, status: "kept" };
496
+ } catch (error) {
497
+ return { name, status: "unfit", to: type(q), reason: error.message };
498
+ }
499
+ });
500
+ const outputs = replaceOutputs(content, base.content, panes);
501
+ return { ...base, content: { ...base.content, ...(params ? { params } : {}) }, params, ports, added, droppedParams, settings, ...outputs };
502
+ }
503
+
504
+ /** The named outputs a subgraph's value offers: `null` when it is one unnamed value (nothing to tell), else [{ name, type? }]. */
505
+ function madeOutputs(content) {
506
+ const inner = graphPanes(content);
507
+ const leaves = outputIds(content, inner).map((id) => inner.find((p) => p.id === id)).filter(Boolean);
508
+ if (leaves.length > 1) return leaves.map((p) => ({ name: p.name || p.id }));
509
+ if (leaves.length === 1 && leaves[0].outputs?.length) return outputsOf(leaves[0]).filter((o) => o.type !== EVENT_TYPE).map((o) => ({ name: o.name, ...(o.type ? { type: typeText(o.type) } : {}) }));
510
+ return null;
511
+ }
512
+
513
+ /**
514
+ * How the move changes what the pane makes, and what reads it (the panes of the
515
+ * canvas wired to its outputs): `{ outputsAdded, outputsRemoved, readers }`.
516
+ * A reader is `{ id, name, input, output?, status }`: "same" (the output is still
517
+ * made), "retyped" (it is, but with another type than the reader's input takes:
518
+ * `from` is what the reader takes, `to` what it now gets), "gone" (the replacement
519
+ * makes no such output: that wire skips) or "unchecked" (the replacement's value is
520
+ * not split into named outputs, so there is nothing to compare).
521
+ */
522
+ function replaceOutputs(before, after, panes) {
523
+ const was = madeOutputs(before) ?? [];
524
+ const now = madeOutputs(after);
525
+ const nowNames = new Set((now ?? []).map((o) => o.name));
526
+ const wasNames = new Set(was.map((o) => o.name));
527
+ const readers = [];
528
+ for (const pane of panes) {
529
+ for (const input of pane.inputs ?? []) {
530
+ if (input.source !== before.id) continue;
531
+ const out = input.output || undefined;
532
+ const row = { id: pane.id, name: pane.name || pane.id, input: input.name, ...(out ? { output: out } : {}) };
533
+ if (!out) readers.push({ ...row, status: "same" });
534
+ else if (now === null) readers.push({ ...row, status: "unchecked" });
535
+ else if (!nowNames.has(out)) readers.push({ ...row, status: "gone" });
536
+ else {
537
+ const made = now.find((o) => o.name === out)?.type;
538
+ const takes = input.type === undefined ? undefined : typeText(input.type);
539
+ readers.push(made && takes && !portFits(made, takes) ? { ...row, status: "retyped", from: takes, to: made } : { ...row, status: "same" });
540
+ }
541
+ }
542
+ }
543
+ return {
544
+ outputsAdded: now === null ? [] : now.filter((o) => !wasNames.has(o.name)).map((o) => o.name),
545
+ outputsRemoved: now === null ? [] : was.filter((o) => !nowNames.has(o.name)).map((o) => o.name),
546
+ readers,
547
+ };
548
+ }
549
+
550
+ /**
551
+ * Move linked subgraph pane `id` of `canvas` to the replacement `source` (see
552
+ * planReplace), as ONE undo step: the panes inside, the link and the
553
+ * parameter form go together, and undo puts the old ones back (and redo the
554
+ * new). Wires stay by input name; wires to ports that are gone stay, flagged.
555
+ * It reruns (once the canvas is running). Returns the plan.
556
+ */
557
+ export function acceptReplacement(canvas, id, source) {
558
+ const pane = canvas.panes.get(id);
559
+ if (pane?.type !== "subgraph" || !canvas.attached.has(id) || !pane.ref) throw new Error("That isn't a linked subgraph pane on this canvas.");
560
+ const plan = planReplace(pane, source, { rootId: canvas.root.id });
561
+ const before = structuredClone({ graph: pane.graph, output: pane.output ?? null, ref: pane.ref, ...(pane.params ? { params: pane.params } : {}) });
562
+ const put = (state) => {
563
+ disposeInner(canvas, id); // before the new graph: disposing saves the inner canvas into the pane
564
+ canvas.update(id, structuredClone(state));
565
+ canvas.flow.invalidate(id);
566
+ };
567
+ const after = { graph: plan.graph, output: plan.output, ref: plan.ref, ...(plan.params ? { params: plan.params } : {}) };
568
+ canvas.contentStep(() => put(after), () => put(before), undefined, `replacing ${pane.name || id} with a newer version`);
569
+ carryPackagePane(canvas.root, source);
570
+ return plan;
571
+ }
572
+
573
+ /**
574
+ * What accepting `source` on template `key` of repeater pane content
575
+ * `repeater` would make, without changing anything: planUpdate's
576
+ * `{ ports, flagged, lostOutputs, ref, graph }` plus `entry`, the template's
577
+ * new `{ name, ref, graph }`. Ports are the repeater's inputs: `flagged` are
578
+ * its wires into an input pane the old template had and the new one hasn't
579
+ * (another template may still use them), `lostOutputs` its exposed panes
580
+ * (`each.expose`) the old template had and the new one hasn't (instances of
581
+ * it are left out of them). Throws when `source` would make a loop.
582
+ */
583
+ export function planTemplateUpdate(repeater, key, source, { rootId, keepPersonOnly = true } = {}) {
584
+ const t = repeater?.each?.templates?.[key];
585
+ if (!t?.ref?.canvas || !Array.isArray(t.graph?.panes)) throw new Error(`"${repeater?.name || repeater?.id}" has no linked template "${key}".`);
586
+ const content = { type: "subgraph", id: `${repeater.id}@${key}`, name: t.name ?? key, inputs: repeater.inputs ?? [], graph: t.graph, output: null, ref: t.ref };
587
+ const plan = planUpdate(content, source, { rootId, follow: false, keepPersonOnly }); // a repeater's wires belong to its instances: no rename is followed
588
+ const had = new Set(portsOf(content).map((p) => p.name));
589
+ const flagged = plan.flagged.filter((f) => had.has(f.name));
590
+ const lostOutputs = (cleanExpose(repeater.each?.expose) ?? []).filter((e) => exposedPath(graphPanes(content), e.pane) && !exposedPath(plan.graph.panes, e.pane)).map((e) => ({ name: e.name, pane: e.pane }));
591
+ const entry = { ...t, name: source.name ?? t.name, ref: plan.ref, graph: plan.graph };
592
+ return { ...plan, flagged, lostOutputs, entry, template: key };
593
+ }
594
+
595
+ /**
596
+ * Accept an update on template `key` of repeater pane `id` of `canvas`
597
+ * : the template takes the new version and the repeater reruns, and
598
+ * its instances of that template follow it in place (src/model/repeater.js
599
+ * applyTemplate): panes that are in both versions unchanged keep their values
600
+ * and state, changed ones rerun. Returns the plan (see planTemplateUpdate).
601
+ */
602
+ export function acceptTemplateUpdate(canvas, id, key, source) {
603
+ const pane = canvas.panes.get(id);
604
+ if (pane?.type !== "subgraph" || !canvas.attached.has(id)) throw new Error("That isn't a subgraph pane on this canvas.");
605
+ const plan = planTemplateUpdate(pane, key, source, { rootId: canvas.root.id });
606
+ canvas.update(id, { each: { ...pane.each, templates: { ...pane.each.templates, [key]: plan.entry } } });
607
+ const root = canvas.root;
608
+ if (root.library?.[plan.ref.canvas]) delete root.library[plan.ref.canvas]; // as acceptUpdate: the carried version is behind
609
+ carryPackagePane(root, source);
610
+ return plan;
611
+ }
612
+
613
+ /**
614
+ * What moving template `key` of repeater pane content `repeater` to another
615
+ * package pane `source` (the replacement a deprecation notice names) would
616
+ * make, without changing anything: planTemplateUpdate's plan for the template
617
+ * as if it already followed `source` (the repeater's inputs matched by name, so
618
+ * `ports.added`, `.removed` and `.retyped` say what the replacement takes
619
+ * differently, `flagged` the wires into inputs it hasn't, `lostOutputs` the
620
+ * exposed panes it hasn't) with `entry`, the template's new `{ name, ref, graph }`.
621
+ * Nothing is rewired. Throws when there is no such linked template, or when
622
+ * `source` would make a loop.
623
+ */
624
+ export function planTemplateReplace(repeater, key, source, { rootId } = {}) {
625
+ const t = repeater?.each?.templates?.[key];
626
+ if (!t?.ref?.canvas || !Array.isArray(t.graph?.panes)) throw new Error(`"${repeater?.name || repeater?.id}" has no linked template "${key}".`);
627
+ if (!source?.id) throw new Error("The replacement isn't a canvas.");
628
+ const moved = { ...repeater, each: { ...repeater.each, templates: { ...repeater.each.templates, [key]: { ...t, ref: { ...t.ref, canvas: source.id } } } } };
629
+ return { ...planTemplateUpdate(moved, key, source, { rootId, keepPersonOnly: false }), replacing: t.ref.canvas };
630
+ }
631
+
632
+ /**
633
+ * Move template `key` of repeater pane `id` of `canvas` to the replacement
634
+ * `source` (see planTemplateReplace) as ONE undo step: its instances follow in
635
+ * place as for an update. Returns the plan.
636
+ */
637
+ export function acceptTemplateReplacement(canvas, id, key, source) {
638
+ const pane = canvas.panes.get(id);
639
+ if (pane?.type !== "subgraph" || !canvas.attached.has(id)) throw new Error("That isn't a subgraph pane on this canvas.");
640
+ const plan = planTemplateReplace(pane, key, source, { rootId: canvas.root.id });
641
+ const before = structuredClone(pane.each.templates[key]);
642
+ const put = (entry) => {
643
+ const now = canvas.panes.get(id);
644
+ canvas.update(id, { each: { ...now.each, templates: { ...now.each.templates, [key]: structuredClone(entry) } } });
645
+ };
646
+ canvas.contentStep(() => put(plan.entry), () => put(before), undefined, `replacing the template ${key} of ${pane.name || id}`);
647
+ carryPackagePane(canvas.root, source);
648
+ return plan;
649
+ }
650
+
651
+ /**
652
+ * The deprecated package panes among `panes` that a canvas can act on (its own
653
+ * linked panes, those inside its copy subgraphs and its repeaters' templates:
654
+ * ownLinkedPanes): `[{ path, name, package, pane, version, notice, removal,
655
+ * template? }]`. `notice` is the author's (the installed package's, else the
656
+ * copy the canvas carries), `version` the copy the pane runs, `removal` how its
657
+ * planned removal stands against that (removalState). `where` is linkStatus's.
658
+ */
659
+ export function deprecatedPanes(panes, where) {
660
+ return ownLinkedPanes(panes).flatMap(({ pane, path, template, repeater }) => {
661
+ const status = linkStatus(pane, where);
662
+ if (!status?.deprecated) return [];
663
+ const name = template === undefined ? pane.name || pane.id : `template “${template}” of “${repeater.name || repeater.id}”`;
664
+ return [{ path, name, ...(template === undefined ? {} : { template }), ...(pane.ref.package ? { package: pane.ref.package, pane: pane.ref.pane } : {}), version: pane.ref.version, notice: status.deprecated, removal: removalState(status.deprecated, pane.ref.version) }];
665
+ });
666
+ }
667
+
668
+ /**
669
+ * A package pane (a doc from src/packages/package.js paneDoc) as the library
670
+ * entry the canvas carries, with the pane's description, icon, tests and
671
+ * hosts: whoever opens the file can install the whole pane from it.
672
+ * Nothing for a saved canvas's doc.
673
+ */
674
+ export function carryPackagePane(root, doc) {
675
+ if (!doc?.package?.name || !isPackageId(doc.id) || !root) return;
676
+ const info = doc.paneInfo ?? {};
677
+ const pkg = { ...doc.package, ...(info.description !== undefined ? { description: info.description } : {}), ...(info.icon !== undefined ? { icon: info.icon } : {}), ...(doc.tests?.length ? { tests: structuredClone(doc.tests) } : {}), ...(info.hosts?.length ? { hosts: [...info.hosts] } : {}), ...(info.deprecated ? { deprecated: structuredClone(info.deprecated) } : {}) };
678
+ root.library ??= {};
679
+ root.library[doc.id] = { name: doc.name, hash: linkHash(doc.panes ?? [], doc.groups, doc.presentation), graph: { panes: structuredClone(stripPins(doc.panes ?? [])), ...(doc.viewport ? { viewport: doc.viewport } : {}), ...(doc.groups ? { groups: structuredClone(doc.groups) } : {}), ...(doc.presentation ? { presentation: structuredClone(doc.presentation) } : {}) }, package: pkg };
680
+ // The package's shared module (src/packages/module.js): once per package version, whichever of its panes brought it.
681
+ if (doc.packageModule?.source) (root.packageModules ??= {})[moduleKey(doc.package.name, doc.package.version)] = structuredClone(doc.packageModule);
682
+ }
683
+
684
+ /** "Edit just this one": linked subgraph pane `id` becomes a copy (its graph stays; `from` records where it came from). */
685
+ export function detachLinked(canvas, id) {
686
+ const pane = canvas.panes.get(id);
687
+ if (!pane?.ref) throw new Error("That subgraph pane isn't linked to a canvas.");
688
+ const { ref } = pane;
689
+ const from = pane.from === undefined ? undefined : structuredClone(pane.from);
690
+ const apply = () => {
691
+ delete canvas.panes.get(id).ref;
692
+ canvas.update(id, { from: { id: ref.canvas, name: ref.name } });
693
+ };
694
+ const revert = () => {
695
+ const now = canvas.panes.get(id);
696
+ if (!now) return;
697
+ now.ref = structuredClone(ref);
698
+ if (from === undefined) delete now.from;
699
+ canvas.update(id, from === undefined ? {} : { from: structuredClone(from) });
700
+ };
701
+ canvas.contentStep(apply, revert, undefined, `making ${pane.name || id} a copy of ${ref.name}`);
702
+ return ref;
703
+ }
704
+
705
+ /**
706
+ * The live canvas that holds the pane at the end of `path` (ids from `canvas`
707
+ * down through copy subgraph panes), made on first use as running them does.
708
+ * Throws when a step isn't a subgraph pane there.
709
+ */
710
+ export function canvasAt(canvas, path) {
711
+ let c = canvas;
712
+ for (const id of path.slice(0, -1)) {
713
+ if (c.panes.get(id)?.type !== "subgraph" || !c.attached.has(id)) throw new Error("That pane isn't inside a subgraph here any more.");
714
+ c = innerCanvas(c, id);
715
+ }
716
+ return c;
717
+ }
718
+
719
+ /**
720
+ * Accept an update on the linked pane at `path` (ownLinkedPanes): on this
721
+ * canvas, or inside a copy subgraph that isn't open. The copy saves the
722
+ * change into its pane like any edit inside it. With `template`, the path
723
+ * ends at a repeater and that template of it takes the update.
724
+ * Returns the plan.
725
+ */
726
+ export function acceptAt(canvas, path, source, { template } = {}) {
727
+ const holder = canvasAt(canvas, path);
728
+ const id = path[path.length - 1];
729
+ return template === undefined ? acceptUpdate(holder, id, source) : acceptTemplateUpdate(holder, id, template, source);
730
+ }
731
+
732
+ /**
733
+ * Has the live canvas inside linked pane `id` been edited (its panes no
734
+ * longer the link's)? A linked pane's view shows its own copy running,
735
+ * but its graph changes only through an update: edits there are never saved
736
+ * into the pane (syncGraph), and leaving puts the copy back. Returns true
737
+ * when it did (the pane then reruns from its graph).
738
+ */
739
+ export function resetInstance(canvas, id) {
740
+ const pane = canvas.panes.get(id);
741
+ const inner = canvas.subgraphs?.get(id);
742
+ if (!pane?.ref || !inner) return false;
743
+ const { panes, groups } = inner.toJSON();
744
+ if (linkHash(panes, groups) === linkHash(graphPanes(pane), pane.graph?.groups)) return false;
745
+ disposeInner(canvas, id); // the edited copy goes (syncGraph leaves a linked pane's graph alone)
746
+ canvas.flow.invalidate(id);
747
+ return true;
748
+ }
749
+
750
+ /**
751
+ * The updates "follow automatically" may take without a review: linked
752
+ * panes on `canvas` (and inside its copy subgraphs) whose source is the
753
+ * person's own saved canvas, run before (trusted), never a library entry
754
+ * that came with a file or link, nor a package; and whose update keeps
755
+ * every wire and output (nothing flagged, no input retyped). The rest stay
756
+ * offered as "use new version". A repeater's templates too, with
757
+ * `template`. [{ path, pane, source, plan, template? }]
758
+ */
759
+ export function autoFollowable(canvas, where) {
760
+ const out = [];
761
+ for (const { pane, path, template, repeater } of ownLinkedPanes([...canvas.attached].map((id) => canvas.panes.get(id)))) {
762
+ if (pane.ref.package) continue;
763
+ const source = linkSource(pane.ref, where);
764
+ if (source?.from !== "canvas" || source.trusted !== true || source.hash === pane.ref.hash) continue;
765
+ let plan;
766
+ try {
767
+ plan = template === undefined ? planUpdate(pane, source.doc, { rootId: canvas.root.id }) : planTemplateUpdate(repeater, template, source.doc, { rootId: canvas.root.id });
768
+ } catch {
769
+ continue; // a loop: the review says why
770
+ }
771
+ if (plan.flagged.length || plan.lostOutputs.length || plan.ports.retyped?.length || plan.followed?.length) continue; // a rename that moves a wire waits for its review too
772
+ out.push({ path, pane, source, plan, ...(template === undefined ? {} : { template }) });
773
+ }
774
+ return out;
775
+ }
776
+
777
+ // ── inserting ──────────────────────────────────────────────────────────────
778
+
779
+ /** The settings insertLinked's `extra` may carry: a package pane's inputs. Never the name, graph, outputs or ref. */
780
+ const EXTRA_KEYS = ["params"];
781
+
782
+ /** A saved canvas (its doc) as a new linked subgraph pane at `at`. `extra` is more settings for the pane (a package pane's `params`). Throws when it would contain itself. Returns its id. */
783
+ export function insertLinked(canvas, doc, at = { x: 0, y: 0 }, extra = {}) {
784
+ for (const key of Object.keys(extra)) if (!EXTRA_KEYS.includes(key)) throw new Error(`insertLinked: ${key} is not an extra setting (only ${EXTRA_KEYS.join(", ")})`);
785
+ const root = canvas.root;
786
+ const problem = insertProblem(root.id, doc);
787
+ if (problem) throw new Error(problem);
788
+ const taken = tagsIn([...root.attached].map((pid) => root.panes.get(pid)));
789
+ const tag = newTag(taken);
790
+ const graph = instanceGraph(doc, tag);
791
+ const outputs = leafOutputs({ graph, output: null });
792
+ carryPackagePane(root, doc); // a package pane: the canvas carries it whole (first: its shared module is there when its inner canvas starts)
793
+ const id = canvas.createPane("subgraph", at, { name: insertName(doc.name), graph, output: null, ...(outputs ? { outputs } : {}), ...(doc.presentation?.panes?.length ? { composite: true } : {}), ...extra, ref: { canvas: doc.id, name: doc.name, hash: linkHash(doc.panes ?? [], doc.groups, doc.presentation), tag, ...packageFields(doc.package) } });
794
+ return id;
795
+ }
796
+
797
+ /**
798
+ * A saved canvas or package pane (its doc) as a repeater's template
799
+ * (src/model/repeater.js `each.templates`): `{ name, ref, graph }`, a linked
800
+ * subgraph's ref with its own tag and the graph it runs. Throws when it would
801
+ * make a loop inside `canvas`'s root. A package pane is carried whole.
802
+ */
803
+ export function linkedTemplate(canvas, doc) {
804
+ const root = canvas.root;
805
+ const problem = insertProblem(root.id, doc);
806
+ if (problem) throw new Error(problem);
807
+ const tag = newTag(tagsIn([...root.attached].map((pid) => root.panes.get(pid))));
808
+ carryPackagePane(root, doc);
809
+ return { name: doc.name, ref: { canvas: doc.id, name: doc.name, hash: linkHash(doc.panes ?? [], doc.groups, doc.presentation), tag, ...packageFields(doc.package) }, graph: instanceGraph(doc, tag) };
810
+ }
811
+
812
+ /**
813
+ * Insert saved canvas `doc` into `canvas` as a subgraph pane: linked (`link`)
814
+ * or an embedded copy. Refuses a canvas that would contain itself, directly
815
+ * or through what it links to. Returns the new pane's id.
816
+ */
817
+ export function insertSaved(canvas, doc, at, { link = false } = {}) {
818
+ const problem = insertProblem(canvas.root.id, doc);
819
+ if (problem) throw new Error(problem);
820
+ return link ? insertLinked(canvas, doc, at) : insertCanvas(canvas, doc, at);
821
+ }
822
+
823
+ /** Insert as a link unless asked otherwise: yes for a canvas marked as a function, else a copy. */
824
+ export const linksByDefault = (doc) => Boolean(doc?.function);
825
+
826
+ // ── the library a file or link carries ─────────────────────────────────────
827
+
828
+ /**
829
+ * The library for a canvas's panes: every canvas they link to (nested links
830
+ * too), at the version they use: `{ <canvas id>: { name, hash, graph } }`,
831
+ * or undefined when nothing links. An entry the canvas came with (`carried`,
832
+ * from its file or link) is kept when a pane uses that version; otherwise the
833
+ * entry is the pane's own cached graph with its ids untagged.
834
+ */
835
+ export function buildLibrary(panes, carried = {}) {
836
+ const out = {};
837
+ for (const { pane } of linkedPanes(panes)) {
838
+ const id = pane.ref.canvas;
839
+ if (out[id]) continue;
840
+ const kept = carried?.[id];
841
+ if (kept && Array.isArray(kept.graph?.panes) && linkHash(kept.graph.panes, kept.graph.groups, kept.graph.presentation) === pane.ref.hash) {
842
+ out[id] = { name: kept.name ?? pane.ref.name, hash: pane.ref.hash, graph: structuredClone(kept.graph), ...packageNote(pane.ref, kept) };
843
+ continue;
844
+ }
845
+ const graph = sourceGraph(pane.graph, pane.ref.tag);
846
+ out[id] = { name: pane.ref.name, hash: linkHash(graph.panes, graph.groups, graph.presentation), graph, ...packageNote(pane.ref) };
847
+ }
848
+ return Object.keys(out).length ? out : undefined;
849
+ }
850
+
851
+ /**
852
+ * A library for a share link: an entry whose graph is exactly the one
853
+ * a pane's own cached copy gives (buildLibrary without carried entries) is
854
+ * sent without it (`graph` left out), since opening the link rebuilds it
855
+ * (expandLibrary). Entries that differ (a carried version with other
856
+ * positions, say) go whole. Files keep every entry whole.
857
+ */
858
+ export function compactLibrary(panes, library) {
859
+ if (!library) return library;
860
+ const rebuilt = buildLibrary(panes) ?? {};
861
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
862
+ return Object.fromEntries(Object.entries(library).map(([id, entry]) => [id, rebuilt[id] && entry?.hash === rebuilt[id].hash && same(entry.graph, rebuilt[id].graph) ? (({ graph, ...rest }) => rest)(entry) : entry]));
863
+ }
864
+
865
+ /** The other half of compactLibrary: every entry sent without its graph gets the one its pane's copy gives. Returns the doc. */
866
+ export function expandLibrary(doc) {
867
+ const library = doc?.library;
868
+ if (!library || typeof library !== "object" || Array.isArray(library)) return doc;
869
+ const missing = Object.entries(library).filter(([, e]) => e && typeof e === "object" && e.graph === undefined);
870
+ if (!missing.length) return doc;
871
+ const rebuilt = buildLibrary(Array.isArray(doc.panes) ? doc.panes : []) ?? {};
872
+ for (const [id, entry] of missing) if (rebuilt[id] && rebuilt[id].hash === entry.hash) library[id] = (({ graph, ...rest }) => ({ name: rest.name, hash: rest.hash, graph: rebuilt[id].graph, ...rest }))(entry); // else validateLibrary says it has no panes
873
+ return doc;
874
+ }
875
+
876
+ /** Throws a readable error unless `library` is a well-formed library (see the header). */
877
+ export function validateLibrary(library, validateGraphs) {
878
+ if (library === undefined) return;
879
+ if (!library || typeof library !== "object" || Array.isArray(library)) throw new Error("That canvas's library isn't a set of canvases.");
880
+ for (const [id, entry] of Object.entries(library)) {
881
+ if (!entry || typeof entry !== "object" || !Array.isArray(entry.graph?.panes)) throw new Error(`The linked canvas "${entry?.name || id}" in that canvas's library has no panes.`);
882
+ const pkg = entry.package;
883
+ const textOrMissing = (v) => v === undefined || typeof v === "string";
884
+ if (
885
+ pkg !== undefined &&
886
+ (!pkg ||
887
+ typeof pkg !== "object" ||
888
+ ["name", "version", "pane"].some((k) => typeof pkg[k] !== "string") ||
889
+ !textOrMissing(pkg.integrity) ||
890
+ !textOrMissing(pkg.description) ||
891
+ !textOrMissing(pkg.icon) ||
892
+ (pkg.tests !== undefined && !Array.isArray(pkg.tests)) ||
893
+ (pkg.hosts !== undefined && (!Array.isArray(pkg.hosts) || pkg.hosts.some((x) => typeof x !== "string"))))
894
+ ) {
895
+ throw new Error(`The package pane "${entry.name || id}" in that canvas's library has a malformed package note.`);
896
+ }
897
+ if (pkg?.deprecated !== undefined) checkDeprecation(pkg.deprecated, `The package pane "${entry.name || id}" in that canvas's library`); // the author's notice: bounded plain text, a replacement that names its package
898
+ validatePresentation(entry.graph.presentation); // the function's composite view
899
+ validateGraphs?.(entry.graph.panes, ` (in the linked canvas "${entry.name || id}")`);
900
+ }
901
+ }
902
+
903
+ /** The library's canvases as canvas docs (to save as the person's own canvases): [{ id, name, viewport, panes }]. Package panes aren't canvases: they are installed as packages (src/packages/). */
904
+ export const libraryDocs = (library) =>
905
+ Object.entries(library ?? {})
906
+ .filter(([id, e]) => Array.isArray(e?.graph?.panes) && !e.package && !isPackageId(id) && isSafeCanvasId(id)) // an id that is not one plain segment can't be a saved canvas (D17)
907
+ .map(([id, e]) => ({ id, name: e.name || "linked canvas", viewport: e.graph.viewport ?? { x: 60, y: 80, zoom: 1 }, panes: stripPersonOnlyList(e.graph.panes), /* settings only the person turns on are not saved with a canvas that came from a file (src/model/person-only.js) */ ...(e.graph.groups ? { groups: structuredClone(e.graph.groups) } : {}), ...(e.graph.presentation ? { presentation: structuredClone(e.graph.presentation) } : {}) }));
908
+
909
+ // ── headless: resolving links without a person to ask ──────────────────────
910
+
911
+ /**
912
+ * Bring every linked subgraph pane in `doc`, and every repeater's linked
913
+ * template, up to the newest definition a headless run was given: a
914
+ * canvas in `lib` (`--lib dir/`, matched by canvas id, then by name), else
915
+ * the doc's own `library` entry, else the cached graph as it is. Pure:
916
+ * returns `{ doc, notes }`, a copy and what changed.
917
+ * @param {object} doc a canvas doc
918
+ * @param {{ lib?: { doc: object, file?: string }[] }} [options]
919
+ */
920
+ export function resolveLinks(doc, { lib = [] } = {}) {
921
+ const copy = structuredClone(doc);
922
+ const notes = [];
923
+ const byId = new Map(lib.map((l) => [l.doc.id, l]));
924
+ const byName = new Map();
925
+ for (const l of lib) if (l.doc.name && !byName.has(l.doc.name)) byName.set(l.doc.name, l);
926
+ const label = (p) => p.name || p.id;
927
+ // The newest definition a run was given for a ref, or null. A package pane is matched by its id only
928
+ // (`pkg:<package>/<pane>`, from --pkg or a package in --lib), never by a canvas's name.
929
+ const sourceFor = (ref) => {
930
+ const found = byId.get(ref.canvas) ?? (ref.package || isPackageId(ref.canvas) ? undefined : byName.get(ref.name));
931
+ const entry = copy.library?.[ref.canvas];
932
+ if (found) return { doc: found.doc, where: `--lib ${found.file ?? found.doc.name}` };
933
+ return entry && Array.isArray(entry.graph?.panes) ? { doc: entryDoc(ref.canvas, entry, ref), where: "the canvas's library" } : null;
934
+ };
935
+ const newer = (source, ref) => source && linkHash(source.doc.panes ?? [], source.doc.groups, source.doc.presentation) !== ref.hash;
936
+ // A repeater's templates: each takes the newest version too; its instances are made from it.
937
+ const templates = (pane, stack) => {
938
+ for (const { key, content } of templatesOf(pane)) {
939
+ const { ref } = content;
940
+ if (stack.includes(ref.canvas)) continue;
941
+ const source = sourceFor(ref);
942
+ const what = `repeater "${label(pane)}", template "${key}"`;
943
+ if (newer(source, ref)) {
944
+ try {
945
+ const plan = planTemplateUpdate(pane, key, source.doc, { rootId: copy.id });
946
+ pane.each.templates[key] = plan.entry;
947
+ notes.push(`${what} uses "${source.doc.name || ref.canvas}" from ${source.where}`);
948
+ for (const f of plan.flagged) notes.push(`${what}: input "${f.name}" feeds no port of "${source.doc.name || ref.canvas}" any more`);
949
+ for (const o of plan.lostOutputs) notes.push(`${what}: "${source.doc.name || ref.canvas}" has no pane "${o.pane}" any more, so its instances are left out of "${o.name}"`);
950
+ } catch (error) {
951
+ notes.push(`${what}: ${error.message} (using the copy in the file)`);
952
+ }
953
+ }
954
+ walk(graphPanes(pane.each.templates[key]), [...stack, ref.canvas]);
955
+ }
956
+ };
957
+ const walk = (panes, stack) => {
958
+ for (const pane of panes ?? []) {
959
+ if (pane?.type !== "subgraph") continue;
960
+ const ref = pane.ref;
961
+ templates(pane, stack);
962
+ if (ref?.canvas && !stack.includes(ref.canvas)) {
963
+ const source = sourceFor(ref);
964
+ if (newer(source, ref)) {
965
+ try {
966
+ const plan = planUpdate(pane, source.doc, { rootId: copy.id });
967
+ Object.assign(pane, { graph: plan.graph, output: plan.output, ref: plan.ref, ...(plan.outputs ? { outputs: plan.outputs } : {}) });
968
+ notes.push(`linked subgraph "${label(pane)}" uses "${source.doc.name || ref.canvas}" from ${source.where}`);
969
+ for (const f of plan.flagged) notes.push(`linked subgraph "${label(pane)}": input "${f.name}" feeds no port of "${source.doc.name || ref.canvas}" any more`);
970
+ for (const o of plan.lostOutputs) notes.push(`linked subgraph "${label(pane)}": "${source.doc.name || ref.canvas}" makes no "${o.name}" output any more (what reads it skips)`);
971
+ } catch (error) {
972
+ notes.push(`linked subgraph "${label(pane)}": ${error.message} (using the copy in the file)`);
973
+ }
974
+ }
975
+ }
976
+ walk(graphPanes(pane), ref?.canvas ? [...stack, ref.canvas] : stack);
977
+ }
978
+ };
979
+ walk(copy.panes, [copy.id]);
980
+ return { doc: copy, notes };
981
+ }