yaml-flow 7.1.0 → 8.0.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 (386) hide show
  1. package/browser/asset-integrity.json +8 -4
  2. package/browser/board-livecards-client.js +1 -1
  3. package/browser/board-livecards-localstorage.js +5 -5
  4. package/browser/live-cards.js +19 -3309
  5. package/cli/board-live-cards-lib-tjYsPt5U.d.ts +321 -0
  6. package/{dist/cli → cli}/browser-api/board-live-cards-browser-adapter.d.ts +3 -5
  7. package/{dist/cli → cli}/browser-api/card-store-browser-api.d.ts +1 -2
  8. package/{dist/cli → cli}/browser-api/card-store-browser-api.js +1 -1
  9. package/cli/execution-interface-C_A6WCiK.d.ts +284 -0
  10. package/{dist/cli → cli}/node/artifacts-store-cli.js +2 -2
  11. package/cli/node/batch-runner-cli.js +3 -0
  12. package/cli/node/board-live-cards-cli.js +15 -0
  13. package/{dist/cli → cli}/node/execution-adapter.d.ts +3 -3
  14. package/cli/node/execution-adapter.js +3 -0
  15. package/{dist/cli → cli}/node/fs-board-adapter.d.ts +24 -11
  16. package/cli/node/fs-board-adapter.js +14 -0
  17. package/cli/node/step-machine-cli.d.ts +7 -0
  18. package/cli/node/step-machine-cli.js +5 -0
  19. package/{dist/board-live-cards-public-5n1-syA3.d.cts → cli/types-CziUxkiv.d.ts} +68 -5
  20. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/gandalf-runtime/.config/card-store-ref.json +1 -0
  21. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/gandalf-runtime/.config/chat-handler.json +1 -0
  22. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/gandalf-runtime/.config/outputs-store-ref.json +1 -0
  23. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/gandalf-runtime/.config/task-executor.json +1 -0
  24. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/gandalf-runtime/.state-snapshot/board/graph.json +29 -0
  25. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/gandalf-runtime/.state-snapshot/board/lastJournalProcessedId.json +1 -0
  26. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/gandalf-runtime-out/.outputs/status.json +25 -0
  27. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/runtime-out/.outputs/cards/card-market-prices/computed_values.json +67 -0
  28. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/runtime-out/.outputs/cards/card-portfolio/computed_values.json +1 -0
  29. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/runtime-out/.outputs/cards/card-portfolio-value/computed_values.json +52 -0
  30. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/runtime-out/.outputs/data-objects/holdings.json +22 -0
  31. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/runtime-out/.outputs/data-objects/positions.json +46 -0
  32. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/runtime-out/.outputs/data-objects/quotes.json +35 -0
  33. package/examples/board/.demo-setup/run-1778643703151-3360-dopnpv/board-default/runtime-out/.outputs/status.json +113 -0
  34. package/examples/{example-board → board}/demo-server-config.json +0 -1
  35. package/examples/{example-board → board}/demo-server.js +23 -48
  36. package/examples/{example-board → board}/demo-shell-with-server.html +3 -3
  37. package/examples/{example-board → board}/demo-task-executor.js +71 -24
  38. package/examples/board/gandalf-cards/card-source-kinds.json +36 -0
  39. package/examples/board/gandalf-cards/cards/_index.json +7 -0
  40. package/examples/board/gandalf-cards/cards/card-source-kinds.json +64 -0
  41. package/examples/board/source-def-flows/copilot.flow.json +33 -0
  42. package/examples/board/source-def-flows/mock.flow.json +35 -0
  43. package/examples/board/source-def-flows/url-list.flow.json +33 -0
  44. package/examples/board/source-def-flows/url.flow.json +33 -0
  45. package/examples/board/source-def-flows/workiq.flow.json +34 -0
  46. package/examples/board/source-def-handlers/copilot-source-handler.js +141 -0
  47. package/examples/board/source-def-handlers/http-source-handler.js +145 -0
  48. package/examples/board/source_def_flows.json +249 -0
  49. package/examples/board/test/demo-http-test.js +317 -0
  50. package/examples/{example-board → board-local}/demo-shell-localstorage.html +4 -4
  51. package/examples/{browser/boards/portfolio-tracker → portfolio-tracker/handlers}/portfolio-tracker-fetch-prices.js +1 -1
  52. package/examples/{browser/boards/portfolio-tracker/portfolio-tracker-public.js → portfolio-tracker/portfolio-tracker.js} +11 -14
  53. package/examples/{browser/boards/portfolio-tracker → portfolio-tracker/test}/portfolio-t4.js +32 -50
  54. package/lib/artifacts-store-lib-public-BABrgFkV.d.ts +119 -0
  55. package/lib/artifacts-store-lib-public-DGa8BpJT.d.cts +119 -0
  56. package/lib/artifacts-store-public.cjs +2 -0
  57. package/lib/artifacts-store-public.d.cts +5 -0
  58. package/lib/artifacts-store-public.d.ts +5 -0
  59. package/lib/artifacts-store-public.js +2 -0
  60. package/lib/board-live-cards-node.cjs +14 -0
  61. package/{dist/cli/node/execution-adapter.d.cts → lib/board-live-cards-node.d.cts} +45 -85
  62. package/lib/board-live-cards-node.d.ts +134 -0
  63. package/lib/board-live-cards-node.js +14 -0
  64. package/lib/board-live-cards-public-BnmRAbQV.d.cts +383 -0
  65. package/{dist/board-live-cards-public-CK_J8uv0.d.ts → lib/board-live-cards-public-CsmYrvpd.d.ts} +142 -76
  66. package/lib/board-live-cards-public.cjs +3 -0
  67. package/lib/board-live-cards-public.d.cts +4 -0
  68. package/lib/board-live-cards-public.d.ts +4 -0
  69. package/lib/board-live-cards-public.js +3 -0
  70. package/lib/board-live-cards-server-runtime.cjs +9 -0
  71. package/lib/board-live-cards-server-runtime.d.cts +6 -0
  72. package/lib/board-live-cards-server-runtime.d.ts +6 -0
  73. package/lib/board-live-cards-server-runtime.js +9 -0
  74. package/lib/board-livegraph-runtime/index.cjs +3 -0
  75. package/{dist → lib}/board-livegraph-runtime/index.d.cts +1 -2
  76. package/{dist → lib}/board-livegraph-runtime/index.d.ts +1 -2
  77. package/lib/board-livegraph-runtime/index.js +3 -0
  78. package/{dist/storage-refs.cjs → lib/board-worker-adapter.cjs} +2 -2
  79. package/{dist/storage-refs.d.cts → lib/board-worker-adapter.d.cts} +4 -3
  80. package/{dist/storage-refs.d.ts → lib/board-worker-adapter.d.ts} +4 -3
  81. package/{dist/storage-refs.js → lib/board-worker-adapter.js} +2 -2
  82. package/{dist → lib}/card-compute/index.cjs +1 -1
  83. package/{dist → lib}/card-compute/index.js +1 -1
  84. package/lib/card-store-public.cjs +2 -0
  85. package/lib/card-store-public.d.cts +61 -0
  86. package/lib/card-store-public.d.ts +61 -0
  87. package/lib/card-store-public.js +2 -0
  88. package/lib/card-validation.cjs +10 -0
  89. package/lib/card-validation.d.cts +35 -0
  90. package/lib/card-validation.d.ts +35 -0
  91. package/lib/card-validation.js +10 -0
  92. package/{dist/constants-oCEbNpul.d.ts → lib/constants-BPVLb3Es.d.ts} +1 -1
  93. package/{dist/constants-BzZUyYlp.d.cts → lib/constants-DXxsRN9y.d.cts} +1 -1
  94. package/{dist → lib}/continuous-event-graph/index.cjs +2 -2
  95. package/{dist → lib}/continuous-event-graph/index.d.cts +3 -5
  96. package/{dist → lib}/continuous-event-graph/index.d.ts +3 -5
  97. package/{dist → lib}/continuous-event-graph/index.js +2 -2
  98. package/{dist → lib}/event-graph/index.d.cts +2 -2
  99. package/{dist → lib}/event-graph/index.d.ts +2 -2
  100. package/{dist → lib}/execution-refs.d.cts +29 -10
  101. package/{dist → lib}/execution-refs.d.ts +29 -10
  102. package/lib/index.cjs +25 -0
  103. package/{dist → lib}/index.d.cts +7 -8
  104. package/{dist → lib}/index.d.ts +7 -8
  105. package/lib/index.js +25 -0
  106. package/{dist/live-cards-bridge-BXbVTsna.d.cts → lib/live-cards-bridge-DC_ZU0eS.d.ts} +134 -3
  107. package/{dist/live-cards-bridge-Ds28XR15.d.ts → lib/live-cards-bridge-b25aAVvE.d.cts} +134 -3
  108. package/lib/loader-CuuLjxVA.d.cts +42 -0
  109. package/lib/loader-Zborm2pq.d.ts +42 -0
  110. package/lib/server-runtime/index.cjs +9 -0
  111. package/{dist → lib}/server-runtime/index.d.cts +4 -4
  112. package/{dist → lib}/server-runtime/index.d.ts +4 -4
  113. package/lib/server-runtime/index.js +9 -0
  114. package/lib/step-machine/index.d.cts +64 -0
  115. package/lib/step-machine/index.d.ts +64 -0
  116. package/lib/step-machine-public/index.cjs +5 -0
  117. package/{dist → lib}/step-machine-public/index.d.cts +14 -1
  118. package/{dist → lib}/step-machine-public/index.d.ts +14 -1
  119. package/lib/step-machine-public/index.js +5 -0
  120. package/lib/storage-interface-BhAON-gW.d.cts +84 -0
  121. package/lib/storage-interface-BhAON-gW.d.ts +84 -0
  122. package/lib/stores/index.cjs +3 -0
  123. package/lib/stores/index.d.cts +4 -0
  124. package/lib/stores/index.d.ts +4 -0
  125. package/lib/stores/index.js +3 -0
  126. package/lib/stores/kv.cjs +3 -0
  127. package/lib/stores/kv.d.cts +32 -0
  128. package/lib/stores/kv.d.ts +32 -0
  129. package/lib/stores/kv.js +3 -0
  130. package/{dist → lib}/stores/memory.d.cts +1 -1
  131. package/{dist → lib}/stores/memory.d.ts +1 -1
  132. package/{dist/types-HGDTWIun.d.ts → lib/types-CBxkYuLY.d.ts} +2 -1
  133. package/{dist/types-ycun84cq.d.cts → lib/types-DQ1bKuB1.d.cts} +11 -0
  134. package/{dist/types-ycun84cq.d.ts → lib/types-DQ1bKuB1.d.ts} +11 -0
  135. package/{dist/types-CU3DjTKL.d.cts → lib/types-DkFvgxwq.d.cts} +2 -1
  136. package/package.json +79 -119
  137. package/board-live-cards-cli.js +0 -37
  138. package/browser/board-livecards-client.js.map +0 -1
  139. package/browser/board-livecards-localstorage.js.map +0 -1
  140. package/browser/board-livegraph-engine.js +0 -3
  141. package/browser/board-livegraph-engine.js.map +0 -1
  142. package/browser/card-compute.js +0 -266
  143. package/browser/compute-jsonata.js.map +0 -1
  144. package/card-store.js +0 -37
  145. package/dist/batch/index.cjs.map +0 -1
  146. package/dist/batch/index.js.map +0 -1
  147. package/dist/board-live-cards-lib-Bg6EvCo5.d.cts +0 -136
  148. package/dist/board-live-cards-lib-jM2uYG1v.d.ts +0 -136
  149. package/dist/board-livegraph-runtime/index.cjs +0 -3
  150. package/dist/board-livegraph-runtime/index.cjs.map +0 -1
  151. package/dist/board-livegraph-runtime/index.js +0 -3
  152. package/dist/board-livegraph-runtime/index.js.map +0 -1
  153. package/dist/card-compute/index.cjs.map +0 -1
  154. package/dist/card-compute/index.js.map +0 -1
  155. package/dist/cli/browser-api/board-live-cards-browser-adapter.cjs +0 -3
  156. package/dist/cli/browser-api/board-live-cards-browser-adapter.cjs.map +0 -1
  157. package/dist/cli/browser-api/board-live-cards-browser-adapter.d.cts +0 -37
  158. package/dist/cli/browser-api/board-live-cards-browser-adapter.js.map +0 -1
  159. package/dist/cli/browser-api/card-store-browser-api.cjs +0 -2
  160. package/dist/cli/browser-api/card-store-browser-api.cjs.map +0 -1
  161. package/dist/cli/browser-api/card-store-browser-api.d.cts +0 -26
  162. package/dist/cli/browser-api/card-store-browser-api.js.map +0 -1
  163. package/dist/cli/node/artifacts-store-cli.cjs +0 -11
  164. package/dist/cli/node/artifacts-store-cli.cjs.map +0 -1
  165. package/dist/cli/node/artifacts-store-cli.d.cts +0 -8
  166. package/dist/cli/node/artifacts-store-cli.js.map +0 -1
  167. package/dist/cli/node/board-live-cards-cli.cjs +0 -15
  168. package/dist/cli/node/board-live-cards-cli.cjs.map +0 -1
  169. package/dist/cli/node/board-live-cards-cli.d.cts +0 -20
  170. package/dist/cli/node/board-live-cards-cli.js +0 -15
  171. package/dist/cli/node/board-live-cards-cli.js.map +0 -1
  172. package/dist/cli/node/card-store-cli.cjs +0 -8
  173. package/dist/cli/node/card-store-cli.cjs.map +0 -1
  174. package/dist/cli/node/card-store-cli.d.cts +0 -15
  175. package/dist/cli/node/card-store-cli.js.map +0 -1
  176. package/dist/cli/node/execution-adapter.cjs +0 -3
  177. package/dist/cli/node/execution-adapter.cjs.map +0 -1
  178. package/dist/cli/node/execution-adapter.js +0 -3
  179. package/dist/cli/node/execution-adapter.js.map +0 -1
  180. package/dist/cli/node/fs-board-adapter.cjs +0 -14
  181. package/dist/cli/node/fs-board-adapter.cjs.map +0 -1
  182. package/dist/cli/node/fs-board-adapter.d.cts +0 -204
  183. package/dist/cli/node/fs-board-adapter.js +0 -14
  184. package/dist/cli/node/fs-board-adapter.js.map +0 -1
  185. package/dist/cli/node/source-cli-task-executor.cjs +0 -11
  186. package/dist/cli/node/source-cli-task-executor.cjs.map +0 -1
  187. package/dist/cli/node/source-cli-task-executor.js.map +0 -1
  188. package/dist/config/index.cjs.map +0 -1
  189. package/dist/config/index.js.map +0 -1
  190. package/dist/continuous-event-graph/index.cjs.map +0 -1
  191. package/dist/continuous-event-graph/index.js.map +0 -1
  192. package/dist/event-graph/index.cjs.map +0 -1
  193. package/dist/event-graph/index.js.map +0 -1
  194. package/dist/execution-refs.cjs.map +0 -1
  195. package/dist/execution-refs.js.map +0 -1
  196. package/dist/index.cjs +0 -30
  197. package/dist/index.cjs.map +0 -1
  198. package/dist/index.js +0 -30
  199. package/dist/index.js.map +0 -1
  200. package/dist/inference/index.cjs +0 -7
  201. package/dist/inference/index.cjs.map +0 -1
  202. package/dist/inference/index.d.cts +0 -229
  203. package/dist/inference/index.d.ts +0 -229
  204. package/dist/inference/index.js +0 -7
  205. package/dist/inference/index.js.map +0 -1
  206. package/dist/server-runtime/index.cjs +0 -9
  207. package/dist/server-runtime/index.cjs.map +0 -1
  208. package/dist/server-runtime/index.js +0 -9
  209. package/dist/server-runtime/index.js.map +0 -1
  210. package/dist/step-machine/index.cjs.map +0 -1
  211. package/dist/step-machine/index.d.cts +0 -102
  212. package/dist/step-machine/index.d.ts +0 -102
  213. package/dist/step-machine/index.js.map +0 -1
  214. package/dist/step-machine-public/index.cjs +0 -3
  215. package/dist/step-machine-public/index.cjs.map +0 -1
  216. package/dist/step-machine-public/index.js +0 -3
  217. package/dist/step-machine-public/index.js.map +0 -1
  218. package/dist/storage-refs.cjs.map +0 -1
  219. package/dist/storage-refs.js.map +0 -1
  220. package/dist/stores/file.cjs +0 -2
  221. package/dist/stores/file.cjs.map +0 -1
  222. package/dist/stores/file.d.cts +0 -36
  223. package/dist/stores/file.d.ts +0 -36
  224. package/dist/stores/file.js +0 -2
  225. package/dist/stores/file.js.map +0 -1
  226. package/dist/stores/index.cjs +0 -2
  227. package/dist/stores/index.cjs.map +0 -1
  228. package/dist/stores/index.d.cts +0 -4
  229. package/dist/stores/index.d.ts +0 -4
  230. package/dist/stores/index.js +0 -2
  231. package/dist/stores/index.js.map +0 -1
  232. package/dist/stores/localStorage.cjs +0 -2
  233. package/dist/stores/localStorage.cjs.map +0 -1
  234. package/dist/stores/localStorage.d.cts +0 -34
  235. package/dist/stores/localStorage.d.ts +0 -34
  236. package/dist/stores/localStorage.js +0 -2
  237. package/dist/stores/localStorage.js.map +0 -1
  238. package/dist/stores/memory.cjs.map +0 -1
  239. package/dist/stores/memory.js.map +0 -1
  240. package/dist/types-CHSdoAAA.d.cts +0 -135
  241. package/dist/types-CoW0gQl3.d.ts +0 -135
  242. package/examples/browser/boards/portfolio-tracker/portfolio-tracker-fetch-prices.py +0 -201
  243. package/examples/browser/boards/portfolio-tracker/portfolio-tracker-http-test.js +0 -370
  244. package/examples/browser/boards/portfolio-tracker/portfolio-tracker-http-test.py +0 -398
  245. package/examples/browser/boards/portfolio-tracker/portfolio-tracker-inference-adapter.js +0 -196
  246. package/examples/browser/boards/portfolio-tracker/portfolio-tracker-server.js +0 -300
  247. package/examples/browser/boards/portfolio-tracker/portfolio-tracker-server.py +0 -617
  248. package/examples/browser/boards/portfolio-tracker/portfolio-tracker.py +0 -366
  249. package/examples/browser/livecards-browser/index.html +0 -41
  250. package/examples/browser/step-machine-browser/index.html +0 -367
  251. package/examples/cli/step-machine-cli/portfolio-tracker/--base-ref/.runtime-out +0 -1
  252. package/examples/cli/step-machine-cli/portfolio-tracker/--base-ref/board-graph.json +0 -32
  253. package/examples/cli/step-machine-cli/portfolio-tracker/cards/holdings-table.json +0 -22
  254. package/examples/cli/step-machine-cli/portfolio-tracker/cards/portfolio-form.json +0 -43
  255. package/examples/cli/step-machine-cli/portfolio-tracker/cards/portfolio-value.json +0 -15
  256. package/examples/cli/step-machine-cli/portfolio-tracker/cards/price-fetch.json +0 -15
  257. package/examples/cli/step-machine-cli/portfolio-tracker/fetch-prices.js +0 -48
  258. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/_board-cli.js +0 -125
  259. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/add-cards-cli.js +0 -32
  260. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/init-board-cli.js +0 -26
  261. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/poll-status-cli.js +0 -49
  262. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/reset-board-dir-cli.js +0 -25
  263. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/retrigger-cli.js +0 -23
  264. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/status-cli.js +0 -21
  265. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/update-holdings-cli.js +0 -38
  266. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/wait-completed-cli.js +0 -48
  267. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/write-prices-cli.js +0 -31
  268. package/examples/cli/step-machine-cli/portfolio-tracker/handlers-py/_board_pycli.py +0 -107
  269. package/examples/cli/step-machine-cli/portfolio-tracker/handlers-py/add-cards.py +0 -51
  270. package/examples/cli/step-machine-cli/portfolio-tracker/handlers-py/init-board.py +0 -45
  271. package/examples/cli/step-machine-cli/portfolio-tracker/handlers-py/poll-status.py +0 -71
  272. package/examples/cli/step-machine-cli/portfolio-tracker/handlers-py/reset-board-dir.py +0 -36
  273. package/examples/cli/step-machine-cli/portfolio-tracker/inline-python-demo.flow.yaml +0 -26
  274. package/examples/cli/step-machine-cli/portfolio-tracker/inline-python-handlers.py +0 -39
  275. package/examples/cli/step-machine-cli/portfolio-tracker/portfolio-tracker-pycli.flow.yaml +0 -80
  276. package/examples/cli/step-machine-cli/portfolio-tracker/portfolio-tracker.flow.yaml +0 -76
  277. package/examples/cli/step-machine-cli/portfolio-tracker/portfolio-tracker.input.json +0 -44
  278. package/examples/cli/step-machine-cli/portfolio-tracker/run-inline-python-demo-pycli.py +0 -43
  279. package/examples/cli/step-machine-cli/portfolio-tracker/run-portfolio-tracker-pycli.py +0 -77
  280. package/examples/cli/step-machine-cli/portfolio-tracker/run-portfolio-tracker.bat +0 -28
  281. package/examples/cli/step-machine-demo/jsonata-init-board-cli.js +0 -31
  282. package/examples/cli/step-machine-demo/jsonata-init-board.flow.yaml +0 -54
  283. package/examples/cli/step-machine-demo/one-step-cli-only.flow.yaml +0 -21
  284. package/examples/cli/step-machine-demo/step-cli-echo-y.js +0 -15
  285. package/examples/cli/step-machine-demo/step2-double-cli.js +0 -33
  286. package/examples/cli/step-machine-demo/two-step-math.flow.yaml +0 -93
  287. package/examples/cli/step-machine-demo/two-step-mixed.flow.yaml +0 -43
  288. package/examples/example-board/agent-instructions-cardlayout.md +0 -56
  289. package/examples/example-board/agent-instructions.md +0 -834
  290. package/examples/example-board/demo-shell.html +0 -63
  291. package/examples/index.html +0 -785
  292. package/examples/npm-libs/batch/batch-step-machine.ts +0 -121
  293. package/examples/npm-libs/continuous-event-graph/live-cards-board.ts +0 -215
  294. package/examples/npm-libs/continuous-event-graph/live-portfolio-dashboard.ts +0 -555
  295. package/examples/npm-libs/continuous-event-graph/portfolio-tracker.ts +0 -287
  296. package/examples/npm-libs/continuous-event-graph/reactive-monitoring.ts +0 -265
  297. package/examples/npm-libs/continuous-event-graph/reactive-pipeline.ts +0 -168
  298. package/examples/npm-libs/continuous-event-graph/soc-incident-board.ts +0 -287
  299. package/examples/npm-libs/continuous-event-graph/stock-dashboard.ts +0 -229
  300. package/examples/npm-libs/event-graph/ci-cd-pipeline.ts +0 -243
  301. package/examples/npm-libs/event-graph/executor-diamond.ts +0 -165
  302. package/examples/npm-libs/event-graph/executor-pipeline.ts +0 -161
  303. package/examples/npm-libs/event-graph/research-pipeline.ts +0 -137
  304. package/examples/npm-libs/flows/ai-conversation.yaml +0 -116
  305. package/examples/npm-libs/flows/order-processing.yaml +0 -143
  306. package/examples/npm-libs/flows/simple-greeting.yaml +0 -54
  307. package/examples/npm-libs/graph-of-graphs/multi-stage-etl.ts +0 -307
  308. package/examples/npm-libs/graph-of-graphs/url-processing-pipeline.ts +0 -254
  309. package/examples/npm-libs/inference/azure-deployment.ts +0 -149
  310. package/examples/npm-libs/inference/copilot-cli.ts +0 -138
  311. package/examples/npm-libs/inference/data-pipeline.ts +0 -145
  312. package/examples/npm-libs/inference/pluggable-adapters.ts +0 -254
  313. package/examples/npm-libs/node/ai-conversation.ts +0 -195
  314. package/examples/npm-libs/node/simple-greeting.ts +0 -101
  315. package/examples/step-machine-cli/portfolio-tracker/cards/holdings-table.json +0 -22
  316. package/examples/step-machine-cli/portfolio-tracker/cards/portfolio-form.json +0 -43
  317. package/examples/step-machine-cli/portfolio-tracker/cards/portfolio-value.json +0 -15
  318. package/examples/step-machine-cli/portfolio-tracker/cards/price-fetch.json +0 -15
  319. package/examples/step-machine-cli/portfolio-tracker/fetch-prices.js +0 -48
  320. package/examples/step-machine-cli/portfolio-tracker/handlers/_board-cli.js +0 -57
  321. package/examples/step-machine-cli/portfolio-tracker/handlers/add-cards-cli.js +0 -27
  322. package/examples/step-machine-cli/portfolio-tracker/handlers/init-board-cli.js +0 -25
  323. package/examples/step-machine-cli/portfolio-tracker/handlers/reset-board-dir-cli.js +0 -29
  324. package/examples/step-machine-cli/portfolio-tracker/handlers/retrigger-cli.js +0 -27
  325. package/examples/step-machine-cli/portfolio-tracker/handlers/status-cli.js +0 -25
  326. package/examples/step-machine-cli/portfolio-tracker/handlers/update-holdings-cli.js +0 -37
  327. package/examples/step-machine-cli/portfolio-tracker/handlers/wait-completed-cli.js +0 -53
  328. package/examples/step-machine-cli/portfolio-tracker/handlers/write-prices-cli.js +0 -35
  329. package/examples/step-machine-cli/portfolio-tracker/portfolio-tracker-task-executor.cjs +0 -96
  330. package/examples/step-machine-cli/portfolio-tracker/portfolio-tracker.flow.yaml +0 -227
  331. package/examples/step-machine-cli/portfolio-tracker/portfolio-tracker.input.json +0 -38
  332. package/examples/step-machine-cli/portfolio-tracker/run-portfolio-tracker.bat +0 -28
  333. package/step-machine-cli.js +0 -407
  334. /package/{dist/cli → cli}/browser-api/board-live-cards-browser-adapter.js +0 -0
  335. /package/{dist/board-livegraph-runtime → cli/browser-api}/jsonata-sync.cjs +0 -0
  336. /package/{dist/cli → cli}/node/artifacts-store-cli.d.ts +0 -0
  337. /package/{dist/cli/node/source-cli-task-executor.d.cts → cli/node/batch-runner-cli.d.ts} +0 -0
  338. /package/{dist/cli → cli}/node/board-live-cards-cli.d.ts +0 -0
  339. /package/{dist/cli → cli}/node/card-store-cli.d.ts +0 -0
  340. /package/{dist/cli → cli}/node/card-store-cli.js +0 -0
  341. /package/{dist/card-compute → cli/node}/jsonata-sync.cjs +0 -0
  342. /package/{dist/cli → cli}/node/source-cli-task-executor.d.ts +0 -0
  343. /package/{dist/cli → cli}/node/source-cli-task-executor.js +0 -0
  344. /package/examples/{example-board → board}/cards/card-concentration.json +0 -0
  345. /package/examples/{example-board → board}/cards/card-my-identity.json +0 -0
  346. /package/examples/{example-board → board}/cards/card-portfolio-action.json +0 -0
  347. /package/examples/{example-board → board}/cards/card-portfolio-intelligence.json +0 -0
  348. /package/examples/{example-board → board}/cards/card-portfolio-risks.json +0 -0
  349. /package/examples/{example-board → board}/cards/card-rebalance-impact.json +0 -0
  350. /package/examples/{example-board → board}/cards/card-rebalance-sim.json +0 -0
  351. /package/examples/{example-board → board}/cards/cardT-market-prices.json +0 -0
  352. /package/examples/{example-board → board}/cards/cardT-portfolio-value.json +0 -0
  353. /package/examples/{example-board → board}/cards/cardT-portfolio.json +0 -0
  354. /package/examples/{example-board → board}/demo-chat-handler.js +0 -0
  355. /package/examples/{example-board → board}/scripts/copilot_wrapper.bat +0 -0
  356. /package/examples/{example-board → board}/scripts/copilot_wrapper_helper.ps1 +0 -0
  357. /package/examples/{example-board → board}/scripts/workiq_wrapper.mjs +0 -0
  358. /package/examples/{browser/boards/portfolio-tracker → board/test}/portfolio-tracker-sse-worker.js +0 -0
  359. /package/{dist → lib}/batch/index.cjs +0 -0
  360. /package/{dist → lib}/batch/index.d.cts +0 -0
  361. /package/{dist → lib}/batch/index.d.ts +0 -0
  362. /package/{dist → lib}/batch/index.js +0 -0
  363. /package/{dist/cli/browser-api → lib/board-livegraph-runtime}/jsonata-sync.cjs +0 -0
  364. /package/{dist → lib}/card-compute/index.d.cts +0 -0
  365. /package/{dist → lib}/card-compute/index.d.ts +0 -0
  366. /package/{dist/cli/node → lib/card-compute}/jsonata-sync.cjs +0 -0
  367. /package/{dist → lib}/config/index.cjs +0 -0
  368. /package/{dist → lib}/config/index.d.cts +0 -0
  369. /package/{dist → lib}/config/index.d.ts +0 -0
  370. /package/{dist → lib}/config/index.js +0 -0
  371. /package/{dist → lib}/continuous-event-graph/jsonata-sync.cjs +0 -0
  372. /package/{dist → lib}/event-graph/index.cjs +0 -0
  373. /package/{dist → lib}/event-graph/index.js +0 -0
  374. /package/{dist → lib}/execution-refs.cjs +0 -0
  375. /package/{dist → lib}/execution-refs.js +0 -0
  376. /package/{dist → lib}/jsonata-sync.cjs +0 -0
  377. /package/{dist → lib}/server-runtime/jsonata-sync.cjs +0 -0
  378. /package/{dist → lib}/step-machine/index.cjs +0 -0
  379. /package/{dist → lib}/step-machine/index.js +0 -0
  380. /package/{dist → lib}/step-machine-public/jsonata-sync.cjs +0 -0
  381. /package/{dist → lib}/stores/memory.cjs +0 -0
  382. /package/{dist → lib}/stores/memory.js +0 -0
  383. /package/{dist → lib}/types-BBhqYGhE.d.cts +0 -0
  384. /package/{dist → lib}/types-BBhqYGhE.d.ts +0 -0
  385. /package/{dist → lib}/validate-BAVzUJWa.d.ts +0 -0
  386. /package/{dist → lib}/validate-Dbu7ygys.d.cts +0 -0
@@ -1,3 +0,0 @@
1
- 'use strict';var module$1=require('module');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;var A=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))),p=A("./jsonata-sync.cjs");function m(r,e){if(!r||typeof r!="object")throw new Error(`[step-machine-public] Step "${e}" returned a non-object result.`);let t=r,n=t.result??t.status;if(typeof n=="string"&&n.trim().length>0){let a=t.data&&typeof t.data=="object"&&!Array.isArray(t.data)?{...t.data}:{},s=typeof t.error=="string"?t.error:void 0;return s&&!("error"in a)&&(a.error=s),{result:n,data:a,...s?{error:s}:{}}}return {result:"success",data:{...t}}}function w(r,e){if(!e||e.length===0)return r;let t={};for(let n of e)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n]);return t}function g(r,e){return async(t,n)=>{let a=await r(t,n),s=m(a,n?.stepName??"unknown");return {result:s.result,data:w(s.data,e),...s.error?{error:s.error}:{}}}}function k(r,e,t){if(!e||e.length===0)return null;for(let n of e)try{if(!p(n).evaluate(r))return {result:"failure",data:{error:`[${t}] input validation failed: ${n}`}}}catch(a){let s=a instanceof Error?a.message:String(a);return {result:"failure",data:{error:`[${t}] input validation error on "${n}": ${s}`}}}return null}function y(r,e,t){return !e||e.length===0?r:async(n,a)=>{let s=k(n,e,t);return s||r(n,a)}}var h=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));function O(){try{return h("./jsonata-sync.cjs")}catch{return h("../../card-compute/jsonata-sync.cjs")}}var f=O();function S(r,e,t){if(!r||typeof r!="object")return e;let n={output:e},a=e.result,s=e.data,i=e.error;if(typeof r.resultExpr=="string")try{let o=f(r.resultExpr).evaluate(n);if(typeof o!="string"||!o.trim())throw new Error(`resultExpr did not produce a non-empty string (got ${JSON.stringify(o)})`);a=o;}catch(o){let u=o instanceof Error?o.message:String(o);throw new Error(`[${t}] outputTransforms.resultExpr failed: ${u}`)}if(typeof r.dataTemplate=="string")try{let o=f(r.dataTemplate).evaluate(n);if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`dataTemplate did not produce an object (got ${JSON.stringify(o)})`);s=o;}catch(o){let u=o instanceof Error?o.message:String(o);throw new Error(`[${t}] outputTransforms.dataTemplate failed: ${u}`)}if(typeof r.errorExpr=="string")try{let o=f(r.errorExpr).evaluate(n);i=o!=null?String(o):void 0;}catch(o){let u=o instanceof Error?o.message:String(o);throw new Error(`[${t}] outputTransforms.errorExpr failed: ${u}`)}return i!==void 0?{result:a,data:s,error:i}:{result:a,data:s}}var F="b64:";function z(r){let e=new TextEncoder().encode(r),t=globalThis.Buffer,n;if(t)n=t.from(e).toString("base64");else if(typeof btoa=="function"){let a="";for(let s of e)a+=String.fromCharCode(s);n=btoa(a);}else throw new Error("No base64 encoder available in this runtime");return n.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function R(r){return `${F}${z(JSON.stringify(r))}`}function x(r){return !!r&&typeof r=="object"&&r.type==="compute-jsonata"&&Array.isArray(r.expr)&&r.expr.length>0}function b(r){if(!r||typeof r!="object")return false;let e=r;if(e.type!=="ref"||typeof e.howToRun!="string")return false;if(typeof e.whatToRun=="string")return true;if(e.whatToRun&&typeof e.whatToRun=="object"){let t=e.whatToRun;return typeof t.kind=="string"&&typeof t.value=="string"}return false}function I(r){if(typeof r=="string"){let e=r.indexOf("=");if(e<1)throw new Error(`[step-machine-public] Invalid compute expression (missing "="): "${r}"`);return {bindTo:r.slice(0,e).trim(),expr:r.slice(e+1).trim()}}if(r&&typeof r=="object"&&typeof r.bindTo=="string"&&typeof r.expr=="string")return r;throw new Error(`[step-machine-public] Invalid compute step: ${JSON.stringify(r)}`)}function B(r,e,t){let n=e.split("."),a=r;for(let s=0;s<n.length-1;s++){let i=n[s];(a[i]==null||typeof a[i]!="object")&&(a[i]={}),a=a[i];}a[n[n.length-1]]=t;}function v(r,e,t){let n=r.expr.map(I);return async a=>{let s=a&&typeof a=="object"&&!Array.isArray(a)?{...a}:{},i={},o={expects_data:s,data:i,...t?{config:t}:{}},u,d;for(let l of n)try{let c=p(l.expr).evaluate(o);if(l.bindTo==="result")u=c!=null?String(c):"success";else if(l.bindTo==="error")d=c!=null?String(c):void 0;else if(l.bindTo.startsWith("data."))B(i,l.bindTo.slice(5),c);else return {result:"failure",data:{},error:`[${e}] invalid bindTo "${l.bindTo}": must be "result", "error", or start with "data."`}}catch(c){let H=c instanceof Error?c.message:String(c);return {result:"failure",data:{},error:`[${e}] compute "${l.bindTo}" failed: ${H}`}}return u===void 0?{result:"failure",data:{},error:`[${e}] compute-jsonata: no "result" binding declared \u2014 add '- result = "success"' to expr`}:d?{result:u,data:i,error:d}:{result:u,data:i}}}function j(r,e,t,n){let{type:a,...s}=r,i={...s,whatToRun:typeof s.whatToRun=="object"?R(s.whatToRun):s.whatToRun};return async o=>{let u=o&&typeof o=="object"&&!Array.isArray(o)?{...o}:{};n&&(u.config=n);try{let d=await t(i,u);if(!r.outputTransforms)return d;try{return S(r.outputTransforms,d,e)}catch(l){let c=l instanceof Error?l.message:String(l);return {result:"failure",data:{},error:c}}}catch(d){let l=d instanceof Error?d.message:String(d);return {result:"failure",data:{error:`[step-machine-public] step "${e}" invoke threw: ${l}`}}}}}function E(){return async r=>({result:"success",data:r&&typeof r=="object"&&!Array.isArray(r)?r:{}})}function T(r,e,t){let n=Array.isArray(e?.produces_data)?e?.produces_data:void 0,a=Array.isArray(e?.input_validations)?e?.input_validations:void 0,s=e?.config??void 0,i=e?.handler,o;return x(i)?o=v(i,r,s):b(i)?o=j(i,r,t.invoke,s):o=E(),y(g(o,n),a,r)}function C(r,e){let t={};for(let[n,a]of Object.entries(r.steps??{}))t[n]=T(n,a,e);return t}
2
- exports.buildStepHandlersForFlow=C;exports.createComputeJsonataHandler=v;exports.createPassthroughHandler=E;exports.createRefStepHandler=j;exports.filterProducedData=w;exports.isComputeJsonataSpec=x;exports.isRefSpec=b;exports.jsonata=p;exports.normalizeHandlerResult=m;exports.resolveStepHandler=T;exports.runInputValidations=k;exports.wrapWithInputValidations=y;exports.wrapWithOutputFiltering=g;//# sourceMappingURL=index.cjs.map
3
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/step-machine-public/jsonata-loader.ts","../../src/step-machine-public/result-utils.ts","../../src/cli/common/jsonata-loader.ts","../../src/cli/common/args-massaging.ts","../../src/cli/common/storage-interface.ts","../../src/step-machine-public/handler-factory.ts"],"names":["_require","createRequire","jsonata","normalizeHandlerResult","raw","stepName","obj","result","data","error","filterProducedData","produces","filtered","key","wrapWithOutputFiltering","handler","input","context","normalized","runInputValidations","validations","expr","err","msg","wrapWithInputValidations","failure","_loadJsonata","resolveOutputTransforms","transforms","label","ctx","val","REF_PREFIX","toBase64Url","utf8","buf","base64","binary","byte","serializeRef","ref","isComputeJsonataSpec","spec","isRefSpec","s","w","normalizeComputeStep","item","eq","deepSet","path","value","parts","cur","i","k","createComputeJsonataHandler","config","steps","expects_data","transitionResult","transitionError","step","createRefStepHandler","invoke","_t","refOnly","stepInput","createPassthroughHandler","resolveStepHandler","stepConfig","options","inputValidations","base","buildStepHandlersForFlow","flow","handlers"],"mappings":"iIAeA,IAAMA,EAAWC,sBAAAA,CAAc,2PAAe,CAAA,CAMjCC,EAA+CF,CAAAA,CAAS,oBAAoB,ECHlF,SAASG,EACdC,CAAAA,CACAC,CAAAA,CACyB,CACzB,GAAI,CAACD,CAAAA,EAAO,OAAOA,CAAAA,EAAQ,QAAA,CACzB,MAAM,IAAI,KAAA,CAAM,CAAA,4BAAA,EAA+BC,CAAQ,iCAAiC,CAAA,CAG1F,IAAMC,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A,CAAQA,CAAK,CAAA,CACrDA,EACD,EAC2B,CAAA,CAErC,CAUO,SAASqD,CAAAA,CACdhE,CAAAA,CACAiE,CAAAA,CACAC,CAAAA,CACa,CACb,IAAM5D,CAAAA,CAAW,KAAA,CAAM,OAAA,CAAQ2D,GAAY,aAAa,CAAA,CAAIA,CAAAA,EAAY,aAAA,CAAgB,OAClFE,CAAAA,CAAmB,KAAA,CAAM,OAAA,CAAQF,CAAAA,EAAY,iBAAiB,CAAA,CAChEA,CAAAA,EAAY,iBAAA,CACZ,MAAA,CACEb,EAASa,CAAAA,EAAY,MAAA,EAAU,MAAA,CAC/B5B,CAAAA,CAAgC4B,GAAY,OAAA,CAE9CG,CAAAA,CACJ,OAAIhC,CAAAA,CAAqBC,CAAI,CAAA,CAE3B+B,CAAAA,CAAOjB,CAAAA,CAA4Bd,CAAAA,CAAMrC,EAAUoD,CAAM,CAAA,CAChDd,CAAAA,CAAUD,CAAI,EACvB+B,CAAAA,CAAOV,CAAAA,CAAqBrB,CAAAA,CAAMrC,CAAAA,CAAUkE,EAAQ,MAAA,CAAQd,CAAM,CAAA,CAElEgB,CAAAA,CAAOL,GAAyB,CAG3B5C,CAAAA,CACLV,CAAAA,CAAwB2D,CAAAA,CAAM9D,CAAQ,CAAA,CACtC6D,CAAAA,CACAnE,CACF,CACF,CAUO,SAASqE,CAAAA,CACdC,CAAAA,CACAJ,CAAAA,CAC6B,CAC7B,IAAMK,CAAAA,CAAwC,EAAC,CAC/C,OAAW,CAACvE,CAAAA,CAAUiE,CAAU,CAAA,GAAK,OAAO,OAAA,CAAQK,CAAAA,CAAK,KAAA,EAAS,EAAE,CAAA,CAClEC,CAAAA,CAASvE,CAAQ,CAAA,CAAIgE,EAAmBhE,CAAAA,CAAUiE,CAAAA,CAAYC,CAAO,CAAA,CAEvE,OAAOK,CACT","file":"index.cjs","sourcesContent":["/**\n * step-machine-public — jsonata loader\n *\n * Synchronous jsonata wrapper. Mirrors the loader pattern in\n * src/card-compute/index.ts — uses createRequire to load the vendored\n * synchronous CommonJS build.\n *\n * Runtime portability:\n * - Node ESM: createRequire works.\n * - Browser/cloud: package this lib for that runtime; the consumer ships\n * jsonata-sync.cjs alongside (tsup post-build does this automatically).\n */\n\nimport { createRequire } from 'module';\n\nconst _require = createRequire(import.meta.url);\n\nexport type JsonataExpression = {\n evaluate: (data: unknown) => unknown;\n};\n\nexport const jsonata: (expr: string) => JsonataExpression = _require('./jsonata-sync.cjs');\n","/**\n * step-machine-public — result utilities\n *\n * Pure helpers that:\n * - Normalize handler return shapes into NormalizedHandlerResult.\n * - Filter `data` to the keys declared in `produces_data`.\n * - Wrap a handler with output filtering / input validation.\n *\n * No transport, no I/O — only object reshaping.\n */\n\nimport type { NormalizedHandlerResult, StepHandler } from './types.js';\nimport { jsonata } from './jsonata-loader.js';\n\n// ============================================================================\n// normalizeHandlerResult — accept legacy or strict shape\n// ============================================================================\n\nexport function normalizeHandlerResult(\n raw: unknown,\n stepName: string,\n): NormalizedHandlerResult {\n if (!raw || typeof raw !== 'object') {\n throw new Error(`[step-machine-public] Step \"${stepName}\" returned a non-object result.`);\n }\n\n const obj = raw as Record<string, unknown>;\n const result = (obj.result ?? obj.status) as unknown;\n\n // Strict envelope: { result, data, error? }\n if (typeof result === 'string' && result.trim().length > 0) {\n const data: Record<string, unknown> =\n obj.data && typeof obj.data === 'object' && !Array.isArray(obj.data)\n ? { ...(obj.data as Record<string, unknown>) }\n : {};\n const error = typeof obj.error === 'string' ? (obj.error as string) : undefined;\n if (error && !('error' in data)) {\n data.error = error;\n }\n return { result, data, ...(error ? { error } : {}) };\n }\n\n // Bare object — treat the whole thing as data, intent = success.\n return { result: 'success', data: { ...obj } };\n}\n\n// ============================================================================\n// filterProducedData — narrow data to declared produces_data keys\n// ============================================================================\n\nexport function filterProducedData(\n data: Record<string, unknown>,\n produces: string[] | undefined,\n): Record<string, unknown> {\n if (!produces || produces.length === 0) return data;\n const filtered: Record<string, unknown> = {};\n for (const key of produces) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n filtered[key] = data[key];\n }\n }\n return filtered;\n}\n\n// ============================================================================\n// wrapWithOutputFiltering — compose normalization + produces_data filtering\n// ============================================================================\n\nexport function wrapWithOutputFiltering(\n handler: StepHandler,\n produces: string[] | undefined,\n): StepHandler {\n return async (input, context) => {\n const raw = await handler(input, context);\n const normalized = normalizeHandlerResult(raw, context?.stepName ?? 'unknown');\n return {\n result: normalized.result,\n data: filterProducedData(normalized.data, produces),\n ...(normalized.error ? { error: normalized.error } : {}),\n };\n };\n}\n\n// ============================================================================\n// runInputValidations — evaluate validation expressions\n// ============================================================================\n\n/**\n * Evaluate each validation as a JSONata expression returning truthy.\n *\n * Returns `null` on success, or a normalized failure result on the first\n * failed/throwing validation.\n */\nexport function runInputValidations(\n input: Record<string, unknown>,\n validations: string[] | undefined,\n stepName: string,\n): NormalizedHandlerResult | null {\n if (!validations || validations.length === 0) return null;\n for (const expr of validations) {\n try {\n const ok = jsonata(expr).evaluate(input);\n if (!ok) {\n return {\n result: 'failure',\n data: { error: `[${stepName}] input validation failed: ${expr}` },\n };\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return {\n result: 'failure',\n data: { error: `[${stepName}] input validation error on \"${expr}\": ${msg}` },\n };\n }\n }\n return null;\n}\n\n// ============================================================================\n// wrapWithInputValidations — short-circuit if any validation fails\n// ============================================================================\n\nexport function wrapWithInputValidations(\n handler: StepHandler,\n validations: string[] | undefined,\n stepName: string,\n): StepHandler {\n if (!validations || validations.length === 0) return handler;\n return async (input, context) => {\n const failure = runInputValidations(input, validations, stepName);\n if (failure) return failure;\n return handler(input, context);\n };\n}\n","/**\n * cli/common/jsonata-loader — synchronous jsonata wrapper.\n *\n * Mirrors the loader pattern used by card-compute. Uses createRequire so the\n * vendored CommonJS sync build can be loaded from ESM. The canonical source\n * file is `src/card-compute/jsonata-sync.cjs`; the tsup post-build hook copies\n * it next to every dist bundle that references it.\n */\n\nimport { createRequire } from 'module';\n\nconst _require = createRequire(import.meta.url);\n\nexport type JsonataExpression = {\n evaluate: (data: unknown) => unknown;\n};\n\n// Source path resolves via the file's location at src/cli/common/.\n// Dist path resolves via the post-build copy that places jsonata-sync.cjs\n// alongside the bundled output (handled by tsup's copyJsonataSyncToDistDirs).\nfunction _loadJsonata(): (expr: string) => JsonataExpression {\n // Try sibling first (dist layout). If that fails, fall back to the canonical\n // source location (used when running TypeScript directly under vitest/tsx).\n try {\n return _require('./jsonata-sync.cjs');\n } catch {\n return _require('../../card-compute/jsonata-sync.cjs');\n }\n}\n\nexport const jsonata: (expr: string) => JsonataExpression = _loadJsonata();\n","/**\n * cli/common/args-massaging — JSONata-based mapping from logical args to\n * transport-specific shape.\n *\n * `argsMassaging` is a property of `ExecutionRef`, so honoring it is the job\n * of every adapter (Node spawn, HTTP, Azure Function, etc.). This helper is\n * the shared pure-JSONata implementation reused by all adapters.\n *\n * Adapters call this as the first step inside their `invokeRefSync` /\n * `dispatchExecution` implementation, then perform their transport using\n * `cmdArgs` / `body` / `url`.\n */\n\nimport { jsonata } from './jsonata-loader.js';\nimport type { ArgsMassaging, OutputTransforms } from './execution-interface.js';\nimport type { NormalizedHandlerResult } from '../../step-machine-public/types.js';\n\nexport interface MassagedArgs {\n /** Resolved argv tail for local transports. */\n cmdArgs?: string[];\n /** Resolved request body for http transports (or stdin payload for local). */\n body?: unknown;\n /** Resolved final URL string for http transports. */\n url?: string;\n}\n\n/**\n * Evaluate `argsMassaging` against the supplied context.\n *\n * Throws with a label-tagged message if any expression fails. Adapters\n * should catch and convert to a normalized failure result.\n */\nexport function resolveArgsMassaging(\n argsMassaging: ArgsMassaging | undefined,\n context: Record<string, unknown>,\n label: string,\n): MassagedArgs {\n if (!argsMassaging || typeof argsMassaging !== 'object') return {};\n\n const out: MassagedArgs = {};\n\n if (Array.isArray(argsMassaging.cmdTemplate)) {\n const resolved: string[] = [];\n for (const expr of argsMassaging.cmdTemplate) {\n try {\n resolved.push(String(jsonata(expr).evaluate(context)));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(\n `[${label}] argsMassaging.cmdTemplate failed on \"${expr}\": ${msg}`,\n );\n }\n }\n out.cmdArgs = resolved;\n }\n\n if (typeof argsMassaging.bodyTemplate === 'string') {\n try {\n out.body = jsonata(argsMassaging.bodyTemplate).evaluate(context);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(\n `[${label}] argsMassaging.bodyTemplate failed: ${msg}`,\n );\n }\n }\n\n if (typeof argsMassaging.urlTemplate === 'string') {\n try {\n out.url = String(jsonata(argsMassaging.urlTemplate).evaluate(context));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(\n `[${label}] argsMassaging.urlTemplate failed: ${msg}`,\n );\n }\n }\n\n return out;\n}\n\n/**\n * Apply `outputTransforms` to a raw invoke result.\n *\n * Context for all expressions: `{ output }` where `output` is the raw\n * { result, data, error? } envelope from invokeRefSync.\n *\n * Returns a new NormalizedHandlerResult with overrides applied.\n * Throws with a label-tagged message if any expression fails.\n */\nexport function resolveOutputTransforms(\n transforms: OutputTransforms | undefined,\n raw: NormalizedHandlerResult,\n label: string,\n): NormalizedHandlerResult {\n if (!transforms || typeof transforms !== 'object') return raw;\n\n const ctx = { output: raw };\n let result = raw.result;\n let data = raw.data;\n let error = raw.error;\n\n if (typeof transforms.resultExpr === 'string') {\n try {\n const val = jsonata(transforms.resultExpr).evaluate(ctx);\n if (typeof val !== 'string' || !val.trim()) {\n throw new Error(`resultExpr did not produce a non-empty string (got ${JSON.stringify(val)})`);\n }\n result = val;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(`[${label}] outputTransforms.resultExpr failed: ${msg}`);\n }\n }\n\n if (typeof transforms.dataTemplate === 'string') {\n try {\n const val = jsonata(transforms.dataTemplate).evaluate(ctx);\n if (!val || typeof val !== 'object' || Array.isArray(val)) {\n throw new Error(`dataTemplate did not produce an object (got ${JSON.stringify(val)})`);\n }\n data = val as Record<string, unknown>;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(`[${label}] outputTransforms.dataTemplate failed: ${msg}`);\n }\n }\n\n if (typeof transforms.errorExpr === 'string') {\n try {\n const val = jsonata(transforms.errorExpr).evaluate(ctx);\n // $undefined() evaluates to undefined — clears the error field\n error = val != null ? String(val) : undefined;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(`[${label}] outputTransforms.errorExpr failed: ${msg}`);\n }\n }\n\n return error !== undefined\n ? { result, data, error }\n : { result, data };\n}\n","/**\n * storage-interface.ts\n *\n * Three minimal storage primitives that together cover all persistence needs\n * of the board-live-cards system. Any backend (Node fs, CosmosDB, Azure Blob,\n * browser localStorage, in-memory test double) implements these three interfaces.\n *\n * The pure-logic stores in board-live-cards-all-stores.ts depend only on these\n * interfaces — never on Node built-ins.\n *\n * Blob — raw string content at a logical, backend-neutral key\n * Journal — append-only log with cursor-based reads\n * KV — key-value store with list/delete\n *\n * Mapping to existing storage adapters:\n *\n * CardStorageAdapter\n * inventory (cardId → { blobRef, checksum, fileMetadata? }) → KV\n * card JSON files → Blob\n * source output files → Blob\n *\n * JournalStorageAdapter → Journal (board-journal.jsonl)\n *\n * ExecutionRequestStore → KV (keyed by journalId, via createFsKvStorage)\n *\n * StateSnapshotStorageAdapter\n * board-graph.json (packed single JSON, written atomically) → Blob\n * per-card sidecars (cards/<id>/runtime, fetched-sources-manifest) → KV\n */\n\n// ============================================================================\n// Blob — raw content at an opaque key\n//\n// The key is backend-specific (file path, blob name, storage key).\n// Text helpers are always available. Binary helpers are optional so existing\n// backends can adopt incrementally.\n// ============================================================================\n\nexport interface BlobStat {\n key: string;\n size: number;\n updatedAt?: string;\n contentType?: string;\n}\n\nexport interface BlobStorage {\n /** Returns raw content string, or null if the blob does not exist. */\n read(key: string): string | null;\n\n /** Write content at key. Implementations should be atomic (write-rename). */\n write(key: string, content: string): void;\n\n /** Returns true if a blob exists at key. */\n exists(key: string): boolean;\n\n /** Delete the blob at key. No-op if it does not exist. */\n remove(key: string): void;\n\n /** Optional binary read for file-like artifacts. */\n readBytes?(key: string): Uint8Array | null;\n\n /** Optional binary write for file-like artifacts. */\n writeBytes?(key: string, content: Uint8Array): void;\n\n /** Optional key listing by prefix. */\n listKeys?(prefix?: string): string[];\n\n /** Optional metadata lookup. */\n stat?(key: string): BlobStat | null;\n}\n\n// ============================================================================\n// KindValueRef — backend-neutral typed reference\n//\n// A ref describes WHERE content lives without carrying the bytes.\n// Serialized on the CLI wire as: b64:<base64url({\"kind\":\"...\",\"value\":\"...\"})>\n// kind = 'fs-path': value is an absolute file path\n// Additional kinds (e.g. 'cosmos') are added in public-storage-adapter.ts as new backends are supported.\n// ============================================================================\n\nexport interface KindValueRef {\n readonly kind: string;\n readonly value: string;\n}\n\nconst REF_PREFIX = 'b64:';\n\nfunction toBase64Url(raw: string): string {\n const utf8 = new TextEncoder().encode(raw);\n const buf = (globalThis as { Buffer?: { from(data: Uint8Array): { toString(enc: string): string } } }).Buffer;\n let base64: string;\n if (buf) {\n base64 = buf.from(utf8).toString('base64');\n } else if (typeof btoa === 'function') {\n let binary = '';\n for (const byte of utf8) binary += String.fromCharCode(byte);\n base64 = btoa(binary);\n } else {\n throw new Error('No base64 encoder available in this runtime');\n }\n return base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/g, '');\n}\n\nfunction fromBase64Url(input: string): string {\n const base64 = input.replace(/-/g, '+').replace(/_/g, '/')\n + '='.repeat((4 - (input.length % 4)) % 4);\n const buf = (globalThis as { Buffer?: { from(data: string, enc: string): { toString(enc: string): string } } }).Buffer;\n if (buf) return buf.from(base64, 'base64').toString('utf8');\n if (typeof atob === 'function') {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n return new TextDecoder().decode(bytes);\n }\n throw new Error('No base64 decoder available in this runtime');\n}\n\n/** Serialize a KindValueRef to the wire format: b64:<base64url(json)> */\nexport function serializeRef(ref: KindValueRef): string {\n return `${REF_PREFIX}${toBase64Url(JSON.stringify(ref))}`;\n}\n\n/** Parse a wire-format ref string (b64:<base64url(json)>) into a KindValueRef. */\nexport function parseRef(s: string): KindValueRef {\n if (!s.startsWith(REF_PREFIX)) throw new Error(`Invalid ref format (expected ${REF_PREFIX}<base64url(json)>): ${s}`);\n let parsed: unknown;\n try {\n parsed = JSON.parse(fromBase64Url(s.slice(REF_PREFIX.length)));\n } catch {\n throw new Error(`Invalid ref format (malformed base64url/json): ${s}`);\n }\n if (!parsed || typeof parsed !== 'object') {\n throw new Error(`Invalid ref format (expected object payload): ${s}`);\n }\n const candidate = parsed as { kind?: unknown; value?: unknown };\n if (typeof candidate.kind !== 'string' || typeof candidate.value !== 'string') {\n throw new Error(`Invalid ref format (payload must contain string kind/value): ${s}`);\n }\n return { kind: candidate.kind, value: candidate.value };\n}\n\n// ============================================================================\n// Journal — append-only log, cursor-based reads\n//\n// Each entry has a string id (UUID or monotonic token) and an opaque payload.\n// Cursors are entry ids — readAfter returns entries strictly after that id.\n// A null/empty cursor means \"read from the beginning\".\n// ============================================================================\n\nexport interface JournalEntry {\n id: string;\n payload: unknown;\n}\n\nexport interface JournalReadResult {\n entries: JournalEntry[];\n /** The id of the last entry returned, suitable for use as the next cursor. */\n newCursor: string | null;\n}\n\nexport interface JournalStorage {\n /** Append an entry. The storage layer assigns the id. */\n append(payload: unknown): JournalEntry;\n\n /** Read ALL entries (for index rebuilds, full replay). */\n readAll(): JournalEntry[];\n\n /**\n * Read entries appended after the given cursor id.\n * If cursor is null/empty, returns all entries from the beginning.\n */\n readAfter(cursor: string | null): JournalReadResult;\n}\n\n// ============================================================================\n// KV — key-value store with list and delete\n//\n// Values are opaque unknown — callers own serialisation.\n// Keys are scoped by the adapter factory (e.g. a boardDir prefix is closed\n// over in the adapter, not passed per-call).\n// ============================================================================\n\nexport interface KVStorage {\n /** Returns the stored value, or null if the key does not exist. */\n read(key: string): unknown | null;\n\n /** Write value at key. Overwrites any existing value. */\n write(key: string, value: unknown): void;\n\n /** Delete the key. No-op if it does not exist. */\n delete(key: string): void;\n\n /**\n * List all keys, optionally filtered to those starting with prefix.\n * Order is implementation-defined.\n */\n listKeys(prefix?: string): string[];\n}\n\n// ============================================================================\n// JSONStorage — KV store with JSON-aware merge operations\n//\n// Backed by KVStorage under the hood. Adds deepMerge and shallowMerge so\n// callers never need to read-modify-write manually for partial updates.\n// ============================================================================\n\nexport interface JSONStorage {\n /** Returns the stored JSON value, or null if the key does not exist. */\n read(key: string): unknown | null;\n\n /**\n * Read a nested value inside the stored object using a dot-notation path.\n * e.g. get('myKey', 'a.b.c') returns the value at { a: { b: { c: ... } } }.\n * Returns null if the key does not exist or the path cannot be traversed.\n */\n get(key: string, jsonPath: string): unknown | null;\n\n /** Write value at key. Overwrites any existing value. */\n write(key: string, value: unknown): void;\n\n /** Delete the key. No-op if it does not exist. */\n delete(key: string): void;\n\n /** List all keys, optionally filtered by prefix. */\n listKeys(prefix?: string): string[];\n\n /**\n * Shallow-merge patch into the existing object at key.\n * Equivalent to: write(key, { ...read(key), ...patch })\n * Creates the key if it does not exist.\n */\n shallowMerge(key: string, patch: Record<string, unknown>): void;\n\n /**\n * Deep-merge patch into the existing object at key.\n * Recursively merges nested plain objects; arrays and primitives are replaced.\n * Creates the key if it does not exist.\n */\n deepMerge(key: string, patch: Record<string, unknown>): void;\n\n /**\n * Set a nested value inside the stored object using a dot-notation path.\n * e.g. patch('myKey', 'a.b.c', 42) sets { a: { b: { c: 42 } } } into the stored object.\n * Intermediate objects are created if absent. Arrays are not traversed — use integer\n * segments to index into them (e.g. 'items.0.name').\n * Creates the top-level key if it does not exist.\n */\n patch(key: string, jsonPath: string, value: unknown): void;\n}\n\n// ============================================================================\n// StorageProvider — aggregate of all three primitives\n//\n// Adapter factories receive a StorageProvider and close over any scope (e.g.\n// boardDir) themselves. This is the single injection point for swapping\n// backends (Node fs → CosmosDB, browser localStorage, test doubles, etc.).\n// ============================================================================\n\nexport interface StorageProvider {\n blob: BlobStorage;\n journal: JournalStorage;\n kv: KVStorage;\n}\n\n// ============================================================================\n// AtomicRelayLock — non-blocking try-acquire lock with relay-on-busy semantics\n//\n// This interface serves TWO tightly coupled purposes which are intentionally\n// unified into a single primitive:\n//\n// 1. ATOMICITY — ensures that a read-mutate-save cycle is executed by at\n// most one actor at a time, preventing concurrent actors from racing on\n// stale state and writing conflicting snapshots.\n//\n// 2. RELAY SIGNAL — when tryAcquire() returns null, the caller knows the\n// cycle is already in progress. Because the holder always reads fresh\n// state upon entry, it will pick up every change appended by the skipping\n// caller before the lock was attempted. The caller can therefore safely\n// exit — its work will be completed by the holder. This is the\n// \"relay baton\" pattern: the lock being held IS the in-progress signal.\n//\n// These two purposes are not an accidental overload — they are the same\n// invariant expressed at different scopes. Any backend implementation\n// (FS lockfile, Cosmos document lease, Azure entity lock, in-memory flag)\n// that satisfies \"at most one holder at a time\" automatically satisfies both.\n//\n// Contract:\n// - tryAcquire() is non-blocking. It never waits.\n// - Returns a release function on success, or null if already held.\n// - The release function must be called exactly once (use try/finally).\n// - Behaviour after calling release() more than once is undefined.\n// ============================================================================\n\nexport interface AtomicRelayLock {\n /**\n * Attempt to acquire the lock without blocking.\n * Returns a `release` function if successful, or `null` if the lock is\n * already held by another actor (relay: that actor will complete the work).\n */\n tryAcquire(): (() => void) | null;\n}\n\n/**\n * Execute `work` under an `AtomicRelayLock`.\n *\n * - If the lock is busy, returns false immediately (relay: the holder will\n * complete the work on behalf of this caller).\n * - If acquired, runs `work` exclusively, releases the lock, then calls\n * `continuation` if provided — allowing the caller to schedule the next\n * cycle (e.g. spawn a detached process) after the lock is free.\n * - Returns true if work ran.\n */\nexport async function withRelayLock(\n lock: AtomicRelayLock,\n work: () => Promise<void>,\n continuation?: () => void,\n): Promise<boolean> {\n const release = lock.tryAcquire();\n if (!release) return false; // relay: holder is already doing the work\n try {\n await work();\n } finally {\n release(); // release before continuation so it can immediately re-acquire\n }\n continuation?.();\n return true;\n}\n","/**\n * step-machine-public — handler factory\n *\n * Builds engine-facing StepHandlers from declarative HandlerSpec entries.\n * Pure: no Node imports, no transport. Refs are dispatched through the\n * caller-supplied `InvokeFn`, which is the single boundary between this lib\n * and any transport (Node spawn, HTTP, Azure Function, etc.).\n *\n * Layering:\n *\n * step-machine (pure FSM) — runs handlers, never builds them.\n * step-machine-public (this lib) — declarative spec → StepHandler map.\n * adapter (e.g. node-spawn-invoker) — InvokeFn implementation per transport.\n * step-machine-cli (thin shell) — wires adapter + flow loader + run.\n */\n\nimport { jsonata } from './jsonata-loader.js';\nimport { wrapWithInputValidations, wrapWithOutputFiltering } from './result-utils.js';\nimport { resolveOutputTransforms } from '../cli/common/args-massaging.js';\nimport { serializeRef } from '../cli/common/storage-interface.js';\nimport type {\n ComputeJsonataSpec,\n HandlerSpec,\n InvokeRefFn,\n NormalizedHandlerResult,\n RefSpec,\n StepConfigForFactory,\n StepHandler,\n} from './types.js';\n\n// ============================================================================\n// Discriminators\n// ============================================================================\n\nexport function isComputeJsonataSpec(spec: unknown): spec is ComputeJsonataSpec {\n return (\n !!spec &&\n typeof spec === 'object' &&\n (spec as Record<string, unknown>).type === 'compute-jsonata' &&\n Array.isArray((spec as Record<string, unknown>).expr) &&\n ((spec as Record<string, unknown>).expr as unknown[]).length > 0\n );\n}\n\nexport function isRefSpec(spec: unknown): spec is RefSpec {\n if (!spec || typeof spec !== 'object') return false;\n const s = spec as Record<string, unknown>;\n if (s.type !== 'ref' || typeof s.howToRun !== 'string') return false;\n if (typeof s.whatToRun === 'string') return true;\n if (s.whatToRun && typeof s.whatToRun === 'object') {\n const w = s.whatToRun as Record<string, unknown>;\n return typeof w.kind === 'string' && typeof w.value === 'string';\n }\n return false;\n}\n\n// ============================================================================\n// Compute-jsonata handler\n// ============================================================================\n\ninterface NormalizedComputeStep {\n bindTo: string;\n expr: string;\n}\n\nfunction normalizeComputeStep(item: string | { bindTo: string; expr: string }): NormalizedComputeStep {\n if (typeof item === 'string') {\n const eq = item.indexOf('=');\n if (eq < 1) {\n throw new Error(`[step-machine-public] Invalid compute expression (missing \"=\"): \"${item}\"`);\n }\n return { bindTo: item.slice(0, eq).trim(), expr: item.slice(eq + 1).trim() };\n }\n if (item && typeof item === 'object' && typeof item.bindTo === 'string' && typeof item.expr === 'string') {\n return item;\n }\n throw new Error(`[step-machine-public] Invalid compute step: ${JSON.stringify(item)}`);\n}\n\n/** Mutate nested dict via dot-path key. */\nfunction deepSet(obj: Record<string, unknown>, path: string, value: unknown): void {\n const parts = path.split('.');\n let cur: Record<string, unknown> = obj;\n for (let i = 0; i < parts.length - 1; i++) {\n const k = parts[i];\n if (cur[k] == null || typeof cur[k] !== 'object') cur[k] = {};\n cur = cur[k] as Record<string, unknown>;\n }\n cur[parts[parts.length - 1]] = value;\n}\n\nexport function createComputeJsonataHandler(\n spec: ComputeJsonataSpec,\n stepName: string,\n config?: Record<string, unknown>,\n): StepHandler {\n const steps = spec.expr.map(normalizeComputeStep);\n return async (input) => {\n const expects_data: Record<string, unknown> =\n input && typeof input === 'object' && !Array.isArray(input)\n ? { ...input }\n : {};\n\n // `data` accumulates computed outputs; it is placed in ctx by reference\n // so subsequent expressions can read `data.x` after earlier steps set it.\n const data: Record<string, unknown> = {};\n\n // Context shape:\n // expects_data — named namespace for declared step inputs (from flow state)\n // data — accumulating output namespace (required, mutated by reference)\n // config — optional step-level config\n const ctx: Record<string, unknown> = {\n expects_data,\n data, // same reference — mutations visible in later steps\n ...(config ? { config } : {}),\n };\n\n let transitionResult: string | undefined;\n let transitionError: string | undefined;\n\n for (const step of steps) {\n try {\n const val = jsonata(step.expr).evaluate(ctx);\n\n if (step.bindTo === 'result') {\n // Transition outcome\n transitionResult = val != null ? String(val) : 'success';\n } else if (step.bindTo === 'error') {\n // Transition error detail\n transitionError = val != null ? String(val) : undefined;\n } else if (step.bindTo.startsWith('data.')) {\n // Namespaced output — mutates the shared data reference\n deepSet(data, step.bindTo.slice('data.'.length), val);\n } else {\n return {\n result: 'failure',\n data: {},\n error: `[${stepName}] invalid bindTo \"${step.bindTo}\": must be \"result\", \"error\", or start with \"data.\"`,\n };\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return {\n result: 'failure',\n data: {},\n error: `[${stepName}] compute \"${step.bindTo}\" failed: ${msg}`,\n };\n }\n }\n\n if (transitionResult === undefined) {\n return {\n result: 'failure',\n data: {},\n error: `[${stepName}] compute-jsonata: no \"result\" binding declared — add '- result = \"success\"' to expr`,\n };\n }\n return transitionError\n ? { result: transitionResult, data, error: transitionError }\n : { result: transitionResult, data };\n };\n}\n\n// ============================================================================\n// Ref handler — dispatches via InvokeFn\n// ============================================================================\n\nexport function createRefStepHandler(\n spec: RefSpec,\n stepName: string,\n invoke: InvokeRefFn,\n config?: Record<string, unknown>,\n): StepHandler {\n // The handler spec itself is a superset of ExecutionRef. Strip the discriminator\n // before passing to the adapter so it sees a plain ExecutionRef.\n // Normalize whatToRun from object form { kind, value } → b64 string.\n const { type: _t, ...refOnly } = spec;\n const ref = {\n ...refOnly,\n whatToRun: typeof refOnly.whatToRun === 'object'\n ? serializeRef(refOnly.whatToRun)\n : refOnly.whatToRun,\n };\n\n return async (input) => {\n const stepInput: Record<string, unknown> =\n input && typeof input === 'object' && !Array.isArray(input)\n ? { ...input }\n : {};\n if (config) stepInput.config = config;\n\n try {\n const raw = await invoke(ref, stepInput);\n if (!spec.outputTransforms) return raw;\n try {\n return resolveOutputTransforms(spec.outputTransforms, raw, stepName);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { result: 'failure', data: {}, error: msg };\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return {\n result: 'failure',\n data: { error: `[step-machine-public] step \"${stepName}\" invoke threw: ${msg}` },\n };\n }\n };\n}\n\n// ============================================================================\n// Passthrough handler\n// ============================================================================\n\nexport function createPassthroughHandler(): StepHandler {\n return async (input) => {\n const data: Record<string, unknown> =\n input && typeof input === 'object' && !Array.isArray(input)\n ? (input as Record<string, unknown>)\n : {};\n return { result: 'success', data };\n };\n}\n\n// ============================================================================\n// resolveStepHandler — pick + decorate the right handler for a step\n// ============================================================================\n\nexport interface ResolveStepHandlerOptions {\n invoke: InvokeRefFn;\n}\n\nexport function resolveStepHandler(\n stepName: string,\n stepConfig: StepConfigForFactory | undefined,\n options: ResolveStepHandlerOptions,\n): StepHandler {\n const produces = Array.isArray(stepConfig?.produces_data) ? stepConfig?.produces_data : undefined;\n const inputValidations = Array.isArray(stepConfig?.input_validations)\n ? stepConfig?.input_validations\n : undefined;\n const config = stepConfig?.config ?? undefined;\n const spec: HandlerSpec | undefined = stepConfig?.handler;\n\n let base: StepHandler;\n if (isComputeJsonataSpec(spec)) {\n // compute-jsonata: validations are baked in via the wrapper as well; both work.\n base = createComputeJsonataHandler(spec, stepName, config);\n } else if (isRefSpec(spec)) {\n base = createRefStepHandler(spec, stepName, options.invoke, config);\n } else {\n base = createPassthroughHandler();\n }\n\n return wrapWithInputValidations(\n wrapWithOutputFiltering(base, produces),\n inputValidations,\n stepName,\n );\n}\n\n// ============================================================================\n// buildStepHandlersForFlow — produce the Record<stepName, StepHandler> map\n// ============================================================================\n\nexport interface BuildStepHandlersOptions {\n invoke: InvokeRefFn;\n}\n\nexport function buildStepHandlersForFlow(\n flow: { steps?: Record<string, StepConfigForFactory> },\n options: BuildStepHandlersOptions,\n): Record<string, StepHandler> {\n const handlers: Record<string, StepHandler> = {};\n for (const [stepName, stepConfig] of Object.entries(flow.steps ?? {})) {\n handlers[stepName] = resolveStepHandler(stepName, stepConfig, options);\n }\n return handlers;\n}\n\n// Re-export for adapter convenience.\nexport type { NormalizedHandlerResult };\n"]}
@@ -1,3 +0,0 @@
1
- import {createRequire}from'module';var A=createRequire(import.meta.url),p=A("./jsonata-sync.cjs");function m(r,e){if(!r||typeof r!="object")throw new Error(`[step-machine-public] Step "${e}" returned a non-object result.`);let t=r,n=t.result??t.status;if(typeof n=="string"&&n.trim().length>0){let a=t.data&&typeof t.data=="object"&&!Array.isArray(t.data)?{...t.data}:{},s=typeof t.error=="string"?t.error:void 0;return s&&!("error"in a)&&(a.error=s),{result:n,data:a,...s?{error:s}:{}}}return {result:"success",data:{...t}}}function w(r,e){if(!e||e.length===0)return r;let t={};for(let n of e)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n]);return t}function g(r,e){return async(t,n)=>{let a=await r(t,n),s=m(a,n?.stepName??"unknown");return {result:s.result,data:w(s.data,e),...s.error?{error:s.error}:{}}}}function k(r,e,t){if(!e||e.length===0)return null;for(let n of e)try{if(!p(n).evaluate(r))return {result:"failure",data:{error:`[${t}] input validation failed: ${n}`}}}catch(a){let s=a instanceof Error?a.message:String(a);return {result:"failure",data:{error:`[${t}] input validation error on "${n}": ${s}`}}}return null}function y(r,e,t){return !e||e.length===0?r:async(n,a)=>{let s=k(n,e,t);return s||r(n,a)}}var h=createRequire(import.meta.url);function O(){try{return h("./jsonata-sync.cjs")}catch{return h("../../card-compute/jsonata-sync.cjs")}}var f=O();function S(r,e,t){if(!r||typeof r!="object")return e;let n={output:e},a=e.result,s=e.data,i=e.error;if(typeof r.resultExpr=="string")try{let o=f(r.resultExpr).evaluate(n);if(typeof o!="string"||!o.trim())throw new Error(`resultExpr did not produce a non-empty string (got ${JSON.stringify(o)})`);a=o;}catch(o){let u=o instanceof Error?o.message:String(o);throw new Error(`[${t}] outputTransforms.resultExpr failed: ${u}`)}if(typeof r.dataTemplate=="string")try{let o=f(r.dataTemplate).evaluate(n);if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`dataTemplate did not produce an object (got ${JSON.stringify(o)})`);s=o;}catch(o){let u=o instanceof Error?o.message:String(o);throw new Error(`[${t}] outputTransforms.dataTemplate failed: ${u}`)}if(typeof r.errorExpr=="string")try{let o=f(r.errorExpr).evaluate(n);i=o!=null?String(o):void 0;}catch(o){let u=o instanceof Error?o.message:String(o);throw new Error(`[${t}] outputTransforms.errorExpr failed: ${u}`)}return i!==void 0?{result:a,data:s,error:i}:{result:a,data:s}}var F="b64:";function z(r){let e=new TextEncoder().encode(r),t=globalThis.Buffer,n;if(t)n=t.from(e).toString("base64");else if(typeof btoa=="function"){let a="";for(let s of e)a+=String.fromCharCode(s);n=btoa(a);}else throw new Error("No base64 encoder available in this runtime");return n.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function R(r){return `${F}${z(JSON.stringify(r))}`}function x(r){return !!r&&typeof r=="object"&&r.type==="compute-jsonata"&&Array.isArray(r.expr)&&r.expr.length>0}function b(r){if(!r||typeof r!="object")return false;let e=r;if(e.type!=="ref"||typeof e.howToRun!="string")return false;if(typeof e.whatToRun=="string")return true;if(e.whatToRun&&typeof e.whatToRun=="object"){let t=e.whatToRun;return typeof t.kind=="string"&&typeof t.value=="string"}return false}function I(r){if(typeof r=="string"){let e=r.indexOf("=");if(e<1)throw new Error(`[step-machine-public] Invalid compute expression (missing "="): "${r}"`);return {bindTo:r.slice(0,e).trim(),expr:r.slice(e+1).trim()}}if(r&&typeof r=="object"&&typeof r.bindTo=="string"&&typeof r.expr=="string")return r;throw new Error(`[step-machine-public] Invalid compute step: ${JSON.stringify(r)}`)}function B(r,e,t){let n=e.split("."),a=r;for(let s=0;s<n.length-1;s++){let i=n[s];(a[i]==null||typeof a[i]!="object")&&(a[i]={}),a=a[i];}a[n[n.length-1]]=t;}function v(r,e,t){let n=r.expr.map(I);return async a=>{let s=a&&typeof a=="object"&&!Array.isArray(a)?{...a}:{},i={},o={expects_data:s,data:i,...t?{config:t}:{}},u,d;for(let l of n)try{let c=p(l.expr).evaluate(o);if(l.bindTo==="result")u=c!=null?String(c):"success";else if(l.bindTo==="error")d=c!=null?String(c):void 0;else if(l.bindTo.startsWith("data."))B(i,l.bindTo.slice(5),c);else return {result:"failure",data:{},error:`[${e}] invalid bindTo "${l.bindTo}": must be "result", "error", or start with "data."`}}catch(c){let H=c instanceof Error?c.message:String(c);return {result:"failure",data:{},error:`[${e}] compute "${l.bindTo}" failed: ${H}`}}return u===void 0?{result:"failure",data:{},error:`[${e}] compute-jsonata: no "result" binding declared \u2014 add '- result = "success"' to expr`}:d?{result:u,data:i,error:d}:{result:u,data:i}}}function j(r,e,t,n){let{type:a,...s}=r,i={...s,whatToRun:typeof s.whatToRun=="object"?R(s.whatToRun):s.whatToRun};return async o=>{let u=o&&typeof o=="object"&&!Array.isArray(o)?{...o}:{};n&&(u.config=n);try{let d=await t(i,u);if(!r.outputTransforms)return d;try{return S(r.outputTransforms,d,e)}catch(l){let c=l instanceof Error?l.message:String(l);return {result:"failure",data:{},error:c}}}catch(d){let l=d instanceof Error?d.message:String(d);return {result:"failure",data:{error:`[step-machine-public] step "${e}" invoke threw: ${l}`}}}}}function E(){return async r=>({result:"success",data:r&&typeof r=="object"&&!Array.isArray(r)?r:{}})}function T(r,e,t){let n=Array.isArray(e?.produces_data)?e?.produces_data:void 0,a=Array.isArray(e?.input_validations)?e?.input_validations:void 0,s=e?.config??void 0,i=e?.handler,o;return x(i)?o=v(i,r,s):b(i)?o=j(i,r,t.invoke,s):o=E(),y(g(o,n),a,r)}function C(r,e){let t={};for(let[n,a]of Object.entries(r.steps??{}))t[n]=T(n,a,e);return t}
2
- export{C as buildStepHandlersForFlow,v as createComputeJsonataHandler,E as createPassthroughHandler,j as createRefStepHandler,w as filterProducedData,x as isComputeJsonataSpec,b as isRefSpec,p as jsonata,m as normalizeHandlerResult,T as resolveStepHandler,k as runInputValidations,y as wrapWithInputValidations,g as wrapWithOutputFiltering};//# sourceMappingURL=index.js.map
3
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/step-machine-public/jsonata-loader.ts","../../src/step-machine-public/result-utils.ts","../../src/cli/common/jsonata-loader.ts","../../src/cli/common/args-massaging.ts","../../src/cli/common/storage-interface.ts","../../src/step-machine-public/handler-factory.ts"],"names":["_require","createRequire","jsonata","normalizeHandlerResult","raw","stepName","obj","result","data","error","filterProducedData","produces","filtered","key","wrapWithOutputFiltering","handler","input","context","normalized","runInputValidations","validations","expr","err","msg","wrapWithInputValidations","failure","_loadJsonata","resolveOutputTransforms","transforms","label","ctx","val","REF_PREFIX","toBase64Url","utf8","buf","base64","binary","byte","serializeRef","ref","isComputeJsonataSpec","spec","isRefSpec","s","w","normalizeComputeStep","item","eq","deepSet","path","value","parts","cur","i","k","createComputeJsonataHandler","config","steps","expects_data","transitionResult","transitionError","step","createRefStepHandler","invoke","_t","refOnly","stepInput","createPassthroughHandler","resolveStepHandler","stepConfig","options","inputValidations","base","buildStepHandlersForFlow","flow","handlers"],"mappings":"mCAeA,IAAMA,EAAWC,aAAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAA,CAMjCC,EAA+CF,CAAAA,CAAS,oBAAoB,ECHlF,SAASG,EACdC,CAAAA,CACAC,CAAAA,CACyB,CACzB,GAAI,CAACD,CAAAA,EAAO,OAAOA,CAAAA,EAAQ,QAAA,CACzB,MAAM,IAAI,KAAA,CAAM,CAAA,4BAAA,EAA+BC,CAAQ,iCAAiC,CAAA,CAG1F,IAAMC,CAAAA,CAAMF,CAAAA,CACNG,EAAUD,CAAAA,CAAI,MAAA,EAAUA,CAAAA,CAAI,MAAA,CAGlC,GAAI,OAAOC,CAAAA,EAAW,QAAA,EAAYA,CAAAA,CAAO,MAAK,CAAE,MAAA,CAAS,CAAA,CAAG,CAC1D,IAAMC,CAAAA,CACJF,CAAAA,CAAI,IAAA,EAAQ,OAAOA,EAAI,IAAA,EAAS,QAAA,EAAY,CAAC,KAAA,CAAM,QAAQA,CAAAA,CAAI,IAAI,CAAA,CAC/D,CAAE,GAAIA,CAAAA,CAAI,IAAiC,CAAA,CAC3C,GACAG,CAAAA,CAAQ,OAAOH,CAAAA,CAAI,KAAA,EAAU,SAAYA,CAAAA,CAAI,KAAA,CAAmB,MAAA,CACtE,OAAIG,CAAAA,EAAS,EAAE,OAAA,GAAWD,CAAAA,CAAAA,GACxBA,EAAK,KAAA,CAAQC,CAAAA,CAAAA,CAER,CAA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AAA,CAChDd,CAAAA,CAAUD,CAAI,EACvB+B,CAAAA,CAAOV,CAAAA,CAAqBrB,CAAAA,CAAMrC,CAAAA,CAAUkE,EAAQ,MAAA,CAAQd,CAAM,CAAA,CAElEgB,CAAAA,CAAOL,GAAyB,CAG3B5C,CAAAA,CACLV,CAAAA,CAAwB2D,CAAAA,CAAM9D,CAAQ,CAAA,CACtC6D,CAAAA,CACAnE,CACF,CACF,CAUO,SAASqE,CAAAA,CACdC,CAAAA,CACAJ,CAAAA,CAC6B,CAC7B,IAAMK,CAAAA,CAAwC,EAAC,CAC/C,OAAW,CAACvE,CAAAA,CAAUiE,CAAU,CAAA,GAAK,OAAO,OAAA,CAAQK,CAAAA,CAAK,KAAA,EAAS,EAAE,CAAA,CAClEC,CAAAA,CAASvE,CAAQ,CAAA,CAAIgE,EAAmBhE,CAAAA,CAAUiE,CAAAA,CAAYC,CAAO,CAAA,CAEvE,OAAOK,CACT","file":"index.js","sourcesContent":["/**\n * step-machine-public — jsonata loader\n *\n * Synchronous jsonata wrapper. Mirrors the loader pattern in\n * src/card-compute/index.ts — uses createRequire to load the vendored\n * synchronous CommonJS build.\n *\n * Runtime portability:\n * - Node ESM: createRequire works.\n * - Browser/cloud: package this lib for that runtime; the consumer ships\n * jsonata-sync.cjs alongside (tsup post-build does this automatically).\n */\n\nimport { createRequire } from 'module';\n\nconst _require = createRequire(import.meta.url);\n\nexport type JsonataExpression = {\n evaluate: (data: unknown) => unknown;\n};\n\nexport const jsonata: (expr: string) => JsonataExpression = _require('./jsonata-sync.cjs');\n","/**\n * step-machine-public — result utilities\n *\n * Pure helpers that:\n * - Normalize handler return shapes into NormalizedHandlerResult.\n * - Filter `data` to the keys declared in `produces_data`.\n * - Wrap a handler with output filtering / input validation.\n *\n * No transport, no I/O — only object reshaping.\n */\n\nimport type { NormalizedHandlerResult, StepHandler } from './types.js';\nimport { jsonata } from './jsonata-loader.js';\n\n// ============================================================================\n// normalizeHandlerResult — accept legacy or strict shape\n// ============================================================================\n\nexport function normalizeHandlerResult(\n raw: unknown,\n stepName: string,\n): NormalizedHandlerResult {\n if (!raw || typeof raw !== 'object') {\n throw new Error(`[step-machine-public] Step \"${stepName}\" returned a non-object result.`);\n }\n\n const obj = raw as Record<string, unknown>;\n const result = (obj.result ?? obj.status) as unknown;\n\n // Strict envelope: { result, data, error? }\n if (typeof result === 'string' && result.trim().length > 0) {\n const data: Record<string, unknown> =\n obj.data && typeof obj.data === 'object' && !Array.isArray(obj.data)\n ? { ...(obj.data as Record<string, unknown>) }\n : {};\n const error = typeof obj.error === 'string' ? (obj.error as string) : undefined;\n if (error && !('error' in data)) {\n data.error = error;\n }\n return { result, data, ...(error ? { error } : {}) };\n }\n\n // Bare object — treat the whole thing as data, intent = success.\n return { result: 'success', data: { ...obj } };\n}\n\n// ============================================================================\n// filterProducedData — narrow data to declared produces_data keys\n// ============================================================================\n\nexport function filterProducedData(\n data: Record<string, unknown>,\n produces: string[] | undefined,\n): Record<string, unknown> {\n if (!produces || produces.length === 0) return data;\n const filtered: Record<string, unknown> = {};\n for (const key of produces) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n filtered[key] = data[key];\n }\n }\n return filtered;\n}\n\n// ============================================================================\n// wrapWithOutputFiltering — compose normalization + produces_data filtering\n// ============================================================================\n\nexport function wrapWithOutputFiltering(\n handler: StepHandler,\n produces: string[] | undefined,\n): StepHandler {\n return async (input, context) => {\n const raw = await handler(input, context);\n const normalized = normalizeHandlerResult(raw, context?.stepName ?? 'unknown');\n return {\n result: normalized.result,\n data: filterProducedData(normalized.data, produces),\n ...(normalized.error ? { error: normalized.error } : {}),\n };\n };\n}\n\n// ============================================================================\n// runInputValidations — evaluate validation expressions\n// ============================================================================\n\n/**\n * Evaluate each validation as a JSONata expression returning truthy.\n *\n * Returns `null` on success, or a normalized failure result on the first\n * failed/throwing validation.\n */\nexport function runInputValidations(\n input: Record<string, unknown>,\n validations: string[] | undefined,\n stepName: string,\n): NormalizedHandlerResult | null {\n if (!validations || validations.length === 0) return null;\n for (const expr of validations) {\n try {\n const ok = jsonata(expr).evaluate(input);\n if (!ok) {\n return {\n result: 'failure',\n data: { error: `[${stepName}] input validation failed: ${expr}` },\n };\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return {\n result: 'failure',\n data: { error: `[${stepName}] input validation error on \"${expr}\": ${msg}` },\n };\n }\n }\n return null;\n}\n\n// ============================================================================\n// wrapWithInputValidations — short-circuit if any validation fails\n// ============================================================================\n\nexport function wrapWithInputValidations(\n handler: StepHandler,\n validations: string[] | undefined,\n stepName: string,\n): StepHandler {\n if (!validations || validations.length === 0) return handler;\n return async (input, context) => {\n const failure = runInputValidations(input, validations, stepName);\n if (failure) return failure;\n return handler(input, context);\n };\n}\n","/**\n * cli/common/jsonata-loader — synchronous jsonata wrapper.\n *\n * Mirrors the loader pattern used by card-compute. Uses createRequire so the\n * vendored CommonJS sync build can be loaded from ESM. The canonical source\n * file is `src/card-compute/jsonata-sync.cjs`; the tsup post-build hook copies\n * it next to every dist bundle that references it.\n */\n\nimport { createRequire } from 'module';\n\nconst _require = createRequire(import.meta.url);\n\nexport type JsonataExpression = {\n evaluate: (data: unknown) => unknown;\n};\n\n// Source path resolves via the file's location at src/cli/common/.\n// Dist path resolves via the post-build copy that places jsonata-sync.cjs\n// alongside the bundled output (handled by tsup's copyJsonataSyncToDistDirs).\nfunction _loadJsonata(): (expr: string) => JsonataExpression {\n // Try sibling first (dist layout). If that fails, fall back to the canonical\n // source location (used when running TypeScript directly under vitest/tsx).\n try {\n return _require('./jsonata-sync.cjs');\n } catch {\n return _require('../../card-compute/jsonata-sync.cjs');\n }\n}\n\nexport const jsonata: (expr: string) => JsonataExpression = _loadJsonata();\n","/**\n * cli/common/args-massaging — JSONata-based mapping from logical args to\n * transport-specific shape.\n *\n * `argsMassaging` is a property of `ExecutionRef`, so honoring it is the job\n * of every adapter (Node spawn, HTTP, Azure Function, etc.). This helper is\n * the shared pure-JSONata implementation reused by all adapters.\n *\n * Adapters call this as the first step inside their `invokeRefSync` /\n * `dispatchExecution` implementation, then perform their transport using\n * `cmdArgs` / `body` / `url`.\n */\n\nimport { jsonata } from './jsonata-loader.js';\nimport type { ArgsMassaging, OutputTransforms } from './execution-interface.js';\nimport type { NormalizedHandlerResult } from '../../step-machine-public/types.js';\n\nexport interface MassagedArgs {\n /** Resolved argv tail for local transports. */\n cmdArgs?: string[];\n /** Resolved request body for http transports (or stdin payload for local). */\n body?: unknown;\n /** Resolved final URL string for http transports. */\n url?: string;\n}\n\n/**\n * Evaluate `argsMassaging` against the supplied context.\n *\n * Throws with a label-tagged message if any expression fails. Adapters\n * should catch and convert to a normalized failure result.\n */\nexport function resolveArgsMassaging(\n argsMassaging: ArgsMassaging | undefined,\n context: Record<string, unknown>,\n label: string,\n): MassagedArgs {\n if (!argsMassaging || typeof argsMassaging !== 'object') return {};\n\n const out: MassagedArgs = {};\n\n if (Array.isArray(argsMassaging.cmdTemplate)) {\n const resolved: string[] = [];\n for (const expr of argsMassaging.cmdTemplate) {\n try {\n resolved.push(String(jsonata(expr).evaluate(context)));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(\n `[${label}] argsMassaging.cmdTemplate failed on \"${expr}\": ${msg}`,\n );\n }\n }\n out.cmdArgs = resolved;\n }\n\n if (typeof argsMassaging.bodyTemplate === 'string') {\n try {\n out.body = jsonata(argsMassaging.bodyTemplate).evaluate(context);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(\n `[${label}] argsMassaging.bodyTemplate failed: ${msg}`,\n );\n }\n }\n\n if (typeof argsMassaging.urlTemplate === 'string') {\n try {\n out.url = String(jsonata(argsMassaging.urlTemplate).evaluate(context));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(\n `[${label}] argsMassaging.urlTemplate failed: ${msg}`,\n );\n }\n }\n\n return out;\n}\n\n/**\n * Apply `outputTransforms` to a raw invoke result.\n *\n * Context for all expressions: `{ output }` where `output` is the raw\n * { result, data, error? } envelope from invokeRefSync.\n *\n * Returns a new NormalizedHandlerResult with overrides applied.\n * Throws with a label-tagged message if any expression fails.\n */\nexport function resolveOutputTransforms(\n transforms: OutputTransforms | undefined,\n raw: NormalizedHandlerResult,\n label: string,\n): NormalizedHandlerResult {\n if (!transforms || typeof transforms !== 'object') return raw;\n\n const ctx = { output: raw };\n let result = raw.result;\n let data = raw.data;\n let error = raw.error;\n\n if (typeof transforms.resultExpr === 'string') {\n try {\n const val = jsonata(transforms.resultExpr).evaluate(ctx);\n if (typeof val !== 'string' || !val.trim()) {\n throw new Error(`resultExpr did not produce a non-empty string (got ${JSON.stringify(val)})`);\n }\n result = val;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(`[${label}] outputTransforms.resultExpr failed: ${msg}`);\n }\n }\n\n if (typeof transforms.dataTemplate === 'string') {\n try {\n const val = jsonata(transforms.dataTemplate).evaluate(ctx);\n if (!val || typeof val !== 'object' || Array.isArray(val)) {\n throw new Error(`dataTemplate did not produce an object (got ${JSON.stringify(val)})`);\n }\n data = val as Record<string, unknown>;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(`[${label}] outputTransforms.dataTemplate failed: ${msg}`);\n }\n }\n\n if (typeof transforms.errorExpr === 'string') {\n try {\n const val = jsonata(transforms.errorExpr).evaluate(ctx);\n // $undefined() evaluates to undefined — clears the error field\n error = val != null ? String(val) : undefined;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(`[${label}] outputTransforms.errorExpr failed: ${msg}`);\n }\n }\n\n return error !== undefined\n ? { result, data, error }\n : { result, data };\n}\n","/**\n * storage-interface.ts\n *\n * Three minimal storage primitives that together cover all persistence needs\n * of the board-live-cards system. Any backend (Node fs, CosmosDB, Azure Blob,\n * browser localStorage, in-memory test double) implements these three interfaces.\n *\n * The pure-logic stores in board-live-cards-all-stores.ts depend only on these\n * interfaces — never on Node built-ins.\n *\n * Blob — raw string content at a logical, backend-neutral key\n * Journal — append-only log with cursor-based reads\n * KV — key-value store with list/delete\n *\n * Mapping to existing storage adapters:\n *\n * CardStorageAdapter\n * inventory (cardId → { blobRef, checksum, fileMetadata? }) → KV\n * card JSON files → Blob\n * source output files → Blob\n *\n * JournalStorageAdapter → Journal (board-journal.jsonl)\n *\n * ExecutionRequestStore → KV (keyed by journalId, via createFsKvStorage)\n *\n * StateSnapshotStorageAdapter\n * board-graph.json (packed single JSON, written atomically) → Blob\n * per-card sidecars (cards/<id>/runtime, fetched-sources-manifest) → KV\n */\n\n// ============================================================================\n// Blob — raw content at an opaque key\n//\n// The key is backend-specific (file path, blob name, storage key).\n// Text helpers are always available. Binary helpers are optional so existing\n// backends can adopt incrementally.\n// ============================================================================\n\nexport interface BlobStat {\n key: string;\n size: number;\n updatedAt?: string;\n contentType?: string;\n}\n\nexport interface BlobStorage {\n /** Returns raw content string, or null if the blob does not exist. */\n read(key: string): string | null;\n\n /** Write content at key. Implementations should be atomic (write-rename). */\n write(key: string, content: string): void;\n\n /** Returns true if a blob exists at key. */\n exists(key: string): boolean;\n\n /** Delete the blob at key. No-op if it does not exist. */\n remove(key: string): void;\n\n /** Optional binary read for file-like artifacts. */\n readBytes?(key: string): Uint8Array | null;\n\n /** Optional binary write for file-like artifacts. */\n writeBytes?(key: string, content: Uint8Array): void;\n\n /** Optional key listing by prefix. */\n listKeys?(prefix?: string): string[];\n\n /** Optional metadata lookup. */\n stat?(key: string): BlobStat | null;\n}\n\n// ============================================================================\n// KindValueRef — backend-neutral typed reference\n//\n// A ref describes WHERE content lives without carrying the bytes.\n// Serialized on the CLI wire as: b64:<base64url({\"kind\":\"...\",\"value\":\"...\"})>\n// kind = 'fs-path': value is an absolute file path\n// Additional kinds (e.g. 'cosmos') are added in public-storage-adapter.ts as new backends are supported.\n// ============================================================================\n\nexport interface KindValueRef {\n readonly kind: string;\n readonly value: string;\n}\n\nconst REF_PREFIX = 'b64:';\n\nfunction toBase64Url(raw: string): string {\n const utf8 = new TextEncoder().encode(raw);\n const buf = (globalThis as { Buffer?: { from(data: Uint8Array): { toString(enc: string): string } } }).Buffer;\n let base64: string;\n if (buf) {\n base64 = buf.from(utf8).toString('base64');\n } else if (typeof btoa === 'function') {\n let binary = '';\n for (const byte of utf8) binary += String.fromCharCode(byte);\n base64 = btoa(binary);\n } else {\n throw new Error('No base64 encoder available in this runtime');\n }\n return base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/g, '');\n}\n\nfunction fromBase64Url(input: string): string {\n const base64 = input.replace(/-/g, '+').replace(/_/g, '/')\n + '='.repeat((4 - (input.length % 4)) % 4);\n const buf = (globalThis as { Buffer?: { from(data: string, enc: string): { toString(enc: string): string } } }).Buffer;\n if (buf) return buf.from(base64, 'base64').toString('utf8');\n if (typeof atob === 'function') {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n return new TextDecoder().decode(bytes);\n }\n throw new Error('No base64 decoder available in this runtime');\n}\n\n/** Serialize a KindValueRef to the wire format: b64:<base64url(json)> */\nexport function serializeRef(ref: KindValueRef): string {\n return `${REF_PREFIX}${toBase64Url(JSON.stringify(ref))}`;\n}\n\n/** Parse a wire-format ref string (b64:<base64url(json)>) into a KindValueRef. */\nexport function parseRef(s: string): KindValueRef {\n if (!s.startsWith(REF_PREFIX)) throw new Error(`Invalid ref format (expected ${REF_PREFIX}<base64url(json)>): ${s}`);\n let parsed: unknown;\n try {\n parsed = JSON.parse(fromBase64Url(s.slice(REF_PREFIX.length)));\n } catch {\n throw new Error(`Invalid ref format (malformed base64url/json): ${s}`);\n }\n if (!parsed || typeof parsed !== 'object') {\n throw new Error(`Invalid ref format (expected object payload): ${s}`);\n }\n const candidate = parsed as { kind?: unknown; value?: unknown };\n if (typeof candidate.kind !== 'string' || typeof candidate.value !== 'string') {\n throw new Error(`Invalid ref format (payload must contain string kind/value): ${s}`);\n }\n return { kind: candidate.kind, value: candidate.value };\n}\n\n// ============================================================================\n// Journal — append-only log, cursor-based reads\n//\n// Each entry has a string id (UUID or monotonic token) and an opaque payload.\n// Cursors are entry ids — readAfter returns entries strictly after that id.\n// A null/empty cursor means \"read from the beginning\".\n// ============================================================================\n\nexport interface JournalEntry {\n id: string;\n payload: unknown;\n}\n\nexport interface JournalReadResult {\n entries: JournalEntry[];\n /** The id of the last entry returned, suitable for use as the next cursor. */\n newCursor: string | null;\n}\n\nexport interface JournalStorage {\n /** Append an entry. The storage layer assigns the id. */\n append(payload: unknown): JournalEntry;\n\n /** Read ALL entries (for index rebuilds, full replay). */\n readAll(): JournalEntry[];\n\n /**\n * Read entries appended after the given cursor id.\n * If cursor is null/empty, returns all entries from the beginning.\n */\n readAfter(cursor: string | null): JournalReadResult;\n}\n\n// ============================================================================\n// KV — key-value store with list and delete\n//\n// Values are opaque unknown — callers own serialisation.\n// Keys are scoped by the adapter factory (e.g. a boardDir prefix is closed\n// over in the adapter, not passed per-call).\n// ============================================================================\n\nexport interface KVStorage {\n /** Returns the stored value, or null if the key does not exist. */\n read(key: string): unknown | null;\n\n /** Write value at key. Overwrites any existing value. */\n write(key: string, value: unknown): void;\n\n /** Delete the key. No-op if it does not exist. */\n delete(key: string): void;\n\n /**\n * List all keys, optionally filtered to those starting with prefix.\n * Order is implementation-defined.\n */\n listKeys(prefix?: string): string[];\n}\n\n// ============================================================================\n// JSONStorage — KV store with JSON-aware merge operations\n//\n// Backed by KVStorage under the hood. Adds deepMerge and shallowMerge so\n// callers never need to read-modify-write manually for partial updates.\n// ============================================================================\n\nexport interface JSONStorage {\n /** Returns the stored JSON value, or null if the key does not exist. */\n read(key: string): unknown | null;\n\n /**\n * Read a nested value inside the stored object using a dot-notation path.\n * e.g. get('myKey', 'a.b.c') returns the value at { a: { b: { c: ... } } }.\n * Returns null if the key does not exist or the path cannot be traversed.\n */\n get(key: string, jsonPath: string): unknown | null;\n\n /** Write value at key. Overwrites any existing value. */\n write(key: string, value: unknown): void;\n\n /** Delete the key. No-op if it does not exist. */\n delete(key: string): void;\n\n /** List all keys, optionally filtered by prefix. */\n listKeys(prefix?: string): string[];\n\n /**\n * Shallow-merge patch into the existing object at key.\n * Equivalent to: write(key, { ...read(key), ...patch })\n * Creates the key if it does not exist.\n */\n shallowMerge(key: string, patch: Record<string, unknown>): void;\n\n /**\n * Deep-merge patch into the existing object at key.\n * Recursively merges nested plain objects; arrays and primitives are replaced.\n * Creates the key if it does not exist.\n */\n deepMerge(key: string, patch: Record<string, unknown>): void;\n\n /**\n * Set a nested value inside the stored object using a dot-notation path.\n * e.g. patch('myKey', 'a.b.c', 42) sets { a: { b: { c: 42 } } } into the stored object.\n * Intermediate objects are created if absent. Arrays are not traversed — use integer\n * segments to index into them (e.g. 'items.0.name').\n * Creates the top-level key if it does not exist.\n */\n patch(key: string, jsonPath: string, value: unknown): void;\n}\n\n// ============================================================================\n// StorageProvider — aggregate of all three primitives\n//\n// Adapter factories receive a StorageProvider and close over any scope (e.g.\n// boardDir) themselves. This is the single injection point for swapping\n// backends (Node fs → CosmosDB, browser localStorage, test doubles, etc.).\n// ============================================================================\n\nexport interface StorageProvider {\n blob: BlobStorage;\n journal: JournalStorage;\n kv: KVStorage;\n}\n\n// ============================================================================\n// AtomicRelayLock — non-blocking try-acquire lock with relay-on-busy semantics\n//\n// This interface serves TWO tightly coupled purposes which are intentionally\n// unified into a single primitive:\n//\n// 1. ATOMICITY — ensures that a read-mutate-save cycle is executed by at\n// most one actor at a time, preventing concurrent actors from racing on\n// stale state and writing conflicting snapshots.\n//\n// 2. RELAY SIGNAL — when tryAcquire() returns null, the caller knows the\n// cycle is already in progress. Because the holder always reads fresh\n// state upon entry, it will pick up every change appended by the skipping\n// caller before the lock was attempted. The caller can therefore safely\n// exit — its work will be completed by the holder. This is the\n// \"relay baton\" pattern: the lock being held IS the in-progress signal.\n//\n// These two purposes are not an accidental overload — they are the same\n// invariant expressed at different scopes. Any backend implementation\n// (FS lockfile, Cosmos document lease, Azure entity lock, in-memory flag)\n// that satisfies \"at most one holder at a time\" automatically satisfies both.\n//\n// Contract:\n// - tryAcquire() is non-blocking. It never waits.\n// - Returns a release function on success, or null if already held.\n// - The release function must be called exactly once (use try/finally).\n// - Behaviour after calling release() more than once is undefined.\n// ============================================================================\n\nexport interface AtomicRelayLock {\n /**\n * Attempt to acquire the lock without blocking.\n * Returns a `release` function if successful, or `null` if the lock is\n * already held by another actor (relay: that actor will complete the work).\n */\n tryAcquire(): (() => void) | null;\n}\n\n/**\n * Execute `work` under an `AtomicRelayLock`.\n *\n * - If the lock is busy, returns false immediately (relay: the holder will\n * complete the work on behalf of this caller).\n * - If acquired, runs `work` exclusively, releases the lock, then calls\n * `continuation` if provided — allowing the caller to schedule the next\n * cycle (e.g. spawn a detached process) after the lock is free.\n * - Returns true if work ran.\n */\nexport async function withRelayLock(\n lock: AtomicRelayLock,\n work: () => Promise<void>,\n continuation?: () => void,\n): Promise<boolean> {\n const release = lock.tryAcquire();\n if (!release) return false; // relay: holder is already doing the work\n try {\n await work();\n } finally {\n release(); // release before continuation so it can immediately re-acquire\n }\n continuation?.();\n return true;\n}\n","/**\n * step-machine-public — handler factory\n *\n * Builds engine-facing StepHandlers from declarative HandlerSpec entries.\n * Pure: no Node imports, no transport. Refs are dispatched through the\n * caller-supplied `InvokeFn`, which is the single boundary between this lib\n * and any transport (Node spawn, HTTP, Azure Function, etc.).\n *\n * Layering:\n *\n * step-machine (pure FSM) — runs handlers, never builds them.\n * step-machine-public (this lib) — declarative spec → StepHandler map.\n * adapter (e.g. node-spawn-invoker) — InvokeFn implementation per transport.\n * step-machine-cli (thin shell) — wires adapter + flow loader + run.\n */\n\nimport { jsonata } from './jsonata-loader.js';\nimport { wrapWithInputValidations, wrapWithOutputFiltering } from './result-utils.js';\nimport { resolveOutputTransforms } from '../cli/common/args-massaging.js';\nimport { serializeRef } from '../cli/common/storage-interface.js';\nimport type {\n ComputeJsonataSpec,\n HandlerSpec,\n InvokeRefFn,\n NormalizedHandlerResult,\n RefSpec,\n StepConfigForFactory,\n StepHandler,\n} from './types.js';\n\n// ============================================================================\n// Discriminators\n// ============================================================================\n\nexport function isComputeJsonataSpec(spec: unknown): spec is ComputeJsonataSpec {\n return (\n !!spec &&\n typeof spec === 'object' &&\n (spec as Record<string, unknown>).type === 'compute-jsonata' &&\n Array.isArray((spec as Record<string, unknown>).expr) &&\n ((spec as Record<string, unknown>).expr as unknown[]).length > 0\n );\n}\n\nexport function isRefSpec(spec: unknown): spec is RefSpec {\n if (!spec || typeof spec !== 'object') return false;\n const s = spec as Record<string, unknown>;\n if (s.type !== 'ref' || typeof s.howToRun !== 'string') return false;\n if (typeof s.whatToRun === 'string') return true;\n if (s.whatToRun && typeof s.whatToRun === 'object') {\n const w = s.whatToRun as Record<string, unknown>;\n return typeof w.kind === 'string' && typeof w.value === 'string';\n }\n return false;\n}\n\n// ============================================================================\n// Compute-jsonata handler\n// ============================================================================\n\ninterface NormalizedComputeStep {\n bindTo: string;\n expr: string;\n}\n\nfunction normalizeComputeStep(item: string | { bindTo: string; expr: string }): NormalizedComputeStep {\n if (typeof item === 'string') {\n const eq = item.indexOf('=');\n if (eq < 1) {\n throw new Error(`[step-machine-public] Invalid compute expression (missing \"=\"): \"${item}\"`);\n }\n return { bindTo: item.slice(0, eq).trim(), expr: item.slice(eq + 1).trim() };\n }\n if (item && typeof item === 'object' && typeof item.bindTo === 'string' && typeof item.expr === 'string') {\n return item;\n }\n throw new Error(`[step-machine-public] Invalid compute step: ${JSON.stringify(item)}`);\n}\n\n/** Mutate nested dict via dot-path key. */\nfunction deepSet(obj: Record<string, unknown>, path: string, value: unknown): void {\n const parts = path.split('.');\n let cur: Record<string, unknown> = obj;\n for (let i = 0; i < parts.length - 1; i++) {\n const k = parts[i];\n if (cur[k] == null || typeof cur[k] !== 'object') cur[k] = {};\n cur = cur[k] as Record<string, unknown>;\n }\n cur[parts[parts.length - 1]] = value;\n}\n\nexport function createComputeJsonataHandler(\n spec: ComputeJsonataSpec,\n stepName: string,\n config?: Record<string, unknown>,\n): StepHandler {\n const steps = spec.expr.map(normalizeComputeStep);\n return async (input) => {\n const expects_data: Record<string, unknown> =\n input && typeof input === 'object' && !Array.isArray(input)\n ? { ...input }\n : {};\n\n // `data` accumulates computed outputs; it is placed in ctx by reference\n // so subsequent expressions can read `data.x` after earlier steps set it.\n const data: Record<string, unknown> = {};\n\n // Context shape:\n // expects_data — named namespace for declared step inputs (from flow state)\n // data — accumulating output namespace (required, mutated by reference)\n // config — optional step-level config\n const ctx: Record<string, unknown> = {\n expects_data,\n data, // same reference — mutations visible in later steps\n ...(config ? { config } : {}),\n };\n\n let transitionResult: string | undefined;\n let transitionError: string | undefined;\n\n for (const step of steps) {\n try {\n const val = jsonata(step.expr).evaluate(ctx);\n\n if (step.bindTo === 'result') {\n // Transition outcome\n transitionResult = val != null ? String(val) : 'success';\n } else if (step.bindTo === 'error') {\n // Transition error detail\n transitionError = val != null ? String(val) : undefined;\n } else if (step.bindTo.startsWith('data.')) {\n // Namespaced output — mutates the shared data reference\n deepSet(data, step.bindTo.slice('data.'.length), val);\n } else {\n return {\n result: 'failure',\n data: {},\n error: `[${stepName}] invalid bindTo \"${step.bindTo}\": must be \"result\", \"error\", or start with \"data.\"`,\n };\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return {\n result: 'failure',\n data: {},\n error: `[${stepName}] compute \"${step.bindTo}\" failed: ${msg}`,\n };\n }\n }\n\n if (transitionResult === undefined) {\n return {\n result: 'failure',\n data: {},\n error: `[${stepName}] compute-jsonata: no \"result\" binding declared — add '- result = \"success\"' to expr`,\n };\n }\n return transitionError\n ? { result: transitionResult, data, error: transitionError }\n : { result: transitionResult, data };\n };\n}\n\n// ============================================================================\n// Ref handler — dispatches via InvokeFn\n// ============================================================================\n\nexport function createRefStepHandler(\n spec: RefSpec,\n stepName: string,\n invoke: InvokeRefFn,\n config?: Record<string, unknown>,\n): StepHandler {\n // The handler spec itself is a superset of ExecutionRef. Strip the discriminator\n // before passing to the adapter so it sees a plain ExecutionRef.\n // Normalize whatToRun from object form { kind, value } → b64 string.\n const { type: _t, ...refOnly } = spec;\n const ref = {\n ...refOnly,\n whatToRun: typeof refOnly.whatToRun === 'object'\n ? serializeRef(refOnly.whatToRun)\n : refOnly.whatToRun,\n };\n\n return async (input) => {\n const stepInput: Record<string, unknown> =\n input && typeof input === 'object' && !Array.isArray(input)\n ? { ...input }\n : {};\n if (config) stepInput.config = config;\n\n try {\n const raw = await invoke(ref, stepInput);\n if (!spec.outputTransforms) return raw;\n try {\n return resolveOutputTransforms(spec.outputTransforms, raw, stepName);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { result: 'failure', data: {}, error: msg };\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return {\n result: 'failure',\n data: { error: `[step-machine-public] step \"${stepName}\" invoke threw: ${msg}` },\n };\n }\n };\n}\n\n// ============================================================================\n// Passthrough handler\n// ============================================================================\n\nexport function createPassthroughHandler(): StepHandler {\n return async (input) => {\n const data: Record<string, unknown> =\n input && typeof input === 'object' && !Array.isArray(input)\n ? (input as Record<string, unknown>)\n : {};\n return { result: 'success', data };\n };\n}\n\n// ============================================================================\n// resolveStepHandler — pick + decorate the right handler for a step\n// ============================================================================\n\nexport interface ResolveStepHandlerOptions {\n invoke: InvokeRefFn;\n}\n\nexport function resolveStepHandler(\n stepName: string,\n stepConfig: StepConfigForFactory | undefined,\n options: ResolveStepHandlerOptions,\n): StepHandler {\n const produces = Array.isArray(stepConfig?.produces_data) ? stepConfig?.produces_data : undefined;\n const inputValidations = Array.isArray(stepConfig?.input_validations)\n ? stepConfig?.input_validations\n : undefined;\n const config = stepConfig?.config ?? undefined;\n const spec: HandlerSpec | undefined = stepConfig?.handler;\n\n let base: StepHandler;\n if (isComputeJsonataSpec(spec)) {\n // compute-jsonata: validations are baked in via the wrapper as well; both work.\n base = createComputeJsonataHandler(spec, stepName, config);\n } else if (isRefSpec(spec)) {\n base = createRefStepHandler(spec, stepName, options.invoke, config);\n } else {\n base = createPassthroughHandler();\n }\n\n return wrapWithInputValidations(\n wrapWithOutputFiltering(base, produces),\n inputValidations,\n stepName,\n );\n}\n\n// ============================================================================\n// buildStepHandlersForFlow — produce the Record<stepName, StepHandler> map\n// ============================================================================\n\nexport interface BuildStepHandlersOptions {\n invoke: InvokeRefFn;\n}\n\nexport function buildStepHandlersForFlow(\n flow: { steps?: Record<string, StepConfigForFactory> },\n options: BuildStepHandlersOptions,\n): Record<string, StepHandler> {\n const handlers: Record<string, StepHandler> = {};\n for (const [stepName, stepConfig] of Object.entries(flow.steps ?? {})) {\n handlers[stepName] = resolveStepHandler(stepName, stepConfig, options);\n }\n return handlers;\n}\n\n// Re-export for adapter convenience.\nexport type { NormalizedHandlerResult };\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cli/node/public-storage-adapter.ts"],"names":["parseRef","s","payload","padded","decoded","candidate","serializeRef","ref","createFsPathBlobStorage","key","i","content","c","blobStorageForRef","_parseWhatToRun","whatToRun","_notifyChannelFromVia","via","_resolveLocalNodeInvocation","scriptPath","dir","candidates","up","base","tsx","p","reportComplete","callback","outRef","token","cmd","args","notifyChannel","callbackArgs","result","spawnSync","url","body","_httpPostSync","reportFailed","reason","script"],"mappings":"mfA8CO,SAASA,CAAAA,CAASC,CAAAA,CAAyB,CAChD,GAAI,CAACA,CAAAA,CAAE,UAAA,CAAW,MAAM,CAAA,CAAG,MAAM,IAAI,KAAA,CAAM,CAAA,qDAAA,EAAwDA,CAAC,CAAA,CAAE,CAAA,CACtG,IAAMC,CAAAA,CAAUD,EAAE,KAAA,CAAM,CAAC,CAAA,CACnBE,CAAAA,CAASD,EAAQ,OAAA,CAAQ,IAAA,CAAM,GAAG,CAAA,CAAE,OAAA,CAAQ,IAAA,CAAM,GAAG,CAAA,CAAI,IAAI,MAAA,CAAA,CAAQ,CAAA,CAAKA,CAAAA,CAAQ,MAAA,CAAS,GAAM,CAAC,CAAA,CACpGE,CAAAA,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EAAQ,IAAA,EAAM,CAAA,CAAE,CACvF","file":"storage-refs.cjs","sourcesContent":["/**\n * public-storage-adapter.ts\n *\n * Standalone file — copy this to your task-executor project.\n * Zero dependencies on the rest of yaml-flow.\n *\n * Provides:\n * - KindValueRef wire format: b64:<base64url(json)>\n * - parseRef() parse a b64:<base64url(json)> string\n * - serializeRef() produce a b64:<base64url(json)> string\n * - BlobStorage read/write interface\n * - blobStorageForRef resolve a ref to its BlobStorage backend\n * - ExecutionRef portable invocation descriptor (inlined, stays standalone)\n * - TaskCallback how to report task completion back to the board\n * - reportComplete() call from executor on success\n * - reportFailed() call from executor on failure\n *\n * Supported storage kinds:\n * fs-path — ref.value is an absolute file path; reads/writes via node:fs\n *\n * Supported callback transports (via ExecutionRef.howToRun):\n * local-node — invoke board CLI as a child Node process\n * http:post — HTTP POST to a board endpoint\n *\n * Usage:\n * import { parseRef, blobStorageForRef, reportComplete, reportFailed } from './public-storage-adapter.js';\n *\n * const { source_def, callback } = JSON.parse(blobStorageForRef(inRef).read(inRef.value));\n * // ... do work, write to outRef ...\n * reportComplete(callback, outRef);\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { spawnSync } from 'node:child_process';\n\n// ============================================================================\n// KindValueRef\n// ============================================================================\n\nexport interface KindValueRef {\n readonly kind: string;\n readonly value: string;\n}\n\n/** Parse a wire-format ref string (b64:<base64url(json)>) into a KindValueRef. */\nexport function parseRef(s: string): KindValueRef {\n if (!s.startsWith('b64:')) throw new Error(`Invalid ref format (expected b64:<base64url(json)>): ${s}`);\n const payload = s.slice(4);\n const padded = payload.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (payload.length % 4)) % 4);\n let decoded: unknown;\n try {\n decoded = JSON.parse(Buffer.from(padded, 'base64').toString('utf8'));\n } catch {\n throw new Error(`Invalid ref format (malformed base64url/json): ${s}`);\n }\n if (!decoded || typeof decoded !== 'object') {\n throw new Error(`Invalid ref format (expected object payload): ${s}`);\n }\n const candidate = decoded as { kind?: unknown; value?: unknown };\n if (typeof candidate.kind !== 'string' || typeof candidate.value !== 'string') {\n throw new Error(`Invalid ref format (payload must contain string kind/value): ${s}`);\n }\n return { kind: candidate.kind, value: candidate.value };\n}\n\n/** Serialize a KindValueRef to the wire format: b64:<base64url(json)> */\nexport function serializeRef(ref: KindValueRef): string {\n return `b64:${Buffer.from(JSON.stringify(ref), 'utf8').toString('base64').replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/g, '')}`;\n}\n\n// ============================================================================\n// BlobStorage\n// ============================================================================\n\nexport interface BlobStorage {\n /** Returns content string, or null if not found. */\n read(key: string): string | null;\n /** Write content at key. */\n write(key: string, content: string): void;\n}\n\n// ============================================================================\n// fs-path backend — key IS the absolute file path\n// ============================================================================\n\nfunction createFsPathBlobStorage(): BlobStorage {\n return {\n read(key: string): string | null {\n if (!fs.existsSync(key)) return null;\n try { return fs.readFileSync(key, 'utf-8'); } catch { return null; }\n },\n write(key: string, content: string): void {\n fs.mkdirSync(path.dirname(key), { recursive: true });\n fs.writeFileSync(key, content, 'utf-8');\n },\n };\n}\n\n// ============================================================================\n// blobStorageForRef\n// ============================================================================\n\n/**\n * Resolve a KindValueRef to its BlobStorage backend.\n * Throws a clear error for unrecognised kinds.\n */\nexport function blobStorageForRef(ref: KindValueRef): BlobStorage {\n switch (ref.kind) {\n case 'fs-path': return createFsPathBlobStorage();\n default: throw new Error(`Unsupported storage kind: \"${ref.kind}\". Supported kinds: fs-path`);\n }\n}\n\n// ============================================================================\n// TaskCallback — how a task-executor reports results back to the board\n// ============================================================================\n\n/**\n * Portable invocation descriptor for the board CLI back-channel.\n * Inlined here so this file stays standalone (zero deps on yaml-flow internals).\n * Shape matches ExecutionRef in execution-interface.ts — keep in sync.\n *\n * Supported howToRun values for TaskCallback.via:\n * local-node — invoke board CLI as: node [tsx?] <whatToRun.value> <cmd> [...argv]\n * http:post — POST to <whatToRun.value> with a JSON body\n */\nexport interface ExecutionRef {\n /** Optional human-readable label. Not used for dispatch. */\n meta?: string;\n /** Transport / runtime kind. */\n howToRun: 'local-node' | 'local-python' | 'local-process' | 'http:post' | 'http:get' | 'built-in';\n /** Address of the target in b64:<base64url(json)> wire form. */\n whatToRun: string;\n /** Opaque executor config stored with the ref. */\n extra?: Record<string, unknown>;\n}\n\n/**\n * Describes how the board wants to receive task completion callbacks.\n * Baked into the inRef payload as { source_def, callback }.\n * The executor treats `token` as opaque and passes it back unchanged.\n */\nexport interface TaskCallback {\n /** Opaque routing token — generated by the board, passed back unchanged. */\n token: string;\n /** Delivery mechanism — an ExecutionRef pointing at the board CLI or endpoint. */\n via: ExecutionRef;\n}\n\n/**\n * Extract the path/url value from a whatToRun b64:<base64url(json)> wire string.\n */\nfunction _parseWhatToRun(whatToRun: string): string {\n return parseRef(whatToRun).value;\n}\n\nfunction _notifyChannelFromVia(via: ExecutionRef): string | undefined {\n const candidate = via.extra?.['notifyChannel'];\n return typeof candidate === 'string' && candidate.length > 0 ? candidate : undefined;\n}\n\n/**\n * Resolve the Node invocation for a local board CLI script.\n * If the path ends in .ts (dev mode), attempts to locate tsx alongside it;\n * otherwise assumes it’s a compiled .js and invokes directly with node.\n */\nfunction _resolveLocalNodeInvocation(scriptPath: string): { cmd: string; args: string[] } {\n if (!scriptPath.endsWith('.ts')) {\n return { cmd: process.execPath, args: [scriptPath] };\n }\n // Dev path: look for tsx in node_modules relative to the script's package root.\n // The .ts file may be at src/cli/node/<file>.ts — walk up until we find node_modules/tsx.\n const dir = path.dirname(scriptPath);\n const candidates: string[] = [];\n for (let up = 1; up <= 5; up++) {\n const base = path.join(dir, ...Array(up).fill('..'), 'node_modules');\n candidates.push(path.join(base, 'tsx', 'dist', 'cli.mjs'));\n candidates.push(path.join(base, '.bin', 'tsx'));\n }\n const tsx = candidates.find(p => fs.existsSync(p));\n if (tsx) return { cmd: process.execPath, args: [tsx, scriptPath] };\n return { cmd: 'npx', args: ['tsx', scriptPath] };\n}\n\n/**\n * Report successful task completion back to the board.\n * Call this from a task-executor after writing the result to outRef.\n */\nexport function reportComplete(callback: TaskCallback, outRef: KindValueRef): void {\n const { token, via } = callback;\n if (via.howToRun === 'local-node' || via.howToRun === 'local-process') {\n const scriptPath = _parseWhatToRun(via.whatToRun);\n const { cmd, args } = _resolveLocalNodeInvocation(scriptPath);\n const notifyChannel = _notifyChannelFromVia(via);\n const callbackArgs = [\n ...args,\n 'source-data-fetched',\n '--ref', serializeRef(outRef),\n '--token', token,\n ...(notifyChannel ? ['--notify-channel', notifyChannel] : []),\n ];\n const result = spawnSync(cmd, callbackArgs, { encoding: 'utf-8', windowsHide: true });\n if (result.status !== 0) {\n throw new Error(`reportComplete: board CLI exited ${result.status}: ${result.stderr?.trim()}`);\n }\n return;\n }\n if (via.howToRun === 'http:post') {\n const url = _parseWhatToRun(via.whatToRun);\n const body = JSON.stringify({ status: 'complete', ref: serializeRef(outRef), token });\n _httpPostSync(url, body);\n return;\n }\n throw new Error(`reportComplete: unsupported via.howToRun \"${via.howToRun}\"`);\n}\n\n/**\n * Report task failure back to the board.\n * Call this from a task-executor instead of writing to outRef.\n */\nexport function reportFailed(callback: TaskCallback, reason: string): void {\n const { token, via } = callback;\n if (via.howToRun === 'local-node' || via.howToRun === 'local-process') {\n const scriptPath = _parseWhatToRun(via.whatToRun);\n const { cmd, args } = _resolveLocalNodeInvocation(scriptPath);\n const notifyChannel = _notifyChannelFromVia(via);\n const callbackArgs = [\n ...args,\n 'source-data-fetch-failure',\n '--token', token,\n '--reason', reason,\n ...(notifyChannel ? ['--notify-channel', notifyChannel] : []),\n ];\n const result = spawnSync(cmd, callbackArgs, { encoding: 'utf-8', windowsHide: true });\n if (result.status !== 0) {\n throw new Error(`reportFailed: board CLI exited ${result.status}: ${result.stderr?.trim()}`);\n }\n return;\n }\n if (via.howToRun === 'http:post') {\n const url = _parseWhatToRun(via.whatToRun);\n const body = JSON.stringify({ status: 'failed', reason, token });\n _httpPostSync(url, body);\n return;\n }\n throw new Error(`reportFailed: unsupported via.howToRun \"${via.howToRun}\"`);\n}\n\n/** Synchronous HTTP POST using a child node process (keeps this file free of async). */\nfunction _httpPostSync(url: string, body: string): void {\n const script = `\n const {request} = require(new URL('${url}').protocol === 'https:' ? 'https' : 'http');\n const h = ${JSON.stringify({ 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) })};\n const u = new URL('${url}');\n const req = request({hostname:u.hostname,port:u.port,path:u.pathname+u.search,method:'POST',headers:h});\n req.on('error', e => { process.stderr.write(e.message); process.exit(1); });\n req.write(${JSON.stringify(body)});\n req.end();\n `;\n const result = spawnSync(process.execPath, ['-e', script], { encoding: 'utf-8', windowsHide: true });\n if (result.status !== 0) throw new Error(`http-post failed: ${result.stderr?.trim()}`);\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cli/node/public-storage-adapter.ts"],"names":["parseRef","s","payload","padded","decoded","candidate","serializeRef","ref","createFsPathBlobStorage","key","content","blobStorageForRef","_parseWhatToRun","whatToRun","_notifyChannelFromVia","via","_resolveLocalNodeInvocation","scriptPath","dir","candidates","up","base","tsx","p","reportComplete","callback","outRef","token","cmd","args","notifyChannel","callbackArgs","result","spawnSync","url","body","_httpPostSync","reportFailed","reason","script"],"mappings":"kFA8CO,SAASA,CAAAA,CAASC,CAAAA,CAAyB,CAChD,GAAI,CAACA,CAAAA,CAAE,UAAA,CAAW,MAAM,CAAA,CAAG,MAAM,IAAI,KAAA,CAAM,CAAA,qDAAA,EAAwDA,CAAC,CAAA,CAAE,CAAA,CACtG,IAAMC,CAAAA,CAAUD,EAAE,KAAA,CAAM,CAAC,CAAA,CACnBE,CAAAA,CAASD,EAAQ,OAAA,CAAQ,IAAA,CAAM,GAAG,CAAA,CAAE,OAAA,CAAQ,IAAA,CAAM,GAAG,CAAA,CAAI,IAAI,MAAA,CAAA,CAAQ,CAAA,CAAKA,CAAAA,CAAQ,MAAA,CAAS,GAAM,CAAC,CAAA,CACpGE,CAAAA,CACJ,GAAI,CACFA,CAAAA,CAAU,IA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sourcesContent":["/**\n * public-storage-adapter.ts\n *\n * Standalone file — copy this to your task-executor project.\n * Zero dependencies on the rest of yaml-flow.\n *\n * Provides:\n * - KindValueRef wire format: b64:<base64url(json)>\n * - parseRef() parse a b64:<base64url(json)> string\n * - serializeRef() produce a b64:<base64url(json)> string\n * - BlobStorage read/write interface\n * - blobStorageForRef resolve a ref to its BlobStorage backend\n * - ExecutionRef portable invocation descriptor (inlined, stays standalone)\n * - TaskCallback how to report task completion back to the board\n * - reportComplete() call from executor on success\n * - reportFailed() call from executor on failure\n *\n * Supported storage kinds:\n * fs-path — ref.value is an absolute file path; reads/writes via node:fs\n *\n * Supported callback transports (via ExecutionRef.howToRun):\n * local-node — invoke board CLI as a child Node process\n * http:post — HTTP POST to a board endpoint\n *\n * Usage:\n * import { parseRef, blobStorageForRef, reportComplete, reportFailed } from './public-storage-adapter.js';\n *\n * const { source_def, callback } = JSON.parse(blobStorageForRef(inRef).read(inRef.value));\n * // ... do work, write to outRef ...\n * reportComplete(callback, outRef);\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { spawnSync } from 'node:child_process';\n\n// ============================================================================\n// KindValueRef\n// ============================================================================\n\nexport interface KindValueRef {\n readonly kind: string;\n readonly value: string;\n}\n\n/** Parse a wire-format ref string (b64:<base64url(json)>) into a KindValueRef. */\nexport function parseRef(s: string): KindValueRef {\n if (!s.startsWith('b64:')) throw new Error(`Invalid ref format (expected b64:<base64url(json)>): ${s}`);\n const payload = s.slice(4);\n const padded = payload.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (payload.length % 4)) % 4);\n let decoded: unknown;\n try {\n decoded = JSON.parse(Buffer.from(padded, 'base64').toString('utf8'));\n } catch {\n throw new Error(`Invalid ref format (malformed base64url/json): ${s}`);\n }\n if (!decoded || typeof decoded !== 'object') {\n throw new Error(`Invalid ref format (expected object payload): ${s}`);\n }\n const candidate = decoded as { kind?: unknown; value?: unknown };\n if (typeof candidate.kind !== 'string' || typeof candidate.value !== 'string') {\n throw new Error(`Invalid ref format (payload must contain string kind/value): ${s}`);\n }\n return { kind: candidate.kind, value: candidate.value };\n}\n\n/** Serialize a KindValueRef to the wire format: b64:<base64url(json)> */\nexport function serializeRef(ref: KindValueRef): string {\n return `b64:${Buffer.from(JSON.stringify(ref), 'utf8').toString('base64').replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/g, '')}`;\n}\n\n// ============================================================================\n// BlobStorage\n// ============================================================================\n\nexport interface BlobStorage {\n /** Returns content string, or null if not found. */\n read(key: string): string | null;\n /** Write content at key. */\n write(key: string, content: string): void;\n}\n\n// ============================================================================\n// fs-path backend — key IS the absolute file path\n// ============================================================================\n\nfunction createFsPathBlobStorage(): BlobStorage {\n return {\n read(key: string): string | null {\n if (!fs.existsSync(key)) return null;\n try { return fs.readFileSync(key, 'utf-8'); } catch { return null; }\n },\n write(key: string, content: string): void {\n fs.mkdirSync(path.dirname(key), { recursive: true });\n fs.writeFileSync(key, content, 'utf-8');\n },\n };\n}\n\n// ============================================================================\n// blobStorageForRef\n// ============================================================================\n\n/**\n * Resolve a KindValueRef to its BlobStorage backend.\n * Throws a clear error for unrecognised kinds.\n */\nexport function blobStorageForRef(ref: KindValueRef): BlobStorage {\n switch (ref.kind) {\n case 'fs-path': return createFsPathBlobStorage();\n default: throw new Error(`Unsupported storage kind: \"${ref.kind}\". Supported kinds: fs-path`);\n }\n}\n\n// ============================================================================\n// TaskCallback — how a task-executor reports results back to the board\n// ============================================================================\n\n/**\n * Portable invocation descriptor for the board CLI back-channel.\n * Inlined here so this file stays standalone (zero deps on yaml-flow internals).\n * Shape matches ExecutionRef in execution-interface.ts — keep in sync.\n *\n * Supported howToRun values for TaskCallback.via:\n * local-node — invoke board CLI as: node [tsx?] <whatToRun.value> <cmd> [...argv]\n * http:post — POST to <whatToRun.value> with a JSON body\n */\nexport interface ExecutionRef {\n /** Optional human-readable label. Not used for dispatch. */\n meta?: string;\n /** Transport / runtime kind. */\n howToRun: 'local-node' | 'local-python' | 'local-process' | 'http:post' | 'http:get' | 'built-in';\n /** Address of the target in b64:<base64url(json)> wire form. */\n whatToRun: string;\n /** Opaque executor config stored with the ref. */\n extra?: Record<string, unknown>;\n}\n\n/**\n * Describes how the board wants to receive task completion callbacks.\n * Baked into the inRef payload as { source_def, callback }.\n * The executor treats `token` as opaque and passes it back unchanged.\n */\nexport interface TaskCallback {\n /** Opaque routing token — generated by the board, passed back unchanged. */\n token: string;\n /** Delivery mechanism — an ExecutionRef pointing at the board CLI or endpoint. */\n via: ExecutionRef;\n}\n\n/**\n * Extract the path/url value from a whatToRun b64:<base64url(json)> wire string.\n */\nfunction _parseWhatToRun(whatToRun: string): string {\n return parseRef(whatToRun).value;\n}\n\nfunction _notifyChannelFromVia(via: ExecutionRef): string | undefined {\n const candidate = via.extra?.['notifyChannel'];\n return typeof candidate === 'string' && candidate.length > 0 ? candidate : undefined;\n}\n\n/**\n * Resolve the Node invocation for a local board CLI script.\n * If the path ends in .ts (dev mode), attempts to locate tsx alongside it;\n * otherwise assumes it’s a compiled .js and invokes directly with node.\n */\nfunction _resolveLocalNodeInvocation(scriptPath: string): { cmd: string; args: string[] } {\n if (!scriptPath.endsWith('.ts')) {\n return { cmd: process.execPath, args: [scriptPath] };\n }\n // Dev path: look for tsx in node_modules relative to the script's package root.\n // The .ts file may be at src/cli/node/<file>.ts — walk up until we find node_modules/tsx.\n const dir = path.dirname(scriptPath);\n const candidates: string[] = [];\n for (let up = 1; up <= 5; up++) {\n const base = path.join(dir, ...Array(up).fill('..'), 'node_modules');\n candidates.push(path.join(base, 'tsx', 'dist', 'cli.mjs'));\n candidates.push(path.join(base, '.bin', 'tsx'));\n }\n const tsx = candidates.find(p => fs.existsSync(p));\n if (tsx) return { cmd: process.execPath, args: [tsx, scriptPath] };\n return { cmd: 'npx', args: ['tsx', scriptPath] };\n}\n\n/**\n * Report successful task completion back to the board.\n * Call this from a task-executor after writing the result to outRef.\n */\nexport function reportComplete(callback: TaskCallback, outRef: KindValueRef): void {\n const { token, via } = callback;\n if (via.howToRun === 'local-node' || via.howToRun === 'local-process') {\n const scriptPath = _parseWhatToRun(via.whatToRun);\n const { cmd, args } = _resolveLocalNodeInvocation(scriptPath);\n const notifyChannel = _notifyChannelFromVia(via);\n const callbackArgs = [\n ...args,\n 'source-data-fetched',\n '--ref', serializeRef(outRef),\n '--token', token,\n ...(notifyChannel ? ['--notify-channel', notifyChannel] : []),\n ];\n const result = spawnSync(cmd, callbackArgs, { encoding: 'utf-8', windowsHide: true });\n if (result.status !== 0) {\n throw new Error(`reportComplete: board CLI exited ${result.status}: ${result.stderr?.trim()}`);\n }\n return;\n }\n if (via.howToRun === 'http:post') {\n const url = _parseWhatToRun(via.whatToRun);\n const body = JSON.stringify({ status: 'complete', ref: serializeRef(outRef), token });\n _httpPostSync(url, body);\n return;\n }\n throw new Error(`reportComplete: unsupported via.howToRun \"${via.howToRun}\"`);\n}\n\n/**\n * Report task failure back to the board.\n * Call this from a task-executor instead of writing to outRef.\n */\nexport function reportFailed(callback: TaskCallback, reason: string): void {\n const { token, via } = callback;\n if (via.howToRun === 'local-node' || via.howToRun === 'local-process') {\n const scriptPath = _parseWhatToRun(via.whatToRun);\n const { cmd, args } = _resolveLocalNodeInvocation(scriptPath);\n const notifyChannel = _notifyChannelFromVia(via);\n const callbackArgs = [\n ...args,\n 'source-data-fetch-failure',\n '--token', token,\n '--reason', reason,\n ...(notifyChannel ? ['--notify-channel', notifyChannel] : []),\n ];\n const result = spawnSync(cmd, callbackArgs, { encoding: 'utf-8', windowsHide: true });\n if (result.status !== 0) {\n throw new Error(`reportFailed: board CLI exited ${result.status}: ${result.stderr?.trim()}`);\n }\n return;\n }\n if (via.howToRun === 'http:post') {\n const url = _parseWhatToRun(via.whatToRun);\n const body = JSON.stringify({ status: 'failed', reason, token });\n _httpPostSync(url, body);\n return;\n }\n throw new Error(`reportFailed: unsupported via.howToRun \"${via.howToRun}\"`);\n}\n\n/** Synchronous HTTP POST using a child node process (keeps this file free of async). */\nfunction _httpPostSync(url: string, body: string): void {\n const script = `\n const {request} = require(new URL('${url}').protocol === 'https:' ? 'https' : 'http');\n const h = ${JSON.stringify({ 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) })};\n const u = new URL('${url}');\n const req = request({hostname:u.hostname,port:u.port,path:u.pathname+u.search,method:'POST',headers:h});\n req.on('error', e => { process.stderr.write(e.message); process.exit(1); });\n req.write(${JSON.stringify(body)});\n req.end();\n `;\n const result = spawnSync(process.execPath, ['-e', script], { encoding: 'utf-8', windowsHide: true });\n if (result.status !== 0) throw new Error(`http-post failed: ${result.stderr?.trim()}`);\n}\n"]}
@@ -1,2 +0,0 @@
1
- 'use strict';var a=class{directory;fs=null;path=null;constructor(i){this.directory=i.directory;}async ensureModules(){(!this.fs||!this.path)&&(this.fs=await import('fs/promises'),this.path=await import('path'),await this.fs.mkdir(this.directory,{recursive:true}));}runPath(i){return this.path.join(this.directory,`${i}.run.json`)}dataPath(i){return this.path.join(this.directory,`${i}.data.json`)}async saveRunState(i,t){await this.ensureModules(),await this.fs.writeFile(this.runPath(i),JSON.stringify(t,null,2),"utf-8");}async loadRunState(i){await this.ensureModules();try{let t=await this.fs.readFile(this.runPath(i),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async deleteRunState(i){await this.ensureModules();try{await this.fs.unlink(this.runPath(i));}catch(t){if(t.code!=="ENOENT")throw t}try{await this.fs.unlink(this.dataPath(i));}catch(t){if(t.code!=="ENOENT")throw t}}async setData(i,t,r){await this.ensureModules();let e=await this.getAllData(i);e[t]=r,await this.fs.writeFile(this.dataPath(i),JSON.stringify(e,null,2),"utf-8");}async getData(i,t){return (await this.getAllData(i))[t]}async getAllData(i){await this.ensureModules();try{let t=await this.fs.readFile(this.dataPath(i),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return {};throw t}}async clearData(i){await this.ensureModules();try{await this.fs.unlink(this.dataPath(i));}catch(t){if(t.code!=="ENOENT")throw t}}async listRuns(){await this.ensureModules();try{return (await this.fs.readdir(this.directory)).filter(t=>t.endsWith(".run.json")).map(t=>t.replace(".run.json",""))}catch(i){if(i.code==="ENOENT")return [];throw i}}async clearAll(){await this.ensureModules();let i=await this.listRuns();await Promise.all(i.map(t=>this.deleteRunState(t)));}};exports.FileStore=a;//# sourceMappingURL=file.cjs.map
2
- //# sourceMappingURL=file.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/stores/file.ts"],"names":["FileStore","options","runId","state","raw","err","key","value","allData","f","runs"],"mappings":"aAcO,IAAMA,CAAAA,CAAN,KAA4C,CACzC,SAAA,CACA,GAA0C,IAAA,CAC1C,IAAA,CAAqC,KAE7C,WAAA,CAAYC,CAAAA,CAA2B,CACrC,IAAA,CAAK,SAAA,CAAYA,EAAQ,UAC3B,CAEA,MAAc,aAAA,EAA+B,CAAA,CACvC,CAAC,IAAA,CAAK,EAAA,EAAM,CAAC,IAAA,CAAK,IAAA,IAEpB,KAAK,EAAA,CAAK,aAAa,aAAa,CAAA,CACpC,KAAK,IAAA,CAAO,aAAa,MAAM,CAAA,CAG/B,MAAM,IAAA,CAAK,EAAA,CAAG,MAAM,IAAA,CAAK,SAAA,CAAW,CAAE,SAAA,CAAW,IAAK,CAAC,GAE3D,CAEQ,OAAA,CAAQC,EAAuB,CACrC,OAAO,KAAK,IAAA,CAAM,IAAA,CAAK,KAAK,SAAA,CAAW,CAAA,EAAGA,CAAK,CAAA,SAAA,CAAW,CAC5D,CAEQ,QAAA,CAASA,CAAAA,CAAuB,CACtC,OAAO,IAAA,CAAK,KAAM,IAAA,CAAK,IAAA,CAAK,UAAW,CAAA,EAAGA,CAAK,YAAY,CAC7D,CAEA,MAAM,YAAA,CAAaA,CAAAA,CAAeC,EAAwC,CACxE,MAAM,KAAK,aAAA,EAAc,CACzB,MAAM,IAAA,CAAK,EAAA,CAAI,UACb,IAAA,CAAK,OAAA,CAAQD,CAAK,CAAA,CAClB,IAAA,CAAK,SA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/**\n * yaml-flow - File Store\n * \n * File-system based store for Node.js environments.\n * Stores each run as a JSON file in the specified directory.\n */\n\nimport type { StepMachineStore, StepMachineState } from '../step-machine/types.js';\n\nexport interface FileStoreOptions {\n /** Directory path for storing flow data */\n directory: string;\n}\n\nexport class FileStore implements StepMachineStore {\n private directory: string;\n private fs: typeof import('fs/promises') | null = null;\n private path: typeof import('path') | null = null;\n\n constructor(options: FileStoreOptions) {\n this.directory = options.directory;\n }\n\n private async ensureModules(): Promise<void> {\n if (!this.fs || !this.path) {\n // Dynamic import for Node.js modules\n this.fs = await import('fs/promises');\n this.path = await import('path');\n \n // Ensure directory exists\n await this.fs.mkdir(this.directory, { recursive: true });\n }\n }\n\n private runPath(runId: string): string {\n return this.path!.join(this.directory, `${runId}.run.json`);\n }\n\n private dataPath(runId: string): string {\n return this.path!.join(this.directory, `${runId}.data.json`);\n }\n\n async saveRunState(runId: string, state: StepMachineState): Promise<void> {\n await this.ensureModules();\n await this.fs!.writeFile(\n this.runPath(runId),\n JSON.stringify(state, null, 2),\n 'utf-8'\n );\n }\n\n async loadRunState(runId: string): Promise<StepMachineState | null> {\n await this.ensureModules();\n try {\n const raw = await this.fs!.readFile(this.runPath(runId), 'utf-8');\n return JSON.parse(raw);\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return null;\n }\n throw err;\n }\n }\n\n async deleteRunState(runId: string): Promise<void> {\n await this.ensureModules();\n try {\n await this.fs!.unlink(this.runPath(runId));\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n }\n try {\n await this.fs!.unlink(this.dataPath(runId));\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n }\n }\n\n async setData(runId: string, key: string, value: unknown): Promise<void> {\n await this.ensureModules();\n const allData = await this.getAllData(runId);\n allData[key] = value;\n await this.fs!.writeFile(\n this.dataPath(runId),\n JSON.stringify(allData, null, 2),\n 'utf-8'\n );\n }\n\n async getData(runId: string, key: string): Promise<unknown> {\n const allData = await this.getAllData(runId);\n return allData[key];\n }\n\n async getAllData(runId: string): Promise<Record<string, unknown>> {\n await this.ensureModules();\n try {\n const raw = await this.fs!.readFile(this.dataPath(runId), 'utf-8');\n return JSON.parse(raw);\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return {};\n }\n throw err;\n }\n }\n\n async clearData(runId: string): Promise<void> {\n await this.ensureModules();\n try {\n await this.fs!.unlink(this.dataPath(runId));\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n }\n }\n\n async listRuns(): Promise<string[]> {\n await this.ensureModules();\n try {\n const files = await this.fs!.readdir(this.directory);\n return files\n .filter(f => f.endsWith('.run.json'))\n .map(f => f.replace('.run.json', ''));\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return [];\n }\n throw err;\n }\n }\n\n /**\n * Clear all flow data from directory\n */\n async clearAll(): Promise<void> {\n await this.ensureModules();\n const runs = await this.listRuns();\n await Promise.all(runs.map(runId => this.deleteRunState(runId)));\n }\n}\n"]}
@@ -1,36 +0,0 @@
1
- import { l as StepMachineStore, k as StepMachineState } from '../types-ycun84cq.cjs';
2
-
3
- /**
4
- * yaml-flow - File Store
5
- *
6
- * File-system based store for Node.js environments.
7
- * Stores each run as a JSON file in the specified directory.
8
- */
9
-
10
- interface FileStoreOptions {
11
- /** Directory path for storing flow data */
12
- directory: string;
13
- }
14
- declare class FileStore implements StepMachineStore {
15
- private directory;
16
- private fs;
17
- private path;
18
- constructor(options: FileStoreOptions);
19
- private ensureModules;
20
- private runPath;
21
- private dataPath;
22
- saveRunState(runId: string, state: StepMachineState): Promise<void>;
23
- loadRunState(runId: string): Promise<StepMachineState | null>;
24
- deleteRunState(runId: string): Promise<void>;
25
- setData(runId: string, key: string, value: unknown): Promise<void>;
26
- getData(runId: string, key: string): Promise<unknown>;
27
- getAllData(runId: string): Promise<Record<string, unknown>>;
28
- clearData(runId: string): Promise<void>;
29
- listRuns(): Promise<string[]>;
30
- /**
31
- * Clear all flow data from directory
32
- */
33
- clearAll(): Promise<void>;
34
- }
35
-
36
- export { FileStore, type FileStoreOptions };
@@ -1,36 +0,0 @@
1
- import { l as StepMachineStore, k as StepMachineState } from '../types-ycun84cq.js';
2
-
3
- /**
4
- * yaml-flow - File Store
5
- *
6
- * File-system based store for Node.js environments.
7
- * Stores each run as a JSON file in the specified directory.
8
- */
9
-
10
- interface FileStoreOptions {
11
- /** Directory path for storing flow data */
12
- directory: string;
13
- }
14
- declare class FileStore implements StepMachineStore {
15
- private directory;
16
- private fs;
17
- private path;
18
- constructor(options: FileStoreOptions);
19
- private ensureModules;
20
- private runPath;
21
- private dataPath;
22
- saveRunState(runId: string, state: StepMachineState): Promise<void>;
23
- loadRunState(runId: string): Promise<StepMachineState | null>;
24
- deleteRunState(runId: string): Promise<void>;
25
- setData(runId: string, key: string, value: unknown): Promise<void>;
26
- getData(runId: string, key: string): Promise<unknown>;
27
- getAllData(runId: string): Promise<Record<string, unknown>>;
28
- clearData(runId: string): Promise<void>;
29
- listRuns(): Promise<string[]>;
30
- /**
31
- * Clear all flow data from directory
32
- */
33
- clearAll(): Promise<void>;
34
- }
35
-
36
- export { FileStore, type FileStoreOptions };
@@ -1,2 +0,0 @@
1
- var a=class{directory;fs=null;path=null;constructor(i){this.directory=i.directory;}async ensureModules(){(!this.fs||!this.path)&&(this.fs=await import('fs/promises'),this.path=await import('path'),await this.fs.mkdir(this.directory,{recursive:true}));}runPath(i){return this.path.join(this.directory,`${i}.run.json`)}dataPath(i){return this.path.join(this.directory,`${i}.data.json`)}async saveRunState(i,t){await this.ensureModules(),await this.fs.writeFile(this.runPath(i),JSON.stringify(t,null,2),"utf-8");}async loadRunState(i){await this.ensureModules();try{let t=await this.fs.readFile(this.runPath(i),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}async deleteRunState(i){await this.ensureModules();try{await this.fs.unlink(this.runPath(i));}catch(t){if(t.code!=="ENOENT")throw t}try{await this.fs.unlink(this.dataPath(i));}catch(t){if(t.code!=="ENOENT")throw t}}async setData(i,t,r){await this.ensureModules();let e=await this.getAllData(i);e[t]=r,await this.fs.writeFile(this.dataPath(i),JSON.stringify(e,null,2),"utf-8");}async getData(i,t){return (await this.getAllData(i))[t]}async getAllData(i){await this.ensureModules();try{let t=await this.fs.readFile(this.dataPath(i),"utf-8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return {};throw t}}async clearData(i){await this.ensureModules();try{await this.fs.unlink(this.dataPath(i));}catch(t){if(t.code!=="ENOENT")throw t}}async listRuns(){await this.ensureModules();try{return (await this.fs.readdir(this.directory)).filter(t=>t.endsWith(".run.json")).map(t=>t.replace(".run.json",""))}catch(i){if(i.code==="ENOENT")return [];throw i}}async clearAll(){await this.ensureModules();let i=await this.listRuns();await Promise.all(i.map(t=>this.deleteRunState(t)));}};export{a as FileStore};//# sourceMappingURL=file.js.map
2
- //# sourceMappingURL=file.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/stores/file.ts"],"names":["FileStore","options","runId","state","raw","err","key","value","allData","f","runs"],"mappings":"AAcO,IAAMA,CAAAA,CAAN,KAA4C,CACzC,SAAA,CACA,GAA0C,IAAA,CAC1C,IAAA,CAAqC,KAE7C,WAAA,CAAYC,CAAAA,CAA2B,CACrC,IAAA,CAAK,SAAA,CAAYA,EAAQ,UAC3B,CAEA,MAAc,aAAA,EAA+B,CAAA,CACvC,CAAC,IAAA,CAAK,EAAA,EAAM,CAAC,IAAA,CAAK,IAAA,IAEpB,KAAK,EAAA,CAAK,aAAa,aAAa,CAAA,CACpC,KAAK,IAAA,CAAO,aAAa,MAAM,CAAA,CAG/B,MAAM,IAAA,CAAK,EAAA,CAAG,MAAM,IAAA,CAAK,SAAA,CAAW,CAAE,SAAA,CAAW,IAAK,CAAC,GAE3D,CAEQ,OAAA,CAAQC,EAAuB,CACrC,O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CAAAA,EAAKA,CAAAA,CAAE,QAAQ,WAAA,CAAa,EAAE,CAAC,CACxC,CAAA,MAASJ,EAAc,CACrB,GAAKA,EAA8B,IAAA,GAAS,QAAA,CAC1C,OAAO,EAAC,CAEV,MAAMA,CACR,CACF,CAKA,MAAM,QAAA,EAA0B,CAC9B,MAAM,IAAA,CAAK,eAAc,CACzB,IAAMK,EAAO,MAAM,IAAA,CAAK,UAAS,CACjC,MAAM,QAAQ,GAAA,CAAIA,CAAAA,CAAK,IAAIR,CAAAA,EAAS,IAAA,CAAK,eAAeA,CAAK,CAAC,CAAC,EACjE,CACF","file":"file.js","sourcesContent":["/**\n * yaml-flow - File Store\n * \n * File-system based store for Node.js environments.\n * Stores each run as a JSON file in the specified directory.\n */\n\nimport type { StepMachineStore, StepMachineState } from '../step-machine/types.js';\n\nexport interface FileStoreOptions {\n /** Directory path for storing flow data */\n directory: string;\n}\n\nexport class FileStore implements StepMachineStore {\n private directory: string;\n private fs: typeof import('fs/promises') | null = null;\n private path: typeof import('path') | null = null;\n\n constructor(options: FileStoreOptions) {\n this.directory = options.directory;\n }\n\n private async ensureModules(): Promise<void> {\n if (!this.fs || !this.path) {\n // Dynamic import for Node.js modules\n this.fs = await import('fs/promises');\n this.path = await import('path');\n \n // Ensure directory exists\n await this.fs.mkdir(this.directory, { recursive: true });\n }\n }\n\n private runPath(runId: string): string {\n return this.path!.join(this.directory, `${runId}.run.json`);\n }\n\n private dataPath(runId: string): string {\n return this.path!.join(this.directory, `${runId}.data.json`);\n }\n\n async saveRunState(runId: string, state: StepMachineState): Promise<void> {\n await this.ensureModules();\n await this.fs!.writeFile(\n this.runPath(runId),\n JSON.stringify(state, null, 2),\n 'utf-8'\n );\n }\n\n async loadRunState(runId: string): Promise<StepMachineState | null> {\n await this.ensureModules();\n try {\n const raw = await this.fs!.readFile(this.runPath(runId), 'utf-8');\n return JSON.parse(raw);\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return null;\n }\n throw err;\n }\n }\n\n async deleteRunState(runId: string): Promise<void> {\n await this.ensureModules();\n try {\n await this.fs!.unlink(this.runPath(runId));\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n }\n try {\n await this.fs!.unlink(this.dataPath(runId));\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n }\n }\n\n async setData(runId: string, key: string, value: unknown): Promise<void> {\n await this.ensureModules();\n const allData = await this.getAllData(runId);\n allData[key] = value;\n await this.fs!.writeFile(\n this.dataPath(runId),\n JSON.stringify(allData, null, 2),\n 'utf-8'\n );\n }\n\n async getData(runId: string, key: string): Promise<unknown> {\n const allData = await this.getAllData(runId);\n return allData[key];\n }\n\n async getAllData(runId: string): Promise<Record<string, unknown>> {\n await this.ensureModules();\n try {\n const raw = await this.fs!.readFile(this.dataPath(runId), 'utf-8');\n return JSON.parse(raw);\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return {};\n }\n throw err;\n }\n }\n\n async clearData(runId: string): Promise<void> {\n await this.ensureModules();\n try {\n await this.fs!.unlink(this.dataPath(runId));\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n }\n }\n\n async listRuns(): Promise<string[]> {\n await this.ensureModules();\n try {\n const files = await this.fs!.readdir(this.directory);\n return files\n .filter(f => f.endsWith('.run.json'))\n .map(f => f.replace('.run.json', ''));\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return [];\n }\n throw err;\n }\n }\n\n /**\n * Clear all flow data from directory\n */\n async clearAll(): Promise<void> {\n await this.ensureModules();\n const runs = await this.listRuns();\n await Promise.all(runs.map(runId => this.deleteRunState(runId)));\n }\n}\n"]}
@@ -1,2 +0,0 @@
1
- 'use strict';var i=class{runs=new Map;data=new Map;async saveRunState(t,e){this.runs.set(t,{...e});}async loadRunState(t){let e=this.runs.get(t);return e?{...e}:null}async deleteRunState(t){this.runs.delete(t),this.data.delete(t);}async setData(t,e,a){this.data.has(t)||this.data.set(t,{});let r=this.data.get(t);r[e]=a;}async getData(t,e){return this.data.get(t)?.[e]}async getAllData(t){return {...this.data.get(t)??{}}}async clearData(t){this.data.delete(t);}async listRuns(){return Array.from(this.runs.keys())}clear(){this.runs.clear(),this.data.clear();}};var s=class{prefix;constructor(t={}){if(this.prefix=t.prefix??"yamlflow",typeof localStorage>"u")throw new Error("LocalStorageStore requires localStorage (browser environment)")}runKey(t){return `${this.prefix}:run:${t}`}dataKey(t){return `${this.prefix}:data:${t}`}indexKey(){return `${this.prefix}:runs`}async saveRunState(t,e){localStorage.setItem(this.runKey(t),JSON.stringify(e));let a=await this.listRuns();a.includes(t)||(a.push(t),localStorage.setItem(this.indexKey(),JSON.stringify(a)));}async loadRunState(t){let e=localStorage.getItem(this.runKey(t));return e?JSON.parse(e):null}async deleteRunState(t){localStorage.removeItem(this.runKey(t)),localStorage.removeItem(this.dataKey(t));let a=(await this.listRuns()).filter(r=>r!==t);localStorage.setItem(this.indexKey(),JSON.stringify(a));}async setData(t,e,a){let r=await this.getAllData(t);r[e]=a,localStorage.setItem(this.dataKey(t),JSON.stringify(r));}async getData(t,e){return (await this.getAllData(t))[e]}async getAllData(t){let e=localStorage.getItem(this.dataKey(t));return e?JSON.parse(e):{}}async clearData(t){localStorage.removeItem(this.dataKey(t));}async listRuns(){let t=localStorage.getItem(this.indexKey());return t?JSON.parse(t):[]}clearAll(){let t=[];for(let e=0;e<localStorage.length;e++){let a=localStorage.key(e);a?.startsWith(this.prefix+":")&&t.push(a);}t.forEach(e=>localStorage.removeItem(e));}};var n=class{directory;fs=null;path=null;constructor(t){this.directory=t.directory;}async ensureModules(){(!this.fs||!this.path)&&(this.fs=await import('fs/promises'),this.path=await import('path'),await this.fs.mkdir(this.directory,{recursive:true}));}runPath(t){return this.path.join(this.directory,`${t}.run.json`)}dataPath(t){return this.path.join(this.directory,`${t}.data.json`)}async saveRunState(t,e){await this.ensureModules(),await this.fs.writeFile(this.runPath(t),JSON.stringify(e,null,2),"utf-8");}async loadRunState(t){await this.ensureModules();try{let e=await this.fs.readFile(this.runPath(t),"utf-8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async deleteRunState(t){await this.ensureModules();try{await this.fs.unlink(this.runPath(t));}catch(e){if(e.code!=="ENOENT")throw e}try{await this.fs.unlink(this.dataPath(t));}catch(e){if(e.code!=="ENOENT")throw e}}async setData(t,e,a){await this.ensureModules();let r=await this.getAllData(t);r[e]=a,await this.fs.writeFile(this.dataPath(t),JSON.stringify(r,null,2),"utf-8");}async getData(t,e){return (await this.getAllData(t))[e]}async getAllData(t){await this.ensureModules();try{let e=await this.fs.readFile(this.dataPath(t),"utf-8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return {};throw e}}async clearData(t){await this.ensureModules();try{await this.fs.unlink(this.dataPath(t));}catch(e){if(e.code!=="ENOENT")throw e}}async listRuns(){await this.ensureModules();try{return (await this.fs.readdir(this.directory)).filter(e=>e.endsWith(".run.json")).map(e=>e.replace(".run.json",""))}catch(t){if(t.code==="ENOENT")return [];throw t}}async clearAll(){await this.ensureModules();let t=await this.listRuns();await Promise.all(t.map(e=>this.deleteRunState(e)));}};exports.FileStore=n;exports.LocalStorageStore=s;exports.MemoryStore=i;//# sourceMappingURL=index.cjs.map
2
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/stores/memory.ts","../../src/stores/localStorage.ts","../../src/stores/file.ts"],"names":["MemoryStore","runId","state","key","value","runData","LocalStorageStore","options","runs","raw","filtered","id","allData","keysToRemove","i","FileStore","err","f"],"mappings":"aASO,IAAMA,CAAAA,CAAN,KAA8C,CAC3C,IAAA,CAAsC,IAAI,GAAA,CAC1C,IAAA,CAA6C,IAAI,GAAA,CAEzD,MAAM,YAAA,CAAaC,EAAeC,CAAAA,CAAwC,CACxE,KAAK,IAAA,CAAK,GAAA,CAAID,E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","sourcesContent":["/**\n * yaml-flow - Memory Store\n * \n * In-memory store implementation. Works in both browser and Node.js.\n * Data is lost when the process exits - use for testing or short-lived flows.\n */\n\nimport type { StepMachineStore, StepMachineState } from '../step-machine/types.js';\n\nexport class MemoryStore implements StepMachineStore {\n private runs: Map<string, StepMachineState> = new Map();\n private data: Map<string, Record<string, unknown>> = new Map();\n\n async saveRunState(runId: string, state: StepMachineState): Promise<void> {\n this.runs.set(runId, { ...state });\n }\n\n async loadRunState(runId: string): Promise<StepMachineState | null> {\n const state = this.runs.get(runId);\n return state ? { ...state } : null;\n }\n\n async deleteRunState(runId: string): Promise<void> {\n this.runs.delete(runId);\n this.data.delete(runId);\n }\n\n async setData(runId: string, key: string, value: unknown): Promise<void> {\n if (!this.data.has(runId)) {\n this.data.set(runId, {});\n }\n const runData = this.data.get(runId)!;\n runData[key] = value;\n }\n\n async getData(runId: string, key: string): Promise<unknown> {\n return this.data.get(runId)?.[key];\n }\n\n async getAllData(runId: string): Promise<Record<string, unknown>> {\n return { ...(this.data.get(runId) ?? {}) };\n }\n\n async clearData(runId: string): Promise<void> {\n this.data.delete(runId);\n }\n\n async listRuns(): Promise<string[]> {\n return Array.from(this.runs.keys());\n }\n\n /**\n * Clear all data (useful for testing)\n */\n clear(): void {\n this.runs.clear();\n this.data.clear();\n }\n}\n","/**\n * yaml-flow - LocalStorage Store\n * \n * Browser localStorage-based store implementation.\n * Data persists across page reloads but is limited to ~5MB per origin.\n */\n\nimport type { StepMachineStore, StepMachineState } from '../step-machine/types.js';\n\nexport interface LocalStorageStoreOptions {\n /** Key prefix for namespacing (default: 'yamlflow') */\n prefix?: string;\n}\n\nexport class LocalStorageStore implements StepMachineStore {\n private prefix: string;\n\n constructor(options: LocalStorageStoreOptions = {}) {\n this.prefix = options.prefix ?? 'yamlflow';\n \n // Ensure localStorage is available\n if (typeof localStorage === 'undefined') {\n throw new Error('LocalStorageStore requires localStorage (browser environment)');\n }\n }\n\n private runKey(runId: string): string {\n return `${this.prefix}:run:${runId}`;\n }\n\n private dataKey(runId: string): string {\n return `${this.prefix}:data:${runId}`;\n }\n\n private indexKey(): string {\n return `${this.prefix}:runs`;\n }\n\n async saveRunState(runId: string, state: StepMachineState): Promise<void> {\n localStorage.setItem(this.runKey(runId), JSON.stringify(state));\n \n // Update run index\n const runs = await this.listRuns();\n if (!runs.includes(runId)) {\n runs.push(runId);\n localStorage.setItem(this.indexKey(), JSON.stringify(runs));\n }\n }\n\n async loadRunState(runId: string): Promise<StepMachineState | null> {\n const raw = localStorage.getItem(this.runKey(runId));\n return raw ? JSON.parse(raw) : null;\n }\n\n async deleteRunState(runId: string): Promise<void> {\n localStorage.removeItem(this.runKey(runId));\n localStorage.removeItem(this.dataKey(runId));\n \n // Update run index\n const runs = await this.listRuns();\n const filtered = runs.filter(id => id !== runId);\n localStorage.setItem(this.indexKey(), JSON.stringify(filtered));\n }\n\n async setData(runId: string, key: string, value: unknown): Promise<void> {\n const allData = await this.getAllData(runId);\n allData[key] = value;\n localStorage.setItem(this.dataKey(runId), JSON.stringify(allData));\n }\n\n async getData(runId: string, key: string): Promise<unknown> {\n const allData = await this.getAllData(runId);\n return allData[key];\n }\n\n async getAllData(runId: string): Promise<Record<string, unknown>> {\n const raw = localStorage.getItem(this.dataKey(runId));\n return raw ? JSON.parse(raw) : {};\n }\n\n async clearData(runId: string): Promise<void> {\n localStorage.removeItem(this.dataKey(runId));\n }\n\n async listRuns(): Promise<string[]> {\n const raw = localStorage.getItem(this.indexKey());\n return raw ? JSON.parse(raw) : [];\n }\n\n /**\n * Clear all flow data from localStorage\n */\n clearAll(): void {\n const keysToRemove: string[] = [];\n \n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (key?.startsWith(this.prefix + ':')) {\n keysToRemove.push(key);\n }\n }\n \n keysToRemove.forEach(key => localStorage.removeItem(key));\n }\n}\n","/**\n * yaml-flow - File Store\n * \n * File-system based store for Node.js environments.\n * Stores each run as a JSON file in the specified directory.\n */\n\nimport type { StepMachineStore, StepMachineState } from '../step-machine/types.js';\n\nexport interface FileStoreOptions {\n /** Directory path for storing flow data */\n directory: string;\n}\n\nexport class FileStore implements StepMachineStore {\n private directory: string;\n private fs: typeof import('fs/promises') | null = null;\n private path: typeof import('path') | null = null;\n\n constructor(options: FileStoreOptions) {\n this.directory = options.directory;\n }\n\n private async ensureModules(): Promise<void> {\n if (!this.fs || !this.path) {\n // Dynamic import for Node.js modules\n this.fs = await import('fs/promises');\n this.path = await import('path');\n \n // Ensure directory exists\n await this.fs.mkdir(this.directory, { recursive: true });\n }\n }\n\n private runPath(runId: string): string {\n return this.path!.join(this.directory, `${runId}.run.json`);\n }\n\n private dataPath(runId: string): string {\n return this.path!.join(this.directory, `${runId}.data.json`);\n }\n\n async saveRunState(runId: string, state: StepMachineState): Promise<void> {\n await this.ensureModules();\n await this.fs!.writeFile(\n this.runPath(runId),\n JSON.stringify(state, null, 2),\n 'utf-8'\n );\n }\n\n async loadRunState(runId: string): Promise<StepMachineState | null> {\n await this.ensureModules();\n try {\n const raw = await this.fs!.readFile(this.runPath(runId), 'utf-8');\n return JSON.parse(raw);\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return null;\n }\n throw err;\n }\n }\n\n async deleteRunState(runId: string): Promise<void> {\n await this.ensureModules();\n try {\n await this.fs!.unlink(this.runPath(runId));\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n }\n try {\n await this.fs!.unlink(this.dataPath(runId));\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n }\n }\n\n async setData(runId: string, key: string, value: unknown): Promise<void> {\n await this.ensureModules();\n const allData = await this.getAllData(runId);\n allData[key] = value;\n await this.fs!.writeFile(\n this.dataPath(runId),\n JSON.stringify(allData, null, 2),\n 'utf-8'\n );\n }\n\n async getData(runId: string, key: string): Promise<unknown> {\n const allData = await this.getAllData(runId);\n return allData[key];\n }\n\n async getAllData(runId: string): Promise<Record<string, unknown>> {\n await this.ensureModules();\n try {\n const raw = await this.fs!.readFile(this.dataPath(runId), 'utf-8');\n return JSON.parse(raw);\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return {};\n }\n throw err;\n }\n }\n\n async clearData(runId: string): Promise<void> {\n await this.ensureModules();\n try {\n await this.fs!.unlink(this.dataPath(runId));\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n }\n }\n\n async listRuns(): Promise<string[]> {\n await this.ensureModules();\n try {\n const files = await this.fs!.readdir(this.directory);\n return files\n .filter(f => f.endsWith('.run.json'))\n .map(f => f.replace('.run.json', ''));\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return [];\n }\n throw err;\n }\n }\n\n /**\n * Clear all flow data from directory\n */\n async clearAll(): Promise<void> {\n await this.ensureModules();\n const runs = await this.listRuns();\n await Promise.all(runs.map(runId => this.deleteRunState(runId)));\n }\n}\n"]}
@@ -1,4 +0,0 @@
1
- export { MemoryStore } from './memory.cjs';
2
- export { LocalStorageStore } from './localStorage.cjs';
3
- export { FileStore } from './file.cjs';
4
- import '../types-ycun84cq.cjs';
@@ -1,4 +0,0 @@
1
- export { MemoryStore } from './memory.js';
2
- export { LocalStorageStore } from './localStorage.js';
3
- export { FileStore } from './file.js';
4
- import '../types-ycun84cq.js';
@@ -1,2 +0,0 @@
1
- var i=class{runs=new Map;data=new Map;async saveRunState(t,e){this.runs.set(t,{...e});}async loadRunState(t){let e=this.runs.get(t);return e?{...e}:null}async deleteRunState(t){this.runs.delete(t),this.data.delete(t);}async setData(t,e,a){this.data.has(t)||this.data.set(t,{});let r=this.data.get(t);r[e]=a;}async getData(t,e){return this.data.get(t)?.[e]}async getAllData(t){return {...this.data.get(t)??{}}}async clearData(t){this.data.delete(t);}async listRuns(){return Array.from(this.runs.keys())}clear(){this.runs.clear(),this.data.clear();}};var s=class{prefix;constructor(t={}){if(this.prefix=t.prefix??"yamlflow",typeof localStorage>"u")throw new Error("LocalStorageStore requires localStorage (browser environment)")}runKey(t){return `${this.prefix}:run:${t}`}dataKey(t){return `${this.prefix}:data:${t}`}indexKey(){return `${this.prefix}:runs`}async saveRunState(t,e){localStorage.setItem(this.runKey(t),JSON.stringify(e));let a=await this.listRuns();a.includes(t)||(a.push(t),localStorage.setItem(this.indexKey(),JSON.stringify(a)));}async loadRunState(t){let e=localStorage.getItem(this.runKey(t));return e?JSON.parse(e):null}async deleteRunState(t){localStorage.removeItem(this.runKey(t)),localStorage.removeItem(this.dataKey(t));let a=(await this.listRuns()).filter(r=>r!==t);localStorage.setItem(this.indexKey(),JSON.stringify(a));}async setData(t,e,a){let r=await this.getAllData(t);r[e]=a,localStorage.setItem(this.dataKey(t),JSON.stringify(r));}async getData(t,e){return (await this.getAllData(t))[e]}async getAllData(t){let e=localStorage.getItem(this.dataKey(t));return e?JSON.parse(e):{}}async clearData(t){localStorage.removeItem(this.dataKey(t));}async listRuns(){let t=localStorage.getItem(this.indexKey());return t?JSON.parse(t):[]}clearAll(){let t=[];for(let e=0;e<localStorage.length;e++){let a=localStorage.key(e);a?.startsWith(this.prefix+":")&&t.push(a);}t.forEach(e=>localStorage.removeItem(e));}};var n=class{directory;fs=null;path=null;constructor(t){this.directory=t.directory;}async ensureModules(){(!this.fs||!this.path)&&(this.fs=await import('fs/promises'),this.path=await import('path'),await this.fs.mkdir(this.directory,{recursive:true}));}runPath(t){return this.path.join(this.directory,`${t}.run.json`)}dataPath(t){return this.path.join(this.directory,`${t}.data.json`)}async saveRunState(t,e){await this.ensureModules(),await this.fs.writeFile(this.runPath(t),JSON.stringify(e,null,2),"utf-8");}async loadRunState(t){await this.ensureModules();try{let e=await this.fs.readFile(this.runPath(t),"utf-8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async deleteRunState(t){await this.ensureModules();try{await this.fs.unlink(this.runPath(t));}catch(e){if(e.code!=="ENOENT")throw e}try{await this.fs.unlink(this.dataPath(t));}catch(e){if(e.code!=="ENOENT")throw e}}async setData(t,e,a){await this.ensureModules();let r=await this.getAllData(t);r[e]=a,await this.fs.writeFile(this.dataPath(t),JSON.stringify(r,null,2),"utf-8");}async getData(t,e){return (await this.getAllData(t))[e]}async getAllData(t){await this.ensureModules();try{let e=await this.fs.readFile(this.dataPath(t),"utf-8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return {};throw e}}async clearData(t){await this.ensureModules();try{await this.fs.unlink(this.dataPath(t));}catch(e){if(e.code!=="ENOENT")throw e}}async listRuns(){await this.ensureModules();try{return (await this.fs.readdir(this.directory)).filter(e=>e.endsWith(".run.json")).map(e=>e.replace(".run.json",""))}catch(t){if(t.code==="ENOENT")return [];throw t}}async clearAll(){await this.ensureModules();let t=await this.listRuns();await Promise.all(t.map(e=>this.deleteRunState(e)));}};export{n as FileStore,s as LocalStorageStore,i as MemoryStore};//# sourceMappingURL=index.js.map
2
- //# sourceMappingURL=index.js.map