yaml-flow 6.0.0 → 7.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 (162) hide show
  1. package/board-live-cards-cli.js +4 -4
  2. package/browser/asset-integrity.json +3 -3
  3. package/browser/board-livecards-client.js +2 -0
  4. package/browser/board-livecards-client.js.map +1 -0
  5. package/browser/board-livecards-localstorage.js +10 -0
  6. package/browser/board-livecards-localstorage.js.map +1 -0
  7. package/browser/board-livegraph-engine.js +2 -2
  8. package/browser/board-livegraph-engine.js.map +1 -1
  9. package/browser/card-compute.js +28 -28
  10. package/browser/compute-jsonata.js +5 -0
  11. package/browser/compute-jsonata.js.map +1 -0
  12. package/browser/live-cards.js +261 -150
  13. package/card-store.js +4 -4
  14. package/dist/{board-live-cards-public-CltXYgaY.d.cts → board-live-cards-public-CW5074xr.d.cts} +9 -5
  15. package/dist/{board-live-cards-public-f-E-FAyp.d.ts → board-live-cards-public-hnZo0mAf.d.ts} +9 -5
  16. package/dist/board-livegraph-runtime/index.cjs +2 -2
  17. package/dist/board-livegraph-runtime/index.cjs.map +1 -1
  18. package/dist/board-livegraph-runtime/index.d.cts +11 -9
  19. package/dist/board-livegraph-runtime/index.d.ts +11 -9
  20. package/dist/board-livegraph-runtime/index.js +2 -2
  21. package/dist/board-livegraph-runtime/index.js.map +1 -1
  22. package/dist/board-livegraph-runtime/jsonata-sync.cjs +37 -1
  23. package/dist/card-compute/index.cjs +4 -4
  24. package/dist/card-compute/index.cjs.map +1 -1
  25. package/dist/card-compute/index.d.cts +5 -1
  26. package/dist/card-compute/index.d.ts +5 -1
  27. package/dist/card-compute/index.js +4 -4
  28. package/dist/card-compute/index.js.map +1 -1
  29. package/dist/card-compute/jsonata-sync.cjs +37 -1
  30. package/dist/cli/browser-api/board-live-cards-browser-adapter.cjs +2 -1
  31. package/dist/cli/browser-api/board-live-cards-browser-adapter.cjs.map +1 -1
  32. package/dist/cli/browser-api/board-live-cards-browser-adapter.d.cts +27 -14
  33. package/dist/cli/browser-api/board-live-cards-browser-adapter.d.ts +27 -14
  34. package/dist/cli/browser-api/board-live-cards-browser-adapter.js +2 -1
  35. package/dist/cli/browser-api/board-live-cards-browser-adapter.js.map +1 -1
  36. package/dist/cli/browser-api/card-store-browser-api.cjs +1 -1
  37. package/dist/cli/browser-api/card-store-browser-api.cjs.map +1 -1
  38. package/dist/cli/browser-api/card-store-browser-api.js +1 -1
  39. package/dist/cli/browser-api/card-store-browser-api.js.map +1 -1
  40. package/dist/cli/browser-api/jsonata-sync.cjs +37 -1
  41. package/dist/cli/node/artifacts-store-cli.cjs +8 -8
  42. package/dist/cli/node/artifacts-store-cli.cjs.map +1 -1
  43. package/dist/cli/node/artifacts-store-cli.js +8 -8
  44. package/dist/cli/node/artifacts-store-cli.js.map +1 -1
  45. package/dist/cli/node/board-live-cards-cli.cjs +7 -7
  46. package/dist/cli/node/board-live-cards-cli.cjs.map +1 -1
  47. package/dist/cli/node/board-live-cards-cli.js +7 -7
  48. package/dist/cli/node/board-live-cards-cli.js.map +1 -1
  49. package/dist/cli/node/card-store-cli.cjs +5 -5
  50. package/dist/cli/node/card-store-cli.cjs.map +1 -1
  51. package/dist/cli/node/card-store-cli.js +5 -5
  52. package/dist/cli/node/card-store-cli.js.map +1 -1
  53. package/dist/cli/node/execution-adapter.cjs +3 -0
  54. package/dist/cli/node/execution-adapter.cjs.map +1 -0
  55. package/dist/cli/node/execution-adapter.d.cts +174 -0
  56. package/dist/cli/node/execution-adapter.d.ts +174 -0
  57. package/dist/cli/node/execution-adapter.js +3 -0
  58. package/dist/cli/node/execution-adapter.js.map +1 -0
  59. package/dist/cli/node/fs-board-adapter.cjs +7 -7
  60. package/dist/cli/node/fs-board-adapter.cjs.map +1 -1
  61. package/dist/cli/node/fs-board-adapter.d.cts +2 -2
  62. package/dist/cli/node/fs-board-adapter.d.ts +2 -2
  63. package/dist/cli/node/fs-board-adapter.js +7 -7
  64. package/dist/cli/node/fs-board-adapter.js.map +1 -1
  65. package/dist/cli/node/jsonata-sync.cjs +37 -1
  66. package/dist/cli/node/source-cli-task-executor.cjs +4 -4
  67. package/dist/cli/node/source-cli-task-executor.cjs.map +1 -1
  68. package/dist/cli/node/source-cli-task-executor.js +4 -4
  69. package/dist/cli/node/source-cli-task-executor.js.map +1 -1
  70. package/dist/continuous-event-graph/index.cjs +2 -2
  71. package/dist/continuous-event-graph/index.cjs.map +1 -1
  72. package/dist/continuous-event-graph/index.js +2 -2
  73. package/dist/continuous-event-graph/index.js.map +1 -1
  74. package/dist/continuous-event-graph/jsonata-sync.cjs +37 -1
  75. package/dist/execution-refs.cjs +2 -1
  76. package/dist/execution-refs.cjs.map +1 -1
  77. package/dist/execution-refs.d.cts +49 -11
  78. package/dist/execution-refs.d.ts +49 -11
  79. package/dist/execution-refs.js +2 -1
  80. package/dist/execution-refs.js.map +1 -1
  81. package/dist/index.cjs +10 -10
  82. package/dist/index.cjs.map +1 -1
  83. package/dist/index.js +10 -10
  84. package/dist/index.js.map +1 -1
  85. package/dist/jsonata-sync.cjs +37 -1
  86. package/dist/server-runtime/index.cjs +9 -0
  87. package/dist/server-runtime/index.cjs.map +1 -0
  88. package/dist/server-runtime/index.d.cts +31 -0
  89. package/dist/server-runtime/index.d.ts +31 -0
  90. package/dist/server-runtime/index.js +9 -0
  91. package/dist/server-runtime/index.js.map +1 -0
  92. package/dist/server-runtime/jsonata-sync.cjs +7623 -0
  93. package/dist/step-machine-public/index.cjs +2 -0
  94. package/dist/step-machine-public/index.cjs.map +1 -0
  95. package/dist/step-machine-public/index.d.cts +159 -0
  96. package/dist/step-machine-public/index.d.ts +159 -0
  97. package/dist/step-machine-public/index.js +2 -0
  98. package/dist/step-machine-public/index.js.map +1 -0
  99. package/dist/step-machine-public/jsonata-sync.cjs +7623 -0
  100. package/dist/storage-refs.cjs +2 -2
  101. package/dist/storage-refs.cjs.map +1 -1
  102. package/dist/storage-refs.d.cts +7 -6
  103. package/dist/storage-refs.d.ts +7 -6
  104. package/dist/storage-refs.js +2 -2
  105. package/dist/storage-refs.js.map +1 -1
  106. package/dist/types-B1ZRa4aI.d.ts +147 -0
  107. package/dist/types-BxEFcVK9.d.cts +147 -0
  108. package/examples/browser/boards/portfolio-tracker/portfolio-t4.js +9 -10
  109. package/examples/browser/boards/portfolio-tracker/portfolio-tracker-http-test.js +357 -0
  110. package/examples/browser/boards/portfolio-tracker/portfolio-tracker-public.js +9 -10
  111. package/examples/browser/boards/portfolio-tracker/portfolio-tracker-server.js +300 -0
  112. package/examples/browser/boards/portfolio-tracker/portfolio-tracker-server.py +617 -0
  113. package/examples/browser/boards/portfolio-tracker/portfolio-tracker-sse-worker.js +48 -0
  114. package/examples/browser/boards/portfolio-tracker/portfolio-tracker.py +11 -10
  115. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/_board-cli.js +19 -4
  116. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/add-cards-cli.js +4 -8
  117. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/init-board-cli.js +6 -10
  118. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/poll-status-cli.js +8 -16
  119. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/reset-board-dir-cli.js +2 -6
  120. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/retrigger-cli.js +4 -8
  121. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/status-cli.js +3 -7
  122. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/update-holdings-cli.js +4 -8
  123. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/wait-completed-cli.js +7 -16
  124. package/examples/cli/step-machine-cli/portfolio-tracker/handlers/write-prices-cli.js +2 -6
  125. package/examples/cli/step-machine-cli/portfolio-tracker/handlers-py/_board_pycli.py +13 -3
  126. package/examples/cli/step-machine-cli/portfolio-tracker/handlers-py/add-cards.py +2 -1
  127. package/examples/cli/step-machine-cli/portfolio-tracker/handlers-py/init-board.py +2 -1
  128. package/examples/cli/step-machine-cli/portfolio-tracker/handlers-py/poll-status.py +2 -1
  129. package/examples/cli/step-machine-cli/portfolio-tracker/portfolio-tracker.flow.yaml +20 -24
  130. package/examples/cli/step-machine-cli/portfolio-tracker/run-inline-python-demo-pycli.py +0 -3
  131. package/examples/cli/step-machine-demo/jsonata-init-board-cli.js +8 -13
  132. package/examples/cli/step-machine-demo/jsonata-init-board.flow.yaml +33 -9
  133. package/examples/cli/step-machine-demo/one-step-cli-only.flow.yaml +3 -1
  134. package/examples/cli/step-machine-demo/step2-double-cli.js +6 -12
  135. package/examples/cli/step-machine-demo/two-step-math.flow.yaml +66 -4
  136. package/examples/cli/step-machine-demo/two-step-mixed.flow.yaml +13 -5
  137. package/examples/example-board/cards/_index.json +47 -0
  138. package/examples/example-board/cards/card-market-prices.json +33 -9
  139. package/examples/example-board/cards/card-my-identity.json +30 -6
  140. package/examples/example-board/cards/card-portfolio-action.json +24 -6
  141. package/examples/example-board/cards/card-portfolio-intelligence.json +97 -0
  142. package/examples/example-board/cards/card-portfolio-risks.json +24 -6
  143. package/examples/example-board/cards/card-portfolio-value.json +38 -10
  144. package/examples/example-board/cards/card-portfolio.json +57 -13
  145. package/examples/example-board/cards/card-rebalance-impact.json +22 -6
  146. package/examples/example-board/cards/card-rebalance-sim.json +66 -15
  147. package/examples/example-board/demo-server.js +360 -69
  148. package/examples/example-board/demo-shell-localstorage.html +774 -0
  149. package/examples/example-board/demo-shell-with-server.html +18 -36
  150. package/examples/example-board/demo-shell.html +5 -4
  151. package/examples/example-board/demo-task-executor.js +217 -265
  152. package/package.json +15 -13
  153. package/step-machine-cli.js +43 -310
  154. package/board-livecards-server-runtime.js +0 -1513
  155. package/browser/board-livecards-runtime-client.js +0 -263
  156. package/dist/pycli/quickjs-board-runtime.global.js +0 -9
  157. package/dist/pycli/quickjs-board-runtime.global.js.map +0 -1
  158. package/dist/pycli/quickjs-step-machine-runtime.global.js +0 -5
  159. package/dist/pycli/quickjs-step-machine-runtime.global.js.map +0 -1
  160. package/examples/cli/step-machine-demo/two-step-math-handlers.js +0 -32
  161. package/examples/cli/step-machine-demo/two-step-mixed-handlers.js +0 -24
  162. package/examples/example-board/demo-shell-browser.html +0 -675
@@ -0,0 +1,2 @@
1
+ 'use strict';var module$1=require('module');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;var $=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))),d=$("./jsonata-sync.cjs");function y(r,e){if(!r||typeof r!="object")throw new Error(`[step-machine-public] Step "${e}" returned a non-object result.`);let o=r,n=o.result??o.status;if(typeof n=="string"&&n.trim().length>0){let s=o.data&&typeof o.data=="object"&&!Array.isArray(o.data)?{...o.data}:{},a=typeof o.error=="string"?o.error:void 0;return a&&!("error"in s)&&(s.error=a),{result:n,data:s,...a?{error:a}:{}}}return {result:"success",data:{...o}}}function w(r,e){if(!e||e.length===0)return r;let o={};for(let n of e)Object.prototype.hasOwnProperty.call(r,n)&&(o[n]=r[n]);return o}function g(r,e){return async(o,n)=>{let s=await r(o,n),a=y(s,n?.stepName??"unknown");return {result:a.result,data:w(a.data,e),...a.error?{error:a.error}:{}}}}function S(r,e,o){if(!e||e.length===0)return null;for(let n of e)try{if(!d(n).evaluate(r))return {result:"failure",data:{error:`[${o}] input validation failed: ${n}`}}}catch(s){let a=s instanceof Error?s.message:String(s);return {result:"failure",data:{error:`[${o}] input validation error on "${n}": ${a}`}}}return null}function m(r,e,o){return !e||e.length===0?r:async(n,s)=>{let a=S(n,e,o);return a||r(n,s)}}var R=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 R("./jsonata-sync.cjs")}catch{return R("../../card-compute/jsonata-sync.cjs")}}var f=O();function x(r,e,o){if(!r||typeof r!="object")return e;let n={output:e},s=e.result,a=e.data,i=e.error;if(typeof r.resultExpr=="string")try{let t=f(r.resultExpr).evaluate(n);if(typeof t!="string"||!t.trim())throw new Error(`resultExpr did not produce a non-empty string (got ${JSON.stringify(t)})`);s=t;}catch(t){let u=t instanceof Error?t.message:String(t);throw new Error(`[${o}] outputTransforms.resultExpr failed: ${u}`)}if(typeof r.dataTemplate=="string")try{let t=f(r.dataTemplate).evaluate(n);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`dataTemplate did not produce an object (got ${JSON.stringify(t)})`);a=t;}catch(t){let u=t instanceof Error?t.message:String(t);throw new Error(`[${o}] outputTransforms.dataTemplate failed: ${u}`)}if(typeof r.errorExpr=="string")try{let t=f(r.errorExpr).evaluate(n);i=t!=null?String(t):void 0;}catch(t){let u=t instanceof Error?t.message:String(t);throw new Error(`[${o}] outputTransforms.errorExpr failed: ${u}`)}return i!==void 0?{result:s,data:a,error:i}:{result:s,data:a}}function h(r){return !!r&&typeof r=="object"&&r.type==="compute-jsonata"&&Array.isArray(r.expr)&&r.expr.length>0}function k(r){if(!r||typeof r!="object")return false;let e=r;return e.type==="ref"&&typeof e.howToRun=="string"&&typeof e.whatToRun=="string"}function F(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 J(r,e,o){let n=e.split("."),s=r;for(let a=0;a<n.length-1;a++){let i=n[a];(s[i]==null||typeof s[i]!="object")&&(s[i]={}),s=s[i];}s[n[n.length-1]]=o;}function H(r,e,o){let n=r.expr.map(F);return async s=>{let a=s&&typeof s=="object"&&!Array.isArray(s)?{...s}:{},i={},t={expects_data:a,data:i,...o?{config:o}:{}},u,l;for(let p of n)try{let c=d(p.expr).evaluate(t);if(p.bindTo==="result")u=c!=null?String(c):"success";else if(p.bindTo==="error")l=c!=null?String(c):void 0;else if(p.bindTo.startsWith("data."))J(i,p.bindTo.slice(5),c);else return {result:"failure",data:{},error:`[${e}] invalid bindTo "${p.bindTo}": must be "result", "error", or start with "data."`}}catch(c){let E=c instanceof Error?c.message:String(c);return {result:"failure",data:{},error:`[${e}] compute "${p.bindTo}" failed: ${E}`}}return u===void 0?{result:"failure",data:{},error:`[${e}] compute-jsonata: no "result" binding declared \u2014 add '- result = "success"' to expr`}:l?{result:u,data:i,error:l}:{result:u,data:i}}}function b(r,e,o,n){let{type:s,...a}=r,i=a;return async t=>{let u=t&&typeof t=="object"&&!Array.isArray(t)?{...t}:{};n&&(u.config=n);try{let l=await o(i,u);if(!r.outputTransforms)return l;try{return x(r.outputTransforms,l,e)}catch(p){let c=p instanceof Error?p.message:String(p);return {result:"failure",data:{},error:c}}}catch(l){let p=l instanceof Error?l.message:String(l);return {result:"failure",data:{error:`[step-machine-public] step "${e}" invoke threw: ${p}`}}}}}function j(){return async r=>({result:"success",data:r&&typeof r=="object"&&!Array.isArray(r)?r:{}})}function v(r,e,o){let n=Array.isArray(e?.produces_data)?e?.produces_data:void 0,s=Array.isArray(e?.input_validations)?e?.input_validations:void 0,a=e?.config??void 0,i=e?.handler,t;return h(i)?t=H(i,r,a):k(i)?t=b(i,r,o.invoke,a):t=j(),m(g(t,n),s,r)}function z(r,e){let o={};for(let[n,s]of Object.entries(r.steps??{}))o[n]=v(n,s,e);return o}exports.buildStepHandlersForFlow=z;exports.createComputeJsonataHandler=H;exports.createPassthroughHandler=j;exports.createRefStepHandler=b;exports.filterProducedData=w;exports.isComputeJsonataSpec=h;exports.isRefSpec=k;exports.jsonata=d;exports.normalizeHandlerResult=y;exports.resolveStepHandler=v;exports.runInputValidations=S;exports.wrapWithInputValidations=m;exports.wrapWithOutputFiltering=g;//# sourceMappingURL=index.cjs.map
2
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
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/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","isComputeJsonataSpec","spec","isRefSpec","s","normalizeComputeStep","item","eq","deepSet","path","value","parts","cur","i","k","createComputeJsonataHandler","config","steps","expects_data","transitionResult","transitionError","step","createRefStepHandler","invoke","_t","refOnly","ref","stepInput","createPassthroughHandler","resolveStepHandler","stepConfig","options","inputValidations","base","buildStepHandlersForFlow","flow","handlers"],"mappings":"iIAeA,IAAMA,CAAAA,CAAWC,sBAAAA,CAAc,2PAAe,CAAA,CAMjCC,CAAAA,CAA+CF,CAAAA,CAAS,oBAAoB,ECHlF,SAASG,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACyB,CACzB,GAAI,CAACD,CAAAA,EAAO,OAAOA,CAAAA,EAAQ,QAAA,CACzB,MAAM,IAAI,KAAA,CAAM,CAAA,4BAAA,EAA+BC,CAAQ,CAAA,+BAAA,CAAiC,EAG1F,IAAMC,CAAAA,CAAMF,CAAAA,CACNG,CAAAA,CAAUD,CAAAA,CAAI,MAAA,EAAUA,CAAAA,CAAI,MAAA,CAGlC,GAAI,OAAOC,CAAAA,EAAW,QAAA,EAAYA,CAAAA,CAAO,IAAA,EAAK,CAAE,MAAA,CAAS,CAAA,CAAG,CAC1D,IAAMC,CAAAA,CACJF,CAAAA,CAAI,IAAA,EAAQ,OAAOA,CAAAA,CAAI,IAAA,EAAS,QAAA,EAAY,CAAC,KAAA,CAAM,OAAA,CAAQA,CAAAA,CAAI,IAAI,CAAA,CAC/D,C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ata 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 * 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 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 return (\n s.type === 'ref' &&\n typeof s.howToRun === 'string' &&\n typeof s.whatToRun === 'string'\n );\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 const { type: _t, ...refOnly } = spec;\n const ref = refOnly;\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"]}
@@ -0,0 +1,159 @@
1
+ import { ExecutionRef } from '../execution-refs.cjs';
2
+
3
+ /**
4
+ * step-machine-public — types
5
+ *
6
+ * Platform-free types for the declarative handler model.
7
+ * No Node imports. Safe for any runtime (Node, browser, Python via codegen, etc.).
8
+ */
9
+
10
+ /**
11
+ * The single normalized shape the engine consumes.
12
+ *
13
+ * - `result` drives transitions (e.g. 'success' | 'failure' | 'timeout' | <custom>)
14
+ * - `data` drives produces_data projection into flow context
15
+ * - `error` optional human-readable failure detail
16
+ *
17
+ * Adapters MUST normalize their transport-specific output into this shape
18
+ * before returning. The engine never inspects payload format.
19
+ */
20
+ interface NormalizedHandlerResult {
21
+ result: string;
22
+ data: Record<string, unknown>;
23
+ error?: string;
24
+ }
25
+ /**
26
+ * Pure JSONata compute step.
27
+ * Each `expr` entry is `"<bindTo> = <jsonata-expression>"` or
28
+ * `{ bindTo: "...", expr: "..." }`.
29
+ *
30
+ * Evaluated sequentially against the flat flow context; each binding is added
31
+ * before the next expression is evaluated.
32
+ */
33
+ interface ComputeJsonataSpec {
34
+ type: 'compute-jsonata';
35
+ expr: Array<string | {
36
+ bindTo: string;
37
+ expr: string;
38
+ }>;
39
+ }
40
+ /**
41
+ * External reference step. The handler spec IS an ExecutionRef plus a
42
+ * `type: 'ref'` discriminator.
43
+ *
44
+ * The engine never invokes refs directly — invocation is delegated to an
45
+ * `InvokeFn` adapter (e.g. Node spawn, HTTP, Azure Function).
46
+ */
47
+ interface RefSpec extends ExecutionRef {
48
+ type: 'ref';
49
+ }
50
+ type HandlerSpec = ComputeJsonataSpec | RefSpec;
51
+ /**
52
+ * Single invocation boundary. The framework calls this for every ref step;
53
+ * the adapter (Node spawn / HTTP / Azure Function / etc.) decides how to
54
+ * actually invoke the ref and normalizes the outcome to {result, data, error?}.
55
+ *
56
+ * `args` is the flat flow context for the step. The adapter is responsible
57
+ * for honoring `ref.argsMassaging` (cmdTemplate / urlTemplate / bodyTemplate)
58
+ * before performing the transport.
59
+ *
60
+ * May return synchronously (sync transports) or as a Promise (async transports).
61
+ * The framework awaits regardless.
62
+ */
63
+ type InvokeRefFn = (ref: ExecutionRef, args: Record<string, unknown>) => NormalizedHandlerResult | Promise<NormalizedHandlerResult>;
64
+ /**
65
+ * Handler signature consumed by the existing pure step machine.
66
+ *
67
+ * (Mirrors the StepHandler type in src/step-machine/types.ts but typed in
68
+ * platform-free terms.)
69
+ */
70
+ type StepHandler = (input: Record<string, unknown>, context?: {
71
+ stepName?: string;
72
+ runId?: string;
73
+ }) => Promise<NormalizedHandlerResult>;
74
+ /**
75
+ * The subset of step configuration the handler factory consumes.
76
+ *
77
+ * (We do NOT re-export StepFlowConfig here — that lives in src/step-machine/.
78
+ * This is just the shape the factory needs.)
79
+ */
80
+ interface StepConfigForFactory {
81
+ handler?: HandlerSpec;
82
+ produces_data?: string[];
83
+ input_validations?: string[];
84
+ config?: Record<string, unknown>;
85
+ }
86
+
87
+ /**
88
+ * step-machine-public — handler factory
89
+ *
90
+ * Builds engine-facing StepHandlers from declarative HandlerSpec entries.
91
+ * Pure: no Node imports, no transport. Refs are dispatched through the
92
+ * caller-supplied `InvokeFn`, which is the single boundary between this lib
93
+ * and any transport (Node spawn, HTTP, Azure Function, etc.).
94
+ *
95
+ * Layering:
96
+ *
97
+ * step-machine (pure FSM) — runs handlers, never builds them.
98
+ * step-machine-public (this lib) — declarative spec → StepHandler map.
99
+ * adapter (e.g. node-spawn-invoker) — InvokeFn implementation per transport.
100
+ * step-machine-cli (thin shell) — wires adapter + flow loader + run.
101
+ */
102
+
103
+ declare function isComputeJsonataSpec(spec: unknown): spec is ComputeJsonataSpec;
104
+ declare function isRefSpec(spec: unknown): spec is RefSpec;
105
+ declare function createComputeJsonataHandler(spec: ComputeJsonataSpec, stepName: string, config?: Record<string, unknown>): StepHandler;
106
+ declare function createRefStepHandler(spec: RefSpec, stepName: string, invoke: InvokeRefFn, config?: Record<string, unknown>): StepHandler;
107
+ declare function createPassthroughHandler(): StepHandler;
108
+ interface ResolveStepHandlerOptions {
109
+ invoke: InvokeRefFn;
110
+ }
111
+ declare function resolveStepHandler(stepName: string, stepConfig: StepConfigForFactory | undefined, options: ResolveStepHandlerOptions): StepHandler;
112
+ interface BuildStepHandlersOptions {
113
+ invoke: InvokeRefFn;
114
+ }
115
+ declare function buildStepHandlersForFlow(flow: {
116
+ steps?: Record<string, StepConfigForFactory>;
117
+ }, options: BuildStepHandlersOptions): Record<string, StepHandler>;
118
+
119
+ /**
120
+ * step-machine-public — result utilities
121
+ *
122
+ * Pure helpers that:
123
+ * - Normalize handler return shapes into NormalizedHandlerResult.
124
+ * - Filter `data` to the keys declared in `produces_data`.
125
+ * - Wrap a handler with output filtering / input validation.
126
+ *
127
+ * No transport, no I/O — only object reshaping.
128
+ */
129
+
130
+ declare function normalizeHandlerResult(raw: unknown, stepName: string): NormalizedHandlerResult;
131
+ declare function filterProducedData(data: Record<string, unknown>, produces: string[] | undefined): Record<string, unknown>;
132
+ declare function wrapWithOutputFiltering(handler: StepHandler, produces: string[] | undefined): StepHandler;
133
+ /**
134
+ * Evaluate each validation as a JSONata expression returning truthy.
135
+ *
136
+ * Returns `null` on success, or a normalized failure result on the first
137
+ * failed/throwing validation.
138
+ */
139
+ declare function runInputValidations(input: Record<string, unknown>, validations: string[] | undefined, stepName: string): NormalizedHandlerResult | null;
140
+ declare function wrapWithInputValidations(handler: StepHandler, validations: string[] | undefined, stepName: string): StepHandler;
141
+
142
+ /**
143
+ * step-machine-public — jsonata loader
144
+ *
145
+ * Synchronous jsonata wrapper. Mirrors the loader pattern in
146
+ * src/card-compute/index.ts — uses createRequire to load the vendored
147
+ * synchronous CommonJS build.
148
+ *
149
+ * Runtime portability:
150
+ * - Node ESM: createRequire works.
151
+ * - Browser/cloud: package this lib for that runtime; the consumer ships
152
+ * jsonata-sync.cjs alongside (tsup post-build does this automatically).
153
+ */
154
+ type JsonataExpression = {
155
+ evaluate: (data: unknown) => unknown;
156
+ };
157
+ declare const jsonata: (expr: string) => JsonataExpression;
158
+
159
+ export { type BuildStepHandlersOptions, type ComputeJsonataSpec, type HandlerSpec, type InvokeRefFn, type JsonataExpression, type NormalizedHandlerResult, type RefSpec, type ResolveStepHandlerOptions, type StepConfigForFactory, type StepHandler, buildStepHandlersForFlow, createComputeJsonataHandler, createPassthroughHandler, createRefStepHandler, filterProducedData, isComputeJsonataSpec, isRefSpec, jsonata, normalizeHandlerResult, resolveStepHandler, runInputValidations, wrapWithInputValidations, wrapWithOutputFiltering };
@@ -0,0 +1,159 @@
1
+ import { ExecutionRef } from '../execution-refs.js';
2
+
3
+ /**
4
+ * step-machine-public — types
5
+ *
6
+ * Platform-free types for the declarative handler model.
7
+ * No Node imports. Safe for any runtime (Node, browser, Python via codegen, etc.).
8
+ */
9
+
10
+ /**
11
+ * The single normalized shape the engine consumes.
12
+ *
13
+ * - `result` drives transitions (e.g. 'success' | 'failure' | 'timeout' | <custom>)
14
+ * - `data` drives produces_data projection into flow context
15
+ * - `error` optional human-readable failure detail
16
+ *
17
+ * Adapters MUST normalize their transport-specific output into this shape
18
+ * before returning. The engine never inspects payload format.
19
+ */
20
+ interface NormalizedHandlerResult {
21
+ result: string;
22
+ data: Record<string, unknown>;
23
+ error?: string;
24
+ }
25
+ /**
26
+ * Pure JSONata compute step.
27
+ * Each `expr` entry is `"<bindTo> = <jsonata-expression>"` or
28
+ * `{ bindTo: "...", expr: "..." }`.
29
+ *
30
+ * Evaluated sequentially against the flat flow context; each binding is added
31
+ * before the next expression is evaluated.
32
+ */
33
+ interface ComputeJsonataSpec {
34
+ type: 'compute-jsonata';
35
+ expr: Array<string | {
36
+ bindTo: string;
37
+ expr: string;
38
+ }>;
39
+ }
40
+ /**
41
+ * External reference step. The handler spec IS an ExecutionRef plus a
42
+ * `type: 'ref'` discriminator.
43
+ *
44
+ * The engine never invokes refs directly — invocation is delegated to an
45
+ * `InvokeFn` adapter (e.g. Node spawn, HTTP, Azure Function).
46
+ */
47
+ interface RefSpec extends ExecutionRef {
48
+ type: 'ref';
49
+ }
50
+ type HandlerSpec = ComputeJsonataSpec | RefSpec;
51
+ /**
52
+ * Single invocation boundary. The framework calls this for every ref step;
53
+ * the adapter (Node spawn / HTTP / Azure Function / etc.) decides how to
54
+ * actually invoke the ref and normalizes the outcome to {result, data, error?}.
55
+ *
56
+ * `args` is the flat flow context for the step. The adapter is responsible
57
+ * for honoring `ref.argsMassaging` (cmdTemplate / urlTemplate / bodyTemplate)
58
+ * before performing the transport.
59
+ *
60
+ * May return synchronously (sync transports) or as a Promise (async transports).
61
+ * The framework awaits regardless.
62
+ */
63
+ type InvokeRefFn = (ref: ExecutionRef, args: Record<string, unknown>) => NormalizedHandlerResult | Promise<NormalizedHandlerResult>;
64
+ /**
65
+ * Handler signature consumed by the existing pure step machine.
66
+ *
67
+ * (Mirrors the StepHandler type in src/step-machine/types.ts but typed in
68
+ * platform-free terms.)
69
+ */
70
+ type StepHandler = (input: Record<string, unknown>, context?: {
71
+ stepName?: string;
72
+ runId?: string;
73
+ }) => Promise<NormalizedHandlerResult>;
74
+ /**
75
+ * The subset of step configuration the handler factory consumes.
76
+ *
77
+ * (We do NOT re-export StepFlowConfig here — that lives in src/step-machine/.
78
+ * This is just the shape the factory needs.)
79
+ */
80
+ interface StepConfigForFactory {
81
+ handler?: HandlerSpec;
82
+ produces_data?: string[];
83
+ input_validations?: string[];
84
+ config?: Record<string, unknown>;
85
+ }
86
+
87
+ /**
88
+ * step-machine-public — handler factory
89
+ *
90
+ * Builds engine-facing StepHandlers from declarative HandlerSpec entries.
91
+ * Pure: no Node imports, no transport. Refs are dispatched through the
92
+ * caller-supplied `InvokeFn`, which is the single boundary between this lib
93
+ * and any transport (Node spawn, HTTP, Azure Function, etc.).
94
+ *
95
+ * Layering:
96
+ *
97
+ * step-machine (pure FSM) — runs handlers, never builds them.
98
+ * step-machine-public (this lib) — declarative spec → StepHandler map.
99
+ * adapter (e.g. node-spawn-invoker) — InvokeFn implementation per transport.
100
+ * step-machine-cli (thin shell) — wires adapter + flow loader + run.
101
+ */
102
+
103
+ declare function isComputeJsonataSpec(spec: unknown): spec is ComputeJsonataSpec;
104
+ declare function isRefSpec(spec: unknown): spec is RefSpec;
105
+ declare function createComputeJsonataHandler(spec: ComputeJsonataSpec, stepName: string, config?: Record<string, unknown>): StepHandler;
106
+ declare function createRefStepHandler(spec: RefSpec, stepName: string, invoke: InvokeRefFn, config?: Record<string, unknown>): StepHandler;
107
+ declare function createPassthroughHandler(): StepHandler;
108
+ interface ResolveStepHandlerOptions {
109
+ invoke: InvokeRefFn;
110
+ }
111
+ declare function resolveStepHandler(stepName: string, stepConfig: StepConfigForFactory | undefined, options: ResolveStepHandlerOptions): StepHandler;
112
+ interface BuildStepHandlersOptions {
113
+ invoke: InvokeRefFn;
114
+ }
115
+ declare function buildStepHandlersForFlow(flow: {
116
+ steps?: Record<string, StepConfigForFactory>;
117
+ }, options: BuildStepHandlersOptions): Record<string, StepHandler>;
118
+
119
+ /**
120
+ * step-machine-public — result utilities
121
+ *
122
+ * Pure helpers that:
123
+ * - Normalize handler return shapes into NormalizedHandlerResult.
124
+ * - Filter `data` to the keys declared in `produces_data`.
125
+ * - Wrap a handler with output filtering / input validation.
126
+ *
127
+ * No transport, no I/O — only object reshaping.
128
+ */
129
+
130
+ declare function normalizeHandlerResult(raw: unknown, stepName: string): NormalizedHandlerResult;
131
+ declare function filterProducedData(data: Record<string, unknown>, produces: string[] | undefined): Record<string, unknown>;
132
+ declare function wrapWithOutputFiltering(handler: StepHandler, produces: string[] | undefined): StepHandler;
133
+ /**
134
+ * Evaluate each validation as a JSONata expression returning truthy.
135
+ *
136
+ * Returns `null` on success, or a normalized failure result on the first
137
+ * failed/throwing validation.
138
+ */
139
+ declare function runInputValidations(input: Record<string, unknown>, validations: string[] | undefined, stepName: string): NormalizedHandlerResult | null;
140
+ declare function wrapWithInputValidations(handler: StepHandler, validations: string[] | undefined, stepName: string): StepHandler;
141
+
142
+ /**
143
+ * step-machine-public — jsonata loader
144
+ *
145
+ * Synchronous jsonata wrapper. Mirrors the loader pattern in
146
+ * src/card-compute/index.ts — uses createRequire to load the vendored
147
+ * synchronous CommonJS build.
148
+ *
149
+ * Runtime portability:
150
+ * - Node ESM: createRequire works.
151
+ * - Browser/cloud: package this lib for that runtime; the consumer ships
152
+ * jsonata-sync.cjs alongside (tsup post-build does this automatically).
153
+ */
154
+ type JsonataExpression = {
155
+ evaluate: (data: unknown) => unknown;
156
+ };
157
+ declare const jsonata: (expr: string) => JsonataExpression;
158
+
159
+ export { type BuildStepHandlersOptions, type ComputeJsonataSpec, type HandlerSpec, type InvokeRefFn, type JsonataExpression, type NormalizedHandlerResult, type RefSpec, type ResolveStepHandlerOptions, type StepConfigForFactory, type StepHandler, buildStepHandlersForFlow, createComputeJsonataHandler, createPassthroughHandler, createRefStepHandler, filterProducedData, isComputeJsonataSpec, isRefSpec, jsonata, normalizeHandlerResult, resolveStepHandler, runInputValidations, wrapWithInputValidations, wrapWithOutputFiltering };
@@ -0,0 +1,2 @@
1
+ import {createRequire}from'module';var $=createRequire(import.meta.url),d=$("./jsonata-sync.cjs");function y(r,e){if(!r||typeof r!="object")throw new Error(`[step-machine-public] Step "${e}" returned a non-object result.`);let o=r,n=o.result??o.status;if(typeof n=="string"&&n.trim().length>0){let s=o.data&&typeof o.data=="object"&&!Array.isArray(o.data)?{...o.data}:{},a=typeof o.error=="string"?o.error:void 0;return a&&!("error"in s)&&(s.error=a),{result:n,data:s,...a?{error:a}:{}}}return {result:"success",data:{...o}}}function w(r,e){if(!e||e.length===0)return r;let o={};for(let n of e)Object.prototype.hasOwnProperty.call(r,n)&&(o[n]=r[n]);return o}function g(r,e){return async(o,n)=>{let s=await r(o,n),a=y(s,n?.stepName??"unknown");return {result:a.result,data:w(a.data,e),...a.error?{error:a.error}:{}}}}function S(r,e,o){if(!e||e.length===0)return null;for(let n of e)try{if(!d(n).evaluate(r))return {result:"failure",data:{error:`[${o}] input validation failed: ${n}`}}}catch(s){let a=s instanceof Error?s.message:String(s);return {result:"failure",data:{error:`[${o}] input validation error on "${n}": ${a}`}}}return null}function m(r,e,o){return !e||e.length===0?r:async(n,s)=>{let a=S(n,e,o);return a||r(n,s)}}var R=createRequire(import.meta.url);function O(){try{return R("./jsonata-sync.cjs")}catch{return R("../../card-compute/jsonata-sync.cjs")}}var f=O();function x(r,e,o){if(!r||typeof r!="object")return e;let n={output:e},s=e.result,a=e.data,i=e.error;if(typeof r.resultExpr=="string")try{let t=f(r.resultExpr).evaluate(n);if(typeof t!="string"||!t.trim())throw new Error(`resultExpr did not produce a non-empty string (got ${JSON.stringify(t)})`);s=t;}catch(t){let u=t instanceof Error?t.message:String(t);throw new Error(`[${o}] outputTransforms.resultExpr failed: ${u}`)}if(typeof r.dataTemplate=="string")try{let t=f(r.dataTemplate).evaluate(n);if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`dataTemplate did not produce an object (got ${JSON.stringify(t)})`);a=t;}catch(t){let u=t instanceof Error?t.message:String(t);throw new Error(`[${o}] outputTransforms.dataTemplate failed: ${u}`)}if(typeof r.errorExpr=="string")try{let t=f(r.errorExpr).evaluate(n);i=t!=null?String(t):void 0;}catch(t){let u=t instanceof Error?t.message:String(t);throw new Error(`[${o}] outputTransforms.errorExpr failed: ${u}`)}return i!==void 0?{result:s,data:a,error:i}:{result:s,data:a}}function h(r){return !!r&&typeof r=="object"&&r.type==="compute-jsonata"&&Array.isArray(r.expr)&&r.expr.length>0}function k(r){if(!r||typeof r!="object")return false;let e=r;return e.type==="ref"&&typeof e.howToRun=="string"&&typeof e.whatToRun=="string"}function F(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 J(r,e,o){let n=e.split("."),s=r;for(let a=0;a<n.length-1;a++){let i=n[a];(s[i]==null||typeof s[i]!="object")&&(s[i]={}),s=s[i];}s[n[n.length-1]]=o;}function H(r,e,o){let n=r.expr.map(F);return async s=>{let a=s&&typeof s=="object"&&!Array.isArray(s)?{...s}:{},i={},t={expects_data:a,data:i,...o?{config:o}:{}},u,l;for(let p of n)try{let c=d(p.expr).evaluate(t);if(p.bindTo==="result")u=c!=null?String(c):"success";else if(p.bindTo==="error")l=c!=null?String(c):void 0;else if(p.bindTo.startsWith("data."))J(i,p.bindTo.slice(5),c);else return {result:"failure",data:{},error:`[${e}] invalid bindTo "${p.bindTo}": must be "result", "error", or start with "data."`}}catch(c){let E=c instanceof Error?c.message:String(c);return {result:"failure",data:{},error:`[${e}] compute "${p.bindTo}" failed: ${E}`}}return u===void 0?{result:"failure",data:{},error:`[${e}] compute-jsonata: no "result" binding declared \u2014 add '- result = "success"' to expr`}:l?{result:u,data:i,error:l}:{result:u,data:i}}}function b(r,e,o,n){let{type:s,...a}=r,i=a;return async t=>{let u=t&&typeof t=="object"&&!Array.isArray(t)?{...t}:{};n&&(u.config=n);try{let l=await o(i,u);if(!r.outputTransforms)return l;try{return x(r.outputTransforms,l,e)}catch(p){let c=p instanceof Error?p.message:String(p);return {result:"failure",data:{},error:c}}}catch(l){let p=l instanceof Error?l.message:String(l);return {result:"failure",data:{error:`[step-machine-public] step "${e}" invoke threw: ${p}`}}}}}function j(){return async r=>({result:"success",data:r&&typeof r=="object"&&!Array.isArray(r)?r:{}})}function v(r,e,o){let n=Array.isArray(e?.produces_data)?e?.produces_data:void 0,s=Array.isArray(e?.input_validations)?e?.input_validations:void 0,a=e?.config??void 0,i=e?.handler,t;return h(i)?t=H(i,r,a):k(i)?t=b(i,r,o.invoke,a):t=j(),m(g(t,n),s,r)}function z(r,e){let o={};for(let[n,s]of Object.entries(r.steps??{}))o[n]=v(n,s,e);return o}export{z as buildStepHandlersForFlow,H as createComputeJsonataHandler,j as createPassthroughHandler,b as createRefStepHandler,w as filterProducedData,h as isComputeJsonataSpec,k as isRefSpec,d as jsonata,y as normalizeHandlerResult,v as resolveStepHandler,S as runInputValidations,m as wrapWithInputValidations,g as wrapWithOutputFiltering};//# sourceMappingURL=index.js.map
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
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/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","isComputeJsonataSpec","spec","isRefSpec","s","normalizeComputeStep","item","eq","deepSet","path","value","parts","cur","i","k","createComputeJsonataHandler","config","steps","expects_data","transitionResult","transitionError","step","createRefStepHandler","invoke","_t","refOnly","ref","stepInput","createPassthroughHandler","resolveStepHandler","stepConfig","options","inputValidations","base","buildStepHandlersForFlow","flow","handlers"],"mappings":"mCAeA,IAAMA,CAAAA,CAAWC,aAAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAA,CAMjCC,CAAAA,CAA+CF,CAAAA,CAAS,oBAAoB,ECHlF,SAASG,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACyB,CACzB,GAAI,CAACD,CAAAA,EAAO,OAAOA,CAAAA,EAAQ,QAAA,CACzB,MAAM,IAAI,KAAA,CAAM,CAAA,4BAAA,EAA+BC,CAAQ,CAAA,+BAAA,CAAiC,EAG1F,IAAMC,CAAAA,CAAMF,CAAAA,CACNG,CAAAA,CAAUD,CAAAA,CAAI,MAAA,EAAUA,CAAAA,CAAI,MAAA,CAGlC,GAAI,OAAOC,CAAAA,EAAW,QAAA,EAAYA,CAAAA,CAAO,IAAA,EAAK,CAAE,MAAA,CAAS,CAAA,CAAG,CAC1D,IAAMC,CAAAA,CACJF,CAAAA,CAAI,IAAA,EAAQ,OAAOA,CAA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uD,CAAAA,CAAmBvD,CAAAA,CAAUwD,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 * 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 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 return (\n s.type === 'ref' &&\n typeof s.howToRun === 'string' &&\n typeof s.whatToRun === 'string'\n );\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 const { type: _t, ...refOnly } = spec;\n const ref = refOnly;\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"]}