awaitly 1.35.0 → 2.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 (241) hide show
  1. package/dist/{duration.d.ts → di-BDlT7InM.d.cts} +15 -1
  2. package/dist/{duration.d.cts → di-BbFFfO8y.d.ts} +15 -1
  3. package/dist/errors-DtXvrCiO.d.cts +708 -0
  4. package/dist/errors-DtXvrCiO.d.ts +708 -0
  5. package/dist/index.cjs +4594 -1
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.cts +1970 -141
  8. package/dist/index.d.ts +1970 -141
  9. package/dist/index.js +4398 -1
  10. package/dist/index.js.map +1 -1
  11. package/dist/result.cjs +641 -1
  12. package/dist/result.cjs.map +1 -1
  13. package/dist/result.d.cts +29 -4
  14. package/dist/result.d.ts +29 -4
  15. package/dist/result.js +561 -1
  16. package/dist/result.js.map +1 -1
  17. package/dist/testing.cjs +4202 -8
  18. package/dist/testing.cjs.map +1 -1
  19. package/dist/testing.d.cts +2 -6
  20. package/dist/testing.d.ts +2 -6
  21. package/dist/testing.js +4154 -8
  22. package/dist/testing.js.map +1 -1
  23. package/dist/{run-entry-DGs0tySr.d.cts → types-B8NfNRGX.d.ts} +1078 -1502
  24. package/dist/{run-entry-BOuNyVoO.d.ts → types-BZ2f4MRR.d.cts} +1078 -1502
  25. package/dist/workflow.cjs +7096 -6
  26. package/dist/workflow.cjs.map +1 -1
  27. package/dist/workflow.d.cts +3346 -22
  28. package/dist/workflow.d.ts +3346 -22
  29. package/dist/workflow.js +6929 -6
  30. package/dist/workflow.js.map +1 -1
  31. package/package.json +3 -168
  32. package/dist/adapters.cjs +0 -7
  33. package/dist/adapters.cjs.map +0 -1
  34. package/dist/adapters.d.cts +0 -179
  35. package/dist/adapters.d.ts +0 -179
  36. package/dist/adapters.js +0 -7
  37. package/dist/adapters.js.map +0 -1
  38. package/dist/batch.cjs +0 -7
  39. package/dist/batch.cjs.map +0 -1
  40. package/dist/batch.d.cts +0 -200
  41. package/dist/batch.d.ts +0 -200
  42. package/dist/batch.js +0 -7
  43. package/dist/batch.js.map +0 -1
  44. package/dist/bind-deps.cjs +0 -2
  45. package/dist/bind-deps.cjs.map +0 -1
  46. package/dist/bind-deps.d.cts +0 -28
  47. package/dist/bind-deps.d.ts +0 -28
  48. package/dist/bind-deps.js +0 -2
  49. package/dist/bind-deps.js.map +0 -1
  50. package/dist/cache.cjs +0 -2
  51. package/dist/cache.cjs.map +0 -1
  52. package/dist/cache.d.cts +0 -269
  53. package/dist/cache.d.ts +0 -269
  54. package/dist/cache.js +0 -2
  55. package/dist/cache.js.map +0 -1
  56. package/dist/circuit-breaker.cjs +0 -7
  57. package/dist/circuit-breaker.cjs.map +0 -1
  58. package/dist/circuit-breaker.d.cts +0 -211
  59. package/dist/circuit-breaker.d.ts +0 -211
  60. package/dist/circuit-breaker.js +0 -7
  61. package/dist/circuit-breaker.js.map +0 -1
  62. package/dist/conditional.cjs +0 -2
  63. package/dist/conditional.cjs.map +0 -1
  64. package/dist/conditional.d.cts +0 -252
  65. package/dist/conditional.d.ts +0 -252
  66. package/dist/conditional.js +0 -2
  67. package/dist/conditional.js.map +0 -1
  68. package/dist/core.cjs +0 -7
  69. package/dist/core.cjs.map +0 -1
  70. package/dist/core.d.cts +0 -5
  71. package/dist/core.d.ts +0 -5
  72. package/dist/core.js +0 -7
  73. package/dist/core.js.map +0 -1
  74. package/dist/di-By77n4Fa.d.ts +0 -15
  75. package/dist/di-OJfsohf-.d.cts +0 -15
  76. package/dist/diagnostics.cjs +0 -8
  77. package/dist/diagnostics.cjs.map +0 -1
  78. package/dist/diagnostics.d.cts +0 -68
  79. package/dist/diagnostics.d.ts +0 -68
  80. package/dist/diagnostics.js +0 -8
  81. package/dist/diagnostics.js.map +0 -1
  82. package/dist/durable.cjs +0 -11
  83. package/dist/durable.cjs.map +0 -1
  84. package/dist/durable.d.cts +0 -9
  85. package/dist/durable.d.ts +0 -9
  86. package/dist/durable.js +0 -11
  87. package/dist/durable.js.map +0 -1
  88. package/dist/duration.cjs +0 -2
  89. package/dist/duration.cjs.map +0 -1
  90. package/dist/duration.js +0 -2
  91. package/dist/duration.js.map +0 -1
  92. package/dist/engine.cjs +0 -11
  93. package/dist/engine.cjs.map +0 -1
  94. package/dist/engine.d.cts +0 -115
  95. package/dist/engine.d.ts +0 -115
  96. package/dist/engine.js +0 -11
  97. package/dist/engine.js.map +0 -1
  98. package/dist/errors.cjs +0 -2
  99. package/dist/errors.cjs.map +0 -1
  100. package/dist/errors.d.cts +0 -361
  101. package/dist/errors.d.ts +0 -361
  102. package/dist/errors.js +0 -2
  103. package/dist/errors.js.map +0 -1
  104. package/dist/fetch.cjs +0 -7
  105. package/dist/fetch.cjs.map +0 -1
  106. package/dist/fetch.d.cts +0 -86
  107. package/dist/fetch.d.ts +0 -86
  108. package/dist/fetch.js +0 -7
  109. package/dist/fetch.js.map +0 -1
  110. package/dist/flow.cjs +0 -7
  111. package/dist/flow.cjs.map +0 -1
  112. package/dist/flow.d.cts +0 -163
  113. package/dist/flow.d.ts +0 -163
  114. package/dist/flow.js +0 -7
  115. package/dist/flow.js.map +0 -1
  116. package/dist/functional.cjs +0 -2
  117. package/dist/functional.cjs.map +0 -1
  118. package/dist/functional.d.cts +0 -444
  119. package/dist/functional.d.ts +0 -444
  120. package/dist/functional.js +0 -2
  121. package/dist/functional.js.map +0 -1
  122. package/dist/guards-4sV7mTqj.d.cts +0 -72
  123. package/dist/guards-BIX05ALH.d.ts +0 -72
  124. package/dist/hitl-DFn4Xa_l.d.cts +0 -468
  125. package/dist/hitl-DU5VpKq7.d.ts +0 -468
  126. package/dist/hitl.cjs +0 -7
  127. package/dist/hitl.cjs.map +0 -1
  128. package/dist/hitl.d.cts +0 -442
  129. package/dist/hitl.d.ts +0 -442
  130. package/dist/hitl.js +0 -7
  131. package/dist/hitl.js.map +0 -1
  132. package/dist/index-CnvBryQB.d.ts +0 -417
  133. package/dist/index-DEZEf8Fs.d.cts +0 -417
  134. package/dist/match-entry-DjI2bLpD.d.cts +0 -209
  135. package/dist/match-entry-DjI2bLpD.d.ts +0 -209
  136. package/dist/match.cjs +0 -2
  137. package/dist/match.cjs.map +0 -1
  138. package/dist/match.d.cts +0 -1
  139. package/dist/match.d.ts +0 -1
  140. package/dist/match.js +0 -2
  141. package/dist/match.js.map +0 -1
  142. package/dist/otel.cjs +0 -2
  143. package/dist/otel.cjs.map +0 -1
  144. package/dist/otel.d.cts +0 -188
  145. package/dist/otel.d.ts +0 -188
  146. package/dist/otel.js +0 -2
  147. package/dist/otel.js.map +0 -1
  148. package/dist/persistence-entry-B-8PjnSR.d.cts +0 -831
  149. package/dist/persistence-entry-D8zRkLiT.d.ts +0 -831
  150. package/dist/persistence.cjs +0 -2
  151. package/dist/persistence.cjs.map +0 -1
  152. package/dist/persistence.d.cts +0 -7
  153. package/dist/persistence.d.ts +0 -7
  154. package/dist/persistence.js +0 -2
  155. package/dist/persistence.js.map +0 -1
  156. package/dist/policies.cjs +0 -2
  157. package/dist/policies.cjs.map +0 -1
  158. package/dist/policies.d.cts +0 -379
  159. package/dist/policies.d.ts +0 -379
  160. package/dist/policies.js +0 -2
  161. package/dist/policies.js.map +0 -1
  162. package/dist/ratelimit.cjs +0 -7
  163. package/dist/ratelimit.cjs.map +0 -1
  164. package/dist/ratelimit.d.cts +0 -458
  165. package/dist/ratelimit.d.ts +0 -458
  166. package/dist/ratelimit.js +0 -7
  167. package/dist/ratelimit.js.map +0 -1
  168. package/dist/reliability.cjs +0 -11
  169. package/dist/reliability.cjs.map +0 -1
  170. package/dist/reliability.d.cts +0 -11
  171. package/dist/reliability.d.ts +0 -11
  172. package/dist/reliability.js +0 -11
  173. package/dist/reliability.js.map +0 -1
  174. package/dist/resolver.cjs +0 -7
  175. package/dist/resolver.cjs.map +0 -1
  176. package/dist/resolver.d.cts +0 -68
  177. package/dist/resolver.d.ts +0 -68
  178. package/dist/resolver.js +0 -7
  179. package/dist/resolver.js.map +0 -1
  180. package/dist/resource.cjs +0 -7
  181. package/dist/resource.cjs.map +0 -1
  182. package/dist/resource.d.cts +0 -174
  183. package/dist/resource.d.ts +0 -174
  184. package/dist/resource.js +0 -7
  185. package/dist/resource.js.map +0 -1
  186. package/dist/result/retry.cjs +0 -2
  187. package/dist/result/retry.cjs.map +0 -1
  188. package/dist/result/retry.d.cts +0 -70
  189. package/dist/result/retry.d.ts +0 -70
  190. package/dist/result/retry.js +0 -2
  191. package/dist/result/retry.js.map +0 -1
  192. package/dist/retry.cjs +0 -2
  193. package/dist/retry.cjs.map +0 -1
  194. package/dist/retry.d.cts +0 -388
  195. package/dist/retry.d.ts +0 -388
  196. package/dist/retry.js +0 -2
  197. package/dist/retry.js.map +0 -1
  198. package/dist/run.cjs +0 -7
  199. package/dist/run.cjs.map +0 -1
  200. package/dist/run.d.cts +0 -4
  201. package/dist/run.d.ts +0 -4
  202. package/dist/run.js +0 -7
  203. package/dist/run.js.map +0 -1
  204. package/dist/saga.cjs +0 -11
  205. package/dist/saga.cjs.map +0 -1
  206. package/dist/saga.d.cts +0 -164
  207. package/dist/saga.d.ts +0 -164
  208. package/dist/saga.js +0 -11
  209. package/dist/saga.js.map +0 -1
  210. package/dist/singleflight.cjs +0 -2
  211. package/dist/singleflight.cjs.map +0 -1
  212. package/dist/singleflight.d.cts +0 -145
  213. package/dist/singleflight.d.ts +0 -145
  214. package/dist/singleflight.js +0 -2
  215. package/dist/singleflight.js.map +0 -1
  216. package/dist/slugs.cjs +0 -2
  217. package/dist/slugs.cjs.map +0 -1
  218. package/dist/slugs.d.cts +0 -67
  219. package/dist/slugs.d.ts +0 -67
  220. package/dist/slugs.js +0 -2
  221. package/dist/slugs.js.map +0 -1
  222. package/dist/streaming.cjs +0 -9
  223. package/dist/streaming.cjs.map +0 -1
  224. package/dist/streaming.d.cts +0 -596
  225. package/dist/streaming.d.ts +0 -596
  226. package/dist/streaming.js +0 -9
  227. package/dist/streaming.js.map +0 -1
  228. package/dist/tagged-error.cjs +0 -2
  229. package/dist/tagged-error.cjs.map +0 -1
  230. package/dist/tagged-error.d.cts +0 -275
  231. package/dist/tagged-error.d.ts +0 -275
  232. package/dist/tagged-error.js +0 -2
  233. package/dist/tagged-error.js.map +0 -1
  234. package/dist/types-BziYHFkD.d.ts +0 -323
  235. package/dist/types-C5jLEUqY.d.cts +0 -323
  236. package/dist/webhook.cjs +0 -7
  237. package/dist/webhook.cjs.map +0 -1
  238. package/dist/webhook.d.cts +0 -499
  239. package/dist/webhook.d.ts +0 -499
  240. package/dist/webhook.js +0 -7
  241. package/dist/webhook.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,2 +1,4399 @@
1
- var Ve=Object.defineProperty;var $e=(e,r)=>{for(var n in r)Ve(e,n,{get:r[n],enumerable:!0})};var U={};$e(U,{AWAITLY_CANCELLED:()=>re,AWAITLY_TIMEOUT:()=>ne,AWAITLY_UNEXPECTED:()=>ee,DESERIALIZATION_ERROR:()=>R,PROMISE_REJECTED:()=>p,UnexpectedError:()=>C,UnwrapError:()=>k,all:()=>Ue,allAsync:()=>Oe,allSettled:()=>Be,allSettledAsync:()=>De,andThen:()=>ye,any:()=>Se,anyAsync:()=>je,bimap:()=>xe,deserialize:()=>He,err:()=>u,flatten:()=>Ie,from:()=>le,fromNullable:()=>de,fromPromise:()=>pe,hydrate:()=>ve,isErr:()=>f,isOk:()=>l,isPromiseRejectedError:()=>oe,isSerializedResult:()=>be,isUnexpectedError:()=>m,map:()=>Te,mapError:()=>Ce,mapErrorTry:()=>ge,mapTry:()=>me,match:()=>v,matchError:()=>P,matchErrorPartial:()=>Ne,ok:()=>a,orElse:()=>we,orElseAsync:()=>Ae,partition:()=>_e,recover:()=>he,recoverAsync:()=>Pe,runOrNull:()=>ce,runOrThrow:()=>ae,runOrThrowAsync:()=>ie,runOrUndefined:()=>Ee,serialize:()=>Ke,tags:()=>te,tap:()=>Re,tapError:()=>ke,tryAsync:()=>fe,unwrap:()=>g,unwrapOr:()=>se,unwrapOrElse:()=>ue,zip:()=>b,zipAsync:()=>Fe});var We={"step-require-id":"step-require-id","step-no-immediate-execution":"step-no-immediate-execution","step-require-thunk-for-key":"step-require-thunk-for-key","step-no-bare-await":"step-no-bare-await","step-no-try-catch-wrap":"step-no-try-catch-wrap","step-stable-cache-keys":"step-stable-cache-keys","workflow-no-floating":"workflow-no-floating","workflow-options-position":"workflow-options-position","workflow-callback-shape":"workflow-callback-shape","workflow-no-callable-form":"workflow-no-callable-form","workflow-no-dynamic-import":"workflow-no-dynamic-import","result-no-floating":"result-no-floating","result-require-handling":"result-require-handling","result-no-double-wrap":"result-no-double-wrap","result-no-manual-propagation":"result-no-manual-propagation","result-no-direct-ok-err":"result-no-direct-ok-err","error-check-unexpected-first":"error-check-unexpected-first","error-access-cause":"error-access-cause","error-normalize":"error-normalize","error-no-throw-in-deps":"error-no-throw-in-deps","concurrency-no-promise-all":"concurrency-no-promise-all","concurrency-no-promise-race":"concurrency-no-promise-race","concurrency-no-promise-allsettled":"concurrency-no-promise-allsettled","runtime-step-timeout":"runtime-step-timeout","runtime-step-aborted":"runtime-step-aborted","runtime-retry-exhausted":"runtime-retry-exhausted","runtime-rate-limit":"runtime-rate-limit","runtime-circuit-open":"runtime-circuit-open","runtime-unexpected":"runtime-unexpected","runtime-resolver-not-found":"runtime-resolver-not-found","runtime-saga-compensation":"runtime-saga-compensation"};function G(e){return`https://jagreehal.github.io/awaitly/rules/#${e}`}var ur=Object.keys(We);var y=class extends Error{_tag};function c(e,r){return class extends y{_tag=e;constructor(n,t){let o=r?.message?r.message(n??{}):e;if(super(o),this.name=e,r?.slug!==void 0){if(!r.hint)throw new TypeError(`TaggedError: 'hint' is required when 'slug' is set (slug: "${r.slug}")`);Object.defineProperty(this,"code",{value:r.slug,enumerable:!0,writable:!1,configurable:!1}),Object.defineProperty(this,"hint",{value:r.hint,enumerable:!0,writable:!1,configurable:!1}),Object.defineProperty(this,"docsUrl",{value:G(r.slug),enumerable:!0,writable:!1,configurable:!1})}if(Object.setPrototypeOf(this,new.target.prototype),n&&typeof n=="object"){let s;if(r?.slug!==void 0){let{_tag:T,name:h,message:Le,stack:ze,code:z,hint:tr,docsUrl:or,...Ge}=n;s=Ge}else{let{_tag:T,name:h,message:Le,stack:ze,...z}=n;s=z}let i=Object.prototype.hasOwnProperty.call(s,"cause"),E=i?s.cause:void 0;i&&delete s.cause;let d=t?.cause!==void 0;if(i&&d)throw new TypeError("TaggedError: cannot provide 'cause' in props when also setting ErrorOptions.cause");Object.assign(this,s),i&&(this.cause=E),d&&(this.cause=t?.cause)}else t?.cause!==void 0&&(this.cause=t.cause)}}}Object.defineProperty(c,Symbol.hasInstance,{value:e=>e instanceof y});(o=>{function e(s){return s instanceof Error}o.isError=e;function r(s){return s instanceof y}o.isTaggedError=r;function n(s,i){let E=s._tag,d=i[E];return d(s)}o.match=n;function t(s,i,E){let d=s._tag,T=i[d];return T?T(s):E(s)}o.matchPartial=t})(c||={});var V=class extends c("TimeoutError",{slug:"runtime-step-timeout",hint:"Increase the step's timeout option, or check why the upstream operation is slow.",message:r=>r.operation?`TimeoutError: ${r.operation} timed out after ${r.ms}ms`:`TimeoutError: Operation timed out after ${r.ms}ms`}){},$=class extends c("RetryExhaustedError",{slug:"runtime-retry-exhausted",hint:"All retry attempts failed. Inspect lastError and decide whether to surface it or compensate.",message:r=>r.operation?`RetryExhaustedError: ${r.operation} failed after ${r.attempts} attempts`:`RetryExhaustedError: Operation failed after ${r.attempts} attempts`}){},W=class extends c("RateLimitError",{slug:"runtime-rate-limit",hint:"Wait retryAfterMs before retrying, or apply step.cache to deduplicate calls.",message:r=>r.limiterName?`RateLimitError: Rate limit exceeded for ${r.limiterName}${r.retryAfterMs?`, retry after ${r.retryAfterMs}ms`:""}`:`RateLimitError: Rate limit exceeded${r.retryAfterMs?`, retry after ${r.retryAfterMs}ms`:""}`}){},Y=class extends c("CircuitBreakerOpenError",{slug:"runtime-circuit-open",hint:"The circuit is open. Wait for it to half-open or fall back to a degraded path.",message:r=>`CircuitBreakerOpenError: Circuit ${r.circuitName} is ${r.state??"OPEN"}${r.retryAfterMs?`, retry after ${Math.ceil(r.retryAfterMs/1e3)}s`:""}`}){},J=class extends c("ValidationError",{message:r=>`ValidationError: Invalid ${r.field} - ${r.reason}`}){},q=class extends c("NotFoundError",{message:r=>r.id?`NotFoundError: ${r.resource} with id ${r.id} not found`:`NotFoundError: ${r.resource} not found`}){},Z=class extends c("UnauthorizedError",{message:r=>r.reason?`UnauthorizedError: ${r.reason}`:r.action&&r.resource?`UnauthorizedError: Not authorized to ${r.action} ${r.resource}`:"UnauthorizedError: Access denied"}){},X=class extends c("NetworkError",{message:r=>r.url?`NetworkError: ${r.reason} (${r.url})`:`NetworkError: ${r.reason}`}){},Q=class extends c("CompensationError",{slug:"runtime-saga-compensation",hint:"A saga compensation step failed. Inspect compensationError and ensure compensation is idempotent.",message:r=>`CompensationError: Failed to compensate step ${r.step}`}){},C=class extends c("UnexpectedError",{slug:"runtime-unexpected",hint:"An unexpected exception escaped a step. Inspect cause; consider returning a typed Result instead of throwing.",message:r=>`UnexpectedError: ${r.cause instanceof Error?r.cause.message:String(r.cause??"unknown")}`}){};var p="PROMISE_REJECTED",ee="AWAITLY_UNEXPECTED",re="AWAITLY_CANCELLED",ne="AWAITLY_TIMEOUT",te=(...e)=>e;function a(e){return{ok:!0,value:e}}function u(e,r){let n=r?.cause;return{ok:!1,error:e,...n!==void 0?{cause:n}:{}}}var l=e=>e.ok,f=e=>!e.ok,m=e=>e instanceof C||typeof e=="object"&&e!==null&&"_tag"in e&&e._tag==="UnexpectedError",oe=e=>typeof e=="object"&&e!==null&&"type"in e&&e.type===p;function P(e,r){if(r===void 0){let t=e;return o=>P(o,t)}let n=e;return m(n)?r.UnexpectedError(n):r[n](n)}var k=class extends Error{error;cause;constructor(r){let n=typeof r.error=="string"?r.error:JSON.stringify(r.error);super(`Attempted to unwrap an Err: ${n}`),this.name="UnwrapError",this.error=r.error,this.cause=r.cause}},g=e=>{if(e.ok)return e.value;throw new k(e)},se=(e,r)=>e.ok?e.value:r,ue=(e,r)=>e.ok?e.value:r(e.error,e.cause),ae=e=>g(e),ie=e=>Promise.resolve(e).then(g),ce=e=>e.ok?e.value:null,Ee=e=>e.ok?e.value:void 0;function le(e,r){try{return a(e())}catch(n){return r?u(r(n),{cause:n}):u(n)}}async function pe(e,r){try{return a(await e)}catch(n){return r?u(r(n),{cause:n}):u(n)}}async function fe(e,r){try{return a(await e())}catch(n){return r?u(r(n),{cause:n}):u(n)}}function de(e,r){return e!=null?a(e):u(r())}function Te(e,r){return e.ok?a(r(e.value)):e}function Ce(e,r){return e.ok?e:u(r(e.error,e.cause),{cause:e.cause})}function v(e,r){if(r===void 0){let n=e;return t=>v(t,n)}return e.ok?r.ok(e.value):r.err(e.error,e.cause)}function ye(e,r){return e.ok?r(e.value):e}function Re(e,r){return e.ok&&r(e.value),e}function ke(e,r){return e.ok||r(e.error,e.cause),e}function me(e,r,n){if(!e.ok)return e;try{return a(r(e.value))}catch(t){return u(n(t),{cause:t})}}function ge(e,r,n){if(e.ok)return e;try{return u(r(e.error),{cause:e.cause})}catch(t){return u(n(t),{cause:t})}}function xe(e,r,n){return e.ok?a(r(e.value)):u(n(e.error,e.cause),{cause:e.cause})}function we(e,r){return e.ok?e:r(e.error,e.cause)}async function Ae(e,r){return e.ok?e:r(e.error,e.cause)}function he(e,r){return e.ok?a(e.value):a(r(e.error,e.cause))}async function Pe(e,r){let n=await e;return n.ok?a(n.value):a(await r(n.error,n.cause))}function ve(e){if(typeof e!="object"||e===null||!("ok"in e))return null;let r=e;return r.ok===!0&&"value"in r?a(r.value):r.ok===!1&&"error"in r?u(r.error,{cause:r.cause}):null}function be(e){if(typeof e!="object"||e===null||!("ok"in e))return!1;let r=e;return r.ok===!0&&"value"in r||r.ok===!1&&"error"in r}function Ue(e){let r=[];for(let n of e){if(!n.ok)return n;r.push(n.value)}return a(r)}async function Oe(e){let r=[];for(let n of e)try{let t=await n;if(!t.ok)return t;r.push(t.value)}catch(t){return u({type:p,cause:t},{cause:{type:"PROMISE_REJECTION",reason:t}})}return a(r)}function Be(e){let r=[],n=[];for(let t of e)t.ok?r.push(t.value):n.push({error:t.error,cause:t.cause});return n.length>0?u(n):a(r)}async function De(e){let r=await Promise.all(e.map(o=>Promise.resolve(o).then(s=>({status:"result",result:s})).catch(s=>({status:"rejected",error:{type:p,cause:s},cause:{type:"PROMISE_REJECTION",reason:s}})))),n=[],t=[];for(let o of r)o.status==="rejected"?t.push({error:o.error,cause:o.cause}):o.result.ok?n.push(o.result.value):t.push({error:o.result.error,cause:o.result.cause});return t.length>0?u(t):a(n)}function _e(e){let r=[],n=[];for(let t of e)t.ok?r.push(t.value):n.push(t.error);return{values:r,errors:n}}function Se(e){if(e.length===0)return u({type:"EMPTY_INPUT",message:"any() requires at least one Result"});let r;for(let n of e){if(n.ok)return n;r||(r=n)}return r}async function je(e){return e.length===0?u({type:"EMPTY_INPUT",message:"anyAsync() requires at least one Result"}):new Promise(r=>{let n=!1,t=e.length,o=null;for(let s of e)Promise.resolve(s).catch(i=>u({type:p,cause:i},{cause:{type:"PROMISE_REJECTION",reason:i}})).then(i=>{if(!n){if(i.ok){n=!0,r(i);return}o||(o=i),t--,t===0&&r(o)}})})}function b(e,r){return e.ok?r.ok?a([e.value,r.value]):r:e}async function Fe(e,r){let n=s=>Promise.resolve(s).catch(i=>u({type:p,cause:i},{cause:{type:"PROMISE_REJECTION",reason:i}})),[t,o]=await Promise.all([n(e),n(r)]);return b(t,o)}function Ie(e){return e.ok?e.value:e}var R="DESERIALIZATION_ERROR";function He(e){if(typeof e!="object"||e===null)return u({type:R,value:e});if(!("ok"in e))return u({type:R,value:e});let r=e;return r.ok===!0&&"value"in r?a(r.value):r.ok===!1&&"error"in r?u(r.error,{cause:r.cause}):u({type:R,value:e})}function Ke(e){return e.ok?{ok:!0,value:e.value}:{ok:!1,error:e.error}}function Ne(e,r,n){if(m(e)){let o=r.UnexpectedError;return o?o(e):n(e)}let t=r[e];return t?t(e):n(e)}function O(e,...r){return r.reduce((n,t)=>t(n),e)}function B(...e){return r=>e.reduce((n,t)=>t(n),r)}function D(...e){return r=>e.reduceRight((n,t)=>t(n),r)}var _=e=>e;function Ye(e,r){return l(e)?a(r(e.value)):e}function Je(e,r){return l(e)?r(e.value):e}function qe(e,r,n){return l(e)?a(r(e.value)):u(n(e.error),{cause:e.cause})}function Ze(e,r){return f(e)?u(r(e.error),{cause:e.cause}):e}function Xe(e,r){return l(e)&&r(e.value),e}function Qe(e,r){return f(e)&&r(e.error),e}function er(e,r){return l(e)?r.ok(e.value):r.err(e.error,e.cause)}function rr(e,r){return l(e)?e.value:r(e.error)}function x(e,r){return l(e)?e:r(e.error)}function w(e,r){return l(e)?e.value:r}function A(e,r){return l(e)?e.value:r()}async function S(e,r){let n=await e;return l(n)?a(await r(n.value)):n}async function j(e,r){let n=await e;return l(n)?r(n.value):n}async function F(e,r){let n=await e;return l(n)&&await r(n.value),n}async function I(e,r){let n=await e;return f(n)&&await r(n.error),n}async function nr(e){if(e.length===0)return a([]);let r=new Array(e.length),n=0,t=!1;return new Promise(o=>{e.forEach((s,i)=>{s.then(E=>{t||(f(E)?(t=!0,o(E)):(r[i]=E.value,n++,n===e.length&&(t=!0,o(a(r)))))},E=>{t||(t=!0,o(u({type:p,cause:E},{cause:{type:"PROMISE_REJECTION",reason:E}})))})})})}async function H(e){return Promise.race(e.map(r=>r.catch(n=>u({type:p,cause:n},{cause:{type:"PROMISE_REJECTION",reason:n}}))))}function K(e,r){let n=[];for(let t=0;t<e.length;t++){let o=r(e[t],t);if(f(o))return o;n.push(o.value)}return a(n)}async function N(e,r){let n=[];for(let t=0;t<e.length;t++){let o=await r(e[t],t);if(f(o))return o;n.push(o.value)}return a(n)}async function M(e,r){return nr(e.map((n,t)=>r(n,t)))}var L={map:e=>r=>Ye(r,e),flatMap:e=>r=>Je(r,e),bimap:(e,r)=>n=>qe(n,e,r),mapError:e=>r=>Ze(r,e),tap:e=>r=>Xe(r,e),tapError:e=>r=>Qe(r,e),match:e=>r=>er(r,e),recover:e=>r=>rr(r,e),recoverWith:e=>r=>x(r,e),getOrElse:e=>r=>w(r,e),getOrElseLazy:e=>r=>A(r,e)};function Me(e,r){let n=t=>((...o)=>{let s=o.at(-1),i=o.length>0&&typeof s=="object"&&s!==null&&!Array.isArray(s)&&typeof s!="function",E=i?s:void 0,d=i?o.slice(0,-1):o,T={...r,...E?.deps??{}},h=E?{...E,deps:T}:{deps:T};return e[t](...d,h)});return{run:n("run"),runWithState:n("runWithState"),withDeps(t){return Me(e,{...r,...t})}}}var kr={...U,TaggedError:c,pipe:O,flow:B,compose:D,identity:_,R:L,recoverWith:x,getOrElse:w,getOrElseLazy:A,mapAsync:S,flatMapAsync:j,tapAsync:F,tapErrorAsync:I,race:H,traverse:K,traverseAsync:N,traverseParallel:M};export{re as AWAITLY_CANCELLED,ne as AWAITLY_TIMEOUT,ee as AWAITLY_UNEXPECTED,kr as Awaitly,R as DESERIALIZATION_ERROR,p as PROMISE_REJECTED,L as R,c as TaggedError,C as UnexpectedError,k as UnwrapError,Ue as all,Oe as allAsync,Be as allSettled,De as allSettledAsync,ye as andThen,Se as any,je as anyAsync,xe as bimap,D as compose,He as deserialize,u as err,j as flatMapAsync,Ie as flatten,B as flow,le as from,de as fromNullable,pe as fromPromise,w as getOrElse,A as getOrElseLazy,ve as hydrate,_ as identity,f as isErr,l as isOk,oe as isPromiseRejectedError,be as isSerializedResult,m as isUnexpectedError,Te as map,S as mapAsync,Ce as mapError,ge as mapErrorTry,me as mapTry,v as match,P as matchError,Ne as matchErrorPartial,a as ok,we as orElse,Ae as orElseAsync,_e as partition,O as pipe,H as race,he as recover,Pe as recoverAsync,x as recoverWith,ce as runOrNull,ae as runOrThrow,ie as runOrThrowAsync,Ee as runOrUndefined,Ke as serialize,te as tags,Re as tap,F as tapAsync,ke as tapError,I as tapErrorAsync,K as traverse,N as traverseAsync,M as traverseParallel,fe as tryAsync,g as unwrap,se as unwrapOr,ue as unwrapOrElse,Me as withDeps,b as zip,Fe as zipAsync};
1
+ // src/slugs.ts
2
+ var AWAITLY_SLUGS = {
3
+ // --- step-* ---
4
+ "step-require-id": "step-require-id",
5
+ "step-no-immediate-execution": "step-no-immediate-execution",
6
+ "step-require-thunk-for-key": "step-require-thunk-for-key",
7
+ "step-no-bare-await": "step-no-bare-await",
8
+ "step-no-try-catch-wrap": "step-no-try-catch-wrap",
9
+ "step-stable-cache-keys": "step-stable-cache-keys",
10
+ // --- workflow-* ---
11
+ "workflow-no-floating": "workflow-no-floating",
12
+ "workflow-options-position": "workflow-options-position",
13
+ "workflow-callback-shape": "workflow-callback-shape",
14
+ "workflow-no-callable-form": "workflow-no-callable-form",
15
+ "workflow-no-dynamic-import": "workflow-no-dynamic-import",
16
+ "workflow-prefer-step-if": "workflow-prefer-step-if",
17
+ "workflow-prefer-step-foreach": "workflow-prefer-step-foreach",
18
+ // --- result-* ---
19
+ "result-no-floating": "result-no-floating",
20
+ "result-require-handling": "result-require-handling",
21
+ "result-no-double-wrap": "result-no-double-wrap",
22
+ "result-no-manual-propagation": "result-no-manual-propagation",
23
+ "result-no-direct-ok-err": "result-no-direct-ok-err",
24
+ // --- error-* ---
25
+ "error-check-unexpected-first": "error-check-unexpected-first",
26
+ "error-access-cause": "error-access-cause",
27
+ "error-normalize": "error-normalize",
28
+ "error-no-throw-in-deps": "error-no-throw-in-deps",
29
+ // --- concurrency-* ---
30
+ "concurrency-no-promise-all": "concurrency-no-promise-all",
31
+ "concurrency-no-promise-race": "concurrency-no-promise-race",
32
+ "concurrency-no-promise-allsettled": "concurrency-no-promise-allsettled",
33
+ // --- runtime-* ---
34
+ "runtime-step-timeout": "runtime-step-timeout",
35
+ "runtime-step-aborted": "runtime-step-aborted",
36
+ "runtime-retry-exhausted": "runtime-retry-exhausted",
37
+ "runtime-rate-limit": "runtime-rate-limit",
38
+ "runtime-circuit-open": "runtime-circuit-open",
39
+ "runtime-unexpected": "runtime-unexpected",
40
+ "runtime-resolver-not-found": "runtime-resolver-not-found",
41
+ "runtime-saga-compensation": "runtime-saga-compensation"
42
+ };
43
+ function slugCategory(slug) {
44
+ return slug.split("-")[0];
45
+ }
46
+ function slugDocsUrl(slug) {
47
+ return `https://jagreehal.github.io/awaitly/rules/#${slug}`;
48
+ }
49
+ function isAwaitlySlug(value) {
50
+ return Object.prototype.hasOwnProperty.call(AWAITLY_SLUGS, value);
51
+ }
52
+ var ALL_SLUGS = Object.keys(
53
+ AWAITLY_SLUGS
54
+ );
55
+
56
+ // src/tagged-error.ts
57
+ var InternalTaggedErrorBase = class extends Error {
58
+ type;
59
+ /** @deprecated Use `type`. */
60
+ _tag;
61
+ };
62
+ function TaggedError(tag2, options) {
63
+ return class extends InternalTaggedErrorBase {
64
+ type = tag2;
65
+ /** @deprecated Use `type`. */
66
+ _tag = tag2;
67
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
68
+ constructor(props, errorOptions) {
69
+ const message = options?.message ? options.message(props ?? {}) : tag2;
70
+ super(message);
71
+ this.name = tag2;
72
+ if (options?.slug !== void 0) {
73
+ if (!options.hint) {
74
+ throw new TypeError(
75
+ `TaggedError: 'hint' is required when 'slug' is set (slug: "${options.slug}")`
76
+ );
77
+ }
78
+ Object.defineProperty(this, "code", {
79
+ value: options.slug,
80
+ enumerable: true,
81
+ writable: false,
82
+ configurable: false
83
+ });
84
+ Object.defineProperty(this, "hint", {
85
+ value: options.hint,
86
+ enumerable: true,
87
+ writable: false,
88
+ configurable: false
89
+ });
90
+ Object.defineProperty(this, "docsUrl", {
91
+ value: slugDocsUrl(options.slug),
92
+ enumerable: true,
93
+ writable: false,
94
+ configurable: false
95
+ });
96
+ }
97
+ Object.setPrototypeOf(this, new.target.prototype);
98
+ if (props && typeof props === "object") {
99
+ let safeProps;
100
+ if (options?.slug !== void 0) {
101
+ const {
102
+ _tag: _,
103
+ type: _t,
104
+ name: _n,
105
+ message: _m,
106
+ stack: _s,
107
+ code: _c,
108
+ hint: _h,
109
+ docsUrl: _d,
110
+ ...rest
111
+ } = props;
112
+ safeProps = rest;
113
+ } else {
114
+ const {
115
+ _tag: _,
116
+ type: _t,
117
+ name: _n,
118
+ message: _m,
119
+ stack: _s,
120
+ ...rest
121
+ } = props;
122
+ safeProps = rest;
123
+ }
124
+ const hasUserCause = Object.prototype.hasOwnProperty.call(
125
+ safeProps,
126
+ "cause"
127
+ );
128
+ const userCause = hasUserCause ? safeProps.cause : void 0;
129
+ if (hasUserCause) {
130
+ delete safeProps.cause;
131
+ }
132
+ const hasOptionsCause = errorOptions?.cause !== void 0;
133
+ if (hasUserCause && hasOptionsCause) {
134
+ throw new TypeError(
135
+ "TaggedError: cannot provide 'cause' in props when also setting ErrorOptions.cause"
136
+ );
137
+ }
138
+ Object.assign(this, safeProps);
139
+ if (hasUserCause) {
140
+ this.cause = userCause;
141
+ }
142
+ if (hasOptionsCause) {
143
+ this.cause = errorOptions?.cause;
144
+ }
145
+ } else if (errorOptions?.cause !== void 0) {
146
+ this.cause = errorOptions.cause;
147
+ }
148
+ }
149
+ };
150
+ }
151
+ Object.defineProperty(TaggedError, Symbol.hasInstance, {
152
+ value: (instance) => instance instanceof InternalTaggedErrorBase
153
+ });
154
+ ((TaggedError2) => {
155
+ function isError(value) {
156
+ return value instanceof Error;
157
+ }
158
+ TaggedError2.isError = isError;
159
+ function isTaggedError(value) {
160
+ return value instanceof InternalTaggedErrorBase;
161
+ }
162
+ TaggedError2.isTaggedError = isTaggedError;
163
+ function match2(error, handlers) {
164
+ const tag2 = error._tag;
165
+ const handler = handlers[tag2];
166
+ return handler(
167
+ error
168
+ );
169
+ }
170
+ TaggedError2.match = match2;
171
+ function matchPartial(error, handlers, otherwise) {
172
+ const tag2 = error._tag;
173
+ const handler = handlers[tag2];
174
+ if (handler) {
175
+ return handler(
176
+ error
177
+ );
178
+ }
179
+ return otherwise(error);
180
+ }
181
+ TaggedError2.matchPartial = matchPartial;
182
+ })(TaggedError || (TaggedError = {}));
183
+
184
+ // src/errors.ts
185
+ function makeError(tag2, options) {
186
+ const messageGenerator = options?.message ?? (() => tag2);
187
+ const defaults = options?.defaults ?? {};
188
+ const BaseClass = TaggedError(tag2, {
189
+ message: (props) => messageGenerator({ ...defaults, ...props })
190
+ });
191
+ return class extends BaseClass {
192
+ constructor(props) {
193
+ super({ ...defaults, ...props });
194
+ Object.assign(this, { ...defaults, ...props });
195
+ }
196
+ };
197
+ }
198
+ var TimeoutError = class extends (/* @__PURE__ */ TaggedError("TimeoutError", {
199
+ slug: "runtime-step-timeout",
200
+ hint: "Increase the step's timeout option, or check why the upstream operation is slow.",
201
+ message: (p) => p.operation ? `TimeoutError: ${p.operation} timed out after ${p.ms}ms` : `TimeoutError: Operation timed out after ${p.ms}ms`
202
+ })) {
203
+ };
204
+ var RetryExhaustedError = class extends (/* @__PURE__ */ TaggedError("RetryExhaustedError", {
205
+ slug: "runtime-retry-exhausted",
206
+ hint: "All retry attempts failed. Inspect lastError and decide whether to surface it or compensate.",
207
+ message: (p) => p.operation ? `RetryExhaustedError: ${p.operation} failed after ${p.attempts} attempts` : `RetryExhaustedError: Operation failed after ${p.attempts} attempts`
208
+ })) {
209
+ };
210
+ var RateLimitError = class extends (/* @__PURE__ */ TaggedError("RateLimitError", {
211
+ slug: "runtime-rate-limit",
212
+ hint: "Wait retryAfterMs before retrying, or apply step.cache to deduplicate calls.",
213
+ message: (p) => p.limiterName ? `RateLimitError: Rate limit exceeded for ${p.limiterName}${p.retryAfterMs ? `, retry after ${p.retryAfterMs}ms` : ""}` : `RateLimitError: Rate limit exceeded${p.retryAfterMs ? `, retry after ${p.retryAfterMs}ms` : ""}`
214
+ })) {
215
+ };
216
+ var CircuitBreakerOpenError = class extends (/* @__PURE__ */ TaggedError(
217
+ "CircuitBreakerOpenError",
218
+ {
219
+ slug: "runtime-circuit-open",
220
+ hint: "The circuit is open. Wait for it to half-open or fall back to a degraded path.",
221
+ message: (p) => `CircuitBreakerOpenError: Circuit ${p.circuitName} is ${p.state ?? "OPEN"}${p.retryAfterMs ? `, retry after ${Math.ceil(p.retryAfterMs / 1e3)}s` : ""}`
222
+ }
223
+ )) {
224
+ };
225
+ var ValidationError = class extends (/* @__PURE__ */ TaggedError("ValidationError", {
226
+ message: (p) => `ValidationError: Invalid ${p.field} - ${p.reason}`
227
+ })) {
228
+ };
229
+ var NotFoundError = class extends (/* @__PURE__ */ TaggedError("NotFoundError", {
230
+ message: (p) => p.id ? `NotFoundError: ${p.resource} with id ${p.id} not found` : `NotFoundError: ${p.resource} not found`
231
+ })) {
232
+ };
233
+ var UnauthorizedError = class extends (/* @__PURE__ */ TaggedError("UnauthorizedError", {
234
+ message: (p) => p.reason ? `UnauthorizedError: ${p.reason}` : p.action && p.resource ? `UnauthorizedError: Not authorized to ${p.action} ${p.resource}` : "UnauthorizedError: Access denied"
235
+ })) {
236
+ };
237
+ var NetworkError = class extends (/* @__PURE__ */ TaggedError("NetworkError", {
238
+ message: (p) => p.url ? `NetworkError: ${p.reason} (${p.url})` : `NetworkError: ${p.reason}`
239
+ })) {
240
+ };
241
+ var CompensationError = class extends (/* @__PURE__ */ TaggedError("CompensationError", {
242
+ slug: "runtime-saga-compensation",
243
+ hint: "A saga compensation step failed. Inspect compensationError and ensure compensation is idempotent.",
244
+ message: (p) => `CompensationError: Failed to compensate step ${p.step}`
245
+ })) {
246
+ };
247
+ var UnexpectedError = class extends (/* @__PURE__ */ TaggedError("UnexpectedError", {
248
+ slug: "runtime-unexpected",
249
+ hint: "An unexpected exception escaped a step. Inspect cause; consider returning a typed Result instead of throwing.",
250
+ message: (p) => `UnexpectedError: ${p.cause instanceof Error ? p.cause.message : String(p.cause ?? "unknown")}`
251
+ })) {
252
+ };
253
+ var AWAITLY_SYSTEM_ERROR_CLASSES = [
254
+ TimeoutError,
255
+ RetryExhaustedError,
256
+ RateLimitError,
257
+ CircuitBreakerOpenError,
258
+ CompensationError,
259
+ UnexpectedError
260
+ ];
261
+ function isTimeoutError(error) {
262
+ return TaggedError.isTaggedError(error) && error._tag === "TimeoutError";
263
+ }
264
+ function isRetryExhaustedError(error) {
265
+ return TaggedError.isTaggedError(error) && error._tag === "RetryExhaustedError";
266
+ }
267
+ function isRateLimitError(error) {
268
+ return TaggedError.isTaggedError(error) && error._tag === "RateLimitError";
269
+ }
270
+ function isCircuitBreakerOpenError(error) {
271
+ return TaggedError.isTaggedError(error) && error._tag === "CircuitBreakerOpenError";
272
+ }
273
+ function isValidationError(error) {
274
+ return TaggedError.isTaggedError(error) && error._tag === "ValidationError";
275
+ }
276
+ function isNotFoundError(error) {
277
+ return TaggedError.isTaggedError(error) && error._tag === "NotFoundError";
278
+ }
279
+ function isUnauthorizedError(error) {
280
+ return TaggedError.isTaggedError(error) && error._tag === "UnauthorizedError";
281
+ }
282
+ function isNetworkError(error) {
283
+ return TaggedError.isTaggedError(error) && error._tag === "NetworkError";
284
+ }
285
+ function isCompensationError(error) {
286
+ return TaggedError.isTaggedError(error) && error._tag === "CompensationError";
287
+ }
288
+ function isAwaitlyError(error) {
289
+ if (!TaggedError.isTaggedError(error)) return false;
290
+ const tag2 = error._tag;
291
+ return [
292
+ "TimeoutError",
293
+ "RetryExhaustedError",
294
+ "RateLimitError",
295
+ "CircuitBreakerOpenError",
296
+ "ValidationError",
297
+ "NotFoundError",
298
+ "UnauthorizedError",
299
+ "NetworkError",
300
+ "CompensationError",
301
+ "UnexpectedError"
302
+ ].includes(tag2);
303
+ }
304
+
305
+ // src/result/index.ts
306
+ var PROMISE_REJECTED = "PROMISE_REJECTED";
307
+ var AWAITLY_UNEXPECTED = "AWAITLY_UNEXPECTED";
308
+ var AWAITLY_CANCELLED = "AWAITLY_CANCELLED";
309
+ var AWAITLY_TIMEOUT = "AWAITLY_TIMEOUT";
310
+ var tags = (...t) => t;
311
+ function ok(value) {
312
+ return { ok: true, value };
313
+ }
314
+ function err(error, options) {
315
+ const cause = options?.cause;
316
+ return { ok: false, error, ...cause !== void 0 ? { cause } : {} };
317
+ }
318
+ var isOk = (r) => r.ok;
319
+ var isErr = (r) => !r.ok;
320
+ var isUnexpectedError = (e) => e instanceof UnexpectedError || typeof e === "object" && e !== null && "_tag" in e && e._tag === "UnexpectedError";
321
+ var isPromiseRejectedError = (e) => typeof e === "object" && e !== null && "type" in e && e.type === PROMISE_REJECTED;
322
+ function matchError(errorOrHandlers, handlers) {
323
+ if (handlers === void 0) {
324
+ const h = errorOrHandlers;
325
+ return (e) => matchError(e, h);
326
+ }
327
+ const error = errorOrHandlers;
328
+ if (isUnexpectedError(error)) {
329
+ return handlers.UnexpectedError(error);
330
+ }
331
+ return handlers[error](error);
332
+ }
333
+ var UnwrapError = class extends Error {
334
+ error;
335
+ cause;
336
+ constructor(result) {
337
+ const errorStr = typeof result.error === "string" ? result.error : JSON.stringify(result.error);
338
+ super(`Attempted to unwrap an Err: ${errorStr}`);
339
+ this.name = "UnwrapError";
340
+ this.error = result.error;
341
+ this.cause = result.cause;
342
+ }
343
+ };
344
+ var unwrap = (r) => {
345
+ if (r.ok) return r.value;
346
+ throw new UnwrapError(r);
347
+ };
348
+ var unwrapOr = (r, defaultValue) => r.ok ? r.value : defaultValue;
349
+ var unwrapOrElse = (r, fn) => r.ok ? r.value : fn(r.error, r.cause);
350
+ var runOrThrow = (r) => unwrap(r);
351
+ var runOrThrowAsync = (ar) => Promise.resolve(ar).then(unwrap);
352
+ var runOrNull = (r) => r.ok ? r.value : null;
353
+ var runOrUndefined = (r) => r.ok ? r.value : void 0;
354
+ function from(fn, onError) {
355
+ try {
356
+ return ok(fn());
357
+ } catch (cause) {
358
+ return onError ? err(onError(cause), { cause }) : err(cause);
359
+ }
360
+ }
361
+ async function fromPromise(promise, onError) {
362
+ try {
363
+ return ok(await promise);
364
+ } catch (cause) {
365
+ return onError ? err(onError(cause), { cause }) : err(cause);
366
+ }
367
+ }
368
+ async function tryAsync(fn, onError) {
369
+ try {
370
+ return ok(await fn());
371
+ } catch (cause) {
372
+ return onError ? err(onError(cause), { cause }) : err(cause);
373
+ }
374
+ }
375
+ function fromNullable(value, onNull) {
376
+ return value != null ? ok(value) : err(onNull());
377
+ }
378
+ function map(r, fn) {
379
+ return r.ok ? ok(fn(r.value)) : r;
380
+ }
381
+ function mapError(r, fn) {
382
+ return r.ok ? r : err(fn(r.error, r.cause), { cause: r.cause });
383
+ }
384
+ function match(r, handlers) {
385
+ if (handlers === void 0) {
386
+ const h = r;
387
+ return (result) => match(result, h);
388
+ }
389
+ if (r.ok) return handlers.ok(r.value);
390
+ if (typeof handlers.err === "function") return handlers.err(r.error, r.cause);
391
+ const e = r.error;
392
+ const key = typeof e === "string" ? e : e?.type ?? e?._tag;
393
+ const handler = key === void 0 ? void 0 : handlers[key];
394
+ if (typeof handler === "function") return handler(e, r.cause);
395
+ throw new TypeError(
396
+ `match: no handler for error type "${String(key)}". Add a handler for it, or use the { ok, err } form for a catch-all.`
397
+ );
398
+ }
399
+ function andThen(r, fn) {
400
+ return r.ok ? fn(r.value) : r;
401
+ }
402
+ function tap(r, fn) {
403
+ if (r.ok) fn(r.value);
404
+ return r;
405
+ }
406
+ function tapError(r, fn) {
407
+ if (!r.ok) fn(r.error, r.cause);
408
+ return r;
409
+ }
410
+ function mapTry(r, fn, onError) {
411
+ if (!r.ok) return r;
412
+ try {
413
+ return ok(fn(r.value));
414
+ } catch (error) {
415
+ return err(onError(error), { cause: error });
416
+ }
417
+ }
418
+ function mapErrorTry(r, fn, onError) {
419
+ if (r.ok) return r;
420
+ try {
421
+ return err(fn(r.error), { cause: r.cause });
422
+ } catch (error) {
423
+ return err(onError(error), { cause: error });
424
+ }
425
+ }
426
+ function bimap(r, onOk, onErr) {
427
+ return r.ok ? ok(onOk(r.value)) : err(onErr(r.error, r.cause), { cause: r.cause });
428
+ }
429
+ function orElse(r, fn) {
430
+ return r.ok ? r : fn(r.error, r.cause);
431
+ }
432
+ async function orElseAsync(r, fn) {
433
+ return r.ok ? r : fn(r.error, r.cause);
434
+ }
435
+ function recover(r, fn) {
436
+ return r.ok ? ok(r.value) : ok(fn(r.error, r.cause));
437
+ }
438
+ async function recoverAsync(r, fn) {
439
+ const resolved = await r;
440
+ if (resolved.ok) return ok(resolved.value);
441
+ return ok(await fn(resolved.error, resolved.cause));
442
+ }
443
+ function hydrate(value) {
444
+ if (typeof value !== "object" || value === null) return null;
445
+ if (!("ok" in value)) return null;
446
+ const obj = value;
447
+ if (obj.ok === true && "value" in obj) {
448
+ return ok(obj.value);
449
+ }
450
+ if (obj.ok === false && "error" in obj) {
451
+ return err(obj.error, { cause: obj.cause });
452
+ }
453
+ return null;
454
+ }
455
+ function isSerializedResult(value) {
456
+ if (typeof value !== "object" || value === null) return false;
457
+ if (!("ok" in value)) return false;
458
+ const obj = value;
459
+ return obj.ok === true && "value" in obj || obj.ok === false && "error" in obj;
460
+ }
461
+ function all(results) {
462
+ const values = [];
463
+ for (const result of results) {
464
+ if (!result.ok) {
465
+ return result;
466
+ }
467
+ values.push(result.value);
468
+ }
469
+ return ok(values);
470
+ }
471
+ async function allAsync(results) {
472
+ const values = [];
473
+ for (const resultOrPromise of results) {
474
+ try {
475
+ const r = await resultOrPromise;
476
+ if (!r.ok) return r;
477
+ values.push(r.value);
478
+ } catch (reason) {
479
+ return err(
480
+ { type: PROMISE_REJECTED, cause: reason },
481
+ { cause: { type: "PROMISE_REJECTION", reason } }
482
+ );
483
+ }
484
+ }
485
+ return ok(values);
486
+ }
487
+ function allSettled(results) {
488
+ const values = [];
489
+ const errors = [];
490
+ for (const result of results) {
491
+ if (result.ok) {
492
+ values.push(result.value);
493
+ } else {
494
+ errors.push({ error: result.error, cause: result.cause });
495
+ }
496
+ }
497
+ if (errors.length > 0) {
498
+ return err(errors);
499
+ }
500
+ return ok(values);
501
+ }
502
+ async function allSettledAsync(results) {
503
+ const settled = await Promise.all(
504
+ results.map(
505
+ (item) => Promise.resolve(item).then((result) => ({ status: "result", result })).catch((reason) => ({
506
+ status: "rejected",
507
+ error: { type: PROMISE_REJECTED, cause: reason },
508
+ cause: { type: "PROMISE_REJECTION", reason }
509
+ }))
510
+ )
511
+ );
512
+ const values = [];
513
+ const errors = [];
514
+ for (const item of settled) {
515
+ if (item.status === "rejected") {
516
+ errors.push({ error: item.error, cause: item.cause });
517
+ } else if (item.result.ok) {
518
+ values.push(item.result.value);
519
+ } else {
520
+ errors.push({ error: item.result.error, cause: item.result.cause });
521
+ }
522
+ }
523
+ if (errors.length > 0) {
524
+ return err(errors);
525
+ }
526
+ return ok(values);
527
+ }
528
+ function partition(results) {
529
+ const values = [];
530
+ const errors = [];
531
+ for (const r of results) {
532
+ if (r.ok) values.push(r.value);
533
+ else errors.push(r.error);
534
+ }
535
+ return { values, errors };
536
+ }
537
+ function any(results) {
538
+ if (results.length === 0) {
539
+ return err({ type: "EMPTY_INPUT", message: "any() requires at least one Result" });
540
+ }
541
+ let firstErr;
542
+ for (const r of results) {
543
+ if (r.ok) return r;
544
+ if (!firstErr) firstErr = r;
545
+ }
546
+ return firstErr;
547
+ }
548
+ async function anyAsync(results) {
549
+ if (results.length === 0) {
550
+ return err({ type: "EMPTY_INPUT", message: "anyAsync() requires at least one Result" });
551
+ }
552
+ return new Promise((resolve) => {
553
+ let settled = false;
554
+ let pendingCount = results.length;
555
+ let firstError = null;
556
+ for (const item of results) {
557
+ Promise.resolve(item).catch(
558
+ (reason) => err(
559
+ { type: PROMISE_REJECTED, cause: reason },
560
+ { cause: { type: "PROMISE_REJECTION", reason } }
561
+ )
562
+ ).then((result) => {
563
+ if (settled) return;
564
+ if (result.ok) {
565
+ settled = true;
566
+ resolve(result);
567
+ return;
568
+ }
569
+ if (!firstError) firstError = result;
570
+ pendingCount--;
571
+ if (pendingCount === 0) {
572
+ resolve(firstError);
573
+ }
574
+ });
575
+ }
576
+ });
577
+ }
578
+ function zip(a, b) {
579
+ if (!a.ok) return a;
580
+ if (!b.ok) return b;
581
+ return ok([a.value, b.value]);
582
+ }
583
+ async function zipAsync(a, b) {
584
+ const wrapRejection = (p) => Promise.resolve(p).catch(
585
+ (reason) => err(
586
+ { type: PROMISE_REJECTED, cause: reason },
587
+ { cause: { type: "PROMISE_REJECTION", reason } }
588
+ )
589
+ );
590
+ const [ra, rb] = await Promise.all([wrapRejection(a), wrapRejection(b)]);
591
+ return zip(ra, rb);
592
+ }
593
+ function flatten(result) {
594
+ if (!result.ok) return result;
595
+ return result.value;
596
+ }
597
+ var DESERIALIZATION_ERROR = "DESERIALIZATION_ERROR";
598
+ function deserialize(value) {
599
+ if (typeof value !== "object" || value === null) {
600
+ return err({ type: DESERIALIZATION_ERROR, value });
601
+ }
602
+ if (!("ok" in value)) {
603
+ return err({ type: DESERIALIZATION_ERROR, value });
604
+ }
605
+ const obj = value;
606
+ if (obj.ok === true && "value" in obj) {
607
+ return ok(obj.value);
608
+ }
609
+ if (obj.ok === false && "error" in obj) {
610
+ return err(obj.error, { cause: obj.cause });
611
+ }
612
+ return err({ type: DESERIALIZATION_ERROR, value });
613
+ }
614
+ function serialize(result) {
615
+ return result.ok ? { ok: true, value: result.value } : { ok: false, error: result.error };
616
+ }
617
+ function matchErrorPartial(error, handlers, fallback2) {
618
+ if (isUnexpectedError(error)) {
619
+ const h2 = handlers.UnexpectedError;
620
+ return h2 ? h2(error) : fallback2(error);
621
+ }
622
+ const h = handlers[error];
623
+ return h ? h(error) : fallback2(error);
624
+ }
625
+
626
+ // src/di.ts
627
+ function withDeps(workflow, overrides) {
628
+ const forward = (method) => ((...args) => {
629
+ const last = args.at(-1);
630
+ const hasConfig = args.length > 0 && typeof last === "object" && last !== null && !Array.isArray(last) && typeof last !== "function";
631
+ const config = hasConfig ? last : void 0;
632
+ const head = hasConfig ? args.slice(0, -1) : args;
633
+ const mergedDeps = { ...overrides, ...config?.deps ?? {} };
634
+ const mergedConfig = config ? { ...config, deps: mergedDeps } : { deps: mergedDeps };
635
+ return workflow[method](...head, mergedConfig);
636
+ });
637
+ return {
638
+ run: forward("run"),
639
+ runWithState: forward("runWithState"),
640
+ withDeps(nextOverrides) {
641
+ return withDeps(workflow, { ...overrides, ...nextOverrides });
642
+ }
643
+ };
644
+ }
645
+
646
+ // src/duration.ts
647
+ function millis(ms) {
648
+ return { _tag: "Duration", millis: ms };
649
+ }
650
+ function seconds(s) {
651
+ return { _tag: "Duration", millis: s * 1e3 };
652
+ }
653
+ function minutes(m) {
654
+ return { _tag: "Duration", millis: m * 60 * 1e3 };
655
+ }
656
+ function hours(h) {
657
+ return { _tag: "Duration", millis: h * 60 * 60 * 1e3 };
658
+ }
659
+ function days(d) {
660
+ return { _tag: "Duration", millis: d * 24 * 60 * 60 * 1e3 };
661
+ }
662
+ var zero = { _tag: "Duration", millis: 0 };
663
+ var infinity = { _tag: "Duration", millis: Infinity };
664
+ function toMillis(duration) {
665
+ return duration.millis;
666
+ }
667
+ function toSeconds(duration) {
668
+ return duration.millis / 1e3;
669
+ }
670
+ function toMinutes(duration) {
671
+ return duration.millis / (60 * 1e3);
672
+ }
673
+ function toHours(duration) {
674
+ return duration.millis / (60 * 60 * 1e3);
675
+ }
676
+ function toDays(duration) {
677
+ return duration.millis / (24 * 60 * 60 * 1e3);
678
+ }
679
+ function add(a, b) {
680
+ return { _tag: "Duration", millis: a.millis + b.millis };
681
+ }
682
+ function subtract(a, b) {
683
+ return { _tag: "Duration", millis: Math.max(0, a.millis - b.millis) };
684
+ }
685
+ function multiply(duration, factor) {
686
+ return { _tag: "Duration", millis: duration.millis * factor };
687
+ }
688
+ function divide(duration, divisor) {
689
+ return { _tag: "Duration", millis: duration.millis / divisor };
690
+ }
691
+ function lessThan(a, b) {
692
+ return a.millis < b.millis;
693
+ }
694
+ function lessThanOrEqual(a, b) {
695
+ return a.millis <= b.millis;
696
+ }
697
+ function greaterThan(a, b) {
698
+ return a.millis > b.millis;
699
+ }
700
+ function greaterThanOrEqual(a, b) {
701
+ return a.millis >= b.millis;
702
+ }
703
+ function equals(a, b) {
704
+ return a.millis === b.millis;
705
+ }
706
+ function min(a, b) {
707
+ return a.millis <= b.millis ? a : b;
708
+ }
709
+ function max(a, b) {
710
+ return a.millis >= b.millis ? a : b;
711
+ }
712
+ function clamp(duration, minimum, maximum) {
713
+ return min(max(duration, minimum), maximum);
714
+ }
715
+ function isZero(duration) {
716
+ return duration.millis === 0;
717
+ }
718
+ function isInfinite(duration) {
719
+ return duration.millis === Infinity;
720
+ }
721
+ function isFinite(duration) {
722
+ return Number.isFinite(duration.millis) && duration.millis > 0;
723
+ }
724
+ function isDuration(value) {
725
+ return typeof value === "object" && value !== null && "_tag" in value && value._tag === "Duration" && "millis" in value && typeof value.millis === "number";
726
+ }
727
+ function format(duration) {
728
+ const ms = duration.millis;
729
+ if (ms === Infinity) return "\u221E";
730
+ if (ms === 0) return "0ms";
731
+ const days2 = Math.floor(ms / (24 * 60 * 60 * 1e3));
732
+ const hours2 = Math.floor(ms % (24 * 60 * 60 * 1e3) / (60 * 60 * 1e3));
733
+ const minutes2 = Math.floor(ms % (60 * 60 * 1e3) / (60 * 1e3));
734
+ const seconds2 = Math.floor(ms % (60 * 1e3) / 1e3);
735
+ const millis2 = ms % 1e3;
736
+ const parts = [];
737
+ if (days2 > 0) parts.push(`${days2}d`);
738
+ if (hours2 > 0) parts.push(`${hours2}h`);
739
+ if (minutes2 > 0) parts.push(`${minutes2}m`);
740
+ if (seconds2 > 0) parts.push(`${seconds2}s`);
741
+ if (millis2 > 0 && parts.length === 0) parts.push(`${millis2}ms`);
742
+ return parts.join(" ") || "0ms";
743
+ }
744
+ function parse(input) {
745
+ const match2 = input.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i);
746
+ if (!match2) return void 0;
747
+ const value = parseFloat(match2[1]);
748
+ const unit = match2[2].toLowerCase();
749
+ switch (unit) {
750
+ case "ms":
751
+ return millis(value);
752
+ case "s":
753
+ return seconds(value);
754
+ case "m":
755
+ return minutes(value);
756
+ case "h":
757
+ return hours(value);
758
+ case "d":
759
+ return days(value);
760
+ default:
761
+ return void 0;
762
+ }
763
+ }
764
+ var Duration = {
765
+ // Constructors
766
+ millis,
767
+ seconds,
768
+ minutes,
769
+ hours,
770
+ days,
771
+ zero,
772
+ infinity,
773
+ // Conversions
774
+ toMillis,
775
+ toSeconds,
776
+ toMinutes,
777
+ toHours,
778
+ toDays,
779
+ // Operations
780
+ add,
781
+ subtract,
782
+ multiply,
783
+ divide,
784
+ // Comparisons
785
+ lessThan,
786
+ lessThanOrEqual,
787
+ greaterThan,
788
+ greaterThanOrEqual,
789
+ equals,
790
+ min,
791
+ max,
792
+ clamp,
793
+ // Predicates
794
+ isZero,
795
+ isInfinite,
796
+ isFinite,
797
+ isDuration,
798
+ // Formatting
799
+ format,
800
+ parse
801
+ };
802
+
803
+ // src/core/bound-steps.ts
804
+ var isDepResultShaped = (value) => typeof value === "object" && value !== null && "ok" in value && typeof value.ok === "boolean" && (value.ok ? "value" in value : "error" in value);
805
+ var bindSteps = (deps, step) => {
806
+ const steps = {};
807
+ const invocationCounts = /* @__PURE__ */ new Map();
808
+ for (const key of Object.keys(deps)) {
809
+ const dep = deps[key];
810
+ if (typeof dep !== "function") continue;
811
+ steps[key] = (...args) => {
812
+ const count = (invocationCounts.get(key) ?? 0) + 1;
813
+ invocationCounts.set(key, count);
814
+ const stepKey = count === 1 ? key : `${key}#${count}`;
815
+ return step(stepKey, async () => {
816
+ const value = await dep(...args);
817
+ return isDepResultShaped(value) ? value : ok(value);
818
+ });
819
+ };
820
+ }
821
+ return steps;
822
+ };
823
+
824
+ // src/core/policies.ts
825
+ var toMs = (d) => typeof d === "number" ? d : toMillis(d);
826
+ var attemptCall = async (fn, args) => {
827
+ try {
828
+ const value = await fn(...args);
829
+ if (isDepResultShaped(value)) {
830
+ return value.ok ? { kind: "ok", value: value.value } : { kind: "err", error: value.error, result: value };
831
+ }
832
+ return { kind: "ok", value };
833
+ } catch (thrown) {
834
+ return { kind: "threw", thrown };
835
+ }
836
+ };
837
+ var named = (wrapped, source) => {
838
+ const name = source.name;
839
+ if (name) {
840
+ Object.defineProperty(wrapped, "name", { value: name, configurable: true });
841
+ }
842
+ return wrapped;
843
+ };
844
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
845
+ function retry(fn, options) {
846
+ const attempts = Math.max(1, Math.trunc(options.attempts));
847
+ const baseDelay = options.delay === void 0 ? 0 : toMs(options.delay);
848
+ const maxDelay = options.maxDelay === void 0 ? Infinity : toMs(options.maxDelay);
849
+ const backoff = options.backoff ?? "fixed";
850
+ const delayFor = (attempt) => {
851
+ const raw = backoff === "exponential" ? baseDelay * 2 ** (attempt - 1) : backoff === "linear" ? baseDelay * attempt : baseDelay;
852
+ return Math.min(raw, maxDelay);
853
+ };
854
+ const wrapped = async (...args) => {
855
+ let last = { kind: "threw", thrown: void 0 };
856
+ for (let attempt = 1; attempt <= attempts; attempt++) {
857
+ last = await attemptCall(fn, args);
858
+ if (last.kind === "ok") return ok(last.value);
859
+ const failure = last.kind === "err" ? last.error : last.thrown;
860
+ if (options.retryIf && !options.retryIf(failure)) break;
861
+ if (attempt < attempts) {
862
+ options.onRetry?.({ attempt, failure });
863
+ const ms = delayFor(attempt);
864
+ if (ms > 0) await sleep(ms);
865
+ }
866
+ }
867
+ if (last.kind === "err") return last.result;
868
+ throw last.thrown;
869
+ };
870
+ return named(wrapped, fn);
871
+ }
872
+ function timeout(fn, after) {
873
+ const ms = toMs(after);
874
+ const TIMED_OUT = /* @__PURE__ */ Symbol("timed-out");
875
+ const wrapped = async (...args) => {
876
+ let timer;
877
+ try {
878
+ const outcome = await Promise.race([
879
+ attemptCall(fn, args),
880
+ new Promise((resolve) => {
881
+ timer = setTimeout(() => resolve(TIMED_OUT), ms);
882
+ })
883
+ ]);
884
+ if (outcome === TIMED_OUT) {
885
+ return err(new TimeoutError({ operation: fn.name || void 0, ms }));
886
+ }
887
+ if (outcome.kind === "ok") return ok(outcome.value);
888
+ if (outcome.kind === "err") return outcome.result;
889
+ throw outcome.thrown;
890
+ } finally {
891
+ if (timer !== void 0) clearTimeout(timer);
892
+ }
893
+ };
894
+ return named(wrapped, fn);
895
+ }
896
+ function fallback(fn, onFailure) {
897
+ const wrapped = async (...args) => {
898
+ const outcome = await attemptCall(fn, args);
899
+ if (outcome.kind === "ok") return ok(outcome.value);
900
+ const failure = outcome.kind === "err" ? outcome.error : new UnexpectedError({ cause: outcome.thrown });
901
+ const recovered = await attemptCall(onFailure, [failure, ...args]);
902
+ if (recovered.kind === "ok") return ok(recovered.value);
903
+ if (recovered.kind === "err") return recovered.result;
904
+ throw recovered.thrown;
905
+ };
906
+ return named(wrapped, fn);
907
+ }
908
+
909
+ // src/core/index.ts
910
+ function parseDurationString(input) {
911
+ const match2 = input.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i);
912
+ if (!match2) return void 0;
913
+ const value = parseFloat(match2[1]);
914
+ const unit = match2[2].toLowerCase();
915
+ const multipliers = { ms: 1, s: 1e3, m: 6e4, h: 36e5, d: 864e5 };
916
+ return { _tag: "Duration", millis: value * (multipliers[unit] ?? 1) };
917
+ }
918
+ function defaultCatchUnexpected(cause) {
919
+ return new UnexpectedError({ cause });
920
+ }
921
+ function ok2(value) {
922
+ return { ok: true, value };
923
+ }
924
+ function err2(error, options) {
925
+ const cause = options?.cause;
926
+ return { ok: false, error, ...cause !== void 0 ? { cause } : {} };
927
+ }
928
+ function extractErrorTag(error) {
929
+ if (error == null) return "unknown";
930
+ if (typeof error === "string") return error.trim() || "unknown";
931
+ if (typeof error === "object") {
932
+ const tagged = error;
933
+ if (typeof tagged._tag === "string") {
934
+ const trimmed = tagged._tag.trim();
935
+ if (trimmed) return trimmed;
936
+ }
937
+ if (typeof tagged.tag === "string") {
938
+ const trimmed = tagged.tag.trim();
939
+ if (trimmed) return trimmed;
940
+ }
941
+ if (typeof tagged.code === "string") {
942
+ const trimmed = tagged.code.trim();
943
+ if (trimmed) return trimmed;
944
+ } else if (typeof tagged.code === "number") {
945
+ return String(tagged.code);
946
+ }
947
+ if (error instanceof Error && error.name) {
948
+ const trimmed = error.name.trim();
949
+ if (trimmed) return trimmed;
950
+ }
951
+ }
952
+ return "unknown";
953
+ }
954
+ function lookupErrorClassification(tag2, errorMeta) {
955
+ if (!errorMeta || !tag2) return void 0;
956
+ return errorMeta[tag2];
957
+ }
958
+ function extractStepMetadata(options) {
959
+ const { intent, domain, owner, tags: tags3, stateChanges, emits, calls } = options;
960
+ if (!intent && !domain && !owner && !tags3?.length && !stateChanges?.length && !emits?.length && !calls?.length) {
961
+ return void 0;
962
+ }
963
+ const metadata = {};
964
+ if (intent) metadata.intent = intent;
965
+ if (domain) metadata.domain = domain;
966
+ if (owner) metadata.owner = owner;
967
+ if (tags3?.length) metadata.tags = tags3;
968
+ if (stateChanges?.length) metadata.stateChanges = stateChanges;
969
+ if (emits?.length) metadata.emits = emits;
970
+ if (calls?.length) metadata.calls = calls;
971
+ return metadata;
972
+ }
973
+ function buildStepErrorPayload(error, errorMeta, origin, attempt, cumulativeDurationMs) {
974
+ const tag2 = extractErrorTag(error);
975
+ const classification = lookupErrorClassification(tag2, errorMeta);
976
+ const diagnostics = { tag: tag2, origin };
977
+ if (classification !== void 0) diagnostics.classification = classification;
978
+ if (attempt !== void 0) diagnostics.attempt = attempt;
979
+ if (cumulativeDurationMs !== void 0) diagnostics.cumulativeDurationMs = cumulativeDurationMs;
980
+ return diagnostics;
981
+ }
982
+ var STEP_TIMEOUT_MARKER = /* @__PURE__ */ Symbol.for("step_timeout_marker");
983
+ function isStepTimeoutError(e) {
984
+ if (typeof e !== "object" || e === null) {
985
+ return false;
986
+ }
987
+ if (e.type === "STEP_TIMEOUT") {
988
+ return true;
989
+ }
990
+ return STEP_TIMEOUT_MARKER in e;
991
+ }
992
+ function getStepTimeoutMeta(e) {
993
+ if (typeof e !== "object" || e === null) {
994
+ return void 0;
995
+ }
996
+ if (e.type === "STEP_TIMEOUT") {
997
+ const err3 = e;
998
+ return {
999
+ timeoutMs: err3.timeoutMs,
1000
+ stepName: err3.stepName,
1001
+ stepKey: err3.stepKey,
1002
+ attempt: err3.attempt
1003
+ };
1004
+ }
1005
+ if (STEP_TIMEOUT_MARKER in e) {
1006
+ return e[STEP_TIMEOUT_MARKER];
1007
+ }
1008
+ return void 0;
1009
+ }
1010
+ var EARLY_EXIT_SYMBOL = /* @__PURE__ */ Symbol("early-exit");
1011
+ function createEarlyExit(error, meta) {
1012
+ return {
1013
+ [EARLY_EXIT_SYMBOL]: true,
1014
+ error,
1015
+ meta
1016
+ };
1017
+ }
1018
+ function isEarlyExit(e) {
1019
+ return typeof e === "object" && e !== null && e[EARLY_EXIT_SYMBOL] === true;
1020
+ }
1021
+ var MAPPER_EXCEPTION_SYMBOL = /* @__PURE__ */ Symbol("mapper-exception");
1022
+ function createMapperException(thrown) {
1023
+ return { [MAPPER_EXCEPTION_SYMBOL]: true, thrown };
1024
+ }
1025
+ function isMapperException(e) {
1026
+ return typeof e === "object" && e !== null && e[MAPPER_EXCEPTION_SYMBOL] === true;
1027
+ }
1028
+ function calculateRetryDelay(attempt, options) {
1029
+ const { backoff, initialDelay, maxDelay, jitter } = options;
1030
+ let delay;
1031
+ switch (backoff) {
1032
+ case "fixed":
1033
+ delay = initialDelay;
1034
+ break;
1035
+ case "linear":
1036
+ delay = initialDelay * attempt;
1037
+ break;
1038
+ case "exponential":
1039
+ delay = initialDelay * Math.pow(2, attempt - 1);
1040
+ break;
1041
+ }
1042
+ delay = Math.min(delay, maxDelay);
1043
+ if (jitter) {
1044
+ const jitterAmount = delay * 0.25 * Math.random();
1045
+ delay = delay + jitterAmount;
1046
+ }
1047
+ return Math.floor(delay);
1048
+ }
1049
+ function sleep2(ms) {
1050
+ return new Promise((resolve) => setTimeout(resolve, ms));
1051
+ }
1052
+ var TIMEOUT_SYMBOL = /* @__PURE__ */ Symbol("timeout");
1053
+ var TIMEOUT_OPTION_SYMBOL = /* @__PURE__ */ Symbol("timeout-option");
1054
+ function isTimeoutOptionMarker(value) {
1055
+ return typeof value === "object" && value !== null && value[TIMEOUT_OPTION_SYMBOL] === true;
1056
+ }
1057
+ async function executeWithTimeout(operation, options, stepInfo, externalSignal) {
1058
+ const controller = new AbortController();
1059
+ const behavior = options.onTimeout ?? "error";
1060
+ const createTimeoutError = () => {
1061
+ if (typeof behavior === "function") {
1062
+ return behavior({
1063
+ name: stepInfo.name,
1064
+ key: stepInfo.key,
1065
+ ms: options.ms
1066
+ });
1067
+ }
1068
+ return options.error ?? {
1069
+ type: "STEP_TIMEOUT",
1070
+ stepName: stepInfo.name,
1071
+ stepKey: stepInfo.key,
1072
+ timeoutMs: options.ms,
1073
+ attempt: stepInfo.attempt
1074
+ };
1075
+ };
1076
+ let timeoutId;
1077
+ if (externalSignal?.aborted) {
1078
+ controller.abort(externalSignal.reason);
1079
+ }
1080
+ let externalAbortHandler;
1081
+ if (externalSignal && !externalSignal.aborted) {
1082
+ externalAbortHandler = () => controller.abort(externalSignal.reason);
1083
+ externalSignal.addEventListener("abort", externalAbortHandler, { once: true });
1084
+ }
1085
+ const timeoutPromise = new Promise((_, reject) => {
1086
+ timeoutId = setTimeout(() => {
1087
+ if (behavior !== "disconnect") {
1088
+ controller.abort();
1089
+ }
1090
+ if (behavior === "option") {
1091
+ reject({ [TIMEOUT_OPTION_SYMBOL]: true, ms: options.ms });
1092
+ return;
1093
+ }
1094
+ reject({ [TIMEOUT_SYMBOL]: true, error: createTimeoutError() });
1095
+ }, options.ms);
1096
+ });
1097
+ let operationPromise;
1098
+ if (options.signal) {
1099
+ operationPromise = Promise.resolve(
1100
+ operation(controller.signal)
1101
+ );
1102
+ } else {
1103
+ operationPromise = Promise.resolve(operation());
1104
+ }
1105
+ try {
1106
+ const result = await Promise.race([operationPromise, timeoutPromise]);
1107
+ return result;
1108
+ } catch (error) {
1109
+ if (typeof error === "object" && error !== null && error[TIMEOUT_OPTION_SYMBOL] === true) {
1110
+ throw { [TIMEOUT_OPTION_SYMBOL]: true, ms: options.ms };
1111
+ }
1112
+ if (typeof error === "object" && error !== null && error[TIMEOUT_SYMBOL] === true) {
1113
+ if (behavior === "disconnect") {
1114
+ operationPromise.catch(() => {
1115
+ });
1116
+ }
1117
+ const errorToThrow = error.error;
1118
+ if (typeof errorToThrow === "object" && errorToThrow !== null && errorToThrow.type !== "STEP_TIMEOUT") {
1119
+ const meta = {
1120
+ timeoutMs: options.ms,
1121
+ stepName: stepInfo.name,
1122
+ stepKey: stepInfo.key,
1123
+ attempt: stepInfo.attempt
1124
+ };
1125
+ if (STEP_TIMEOUT_MARKER in errorToThrow) {
1126
+ errorToThrow[STEP_TIMEOUT_MARKER] = meta;
1127
+ } else {
1128
+ Object.defineProperty(errorToThrow, STEP_TIMEOUT_MARKER, {
1129
+ value: meta,
1130
+ enumerable: false,
1131
+ writable: true,
1132
+ configurable: false
1133
+ });
1134
+ }
1135
+ }
1136
+ throw errorToThrow;
1137
+ }
1138
+ throw error;
1139
+ } finally {
1140
+ clearTimeout(timeoutId);
1141
+ if (externalAbortHandler && externalSignal) {
1142
+ externalSignal.removeEventListener("abort", externalAbortHandler);
1143
+ }
1144
+ }
1145
+ }
1146
+ var DEFAULT_RETRY_CONFIG = {
1147
+ backoff: "exponential",
1148
+ initialDelay: 100,
1149
+ maxDelay: 3e4,
1150
+ jitter: true,
1151
+ shouldRetry: () => true,
1152
+ onRetry: () => {
1153
+ }
1154
+ };
1155
+ async function runFn(fnOrDeps, optionsOrFn, maybeOptions) {
1156
+ if (typeof fnOrDeps !== "function") {
1157
+ const deps = fnOrDeps;
1158
+ const boundFn = optionsOrFn;
1159
+ if (typeof boundFn !== "function") {
1160
+ throw new TypeError(
1161
+ "[awaitly] run(deps, fn) requires a callback as the second argument. Example: run({ getUser }, async (s) => s.getUser(id))"
1162
+ );
1163
+ }
1164
+ const classicRun = runFn;
1165
+ return classicRun(
1166
+ ({ step }) => boundFn(bindSteps(deps, step), { step }),
1167
+ maybeOptions
1168
+ );
1169
+ }
1170
+ const fn = fnOrDeps;
1171
+ const options = optionsOrFn;
1172
+ const {
1173
+ onError,
1174
+ onEvent,
1175
+ catchUnexpected,
1176
+ workflowId: providedWorkflowId,
1177
+ workflowName,
1178
+ context,
1179
+ graph,
1180
+ _workflowSignal
1181
+ } = options && typeof options === "object" ? options : {};
1182
+ const workflowId = providedWorkflowId ?? crypto.randomUUID();
1183
+ const declaredIds = graph ? new Set(
1184
+ Array.isArray(graph) ? graph : graph.states.map((state) => state.semanticId ?? state.id)
1185
+ ) : void 0;
1186
+ const declaredPatterns = declaredIds ? [...declaredIds].filter((id) => id.includes("{")).map(
1187
+ (id) => new RegExp(
1188
+ `^${id.replaceAll(/[.*+?^$()[\]\\|]/g, String.raw`\$&`).replaceAll(/\{[^}]*\}/g, ".+")}$`
1189
+ )
1190
+ ) : void 0;
1191
+ const assertDeclared = (id, kind) => {
1192
+ if (!declaredIds || declaredIds.has(id)) return;
1193
+ if (declaredPatterns?.some((re) => re.test(id))) return;
1194
+ throw new Error(
1195
+ `[awaitly] ${kind} id "${id}" is not in the declared workflow graph. Declared ids: ${[...declaredIds].join(", ")}. Either add it to the graph or remove the graph option.`
1196
+ );
1197
+ };
1198
+ const effectiveCatchUnexpected = catchUnexpected ?? defaultCatchUnexpected;
1199
+ const activeScopeStack = [];
1200
+ let stepIdCounter = 0;
1201
+ const generateStepId = (stepKey) => {
1202
+ return stepKey ?? `step_${++stepIdCounter}`;
1203
+ };
1204
+ const emitEvent = (event) => {
1205
+ const eventWithContext = event.context !== void 0 || context === void 0 ? event : { ...event, context };
1206
+ const eventWithName = workflowName !== void 0 && eventWithContext.workflowName === void 0 ? { ...eventWithContext, workflowName } : eventWithContext;
1207
+ if (eventWithName.type === "step_success") {
1208
+ const stepId = eventWithName.stepId;
1209
+ for (let i = activeScopeStack.length - 1; i >= 0; i--) {
1210
+ const scope = activeScopeStack[i];
1211
+ if (scope.type === "race" && !scope.winnerId) {
1212
+ scope.winnerId = stepId;
1213
+ break;
1214
+ }
1215
+ }
1216
+ }
1217
+ onEvent?.(eventWithName, context);
1218
+ };
1219
+ const earlyExit = createEarlyExit;
1220
+ const isEarlyExitE = (e) => isEarlyExit(e);
1221
+ const wrapForStep = (error, _meta) => {
1222
+ return error;
1223
+ };
1224
+ const isResultLike = (value) => {
1225
+ if (typeof value === "function") return false;
1226
+ if (value && typeof value === "object" && "ok" in value) return true;
1227
+ if (value && typeof value === "object" && "then" in value && typeof value.then === "function") return true;
1228
+ return false;
1229
+ };
1230
+ try {
1231
+ let normalizeParallelOperations2 = function(rawOperations) {
1232
+ const out = {};
1233
+ for (const [key, value2] of Object.entries(rawOperations)) {
1234
+ if (typeof value2 === "function") {
1235
+ out[key] = value2;
1236
+ } else if (value2 && typeof value2 === "object" && "fn" in value2) {
1237
+ out[key] = value2.fn;
1238
+ } else {
1239
+ throw new TypeError(`step.all: operation "${key}" must be a function or { fn, errors? } object`);
1240
+ }
1241
+ }
1242
+ return out;
1243
+ }, executeParallelArray2 = function(name, operation) {
1244
+ const scopeId = `scope_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1245
+ return (async () => {
1246
+ const startTime = performance.now();
1247
+ let scopeEnded = false;
1248
+ activeScopeStack.push({ scopeId, type: "parallel" });
1249
+ const emitScopeEnd = () => {
1250
+ if (scopeEnded) return;
1251
+ scopeEnded = true;
1252
+ const idx = activeScopeStack.findIndex((s) => s.scopeId === scopeId);
1253
+ if (idx !== -1) activeScopeStack.splice(idx, 1);
1254
+ emitEvent({
1255
+ type: "scope_end",
1256
+ workflowId,
1257
+ scopeId,
1258
+ ts: Date.now(),
1259
+ durationMs: performance.now() - startTime
1260
+ });
1261
+ };
1262
+ emitEvent({
1263
+ type: "scope_start",
1264
+ workflowId,
1265
+ scopeId,
1266
+ scopeType: "parallel",
1267
+ name,
1268
+ ts: Date.now()
1269
+ });
1270
+ try {
1271
+ const result = await operation();
1272
+ emitScopeEnd();
1273
+ if (!result.ok) {
1274
+ onError?.(result.error, name, context);
1275
+ throw earlyExit(result.error, {
1276
+ origin: "result",
1277
+ resultCause: result.cause
1278
+ });
1279
+ }
1280
+ return result.value;
1281
+ } catch (error) {
1282
+ emitScopeEnd();
1283
+ throw error;
1284
+ }
1285
+ })();
1286
+ }, executeParallelNamed2 = function(operations, options2) {
1287
+ const keys = Object.keys(operations);
1288
+ const name = options2.name ?? `Parallel(${keys.join(", ")})`;
1289
+ const scopeId = `scope_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1290
+ return (async () => {
1291
+ const startTime = performance.now();
1292
+ let scopeEnded = false;
1293
+ activeScopeStack.push({ scopeId, type: "parallel" });
1294
+ const emitScopeEnd = () => {
1295
+ if (scopeEnded) return;
1296
+ scopeEnded = true;
1297
+ const idx = activeScopeStack.findIndex((s) => s.scopeId === scopeId);
1298
+ if (idx !== -1) activeScopeStack.splice(idx, 1);
1299
+ emitEvent({
1300
+ type: "scope_end",
1301
+ workflowId,
1302
+ scopeId,
1303
+ ts: Date.now(),
1304
+ durationMs: performance.now() - startTime
1305
+ });
1306
+ };
1307
+ emitEvent({
1308
+ type: "scope_start",
1309
+ workflowId,
1310
+ scopeId,
1311
+ scopeType: "parallel",
1312
+ name,
1313
+ ts: Date.now()
1314
+ });
1315
+ try {
1316
+ const results = await new Promise((resolve) => {
1317
+ if (keys.length === 0) {
1318
+ resolve([]);
1319
+ return;
1320
+ }
1321
+ let settled = false;
1322
+ let pendingCount = keys.length;
1323
+ const resultArray = new Array(keys.length);
1324
+ for (let i = 0; i < keys.length; i++) {
1325
+ const key = keys[i];
1326
+ const index = i;
1327
+ Promise.resolve(operations[key]()).catch((reason) => err2(
1328
+ { type: "PROMISE_REJECTED", cause: reason },
1329
+ { cause: { type: "PROMISE_REJECTION", reason } }
1330
+ )).then((result) => {
1331
+ if (settled) return;
1332
+ if (!result.ok) {
1333
+ settled = true;
1334
+ resolve([{ key, result }]);
1335
+ return;
1336
+ }
1337
+ resultArray[index] = { key, result };
1338
+ pendingCount--;
1339
+ if (pendingCount === 0) {
1340
+ resolve(resultArray);
1341
+ }
1342
+ });
1343
+ }
1344
+ });
1345
+ emitScopeEnd();
1346
+ const output = {};
1347
+ for (const { key, result } of results) {
1348
+ if (!result.ok) {
1349
+ onError?.(result.error, key, context);
1350
+ throw earlyExit(result.error, {
1351
+ origin: "result",
1352
+ resultCause: result.cause
1353
+ });
1354
+ }
1355
+ output[key] = result.value;
1356
+ }
1357
+ return output;
1358
+ } catch (error) {
1359
+ emitScopeEnd();
1360
+ throw error;
1361
+ }
1362
+ })();
1363
+ };
1364
+ var normalizeParallelOperations = normalizeParallelOperations2, executeParallelArray = executeParallelArray2, executeParallelNamed = executeParallelNamed2;
1365
+ const stepFn = (id, operationOrResult, stepOptions2) => {
1366
+ return (async () => {
1367
+ if (typeof id !== "string" || id.length === 0) {
1368
+ throw new Error(
1369
+ '[awaitly] step() requires an explicit string ID as the first argument. Example: step("fetchUser", () => fetchUser(id))'
1370
+ );
1371
+ }
1372
+ assertDeclared(id, "step");
1373
+ const parsedOptions = stepOptions2 ?? {};
1374
+ const stepMetadata = extractStepMetadata(parsedOptions);
1375
+ const stepName = id;
1376
+ const stepKey = parsedOptions.key ?? id;
1377
+ const explicitKey = parsedOptions.key ?? id;
1378
+ const { description: stepDescription, retry: retryConfig, timeout: timeoutConfig } = parsedOptions;
1379
+ const stepId = generateStepId(stepKey);
1380
+ const hasEventListeners = onEvent;
1381
+ const overallStartTime = hasEventListeners ? performance.now() : 0;
1382
+ const isDirectResult = isResultLike(operationOrResult);
1383
+ const operation = isDirectResult ? () => operationOrResult : operationOrResult;
1384
+ const maxAttempts = Math.max(1, retryConfig?.attempts ?? 1);
1385
+ const effectiveRetry = {
1386
+ attempts: maxAttempts,
1387
+ backoff: retryConfig?.backoff ?? DEFAULT_RETRY_CONFIG.backoff,
1388
+ initialDelay: retryConfig?.initialDelay ?? DEFAULT_RETRY_CONFIG.initialDelay,
1389
+ maxDelay: retryConfig?.maxDelay ?? DEFAULT_RETRY_CONFIG.maxDelay,
1390
+ jitter: retryConfig?.jitter ?? DEFAULT_RETRY_CONFIG.jitter,
1391
+ shouldRetry: retryConfig?.shouldRetry ?? DEFAULT_RETRY_CONFIG.shouldRetry,
1392
+ onRetry: retryConfig?.onRetry ?? DEFAULT_RETRY_CONFIG.onRetry
1393
+ };
1394
+ if (onEvent) {
1395
+ emitEvent({
1396
+ type: "step_start",
1397
+ workflowId,
1398
+ stepId,
1399
+ stepKey,
1400
+ name: stepName,
1401
+ description: stepDescription,
1402
+ ts: Date.now(),
1403
+ ...stepMetadata && { metadata: stepMetadata }
1404
+ });
1405
+ }
1406
+ let lastResult;
1407
+ for (let attempt = 1; attempt <= effectiveRetry.attempts; attempt++) {
1408
+ const attemptStartTime = hasEventListeners ? performance.now() : 0;
1409
+ try {
1410
+ let result;
1411
+ if (timeoutConfig) {
1412
+ result = await executeWithTimeout(
1413
+ operation,
1414
+ timeoutConfig,
1415
+ { name: stepName, key: stepKey, attempt },
1416
+ _workflowSignal
1417
+ );
1418
+ } else {
1419
+ result = await operation();
1420
+ }
1421
+ if (result.ok) {
1422
+ const durationMs = performance.now() - overallStartTime;
1423
+ emitEvent({
1424
+ type: "step_success",
1425
+ workflowId,
1426
+ stepId,
1427
+ stepKey,
1428
+ name: stepName,
1429
+ description: stepDescription,
1430
+ ts: Date.now(),
1431
+ durationMs,
1432
+ ...stepMetadata && { metadata: stepMetadata }
1433
+ });
1434
+ if (explicitKey) {
1435
+ emitEvent({
1436
+ type: "step_complete",
1437
+ workflowId,
1438
+ stepKey: explicitKey,
1439
+ name: stepName,
1440
+ description: stepDescription,
1441
+ ts: Date.now(),
1442
+ durationMs,
1443
+ result,
1444
+ ...stepMetadata && { metadata: stepMetadata }
1445
+ });
1446
+ }
1447
+ return result.value;
1448
+ }
1449
+ lastResult = result;
1450
+ if (attempt < effectiveRetry.attempts && effectiveRetry.shouldRetry(result.error, attempt)) {
1451
+ const delay = calculateRetryDelay(attempt, effectiveRetry);
1452
+ emitEvent({
1453
+ type: "step_retry",
1454
+ workflowId,
1455
+ stepId,
1456
+ stepKey,
1457
+ name: stepName,
1458
+ ts: Date.now(),
1459
+ attempt: attempt + 1,
1460
+ maxAttempts: effectiveRetry.attempts,
1461
+ delayMs: delay,
1462
+ error: result.error,
1463
+ ...stepMetadata && { metadata: stepMetadata },
1464
+ diagnostics: buildStepErrorPayload(result.error, parsedOptions.errorMeta, "result", attempt, performance.now() - overallStartTime)
1465
+ });
1466
+ effectiveRetry.onRetry(result.error, attempt, delay);
1467
+ await sleep2(delay);
1468
+ continue;
1469
+ }
1470
+ if (effectiveRetry.attempts > 1) {
1471
+ emitEvent({
1472
+ type: "step_retries_exhausted",
1473
+ workflowId,
1474
+ stepId,
1475
+ stepKey,
1476
+ name: stepName,
1477
+ ts: Date.now(),
1478
+ durationMs: performance.now() - overallStartTime,
1479
+ attempts: attempt,
1480
+ lastError: result.error,
1481
+ ...stepMetadata && { metadata: stepMetadata },
1482
+ diagnostics: buildStepErrorPayload(result.error, parsedOptions.errorMeta, "result", attempt, performance.now() - overallStartTime)
1483
+ });
1484
+ }
1485
+ break;
1486
+ } catch (thrown) {
1487
+ const durationMs = performance.now() - attemptStartTime;
1488
+ if (isTimeoutOptionMarker(thrown)) {
1489
+ const timeoutMs = thrown.ms;
1490
+ emitEvent({
1491
+ type: "step_timeout",
1492
+ workflowId,
1493
+ stepId,
1494
+ stepKey,
1495
+ name: stepName,
1496
+ ts: Date.now(),
1497
+ timeoutMs,
1498
+ attempt,
1499
+ ...stepMetadata && { metadata: stepMetadata },
1500
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt)
1501
+ });
1502
+ emitEvent({
1503
+ type: "step_success",
1504
+ workflowId,
1505
+ stepId,
1506
+ stepKey,
1507
+ name: stepName,
1508
+ description: stepDescription,
1509
+ ts: Date.now(),
1510
+ durationMs: performance.now() - overallStartTime,
1511
+ ...stepMetadata && { metadata: stepMetadata }
1512
+ });
1513
+ if (explicitKey) {
1514
+ emitEvent({
1515
+ type: "step_complete",
1516
+ workflowId,
1517
+ stepKey: explicitKey,
1518
+ name: stepName,
1519
+ description: stepDescription,
1520
+ ts: Date.now(),
1521
+ durationMs: performance.now() - overallStartTime,
1522
+ result: ok2(void 0),
1523
+ ...stepMetadata && { metadata: stepMetadata }
1524
+ });
1525
+ }
1526
+ return void 0;
1527
+ }
1528
+ if (isEarlyExitE(thrown)) {
1529
+ emitEvent({
1530
+ type: "step_aborted",
1531
+ workflowId,
1532
+ stepId,
1533
+ stepKey,
1534
+ name: stepName,
1535
+ description: stepDescription,
1536
+ ts: Date.now(),
1537
+ durationMs,
1538
+ ...stepMetadata && { metadata: stepMetadata }
1539
+ });
1540
+ throw thrown;
1541
+ }
1542
+ if (isStepTimeoutError(thrown)) {
1543
+ const timeoutMeta = getStepTimeoutMeta(thrown);
1544
+ const timeoutMs = timeoutConfig?.ms ?? timeoutMeta?.timeoutMs ?? 0;
1545
+ emitEvent({
1546
+ type: "step_timeout",
1547
+ workflowId,
1548
+ stepId,
1549
+ stepKey,
1550
+ name: stepName,
1551
+ ts: Date.now(),
1552
+ timeoutMs,
1553
+ attempt,
1554
+ ...stepMetadata && { metadata: stepMetadata },
1555
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt)
1556
+ });
1557
+ if (attempt < effectiveRetry.attempts && effectiveRetry.shouldRetry(thrown, attempt)) {
1558
+ const delay = calculateRetryDelay(attempt, effectiveRetry);
1559
+ emitEvent({
1560
+ type: "step_retry",
1561
+ workflowId,
1562
+ stepId,
1563
+ stepKey,
1564
+ name: stepName,
1565
+ ts: Date.now(),
1566
+ attempt: attempt + 1,
1567
+ maxAttempts: effectiveRetry.attempts,
1568
+ delayMs: delay,
1569
+ error: thrown,
1570
+ ...stepMetadata && { metadata: stepMetadata },
1571
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt, performance.now() - overallStartTime)
1572
+ });
1573
+ effectiveRetry.onRetry(thrown, attempt, delay);
1574
+ await sleep2(delay);
1575
+ continue;
1576
+ }
1577
+ if (effectiveRetry.attempts > 1) {
1578
+ emitEvent({
1579
+ type: "step_retries_exhausted",
1580
+ workflowId,
1581
+ stepId,
1582
+ stepKey,
1583
+ name: stepName,
1584
+ ts: Date.now(),
1585
+ durationMs: performance.now() - overallStartTime,
1586
+ attempts: attempt,
1587
+ lastError: thrown,
1588
+ ...stepMetadata && { metadata: stepMetadata },
1589
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt, performance.now() - overallStartTime)
1590
+ });
1591
+ }
1592
+ const totalDurationMs3 = performance.now() - overallStartTime;
1593
+ emitEvent({
1594
+ type: "step_error",
1595
+ workflowId,
1596
+ stepId,
1597
+ stepKey,
1598
+ name: stepName,
1599
+ description: stepDescription,
1600
+ ts: Date.now(),
1601
+ durationMs: totalDurationMs3,
1602
+ error: thrown,
1603
+ ...stepMetadata && { metadata: stepMetadata },
1604
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt, totalDurationMs3)
1605
+ });
1606
+ if (explicitKey) {
1607
+ emitEvent({
1608
+ type: "step_complete",
1609
+ workflowId,
1610
+ stepKey: explicitKey,
1611
+ name: stepName,
1612
+ description: stepDescription,
1613
+ ts: Date.now(),
1614
+ durationMs: totalDurationMs3,
1615
+ result: err2(thrown, { cause: thrown }),
1616
+ meta: { origin: "throw", thrown },
1617
+ ...stepMetadata && { metadata: stepMetadata }
1618
+ });
1619
+ }
1620
+ onError?.(thrown, stepName, context);
1621
+ throw earlyExit(thrown, { origin: "throw", thrown });
1622
+ }
1623
+ if (attempt < effectiveRetry.attempts && effectiveRetry.shouldRetry(thrown, attempt)) {
1624
+ const delay = calculateRetryDelay(attempt, effectiveRetry);
1625
+ emitEvent({
1626
+ type: "step_retry",
1627
+ workflowId,
1628
+ stepId,
1629
+ stepKey,
1630
+ name: stepName,
1631
+ ts: Date.now(),
1632
+ attempt: attempt + 1,
1633
+ maxAttempts: effectiveRetry.attempts,
1634
+ delayMs: delay,
1635
+ error: thrown,
1636
+ ...stepMetadata && { metadata: stepMetadata },
1637
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "throw", attempt, performance.now() - overallStartTime)
1638
+ });
1639
+ effectiveRetry.onRetry(thrown, attempt, delay);
1640
+ await sleep2(delay);
1641
+ continue;
1642
+ }
1643
+ if (effectiveRetry.attempts > 1 && !isStepTimeoutError(thrown)) {
1644
+ emitEvent({
1645
+ type: "step_retries_exhausted",
1646
+ workflowId,
1647
+ stepId,
1648
+ stepKey,
1649
+ name: stepName,
1650
+ ts: Date.now(),
1651
+ durationMs: performance.now() - overallStartTime,
1652
+ attempts: attempt,
1653
+ lastError: thrown,
1654
+ ...stepMetadata && { metadata: stepMetadata },
1655
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "throw", attempt, performance.now() - overallStartTime)
1656
+ });
1657
+ }
1658
+ const totalDurationMs2 = performance.now() - overallStartTime;
1659
+ let mappedError;
1660
+ try {
1661
+ mappedError = effectiveCatchUnexpected(thrown);
1662
+ } catch (mapperError) {
1663
+ throw createMapperException(mapperError);
1664
+ }
1665
+ emitEvent({
1666
+ type: "step_error",
1667
+ workflowId,
1668
+ stepId,
1669
+ stepKey,
1670
+ name: stepName,
1671
+ description: stepDescription,
1672
+ ts: Date.now(),
1673
+ durationMs: totalDurationMs2,
1674
+ error: mappedError,
1675
+ ...stepMetadata && { metadata: stepMetadata },
1676
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "throw", attempt, totalDurationMs2)
1677
+ });
1678
+ if (explicitKey) {
1679
+ emitEvent({
1680
+ type: "step_complete",
1681
+ workflowId,
1682
+ stepKey: explicitKey,
1683
+ name: stepName,
1684
+ description: stepDescription,
1685
+ ts: Date.now(),
1686
+ durationMs: totalDurationMs2,
1687
+ result: err2(mappedError, { cause: thrown }),
1688
+ meta: { origin: "throw", thrown },
1689
+ ...stepMetadata && { metadata: stepMetadata }
1690
+ });
1691
+ }
1692
+ onError?.(mappedError, stepName, context);
1693
+ throw earlyExit(mappedError, { origin: "throw", thrown });
1694
+ }
1695
+ }
1696
+ const errorResult = lastResult;
1697
+ const totalDurationMs = performance.now() - overallStartTime;
1698
+ const wrappedError = wrapForStep(errorResult.error, {
1699
+ origin: "result",
1700
+ resultCause: errorResult.cause
1701
+ });
1702
+ emitEvent({
1703
+ type: "step_error",
1704
+ workflowId,
1705
+ stepId,
1706
+ stepKey,
1707
+ name: stepName,
1708
+ description: stepDescription,
1709
+ ts: Date.now(),
1710
+ durationMs: totalDurationMs,
1711
+ error: wrappedError,
1712
+ ...stepMetadata && { metadata: stepMetadata },
1713
+ diagnostics: buildStepErrorPayload(errorResult.error, parsedOptions.errorMeta, "result", effectiveRetry.attempts, totalDurationMs)
1714
+ });
1715
+ if (explicitKey) {
1716
+ emitEvent({
1717
+ type: "step_complete",
1718
+ workflowId,
1719
+ stepKey: explicitKey,
1720
+ name: stepName,
1721
+ description: stepDescription,
1722
+ ts: Date.now(),
1723
+ durationMs: totalDurationMs,
1724
+ result: errorResult,
1725
+ meta: { origin: "result", resultCause: errorResult.cause },
1726
+ ...stepMetadata && { metadata: stepMetadata }
1727
+ });
1728
+ }
1729
+ onError?.(wrappedError, stepName, context);
1730
+ throw earlyExit(wrappedError, {
1731
+ origin: "result",
1732
+ resultCause: errorResult.cause
1733
+ });
1734
+ })();
1735
+ };
1736
+ stepFn.try = (id, operation, opts) => {
1737
+ if (typeof id !== "string" || id.length === 0) {
1738
+ throw new Error(
1739
+ '[awaitly] step.try() requires an explicit string ID as the first argument. Example: step.try("parse", () => JSON.parse(str), { error: "PARSE_ERROR" })'
1740
+ );
1741
+ }
1742
+ assertDeclared(id, "step");
1743
+ const mapToError = "error" in opts ? () => opts.error : opts.onError;
1744
+ if (opts.retry || opts.timeout) {
1745
+ return stepFn.retry(
1746
+ id,
1747
+ async () => {
1748
+ try {
1749
+ return ok2(await operation());
1750
+ } catch (cause) {
1751
+ return err2(mapToError(cause), { cause });
1752
+ }
1753
+ },
1754
+ {
1755
+ attempts: opts.retry?.attempts ?? 1,
1756
+ ...opts.retry ?? {},
1757
+ key: opts.key,
1758
+ timeout: opts.timeout
1759
+ }
1760
+ );
1761
+ }
1762
+ const stepKey = opts.key ?? id;
1763
+ const stepName = id;
1764
+ const stepId = id;
1765
+ const hasEventListeners = onEvent;
1766
+ return (async () => {
1767
+ const startTime = hasEventListeners ? performance.now() : 0;
1768
+ if (onEvent) {
1769
+ emitEvent({
1770
+ type: "step_start",
1771
+ workflowId,
1772
+ stepId,
1773
+ stepKey,
1774
+ name: stepName,
1775
+ ts: Date.now()
1776
+ });
1777
+ }
1778
+ try {
1779
+ const value2 = await operation();
1780
+ const durationMs = performance.now() - startTime;
1781
+ emitEvent({
1782
+ type: "step_success",
1783
+ workflowId,
1784
+ stepId,
1785
+ stepKey,
1786
+ name: stepName,
1787
+ ts: Date.now(),
1788
+ durationMs
1789
+ });
1790
+ if (stepKey) {
1791
+ emitEvent({
1792
+ type: "step_complete",
1793
+ workflowId,
1794
+ stepKey,
1795
+ name: stepName,
1796
+ ts: Date.now(),
1797
+ durationMs,
1798
+ result: ok2(value2)
1799
+ });
1800
+ }
1801
+ return value2;
1802
+ } catch (error) {
1803
+ const mapped = mapToError(error);
1804
+ const durationMs = performance.now() - startTime;
1805
+ const wrappedError = wrapForStep(mapped, { origin: "throw", thrown: error });
1806
+ emitEvent({
1807
+ type: "step_error",
1808
+ workflowId,
1809
+ stepId,
1810
+ stepKey,
1811
+ name: stepName,
1812
+ ts: Date.now(),
1813
+ durationMs,
1814
+ error: wrappedError
1815
+ });
1816
+ if (stepKey) {
1817
+ emitEvent({
1818
+ type: "step_complete",
1819
+ workflowId,
1820
+ stepKey,
1821
+ name: stepName,
1822
+ ts: Date.now(),
1823
+ durationMs,
1824
+ result: err2(mapped, { cause: error }),
1825
+ meta: { origin: "throw", thrown: error }
1826
+ });
1827
+ }
1828
+ onError?.(wrappedError, stepName, context);
1829
+ throw earlyExit(wrappedError, { origin: "throw", thrown: error });
1830
+ }
1831
+ })();
1832
+ };
1833
+ stepFn.fromResult = (id, operation, opts) => {
1834
+ if (typeof id !== "string" || id.length === 0) {
1835
+ throw new Error(
1836
+ '[awaitly] step.fromResult() requires an explicit string ID as the first argument. Example: step.fromResult("callProvider", () => callProvider(input), { onError: (e) => ({ type: "FAILED" }) })'
1837
+ );
1838
+ }
1839
+ assertDeclared(id, "step");
1840
+ const stepKey = opts.key ?? id;
1841
+ const stepName = id;
1842
+ const stepId = id;
1843
+ const mapToError = "error" in opts ? () => opts.error : opts.onError;
1844
+ const hasEventListeners = onEvent;
1845
+ return (async () => {
1846
+ const startTime = hasEventListeners ? performance.now() : 0;
1847
+ if (onEvent) {
1848
+ emitEvent({
1849
+ type: "step_start",
1850
+ workflowId,
1851
+ stepId,
1852
+ stepKey,
1853
+ name: stepName,
1854
+ ts: Date.now()
1855
+ });
1856
+ }
1857
+ const result = await operation();
1858
+ if (result.ok) {
1859
+ const durationMs = performance.now() - startTime;
1860
+ emitEvent({
1861
+ type: "step_success",
1862
+ workflowId,
1863
+ stepId,
1864
+ stepKey,
1865
+ name: stepName,
1866
+ ts: Date.now(),
1867
+ durationMs
1868
+ });
1869
+ if (stepKey) {
1870
+ emitEvent({
1871
+ type: "step_complete",
1872
+ workflowId,
1873
+ stepKey,
1874
+ name: stepName,
1875
+ ts: Date.now(),
1876
+ durationMs,
1877
+ result: ok2(result.value)
1878
+ });
1879
+ }
1880
+ return result.value;
1881
+ } else {
1882
+ const mapped = mapToError(result.error);
1883
+ const durationMs = performance.now() - startTime;
1884
+ const wrappedError = wrapForStep(mapped, {
1885
+ origin: "result",
1886
+ resultCause: result.error
1887
+ });
1888
+ emitEvent({
1889
+ type: "step_error",
1890
+ workflowId,
1891
+ stepId,
1892
+ stepKey,
1893
+ name: stepName,
1894
+ ts: Date.now(),
1895
+ durationMs,
1896
+ error: wrappedError
1897
+ });
1898
+ if (stepKey) {
1899
+ emitEvent({
1900
+ type: "step_complete",
1901
+ workflowId,
1902
+ stepKey,
1903
+ name: stepName,
1904
+ ts: Date.now(),
1905
+ durationMs,
1906
+ result: err2(mapped, { cause: result.error }),
1907
+ meta: { origin: "result", resultCause: result.error }
1908
+ });
1909
+ }
1910
+ onError?.(wrappedError, stepName, context);
1911
+ throw earlyExit(wrappedError, {
1912
+ origin: "result",
1913
+ resultCause: result.error
1914
+ });
1915
+ }
1916
+ })();
1917
+ };
1918
+ stepFn.fromNullable = (id, operation, onNull, options2) => {
1919
+ if (typeof id !== "string" || id.length === 0) {
1920
+ throw new Error(
1921
+ '[awaitly] step.fromNullable() requires an explicit string ID as the first argument. Example: step.fromNullable("getUser", () => db.find(id), () => ({ type: "NOT_FOUND" }))'
1922
+ );
1923
+ }
1924
+ return stepFn(
1925
+ id,
1926
+ async () => {
1927
+ const value2 = await operation();
1928
+ return value2 != null ? ok2(value2) : err2(onNull());
1929
+ },
1930
+ options2
1931
+ );
1932
+ };
1933
+ stepFn.retry = (id, operation, options2) => {
1934
+ if (typeof id !== "string" || id.length === 0) {
1935
+ throw new Error(
1936
+ '[awaitly] step.retry() requires an explicit string ID as the first argument. Example: step.retry("fetchData", () => fetchData(), { attempts: 3 })'
1937
+ );
1938
+ }
1939
+ return stepFn(id, operation, {
1940
+ key: options2.key ?? id,
1941
+ retry: {
1942
+ attempts: options2.attempts,
1943
+ backoff: options2.backoff,
1944
+ initialDelay: options2.initialDelay,
1945
+ maxDelay: options2.maxDelay,
1946
+ jitter: options2.jitter,
1947
+ shouldRetry: options2.shouldRetry,
1948
+ onRetry: options2.onRetry
1949
+ },
1950
+ timeout: options2.timeout
1951
+ });
1952
+ };
1953
+ stepFn.withTimeout = (id, operation, options2) => {
1954
+ if (typeof id !== "string" || id.length === 0) {
1955
+ throw new Error(
1956
+ '[awaitly] step.withTimeout() requires an explicit string ID as the first argument. Example: step.withTimeout("slowOp", () => slowOp(), { ms: 5000 })'
1957
+ );
1958
+ }
1959
+ return stepFn(
1960
+ id,
1961
+ operation,
1962
+ {
1963
+ key: options2.key ?? id,
1964
+ timeout: options2
1965
+ }
1966
+ );
1967
+ };
1968
+ stepFn.sleep = (id, duration, options2) => {
1969
+ if (typeof id !== "string" || id.length === 0) {
1970
+ throw new Error(
1971
+ '[awaitly] step.sleep() requires an explicit string ID as the first argument. Example: step.sleep("delay", "5s")'
1972
+ );
1973
+ }
1974
+ const d = typeof duration === "string" ? parseDurationString(duration) : duration;
1975
+ if (!d) {
1976
+ throw new Error(`step.sleep: invalid duration '${duration}'`);
1977
+ }
1978
+ const ms = d.millis;
1979
+ const userSignal = options2?.signal;
1980
+ return stepFn(
1981
+ id,
1982
+ async () => {
1983
+ if (_workflowSignal?.aborted || userSignal?.aborted) {
1984
+ const e = new Error("Sleep aborted");
1985
+ e.name = "AbortError";
1986
+ throw e;
1987
+ }
1988
+ return new Promise((resolve, reject) => {
1989
+ const state = { timeoutId: void 0 };
1990
+ const onAbort = () => {
1991
+ if (state.timeoutId) clearTimeout(state.timeoutId);
1992
+ const e = new Error("Sleep aborted");
1993
+ e.name = "AbortError";
1994
+ reject(e);
1995
+ };
1996
+ _workflowSignal?.addEventListener("abort", onAbort, { once: true });
1997
+ userSignal?.addEventListener("abort", onAbort, { once: true });
1998
+ state.timeoutId = setTimeout(() => {
1999
+ _workflowSignal?.removeEventListener("abort", onAbort);
2000
+ userSignal?.removeEventListener("abort", onAbort);
2001
+ resolve(ok2(void 0));
2002
+ }, ms);
2003
+ });
2004
+ },
2005
+ {
2006
+ key: options2?.key ?? id,
2007
+ description: options2?.description
2008
+ }
2009
+ );
2010
+ };
2011
+ stepFn.all = ((...args) => {
2012
+ if (typeof args[0] !== "string") {
2013
+ throw new TypeError(
2014
+ "step.all(name, ...): first argument must be a string (step name). Example: step.all('Fetch data', { user: () => fetchUser(), posts: () => fetchPosts() })"
2015
+ );
2016
+ }
2017
+ const name = args[0];
2018
+ const second = args[1];
2019
+ if (typeof second === "function") {
2020
+ return executeParallelArray2(name, second);
2021
+ }
2022
+ if (second && typeof second === "object" && !Array.isArray(second)) {
2023
+ const rawOperations = second;
2024
+ const normalizedOperations = normalizeParallelOperations2(rawOperations);
2025
+ return executeParallelNamed2(normalizedOperations, { name });
2026
+ }
2027
+ throw new TypeError(
2028
+ "step.all(name, ...): second argument must be a function (array form) or an object of operations (object form)."
2029
+ );
2030
+ });
2031
+ stepFn.race = (name, operation) => {
2032
+ const scopeId = `scope_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
2033
+ return (async () => {
2034
+ const startTime = performance.now();
2035
+ let scopeEnded = false;
2036
+ const scopeEntry = { scopeId, type: "race", winnerId: void 0 };
2037
+ activeScopeStack.push(scopeEntry);
2038
+ const emitScopeEnd = () => {
2039
+ if (scopeEnded) return;
2040
+ scopeEnded = true;
2041
+ const idx = activeScopeStack.findIndex((s) => s.scopeId === scopeId);
2042
+ if (idx !== -1) activeScopeStack.splice(idx, 1);
2043
+ emitEvent({
2044
+ type: "scope_end",
2045
+ workflowId,
2046
+ scopeId,
2047
+ ts: Date.now(),
2048
+ durationMs: performance.now() - startTime,
2049
+ winnerId: scopeEntry.winnerId
2050
+ });
2051
+ };
2052
+ emitEvent({
2053
+ type: "scope_start",
2054
+ workflowId,
2055
+ scopeId,
2056
+ scopeType: "race",
2057
+ name,
2058
+ ts: Date.now()
2059
+ });
2060
+ try {
2061
+ const result = await operation();
2062
+ emitScopeEnd();
2063
+ if (!result.ok) {
2064
+ onError?.(result.error, name, context);
2065
+ throw earlyExit(result.error, {
2066
+ origin: "result",
2067
+ resultCause: result.cause
2068
+ });
2069
+ }
2070
+ return result.value;
2071
+ } catch (error) {
2072
+ emitScopeEnd();
2073
+ throw error;
2074
+ }
2075
+ })();
2076
+ };
2077
+ stepFn.if = (id, conditionLabel, condition) => {
2078
+ assertDeclared(id, "decision");
2079
+ const value2 = condition();
2080
+ emitEvent({
2081
+ type: "decision",
2082
+ workflowId,
2083
+ decisionId: id,
2084
+ label: conditionLabel,
2085
+ branch: value2 ? "then" : "else",
2086
+ value: value2,
2087
+ ts: Date.now()
2088
+ });
2089
+ return value2;
2090
+ };
2091
+ stepFn.label = stepFn.if;
2092
+ stepFn.branch = async (id, options2) => {
2093
+ const { condition, then: thenFn, else: elseFn } = options2;
2094
+ assertDeclared(id, "decision");
2095
+ const conditionResult = condition();
2096
+ const branch = conditionResult ? "then" : "else";
2097
+ const startTime = performance.now();
2098
+ emitEvent({
2099
+ type: "decision",
2100
+ workflowId,
2101
+ decisionId: id,
2102
+ label: options2.conditionLabel,
2103
+ branch,
2104
+ value: conditionResult,
2105
+ phase: "start",
2106
+ ts: Date.now()
2107
+ });
2108
+ const emitEnd = () => {
2109
+ emitEvent({
2110
+ type: "decision",
2111
+ workflowId,
2112
+ decisionId: id,
2113
+ label: options2.conditionLabel,
2114
+ branch,
2115
+ value: conditionResult,
2116
+ phase: "end",
2117
+ durationMs: performance.now() - startTime,
2118
+ ts: Date.now()
2119
+ });
2120
+ };
2121
+ try {
2122
+ if (conditionResult) {
2123
+ return await thenFn();
2124
+ } else if (elseFn) {
2125
+ return await elseFn();
2126
+ }
2127
+ return void 0;
2128
+ } finally {
2129
+ emitEnd();
2130
+ }
2131
+ };
2132
+ stepFn.arm = (fn2, errors) => {
2133
+ return { fn: fn2, errors };
2134
+ };
2135
+ stepFn.forEach = async (_id, items, options2) => {
2136
+ const results = [];
2137
+ const maxIterations = options2.maxIterations;
2138
+ let index = 0;
2139
+ const isRunForm = "run" in options2;
2140
+ const asyncItems = Symbol.asyncIterator in items ? items : (async function* () {
2141
+ yield* items;
2142
+ })();
2143
+ for await (const item of asyncItems) {
2144
+ if (maxIterations !== void 0 && index >= maxIterations) {
2145
+ break;
2146
+ }
2147
+ let result;
2148
+ if (isRunForm) {
2149
+ const runOptions = options2;
2150
+ result = await runOptions.run(item, index);
2151
+ } else {
2152
+ const itemOptions = options2;
2153
+ result = await itemOptions.item.handler(item, index, stepFn);
2154
+ }
2155
+ results.push(result);
2156
+ index++;
2157
+ }
2158
+ return results;
2159
+ };
2160
+ stepFn.item = (handler) => {
2161
+ return {
2162
+ __forEachItemHandler: true,
2163
+ handler
2164
+ };
2165
+ };
2166
+ stepFn.dep = (_name, fn2) => {
2167
+ return fn2;
2168
+ };
2169
+ stepFn.workflow = (id, getter, options2) => {
2170
+ return stepFn(id, getter, options2);
2171
+ };
2172
+ stepFn.map = async (id, items, mapper, options2) => {
2173
+ const concurrency = options2?.concurrency ?? items.length;
2174
+ return stepFn(
2175
+ id,
2176
+ () => {
2177
+ if (concurrency >= items.length) {
2178
+ return allAsync2(items.map((item, index) => mapper(item, index)));
2179
+ } else {
2180
+ return (async () => {
2181
+ const results = [];
2182
+ for (let i = 0; i < items.length; i += concurrency) {
2183
+ const batch = items.slice(i, i + concurrency);
2184
+ const batchResult = await allAsync2(
2185
+ batch.map((item, batchIndex) => mapper(item, i + batchIndex))
2186
+ );
2187
+ if (!batchResult.ok) {
2188
+ return batchResult;
2189
+ }
2190
+ results.push(...batchResult.value);
2191
+ }
2192
+ return ok2(results);
2193
+ })();
2194
+ }
2195
+ },
2196
+ { key: options2?.key }
2197
+ );
2198
+ };
2199
+ stepFn.withFallback = (id, operation, options2) => {
2200
+ if (typeof id !== "string" || id.length === 0) {
2201
+ throw new Error(
2202
+ '[awaitly] step.withFallback() requires an explicit string ID as the first argument. Example: step.withFallback("getUser", () => fetchUser(id), { fallback: () => fetchFromCache(id) })'
2203
+ );
2204
+ }
2205
+ assertDeclared(id, "step");
2206
+ const stepKey = options2.key ?? id;
2207
+ const stepName = id;
2208
+ const stepId = generateStepId(stepKey);
2209
+ const hasEventListeners = onEvent;
2210
+ return (async () => {
2211
+ const startTime = hasEventListeners ? performance.now() : 0;
2212
+ if (onEvent) {
2213
+ emitEvent({
2214
+ type: "step_start",
2215
+ workflowId,
2216
+ stepId,
2217
+ stepKey,
2218
+ name: stepName,
2219
+ ts: Date.now()
2220
+ });
2221
+ }
2222
+ let primaryResult;
2223
+ try {
2224
+ primaryResult = await operation();
2225
+ } catch (thrown) {
2226
+ if (isEarlyExitE(thrown)) {
2227
+ emitEvent({
2228
+ type: "step_aborted",
2229
+ workflowId,
2230
+ stepId,
2231
+ stepKey,
2232
+ name: stepName,
2233
+ ts: Date.now(),
2234
+ durationMs: performance.now() - startTime
2235
+ });
2236
+ throw thrown;
2237
+ }
2238
+ let mappedError;
2239
+ try {
2240
+ mappedError = effectiveCatchUnexpected(thrown);
2241
+ } catch (mapperError) {
2242
+ throw createMapperException(mapperError);
2243
+ }
2244
+ if (options2.on !== void 0 && options2.on !== mappedError) {
2245
+ const durationMs2 = performance.now() - startTime;
2246
+ emitEvent({
2247
+ type: "step_error",
2248
+ workflowId,
2249
+ stepId,
2250
+ stepKey,
2251
+ name: stepName,
2252
+ ts: Date.now(),
2253
+ durationMs: durationMs2,
2254
+ error: mappedError
2255
+ });
2256
+ if (stepKey) {
2257
+ emitEvent({
2258
+ type: "step_complete",
2259
+ workflowId,
2260
+ stepKey,
2261
+ name: stepName,
2262
+ ts: Date.now(),
2263
+ durationMs: durationMs2,
2264
+ result: err2(mappedError, { cause: thrown }),
2265
+ meta: { origin: "throw", thrown }
2266
+ });
2267
+ }
2268
+ onError?.(mappedError, stepName, context);
2269
+ throw earlyExit(mappedError, { origin: "throw", thrown });
2270
+ }
2271
+ let fallbackResultFromThrow;
2272
+ try {
2273
+ fallbackResultFromThrow = await options2.fallback();
2274
+ } catch (fallbackThrown) {
2275
+ if (isEarlyExitE(fallbackThrown)) {
2276
+ emitEvent({
2277
+ type: "step_aborted",
2278
+ workflowId,
2279
+ stepId,
2280
+ stepKey,
2281
+ name: stepName,
2282
+ ts: Date.now(),
2283
+ durationMs: performance.now() - startTime
2284
+ });
2285
+ throw fallbackThrown;
2286
+ }
2287
+ let fallbackMappedError;
2288
+ try {
2289
+ fallbackMappedError = effectiveCatchUnexpected(fallbackThrown);
2290
+ } catch (mapperError) {
2291
+ throw createMapperException(mapperError);
2292
+ }
2293
+ const durationMs2 = performance.now() - startTime;
2294
+ emitEvent({
2295
+ type: "step_error",
2296
+ workflowId,
2297
+ stepId,
2298
+ stepKey,
2299
+ name: stepName,
2300
+ ts: Date.now(),
2301
+ durationMs: durationMs2,
2302
+ error: fallbackMappedError
2303
+ });
2304
+ if (stepKey) {
2305
+ emitEvent({
2306
+ type: "step_complete",
2307
+ workflowId,
2308
+ stepKey,
2309
+ name: stepName,
2310
+ ts: Date.now(),
2311
+ durationMs: durationMs2,
2312
+ result: err2(fallbackMappedError, { cause: fallbackThrown }),
2313
+ meta: { origin: "throw", thrown: fallbackThrown }
2314
+ });
2315
+ }
2316
+ onError?.(fallbackMappedError, stepName, context);
2317
+ throw earlyExit(fallbackMappedError, { origin: "throw", thrown: fallbackThrown });
2318
+ }
2319
+ if (fallbackResultFromThrow.ok) {
2320
+ const durationMs2 = performance.now() - startTime;
2321
+ emitEvent({
2322
+ type: "step_success",
2323
+ workflowId,
2324
+ stepId,
2325
+ stepKey,
2326
+ name: stepName,
2327
+ ts: Date.now(),
2328
+ durationMs: durationMs2
2329
+ });
2330
+ if (stepKey) {
2331
+ emitEvent({
2332
+ type: "step_complete",
2333
+ workflowId,
2334
+ stepKey,
2335
+ name: stepName,
2336
+ ts: Date.now(),
2337
+ durationMs: durationMs2,
2338
+ result: fallbackResultFromThrow,
2339
+ meta: { origin: "fallback", fallbackUsed: true, fallbackReason: String(mappedError) }
2340
+ });
2341
+ }
2342
+ return fallbackResultFromThrow.value;
2343
+ } else {
2344
+ const durationMs2 = performance.now() - startTime;
2345
+ const wrappedError2 = wrapForStep(fallbackResultFromThrow.error, {
2346
+ origin: "result",
2347
+ resultCause: fallbackResultFromThrow.cause
2348
+ });
2349
+ emitEvent({
2350
+ type: "step_error",
2351
+ workflowId,
2352
+ stepId,
2353
+ stepKey,
2354
+ name: stepName,
2355
+ ts: Date.now(),
2356
+ durationMs: durationMs2,
2357
+ error: wrappedError2
2358
+ });
2359
+ if (stepKey) {
2360
+ emitEvent({
2361
+ type: "step_complete",
2362
+ workflowId,
2363
+ stepKey,
2364
+ name: stepName,
2365
+ ts: Date.now(),
2366
+ durationMs: durationMs2,
2367
+ result: fallbackResultFromThrow,
2368
+ meta: { origin: "result", resultCause: fallbackResultFromThrow.cause }
2369
+ });
2370
+ }
2371
+ onError?.(wrappedError2, stepName, context);
2372
+ throw earlyExit(wrappedError2, {
2373
+ origin: "result",
2374
+ resultCause: fallbackResultFromThrow.cause
2375
+ });
2376
+ }
2377
+ }
2378
+ if (primaryResult.ok) {
2379
+ const durationMs2 = performance.now() - startTime;
2380
+ emitEvent({
2381
+ type: "step_success",
2382
+ workflowId,
2383
+ stepId,
2384
+ stepKey,
2385
+ name: stepName,
2386
+ ts: Date.now(),
2387
+ durationMs: durationMs2
2388
+ });
2389
+ if (stepKey) {
2390
+ emitEvent({
2391
+ type: "step_complete",
2392
+ workflowId,
2393
+ stepKey,
2394
+ name: stepName,
2395
+ ts: Date.now(),
2396
+ durationMs: durationMs2,
2397
+ result: primaryResult
2398
+ });
2399
+ }
2400
+ return primaryResult.value;
2401
+ }
2402
+ const primaryError = primaryResult.error;
2403
+ if (options2.on !== void 0 && options2.on !== primaryError) {
2404
+ const durationMs2 = performance.now() - startTime;
2405
+ const wrappedError2 = wrapForStep(primaryError, {
2406
+ origin: "result",
2407
+ resultCause: primaryResult.cause
2408
+ });
2409
+ emitEvent({
2410
+ type: "step_error",
2411
+ workflowId,
2412
+ stepId,
2413
+ stepKey,
2414
+ name: stepName,
2415
+ ts: Date.now(),
2416
+ durationMs: durationMs2,
2417
+ error: wrappedError2
2418
+ });
2419
+ if (stepKey) {
2420
+ emitEvent({
2421
+ type: "step_complete",
2422
+ workflowId,
2423
+ stepKey,
2424
+ name: stepName,
2425
+ ts: Date.now(),
2426
+ durationMs: durationMs2,
2427
+ result: primaryResult,
2428
+ meta: { origin: "result", resultCause: primaryResult.cause }
2429
+ });
2430
+ }
2431
+ onError?.(wrappedError2, stepName, context);
2432
+ throw earlyExit(wrappedError2, {
2433
+ origin: "result",
2434
+ resultCause: primaryResult.cause
2435
+ });
2436
+ }
2437
+ let fallbackResult;
2438
+ try {
2439
+ fallbackResult = await options2.fallback();
2440
+ } catch (thrown) {
2441
+ if (isEarlyExitE(thrown)) {
2442
+ emitEvent({
2443
+ type: "step_aborted",
2444
+ workflowId,
2445
+ stepId,
2446
+ stepKey,
2447
+ name: stepName,
2448
+ ts: Date.now(),
2449
+ durationMs: performance.now() - startTime
2450
+ });
2451
+ throw thrown;
2452
+ }
2453
+ let mappedError;
2454
+ try {
2455
+ mappedError = effectiveCatchUnexpected(thrown);
2456
+ } catch (mapperError) {
2457
+ throw createMapperException(mapperError);
2458
+ }
2459
+ const durationMs2 = performance.now() - startTime;
2460
+ emitEvent({
2461
+ type: "step_error",
2462
+ workflowId,
2463
+ stepId,
2464
+ stepKey,
2465
+ name: stepName,
2466
+ ts: Date.now(),
2467
+ durationMs: durationMs2,
2468
+ error: mappedError
2469
+ });
2470
+ if (stepKey) {
2471
+ emitEvent({
2472
+ type: "step_complete",
2473
+ workflowId,
2474
+ stepKey,
2475
+ name: stepName,
2476
+ ts: Date.now(),
2477
+ durationMs: durationMs2,
2478
+ result: err2(mappedError, { cause: thrown }),
2479
+ meta: { origin: "throw", thrown }
2480
+ });
2481
+ }
2482
+ onError?.(mappedError, stepName, context);
2483
+ throw earlyExit(mappedError, { origin: "throw", thrown });
2484
+ }
2485
+ if (fallbackResult.ok) {
2486
+ const durationMs2 = performance.now() - startTime;
2487
+ emitEvent({
2488
+ type: "step_success",
2489
+ workflowId,
2490
+ stepId,
2491
+ stepKey,
2492
+ name: stepName,
2493
+ ts: Date.now(),
2494
+ durationMs: durationMs2
2495
+ });
2496
+ if (stepKey) {
2497
+ emitEvent({
2498
+ type: "step_complete",
2499
+ workflowId,
2500
+ stepKey,
2501
+ name: stepName,
2502
+ ts: Date.now(),
2503
+ durationMs: durationMs2,
2504
+ result: fallbackResult,
2505
+ meta: { origin: "fallback", fallbackUsed: true, fallbackReason: String(primaryError) }
2506
+ });
2507
+ }
2508
+ return fallbackResult.value;
2509
+ }
2510
+ const durationMs = performance.now() - startTime;
2511
+ const wrappedError = wrapForStep(fallbackResult.error, {
2512
+ origin: "result",
2513
+ resultCause: fallbackResult.cause
2514
+ });
2515
+ emitEvent({
2516
+ type: "step_error",
2517
+ workflowId,
2518
+ stepId,
2519
+ stepKey,
2520
+ name: stepName,
2521
+ ts: Date.now(),
2522
+ durationMs,
2523
+ error: wrappedError
2524
+ });
2525
+ if (stepKey) {
2526
+ emitEvent({
2527
+ type: "step_complete",
2528
+ workflowId,
2529
+ stepKey,
2530
+ name: stepName,
2531
+ ts: Date.now(),
2532
+ durationMs,
2533
+ result: fallbackResult,
2534
+ meta: { origin: "result", resultCause: fallbackResult.cause }
2535
+ });
2536
+ }
2537
+ onError?.(wrappedError, stepName, context);
2538
+ throw earlyExit(wrappedError, {
2539
+ origin: "result",
2540
+ resultCause: fallbackResult.cause
2541
+ });
2542
+ })();
2543
+ };
2544
+ stepFn.withResource = (id, options2) => {
2545
+ if (typeof id !== "string" || id.length === 0) {
2546
+ throw new Error(
2547
+ '[awaitly] step.withResource() requires an explicit string ID as the first argument. Example: step.withResource("useDb", { acquire: () => connect(), use: (db) => query(db), release: (db) => db.close() })'
2548
+ );
2549
+ }
2550
+ assertDeclared(id, "step");
2551
+ const stepKey = id;
2552
+ const stepName = id;
2553
+ const stepId = generateStepId(stepKey);
2554
+ const hasEventListeners = onEvent;
2555
+ return (async () => {
2556
+ const startTime = hasEventListeners ? performance.now() : 0;
2557
+ if (onEvent) {
2558
+ emitEvent({
2559
+ type: "step_start",
2560
+ workflowId,
2561
+ stepId,
2562
+ stepKey,
2563
+ name: stepName,
2564
+ ts: Date.now()
2565
+ });
2566
+ }
2567
+ let acquireResult;
2568
+ try {
2569
+ acquireResult = await options2.acquire();
2570
+ } catch (thrown) {
2571
+ if (isEarlyExitE(thrown)) {
2572
+ emitEvent({
2573
+ type: "step_aborted",
2574
+ workflowId,
2575
+ stepId,
2576
+ stepKey,
2577
+ name: stepName,
2578
+ ts: Date.now(),
2579
+ durationMs: performance.now() - startTime
2580
+ });
2581
+ throw thrown;
2582
+ }
2583
+ let mappedError;
2584
+ try {
2585
+ mappedError = effectiveCatchUnexpected(thrown);
2586
+ } catch (mapperError) {
2587
+ throw createMapperException(mapperError);
2588
+ }
2589
+ const durationMs2 = performance.now() - startTime;
2590
+ emitEvent({
2591
+ type: "step_error",
2592
+ workflowId,
2593
+ stepId,
2594
+ stepKey,
2595
+ name: stepName,
2596
+ ts: Date.now(),
2597
+ durationMs: durationMs2,
2598
+ error: mappedError
2599
+ });
2600
+ if (stepKey) {
2601
+ emitEvent({
2602
+ type: "step_complete",
2603
+ workflowId,
2604
+ stepKey,
2605
+ name: stepName,
2606
+ ts: Date.now(),
2607
+ durationMs: durationMs2,
2608
+ result: err2(mappedError, { cause: thrown }),
2609
+ meta: { origin: "throw", thrown }
2610
+ });
2611
+ }
2612
+ onError?.(mappedError, stepName, context);
2613
+ throw earlyExit(mappedError, { origin: "throw", thrown });
2614
+ }
2615
+ if (!acquireResult.ok) {
2616
+ const durationMs2 = performance.now() - startTime;
2617
+ const wrappedError2 = wrapForStep(acquireResult.error, {
2618
+ origin: "result",
2619
+ resultCause: acquireResult.cause
2620
+ });
2621
+ emitEvent({
2622
+ type: "step_error",
2623
+ workflowId,
2624
+ stepId,
2625
+ stepKey,
2626
+ name: stepName,
2627
+ ts: Date.now(),
2628
+ durationMs: durationMs2,
2629
+ error: wrappedError2
2630
+ });
2631
+ if (stepKey) {
2632
+ emitEvent({
2633
+ type: "step_complete",
2634
+ workflowId,
2635
+ stepKey,
2636
+ name: stepName,
2637
+ ts: Date.now(),
2638
+ durationMs: durationMs2,
2639
+ result: acquireResult,
2640
+ meta: { origin: "result", resultCause: acquireResult.cause }
2641
+ });
2642
+ }
2643
+ onError?.(wrappedError2, stepName, context);
2644
+ throw earlyExit(wrappedError2, {
2645
+ origin: "result",
2646
+ resultCause: acquireResult.cause
2647
+ });
2648
+ }
2649
+ const resource = acquireResult.value;
2650
+ let useResult;
2651
+ let useThrown;
2652
+ let useThrewNonResult = false;
2653
+ try {
2654
+ useResult = await options2.use(resource);
2655
+ } catch (thrown) {
2656
+ if (isEarlyExitE(thrown)) {
2657
+ try {
2658
+ await options2.release(resource);
2659
+ } catch (releaseErr) {
2660
+ console.warn(
2661
+ `[awaitly] step.withResource("${id}"): release threw after earlyExit:`,
2662
+ releaseErr
2663
+ );
2664
+ }
2665
+ throw thrown;
2666
+ }
2667
+ useThrown = thrown;
2668
+ useThrewNonResult = true;
2669
+ }
2670
+ try {
2671
+ await options2.release(resource);
2672
+ } catch (releaseErr) {
2673
+ console.warn(
2674
+ `[awaitly] step.withResource("${id}"): release threw:`,
2675
+ releaseErr
2676
+ );
2677
+ }
2678
+ if (useThrewNonResult) {
2679
+ let mappedError;
2680
+ try {
2681
+ mappedError = effectiveCatchUnexpected(useThrown);
2682
+ } catch (mapperError) {
2683
+ throw createMapperException(mapperError);
2684
+ }
2685
+ const durationMs2 = performance.now() - startTime;
2686
+ emitEvent({
2687
+ type: "step_error",
2688
+ workflowId,
2689
+ stepId,
2690
+ stepKey,
2691
+ name: stepName,
2692
+ ts: Date.now(),
2693
+ durationMs: durationMs2,
2694
+ error: mappedError
2695
+ });
2696
+ if (stepKey) {
2697
+ emitEvent({
2698
+ type: "step_complete",
2699
+ workflowId,
2700
+ stepKey,
2701
+ name: stepName,
2702
+ ts: Date.now(),
2703
+ durationMs: durationMs2,
2704
+ result: err2(mappedError, { cause: useThrown }),
2705
+ meta: { origin: "throw", thrown: useThrown }
2706
+ });
2707
+ }
2708
+ onError?.(mappedError, stepName, context);
2709
+ throw earlyExit(mappedError, { origin: "throw", thrown: useThrown });
2710
+ }
2711
+ const result = useResult;
2712
+ if (result.ok) {
2713
+ const durationMs2 = performance.now() - startTime;
2714
+ emitEvent({
2715
+ type: "step_success",
2716
+ workflowId,
2717
+ stepId,
2718
+ stepKey,
2719
+ name: stepName,
2720
+ ts: Date.now(),
2721
+ durationMs: durationMs2
2722
+ });
2723
+ if (stepKey) {
2724
+ emitEvent({
2725
+ type: "step_complete",
2726
+ workflowId,
2727
+ stepKey,
2728
+ name: stepName,
2729
+ ts: Date.now(),
2730
+ durationMs: durationMs2,
2731
+ result
2732
+ });
2733
+ }
2734
+ return result.value;
2735
+ }
2736
+ const durationMs = performance.now() - startTime;
2737
+ const wrappedError = wrapForStep(result.error, {
2738
+ origin: "result",
2739
+ resultCause: result.cause
2740
+ });
2741
+ emitEvent({
2742
+ type: "step_error",
2743
+ workflowId,
2744
+ stepId,
2745
+ stepKey,
2746
+ name: stepName,
2747
+ ts: Date.now(),
2748
+ durationMs,
2749
+ error: wrappedError
2750
+ });
2751
+ if (stepKey) {
2752
+ emitEvent({
2753
+ type: "step_complete",
2754
+ workflowId,
2755
+ stepKey,
2756
+ name: stepName,
2757
+ ts: Date.now(),
2758
+ durationMs,
2759
+ result,
2760
+ meta: { origin: "result", resultCause: result.cause }
2761
+ });
2762
+ }
2763
+ onError?.(wrappedError, stepName, context);
2764
+ throw earlyExit(wrappedError, {
2765
+ origin: "result",
2766
+ resultCause: result.cause
2767
+ });
2768
+ })();
2769
+ };
2770
+ const step = stepFn;
2771
+ const value = await fn({ step });
2772
+ if (process.env.NODE_ENV !== "production" && value !== null && typeof value === "object" && "ok" in value && typeof value.ok === "boolean") {
2773
+ const maybeResult = value;
2774
+ if (maybeResult.ok === true && "value" in maybeResult || maybeResult.ok === false && "error" in maybeResult) {
2775
+ console.warn(
2776
+ `awaitly: Workflow executor returned a Result-like object. Return raw values, not ok() or err().
2777
+
2778
+ Incorrect: return ok({ data });
2779
+ Correct: return { data };
2780
+
2781
+ See: https://jagreehal.github.io/awaitly/guides/troubleshooting/#returning-ok-from-workflow-executor-double-wrapping`
2782
+ );
2783
+ }
2784
+ }
2785
+ return ok2(value);
2786
+ } catch (error) {
2787
+ if (isMapperException(error)) {
2788
+ throw error.thrown;
2789
+ }
2790
+ if (isEarlyExitE(error)) {
2791
+ const originalCause = error.meta.origin === "throw" ? error.meta.thrown : error.meta.origin === "result" ? error.meta.resultCause : void 0;
2792
+ return err2(error.error, { cause: originalCause });
2793
+ }
2794
+ const mapped = effectiveCatchUnexpected(error);
2795
+ onError?.(mapped, "unexpected", context);
2796
+ return err2(mapped, { cause: error });
2797
+ }
2798
+ }
2799
+ var runStrict = (fn, options) => {
2800
+ return runFn(fn, options);
2801
+ };
2802
+ var run = /* @__PURE__ */ Object.assign(runFn, { strict: runStrict });
2803
+ async function allAsync2(results) {
2804
+ if (results.length === 0) {
2805
+ return ok2([]);
2806
+ }
2807
+ return new Promise((resolve) => {
2808
+ let settled = false;
2809
+ let pendingCount = results.length;
2810
+ const values = new Array(results.length);
2811
+ for (let i = 0; i < results.length; i++) {
2812
+ const index = i;
2813
+ Promise.resolve(results[index]).catch((reason) => err2(
2814
+ { type: "PROMISE_REJECTED", cause: reason },
2815
+ { cause: { type: "PROMISE_REJECTION", reason } }
2816
+ )).then((result) => {
2817
+ if (settled) return;
2818
+ if (!result.ok) {
2819
+ settled = true;
2820
+ resolve(result);
2821
+ return;
2822
+ }
2823
+ values[index] = result.value;
2824
+ pendingCount--;
2825
+ if (pendingCount === 0) {
2826
+ resolve(ok2(values));
2827
+ }
2828
+ });
2829
+ }
2830
+ });
2831
+ }
2832
+
2833
+ // src/match.ts
2834
+ function tag(tagValue, handler) {
2835
+ return (matcher) => {
2836
+ const newHandlers = new Map(matcher.handlers);
2837
+ newHandlers.set(tagValue, handler);
2838
+ return {
2839
+ _tag: "Matcher",
2840
+ value: matcher.value,
2841
+ handlers: newHandlers,
2842
+ _remaining: void 0,
2843
+ _output: void 0
2844
+ };
2845
+ };
2846
+ }
2847
+ function tags2(handlers) {
2848
+ return (matcher) => {
2849
+ const newHandlers = new Map(matcher.handlers);
2850
+ for (const [tagValue, handler] of Object.entries(handlers)) {
2851
+ if (handler) {
2852
+ newHandlers.set(tagValue, handler);
2853
+ }
2854
+ }
2855
+ return {
2856
+ _tag: "Matcher",
2857
+ value: matcher.value,
2858
+ handlers: newHandlers,
2859
+ _remaining: void 0,
2860
+ _output: void 0
2861
+ };
2862
+ };
2863
+ }
2864
+ function exhaustive(matcher) {
2865
+ const handler = matcher.handlers.get(matcher.value._tag);
2866
+ if (!handler) {
2867
+ throw new Error(`No handler for tag: ${matcher.value._tag}`);
2868
+ }
2869
+ return handler(matcher.value);
2870
+ }
2871
+ function orElse2(handler) {
2872
+ return (matcher) => {
2873
+ const specificHandler = matcher.handlers.get(matcher.value._tag);
2874
+ if (specificHandler) {
2875
+ return specificHandler(matcher.value);
2876
+ }
2877
+ return handler(matcher.value);
2878
+ };
2879
+ }
2880
+ function orElseValue(defaultValue) {
2881
+ return orElse2(() => defaultValue);
2882
+ }
2883
+ function when(tagValue, predicate, handler) {
2884
+ return (matcher) => {
2885
+ const newHandlers = new Map(matcher.handlers);
2886
+ const existingHandler = matcher.handlers.get(tagValue);
2887
+ newHandlers.set(tagValue, (value) => {
2888
+ const typedValue = value;
2889
+ if (predicate(typedValue)) {
2890
+ return handler(typedValue);
2891
+ }
2892
+ if (existingHandler) {
2893
+ return existingHandler(value);
2894
+ }
2895
+ throw new Error(`No handler matched for tag: ${tagValue}`);
2896
+ });
2897
+ return {
2898
+ _tag: "Matcher",
2899
+ value: matcher.value,
2900
+ handlers: newHandlers,
2901
+ _remaining: matcher._remaining,
2902
+ _output: void 0
2903
+ };
2904
+ };
2905
+ }
2906
+ function is(tagValue) {
2907
+ return (value) => value._tag === tagValue;
2908
+ }
2909
+ function isOneOf(...tags3) {
2910
+ const tagSet = new Set(tags3);
2911
+ return (value) => tagSet.has(value._tag);
2912
+ }
2913
+ function isMatcher(value) {
2914
+ return typeof value === "object" && value !== null && "_tag" in value && value._tag === "Matcher";
2915
+ }
2916
+ function addPipe(matcher) {
2917
+ return {
2918
+ ...matcher,
2919
+ pipe(fn) {
2920
+ const result = fn(matcher);
2921
+ if (isMatcher(result)) {
2922
+ return addPipe(result);
2923
+ }
2924
+ return result;
2925
+ }
2926
+ };
2927
+ }
2928
+ function matchValue(input) {
2929
+ const matcher = {
2930
+ _tag: "Matcher",
2931
+ value: input,
2932
+ handlers: /* @__PURE__ */ new Map(),
2933
+ _remaining: input,
2934
+ _output: void 0
2935
+ };
2936
+ return addPipe(matcher);
2937
+ }
2938
+ var Match = {
2939
+ value: matchValue,
2940
+ tag,
2941
+ tags: tags2,
2942
+ when,
2943
+ exhaustive,
2944
+ orElse: orElse2,
2945
+ orElseValue,
2946
+ is,
2947
+ isOneOf
2948
+ };
2949
+
2950
+ // src/circuit-breaker.ts
2951
+ var CircuitOpenError = class extends Error {
2952
+ type = "CIRCUIT_OPEN";
2953
+ circuitName;
2954
+ state;
2955
+ retryAfterMs;
2956
+ constructor(options) {
2957
+ super(
2958
+ options.message ?? `Circuit breaker "${options.circuitName}" is ${options.state}. Retry after ${Math.ceil(options.retryAfterMs / 1e3)}s`
2959
+ );
2960
+ this.name = "CircuitOpenError";
2961
+ this.circuitName = options.circuitName;
2962
+ this.state = options.state;
2963
+ this.retryAfterMs = options.retryAfterMs;
2964
+ }
2965
+ };
2966
+ function isCircuitOpenError(error) {
2967
+ return typeof error === "object" && error !== null && error.type === "CIRCUIT_OPEN";
2968
+ }
2969
+ var DEFAULT_CONFIG = {
2970
+ failureThreshold: 5,
2971
+ resetTimeout: 3e4,
2972
+ windowSize: 6e4,
2973
+ halfOpenMax: 3
2974
+ };
2975
+ function createCircuitBreaker(name, config) {
2976
+ const effectiveConfig = {
2977
+ ...DEFAULT_CONFIG,
2978
+ ...config
2979
+ };
2980
+ let state = "CLOSED";
2981
+ let failures = [];
2982
+ let lastFailureTime = null;
2983
+ let lastSuccessTime = null;
2984
+ let successCount = 0;
2985
+ let halfOpenSuccesses = 0;
2986
+ function cleanupFailures() {
2987
+ const now = Date.now();
2988
+ failures = failures.filter(
2989
+ (f) => now - f.timestamp < effectiveConfig.windowSize
2990
+ );
2991
+ }
2992
+ function transitionTo(newState) {
2993
+ if (state !== newState) {
2994
+ const oldState = state;
2995
+ state = newState;
2996
+ if (newState === "HALF_OPEN") {
2997
+ halfOpenSuccesses = 0;
2998
+ }
2999
+ effectiveConfig.onStateChange?.(oldState, newState, name);
3000
+ }
3001
+ }
3002
+ function checkOpenToHalfOpen() {
3003
+ if (state !== "OPEN" || lastFailureTime === null) {
3004
+ return false;
3005
+ }
3006
+ const now = Date.now();
3007
+ if (now - lastFailureTime >= effectiveConfig.resetTimeout) {
3008
+ transitionTo("HALF_OPEN");
3009
+ return true;
3010
+ }
3011
+ return false;
3012
+ }
3013
+ function handleSuccess() {
3014
+ lastSuccessTime = Date.now();
3015
+ successCount++;
3016
+ if (state === "HALF_OPEN") {
3017
+ halfOpenSuccesses++;
3018
+ if (halfOpenSuccesses >= effectiveConfig.halfOpenMax) {
3019
+ transitionTo("CLOSED");
3020
+ failures = [];
3021
+ }
3022
+ }
3023
+ }
3024
+ function handleFailure(error) {
3025
+ const now = Date.now();
3026
+ lastFailureTime = now;
3027
+ cleanupFailures();
3028
+ failures.push({ timestamp: now, error });
3029
+ if (state === "HALF_OPEN") {
3030
+ transitionTo("OPEN");
3031
+ } else if (state === "CLOSED") {
3032
+ if (failures.length >= effectiveConfig.failureThreshold) {
3033
+ transitionTo("OPEN");
3034
+ }
3035
+ }
3036
+ }
3037
+ function canExecute() {
3038
+ if (state === "CLOSED") {
3039
+ return 0;
3040
+ }
3041
+ if (state === "OPEN") {
3042
+ if (checkOpenToHalfOpen()) {
3043
+ return 0;
3044
+ }
3045
+ const now = Date.now();
3046
+ const elapsed = lastFailureTime ? now - lastFailureTime : 0;
3047
+ return Math.max(0, effectiveConfig.resetTimeout - elapsed);
3048
+ }
3049
+ return 0;
3050
+ }
3051
+ return {
3052
+ async execute(operation, _options) {
3053
+ const waitTime = canExecute();
3054
+ if (waitTime > 0) {
3055
+ throw new CircuitOpenError({
3056
+ circuitName: name,
3057
+ state,
3058
+ retryAfterMs: waitTime
3059
+ });
3060
+ }
3061
+ try {
3062
+ const result = await operation();
3063
+ handleSuccess();
3064
+ return result;
3065
+ } catch (error) {
3066
+ handleFailure(error);
3067
+ throw error;
3068
+ }
3069
+ },
3070
+ async executeResult(operation, _options) {
3071
+ const waitTime = canExecute();
3072
+ if (waitTime > 0) {
3073
+ return err2(
3074
+ new CircuitOpenError({
3075
+ circuitName: name,
3076
+ state,
3077
+ retryAfterMs: waitTime
3078
+ })
3079
+ );
3080
+ }
3081
+ try {
3082
+ const result = await operation();
3083
+ if (result.ok) {
3084
+ handleSuccess();
3085
+ } else {
3086
+ handleFailure(result.error);
3087
+ }
3088
+ return result;
3089
+ } catch (error) {
3090
+ handleFailure(error);
3091
+ throw error;
3092
+ }
3093
+ },
3094
+ getState() {
3095
+ if (state === "OPEN") {
3096
+ checkOpenToHalfOpen();
3097
+ }
3098
+ return state;
3099
+ },
3100
+ getStats() {
3101
+ cleanupFailures();
3102
+ return {
3103
+ state: this.getState(),
3104
+ failureCount: failures.length,
3105
+ successCount,
3106
+ lastFailureTime,
3107
+ lastSuccessTime,
3108
+ halfOpenSuccesses
3109
+ };
3110
+ },
3111
+ reset() {
3112
+ transitionTo("CLOSED");
3113
+ failures = [];
3114
+ halfOpenSuccesses = 0;
3115
+ },
3116
+ forceOpen() {
3117
+ lastFailureTime = Date.now();
3118
+ transitionTo("OPEN");
3119
+ },
3120
+ recordSuccess() {
3121
+ handleSuccess();
3122
+ },
3123
+ recordFailure(error) {
3124
+ handleFailure(error ?? new Error("Manual failure"));
3125
+ }
3126
+ };
3127
+ }
3128
+ var circuitBreakerPresets = {
3129
+ /**
3130
+ * Aggressive circuit breaker for critical paths.
3131
+ * Opens quickly (3 failures) and recovers slowly (60s).
3132
+ */
3133
+ critical: {
3134
+ failureThreshold: 3,
3135
+ resetTimeout: 6e4,
3136
+ windowSize: 3e4,
3137
+ halfOpenMax: 1
3138
+ },
3139
+ /**
3140
+ * Standard circuit breaker for typical API calls.
3141
+ * Balanced between stability and availability.
3142
+ */
3143
+ standard: {
3144
+ failureThreshold: 5,
3145
+ resetTimeout: 3e4,
3146
+ windowSize: 6e4,
3147
+ halfOpenMax: 3
3148
+ },
3149
+ /**
3150
+ * Lenient circuit breaker for non-critical operations.
3151
+ * Opens slowly (10 failures) and recovers quickly (15s).
3152
+ */
3153
+ lenient: {
3154
+ failureThreshold: 10,
3155
+ resetTimeout: 15e3,
3156
+ windowSize: 12e4,
3157
+ halfOpenMax: 5
3158
+ }
3159
+ };
3160
+
3161
+ // src/rate-limiter/index.ts
3162
+ function isRateLimitExceededError(error) {
3163
+ return typeof error === "object" && error !== null && error.type === "RATE_LIMIT_EXCEEDED";
3164
+ }
3165
+ function isQueueFullError(error) {
3166
+ return typeof error === "object" && error !== null && error.type === "QUEUE_FULL";
3167
+ }
3168
+ function createRateLimiter(name, config) {
3169
+ const { maxPerSecond, strategy = "wait" } = config;
3170
+ const maxTokens = config.burstCapacity ?? maxPerSecond * 2;
3171
+ let tokens = maxTokens;
3172
+ let lastRefill = Date.now();
3173
+ const refillRate = maxPerSecond / 1e3;
3174
+ const waitQueue = [];
3175
+ function refill() {
3176
+ const now = Date.now();
3177
+ const elapsed = now - lastRefill;
3178
+ const tokensToAdd = elapsed * refillRate;
3179
+ tokens = Math.min(maxTokens, tokens + tokensToAdd);
3180
+ lastRefill = now;
3181
+ }
3182
+ function tryConsume() {
3183
+ refill();
3184
+ if (tokens >= 1) {
3185
+ tokens -= 1;
3186
+ return 0;
3187
+ }
3188
+ const tokensNeeded = 1 - tokens;
3189
+ return Math.ceil(tokensNeeded / refillRate);
3190
+ }
3191
+ async function waitForToken() {
3192
+ return new Promise((resolve) => {
3193
+ const check = () => {
3194
+ const waitTime = tryConsume();
3195
+ if (waitTime === 0) {
3196
+ resolve();
3197
+ } else {
3198
+ waitQueue.push(check);
3199
+ setTimeout(() => {
3200
+ const idx = waitQueue.indexOf(check);
3201
+ if (idx !== -1) {
3202
+ waitQueue.splice(idx, 1);
3203
+ check();
3204
+ }
3205
+ }, waitTime);
3206
+ }
3207
+ };
3208
+ check();
3209
+ });
3210
+ }
3211
+ return {
3212
+ async execute(operation) {
3213
+ const waitTime = tryConsume();
3214
+ if (waitTime > 0) {
3215
+ if (strategy === "reject") {
3216
+ throw {
3217
+ type: "RATE_LIMIT_EXCEEDED",
3218
+ limiterName: name,
3219
+ retryAfterMs: waitTime
3220
+ };
3221
+ }
3222
+ await waitForToken();
3223
+ }
3224
+ return operation();
3225
+ },
3226
+ async executeResult(operation) {
3227
+ const waitTime = tryConsume();
3228
+ if (waitTime > 0) {
3229
+ if (strategy === "reject") {
3230
+ return err2({
3231
+ type: "RATE_LIMIT_EXCEEDED",
3232
+ limiterName: name,
3233
+ retryAfterMs: waitTime
3234
+ });
3235
+ }
3236
+ await waitForToken();
3237
+ }
3238
+ return operation();
3239
+ },
3240
+ getStats() {
3241
+ refill();
3242
+ return {
3243
+ availableTokens: Math.floor(tokens),
3244
+ maxTokens,
3245
+ tokensPerSecond: maxPerSecond,
3246
+ waitingCount: waitQueue.length
3247
+ };
3248
+ },
3249
+ reset() {
3250
+ tokens = maxTokens;
3251
+ lastRefill = Date.now();
3252
+ waitQueue.length = 0;
3253
+ }
3254
+ };
3255
+ }
3256
+ function createConcurrencyLimiter(name, config) {
3257
+ const { maxConcurrent, strategy = "queue", maxQueueSize = Infinity } = config;
3258
+ let activeCount = 0;
3259
+ const queue = [];
3260
+ async function acquire() {
3261
+ if (activeCount < maxConcurrent) {
3262
+ activeCount++;
3263
+ return;
3264
+ }
3265
+ if (strategy === "reject") {
3266
+ throw {
3267
+ type: "QUEUE_FULL",
3268
+ limiterName: name,
3269
+ queueSize: queue.length,
3270
+ maxQueueSize
3271
+ };
3272
+ }
3273
+ if (queue.length >= maxQueueSize) {
3274
+ throw {
3275
+ type: "QUEUE_FULL",
3276
+ limiterName: name,
3277
+ queueSize: queue.length,
3278
+ maxQueueSize
3279
+ };
3280
+ }
3281
+ return new Promise((resolve, reject) => {
3282
+ queue.push({ resolve, reject });
3283
+ });
3284
+ }
3285
+ function release() {
3286
+ activeCount--;
3287
+ if (queue.length > 0 && activeCount < maxConcurrent) {
3288
+ activeCount++;
3289
+ const next = queue.shift();
3290
+ next?.resolve();
3291
+ }
3292
+ }
3293
+ return {
3294
+ async execute(operation) {
3295
+ await acquire();
3296
+ try {
3297
+ return await operation();
3298
+ } finally {
3299
+ release();
3300
+ }
3301
+ },
3302
+ async executeAll(operations) {
3303
+ const results = new Array(operations.length);
3304
+ const executing = [];
3305
+ for (let i = 0; i < operations.length; i++) {
3306
+ const index = i;
3307
+ const promise = this.execute(operations[index]).then((result) => {
3308
+ results[index] = result;
3309
+ });
3310
+ executing.push(promise);
3311
+ }
3312
+ await Promise.all(executing);
3313
+ return results;
3314
+ },
3315
+ async executeResult(operation) {
3316
+ try {
3317
+ await acquire();
3318
+ } catch (error) {
3319
+ if (isQueueFullError(error)) {
3320
+ return err2(error);
3321
+ }
3322
+ throw error;
3323
+ }
3324
+ try {
3325
+ return await operation();
3326
+ } finally {
3327
+ release();
3328
+ }
3329
+ },
3330
+ getStats() {
3331
+ return {
3332
+ activeCount,
3333
+ maxConcurrent,
3334
+ queueSize: queue.length,
3335
+ maxQueueSize
3336
+ };
3337
+ },
3338
+ reset() {
3339
+ activeCount = 0;
3340
+ while (queue.length > 0) {
3341
+ const item = queue.shift();
3342
+ item?.reject(new Error("Limiter reset"));
3343
+ }
3344
+ }
3345
+ };
3346
+ }
3347
+ function createCombinedLimiter(name, config) {
3348
+ const rate = config.rate ? createRateLimiter(`${name}-rate`, config.rate) : void 0;
3349
+ const concurrency = config.concurrency ? createConcurrencyLimiter(`${name}-concurrency`, config.concurrency) : void 0;
3350
+ return {
3351
+ rate,
3352
+ concurrency,
3353
+ async execute(operation) {
3354
+ let op = operation;
3355
+ if (rate) {
3356
+ const originalOp = op;
3357
+ op = () => rate.execute(originalOp);
3358
+ }
3359
+ if (concurrency) {
3360
+ return concurrency.execute(op);
3361
+ }
3362
+ return op();
3363
+ }
3364
+ };
3365
+ }
3366
+ function createFixedWindowLimiter(name, config) {
3367
+ const { limit, windowMs = 1e3, strategy = "wait" } = config;
3368
+ let windowStart = Date.now();
3369
+ let requestCount = 0;
3370
+ const waitQueue = [];
3371
+ function checkWindow() {
3372
+ const now = Date.now();
3373
+ const elapsed = now - windowStart;
3374
+ if (elapsed >= windowMs) {
3375
+ windowStart = now;
3376
+ requestCount = 0;
3377
+ return 0;
3378
+ }
3379
+ return windowMs - elapsed;
3380
+ }
3381
+ function tryConsume(cost) {
3382
+ const remainingMs = checkWindow();
3383
+ if (requestCount + cost <= limit) {
3384
+ requestCount += cost;
3385
+ return 0;
3386
+ }
3387
+ return remainingMs;
3388
+ }
3389
+ async function waitForWindow(cost) {
3390
+ return new Promise((resolve) => {
3391
+ const check = () => {
3392
+ const waitTime = tryConsume(cost);
3393
+ if (waitTime === 0) {
3394
+ resolve();
3395
+ } else {
3396
+ waitQueue.push({ resolve: check, cost });
3397
+ setTimeout(() => {
3398
+ const idx = waitQueue.findIndex((w) => w.resolve === check);
3399
+ if (idx !== -1) {
3400
+ waitQueue.splice(idx, 1);
3401
+ check();
3402
+ }
3403
+ }, waitTime);
3404
+ }
3405
+ };
3406
+ check();
3407
+ });
3408
+ }
3409
+ return {
3410
+ async execute(operation, cost = 1) {
3411
+ if (cost > limit) {
3412
+ throw {
3413
+ type: "RATE_LIMIT_EXCEEDED",
3414
+ limiterName: name,
3415
+ retryAfterMs: windowMs
3416
+ };
3417
+ }
3418
+ const waitTime = tryConsume(cost);
3419
+ if (waitTime > 0) {
3420
+ if (strategy === "reject") {
3421
+ throw {
3422
+ type: "RATE_LIMIT_EXCEEDED",
3423
+ limiterName: name,
3424
+ retryAfterMs: waitTime
3425
+ };
3426
+ }
3427
+ await waitForWindow(cost);
3428
+ }
3429
+ return operation();
3430
+ },
3431
+ async executeResult(operation, cost = 1) {
3432
+ if (cost > limit) {
3433
+ return err2({
3434
+ type: "RATE_LIMIT_EXCEEDED",
3435
+ limiterName: name,
3436
+ retryAfterMs: windowMs
3437
+ });
3438
+ }
3439
+ const waitTime = tryConsume(cost);
3440
+ if (waitTime > 0) {
3441
+ if (strategy === "reject") {
3442
+ return err2({
3443
+ type: "RATE_LIMIT_EXCEEDED",
3444
+ limiterName: name,
3445
+ retryAfterMs: waitTime
3446
+ });
3447
+ }
3448
+ await waitForWindow(cost);
3449
+ }
3450
+ return operation();
3451
+ },
3452
+ getStats() {
3453
+ const remainingMs = checkWindow();
3454
+ return {
3455
+ requestCount,
3456
+ limit,
3457
+ windowMs,
3458
+ remainingMs,
3459
+ waitingCount: waitQueue.length
3460
+ };
3461
+ },
3462
+ reset() {
3463
+ windowStart = Date.now();
3464
+ requestCount = 0;
3465
+ waitQueue.length = 0;
3466
+ }
3467
+ };
3468
+ }
3469
+ function createCostBasedRateLimiter(name, config) {
3470
+ const { tokensPerSecond, strategy = "wait" } = config;
3471
+ const maxTokens = config.maxTokens ?? tokensPerSecond * 2;
3472
+ let tokens = maxTokens;
3473
+ let lastRefill = Date.now();
3474
+ const refillRate = tokensPerSecond / 1e3;
3475
+ const waitQueue = [];
3476
+ function refill() {
3477
+ const now = Date.now();
3478
+ const elapsed = now - lastRefill;
3479
+ const tokensToAdd = elapsed * refillRate;
3480
+ tokens = Math.min(maxTokens, tokens + tokensToAdd);
3481
+ lastRefill = now;
3482
+ }
3483
+ function tryConsume(cost) {
3484
+ refill();
3485
+ if (tokens >= cost) {
3486
+ tokens -= cost;
3487
+ return 0;
3488
+ }
3489
+ const tokensNeeded = cost - tokens;
3490
+ return Math.ceil(tokensNeeded / refillRate);
3491
+ }
3492
+ async function waitForTokens(cost) {
3493
+ return new Promise((resolve) => {
3494
+ const check = () => {
3495
+ const waitTime = tryConsume(cost);
3496
+ if (waitTime === 0) {
3497
+ resolve();
3498
+ } else {
3499
+ waitQueue.push({ check, cost });
3500
+ setTimeout(() => {
3501
+ const idx = waitQueue.findIndex((w) => w.check === check);
3502
+ if (idx !== -1) {
3503
+ waitQueue.splice(idx, 1);
3504
+ check();
3505
+ }
3506
+ }, waitTime);
3507
+ }
3508
+ };
3509
+ check();
3510
+ });
3511
+ }
3512
+ return {
3513
+ async execute(operation, cost = 1) {
3514
+ if (cost > maxTokens) {
3515
+ throw {
3516
+ type: "RATE_LIMIT_EXCEEDED",
3517
+ limiterName: name,
3518
+ retryAfterMs: Math.ceil(cost / refillRate)
3519
+ };
3520
+ }
3521
+ const waitTime = tryConsume(cost);
3522
+ if (waitTime > 0) {
3523
+ if (strategy === "reject") {
3524
+ throw {
3525
+ type: "RATE_LIMIT_EXCEEDED",
3526
+ limiterName: name,
3527
+ retryAfterMs: waitTime
3528
+ };
3529
+ }
3530
+ await waitForTokens(cost);
3531
+ }
3532
+ return operation();
3533
+ },
3534
+ async executeResult(operation, cost = 1) {
3535
+ if (cost > maxTokens) {
3536
+ return err2({
3537
+ type: "RATE_LIMIT_EXCEEDED",
3538
+ limiterName: name,
3539
+ retryAfterMs: Math.ceil(cost / refillRate)
3540
+ });
3541
+ }
3542
+ const waitTime = tryConsume(cost);
3543
+ if (waitTime > 0) {
3544
+ if (strategy === "reject") {
3545
+ return err2({
3546
+ type: "RATE_LIMIT_EXCEEDED",
3547
+ limiterName: name,
3548
+ retryAfterMs: waitTime
3549
+ });
3550
+ }
3551
+ await waitForTokens(cost);
3552
+ }
3553
+ return operation();
3554
+ },
3555
+ getStats() {
3556
+ refill();
3557
+ return {
3558
+ availableTokens: tokens,
3559
+ maxTokens,
3560
+ tokensPerSecond,
3561
+ waitingCount: waitQueue.length
3562
+ };
3563
+ },
3564
+ reset() {
3565
+ tokens = maxTokens;
3566
+ lastRefill = Date.now();
3567
+ waitQueue.length = 0;
3568
+ }
3569
+ };
3570
+ }
3571
+ var rateLimiterPresets = {
3572
+ /**
3573
+ * Typical API rate limit (10 req/s).
3574
+ */
3575
+ api: {
3576
+ maxPerSecond: 10,
3577
+ burstCapacity: 20,
3578
+ strategy: "wait"
3579
+ },
3580
+ /**
3581
+ * Database pool limit (concurrent connections).
3582
+ */
3583
+ database: {
3584
+ maxConcurrent: 10,
3585
+ strategy: "queue",
3586
+ maxQueueSize: 100
3587
+ },
3588
+ /**
3589
+ * Aggressive rate limit for external APIs (5 req/s).
3590
+ */
3591
+ external: {
3592
+ maxPerSecond: 5,
3593
+ burstCapacity: 10,
3594
+ strategy: "wait"
3595
+ }
3596
+ };
3597
+
3598
+ // src/cache.ts
3599
+ function toMs2(duration) {
3600
+ if (typeof duration === "string") {
3601
+ const parsed = parse(duration);
3602
+ if (!parsed) {
3603
+ throw new Error(`Invalid duration string: ${duration}`);
3604
+ }
3605
+ return parsed.millis;
3606
+ }
3607
+ return duration.millis;
3608
+ }
3609
+ function cached(fn) {
3610
+ let state = { status: "empty" };
3611
+ return async () => {
3612
+ if (state.status === "filled") {
3613
+ return state.value;
3614
+ }
3615
+ if (state.status === "pending") {
3616
+ return state.promise;
3617
+ }
3618
+ const promise = Promise.resolve(fn()).then((value) => {
3619
+ state = { status: "filled", value };
3620
+ return value;
3621
+ });
3622
+ state = { status: "pending", promise };
3623
+ return promise;
3624
+ };
3625
+ }
3626
+ function cachedWithTTL(fn, options) {
3627
+ const ttlMs = toMs2(options.ttl);
3628
+ let state = { status: "empty" };
3629
+ return async () => {
3630
+ const now = Date.now();
3631
+ if (state.status === "filled" && now < state.expiresAt) {
3632
+ return state.value;
3633
+ }
3634
+ if (state.status === "pending") {
3635
+ return state.promise;
3636
+ }
3637
+ const promise = Promise.resolve(fn()).then((value) => {
3638
+ state = {
3639
+ status: "filled",
3640
+ value,
3641
+ expiresAt: Date.now() + ttlMs
3642
+ };
3643
+ return value;
3644
+ });
3645
+ state = { status: "pending", promise };
3646
+ return promise;
3647
+ };
3648
+ }
3649
+ function cachedFunction(fn, options = {}) {
3650
+ const {
3651
+ keyFn = (...args) => JSON.stringify(args),
3652
+ maxSize = Infinity
3653
+ } = options;
3654
+ const ttlMs = options.ttl ? toMs2(options.ttl) : void 0;
3655
+ const cache = /* @__PURE__ */ new Map();
3656
+ const pending = /* @__PURE__ */ new Map();
3657
+ let hits = 0;
3658
+ let misses = 0;
3659
+ function evictOldest() {
3660
+ if (cache.size <= maxSize) return;
3661
+ let oldestKey = null;
3662
+ let oldestTime = Infinity;
3663
+ for (const [key, entry] of cache.entries()) {
3664
+ if (entry.timestamp < oldestTime) {
3665
+ oldestTime = entry.timestamp;
3666
+ oldestKey = key;
3667
+ }
3668
+ }
3669
+ if (oldestKey) {
3670
+ cache.delete(oldestKey);
3671
+ }
3672
+ }
3673
+ const memoized = async (...args) => {
3674
+ const key = keyFn(...args);
3675
+ const now = Date.now();
3676
+ const cached2 = cache.get(key);
3677
+ if (cached2) {
3678
+ if (cached2.expiresAt && now >= cached2.expiresAt) {
3679
+ cache.delete(key);
3680
+ } else {
3681
+ hits++;
3682
+ return cached2.value;
3683
+ }
3684
+ }
3685
+ const pendingPromise = pending.get(key);
3686
+ if (pendingPromise) {
3687
+ return pendingPromise;
3688
+ }
3689
+ misses++;
3690
+ const promise = Promise.resolve(fn(...args)).then((value) => {
3691
+ const entry = {
3692
+ value,
3693
+ timestamp: Date.now(),
3694
+ expiresAt: ttlMs ? Date.now() + ttlMs : void 0
3695
+ };
3696
+ cache.set(key, entry);
3697
+ pending.delete(key);
3698
+ evictOldest();
3699
+ return value;
3700
+ });
3701
+ pending.set(key, promise);
3702
+ try {
3703
+ return await promise;
3704
+ } catch (error) {
3705
+ pending.delete(key);
3706
+ throw error;
3707
+ }
3708
+ };
3709
+ memoized.clear = () => {
3710
+ cache.clear();
3711
+ pending.clear();
3712
+ };
3713
+ memoized.delete = (...args) => {
3714
+ const key = keyFn(...args);
3715
+ return cache.delete(key);
3716
+ };
3717
+ memoized.has = (...args) => {
3718
+ const key = keyFn(...args);
3719
+ const entry = cache.get(key);
3720
+ if (!entry) return false;
3721
+ if (entry.expiresAt && Date.now() >= entry.expiresAt) {
3722
+ cache.delete(key);
3723
+ return false;
3724
+ }
3725
+ return true;
3726
+ };
3727
+ memoized.getStats = () => ({
3728
+ hits,
3729
+ misses,
3730
+ size: cache.size
3731
+ });
3732
+ return memoized;
3733
+ }
3734
+ function once(fn) {
3735
+ let state = { status: "idle" };
3736
+ const onceFn = async () => {
3737
+ if (state.status === "done") {
3738
+ return state.value;
3739
+ }
3740
+ if (state.status === "failed") {
3741
+ throw state.error;
3742
+ }
3743
+ if (state.status === "running") {
3744
+ return state.promise;
3745
+ }
3746
+ const promise = Promise.resolve(fn()).then((value) => {
3747
+ state = { status: "done", value };
3748
+ return value;
3749
+ }).catch((error) => {
3750
+ state = { status: "failed", error };
3751
+ throw error;
3752
+ });
3753
+ state = { status: "running", promise };
3754
+ return promise;
3755
+ };
3756
+ Object.defineProperty(onceFn, "called", {
3757
+ get: () => state.status !== "idle"
3758
+ });
3759
+ Object.defineProperty(onceFn, "completed", {
3760
+ get: () => state.status === "done"
3761
+ });
3762
+ Object.defineProperty(onceFn, "failed", {
3763
+ get: () => state.status === "failed"
3764
+ });
3765
+ onceFn.reset = () => {
3766
+ state = { status: "idle" };
3767
+ };
3768
+ return onceFn;
3769
+ }
3770
+ function createCache(config = {}) {
3771
+ const { maxSize = Infinity } = config;
3772
+ const defaultTTLMs = config.defaultTTL ? toMs2(config.defaultTTL) : void 0;
3773
+ const store = /* @__PURE__ */ new Map();
3774
+ let hits = 0;
3775
+ let misses = 0;
3776
+ function isExpired(entry) {
3777
+ return entry.expiresAt !== void 0 && Date.now() >= entry.expiresAt;
3778
+ }
3779
+ function evictOldest() {
3780
+ if (store.size <= maxSize) return;
3781
+ let oldestKey = null;
3782
+ let oldestTime = Infinity;
3783
+ for (const [key, entry] of store.entries()) {
3784
+ if (entry.timestamp < oldestTime) {
3785
+ oldestTime = entry.timestamp;
3786
+ oldestKey = key;
3787
+ }
3788
+ }
3789
+ if (oldestKey !== null) {
3790
+ store.delete(oldestKey);
3791
+ }
3792
+ }
3793
+ return {
3794
+ get(key) {
3795
+ const entry = store.get(key);
3796
+ if (!entry) {
3797
+ misses++;
3798
+ return void 0;
3799
+ }
3800
+ if (isExpired(entry)) {
3801
+ store.delete(key);
3802
+ misses++;
3803
+ return void 0;
3804
+ }
3805
+ hits++;
3806
+ return entry.value;
3807
+ },
3808
+ set(key, value, options) {
3809
+ const ttlMs = options?.ttl ? toMs2(options.ttl) : defaultTTLMs;
3810
+ const now = Date.now();
3811
+ store.set(key, {
3812
+ value,
3813
+ timestamp: now,
3814
+ expiresAt: ttlMs ? now + ttlMs : void 0
3815
+ });
3816
+ evictOldest();
3817
+ },
3818
+ has(key) {
3819
+ const entry = store.get(key);
3820
+ if (!entry) return false;
3821
+ if (isExpired(entry)) {
3822
+ store.delete(key);
3823
+ return false;
3824
+ }
3825
+ return true;
3826
+ },
3827
+ delete(key) {
3828
+ return store.delete(key);
3829
+ },
3830
+ clear() {
3831
+ store.clear();
3832
+ },
3833
+ get size() {
3834
+ return store.size;
3835
+ },
3836
+ getStats() {
3837
+ return { hits, misses, size: store.size };
3838
+ }
3839
+ };
3840
+ }
3841
+
3842
+ // src/singleflight.ts
3843
+ function singleflight(operation, options) {
3844
+ const inflight = /* @__PURE__ */ new Map();
3845
+ const cache = options.ttl ? /* @__PURE__ */ new Map() : null;
3846
+ return async (...args) => {
3847
+ const key = options.key(...args);
3848
+ if (cache) {
3849
+ const cached2 = cache.get(key);
3850
+ if (cached2 && cached2.expiresAt > Date.now()) {
3851
+ return cached2.result;
3852
+ }
3853
+ if (cached2) {
3854
+ cache.delete(key);
3855
+ }
3856
+ }
3857
+ const existing = inflight.get(key);
3858
+ if (existing) {
3859
+ return existing;
3860
+ }
3861
+ const promise = operation(...args).then((result) => {
3862
+ if (cache && options.ttl && result.ok) {
3863
+ cache.set(key, {
3864
+ result,
3865
+ expiresAt: Date.now() + options.ttl
3866
+ });
3867
+ }
3868
+ return result;
3869
+ }).finally(() => {
3870
+ inflight.delete(key);
3871
+ });
3872
+ inflight.set(key, promise);
3873
+ return promise;
3874
+ };
3875
+ }
3876
+ function createSingleflightGroup() {
3877
+ const inflight = /* @__PURE__ */ new Map();
3878
+ return {
3879
+ execute: async (key, operation) => {
3880
+ const existing = inflight.get(key);
3881
+ if (existing) {
3882
+ return existing;
3883
+ }
3884
+ const promise = operation().then((result) => result).finally(() => {
3885
+ inflight.delete(key);
3886
+ });
3887
+ inflight.set(key, promise);
3888
+ return promise;
3889
+ },
3890
+ isInflight: (key) => inflight.has(key),
3891
+ size: () => inflight.size,
3892
+ clear: () => inflight.clear()
3893
+ };
3894
+ }
3895
+
3896
+ // src/policies.ts
3897
+ function mergePolicies(...policies) {
3898
+ const result = {};
3899
+ for (const policy of policies) {
3900
+ if (policy.key !== void 0) result.key = policy.key;
3901
+ if (policy.retry !== void 0) {
3902
+ result.retry = result.retry ? { ...result.retry, ...policy.retry } : { ...policy.retry };
3903
+ }
3904
+ if (policy.timeout !== void 0) {
3905
+ result.timeout = result.timeout ? { ...result.timeout, ...policy.timeout } : { ...policy.timeout };
3906
+ }
3907
+ }
3908
+ return result;
3909
+ }
3910
+ function createPolicyApplier(...basePolicies) {
3911
+ const basePolicy = mergePolicies(...basePolicies);
3912
+ return (stepOptions2) => {
3913
+ const opts = stepOptions2 ?? {};
3914
+ return mergePolicies(basePolicy, opts);
3915
+ };
3916
+ }
3917
+ function createPolicyBundle(name, ...policies) {
3918
+ return {
3919
+ name,
3920
+ policy: mergePolicies(...policies)
3921
+ };
3922
+ }
3923
+ function retryPolicy(options) {
3924
+ return { retry: options };
3925
+ }
3926
+ var retryPolicies = {
3927
+ /**
3928
+ * No retry - fail immediately on error.
3929
+ */
3930
+ none: retryPolicy({ attempts: 1 }),
3931
+ /**
3932
+ * Quick retry for transient errors (3 attempts, fast backoff).
3933
+ */
3934
+ transient: retryPolicy({
3935
+ attempts: 3,
3936
+ backoff: "exponential",
3937
+ initialDelay: 100,
3938
+ maxDelay: 1e3,
3939
+ jitter: true
3940
+ }),
3941
+ /**
3942
+ * Standard retry for API calls (3 attempts, moderate backoff).
3943
+ */
3944
+ standard: retryPolicy({
3945
+ attempts: 3,
3946
+ backoff: "exponential",
3947
+ initialDelay: 200,
3948
+ maxDelay: 5e3,
3949
+ jitter: true
3950
+ }),
3951
+ /**
3952
+ * Aggressive retry for critical operations (5 attempts, longer backoff).
3953
+ */
3954
+ aggressive: retryPolicy({
3955
+ attempts: 5,
3956
+ backoff: "exponential",
3957
+ initialDelay: 500,
3958
+ maxDelay: 3e4,
3959
+ jitter: true
3960
+ }),
3961
+ /**
3962
+ * Fixed interval retry (useful for polling).
3963
+ */
3964
+ fixed: (attempts, delayMs) => retryPolicy({
3965
+ attempts,
3966
+ backoff: "fixed",
3967
+ initialDelay: delayMs,
3968
+ jitter: false
3969
+ }),
3970
+ /**
3971
+ * Linear backoff retry.
3972
+ */
3973
+ linear: (attempts, initialDelay) => retryPolicy({
3974
+ attempts,
3975
+ backoff: "linear",
3976
+ initialDelay,
3977
+ jitter: true
3978
+ }),
3979
+ /**
3980
+ * Custom retry policy builder.
3981
+ */
3982
+ custom: (options) => retryPolicy({
3983
+ backoff: "exponential",
3984
+ initialDelay: 100,
3985
+ maxDelay: 3e4,
3986
+ jitter: true,
3987
+ ...options
3988
+ })
3989
+ };
3990
+ function timeoutPolicy(options) {
3991
+ return { timeout: options };
3992
+ }
3993
+ var timeoutPolicies = {
3994
+ /**
3995
+ * No timeout.
3996
+ */
3997
+ none: {},
3998
+ /**
3999
+ * Fast timeout for quick operations (1 second).
4000
+ */
4001
+ fast: timeoutPolicy({ ms: 1e3 }),
4002
+ /**
4003
+ * Standard API timeout (5 seconds).
4004
+ */
4005
+ api: timeoutPolicy({ ms: 5e3 }),
4006
+ /**
4007
+ * Extended timeout for slower operations (30 seconds).
4008
+ */
4009
+ extended: timeoutPolicy({ ms: 3e4 }),
4010
+ /**
4011
+ * Long timeout for batch operations (2 minutes).
4012
+ */
4013
+ long: timeoutPolicy({ ms: 12e4 }),
4014
+ /**
4015
+ * Custom timeout in milliseconds.
4016
+ */
4017
+ ms: (ms) => timeoutPolicy({ ms }),
4018
+ /**
4019
+ * Custom timeout in seconds.
4020
+ */
4021
+ seconds: (seconds2) => timeoutPolicy({ ms: seconds2 * 1e3 }),
4022
+ /**
4023
+ * Timeout with custom error.
4024
+ */
4025
+ withError: (ms, error) => timeoutPolicy({ ms, error }),
4026
+ /**
4027
+ * Timeout with AbortSignal support.
4028
+ */
4029
+ withSignal: (ms) => timeoutPolicy({ ms, signal: true })
4030
+ };
4031
+ var servicePolicies = {
4032
+ /**
4033
+ * Policy for external HTTP APIs.
4034
+ * - 5 second timeout
4035
+ * - 3 retries with exponential backoff
4036
+ */
4037
+ httpApi: mergePolicies(
4038
+ timeoutPolicies.api,
4039
+ retryPolicies.standard
4040
+ ),
4041
+ /**
4042
+ * Policy for database operations.
4043
+ * - 30 second timeout
4044
+ * - 2 retries for transient errors
4045
+ */
4046
+ database: mergePolicies(
4047
+ timeoutPolicies.extended,
4048
+ retryPolicy({
4049
+ attempts: 2,
4050
+ backoff: "exponential",
4051
+ initialDelay: 100,
4052
+ maxDelay: 2e3,
4053
+ jitter: true
4054
+ })
4055
+ ),
4056
+ /**
4057
+ * Policy for cache operations.
4058
+ * - 1 second timeout
4059
+ * - No retry (cache misses are not errors)
4060
+ */
4061
+ cache: mergePolicies(
4062
+ timeoutPolicies.fast,
4063
+ retryPolicies.none
4064
+ ),
4065
+ /**
4066
+ * Policy for message queue operations.
4067
+ * - 30 second timeout
4068
+ * - 5 retries with longer backoff
4069
+ */
4070
+ messageQueue: mergePolicies(
4071
+ timeoutPolicies.extended,
4072
+ retryPolicies.aggressive
4073
+ ),
4074
+ /**
4075
+ * Policy for file operations.
4076
+ * - 2 minute timeout
4077
+ * - 3 retries
4078
+ */
4079
+ fileSystem: mergePolicies(
4080
+ timeoutPolicies.long,
4081
+ retryPolicies.standard
4082
+ ),
4083
+ /**
4084
+ * Policy for third-party services with rate limits.
4085
+ * - 10 second timeout
4086
+ * - 5 retries with linear backoff
4087
+ */
4088
+ rateLimited: mergePolicies(
4089
+ timeoutPolicy({ ms: 1e4 }),
4090
+ retryPolicy({
4091
+ attempts: 5,
4092
+ backoff: "linear",
4093
+ initialDelay: 1e3,
4094
+ maxDelay: 1e4,
4095
+ jitter: true
4096
+ })
4097
+ )
4098
+ };
4099
+ function withPolicy(policy, stepOptions2) {
4100
+ const opts = stepOptions2 ?? {};
4101
+ return mergePolicies(policy, opts);
4102
+ }
4103
+ function withPolicies(policies, stepOptions2) {
4104
+ const opts = stepOptions2 ?? {};
4105
+ return mergePolicies(...policies, opts);
4106
+ }
4107
+ function conditionalPolicy(condition, policy, elsePolicy = {}) {
4108
+ return condition ? policy : elsePolicy;
4109
+ }
4110
+ function envPolicy(envPolicies, currentEnv = process.env.NODE_ENV ?? "development", defaultPolicy = {}) {
4111
+ return envPolicies[currentEnv] ?? defaultPolicy;
4112
+ }
4113
+ function createPolicyRegistry() {
4114
+ const policies = /* @__PURE__ */ new Map();
4115
+ return {
4116
+ register(name, policy) {
4117
+ policies.set(name, policy);
4118
+ },
4119
+ get(name) {
4120
+ return policies.get(name);
4121
+ },
4122
+ has(name) {
4123
+ return policies.has(name);
4124
+ },
4125
+ names() {
4126
+ return Array.from(policies.keys());
4127
+ },
4128
+ apply(policyName, stepOptions2) {
4129
+ const policy = policies.get(policyName);
4130
+ if (!policy) {
4131
+ throw new Error(`Policy not found: ${policyName}`);
4132
+ }
4133
+ return withPolicy(policy, stepOptions2);
4134
+ }
4135
+ };
4136
+ }
4137
+ function stepOptions() {
4138
+ const policies = [];
4139
+ const builder = {
4140
+ key(key) {
4141
+ policies.push({ key });
4142
+ return builder;
4143
+ },
4144
+ policy(policy) {
4145
+ policies.push(policy);
4146
+ return builder;
4147
+ },
4148
+ timeout(ms) {
4149
+ policies.push(timeoutPolicy({ ms }));
4150
+ return builder;
4151
+ },
4152
+ retry(options) {
4153
+ policies.push(retryPolicy(options));
4154
+ return builder;
4155
+ },
4156
+ retries(attempts) {
4157
+ policies.push(retryPolicies.custom({ attempts }));
4158
+ return builder;
4159
+ },
4160
+ build() {
4161
+ return mergePolicies(...policies);
4162
+ }
4163
+ };
4164
+ return builder;
4165
+ }
4166
+
4167
+ // src/conditional.ts
4168
+ function generateDecisionId() {
4169
+ return `decision_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
4170
+ }
4171
+ function emitSkipped(ctx, options, decisionId) {
4172
+ if (!ctx?.onEvent) return;
4173
+ const event = {
4174
+ type: "step_skipped",
4175
+ workflowId: ctx.workflowId,
4176
+ stepKey: options?.key,
4177
+ name: options?.name,
4178
+ reason: options?.reason,
4179
+ decisionId,
4180
+ ts: Date.now()
4181
+ };
4182
+ const eventWithContext = event.context !== void 0 || ctx.context === void 0 ? event : { ...event, context: ctx.context };
4183
+ ctx.onEvent(eventWithContext);
4184
+ }
4185
+ function when2(condition, operation, options, ctx) {
4186
+ if (condition) {
4187
+ return operation();
4188
+ }
4189
+ const decisionId = generateDecisionId();
4190
+ emitSkipped(ctx, options, decisionId);
4191
+ return void 0;
4192
+ }
4193
+ function unless(condition, operation, options, ctx) {
4194
+ return when2(!condition, operation, options, ctx);
4195
+ }
4196
+ function whenOr(condition, operation, defaultValue, options, ctx) {
4197
+ if (condition) {
4198
+ return operation();
4199
+ }
4200
+ const decisionId = generateDecisionId();
4201
+ emitSkipped(ctx, options, decisionId);
4202
+ return defaultValue;
4203
+ }
4204
+ function unlessOr(condition, operation, defaultValue, options, ctx) {
4205
+ return whenOr(!condition, operation, defaultValue, options, ctx);
4206
+ }
4207
+ function createConditionalHelpers(ctx) {
4208
+ return {
4209
+ /**
4210
+ * Run a step only if condition is true, return undefined if skipped.
4211
+ */
4212
+ when: (condition, operation, options) => when2(condition, operation, options, ctx),
4213
+ /**
4214
+ * Run a step only if condition is false, return undefined if skipped.
4215
+ */
4216
+ unless: (condition, operation, options) => unless(condition, operation, options, ctx),
4217
+ /**
4218
+ * Run a step only if condition is true, return default value if skipped.
4219
+ */
4220
+ whenOr: (condition, operation, defaultValue, options) => whenOr(condition, operation, defaultValue, options, ctx),
4221
+ /**
4222
+ * Run a step only if condition is false, return default value if skipped.
4223
+ */
4224
+ unlessOr: (condition, operation, defaultValue, options) => unlessOr(condition, operation, defaultValue, options, ctx)
4225
+ };
4226
+ }
4227
+ export {
4228
+ ALL_SLUGS,
4229
+ AWAITLY_CANCELLED,
4230
+ AWAITLY_SLUGS,
4231
+ AWAITLY_SYSTEM_ERROR_CLASSES,
4232
+ AWAITLY_TIMEOUT,
4233
+ AWAITLY_UNEXPECTED,
4234
+ CircuitBreakerOpenError,
4235
+ CircuitOpenError,
4236
+ CompensationError,
4237
+ DESERIALIZATION_ERROR,
4238
+ Duration,
4239
+ EARLY_EXIT_SYMBOL,
4240
+ Match,
4241
+ NetworkError,
4242
+ NotFoundError,
4243
+ PROMISE_REJECTED,
4244
+ RateLimitError,
4245
+ RetryExhaustedError,
4246
+ STEP_TIMEOUT_MARKER,
4247
+ TaggedError,
4248
+ TimeoutError,
4249
+ UnauthorizedError,
4250
+ UnexpectedError,
4251
+ UnwrapError,
4252
+ ValidationError,
4253
+ add,
4254
+ all,
4255
+ allAsync,
4256
+ allSettled,
4257
+ allSettledAsync,
4258
+ andThen,
4259
+ any,
4260
+ anyAsync,
4261
+ bimap,
4262
+ cached,
4263
+ cachedFunction,
4264
+ cachedWithTTL,
4265
+ circuitBreakerPresets,
4266
+ clamp,
4267
+ conditionalPolicy,
4268
+ createCache,
4269
+ createCircuitBreaker,
4270
+ createCombinedLimiter,
4271
+ createConcurrencyLimiter,
4272
+ createConditionalHelpers,
4273
+ createCostBasedRateLimiter,
4274
+ createEarlyExit,
4275
+ createFixedWindowLimiter,
4276
+ createPolicyApplier,
4277
+ createPolicyBundle,
4278
+ createPolicyRegistry,
4279
+ createRateLimiter,
4280
+ createSingleflightGroup,
4281
+ days,
4282
+ deserialize,
4283
+ divide,
4284
+ envPolicy,
4285
+ equals,
4286
+ err,
4287
+ exhaustive,
4288
+ fallback,
4289
+ flatten,
4290
+ format,
4291
+ from,
4292
+ fromNullable,
4293
+ fromPromise,
4294
+ getStepTimeoutMeta,
4295
+ greaterThan,
4296
+ greaterThanOrEqual,
4297
+ hours,
4298
+ hydrate,
4299
+ infinity,
4300
+ isAwaitlyError,
4301
+ isAwaitlySlug,
4302
+ isCircuitBreakerOpenError,
4303
+ isCircuitOpenError,
4304
+ isCompensationError,
4305
+ isDuration,
4306
+ isEarlyExit,
4307
+ isErr,
4308
+ isFinite,
4309
+ isInfinite,
4310
+ isNetworkError,
4311
+ isNotFoundError,
4312
+ isOk,
4313
+ isOneOf,
4314
+ isPromiseRejectedError,
4315
+ isQueueFullError,
4316
+ isRateLimitError,
4317
+ isRateLimitExceededError,
4318
+ isRetryExhaustedError,
4319
+ isSerializedResult,
4320
+ isStepTimeoutError,
4321
+ is as isTag,
4322
+ isTimeoutError,
4323
+ isUnauthorizedError,
4324
+ isUnexpectedError,
4325
+ isValidationError,
4326
+ isZero,
4327
+ lessThan,
4328
+ lessThanOrEqual,
4329
+ makeError,
4330
+ map,
4331
+ mapError,
4332
+ mapErrorTry,
4333
+ mapTry,
4334
+ match,
4335
+ matchError,
4336
+ matchErrorPartial,
4337
+ orElse2 as matchOrElse,
4338
+ tag as matchTag,
4339
+ tags2 as matchTags,
4340
+ matchValue,
4341
+ max,
4342
+ mergePolicies,
4343
+ millis,
4344
+ min,
4345
+ minutes,
4346
+ multiply,
4347
+ ok,
4348
+ once,
4349
+ orElse,
4350
+ orElseAsync,
4351
+ orElseValue,
4352
+ parse,
4353
+ partition,
4354
+ rateLimiterPresets,
4355
+ recover,
4356
+ recoverAsync,
4357
+ retry,
4358
+ retryPolicies,
4359
+ retryPolicy,
4360
+ run,
4361
+ runOrNull,
4362
+ runOrThrow,
4363
+ runOrThrowAsync,
4364
+ runOrUndefined,
4365
+ seconds,
4366
+ serialize,
4367
+ servicePolicies,
4368
+ singleflight,
4369
+ slugCategory,
4370
+ slugDocsUrl,
4371
+ stepOptions,
4372
+ subtract,
4373
+ tags,
4374
+ tap,
4375
+ tapError,
4376
+ timeout,
4377
+ timeoutPolicies,
4378
+ timeoutPolicy,
4379
+ toDays,
4380
+ toHours,
4381
+ toMillis,
4382
+ toMinutes,
4383
+ toSeconds,
4384
+ tryAsync,
4385
+ unless,
4386
+ unlessOr,
4387
+ unwrap,
4388
+ unwrapOr,
4389
+ unwrapOrElse,
4390
+ when2 as when,
4391
+ whenOr,
4392
+ withDeps,
4393
+ withPolicies,
4394
+ withPolicy,
4395
+ zero,
4396
+ zip,
4397
+ zipAsync
4398
+ };
2
4399
  //# sourceMappingURL=index.js.map