@logixjs/core 0.0.1 → 0.0.2

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 (300) hide show
  1. package/LICENSE +201 -0
  2. package/dist/{Bound-BN1DQ_lM.d.ts → Bound-CEa1ihvH.d.ts} +2 -2
  3. package/dist/{Bound-BPIfH9SS.d.cts → Bound-CNLNkC7c.d.cts} +2 -2
  4. package/dist/Bound.cjs +620 -163
  5. package/dist/Bound.cjs.map +1 -1
  6. package/dist/Bound.d.cts +3 -3
  7. package/dist/Bound.d.ts +3 -3
  8. package/dist/Bound.js +14 -14
  9. package/dist/{Debug-Bq8Sqjcr.d.cts → Debug-BhMYr-1i.d.cts} +3 -3
  10. package/dist/{Debug-B5q5Bkzx.d.ts → Debug-ByM7m4Ft.d.ts} +3 -3
  11. package/dist/Debug.cjs +553 -32
  12. package/dist/Debug.cjs.map +1 -1
  13. package/dist/Debug.d.cts +10 -8
  14. package/dist/Debug.d.ts +10 -8
  15. package/dist/Debug.js +12 -10
  16. package/dist/EffectOp.cjs.map +1 -1
  17. package/dist/EffectOp.js +2 -3
  18. package/dist/EffectOp.js.map +1 -1
  19. package/dist/Env.cjs +664 -6
  20. package/dist/Env.cjs.map +1 -1
  21. package/dist/Env.js +5 -2
  22. package/dist/ExternalStore-BAz83PVq.d.cts +60 -0
  23. package/dist/ExternalStore-BYWPbYs8.d.ts +60 -0
  24. package/dist/ExternalStore.cjs +746 -0
  25. package/dist/ExternalStore.cjs.map +1 -0
  26. package/dist/ExternalStore.d.cts +4 -0
  27. package/dist/ExternalStore.d.ts +4 -0
  28. package/dist/ExternalStore.js +19 -0
  29. package/dist/ExternalStore.js.map +1 -0
  30. package/dist/{Flow-1fZT8MpX.d.cts → Flow-BlSoMmhV.d.cts} +2 -2
  31. package/dist/{Flow-BhpjE22E.d.ts → Flow-CQSGve5c.d.ts} +2 -2
  32. package/dist/Flow.cjs +2 -2
  33. package/dist/Flow.cjs.map +1 -1
  34. package/dist/Flow.d.cts +4 -4
  35. package/dist/Flow.d.ts +4 -4
  36. package/dist/Flow.js +7 -8
  37. package/dist/{Handle-D_cLW1Z3.d.ts → Handle-B7PSmsrY.d.ts} +1 -1
  38. package/dist/{Handle-D8D1zPb_.d.cts → Handle-ByovhL-c.d.cts} +1 -1
  39. package/dist/Handle.d.cts +3 -3
  40. package/dist/Handle.d.ts +3 -3
  41. package/dist/{Kernel-CnGE1Fyk.d.ts → Kernel-DGSpS4GM.d.ts} +2 -2
  42. package/dist/{Kernel-8kC-jOda.d.cts → Kernel-DZAk-Mrn.d.cts} +2 -2
  43. package/dist/Kernel.cjs +680 -22
  44. package/dist/Kernel.cjs.map +1 -1
  45. package/dist/Kernel.d.cts +10 -8
  46. package/dist/Kernel.d.ts +10 -8
  47. package/dist/Kernel.js +7 -4
  48. package/dist/{Link-Db7975nU.d.ts → Link-Cm4eR9n0.d.ts} +10 -3
  49. package/dist/{Link-fX8x1eCK.d.cts → Link-DF8i8iWR.d.cts} +10 -3
  50. package/dist/Link.cjs +1128 -86
  51. package/dist/Link.cjs.map +1 -1
  52. package/dist/Link.d.cts +3 -3
  53. package/dist/Link.d.ts +3 -3
  54. package/dist/Link.js +30 -25
  55. package/dist/{Logic-DRh4sDZj.d.cts → Logic-BcQA0AvE.d.cts} +1 -1
  56. package/dist/{Logic-BRjEMr-W.d.ts → Logic-OotSE1xw.d.ts} +1 -1
  57. package/dist/Logic.d.cts +3 -3
  58. package/dist/Logic.d.ts +3 -3
  59. package/dist/{MatchBuilder-CJk5oCkR.d.cts → MatchBuilder-BNDJ8waF.d.ts} +1 -1
  60. package/dist/{MatchBuilder-0QOc-nlU.d.ts → MatchBuilder-CvZ5WY1B.d.cts} +1 -1
  61. package/dist/MatchBuilder.d.cts +4 -4
  62. package/dist/MatchBuilder.d.ts +4 -4
  63. package/dist/Middleware-D8tUDLv_.d.cts +100 -0
  64. package/dist/Middleware-DS7CbTTN.d.ts +100 -0
  65. package/dist/Middleware.cjs +461 -13
  66. package/dist/Middleware.cjs.map +1 -1
  67. package/dist/Middleware.d.cts +2 -86
  68. package/dist/Middleware.d.ts +2 -86
  69. package/dist/Middleware.js +13 -11
  70. package/dist/{Module-DnzluX2J.d.ts → Module-CFj0I2yE.d.ts} +45 -18
  71. package/dist/{Module-B_0xRDMR.d.cts → Module-DpXPW9EQ.d.cts} +45 -18
  72. package/dist/Module.cjs +8583 -5741
  73. package/dist/Module.cjs.map +1 -1
  74. package/dist/Module.d.cts +5 -4
  75. package/dist/Module.d.ts +5 -4
  76. package/dist/Module.js +32 -27
  77. package/dist/ModuleTag-BcVF6z7B.d.ts +113 -0
  78. package/dist/ModuleTag-DuZXo_NS.d.cts +113 -0
  79. package/dist/ModuleTag.cjs +2609 -1232
  80. package/dist/ModuleTag.cjs.map +1 -1
  81. package/dist/ModuleTag.d.cts +4 -4
  82. package/dist/ModuleTag.d.ts +4 -4
  83. package/dist/ModuleTag.js +28 -25
  84. package/dist/{Observability-cY4kLn0S.d.ts → Observability-D-ZWeEVb.d.ts} +22 -15
  85. package/dist/{Observability-COqEvp2C.d.cts → Observability-V7sRMYTh.d.cts} +22 -15
  86. package/dist/Observability.cjs +1938 -640
  87. package/dist/Observability.cjs.map +1 -1
  88. package/dist/Observability.d.cts +4 -4
  89. package/dist/Observability.d.ts +4 -4
  90. package/dist/Observability.js +21 -19
  91. package/dist/{Process-mL8fHDSB.d.cts → Process-B55aJMFk.d.cts} +29 -4
  92. package/dist/{Process-CM9xbMdP.d.ts → Process-DvhFEwUS.d.ts} +29 -4
  93. package/dist/Process.cjs +1122 -85
  94. package/dist/Process.cjs.map +1 -1
  95. package/dist/Process.d.cts +4 -3
  96. package/dist/Process.d.ts +4 -3
  97. package/dist/Process.js +27 -22
  98. package/dist/{ReadQuery-BlMwhe-F.d.ts → ReadQuery-C4vZ8Prc.d.ts} +2 -2
  99. package/dist/{ReadQuery-SinbStGF.d.ts → ReadQuery-CafjlJQo.d.cts} +1 -1
  100. package/dist/{ReadQuery-SinbStGF.d.cts → ReadQuery-CafjlJQo.d.ts} +1 -1
  101. package/dist/{ReadQuery-CL5XlXts.d.cts → ReadQuery-mc0NgrFV.d.cts} +2 -2
  102. package/dist/ReadQuery.cjs +3 -3
  103. package/dist/ReadQuery.cjs.map +1 -1
  104. package/dist/ReadQuery.d.cts +2 -2
  105. package/dist/ReadQuery.d.ts +2 -2
  106. package/dist/ReadQuery.js +3 -3
  107. package/dist/{Reflection-CQnKwPXj.d.ts → Reflection-C8xZ267q.d.ts} +88 -7
  108. package/dist/{Reflection-Kabo1mlU.d.cts → Reflection-DP7Vsv3f.d.cts} +88 -7
  109. package/dist/Reflection.cjs +2934 -1553
  110. package/dist/Reflection.cjs.map +1 -1
  111. package/dist/Reflection.d.cts +14 -11
  112. package/dist/Reflection.d.ts +14 -11
  113. package/dist/Reflection.js +26 -21
  114. package/dist/Resource.cjs +670 -12
  115. package/dist/Resource.cjs.map +1 -1
  116. package/dist/Resource.js +6 -3
  117. package/dist/Root.cjs +675 -17
  118. package/dist/Root.cjs.map +1 -1
  119. package/dist/Root.js +7 -3
  120. package/dist/{Runtime-CtyzZG4i.d.ts → Runtime-BWc9YfUB.d.ts} +37 -7
  121. package/dist/{Runtime-B-aL-f29.d.cts → Runtime-PShIC4DW.d.cts} +37 -7
  122. package/dist/Runtime.cjs +1899 -809
  123. package/dist/Runtime.cjs.map +1 -1
  124. package/dist/Runtime.d.cts +14 -11
  125. package/dist/Runtime.d.ts +14 -11
  126. package/dist/Runtime.js +33 -28
  127. package/dist/ScopeRegistry.cjs +668 -10
  128. package/dist/ScopeRegistry.cjs.map +1 -1
  129. package/dist/ScopeRegistry.js +6 -3
  130. package/dist/{StateTrait-OWhbj12c.d.cts → StateTrait-CQsDlXJm.d.cts} +23 -6
  131. package/dist/{StateTrait-BGsZghTz.d.ts → StateTrait-YvJzVDKl.d.ts} +23 -6
  132. package/dist/StateTrait.cjs +1475 -370
  133. package/dist/StateTrait.cjs.map +1 -1
  134. package/dist/StateTrait.d.cts +7 -5
  135. package/dist/StateTrait.d.ts +7 -5
  136. package/dist/StateTrait.js +17 -14
  137. package/dist/{TraitLifecycle-LdIWmKlg.d.ts → TraitLifecycle-CjIBICAA.d.ts} +2 -2
  138. package/dist/{TraitLifecycle-CwV5WPFX.d.cts → TraitLifecycle-NmqGiXPC.d.cts} +2 -2
  139. package/dist/TraitLifecycle.cjs +489 -32
  140. package/dist/TraitLifecycle.cjs.map +1 -1
  141. package/dist/TraitLifecycle.d.cts +4 -4
  142. package/dist/TraitLifecycle.d.ts +4 -4
  143. package/dist/TraitLifecycle.js +7 -7
  144. package/dist/Workflow-BlFG_20_.d.cts +414 -0
  145. package/dist/Workflow-CW9S_aAP.d.ts +414 -0
  146. package/dist/Workflow.cjs +2977 -0
  147. package/dist/Workflow.cjs.map +1 -0
  148. package/dist/Workflow.d.cts +7 -0
  149. package/dist/Workflow.d.ts +7 -0
  150. package/dist/Workflow.js +55 -0
  151. package/dist/Workflow.js.map +1 -0
  152. package/dist/{chunk-G5ZBFPNU.js → chunk-2A4UKO2D.js} +2 -2
  153. package/dist/chunk-2DE6D42I.js +248 -0
  154. package/dist/chunk-2DE6D42I.js.map +1 -0
  155. package/dist/{chunk-ANLBCBDC.js → chunk-2DVLMSOE.js} +6 -6
  156. package/dist/{chunk-BE3HW4FY.js → chunk-34CF6OGE.js} +14 -16
  157. package/dist/chunk-34CF6OGE.js.map +1 -0
  158. package/dist/{chunk-ZFY7U2FR.js → chunk-3LPIXG56.js} +43 -3
  159. package/dist/chunk-3LPIXG56.js.map +1 -0
  160. package/dist/chunk-3VZYDNXZ.js +10 -0
  161. package/dist/chunk-3VZYDNXZ.js.map +1 -0
  162. package/dist/{chunk-3TMODYZV.js → chunk-3XO4HR6V.js} +2 -2
  163. package/dist/chunk-46FGVWRF.js +817 -0
  164. package/dist/chunk-46FGVWRF.js.map +1 -0
  165. package/dist/chunk-4LODUXFI.js +288 -0
  166. package/dist/chunk-4LODUXFI.js.map +1 -0
  167. package/dist/{chunk-GMPEOUP2.js → chunk-4MZ7BT3R.js} +2 -2
  168. package/dist/chunk-4MZ7BT3R.js.map +1 -0
  169. package/dist/{chunk-TKZ7MEIA.js → chunk-53GVPGSM.js} +2 -2
  170. package/dist/{chunk-KP7MUZNX.js → chunk-5W2V2NVJ.js} +2 -2
  171. package/dist/chunk-5W2V2NVJ.js.map +1 -0
  172. package/dist/chunk-6DACKW3D.js +613 -0
  173. package/dist/chunk-6DACKW3D.js.map +1 -0
  174. package/dist/chunk-AQ7L2QZ5.js +1395 -0
  175. package/dist/chunk-AQ7L2QZ5.js.map +1 -0
  176. package/dist/{chunk-NZJKFF45.js → chunk-C2UZZQ76.js} +2 -2
  177. package/dist/chunk-CCKP5Z6F.js +701 -0
  178. package/dist/chunk-CCKP5Z6F.js.map +1 -0
  179. package/dist/chunk-CUKM2XUW.js +27 -0
  180. package/dist/{chunk-QCHIQWAJ.js.map → chunk-CUKM2XUW.js.map} +1 -1
  181. package/dist/{chunk-M2RGJPXX.js → chunk-DBD6Q6JH.js} +3 -3
  182. package/dist/{chunk-ZGDVUPTM.js → chunk-EB4RGQO3.js} +2 -2
  183. package/dist/{chunk-PAYXCY6A.js → chunk-G7ESIQTI.js} +12 -14
  184. package/dist/chunk-G7ESIQTI.js.map +1 -0
  185. package/dist/chunk-GPBAZQ23.js +348 -0
  186. package/dist/chunk-GPBAZQ23.js.map +1 -0
  187. package/dist/{chunk-OFADUJWJ.js → chunk-I4LCE5OY.js} +3 -5
  188. package/dist/{chunk-OFADUJWJ.js.map → chunk-I4LCE5OY.js.map} +1 -1
  189. package/dist/{chunk-DFNM3WX2.js → chunk-IMCC6TBN.js} +158 -39
  190. package/dist/chunk-IMCC6TBN.js.map +1 -0
  191. package/dist/{chunk-76WT3HOR.js → chunk-IROZNQAF.js} +22 -21
  192. package/dist/chunk-IROZNQAF.js.map +1 -0
  193. package/dist/{chunk-TAAPQVZN.js → chunk-ISKNULNH.js} +2 -2
  194. package/dist/chunk-J3CWXIPV.js +242 -0
  195. package/dist/chunk-J3CWXIPV.js.map +1 -0
  196. package/dist/{chunk-PYOE4VSI.js → chunk-JBKYRTCS.js} +224 -161
  197. package/dist/chunk-JBKYRTCS.js.map +1 -0
  198. package/dist/{chunk-66ALHVEX.js → chunk-KKIAYH4X.js} +3 -3
  199. package/dist/{chunk-3RMKLXHX.js → chunk-KLDVG3SY.js} +2 -2
  200. package/dist/{chunk-BABLDP24.js → chunk-KSZQYSEH.js} +3 -3
  201. package/dist/chunk-KSZQYSEH.js.map +1 -0
  202. package/dist/{chunk-CW6T36TN.js → chunk-M3M7JFAH.js} +4 -4
  203. package/dist/chunk-M3M7JFAH.js.map +1 -0
  204. package/dist/{chunk-THATMZXD.js → chunk-MLB253V2.js} +2 -2
  205. package/dist/{chunk-THATMZXD.js.map → chunk-MLB253V2.js.map} +1 -1
  206. package/dist/{chunk-JGIWG6SR.js → chunk-MS77U77X.js} +664 -550
  207. package/dist/chunk-MS77U77X.js.map +1 -0
  208. package/dist/chunk-MW4FA3MW.js +23 -0
  209. package/dist/chunk-MW4FA3MW.js.map +1 -0
  210. package/dist/chunk-MYKNINNN.js +228 -0
  211. package/dist/chunk-MYKNINNN.js.map +1 -0
  212. package/dist/{chunk-4CQAV7YB.js → chunk-O6TTQXTY.js} +2 -2
  213. package/dist/{chunk-NBD3KUOZ.js → chunk-OJDJ4VDQ.js} +35 -24
  214. package/dist/chunk-OJDJ4VDQ.js.map +1 -0
  215. package/dist/{chunk-NQZ2OSGR.js → chunk-PVZEMNJY.js} +9 -9
  216. package/dist/chunk-PVZEMNJY.js.map +1 -0
  217. package/dist/chunk-RN26DV2M.js +271 -0
  218. package/dist/chunk-RN26DV2M.js.map +1 -0
  219. package/dist/{chunk-JCXGZRMU.js → chunk-RQQW3IQC.js} +3 -3
  220. package/dist/chunk-RQQW3IQC.js.map +1 -0
  221. package/dist/{chunk-24VULZ7A.js → chunk-TKOGZDD6.js} +3 -3
  222. package/dist/{chunk-EGK3KN7B.js → chunk-TQYLVXGY.js} +70 -39
  223. package/dist/chunk-TQYLVXGY.js.map +1 -0
  224. package/dist/{chunk-QMM6O4CD.js → chunk-UACD2CL2.js} +15 -3
  225. package/dist/{chunk-QMM6O4CD.js.map → chunk-UACD2CL2.js.map} +1 -1
  226. package/dist/{chunk-M3WTHJHJ.js → chunk-VH575UTV.js} +30 -34
  227. package/dist/chunk-VH575UTV.js.map +1 -0
  228. package/dist/{chunk-AUIR5O6W.js → chunk-WWBMC24F.js} +9 -15
  229. package/dist/chunk-WWBMC24F.js.map +1 -0
  230. package/dist/{chunk-JWOYLO27.js → chunk-WYJUJV4L.js} +80 -7
  231. package/dist/chunk-WYJUJV4L.js.map +1 -0
  232. package/dist/{chunk-EY4NZKDR.js → chunk-XFMMPYNU.js} +2 -2
  233. package/dist/chunk-Y4VRBIS6.js +35 -0
  234. package/dist/chunk-Y4VRBIS6.js.map +1 -0
  235. package/dist/{chunk-DMBALCE2.js → chunk-ZC7MSQ5U.js} +77 -4
  236. package/dist/chunk-ZC7MSQ5U.js.map +1 -0
  237. package/dist/{chunk-OGWBVHB3.js → chunk-ZCK6SCOE.js} +67 -8
  238. package/dist/chunk-ZCK6SCOE.js.map +1 -0
  239. package/dist/{chunk-IHVBV5C2.js → chunk-ZTFTABXV.js} +2 -1
  240. package/dist/chunk-ZTFTABXV.js.map +1 -0
  241. package/dist/index.cjs +9532 -5017
  242. package/dist/index.cjs.map +1 -1
  243. package/dist/index.d.cts +163 -27
  244. package/dist/index.d.ts +163 -27
  245. package/dist/index.js +119 -56
  246. package/dist/index.js.map +1 -1
  247. package/dist/{ir-BMP7yxJJ.d.cts → ir-C-Zm_GlZ.d.cts} +1 -1
  248. package/dist/{ir-DUOz6H-5.d.ts → ir-DGyGiwVe.d.ts} +1 -1
  249. package/dist/{module-k7m3txak.d.ts → module-DqQ1U-Me.d.ts} +129 -100
  250. package/dist/{module-B8CBqIZ_.d.cts → module-doenaCsZ.d.cts} +129 -100
  251. package/package.json +12 -1
  252. package/dist/ModuleTag-C8FHY_sY.d.ts +0 -93
  253. package/dist/ModuleTag-EGbgBMpZ.d.cts +0 -93
  254. package/dist/chunk-3QMIVH35.js +0 -43
  255. package/dist/chunk-3QMIVH35.js.map +0 -1
  256. package/dist/chunk-76WT3HOR.js.map +0 -1
  257. package/dist/chunk-AUIR5O6W.js.map +0 -1
  258. package/dist/chunk-BABLDP24.js.map +0 -1
  259. package/dist/chunk-BE3HW4FY.js.map +0 -1
  260. package/dist/chunk-CW6T36TN.js.map +0 -1
  261. package/dist/chunk-DFNM3WX2.js.map +0 -1
  262. package/dist/chunk-DMBALCE2.js.map +0 -1
  263. package/dist/chunk-EGK3KN7B.js.map +0 -1
  264. package/dist/chunk-GMPEOUP2.js.map +0 -1
  265. package/dist/chunk-IHVBV5C2.js.map +0 -1
  266. package/dist/chunk-JCXGZRMU.js.map +0 -1
  267. package/dist/chunk-JGIWG6SR.js.map +0 -1
  268. package/dist/chunk-JWOYLO27.js.map +0 -1
  269. package/dist/chunk-KIXAU3GM.js +0 -137
  270. package/dist/chunk-KIXAU3GM.js.map +0 -1
  271. package/dist/chunk-KP7MUZNX.js.map +0 -1
  272. package/dist/chunk-M3WTHJHJ.js.map +0 -1
  273. package/dist/chunk-M7IYCTJV.js +0 -79
  274. package/dist/chunk-M7IYCTJV.js.map +0 -1
  275. package/dist/chunk-NBD3KUOZ.js.map +0 -1
  276. package/dist/chunk-NQZ2OSGR.js.map +0 -1
  277. package/dist/chunk-OGWBVHB3.js.map +0 -1
  278. package/dist/chunk-PAYXCY6A.js.map +0 -1
  279. package/dist/chunk-PYOE4VSI.js.map +0 -1
  280. package/dist/chunk-QCHIQWAJ.js +0 -21
  281. package/dist/chunk-VZB726PE.js +0 -93
  282. package/dist/chunk-VZB726PE.js.map +0 -1
  283. package/dist/chunk-W3TEWHLO.js +0 -568
  284. package/dist/chunk-W3TEWHLO.js.map +0 -1
  285. package/dist/chunk-ZFLHVFUC.js +0 -192
  286. package/dist/chunk-ZFLHVFUC.js.map +0 -1
  287. package/dist/chunk-ZFY7U2FR.js.map +0 -1
  288. /package/dist/{chunk-G5ZBFPNU.js.map → chunk-2A4UKO2D.js.map} +0 -0
  289. /package/dist/{chunk-ANLBCBDC.js.map → chunk-2DVLMSOE.js.map} +0 -0
  290. /package/dist/{chunk-3TMODYZV.js.map → chunk-3XO4HR6V.js.map} +0 -0
  291. /package/dist/{chunk-TKZ7MEIA.js.map → chunk-53GVPGSM.js.map} +0 -0
  292. /package/dist/{chunk-NZJKFF45.js.map → chunk-C2UZZQ76.js.map} +0 -0
  293. /package/dist/{chunk-M2RGJPXX.js.map → chunk-DBD6Q6JH.js.map} +0 -0
  294. /package/dist/{chunk-ZGDVUPTM.js.map → chunk-EB4RGQO3.js.map} +0 -0
  295. /package/dist/{chunk-TAAPQVZN.js.map → chunk-ISKNULNH.js.map} +0 -0
  296. /package/dist/{chunk-66ALHVEX.js.map → chunk-KKIAYH4X.js.map} +0 -0
  297. /package/dist/{chunk-3RMKLXHX.js.map → chunk-KLDVG3SY.js.map} +0 -0
  298. /package/dist/{chunk-4CQAV7YB.js.map → chunk-O6TTQXTY.js.map} +0 -0
  299. /package/dist/{chunk-24VULZ7A.js.map → chunk-TKOGZDD6.js.map} +0 -0
  300. /package/dist/{chunk-EY4NZKDR.js.map → chunk-XFMMPYNU.js.map} +0 -0
@@ -0,0 +1,2977 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/Workflow.ts
21
+ var Workflow_exports = {};
22
+ __export(Workflow_exports, {
23
+ KernelPorts: () => KernelPorts,
24
+ call: () => call,
25
+ callById: () => callById,
26
+ compose: () => compose,
27
+ constValue: () => constValue,
28
+ delay: () => delay,
29
+ dispatch: () => dispatch,
30
+ forModule: () => forModule,
31
+ fragment: () => fragment,
32
+ fromJSON: () => fromJSON,
33
+ make: () => make,
34
+ merge: () => merge,
35
+ object: () => object,
36
+ onAction: () => onAction,
37
+ onInit: () => onInit,
38
+ onStart: () => onStart,
39
+ payload: () => payload,
40
+ payloadPath: () => payloadPath,
41
+ withPolicy: () => withPolicy
42
+ });
43
+ module.exports = __toCommonJS(Workflow_exports);
44
+ var import_effect14 = require("effect");
45
+
46
+ // src/internal/serviceId.ts
47
+ var asNonEmptyString = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
48
+ var fromTag = (tag) => {
49
+ const anyTag = tag;
50
+ return asNonEmptyString(anyTag.key) ?? asNonEmptyString(anyTag.id) ?? asNonEmptyString(anyTag._id);
51
+ };
52
+
53
+ // src/internal/digest.ts
54
+ var stableStringify = (value) => {
55
+ if (value === null) return "null";
56
+ const t = typeof value;
57
+ if (t === "string") return JSON.stringify(value);
58
+ if (t === "number") return Number.isFinite(value) ? String(value) : "null";
59
+ if (t === "boolean") return value ? "true" : "false";
60
+ if (Array.isArray(value)) {
61
+ return `[${value.map(stableStringify).join(",")}]`;
62
+ }
63
+ if (t === "object") {
64
+ const record2 = value;
65
+ const keys = Object.keys(record2).sort();
66
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(record2[k])}`).join(",")}}`;
67
+ }
68
+ return "null";
69
+ };
70
+ var fnv1a32 = (input) => {
71
+ let hash = 2166136261;
72
+ for (let i = 0; i < input.length; i++) {
73
+ hash ^= input.charCodeAt(i);
74
+ hash = hash * 16777619 >>> 0;
75
+ }
76
+ return hash.toString(16).padStart(8, "0");
77
+ };
78
+
79
+ // src/internal/observability/jsonValue.ts
80
+ var isJsonValue = (input) => {
81
+ const seen = /* @__PURE__ */ new WeakSet();
82
+ const loop = (value, depth) => {
83
+ if (depth > 64) return false;
84
+ if (value === null) return true;
85
+ switch (typeof value) {
86
+ case "string":
87
+ case "boolean":
88
+ return true;
89
+ case "number":
90
+ return Number.isFinite(value);
91
+ case "object": {
92
+ if (Array.isArray(value)) {
93
+ if (seen.has(value)) return false;
94
+ seen.add(value);
95
+ for (const item of value) {
96
+ if (!loop(item, depth + 1)) return false;
97
+ }
98
+ return true;
99
+ }
100
+ if (!isPlainRecord(value)) return false;
101
+ if (seen.has(value)) return false;
102
+ seen.add(value);
103
+ for (const v of Object.values(value)) {
104
+ if (!loop(v, depth + 1)) return false;
105
+ }
106
+ return true;
107
+ }
108
+ default:
109
+ return false;
110
+ }
111
+ };
112
+ return loop(input, 0);
113
+ };
114
+ var defaultOptions = {
115
+ maxDepth: 6,
116
+ maxObjectKeys: 32,
117
+ maxArrayLength: 32,
118
+ maxStringLength: 256,
119
+ maxJsonBytes: 4 * 1024,
120
+ oversizedPreviewBytes: 256
121
+ };
122
+ var truncateString = (value, maxLen, stats) => {
123
+ if (value.length <= maxLen) return value;
124
+ stats.oversized += 1;
125
+ return value.slice(0, maxLen);
126
+ };
127
+ var mergeDowngrade = (current, next) => {
128
+ if (!current) return next;
129
+ if (current === "non_serializable" || next === "non_serializable") return "non_serializable";
130
+ if (current === "oversized" || next === "oversized") return "oversized";
131
+ return "unknown";
132
+ };
133
+ function isPlainRecord(value) {
134
+ if (typeof value !== "object" || value === null) return false;
135
+ const proto = Object.getPrototypeOf(value);
136
+ return proto === Object.prototype || proto === null;
137
+ }
138
+ var asNumber = (value, stats) => {
139
+ if (Number.isFinite(value)) return value;
140
+ stats.nonSerializable += 1;
141
+ return String(value);
142
+ };
143
+ var toJsonValueInternal = (input, options, stats, seen, depth) => {
144
+ if (input === null) return null;
145
+ switch (typeof input) {
146
+ case "string":
147
+ return truncateString(input, options.maxStringLength, stats);
148
+ case "number":
149
+ return asNumber(input, stats);
150
+ case "boolean":
151
+ return input;
152
+ case "bigint":
153
+ stats.nonSerializable += 1;
154
+ return truncateString(input.toString(), options.maxStringLength, stats);
155
+ case "symbol":
156
+ stats.nonSerializable += 1;
157
+ return truncateString(input.toString(), options.maxStringLength, stats);
158
+ case "function":
159
+ stats.nonSerializable += 1;
160
+ return "[Function]";
161
+ case "undefined":
162
+ stats.dropped += 1;
163
+ return null;
164
+ }
165
+ if (depth >= options.maxDepth) {
166
+ stats.oversized += 1;
167
+ return "[Truncated]";
168
+ }
169
+ if (input instanceof Date) {
170
+ return input.toISOString();
171
+ }
172
+ if (input instanceof Error) {
173
+ stats.nonSerializable += 1;
174
+ return {
175
+ name: truncateString(input.name, options.maxStringLength, stats),
176
+ message: truncateString(input.message, options.maxStringLength, stats)
177
+ };
178
+ }
179
+ if (typeof input === "object") {
180
+ if (seen.has(input)) {
181
+ stats.nonSerializable += 1;
182
+ return "[Circular]";
183
+ }
184
+ seen.add(input);
185
+ }
186
+ if (Array.isArray(input)) {
187
+ const out2 = [];
188
+ const limit2 = Math.min(input.length, options.maxArrayLength);
189
+ for (let i = 0; i < limit2; i++) {
190
+ out2.push(toJsonValueInternal(input[i], options, stats, seen, depth + 1));
191
+ }
192
+ if (input.length > limit2) {
193
+ stats.oversized += 1;
194
+ out2.push(`[...${input.length - limit2} more]`);
195
+ }
196
+ return out2;
197
+ }
198
+ if (!isPlainRecord(input)) {
199
+ stats.nonSerializable += 1;
200
+ return truncateString(String(input), options.maxStringLength, stats);
201
+ }
202
+ const keys = Object.keys(input).sort();
203
+ const limit = Math.min(keys.length, options.maxObjectKeys);
204
+ const out = {};
205
+ for (let i = 0; i < limit; i++) {
206
+ const rawKey = keys[i];
207
+ const rawValue = input[rawKey];
208
+ const key = truncateString(rawKey, options.maxStringLength, stats);
209
+ if (rawValue === void 0) {
210
+ stats.dropped += 1;
211
+ continue;
212
+ }
213
+ out[key] = toJsonValueInternal(rawValue, options, stats, seen, depth + 1);
214
+ }
215
+ if (keys.length > limit) {
216
+ stats.oversized += 1;
217
+ out.__truncatedKeys = keys.length - limit;
218
+ }
219
+ return out;
220
+ };
221
+ var projectJsonValue = (input, options) => {
222
+ const resolved = { ...defaultOptions, ...options ?? {} };
223
+ const stats = { dropped: 0, oversized: 0, nonSerializable: 0 };
224
+ const seen = /* @__PURE__ */ new WeakSet();
225
+ let downgrade;
226
+ const value = toJsonValueInternal(input, resolved, stats, seen, 0);
227
+ if (stats.nonSerializable > 0) {
228
+ downgrade = mergeDowngrade(downgrade, "non_serializable");
229
+ }
230
+ if (stats.oversized > 0) {
231
+ downgrade = mergeDowngrade(downgrade, "oversized");
232
+ }
233
+ try {
234
+ const json = JSON.stringify(value);
235
+ if (json.length > resolved.maxJsonBytes) {
236
+ downgrade = mergeDowngrade(downgrade, "oversized");
237
+ const preview = json.slice(0, Math.min(resolved.oversizedPreviewBytes, resolved.maxJsonBytes));
238
+ return {
239
+ value: {
240
+ _tag: "oversized",
241
+ bytes: json.length,
242
+ preview
243
+ },
244
+ stats: {
245
+ dropped: stats.dropped,
246
+ oversized: stats.oversized + 1,
247
+ nonSerializable: stats.nonSerializable
248
+ },
249
+ downgrade
250
+ };
251
+ }
252
+ } catch {
253
+ downgrade = mergeDowngrade(downgrade, "non_serializable");
254
+ return {
255
+ value: "[Unserializable]",
256
+ stats: {
257
+ dropped: stats.dropped,
258
+ oversized: stats.oversized,
259
+ nonSerializable: stats.nonSerializable + 1
260
+ },
261
+ downgrade
262
+ };
263
+ }
264
+ return {
265
+ value,
266
+ stats: {
267
+ dropped: stats.dropped,
268
+ oversized: stats.oversized,
269
+ nonSerializable: stats.nonSerializable
270
+ },
271
+ downgrade
272
+ };
273
+ };
274
+
275
+ // src/internal/workflow/errors.ts
276
+ var toJsonValue = (detail) => {
277
+ if (isJsonValue(detail)) return detail;
278
+ return projectJsonValue(detail).value;
279
+ };
280
+ var makeWorkflowError = (args) => {
281
+ const detailJson = args.detail !== void 0 ? toJsonValue(args.detail) : void 0;
282
+ const msg = args.detail !== void 0 ? `${args.message}
283
+ (detail=${stableStringify(detailJson)})` : args.message;
284
+ return Object.assign(new Error(msg), {
285
+ _tag: "WorkflowError",
286
+ code: args.code,
287
+ programId: args.programId,
288
+ source: args.source,
289
+ detail: detailJson
290
+ });
291
+ };
292
+
293
+ // src/internal/workflow/inputExpr.ts
294
+ var decodePointerToken = (raw) => raw.replace(/~1/g, "/").replace(/~0/g, "~");
295
+ var isIndexToken = (token) => token === "0" || !token.startsWith("0") && /^\d+$/.test(token);
296
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
297
+ var parseJsonPointer = (pointer) => {
298
+ if (pointer === "") return [];
299
+ if (!pointer.startsWith("/")) {
300
+ throw makeWorkflowError({
301
+ code: "WORKFLOW_INVALID_JSON_POINTER",
302
+ message: 'Invalid JSON Pointer (must be "" or start with "/").',
303
+ detail: { pointer }
304
+ });
305
+ }
306
+ const raw = pointer.split("/").slice(1);
307
+ const out = [];
308
+ for (const part of raw) {
309
+ const decoded = decodePointerToken(part);
310
+ out.push(isIndexToken(decoded) ? Number(decoded) : decoded);
311
+ }
312
+ return out;
313
+ };
314
+ var compileInputExpr = (expr, pathForError) => {
315
+ switch (expr.kind) {
316
+ case "payload":
317
+ return { kind: "payload" };
318
+ case "payload.path": {
319
+ const pointer = expr.pointer;
320
+ if (typeof pointer !== "string") {
321
+ throw makeWorkflowError({
322
+ code: "WORKFLOW_INVALID_INPUT_EXPR",
323
+ message: "InputExpr.payload.path.pointer must be a string.",
324
+ source: { stepKey: pathForError?.stepKey },
325
+ detail: { pointer }
326
+ });
327
+ }
328
+ return { kind: "payload.path", pointer, tokens: parseJsonPointer(pointer) };
329
+ }
330
+ case "const": {
331
+ const value = expr.value;
332
+ if (!isJsonValue(value)) {
333
+ throw makeWorkflowError({
334
+ code: "WORKFLOW_INVALID_INPUT_EXPR",
335
+ message: "InputExpr.const.value must be JSON-serializable.",
336
+ source: { stepKey: pathForError?.stepKey },
337
+ detail: { value }
338
+ });
339
+ }
340
+ return { kind: "const", value };
341
+ }
342
+ case "object": {
343
+ const fields = expr.fields;
344
+ if (!fields || typeof fields !== "object" || Array.isArray(fields)) {
345
+ throw makeWorkflowError({
346
+ code: "WORKFLOW_INVALID_INPUT_EXPR",
347
+ message: "InputExpr.object.fields must be a record.",
348
+ source: { stepKey: pathForError?.stepKey }
349
+ });
350
+ }
351
+ const entries = Object.entries(fields).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
352
+ return {
353
+ kind: "object",
354
+ fields: entries.map(([k, v]) => [k, compileInputExpr(v, pathForError)])
355
+ };
356
+ }
357
+ case "merge": {
358
+ const items = expr.items;
359
+ if (!Array.isArray(items)) {
360
+ throw makeWorkflowError({
361
+ code: "WORKFLOW_INVALID_INPUT_EXPR",
362
+ message: "InputExpr.merge.items must be an array.",
363
+ source: { stepKey: pathForError?.stepKey }
364
+ });
365
+ }
366
+ for (const item of items) {
367
+ const kind = isRecord(item) ? item.kind : void 0;
368
+ if (kind !== "object") {
369
+ throw makeWorkflowError({
370
+ code: "WORKFLOW_INVALID_MERGE_ITEMS",
371
+ message: "InputExpr.merge.items must all be InputExpr.object.",
372
+ source: { stepKey: pathForError?.stepKey },
373
+ detail: { kind }
374
+ });
375
+ }
376
+ }
377
+ return {
378
+ kind: "merge",
379
+ items: items.map((i) => compileInputExpr(i, pathForError))
380
+ };
381
+ }
382
+ }
383
+ };
384
+ var isPlainRecord2 = (value) => {
385
+ if (typeof value !== "object" || value === null) return false;
386
+ if (Array.isArray(value)) return false;
387
+ const proto = Object.getPrototypeOf(value);
388
+ return proto === Object.prototype || proto === null;
389
+ };
390
+ var evalPointer = (root, tokens) => {
391
+ let current = root;
392
+ for (const token of tokens) {
393
+ if (current == null) return void 0;
394
+ if (Array.isArray(current) && typeof token === "number") {
395
+ current = current[token];
396
+ continue;
397
+ }
398
+ if (typeof current !== "object") return void 0;
399
+ const key = typeof token === "number" ? String(token) : token;
400
+ current = current[key];
401
+ }
402
+ return current;
403
+ };
404
+ var evalInputExpr = (expr, payload2) => {
405
+ switch (expr.kind) {
406
+ case "payload":
407
+ return payload2;
408
+ case "payload.path":
409
+ return evalPointer(payload2, expr.tokens);
410
+ case "const":
411
+ return expr.value;
412
+ case "object": {
413
+ const out = {};
414
+ for (const [k, v] of expr.fields) {
415
+ out[k] = evalInputExpr(v, payload2);
416
+ }
417
+ return out;
418
+ }
419
+ case "merge": {
420
+ const out = {};
421
+ for (const item of expr.items) {
422
+ const value = evalInputExpr(item, payload2);
423
+ if (isPlainRecord2(value)) {
424
+ for (const [k, v] of Object.entries(value)) {
425
+ out[k] = v;
426
+ }
427
+ }
428
+ }
429
+ return out;
430
+ }
431
+ }
432
+ };
433
+
434
+ // src/internal/workflow/compiler.ts
435
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
436
+ var asNonEmptyString2 = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
437
+ var asNonNegInt = (value) => {
438
+ if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
439
+ const n = Math.floor(value);
440
+ return n >= 0 ? n : void 0;
441
+ };
442
+ var asPosInt = (value) => {
443
+ if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
444
+ const n = Math.floor(value);
445
+ return n > 0 ? n : void 0;
446
+ };
447
+ var normalizeWorkflowDefV1 = (input) => {
448
+ const normalizeStep = (step) => {
449
+ if (!isRecord2(step)) return step;
450
+ if (step.kind !== "call") return step;
451
+ const raw = step;
452
+ const onSuccessRaw = Array.isArray(raw.onSuccess) ? raw.onSuccess : [];
453
+ const onFailureRaw = Array.isArray(raw.onFailure) ? raw.onFailure : [];
454
+ return {
455
+ ...step,
456
+ onSuccess: onSuccessRaw.map(normalizeStep),
457
+ onFailure: onFailureRaw.map(normalizeStep)
458
+ };
459
+ };
460
+ const normalizeSteps = (steps) => steps.map(normalizeStep);
461
+ return {
462
+ ...input,
463
+ steps: normalizeSteps(input.steps)
464
+ };
465
+ };
466
+ function validateWorkflowDefV1(def, options) {
467
+ if (!isRecord2(def)) {
468
+ throw makeWorkflowError({
469
+ code: "WORKFLOW_INVALID_DEF",
470
+ message: "WorkflowDef must be an object.",
471
+ detail: { def }
472
+ });
473
+ }
474
+ if (def.astVersion !== 1) {
475
+ throw makeWorkflowError({
476
+ code: "WORKFLOW_UNSUPPORTED_VERSION",
477
+ message: "Unsupported workflow astVersion.",
478
+ detail: { astVersion: def.astVersion }
479
+ });
480
+ }
481
+ if (!asNonEmptyString2(def.localId)) {
482
+ throw makeWorkflowError({
483
+ code: "WORKFLOW_INVALID_DEF",
484
+ message: "WorkflowDef.localId must be a non-empty string.",
485
+ detail: { localId: def.localId }
486
+ });
487
+ }
488
+ const trigger = def.trigger;
489
+ if (!isRecord2(trigger)) {
490
+ throw makeWorkflowError({
491
+ code: "WORKFLOW_INVALID_TRIGGER",
492
+ message: "Workflow trigger must be an object.",
493
+ detail: { trigger }
494
+ });
495
+ }
496
+ if (trigger.kind === "action") {
497
+ if (!asNonEmptyString2(trigger.actionTag)) {
498
+ throw makeWorkflowError({
499
+ code: "WORKFLOW_INVALID_TRIGGER",
500
+ message: "Workflow trigger.actionTag must be a non-empty string.",
501
+ detail: { trigger }
502
+ });
503
+ }
504
+ } else if (trigger.kind === "lifecycle") {
505
+ const phase = trigger.phase;
506
+ if (phase !== "onStart" && phase !== "onInit") {
507
+ throw makeWorkflowError({
508
+ code: "WORKFLOW_INVALID_TRIGGER",
509
+ message: 'Workflow trigger.phase must be "onStart" or "onInit".',
510
+ detail: { trigger }
511
+ });
512
+ }
513
+ } else {
514
+ throw makeWorkflowError({
515
+ code: "WORKFLOW_INVALID_TRIGGER",
516
+ message: 'Workflow trigger.kind must be "action" or "lifecycle".',
517
+ detail: { trigger }
518
+ });
519
+ }
520
+ if (!Array.isArray(def.steps)) {
521
+ throw makeWorkflowError({
522
+ code: "WORKFLOW_INVALID_DEF",
523
+ message: "WorkflowDef.steps must be an array.",
524
+ detail: { steps: def.steps }
525
+ });
526
+ }
527
+ const seenKeys = /* @__PURE__ */ new Set();
528
+ const visit = (step, fragmentId) => {
529
+ if (!isRecord2(step)) {
530
+ throw makeWorkflowError({
531
+ code: "WORKFLOW_INVALID_STEP",
532
+ message: "Workflow step must be an object.",
533
+ detail: { step },
534
+ source: fragmentId ? { fragmentId } : void 0
535
+ });
536
+ }
537
+ const key = asNonEmptyString2(step.key);
538
+ if (!key) {
539
+ throw makeWorkflowError({
540
+ code: "WORKFLOW_INVALID_STEP",
541
+ message: "Workflow step.key must be a non-empty string.",
542
+ detail: { stepKey: step.key, kind: step.kind },
543
+ source: fragmentId ? { fragmentId } : void 0
544
+ });
545
+ }
546
+ if (seenKeys.has(key)) {
547
+ throw makeWorkflowError({
548
+ code: "WORKFLOW_DUPLICATE_STEP_KEY",
549
+ message: `Duplicate stepKey "${key}" detected.`,
550
+ detail: { duplicateKey: key },
551
+ source: { stepKey: key, ...fragmentId ? { fragmentId } : null }
552
+ });
553
+ }
554
+ seenKeys.add(key);
555
+ if (step.kind === "dispatch") {
556
+ if (!asNonEmptyString2(step.actionTag)) {
557
+ throw makeWorkflowError({
558
+ code: "WORKFLOW_INVALID_STEP",
559
+ message: "dispatch.actionTag must be a non-empty string.",
560
+ source: { stepKey: key, ...fragmentId ? { fragmentId } : null },
561
+ detail: { actionTag: step.actionTag }
562
+ });
563
+ }
564
+ const payload2 = step.payload;
565
+ if (payload2 !== void 0) {
566
+ validateInputExpr(payload2, { stepKey: key });
567
+ }
568
+ return;
569
+ }
570
+ if (step.kind === "delay") {
571
+ const ms = asNonNegInt(step.ms);
572
+ if (ms === void 0) {
573
+ throw makeWorkflowError({
574
+ code: "WORKFLOW_INVALID_STEP",
575
+ message: "delay.ms must be a non-negative integer.",
576
+ source: { stepKey: key, ...fragmentId ? { fragmentId } : null },
577
+ detail: { ms: step.ms }
578
+ });
579
+ }
580
+ return;
581
+ }
582
+ if (step.kind === "call") {
583
+ if (!asNonEmptyString2(step.serviceId)) {
584
+ throw makeWorkflowError({
585
+ code: "WORKFLOW_INVALID_SERVICE_ID",
586
+ message: "call.serviceId must be a non-empty string.",
587
+ source: { stepKey: key, ...fragmentId ? { fragmentId } : null },
588
+ detail: { serviceId: step.serviceId }
589
+ });
590
+ }
591
+ const inputExpr = step.input;
592
+ if (inputExpr !== void 0) {
593
+ validateInputExpr(inputExpr, { stepKey: key });
594
+ }
595
+ const timeoutMsRaw = step.timeoutMs;
596
+ if (timeoutMsRaw !== void 0 && asPosInt(timeoutMsRaw) === void 0) {
597
+ throw makeWorkflowError({
598
+ code: "WORKFLOW_INVALID_STEP",
599
+ message: "call.timeoutMs must be a positive integer (milliseconds).",
600
+ source: { stepKey: key, ...fragmentId ? { fragmentId } : null },
601
+ detail: { timeoutMs: timeoutMsRaw }
602
+ });
603
+ }
604
+ const retryRaw = step.retry;
605
+ if (retryRaw !== void 0) {
606
+ const times = isRecord2(retryRaw) ? asPosInt(retryRaw.times) : void 0;
607
+ if (times === void 0) {
608
+ throw makeWorkflowError({
609
+ code: "WORKFLOW_INVALID_STEP",
610
+ message: "call.retry.times must be a positive integer.",
611
+ source: { stepKey: key, ...fragmentId ? { fragmentId } : null },
612
+ detail: { retry: retryRaw }
613
+ });
614
+ }
615
+ }
616
+ const onSuccess = Array.isArray(step.onSuccess) ? step.onSuccess : [];
617
+ const onFailure = Array.isArray(step.onFailure) ? step.onFailure : [];
618
+ for (const inner of onSuccess) visit(inner, fragmentId);
619
+ for (const inner of onFailure) visit(inner, fragmentId);
620
+ return;
621
+ }
622
+ throw makeWorkflowError({
623
+ code: "WORKFLOW_INVALID_STEP",
624
+ message: "Unknown step kind.",
625
+ source: { stepKey: key, ...fragmentId ? { fragmentId } : null },
626
+ detail: { kind: step.kind }
627
+ });
628
+ };
629
+ const sources = def.sources;
630
+ const fragmentByStepKey = /* @__PURE__ */ new Map();
631
+ if (sources && typeof sources === "object") {
632
+ for (const [k, v] of Object.entries(sources)) {
633
+ fragmentByStepKey.set(k, isRecord2(v) ? asNonEmptyString2(v.fragmentId) : void 0);
634
+ }
635
+ }
636
+ for (const step of def.steps) {
637
+ const key = isRecord2(step) ? asNonEmptyString2(step.key) : void 0;
638
+ const fragmentId = key ? fragmentByStepKey.get(key) : void 0;
639
+ visit(step, fragmentId);
640
+ }
641
+ const generator = isRecord2(def.meta) ? def.meta.generator : void 0;
642
+ if (generator !== void 0 && !isJsonValue(generator)) {
643
+ throw makeWorkflowError({
644
+ code: "WORKFLOW_INVALID_DEF",
645
+ message: "WorkflowDef.meta.generator must be JSON-serializable.",
646
+ detail: { generator }
647
+ });
648
+ }
649
+ const policy = isRecord2(def.policy) ? def.policy : void 0;
650
+ if (policy) {
651
+ const concurrency = policy.concurrency;
652
+ if (concurrency !== void 0 && concurrency !== "latest" && concurrency !== "exhaust" && concurrency !== "parallel") {
653
+ throw makeWorkflowError({
654
+ code: "WORKFLOW_INVALID_DEF",
655
+ message: "policy.concurrency must be latest|exhaust|parallel.",
656
+ detail: { concurrency }
657
+ });
658
+ }
659
+ const priority = policy.priority;
660
+ if (priority !== void 0 && priority !== "urgent" && priority !== "nonUrgent") {
661
+ throw makeWorkflowError({
662
+ code: "WORKFLOW_INVALID_DEF",
663
+ message: "policy.priority must be urgent|nonUrgent.",
664
+ detail: { priority }
665
+ });
666
+ }
667
+ }
668
+ void options?.moduleId;
669
+ }
670
+ var validateInputExpr = (expr, options) => {
671
+ const visit = (e) => {
672
+ if (!isRecord2(e)) {
673
+ throw makeWorkflowError({
674
+ code: "WORKFLOW_INVALID_INPUT_EXPR",
675
+ message: "InputExpr must be an object.",
676
+ source: { stepKey: options?.stepKey },
677
+ detail: { expr: e }
678
+ });
679
+ }
680
+ const kind = e.kind;
681
+ switch (kind) {
682
+ case "payload":
683
+ return;
684
+ case "payload.path": {
685
+ const pointer = e.pointer;
686
+ if (typeof pointer !== "string") {
687
+ throw makeWorkflowError({
688
+ code: "WORKFLOW_INVALID_INPUT_EXPR",
689
+ message: "InputExpr.payload.path.pointer must be a string.",
690
+ source: { stepKey: options?.stepKey },
691
+ detail: { pointer }
692
+ });
693
+ }
694
+ return;
695
+ }
696
+ case "const": {
697
+ const value = e.value;
698
+ if (!isJsonValue(value)) {
699
+ throw makeWorkflowError({
700
+ code: "WORKFLOW_INVALID_INPUT_EXPR",
701
+ message: "InputExpr.const.value must be JSON-serializable.",
702
+ source: { stepKey: options?.stepKey }
703
+ });
704
+ }
705
+ return;
706
+ }
707
+ case "object": {
708
+ const fields = e.fields;
709
+ if (!isRecord2(fields)) {
710
+ throw makeWorkflowError({
711
+ code: "WORKFLOW_INVALID_INPUT_EXPR",
712
+ message: "InputExpr.object.fields must be a record.",
713
+ source: { stepKey: options?.stepKey }
714
+ });
715
+ }
716
+ for (const v of Object.values(fields)) {
717
+ visit(v);
718
+ }
719
+ return;
720
+ }
721
+ case "merge": {
722
+ const items = e.items;
723
+ if (!Array.isArray(items)) {
724
+ throw makeWorkflowError({
725
+ code: "WORKFLOW_INVALID_INPUT_EXPR",
726
+ message: "InputExpr.merge.items must be an array.",
727
+ source: { stepKey: options?.stepKey }
728
+ });
729
+ }
730
+ for (const item of items) {
731
+ visit(item);
732
+ }
733
+ return;
734
+ }
735
+ default:
736
+ throw makeWorkflowError({
737
+ code: "WORKFLOW_INVALID_INPUT_EXPR",
738
+ message: "Unknown InputExpr kind.",
739
+ source: { stepKey: options?.stepKey },
740
+ detail: { kind }
741
+ });
742
+ }
743
+ };
744
+ visit(expr);
745
+ };
746
+ var makeDigest = (prefix, value) => `${prefix}:${fnv1a32(stableStringify(value))}`;
747
+ var makeTriggerNodeId = (programId) => `wf_trigger_v1:${fnv1a32(programId)}`;
748
+ var makeStepNodeId = (programId, stepKey, kind) => `wf_node_v1:${fnv1a32(`${programId}\0${stepKey}\0${kind}`)}`;
749
+ var budgetJsonValue = (value) => projectJsonValue(value).value;
750
+ var budgetInputExpr = (expr) => {
751
+ switch (expr.kind) {
752
+ case "payload":
753
+ case "payload.path":
754
+ return expr;
755
+ case "const": {
756
+ const value = expr.value;
757
+ if (!isJsonValue(value)) return expr;
758
+ return { ...expr, value: budgetJsonValue(expr.value) };
759
+ }
760
+ case "object": {
761
+ const out = {};
762
+ for (const k of Object.keys(expr.fields).sort()) {
763
+ out[k] = budgetInputExpr(expr.fields[k]);
764
+ }
765
+ return { ...expr, fields: out };
766
+ }
767
+ case "merge":
768
+ return { ...expr, items: expr.items.map(budgetInputExpr) };
769
+ }
770
+ };
771
+ var toStaticStep = (step) => {
772
+ switch (step.kind) {
773
+ case "dispatch":
774
+ return {
775
+ kind: "dispatch",
776
+ actionTag: step.actionTag,
777
+ ...step.payload ? { payload: budgetInputExpr(step.payload) } : null
778
+ };
779
+ case "delay":
780
+ return { kind: "delay", ms: step.ms };
781
+ case "call": {
782
+ const policy = step.timeoutMs !== void 0 || step.retry !== void 0 ? {
783
+ ...step.timeoutMs !== void 0 ? { timeoutMs: step.timeoutMs } : null,
784
+ ...step.retry !== void 0 ? { retry: { times: step.retry.times } } : null
785
+ } : void 0;
786
+ return {
787
+ kind: "call",
788
+ serviceId: step.serviceId,
789
+ ...step.input ? { input: budgetInputExpr(step.input) } : null,
790
+ ...policy ? { policy } : null
791
+ };
792
+ }
793
+ }
794
+ };
795
+ var compileWorkflowStaticIrV1 = (args) => {
796
+ const normalized = normalizeWorkflowDefV1(args.def);
797
+ validateWorkflowDefV1(normalized, { moduleId: args.moduleId });
798
+ const programId = `${args.moduleId}.${normalized.localId}`;
799
+ const triggerNodeId = makeTriggerNodeId(programId);
800
+ const fragmentByStepKey = /* @__PURE__ */ new Map();
801
+ if (normalized.sources && typeof normalized.sources === "object") {
802
+ for (const [k, v] of Object.entries(normalized.sources)) {
803
+ fragmentByStepKey.set(k, isRecord2(v) ? asNonEmptyString2(v.fragmentId) : void 0);
804
+ }
805
+ }
806
+ const nodesByKey = /* @__PURE__ */ new Map();
807
+ const collectNodes = (steps) => {
808
+ for (const step of steps) {
809
+ const id = makeStepNodeId(programId, step.key, step.kind);
810
+ nodesByKey.set(step.key, id);
811
+ if (step.kind === "call") {
812
+ collectNodes(step.onSuccess);
813
+ collectNodes(step.onFailure);
814
+ }
815
+ }
816
+ };
817
+ collectNodes(normalized.steps);
818
+ const nodes = [
819
+ {
820
+ id: triggerNodeId,
821
+ kind: "trigger",
822
+ trigger: normalized.trigger
823
+ }
824
+ ];
825
+ const addStepNodes = (steps) => {
826
+ for (const step of steps) {
827
+ const id = nodesByKey.get(step.key);
828
+ if (!id) continue;
829
+ const fragmentId = fragmentByStepKey.get(step.key);
830
+ nodes.push({
831
+ id,
832
+ kind: "step",
833
+ step: toStaticStep(step),
834
+ source: {
835
+ stepKey: step.key,
836
+ ...fragmentId ? { fragmentId } : null
837
+ }
838
+ });
839
+ if (step.kind === "call") {
840
+ addStepNodes(step.onSuccess);
841
+ addStepNodes(step.onFailure);
842
+ }
843
+ }
844
+ };
845
+ addStepNodes(normalized.steps);
846
+ const edges = [];
847
+ const pushEdge = (from, to, kind) => {
848
+ edges.push({ from, to, kind });
849
+ };
850
+ const compileBlock = (args2) => {
851
+ if (args2.steps.length === 0) {
852
+ if (args2.continuation) {
853
+ for (const from of args2.entryFrom) {
854
+ pushEdge(from, args2.continuation, args2.entryKind);
855
+ }
856
+ }
857
+ return;
858
+ }
859
+ const first = args2.steps[0];
860
+ const firstId = nodesByKey.get(first.key);
861
+ if (!firstId) {
862
+ throw makeWorkflowError({
863
+ code: "WORKFLOW_INVALID_STEP",
864
+ message: "Internal error: missing node id for stepKey.",
865
+ programId,
866
+ source: { stepKey: first.key }
867
+ });
868
+ }
869
+ for (const from of args2.entryFrom) {
870
+ pushEdge(from, firstId, args2.entryKind);
871
+ }
872
+ const compileStepAndTail = (step, tail, continuation) => {
873
+ const stepId = nodesByKey.get(step.key);
874
+ if (!stepId) return;
875
+ if (step.kind !== "call") {
876
+ compileBlock({ steps: tail, entryFrom: [stepId], entryKind: "next", continuation });
877
+ return;
878
+ }
879
+ const cont = tail.length > 0 ? nodesByKey.get(tail[0].key) : continuation;
880
+ compileBlock({
881
+ steps: step.onSuccess,
882
+ entryFrom: [stepId],
883
+ entryKind: "success",
884
+ continuation: cont
885
+ });
886
+ compileBlock({
887
+ steps: step.onFailure,
888
+ entryFrom: [stepId],
889
+ entryKind: "failure",
890
+ continuation: cont
891
+ });
892
+ compileBlock({ steps: tail, entryFrom: [], entryKind: "next", continuation });
893
+ };
894
+ compileStepAndTail(first, args2.steps.slice(1), args2.continuation);
895
+ };
896
+ compileBlock({ steps: normalized.steps, entryFrom: [triggerNodeId], entryKind: "next", continuation: void 0 });
897
+ nodes.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
898
+ edges.sort((a, b) => {
899
+ if (a.from !== b.from) return a.from < b.from ? -1 : 1;
900
+ if (a.to !== b.to) return a.to < b.to ? -1 : 1;
901
+ const ak = String(a.kind ?? "");
902
+ const bk = String(b.kind ?? "");
903
+ if (ak !== bk) return ak < bk ? -1 : 1;
904
+ return 0;
905
+ });
906
+ const meta = (() => {
907
+ const generator = normalized.meta?.generator;
908
+ if (generator === void 0) return void 0;
909
+ return { generator: budgetJsonValue(generator) };
910
+ })();
911
+ const irNoDigest = {
912
+ version: 1,
913
+ programId,
914
+ nodes,
915
+ edges,
916
+ policy: normalized.policy,
917
+ meta
918
+ };
919
+ const digest = makeDigest("workflow_ir_v1", irNoDigest);
920
+ return {
921
+ ...irNoDigest,
922
+ digest
923
+ };
924
+ };
925
+ var compileWorkflowRuntimeStepsV1 = (args) => {
926
+ const normalized = normalizeWorkflowDefV1(args.def);
927
+ validateWorkflowDefV1(normalized);
928
+ const compileStep = (step) => {
929
+ const stepKey = step.key;
930
+ switch (step.kind) {
931
+ case "dispatch":
932
+ return {
933
+ kind: "dispatch",
934
+ key: step.key,
935
+ actionTag: step.actionTag,
936
+ ...step.payload ? { payload: compileInputExpr(step.payload, { stepKey }) } : null
937
+ };
938
+ case "delay":
939
+ return { kind: "delay", key: step.key, ms: step.ms };
940
+ case "call": {
941
+ const retryTimes = step.retry?.times;
942
+ return {
943
+ kind: "call",
944
+ key: step.key,
945
+ serviceId: step.serviceId,
946
+ ...step.input ? { input: compileInputExpr(step.input, { stepKey }) } : null,
947
+ ...step.timeoutMs !== void 0 ? { timeoutMs: step.timeoutMs } : null,
948
+ ...retryTimes !== void 0 ? { retryTimes } : null,
949
+ onSuccess: step.onSuccess.map(compileStep),
950
+ onFailure: step.onFailure.map(compileStep)
951
+ };
952
+ }
953
+ }
954
+ };
955
+ return normalized.steps.map(compileStep);
956
+ };
957
+
958
+ // src/internal/runtime/core/WorkflowRuntime.ts
959
+ var import_effect13 = require("effect");
960
+
961
+ // src/internal/runtime/core/EffectOpCore.ts
962
+ var import_effect = require("effect");
963
+ var currentLinkId = import_effect.FiberRef.unsafeMake(void 0);
964
+ var EffectOpMiddlewareTag = class extends import_effect.Context.Tag("Logix/EffectOpMiddleware")() {
965
+ };
966
+ var composeMiddleware = (stack) => {
967
+ return (op) => stack.reduceRight(
968
+ (eff, mw) => mw({ ...op, effect: eff }),
969
+ op.effect
970
+ );
971
+ };
972
+ var runWithMiddleware = (op, stack) => {
973
+ return import_effect.Effect.gen(function* () {
974
+ const existing = yield* import_effect.FiberRef.get(currentLinkId);
975
+ const metaLinkId = op.meta?.linkId;
976
+ const linkId = typeof metaLinkId === "string" && metaLinkId.length > 0 ? metaLinkId : existing ?? op.id;
977
+ const nextOp = {
978
+ ...op,
979
+ meta: {
980
+ ...op.meta ?? {},
981
+ linkId
982
+ }
983
+ };
984
+ const program = stack.length ? composeMiddleware(stack)(nextOp) : nextOp.effect;
985
+ return yield* import_effect.Effect.locally(currentLinkId, linkId)(program);
986
+ });
987
+ };
988
+
989
+ // src/internal/runtime/core/DebugSink.record.ts
990
+ var import_effect3 = require("effect");
991
+
992
+ // src/internal/runtime/core/errorSummary.ts
993
+ var import_effect2 = require("effect");
994
+ var truncate = (value, maxLen) => {
995
+ if (value.length <= maxLen) return { value, truncated: false };
996
+ return { value: value.slice(0, maxLen), truncated: true };
997
+ };
998
+ var safeStringify = (value) => {
999
+ try {
1000
+ return { ok: true, json: JSON.stringify(value) };
1001
+ } catch {
1002
+ return { ok: false };
1003
+ }
1004
+ };
1005
+ var getMessageFromUnknown = (cause) => {
1006
+ if (typeof cause === "string") return cause;
1007
+ if (typeof cause === "number" || typeof cause === "boolean" || typeof cause === "bigint") return String(cause);
1008
+ if (cause instanceof Error) return cause.message || cause.name || "Error";
1009
+ if (cause && typeof cause === "object" && "message" in cause && typeof cause.message === "string") {
1010
+ return cause.message;
1011
+ }
1012
+ try {
1013
+ const pretty = import_effect2.Cause.pretty(cause, { renderErrorCause: true });
1014
+ if (typeof pretty === "string" && pretty.length > 0) return pretty;
1015
+ } catch {
1016
+ }
1017
+ return "Unknown error";
1018
+ };
1019
+ var toSerializableErrorSummary = (cause, options) => {
1020
+ const maxMessageLength = options?.maxMessageLength ?? 256;
1021
+ const messageRaw = getMessageFromUnknown(cause);
1022
+ const { value: message, truncated } = truncate(messageRaw, maxMessageLength);
1023
+ const summary = {
1024
+ message
1025
+ };
1026
+ if (cause instanceof Error) {
1027
+ if (cause.name && cause.name !== "Error") summary.name = cause.name;
1028
+ const anyCause = cause;
1029
+ if (typeof anyCause.code === "string" && anyCause.code.length > 0) summary.code = anyCause.code;
1030
+ else if (typeof anyCause.code === "number" && Number.isFinite(anyCause.code)) summary.code = String(anyCause.code);
1031
+ if (typeof anyCause.hint === "string" && anyCause.hint.length > 0) summary.hint = anyCause.hint;
1032
+ return {
1033
+ errorSummary: summary,
1034
+ downgrade: truncated ? "oversized" : void 0
1035
+ };
1036
+ }
1037
+ if (cause && typeof cause === "object") {
1038
+ const anyCause = cause;
1039
+ if (typeof anyCause.name === "string" && anyCause.name.length > 0) summary.name = anyCause.name;
1040
+ if (typeof anyCause.code === "string" && anyCause.code.length > 0) summary.code = anyCause.code;
1041
+ if (typeof anyCause.hint === "string" && anyCause.hint.length > 0) summary.hint = anyCause.hint;
1042
+ }
1043
+ const stringifyResult = safeStringify(cause);
1044
+ if (!stringifyResult.ok) {
1045
+ return {
1046
+ errorSummary: summary,
1047
+ downgrade: "non_serializable"
1048
+ };
1049
+ }
1050
+ if (truncated) {
1051
+ return {
1052
+ errorSummary: summary,
1053
+ downgrade: "oversized"
1054
+ };
1055
+ }
1056
+ if (message === "Unknown error") {
1057
+ return {
1058
+ errorSummary: summary,
1059
+ downgrade: "unknown"
1060
+ };
1061
+ }
1062
+ return { errorSummary: summary };
1063
+ };
1064
+
1065
+ // src/internal/runtime/core/DebugSink.record.ts
1066
+ var currentDebugSinks = import_effect3.FiberRef.unsafeMake([]);
1067
+ var currentRuntimeLabel = import_effect3.FiberRef.unsafeMake(void 0);
1068
+ var currentTxnId = import_effect3.FiberRef.unsafeMake(void 0);
1069
+ var currentOpSeq = import_effect3.FiberRef.unsafeMake(void 0);
1070
+ var currentDiagnosticsLevel = import_effect3.FiberRef.unsafeMake("off");
1071
+ var currentTraitConvergeDiagnosticsSampling = import_effect3.FiberRef.unsafeMake({
1072
+ sampleEveryN: 32,
1073
+ topK: 3
1074
+ });
1075
+ var browserLifecycleSeen = /* @__PURE__ */ new Set();
1076
+ var browserDiagnosticSeen = /* @__PURE__ */ new Set();
1077
+ var lifecycleErrorLog = (event) => {
1078
+ const moduleId = event.moduleId ?? "unknown";
1079
+ const causePretty = (() => {
1080
+ try {
1081
+ return import_effect3.Cause.pretty(event.cause, {
1082
+ renderErrorCause: true
1083
+ });
1084
+ } catch {
1085
+ try {
1086
+ return JSON.stringify(event.cause, null, 2);
1087
+ } catch {
1088
+ return String(event.cause);
1089
+ }
1090
+ }
1091
+ })();
1092
+ const message = `[Logix][module=${moduleId}] lifecycle:error
1093
+ ${causePretty}`;
1094
+ return import_effect3.Effect.logError(message).pipe(
1095
+ import_effect3.Effect.annotateLogs({
1096
+ "logix.moduleId": moduleId,
1097
+ "logix.event": "lifecycle:error",
1098
+ "logix.cause": causePretty
1099
+ })
1100
+ );
1101
+ };
1102
+ var diagnosticLog = (event) => {
1103
+ const moduleId = event.moduleId ?? "unknown";
1104
+ const header = `[Logix][module=${moduleId}] diagnostic(${event.severity})`;
1105
+ const detail = `code=${event.code} message=${event.message}${event.actionTag ? ` action=${event.actionTag}` : ""}${event.hint ? `
1106
+ hint: ${event.hint}` : ""}`;
1107
+ const msg = `${header}
1108
+ ${detail}`;
1109
+ const base = event.severity === "warning" ? import_effect3.Effect.logWarning(msg) : event.severity === "info" ? import_effect3.Effect.logInfo(msg) : import_effect3.Effect.logError(msg);
1110
+ const annotations = {
1111
+ "logix.moduleId": moduleId,
1112
+ "logix.event": `diagnostic(${event.severity})`,
1113
+ "logix.diagnostic.code": event.code,
1114
+ "logix.diagnostic.message": event.message
1115
+ };
1116
+ if (event.hint) {
1117
+ annotations["logix.diagnostic.hint"] = event.hint;
1118
+ }
1119
+ if (event.actionTag) {
1120
+ annotations["logix.diagnostic.actionTag"] = event.actionTag;
1121
+ }
1122
+ return base.pipe(import_effect3.Effect.annotateLogs(annotations));
1123
+ };
1124
+ var noopLayer = import_effect3.Layer.locallyScoped(currentDebugSinks, []);
1125
+ var errorOnlySink = {
1126
+ record: (event) => event.type === "lifecycle:error" ? lifecycleErrorLog(event) : event.type === "diagnostic" && event.severity !== "info" ? diagnosticLog(event) : import_effect3.Effect.void
1127
+ };
1128
+ var errorOnlyLayer = import_effect3.Layer.locallyScoped(currentDebugSinks, [errorOnlySink]);
1129
+ var isErrorOnlyOnlySinks = (sinks) => sinks.length === 1 && sinks[0] === errorOnlySink;
1130
+ var consoleSink = {
1131
+ record: (event) => event.type === "lifecycle:error" ? lifecycleErrorLog(event) : event.type === "diagnostic" ? diagnosticLog(event) : import_effect3.Effect.logDebug({ debugEvent: event })
1132
+ };
1133
+ var consoleLayer = import_effect3.Layer.locallyScoped(currentDebugSinks, [consoleSink]);
1134
+ var isBrowser = typeof window !== "undefined" && typeof document !== "undefined";
1135
+ var renderBrowserConsoleEvent = (event) => {
1136
+ if (typeof event.type === "string" && event.type.startsWith("trace:")) {
1137
+ const moduleId = event.moduleId ?? "unknown";
1138
+ const type = event.type;
1139
+ return import_effect3.Effect.sync(() => {
1140
+ console.groupCollapsed(
1141
+ "%c[Logix]%c trace %c" + moduleId + "%c " + String(type),
1142
+ "color:#6b7280;font-weight:bold",
1143
+ // tag
1144
+ "color:#3b82f6",
1145
+ // label
1146
+ "color:#9ca3af",
1147
+ // module id
1148
+ "color:#6b7280"
1149
+ // type
1150
+ );
1151
+ console.log(event);
1152
+ console.groupEnd();
1153
+ });
1154
+ }
1155
+ if (event.type === "lifecycle:error") {
1156
+ const moduleId = event.moduleId ?? "unknown";
1157
+ const causePretty = (() => {
1158
+ try {
1159
+ return import_effect3.Cause.pretty(event.cause, { renderErrorCause: true });
1160
+ } catch {
1161
+ try {
1162
+ return JSON.stringify(event.cause, null, 2);
1163
+ } catch {
1164
+ return String(event.cause);
1165
+ }
1166
+ }
1167
+ })();
1168
+ const key = `${moduleId}|${causePretty}`;
1169
+ if (browserLifecycleSeen.has(key)) {
1170
+ return import_effect3.Effect.void;
1171
+ }
1172
+ browserLifecycleSeen.add(key);
1173
+ return import_effect3.Effect.sync(() => {
1174
+ console.groupCollapsed(
1175
+ "%c[Logix]%c lifecycle:error %c" + moduleId,
1176
+ "color:#ef4444;font-weight:bold",
1177
+ // tag
1178
+ "color:#ef4444",
1179
+ // label
1180
+ "color:#9ca3af"
1181
+ // module id
1182
+ );
1183
+ console.error(causePretty);
1184
+ console.groupEnd();
1185
+ });
1186
+ }
1187
+ if (event.type === "diagnostic") {
1188
+ const moduleId = event.moduleId ?? "unknown";
1189
+ const detail = `code=${event.code} message=${event.message}${event.actionTag ? ` action=${event.actionTag}` : ""}${event.hint ? `
1190
+ hint: ${event.hint}` : ""}`;
1191
+ const color = event.severity === "warning" ? "color:#d97706" : event.severity === "info" ? "color:#3b82f6" : "color:#ef4444";
1192
+ const label = event.severity === "warning" ? "diagnostic(warning)" : event.severity === "info" ? "diagnostic(info)" : "diagnostic(error)";
1193
+ const key = `${moduleId}|${event.code}|${event.message}`;
1194
+ if (browserDiagnosticSeen.has(key)) {
1195
+ return import_effect3.Effect.void;
1196
+ }
1197
+ browserDiagnosticSeen.add(key);
1198
+ return import_effect3.Effect.sync(() => {
1199
+ console.groupCollapsed(
1200
+ "%c[Logix]%c " + label + "%c module=" + moduleId,
1201
+ "color:#6b7280;font-weight:bold",
1202
+ color,
1203
+ "color:#9ca3af"
1204
+ );
1205
+ if (event.severity === "warning") {
1206
+ console.warn(detail);
1207
+ } else if (event.severity === "info") {
1208
+ console.info(detail);
1209
+ } else {
1210
+ console.error(detail);
1211
+ }
1212
+ console.groupEnd();
1213
+ });
1214
+ }
1215
+ return import_effect3.Effect.void;
1216
+ };
1217
+ var browserConsoleSink = {
1218
+ record: (event) => {
1219
+ if (!isBrowser) {
1220
+ return event.type === "lifecycle:error" ? lifecycleErrorLog(event) : event.type === "diagnostic" ? diagnosticLog(event) : import_effect3.Effect.logDebug({ debugEvent: event });
1221
+ }
1222
+ return renderBrowserConsoleEvent(event);
1223
+ }
1224
+ };
1225
+ var browserConsoleLayer = import_effect3.Layer.locallyScoped(currentDebugSinks, [browserConsoleSink]);
1226
+ var browserDiagnosticConsoleSink = {
1227
+ record: (event) => {
1228
+ if (!isBrowser) {
1229
+ return event.type === "lifecycle:error" ? lifecycleErrorLog(event) : event.type === "diagnostic" && event.severity !== "info" ? diagnosticLog(event) : import_effect3.Effect.void;
1230
+ }
1231
+ return event.type === "lifecycle:error" || event.type === "diagnostic" && event.severity !== "info" ? renderBrowserConsoleEvent(event) : import_effect3.Effect.void;
1232
+ }
1233
+ };
1234
+ var browserDiagnosticConsoleLayer = import_effect3.Layer.locallyScoped(currentDebugSinks, [browserDiagnosticConsoleSink]);
1235
+ var browserPrettyLoggerLayer = import_effect3.Logger.replace(
1236
+ import_effect3.Logger.defaultLogger,
1237
+ import_effect3.Logger.prettyLogger({ mode: "browser", colors: true })
1238
+ );
1239
+ var record = (event) => import_effect3.Effect.gen(function* () {
1240
+ const sinks = yield* import_effect3.FiberRef.get(currentDebugSinks);
1241
+ if (isErrorOnlyOnlySinks(sinks)) {
1242
+ if (event.type === "lifecycle:error") {
1243
+ yield* lifecycleErrorLog(event);
1244
+ return;
1245
+ }
1246
+ if (event.type === "diagnostic") {
1247
+ if (event.severity !== "info") {
1248
+ yield* diagnosticLog(event);
1249
+ } else {
1250
+ yield* import_effect3.Effect.void;
1251
+ }
1252
+ return;
1253
+ }
1254
+ yield* import_effect3.Effect.void;
1255
+ return;
1256
+ }
1257
+ if (sinks.length === 0) {
1258
+ if (isBrowser) {
1259
+ if (event.type === "lifecycle:error" || event.type === "diagnostic") {
1260
+ yield* renderBrowserConsoleEvent(event);
1261
+ return;
1262
+ }
1263
+ yield* import_effect3.Effect.void;
1264
+ return;
1265
+ }
1266
+ if (event.type === "lifecycle:error") {
1267
+ yield* lifecycleErrorLog(event);
1268
+ return;
1269
+ }
1270
+ if (event.type === "diagnostic") {
1271
+ yield* diagnosticLog(event);
1272
+ return;
1273
+ }
1274
+ yield* import_effect3.Effect.void;
1275
+ return;
1276
+ }
1277
+ const enriched = event;
1278
+ const diagnosticsLevel = yield* import_effect3.FiberRef.get(currentDiagnosticsLevel);
1279
+ let now;
1280
+ const getNow = () => {
1281
+ if (now === void 0) now = Date.now();
1282
+ return now;
1283
+ };
1284
+ if (enriched.timestamp === void 0 && (diagnosticsLevel !== "off" || enriched.type === "lifecycle:error" || enriched.type === "diagnostic")) {
1285
+ ;
1286
+ enriched.timestamp = getNow();
1287
+ }
1288
+ if (diagnosticsLevel !== "off" && enriched.runtimeLabel === void 0) {
1289
+ const runtimeLabel = yield* import_effect3.FiberRef.get(currentRuntimeLabel);
1290
+ if (runtimeLabel) {
1291
+ ;
1292
+ enriched.runtimeLabel = runtimeLabel;
1293
+ }
1294
+ }
1295
+ if (enriched.type === "diagnostic" && enriched.txnId === void 0) {
1296
+ const txnId = yield* import_effect3.FiberRef.get(currentTxnId);
1297
+ if (txnId) {
1298
+ ;
1299
+ enriched.txnId = txnId;
1300
+ }
1301
+ }
1302
+ if (diagnosticsLevel !== "off" && enriched.type === "trace:effectop" && enriched.linkId === void 0) {
1303
+ const linkId = yield* import_effect3.FiberRef.get(currentLinkId);
1304
+ if (linkId) {
1305
+ ;
1306
+ enriched.linkId = linkId;
1307
+ }
1308
+ }
1309
+ if (sinks.length === 1) {
1310
+ yield* sinks[0].record(enriched);
1311
+ return;
1312
+ }
1313
+ yield* import_effect3.Effect.forEach(sinks, (sink) => sink.record(enriched), { discard: true });
1314
+ });
1315
+
1316
+ // src/internal/runtime/core/LogicUnitMeta.ts
1317
+ var LOGIC_UNIT_META = /* @__PURE__ */ Symbol.for("logix.module.logic.meta");
1318
+ var attachLogicUnitMeta = (logic, meta) => {
1319
+ try {
1320
+ Object.defineProperty(logic, LOGIC_UNIT_META, {
1321
+ value: meta,
1322
+ enumerable: false,
1323
+ configurable: true
1324
+ });
1325
+ } catch {
1326
+ }
1327
+ return logic;
1328
+ };
1329
+
1330
+ // src/internal/runtime/core/env.ts
1331
+ var import_effect8 = require("effect");
1332
+
1333
+ // src/internal/runtime/core/HostScheduler.ts
1334
+ var noopCancel = () => {
1335
+ };
1336
+ var safeNowMs = () => {
1337
+ const perf = globalThis.performance;
1338
+ if (perf && typeof perf.now === "function") {
1339
+ try {
1340
+ const v = perf.now();
1341
+ if (typeof v === "number" && Number.isFinite(v)) return v;
1342
+ } catch {
1343
+ }
1344
+ }
1345
+ return Date.now();
1346
+ };
1347
+ var safeQueueMicrotask = (cb) => {
1348
+ const qm = globalThis.queueMicrotask;
1349
+ if (typeof qm === "function") {
1350
+ try {
1351
+ qm(cb);
1352
+ return;
1353
+ } catch {
1354
+ }
1355
+ }
1356
+ try {
1357
+ Promise.resolve().then(cb);
1358
+ } catch {
1359
+ setTimeout(cb, 0);
1360
+ }
1361
+ };
1362
+ var safeSetTimeout = (ms, cb) => {
1363
+ const id = setTimeout(cb, ms);
1364
+ return () => {
1365
+ try {
1366
+ clearTimeout(id);
1367
+ } catch {
1368
+ }
1369
+ };
1370
+ };
1371
+ var makeMessageChannelMacrotask = () => {
1372
+ const MC = globalThis.MessageChannel;
1373
+ if (typeof MC !== "function") return void 0;
1374
+ let channel;
1375
+ try {
1376
+ channel = new MC();
1377
+ } catch {
1378
+ return void 0;
1379
+ }
1380
+ const queue = [];
1381
+ let scheduled = false;
1382
+ const flush = () => {
1383
+ scheduled = false;
1384
+ const tasks = queue.splice(0, queue.length);
1385
+ for (const t of tasks) {
1386
+ if (t.canceled) continue;
1387
+ try {
1388
+ t.cb();
1389
+ } catch {
1390
+ }
1391
+ }
1392
+ };
1393
+ try {
1394
+ channel.port1.onmessage = flush;
1395
+ } catch {
1396
+ return void 0;
1397
+ }
1398
+ const schedule = (cb) => {
1399
+ const task = { canceled: false, cb };
1400
+ queue.push(task);
1401
+ if (!scheduled) {
1402
+ scheduled = true;
1403
+ try {
1404
+ channel.port2.postMessage(void 0);
1405
+ } catch {
1406
+ scheduled = false;
1407
+ return safeSetTimeout(0, cb);
1408
+ }
1409
+ }
1410
+ return () => {
1411
+ task.canceled = true;
1412
+ };
1413
+ };
1414
+ return schedule;
1415
+ };
1416
+ var makeSetImmediateMacrotask = () => {
1417
+ const si = globalThis.setImmediate;
1418
+ const ci = globalThis.clearImmediate;
1419
+ if (typeof si !== "function") return void 0;
1420
+ return (cb) => {
1421
+ let id;
1422
+ try {
1423
+ id = si(cb);
1424
+ } catch {
1425
+ return safeSetTimeout(0, cb);
1426
+ }
1427
+ return () => {
1428
+ if (typeof ci !== "function") return;
1429
+ try {
1430
+ ci(id);
1431
+ } catch {
1432
+ }
1433
+ };
1434
+ };
1435
+ };
1436
+ var makeRaf = () => {
1437
+ const raf = globalThis.requestAnimationFrame;
1438
+ const cancel = globalThis.cancelAnimationFrame;
1439
+ if (typeof raf !== "function") return void 0;
1440
+ return (cb) => {
1441
+ let id;
1442
+ try {
1443
+ id = raf(cb);
1444
+ } catch {
1445
+ return noopCancel;
1446
+ }
1447
+ return () => {
1448
+ if (typeof cancel !== "function") return;
1449
+ try {
1450
+ cancel(id);
1451
+ } catch {
1452
+ }
1453
+ };
1454
+ };
1455
+ };
1456
+ var makeDefaultHostScheduler = () => {
1457
+ const macrotask = makeSetImmediateMacrotask() ?? makeMessageChannelMacrotask() ?? ((cb) => safeSetTimeout(0, cb));
1458
+ const raf = makeRaf();
1459
+ return {
1460
+ nowMs: safeNowMs,
1461
+ scheduleMicrotask: safeQueueMicrotask,
1462
+ scheduleMacrotask: macrotask,
1463
+ scheduleAnimationFrame: (cb) => raf?.(cb) ?? macrotask(cb),
1464
+ scheduleTimeout: safeSetTimeout
1465
+ };
1466
+ };
1467
+ var globalHostScheduler;
1468
+ var getGlobalHostScheduler = () => {
1469
+ globalHostScheduler ?? (globalHostScheduler = makeDefaultHostScheduler());
1470
+ return globalHostScheduler;
1471
+ };
1472
+
1473
+ // src/internal/runtime/core/RuntimeStore.ts
1474
+ var parseTopicKey = (topicKey) => {
1475
+ const idx = topicKey.indexOf("::");
1476
+ if (idx <= 0) return void 0;
1477
+ const moduleId = topicKey.slice(0, idx);
1478
+ const rest = topicKey.slice(idx + 2);
1479
+ if (rest.length === 0) return void 0;
1480
+ const idx2 = rest.indexOf("::");
1481
+ if (idx2 < 0) {
1482
+ return { kind: "module", moduleInstanceKey: `${moduleId}::${rest}` };
1483
+ }
1484
+ const instanceId = rest.slice(0, idx2);
1485
+ const suffix = rest.slice(idx2 + 2);
1486
+ if (suffix.startsWith("rq:")) {
1487
+ const selectorId = suffix.slice("rq:".length);
1488
+ if (selectorId.length === 0) return void 0;
1489
+ return {
1490
+ kind: "readQuery",
1491
+ moduleInstanceKey: `${moduleId}::${instanceId}`,
1492
+ selectorId
1493
+ };
1494
+ }
1495
+ return { kind: "module", moduleInstanceKey: `${moduleId}::${instanceId}` };
1496
+ };
1497
+ var makeRuntimeStore = () => {
1498
+ let tickSeq = 0;
1499
+ const moduleStates = /* @__PURE__ */ new Map();
1500
+ const topicVersions = /* @__PURE__ */ new Map();
1501
+ const topicPriorities = /* @__PURE__ */ new Map();
1502
+ const listenersByTopic = /* @__PURE__ */ new Map();
1503
+ const subscriberCountByModule = /* @__PURE__ */ new Map();
1504
+ const getTopicVersion = (topicKey) => topicVersions.get(topicKey) ?? 0;
1505
+ const getTopicPriority = (topicKey) => topicPriorities.get(topicKey) ?? "normal";
1506
+ const commitTopicBump = (topicKey, priority) => {
1507
+ const prev = topicVersions.get(topicKey) ?? 0;
1508
+ topicVersions.set(topicKey, prev + 1);
1509
+ topicPriorities.set(topicKey, priority);
1510
+ };
1511
+ const subscribeTopic = (topicKey, listener) => {
1512
+ const info = parseTopicKey(topicKey);
1513
+ const existing = listenersByTopic.get(topicKey);
1514
+ const set = existing ?? /* @__PURE__ */ new Set();
1515
+ const alreadyHas = set.has(listener);
1516
+ if (!alreadyHas) {
1517
+ set.add(listener);
1518
+ }
1519
+ if (!existing) {
1520
+ listenersByTopic.set(topicKey, set);
1521
+ }
1522
+ if (!alreadyHas && info) {
1523
+ const prev = subscriberCountByModule.get(info.moduleInstanceKey) ?? 0;
1524
+ subscriberCountByModule.set(info.moduleInstanceKey, prev + 1);
1525
+ }
1526
+ return () => {
1527
+ const current = listenersByTopic.get(topicKey);
1528
+ if (!current) return;
1529
+ const deleted = current.delete(listener);
1530
+ if (deleted && info) {
1531
+ const prev = subscriberCountByModule.get(info.moduleInstanceKey) ?? 0;
1532
+ const next = prev - 1;
1533
+ if (next <= 0) {
1534
+ subscriberCountByModule.delete(info.moduleInstanceKey);
1535
+ } else {
1536
+ subscriberCountByModule.set(info.moduleInstanceKey, next);
1537
+ }
1538
+ }
1539
+ if (current.size === 0) {
1540
+ listenersByTopic.delete(topicKey);
1541
+ }
1542
+ };
1543
+ };
1544
+ const getTopicSubscriberCount = (topicKey) => listenersByTopic.get(topicKey)?.size ?? 0;
1545
+ const getModuleSubscriberCount = (moduleInstanceKey) => subscriberCountByModule.get(moduleInstanceKey) ?? 0;
1546
+ const registerModuleInstance = (args) => {
1547
+ moduleStates.set(args.moduleInstanceKey, args.initialState);
1548
+ if (!topicVersions.has(args.moduleInstanceKey)) {
1549
+ topicVersions.set(args.moduleInstanceKey, 0);
1550
+ topicPriorities.set(args.moduleInstanceKey, "normal");
1551
+ }
1552
+ };
1553
+ const unregisterModuleInstance = (moduleInstanceKey) => {
1554
+ moduleStates.delete(moduleInstanceKey);
1555
+ };
1556
+ const commitTick = (args) => {
1557
+ tickSeq = args.tickSeq;
1558
+ for (const [key, commit] of args.accepted.modules) {
1559
+ moduleStates.set(key, commit.state);
1560
+ }
1561
+ const changedTopics = /* @__PURE__ */ new Map();
1562
+ for (const [topicKey, priority] of args.accepted.dirtyTopics) {
1563
+ commitTopicBump(topicKey, priority);
1564
+ const listeners = Array.from(listenersByTopic.get(topicKey) ?? []);
1565
+ if (listeners.length > 0) {
1566
+ changedTopics.set(topicKey, { priority, listeners });
1567
+ }
1568
+ }
1569
+ return { changedTopics };
1570
+ };
1571
+ const getModuleState = (moduleInstanceKey) => moduleStates.get(moduleInstanceKey);
1572
+ const dispose = () => {
1573
+ moduleStates.clear();
1574
+ topicVersions.clear();
1575
+ topicPriorities.clear();
1576
+ listenersByTopic.clear();
1577
+ subscriberCountByModule.clear();
1578
+ };
1579
+ return {
1580
+ getTickSeq: () => tickSeq,
1581
+ getModuleState,
1582
+ getTopicVersion,
1583
+ getTopicPriority,
1584
+ subscribeTopic,
1585
+ getTopicSubscriberCount,
1586
+ getModuleSubscriberCount,
1587
+ registerModuleInstance,
1588
+ unregisterModuleInstance,
1589
+ commitTick,
1590
+ dispose
1591
+ };
1592
+ };
1593
+
1594
+ // src/internal/runtime/core/TickScheduler.ts
1595
+ var import_effect6 = require("effect");
1596
+
1597
+ // src/internal/runtime/core/DevtoolsHub.ts
1598
+ var import_effect4 = require("effect");
1599
+ var lastRunTs = 0;
1600
+ var lastRunTsSeq = 0;
1601
+ var nextRunId = () => {
1602
+ const ts = Date.now();
1603
+ if (ts === lastRunTs) {
1604
+ lastRunTsSeq += 1;
1605
+ } else {
1606
+ lastRunTs = ts;
1607
+ lastRunTsSeq = 0;
1608
+ }
1609
+ return lastRunTsSeq === 0 ? `run-${ts}` : `run-${ts}.${lastRunTsSeq}`;
1610
+ };
1611
+ var currentRunId = nextRunId();
1612
+
1613
+ // src/internal/runtime/core/TaskRunner.ts
1614
+ var import_effect5 = require("effect");
1615
+ var inSyncTransactionFiber = import_effect5.FiberRef.unsafeMake(false);
1616
+ var forceSourceRefresh = import_effect5.FiberRef.unsafeMake(false);
1617
+
1618
+ // src/internal/runtime/core/DeclarativeLinkRuntime.ts
1619
+ var import_effect7 = require("effect");
1620
+ var makeDeclarativeLinkRuntime = () => {
1621
+ const moduleAsSourceById = /* @__PURE__ */ new Map();
1622
+ const moduleAsSourceIdsBySource = /* @__PURE__ */ new Map();
1623
+ const declarativeById = /* @__PURE__ */ new Map();
1624
+ const declarativeReadNodesBySource = /* @__PURE__ */ new Map();
1625
+ const registerModuleAsSourceLink = (link) => {
1626
+ const stored = {
1627
+ ...link,
1628
+ hasValue: false,
1629
+ lastValue: void 0
1630
+ };
1631
+ moduleAsSourceById.set(link.id, stored);
1632
+ const set = moduleAsSourceIdsBySource.get(link.sourceModuleInstanceKey) ?? /* @__PURE__ */ new Set();
1633
+ set.add(link.id);
1634
+ moduleAsSourceIdsBySource.set(link.sourceModuleInstanceKey, set);
1635
+ return () => {
1636
+ moduleAsSourceById.delete(link.id);
1637
+ const current = moduleAsSourceIdsBySource.get(link.sourceModuleInstanceKey);
1638
+ if (!current) return;
1639
+ current.delete(link.id);
1640
+ if (current.size === 0) {
1641
+ moduleAsSourceIdsBySource.delete(link.sourceModuleInstanceKey);
1642
+ }
1643
+ };
1644
+ };
1645
+ const registerDeclarativeLink = (link) => {
1646
+ const readNodeById = /* @__PURE__ */ new Map();
1647
+ for (const n of link.readNodes) {
1648
+ readNodeById.set(n.nodeId, n);
1649
+ }
1650
+ const dispatchNodeById = /* @__PURE__ */ new Map();
1651
+ for (const n of link.dispatchNodes) {
1652
+ dispatchNodeById.set(n.nodeId, n);
1653
+ }
1654
+ const incomingByDispatch = /* @__PURE__ */ new Map();
1655
+ for (const e of link.ir.edges) {
1656
+ const to = e.to;
1657
+ const isDispatch = dispatchNodeById.has(to);
1658
+ if (!isDispatch) continue;
1659
+ incomingByDispatch.set(to, (incomingByDispatch.get(to) ?? 0) + 1);
1660
+ const count = incomingByDispatch.get(to) ?? 0;
1661
+ if (count > 1) {
1662
+ throw new Error(
1663
+ `[DeclarativeLinkRuntime] Invalid DeclarativeLinkIR: dispatch node has multiple incoming edges (linkId=${link.linkId}, nodeId=${to}).`
1664
+ );
1665
+ }
1666
+ }
1667
+ const dispatchTargetsByReadNode = /* @__PURE__ */ new Map();
1668
+ for (const e of link.ir.edges) {
1669
+ const from = e.from;
1670
+ const to = e.to;
1671
+ if (!readNodeById.has(from)) continue;
1672
+ if (!dispatchNodeById.has(to)) continue;
1673
+ const list = dispatchTargetsByReadNode.get(from) ?? [];
1674
+ list.push(to);
1675
+ dispatchTargetsByReadNode.set(from, list);
1676
+ }
1677
+ const stored = {
1678
+ ...link,
1679
+ readNodeById,
1680
+ dispatchNodeById,
1681
+ dispatchTargetsByReadNode,
1682
+ readNodeState: /* @__PURE__ */ new Map()
1683
+ };
1684
+ declarativeById.set(link.linkId, stored);
1685
+ for (const n of link.readNodes) {
1686
+ const list = declarativeReadNodesBySource.get(n.moduleInstanceKey) ?? [];
1687
+ list.push({ linkId: link.linkId, nodeId: n.nodeId });
1688
+ declarativeReadNodesBySource.set(n.moduleInstanceKey, list);
1689
+ }
1690
+ return () => {
1691
+ declarativeById.delete(link.linkId);
1692
+ for (const n of link.readNodes) {
1693
+ const list = declarativeReadNodesBySource.get(n.moduleInstanceKey);
1694
+ if (!list) continue;
1695
+ const next = list.filter((x) => !(x.linkId === link.linkId && x.nodeId === n.nodeId));
1696
+ if (next.length === 0) {
1697
+ declarativeReadNodesBySource.delete(n.moduleInstanceKey);
1698
+ } else {
1699
+ declarativeReadNodesBySource.set(n.moduleInstanceKey, next);
1700
+ }
1701
+ }
1702
+ };
1703
+ };
1704
+ const applyForSources = (args) => import_effect7.Effect.gen(function* () {
1705
+ let scheduled = false;
1706
+ for (const sourceKey of args.changedModuleInstanceKeys) {
1707
+ const ids = moduleAsSourceIdsBySource.get(sourceKey);
1708
+ if (!ids || ids.size === 0) continue;
1709
+ const commit = args.acceptedModules.get(sourceKey);
1710
+ if (!commit) continue;
1711
+ for (const id of ids) {
1712
+ const link = moduleAsSourceById.get(id);
1713
+ if (!link) continue;
1714
+ let selected;
1715
+ try {
1716
+ selected = link.readQuery.select(commit.state);
1717
+ } catch {
1718
+ continue;
1719
+ }
1720
+ const nextValue = link.computeValue(selected);
1721
+ if (link.hasValue && link.equalsValue(link.lastValue, nextValue)) {
1722
+ continue;
1723
+ }
1724
+ link.hasValue = true;
1725
+ link.lastValue = nextValue;
1726
+ scheduled = true;
1727
+ yield* link.applyValue(nextValue);
1728
+ }
1729
+ }
1730
+ for (const sourceKey of args.changedModuleInstanceKeys) {
1731
+ const refs = declarativeReadNodesBySource.get(sourceKey);
1732
+ if (!refs || refs.length === 0) continue;
1733
+ const commit = args.acceptedModules.get(sourceKey);
1734
+ if (!commit) continue;
1735
+ for (const ref of refs) {
1736
+ const link = declarativeById.get(ref.linkId);
1737
+ if (!link) continue;
1738
+ const readNode = link.readNodeById.get(ref.nodeId);
1739
+ if (!readNode) continue;
1740
+ let value;
1741
+ try {
1742
+ value = readNode.readQuery.select(commit.state);
1743
+ } catch {
1744
+ continue;
1745
+ }
1746
+ const state = link.readNodeState.get(ref.nodeId) ?? { hasValue: false, lastValue: void 0 };
1747
+ const changed = !state.hasValue || !Object.is(state.lastValue, value);
1748
+ if (!changed) continue;
1749
+ state.hasValue = true;
1750
+ state.lastValue = value;
1751
+ link.readNodeState.set(ref.nodeId, state);
1752
+ const targets = link.dispatchTargetsByReadNode.get(ref.nodeId) ?? [];
1753
+ for (const dispatchNodeId of targets) {
1754
+ const node = link.dispatchNodeById.get(dispatchNodeId);
1755
+ if (!node) continue;
1756
+ scheduled = true;
1757
+ yield* node.dispatch(value);
1758
+ }
1759
+ }
1760
+ }
1761
+ return { scheduled };
1762
+ });
1763
+ return {
1764
+ registerModuleAsSourceLink,
1765
+ registerDeclarativeLink,
1766
+ applyForSources
1767
+ };
1768
+ };
1769
+
1770
+ // src/internal/runtime/core/env.ts
1771
+ var getNodeEnv = () => {
1772
+ try {
1773
+ const env = globalThis?.process?.env;
1774
+ return typeof env?.NODE_ENV === "string" ? env.NODE_ENV : void 0;
1775
+ } catch {
1776
+ return void 0;
1777
+ }
1778
+ };
1779
+ var isDevEnv = () => getNodeEnv() !== "production";
1780
+ var StateTransactionConfigTagImpl = class extends import_effect8.Context.Tag("@logixjs/core/StateTransactionRuntimeConfig")() {
1781
+ };
1782
+ var ReadQueryStrictGateConfigTagImpl = class extends import_effect8.Context.Tag("@logixjs/core/ReadQueryStrictGateRuntimeConfig")() {
1783
+ };
1784
+ var ReplayModeConfigTagImpl = class extends import_effect8.Context.Tag("@logixjs/core/ReplayModeConfig")() {
1785
+ };
1786
+ var StateTransactionOverridesTagImpl = class extends import_effect8.Context.Tag("@logixjs/core/StateTransactionOverrides")() {
1787
+ };
1788
+ var ConcurrencyPolicyTagImpl = class extends import_effect8.Context.Tag("@logixjs/core/ConcurrencyPolicy")() {
1789
+ };
1790
+ var ConcurrencyPolicyOverridesTagImpl = class extends import_effect8.Context.Tag("@logixjs/core/ConcurrencyPolicyOverrides")() {
1791
+ };
1792
+ var RuntimeStoreTag = class extends import_effect8.Context.Tag("@logixjs/core/RuntimeStore")() {
1793
+ };
1794
+ var runtimeStoreLayer = import_effect8.Layer.scoped(
1795
+ RuntimeStoreTag,
1796
+ import_effect8.Effect.acquireRelease(
1797
+ import_effect8.Effect.sync(() => makeRuntimeStore()),
1798
+ (store) => import_effect8.Effect.sync(() => store.dispose())
1799
+ )
1800
+ );
1801
+ var HostSchedulerTag = class extends import_effect8.Context.Tag("@logixjs/core/HostScheduler")() {
1802
+ };
1803
+ var hostSchedulerLayer = import_effect8.Layer.succeed(
1804
+ HostSchedulerTag,
1805
+ getGlobalHostScheduler()
1806
+ );
1807
+ var DeclarativeLinkRuntimeTag = class extends import_effect8.Context.Tag("@logixjs/core/DeclarativeLinkRuntime")() {
1808
+ };
1809
+ var declarativeLinkRuntimeLayer = import_effect8.Layer.succeed(
1810
+ DeclarativeLinkRuntimeTag,
1811
+ makeDeclarativeLinkRuntime()
1812
+ );
1813
+ var TickSchedulerTag = class extends import_effect8.Context.Tag("@logixjs/core/TickScheduler")() {
1814
+ };
1815
+
1816
+ // src/internal/runtime/core/TxnOriginOverride.ts
1817
+ var import_effect9 = require("effect");
1818
+ var currentTxnOriginOverride = import_effect9.FiberRef.unsafeMake(void 0);
1819
+
1820
+ // src/internal/runtime/core/runtimeInternalsAccessor.ts
1821
+ var RUNTIME_INTERNALS = /* @__PURE__ */ Symbol.for("@logixjs/core/runtimeInternals");
1822
+ var formatScope = (moduleId, instanceId) => {
1823
+ const m = typeof moduleId === "string" && moduleId.length > 0 ? moduleId : "unknown";
1824
+ const i = typeof instanceId === "string" && instanceId.length > 0 ? instanceId : "unknown";
1825
+ return `moduleId=${m}, instanceId=${i}`;
1826
+ };
1827
+ var getRuntimeInternals = (runtime) => {
1828
+ const scope = runtime;
1829
+ const internals = runtime[RUNTIME_INTERNALS];
1830
+ if (!internals) {
1831
+ const msg = isDevEnv() ? [
1832
+ "[MissingRuntimeInternals] Runtime internals not installed on ModuleRuntime instance.",
1833
+ `scope: ${formatScope(scope.moduleId, scope.instanceId)}`,
1834
+ "fix:",
1835
+ "- Ensure ModuleRuntime.make calls internalHooks.installInternalHooks (020 foundation).",
1836
+ "- If you created a mock runtime for tests, attach internals or avoid calling internal-only APIs."
1837
+ ].join("\n") : "Runtime internals not installed";
1838
+ throw new Error(msg);
1839
+ }
1840
+ const runtimeInstanceId = scope.instanceId;
1841
+ if (typeof runtimeInstanceId === "string" && runtimeInstanceId.length > 0 && runtimeInstanceId !== internals.instanceId) {
1842
+ throw new Error(
1843
+ isDevEnv() ? [
1844
+ "[InconsistentRuntimeInternals] Runtime internals instanceId mismatch.",
1845
+ `runtime: ${formatScope(scope.moduleId, runtimeInstanceId)}`,
1846
+ `internals: ${formatScope(internals.moduleId, internals.instanceId)}`
1847
+ ].join("\n") : "Runtime internals mismatch"
1848
+ );
1849
+ }
1850
+ return internals;
1851
+ };
1852
+
1853
+ // src/internal/runtime/core/RootContext.ts
1854
+ var import_effect10 = require("effect");
1855
+ var RootContextTagImpl = class extends import_effect10.Context.Tag("@logixjs/core/RootContext")() {
1856
+ };
1857
+ var RootContextTag = RootContextTagImpl;
1858
+
1859
+ // src/internal/effect-op.ts
1860
+ var import_effect12 = require("effect");
1861
+
1862
+ // src/internal/observability/runSession.ts
1863
+ var import_effect11 = require("effect");
1864
+ var RunSessionTagImpl = class extends import_effect11.Context.Tag("@logixjs/core/RunSession")() {
1865
+ };
1866
+ var RunSessionTag = RunSessionTagImpl;
1867
+
1868
+ // src/internal/effect-op.ts
1869
+ var nextGlobalOpSeq = 0;
1870
+ var nextOpSeq = () => {
1871
+ nextGlobalOpSeq += 1;
1872
+ return nextGlobalOpSeq;
1873
+ };
1874
+ var makeId = (instanceId, opSeq) => instanceId ? `${instanceId}::o${opSeq}` : `o${opSeq}`;
1875
+ var makeInRunSession = (params) => import_effect12.Effect.gen(function* () {
1876
+ if (params.id) {
1877
+ return {
1878
+ id: params.id,
1879
+ kind: params.kind,
1880
+ name: params.name,
1881
+ payload: params.payload,
1882
+ meta: params.meta,
1883
+ effect: params.effect
1884
+ };
1885
+ }
1886
+ const meta = params.meta ?? {};
1887
+ const instanceId = meta.instanceId;
1888
+ let opSeq;
1889
+ if (typeof meta.opSeq === "number" && Number.isFinite(meta.opSeq)) {
1890
+ opSeq = Math.floor(meta.opSeq);
1891
+ } else {
1892
+ const sessionOpt = yield* import_effect12.Effect.serviceOption(RunSessionTag);
1893
+ if (import_effect12.Option.isSome(sessionOpt)) {
1894
+ const key = instanceId ?? "global";
1895
+ opSeq = sessionOpt.value.local.nextSeq("opSeq", key);
1896
+ } else {
1897
+ opSeq = nextOpSeq();
1898
+ }
1899
+ }
1900
+ return {
1901
+ id: makeId(instanceId, opSeq),
1902
+ kind: params.kind,
1903
+ name: params.name,
1904
+ payload: params.payload,
1905
+ meta: meta.opSeq === opSeq ? meta : { ...meta, opSeq },
1906
+ effect: params.effect
1907
+ };
1908
+ });
1909
+ var run = (op, stack) => runWithMiddleware(op, stack);
1910
+
1911
+ // src/internal/runtime/core/WorkflowRuntime.ts
1912
+ var WORKFLOW_REGISTRY = /* @__PURE__ */ Symbol.for("@logixjs/core/workflowRegistry");
1913
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1914
+ var isObjectLike = (value) => typeof value === "object" && value !== null || typeof value === "function";
1915
+ var getRegistry = (runtime) => runtime[WORKFLOW_REGISTRY];
1916
+ var resolveActionTag = (action) => {
1917
+ const tag = isObjectLike(action) ? action._tag : void 0;
1918
+ if (typeof tag === "string" && tag.length > 0) return tag;
1919
+ const type = isObjectLike(action) ? action.type : void 0;
1920
+ if (typeof type === "string" && type.length > 0) return type;
1921
+ if (tag != null) return String(tag);
1922
+ if (type != null) return String(type);
1923
+ return void 0;
1924
+ };
1925
+ var asNonEmptyString3 = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
1926
+ var KERNEL_PORT_SOURCE_REFRESH = "logix/kernel/sourceRefresh";
1927
+ var resolveServicePort = (runtime, env, serviceId, programId, stepKey) => {
1928
+ if (serviceId === KERNEL_PORT_SOURCE_REFRESH) {
1929
+ return (input) => import_effect13.Effect.gen(function* () {
1930
+ const fieldPath = asNonEmptyString3(isRecord3(input) ? input.fieldPath : void 0);
1931
+ if (!fieldPath) {
1932
+ throw makeWorkflowError({
1933
+ code: "WORKFLOW_INVALID_STEP",
1934
+ message: "KernelPort sourceRefresh requires input.fieldPath (non-empty string).",
1935
+ programId,
1936
+ source: { stepKey },
1937
+ detail: { serviceId, input }
1938
+ });
1939
+ }
1940
+ const internals = getRuntimeInternals(runtime);
1941
+ const handler = internals.traits.getSourceRefreshHandler(fieldPath);
1942
+ if (!handler) {
1943
+ return;
1944
+ }
1945
+ const force = isRecord3(input) && input.force === true;
1946
+ const runHandler = (state) => force ? import_effect13.Effect.locally(forceSourceRefresh, true)(handler(state)) : handler(state);
1947
+ const inTxn = yield* import_effect13.FiberRef.get(inSyncTransactionFiber);
1948
+ if (inTxn) {
1949
+ const state = yield* runtime.getState;
1950
+ yield* runHandler(state);
1951
+ return;
1952
+ }
1953
+ yield* internals.txn.runWithStateTransaction(
1954
+ {
1955
+ kind: "source-refresh",
1956
+ name: fieldPath
1957
+ },
1958
+ () => import_effect13.Effect.gen(function* () {
1959
+ const state = yield* runtime.getState;
1960
+ yield* runHandler(state);
1961
+ })
1962
+ );
1963
+ });
1964
+ }
1965
+ const tag = import_effect13.Context.GenericTag(serviceId);
1966
+ const opt = import_effect13.Context.getOption(env, tag);
1967
+ if (import_effect13.Option.isNone(opt)) {
1968
+ throw makeWorkflowError({
1969
+ code: "WORKFLOW_MISSING_SERVICE",
1970
+ message: `Missing service for serviceId="${serviceId}".`,
1971
+ programId,
1972
+ source: { stepKey },
1973
+ detail: { serviceId }
1974
+ });
1975
+ }
1976
+ const value = opt.value;
1977
+ if (typeof value === "function") {
1978
+ const fn = value;
1979
+ return (input) => fn(input);
1980
+ }
1981
+ const callFn = isObjectLike(value) ? value.call : void 0;
1982
+ if (typeof callFn === "function") {
1983
+ const call2 = callFn;
1984
+ return (input) => call2.call(value, input);
1985
+ }
1986
+ throw makeWorkflowError({
1987
+ code: "WORKFLOW_INVALID_SERVICE_PORT",
1988
+ message: `Invalid service port for serviceId="${serviceId}" (expected a function or { call(input): Effect }).`,
1989
+ programId,
1990
+ source: { stepKey },
1991
+ detail: { serviceId, portType: typeof value }
1992
+ });
1993
+ };
1994
+ var compileSteps = (steps, resolvePort) => {
1995
+ const visit = (step) => {
1996
+ switch (step.kind) {
1997
+ case "dispatch":
1998
+ return {
1999
+ kind: "dispatch",
2000
+ key: step.key,
2001
+ actionTag: step.actionTag,
2002
+ ...step.payload ? { payload: step.payload } : null
2003
+ };
2004
+ case "delay":
2005
+ return { kind: "delay", key: step.key, ms: step.ms };
2006
+ case "call":
2007
+ return {
2008
+ kind: "call",
2009
+ key: step.key,
2010
+ serviceId: step.serviceId,
2011
+ port: resolvePort(step.serviceId, step.key),
2012
+ ...step.input ? { input: step.input } : null,
2013
+ ...step.timeoutMs !== void 0 ? { timeoutMs: step.timeoutMs } : null,
2014
+ ...step.retryTimes !== void 0 ? { retryTimes: step.retryTimes } : null,
2015
+ onSuccess: step.onSuccess.map(visit),
2016
+ onFailure: step.onFailure.map(visit)
2017
+ };
2018
+ }
2019
+ };
2020
+ return steps.map(visit);
2021
+ };
2022
+ var resolveConcurrency = (def) => def.policy?.concurrency ?? "parallel";
2023
+ var resolvePriority = (def) => def.policy?.priority ?? "urgent";
2024
+ var makeRunId = (instanceId, programId, runSeq) => `${instanceId}::wf:${programId}::r${runSeq}`;
2025
+ var runBoundary = (args) => import_effect13.Effect.gen(function* () {
2026
+ const op = yield* makeInRunSession({
2027
+ kind: args.kind,
2028
+ name: args.name,
2029
+ effect: args.effect,
2030
+ payload: args.payload,
2031
+ meta: args.meta
2032
+ });
2033
+ const stack = args.middleware?.stack ?? [];
2034
+ return yield* run(op, stack);
2035
+ });
2036
+ var makeTimer = (args) => import_effect13.Effect.async((resume) => {
2037
+ let fired = false;
2038
+ const cancel = args.host.scheduleTimeout(args.ms, () => {
2039
+ fired = true;
2040
+ args.host.scheduleMicrotask(() => resume(import_effect13.Effect.void));
2041
+ });
2042
+ return import_effect13.Effect.sync(() => {
2043
+ cancel();
2044
+ }).pipe(import_effect13.Effect.zipRight(fired ? import_effect13.Effect.void : args.onCancel));
2045
+ });
2046
+ var ensureLimiterReady = (registry, runtime) => import_effect13.Effect.gen(function* () {
2047
+ if (registry.parallelLimiter !== void 0) return;
2048
+ const internals = getRuntimeInternals(runtime);
2049
+ const policy = yield* internals.concurrency.resolveConcurrencyPolicy();
2050
+ const limit = policy.concurrencyLimit;
2051
+ if (limit === "unbounded") {
2052
+ registry.parallelLimiter = null;
2053
+ return;
2054
+ }
2055
+ const n = typeof limit === "number" && Number.isFinite(limit) && limit >= 1 ? Math.floor(limit) : 16;
2056
+ registry.parallelLimiter = yield* import_effect13.Effect.makeSemaphore(n);
2057
+ });
2058
+ var withRootEnvIfAvailable = (eff) => import_effect13.Effect.gen(function* () {
2059
+ const rootOpt = yield* import_effect13.Effect.serviceOption(RootContextTag);
2060
+ if (import_effect13.Option.isNone(rootOpt)) {
2061
+ return yield* eff;
2062
+ }
2063
+ const root = rootOpt.value;
2064
+ const rootEnv = root.context ?? (yield* import_effect13.Deferred.await(root.ready));
2065
+ const currentEnv = yield* import_effect13.Effect.context();
2066
+ const mergedEnv = import_effect13.Context.merge(rootEnv, currentEnv);
2067
+ return yield* import_effect13.Effect.provide(eff, mergedEnv);
2068
+ });
2069
+ var ensurePortsResolved = (registry, runtime) => import_effect13.Effect.gen(function* () {
2070
+ const done = yield* import_effect13.Deferred.isDone(registry.portsReady);
2071
+ if (done) {
2072
+ yield* import_effect13.Deferred.await(registry.portsReady);
2073
+ return;
2074
+ }
2075
+ if (registry.portsResolving) {
2076
+ yield* import_effect13.Deferred.await(registry.portsReady);
2077
+ return;
2078
+ }
2079
+ registry.portsResolving = true;
2080
+ const env = yield* import_effect13.Effect.context();
2081
+ yield* import_effect13.Effect.sync(() => {
2082
+ const portCache = /* @__PURE__ */ new Map();
2083
+ for (const entry of registry.entries) {
2084
+ const program = entry.program;
2085
+ if (program.steps) continue;
2086
+ const resolvePort = (serviceId, stepKey) => {
2087
+ const cached = portCache.get(serviceId);
2088
+ if (cached) return cached;
2089
+ const resolved = resolveServicePort(runtime, env, serviceId, program.programId, stepKey);
2090
+ portCache.set(serviceId, resolved);
2091
+ return resolved;
2092
+ };
2093
+ program.steps = compileSteps(program.compiledSteps, resolvePort);
2094
+ }
2095
+ }).pipe(
2096
+ import_effect13.Effect.tap(() => import_effect13.Deferred.succeed(registry.portsReady, void 0)),
2097
+ import_effect13.Effect.catchAllCause((cause) => import_effect13.Deferred.failCause(registry.portsReady, cause).pipe(import_effect13.Effect.zipRight(import_effect13.Effect.failCause(cause)))),
2098
+ import_effect13.Effect.ensuring(
2099
+ import_effect13.Effect.sync(() => {
2100
+ registry.portsResolving = false;
2101
+ })
2102
+ )
2103
+ );
2104
+ });
2105
+ var shouldObserveForRun = (diagnostics, runSeq) => {
2106
+ if (diagnostics === "off") return false;
2107
+ if (diagnostics === "sampled") {
2108
+ return (runSeq & 15) === 0;
2109
+ }
2110
+ return true;
2111
+ };
2112
+ var startProgramRun = (args) => import_effect13.Effect.gen(function* () {
2113
+ const { entry, runtime, registry } = args;
2114
+ const { program, state } = entry;
2115
+ const diagnostics = yield* import_effect13.FiberRef.get(currentDiagnosticsLevel);
2116
+ const beginRun = () => {
2117
+ if (state.mode === "latest") {
2118
+ state.runSeq += 1;
2119
+ const runSeq3 = state.runSeq;
2120
+ const runId3 = makeRunId(runtime.instanceId, program.programId, runSeq3);
2121
+ return {
2122
+ runSeq: runSeq3,
2123
+ runId: runId3,
2124
+ canWriteBack: () => state.runSeq === runSeq3
2125
+ };
2126
+ }
2127
+ state.runSeq += 1;
2128
+ const runSeq2 = state.runSeq;
2129
+ const runId2 = makeRunId(runtime.instanceId, program.programId, runSeq2);
2130
+ return {
2131
+ runSeq: runSeq2,
2132
+ runId: runId2,
2133
+ canWriteBack: () => true
2134
+ };
2135
+ };
2136
+ if (state.mode === "exhaust") {
2137
+ if (state.busy) {
2138
+ if (diagnostics !== "off") {
2139
+ const observe2 = shouldObserveForRun(diagnostics, state.runSeq);
2140
+ const tickSeq = observe2 ? (yield* TickSchedulerTag).getTickSeq() : void 0;
2141
+ yield* runBoundary({
2142
+ kind: "flow",
2143
+ name: "workflow.drop",
2144
+ payload: { programId: program.programId, trigger: args.trigger },
2145
+ meta: {
2146
+ moduleId: runtime.moduleId,
2147
+ instanceId: runtime.instanceId,
2148
+ programId: program.programId,
2149
+ ...tickSeq !== void 0 ? { tickSeq } : null,
2150
+ policy: { disableObservers: !observe2 },
2151
+ reason: "exhaust"
2152
+ },
2153
+ effect: import_effect13.Effect.void,
2154
+ middleware: args.middleware
2155
+ });
2156
+ }
2157
+ return;
2158
+ }
2159
+ state.busy = true;
2160
+ }
2161
+ const { runSeq, runId, canWriteBack } = beginRun();
2162
+ if (state.mode === "latest") {
2163
+ const prev = state.current;
2164
+ const prevRunId = state.currentRunId;
2165
+ if (prev) {
2166
+ yield* import_effect13.Fiber.interruptFork(prev);
2167
+ if (diagnostics !== "off") {
2168
+ const observe2 = shouldObserveForRun(diagnostics, runSeq);
2169
+ const tickSeq = observe2 ? (yield* TickSchedulerTag).getTickSeq() : void 0;
2170
+ yield* runBoundary({
2171
+ kind: "flow",
2172
+ name: "workflow.cancel",
2173
+ payload: { programId: program.programId, cancelled: prevRunId, by: runId },
2174
+ meta: {
2175
+ moduleId: runtime.moduleId,
2176
+ instanceId: runtime.instanceId,
2177
+ programId: program.programId,
2178
+ ...tickSeq !== void 0 ? { tickSeq } : null,
2179
+ policy: { disableObservers: !observe2 },
2180
+ reason: "latest",
2181
+ cancelledByRunId: runId,
2182
+ cancelledRunId: prevRunId
2183
+ },
2184
+ effect: import_effect13.Effect.void,
2185
+ middleware: args.middleware
2186
+ });
2187
+ }
2188
+ }
2189
+ state.currentRunId = runId;
2190
+ }
2191
+ const observe = shouldObserveForRun(diagnostics, runSeq);
2192
+ const policy = { disableObservers: !observe };
2193
+ const programEffect = import_effect13.Effect.gen(function* () {
2194
+ const host = yield* HostSchedulerTag;
2195
+ const tick = yield* TickSchedulerTag;
2196
+ if (!program.steps) {
2197
+ const env = yield* import_effect13.Effect.context();
2198
+ const portCache = /* @__PURE__ */ new Map();
2199
+ const resolvePort = (serviceId, stepKey) => {
2200
+ const cached = portCache.get(serviceId);
2201
+ if (cached) return cached;
2202
+ const resolved = resolveServicePort(runtime, env, serviceId, program.programId, stepKey);
2203
+ portCache.set(serviceId, resolved);
2204
+ return resolved;
2205
+ };
2206
+ program.steps = compileSteps(program.compiledSteps, resolvePort);
2207
+ }
2208
+ const getTickSeq = () => observe ? tick.getTickSeq() : void 0;
2209
+ const emitTimerEvents = observe && diagnostics === "full";
2210
+ const evalPayload = (expr) => expr ? evalInputExpr(expr, args.payload) : void 0;
2211
+ const defaultInputForCall = () => args.trigger.kind === "action" ? args.payload : void 0;
2212
+ let timerTriggered = false;
2213
+ const runSteps = (steps) => import_effect13.Effect.gen(function* () {
2214
+ for (const step of steps) {
2215
+ if (!canWriteBack()) return;
2216
+ if (step.kind === "dispatch") {
2217
+ const payload2 = evalPayload(step.payload);
2218
+ const action = { _tag: step.actionTag, payload: payload2 };
2219
+ const tickSeq = getTickSeq();
2220
+ const dispatchEffectBase = program.priority === "nonUrgent" ? runtime.dispatchLowPriority(action) : runtime.dispatch(action);
2221
+ const dispatchEffect = timerTriggered ? import_effect13.Effect.locally(
2222
+ currentTxnOriginOverride,
2223
+ {
2224
+ kind: "workflow.timer",
2225
+ name: `timer:${program.programId}:${step.key}`
2226
+ }
2227
+ )(dispatchEffectBase) : dispatchEffectBase;
2228
+ yield* runBoundary({
2229
+ kind: "flow",
2230
+ name: "workflow.dispatch",
2231
+ payload: { actionTag: step.actionTag },
2232
+ meta: {
2233
+ moduleId: runtime.moduleId,
2234
+ instanceId: runtime.instanceId,
2235
+ programId: program.programId,
2236
+ runId,
2237
+ stepKey: step.key,
2238
+ ...tickSeq !== void 0 ? { tickSeq } : null,
2239
+ policy
2240
+ },
2241
+ effect: dispatchEffect,
2242
+ middleware: args.middleware
2243
+ }).pipe(import_effect13.Effect.asVoid);
2244
+ continue;
2245
+ }
2246
+ if (step.kind === "delay") {
2247
+ const timerId = emitTimerEvents ? `${runId}::timer:${step.key}` : void 0;
2248
+ const recordTimerEvent = (name, patchMeta) => import_effect13.Effect.gen(function* () {
2249
+ const tickSeq2 = getTickSeq();
2250
+ yield* runBoundary({
2251
+ kind: "flow",
2252
+ name,
2253
+ payload: { ms: step.ms },
2254
+ meta: {
2255
+ moduleId: runtime.moduleId,
2256
+ instanceId: runtime.instanceId,
2257
+ programId: program.programId,
2258
+ runId,
2259
+ stepKey: step.key,
2260
+ ...timerId ? { timerId } : null,
2261
+ ...tickSeq2 !== void 0 ? { tickSeq: tickSeq2 } : null,
2262
+ policy,
2263
+ ...patchMeta ?? null
2264
+ },
2265
+ effect: import_effect13.Effect.void,
2266
+ middleware: args.middleware
2267
+ });
2268
+ });
2269
+ const schedule = emitTimerEvents ? recordTimerEvent("workflow.timer.schedule") : import_effect13.Effect.void;
2270
+ const onCancel = emitTimerEvents ? recordTimerEvent("workflow.timer.cancel", { reason: "interrupt" }) : import_effect13.Effect.void;
2271
+ const fired = emitTimerEvents ? recordTimerEvent("workflow.timer.fired") : import_effect13.Effect.void;
2272
+ const delayEffect = schedule.pipe(
2273
+ import_effect13.Effect.zipRight(makeTimer({ host, ms: step.ms, onCancel })),
2274
+ import_effect13.Effect.zipRight(fired)
2275
+ );
2276
+ const tickSeq = getTickSeq();
2277
+ yield* runBoundary({
2278
+ kind: "flow",
2279
+ name: "workflow.delay",
2280
+ payload: { ms: step.ms },
2281
+ meta: {
2282
+ moduleId: runtime.moduleId,
2283
+ instanceId: runtime.instanceId,
2284
+ programId: program.programId,
2285
+ runId,
2286
+ stepKey: step.key,
2287
+ ...tickSeq !== void 0 ? { tickSeq } : null,
2288
+ ...timerId ? { timerId } : null,
2289
+ policy
2290
+ },
2291
+ effect: delayEffect,
2292
+ middleware: args.middleware
2293
+ }).pipe(import_effect13.Effect.asVoid);
2294
+ timerTriggered = true;
2295
+ continue;
2296
+ }
2297
+ const input = step.input ? evalInputExpr(step.input, args.payload) : defaultInputForCall();
2298
+ const maxRetries = step.retryTimes ?? 0;
2299
+ let exit;
2300
+ for (let attempt = 1; attempt <= maxRetries + 1; attempt += 1) {
2301
+ const tickSeq = getTickSeq();
2302
+ const base = runBoundary({
2303
+ kind: "service",
2304
+ name: `workflow.call:${step.serviceId}`,
2305
+ payload: { serviceId: step.serviceId },
2306
+ meta: {
2307
+ moduleId: runtime.moduleId,
2308
+ instanceId: runtime.instanceId,
2309
+ programId: program.programId,
2310
+ runId,
2311
+ stepKey: step.key,
2312
+ serviceId: step.serviceId,
2313
+ attempt,
2314
+ ...tickSeq !== void 0 ? { tickSeq } : null,
2315
+ policy
2316
+ },
2317
+ effect: step.port(input),
2318
+ middleware: args.middleware
2319
+ });
2320
+ const withTimeout = step.timeoutMs === void 0 ? base : import_effect13.Effect.gen(function* () {
2321
+ const timeoutMs = step.timeoutMs;
2322
+ if (timeoutMs === void 0) {
2323
+ return yield* base;
2324
+ }
2325
+ const timerId = emitTimerEvents ? `${runId}::timeout:${step.key}:a${attempt}` : void 0;
2326
+ const recordTimeoutEvent = (name, patchMeta) => import_effect13.Effect.gen(function* () {
2327
+ const tickSeq2 = getTickSeq();
2328
+ yield* runBoundary({
2329
+ kind: "flow",
2330
+ name,
2331
+ payload: { ms: timeoutMs },
2332
+ meta: {
2333
+ moduleId: runtime.moduleId,
2334
+ instanceId: runtime.instanceId,
2335
+ programId: program.programId,
2336
+ runId,
2337
+ stepKey: step.key,
2338
+ attempt,
2339
+ ...timerId ? { timerId } : null,
2340
+ ...tickSeq2 !== void 0 ? { tickSeq: tickSeq2 } : null,
2341
+ policy,
2342
+ ...patchMeta ?? null
2343
+ },
2344
+ effect: import_effect13.Effect.void,
2345
+ middleware: args.middleware
2346
+ });
2347
+ });
2348
+ const schedule = emitTimerEvents ? recordTimeoutEvent("workflow.timeout.schedule") : import_effect13.Effect.void;
2349
+ const onCancel = emitTimerEvents ? recordTimeoutEvent("workflow.timeout.cancel", { reason: "interrupt" }) : import_effect13.Effect.void;
2350
+ const fired = emitTimerEvents ? recordTimeoutEvent("workflow.timeout.fired") : import_effect13.Effect.void;
2351
+ const timeoutError = makeWorkflowError({
2352
+ code: "WORKFLOW_CALL_TIMEOUT",
2353
+ message: `Workflow call timed out (serviceId="${step.serviceId}", timeoutMs=${timeoutMs}).`,
2354
+ programId: program.programId,
2355
+ source: { stepKey: step.key },
2356
+ detail: { serviceId: step.serviceId, timeoutMs, attempt }
2357
+ });
2358
+ const timeoutFail = schedule.pipe(
2359
+ import_effect13.Effect.zipRight(makeTimer({ host, ms: timeoutMs, onCancel })),
2360
+ import_effect13.Effect.zipRight(fired),
2361
+ import_effect13.Effect.zipRight(import_effect13.Effect.fail(timeoutError))
2362
+ );
2363
+ return yield* import_effect13.Effect.raceFirst(base, timeoutFail);
2364
+ });
2365
+ const attemptExit = yield* import_effect13.Effect.exit(withTimeout);
2366
+ exit = attemptExit;
2367
+ if (!canWriteBack() || import_effect13.Exit.isSuccess(attemptExit)) {
2368
+ break;
2369
+ }
2370
+ if (import_effect13.Cause.isInterrupted(attemptExit.cause) || import_effect13.Option.isNone(import_effect13.Cause.failureOption(attemptExit.cause))) {
2371
+ break;
2372
+ }
2373
+ if (attempt < maxRetries + 1) {
2374
+ continue;
2375
+ }
2376
+ break;
2377
+ }
2378
+ if (!exit) {
2379
+ exit = import_effect13.Exit.succeed(void 0);
2380
+ }
2381
+ if (!canWriteBack()) return;
2382
+ if (import_effect13.Exit.isSuccess(exit)) {
2383
+ yield* runSteps(step.onSuccess);
2384
+ } else {
2385
+ const failure = import_effect13.Option.getOrUndefined(import_effect13.Cause.failureOption(exit.cause));
2386
+ const isTimeout = isObjectLike(failure) && failure._tag === "WorkflowError" && failure.code === "WORKFLOW_CALL_TIMEOUT";
2387
+ if (isTimeout) timerTriggered = true;
2388
+ yield* runSteps(step.onFailure);
2389
+ }
2390
+ }
2391
+ });
2392
+ const runTickSeq = getTickSeq();
2393
+ yield* runBoundary({
2394
+ kind: "flow",
2395
+ name: "workflow.run",
2396
+ payload: { trigger: args.trigger },
2397
+ meta: {
2398
+ moduleId: runtime.moduleId,
2399
+ instanceId: runtime.instanceId,
2400
+ programId: program.programId,
2401
+ runId,
2402
+ ...runTickSeq !== void 0 ? { tickSeq: runTickSeq } : null,
2403
+ policy
2404
+ },
2405
+ effect: runSteps(program.steps),
2406
+ middleware: args.middleware
2407
+ }).pipe(import_effect13.Effect.asVoid);
2408
+ });
2409
+ const limited = registry.parallelLimiter ? registry.parallelLimiter.withPermits(1)(programEffect) : programEffect;
2410
+ const fiber = yield* import_effect13.Effect.forkScoped(
2411
+ limited.pipe(
2412
+ import_effect13.Effect.catchAllCause((cause) => {
2413
+ const { errorSummary, downgrade } = toSerializableErrorSummary(cause);
2414
+ const downgradeHint = downgrade ? ` (downgrade=${downgrade})` : "";
2415
+ return record({
2416
+ type: "diagnostic",
2417
+ moduleId: runtime.moduleId,
2418
+ instanceId: runtime.instanceId,
2419
+ code: "workflow::run_crashed",
2420
+ severity: "error",
2421
+ message: `Workflow run crashed for programId="${program.programId}" runId="${runId}".${downgradeHint}`,
2422
+ hint: `${errorSummary.name ? `${errorSummary.name}: ` : ""}${errorSummary.message}`,
2423
+ actionTag: args.trigger.kind === "action" ? args.trigger.actionTag : void 0,
2424
+ kind: "workflow_run_crashed",
2425
+ trigger: {
2426
+ kind: "workflow",
2427
+ name: "run",
2428
+ details: {
2429
+ programId: program.programId,
2430
+ runId,
2431
+ trigger: args.trigger
2432
+ }
2433
+ }
2434
+ }).pipe(import_effect13.Effect.catchAllCause(() => import_effect13.Effect.void));
2435
+ }),
2436
+ import_effect13.Effect.ensuring(
2437
+ import_effect13.Effect.sync(() => {
2438
+ if (state.mode === "exhaust") {
2439
+ state.busy = false;
2440
+ }
2441
+ })
2442
+ )
2443
+ )
2444
+ );
2445
+ if (state.mode === "latest") {
2446
+ state.current = fiber;
2447
+ }
2448
+ });
2449
+ var ensureRegistry = (runtime) => import_effect13.Effect.gen(function* () {
2450
+ const existing = getRegistry(runtime);
2451
+ if (existing) {
2452
+ return {
2453
+ moduleId: runtime.moduleId,
2454
+ instanceId: runtime.instanceId,
2455
+ registry: existing
2456
+ };
2457
+ }
2458
+ const portsReady = yield* import_effect13.Deferred.make();
2459
+ const next = {
2460
+ byActionTag: /* @__PURE__ */ new Map(),
2461
+ entries: [],
2462
+ watcherStarted: false,
2463
+ watcherStartCount: 0,
2464
+ portsResolving: false,
2465
+ portsReady,
2466
+ parallelLimiter: void 0
2467
+ };
2468
+ Object.defineProperty(runtime, WORKFLOW_REGISTRY, {
2469
+ value: next,
2470
+ enumerable: false,
2471
+ configurable: true,
2472
+ writable: false
2473
+ });
2474
+ return { moduleId: runtime.moduleId, instanceId: runtime.instanceId, registry: next };
2475
+ });
2476
+ var registerPrograms = (args) => import_effect13.Effect.gen(function* () {
2477
+ const runtime = yield* args.moduleTag;
2478
+ const { moduleId, instanceId, registry } = yield* ensureRegistry(runtime);
2479
+ if (registry.parallelLimiter === void 0) {
2480
+ yield* ensureLimiterReady(registry, runtime);
2481
+ }
2482
+ const validateNoIoStepsForOnInit = (steps, programId) => {
2483
+ const visit = (step) => {
2484
+ if (step.kind === "call" || step.kind === "delay") {
2485
+ throw makeWorkflowError({
2486
+ code: "WORKFLOW_INVALID_TRIGGER",
2487
+ message: "Lifecycle onInit programs must not include call/delay (initRequired must stay sync-only; use onStart for IO/time).",
2488
+ programId,
2489
+ source: { stepKey: step.key },
2490
+ detail: { kind: step.kind }
2491
+ });
2492
+ }
2493
+ };
2494
+ for (const s of steps) visit(s);
2495
+ };
2496
+ const programHasCall = (steps) => steps.some((s) => s.kind === "call");
2497
+ const insertEntry = (actionTag, entry) => {
2498
+ const prev = registry.byActionTag.get(actionTag);
2499
+ registry.byActionTag.set(actionTag, prev ? [...prev, entry] : [entry]);
2500
+ };
2501
+ const internals = getRuntimeInternals(runtime);
2502
+ for (const program of args.programs) {
2503
+ const def = program.def;
2504
+ const localId = asNonEmptyString3(def.localId);
2505
+ if (!localId) {
2506
+ throw makeWorkflowError({
2507
+ code: "WORKFLOW_INVALID_DEF",
2508
+ message: "Workflow.install: def.localId must be a non-empty string.",
2509
+ detail: { localId: def.localId }
2510
+ });
2511
+ }
2512
+ const programId = `${moduleId}.${localId}`;
2513
+ const compiled = compileWorkflowRuntimeStepsV1({ def });
2514
+ if (def.trigger.kind === "lifecycle" && def.trigger.phase === "onInit") {
2515
+ validateNoIoStepsForOnInit(compiled, programId);
2516
+ }
2517
+ const compiledProgram = {
2518
+ programId,
2519
+ localId,
2520
+ trigger: def.trigger,
2521
+ concurrency: resolveConcurrency(def),
2522
+ priority: resolvePriority(def),
2523
+ compiledSteps: compiled
2524
+ };
2525
+ if (!programHasCall(compiled)) {
2526
+ compiledProgram.steps = compileSteps(compiled, () => {
2527
+ throw makeWorkflowError({
2528
+ code: "WORKFLOW_MISSING_SERVICE",
2529
+ message: "Internal error: unexpected call step while resolving call-less program.",
2530
+ programId,
2531
+ detail: { programId }
2532
+ });
2533
+ });
2534
+ }
2535
+ const state = compiledProgram.concurrency === "latest" ? { mode: "latest", runSeq: 0, current: void 0, currentRunId: void 0 } : compiledProgram.concurrency === "exhaust" ? { mode: "exhaust", runSeq: 0, busy: false } : { mode: "parallel", runSeq: 0 };
2536
+ const entry = { program: compiledProgram, state };
2537
+ registry.entries.push(entry);
2538
+ if (def.trigger.kind === "action") {
2539
+ insertEntry(def.trigger.actionTag, entry);
2540
+ } else {
2541
+ if (def.trigger.phase === "onStart") {
2542
+ internals.lifecycle.registerStart(
2543
+ withRootEnvIfAvailable(
2544
+ import_effect13.Effect.gen(function* () {
2545
+ const middlewareOpt = yield* import_effect13.Effect.serviceOption(EffectOpMiddlewareTag);
2546
+ const middleware = import_effect13.Option.isSome(middlewareOpt) ? middlewareOpt.value : void 0;
2547
+ yield* ensurePortsResolved(registry, runtime).pipe(import_effect13.Effect.orDie);
2548
+ yield* startProgramRun({
2549
+ entry,
2550
+ runtime,
2551
+ registry,
2552
+ trigger: { kind: "lifecycle", phase: "onStart" },
2553
+ payload: void 0,
2554
+ middleware
2555
+ });
2556
+ })
2557
+ ),
2558
+ { name: `workflow:${localId}` }
2559
+ );
2560
+ } else {
2561
+ internals.lifecycle.registerInitRequired(
2562
+ import_effect13.Effect.gen(function* () {
2563
+ const middlewareOpt = yield* import_effect13.Effect.serviceOption(EffectOpMiddlewareTag);
2564
+ const middleware = import_effect13.Option.isSome(middlewareOpt) ? middlewareOpt.value : void 0;
2565
+ yield* startProgramRun({
2566
+ entry,
2567
+ runtime,
2568
+ registry,
2569
+ trigger: { kind: "lifecycle", phase: "onInit" },
2570
+ payload: void 0,
2571
+ middleware
2572
+ });
2573
+ }),
2574
+ { name: `workflow:${localId}` }
2575
+ );
2576
+ }
2577
+ }
2578
+ }
2579
+ void instanceId;
2580
+ });
2581
+ var startWatcherIfNeeded = (args) => import_effect13.Effect.gen(function* () {
2582
+ const runtime = yield* args.moduleTag;
2583
+ const init = yield* ensureRegistry(runtime);
2584
+ const registry = init.registry;
2585
+ if (registry.watcherStarted) {
2586
+ return;
2587
+ }
2588
+ registry.watcherStarted = true;
2589
+ registry.watcherStartCount += 1;
2590
+ const middlewareOpt = yield* import_effect13.Effect.serviceOption(EffectOpMiddlewareTag);
2591
+ const middleware = import_effect13.Option.isSome(middlewareOpt) ? middlewareOpt.value : void 0;
2592
+ const actions$ = runtime.actions$;
2593
+ const portsExit = yield* import_effect13.Effect.exit(ensurePortsResolved(registry, runtime));
2594
+ if (import_effect13.Exit.isFailure(portsExit)) {
2595
+ const { errorSummary, downgrade } = toSerializableErrorSummary(portsExit.cause);
2596
+ const downgradeHint = downgrade ? ` (downgrade=${downgrade})` : "";
2597
+ yield* record({
2598
+ type: "diagnostic",
2599
+ moduleId: runtime.moduleId,
2600
+ instanceId: runtime.instanceId,
2601
+ code: "workflow::ports_resolution_failed",
2602
+ severity: "error",
2603
+ message: `Workflow ports resolution failed before starting watcher.${downgradeHint}`,
2604
+ hint: `${errorSummary.name ? `${errorSummary.name}: ` : ""}${errorSummary.message}`,
2605
+ kind: "workflow_ports_resolution_failed",
2606
+ trigger: {
2607
+ kind: "workflow",
2608
+ name: "portsResolution",
2609
+ details: {
2610
+ entryLabel: args.entryLabel
2611
+ }
2612
+ }
2613
+ });
2614
+ return;
2615
+ }
2616
+ yield* import_effect13.Stream.runForEach(
2617
+ actions$,
2618
+ (action) => import_effect13.Effect.gen(function* () {
2619
+ const actionTag = resolveActionTag(action);
2620
+ if (!actionTag) return;
2621
+ const entries = registry.byActionTag.get(actionTag);
2622
+ if (!entries || entries.length === 0) return;
2623
+ const payload2 = isRecord3(action) ? action.payload : void 0;
2624
+ yield* import_effect13.Effect.forEach(
2625
+ entries,
2626
+ (entry) => startProgramRun({
2627
+ entry,
2628
+ runtime,
2629
+ registry,
2630
+ trigger: { kind: "action", actionTag },
2631
+ payload: payload2,
2632
+ middleware
2633
+ }),
2634
+ { discard: true }
2635
+ );
2636
+ })
2637
+ ).pipe(
2638
+ import_effect13.Effect.catchAllCause((cause) => {
2639
+ const { errorSummary, downgrade } = toSerializableErrorSummary(cause);
2640
+ const downgradeHint = downgrade ? ` (downgrade=${downgrade})` : "";
2641
+ return record({
2642
+ type: "diagnostic",
2643
+ moduleId: runtime.moduleId,
2644
+ instanceId: runtime.instanceId,
2645
+ code: "workflow::watcher_crashed",
2646
+ severity: "error",
2647
+ message: `Workflow watcher crashed.${downgradeHint}`,
2648
+ hint: `${errorSummary.name ? `${errorSummary.name}: ` : ""}${errorSummary.message}`,
2649
+ kind: "workflow_watcher_crashed",
2650
+ trigger: {
2651
+ kind: "workflow",
2652
+ name: "watcher",
2653
+ details: {
2654
+ entryLabel: args.entryLabel
2655
+ }
2656
+ }
2657
+ });
2658
+ })
2659
+ );
2660
+ void args.entryLabel;
2661
+ });
2662
+ var installOne = (args) => {
2663
+ const localId = asNonEmptyString3(args.program.def.localId) ?? "unknown";
2664
+ const plan = {
2665
+ setup: registerPrograms({ moduleTag: args.moduleTag, programs: [args.program], entryLabel: `install:${localId}` }),
2666
+ run: startWatcherIfNeeded({ moduleTag: args.moduleTag, entryLabel: `install:${localId}` })
2667
+ };
2668
+ attachLogicUnitMeta(plan, {
2669
+ id: `workflow:${localId}`,
2670
+ kind: "workflow",
2671
+ name: localId
2672
+ });
2673
+ return plan;
2674
+ };
2675
+
2676
+ // src/Workflow.ts
2677
+ var KernelSourceRefreshPortTagImpl = class extends import_effect14.Context.Tag("logix/kernel/sourceRefresh")() {
2678
+ };
2679
+ var KernelPorts = {
2680
+ sourceRefresh: KernelSourceRefreshPortTagImpl
2681
+ };
2682
+ var forModule = (_module) => {
2683
+ return {
2684
+ onAction: (actionTag) => onAction(actionTag),
2685
+ onStart,
2686
+ onInit,
2687
+ payload,
2688
+ payloadPath,
2689
+ constValue,
2690
+ object,
2691
+ merge,
2692
+ dispatch: (args) => dispatch(args),
2693
+ delay,
2694
+ callById: (args) => callById(args),
2695
+ call: (args) => call(args),
2696
+ fragment: (fragmentId, steps) => fragment(fragmentId, steps),
2697
+ withPolicy: (patch, part) => withPolicy(patch, part),
2698
+ compose: (...parts) => compose(...parts),
2699
+ make: (input) => make(input),
2700
+ fromJSON: (def) => fromJSON(def)
2701
+ };
2702
+ };
2703
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2704
+ var isReadonlyArray = (value) => Array.isArray(value);
2705
+ var asNonEmptyString4 = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
2706
+ var mergePolicy = (base, patch) => {
2707
+ if (!base && !patch) return void 0;
2708
+ return {
2709
+ ...base ?? {},
2710
+ ...patch ?? {}
2711
+ };
2712
+ };
2713
+ var applyCallDefaults = (steps, patch) => {
2714
+ const timeoutMsDefault = patch.timeoutMs;
2715
+ const retryDefault = patch.retry;
2716
+ const visit = (step) => {
2717
+ if (step.kind !== "call") return step;
2718
+ let changed = false;
2719
+ const timeoutMs = step.timeoutMs ?? timeoutMsDefault;
2720
+ if (timeoutMs !== step.timeoutMs) changed = true;
2721
+ const retry = step.retry ?? retryDefault;
2722
+ if (retry !== step.retry) changed = true;
2723
+ const onSuccess = step.onSuccess.map(visit);
2724
+ const onFailure = step.onFailure.map(visit);
2725
+ if (onSuccess !== step.onSuccess) changed = true;
2726
+ if (onFailure !== step.onFailure) changed = true;
2727
+ if (!changed) return step;
2728
+ return {
2729
+ ...step,
2730
+ ...timeoutMs !== void 0 ? { timeoutMs } : null,
2731
+ ...retry !== void 0 ? { retry } : null,
2732
+ onSuccess,
2733
+ onFailure
2734
+ };
2735
+ };
2736
+ return steps.map(visit);
2737
+ };
2738
+ var resolveStepsInput = (input) => {
2739
+ if (Array.isArray(input)) {
2740
+ return { steps: input };
2741
+ }
2742
+ if (isRecord4(input) && Array.isArray(input.steps)) {
2743
+ return input;
2744
+ }
2745
+ throw makeWorkflowError({
2746
+ code: "WORKFLOW_INVALID_DEF",
2747
+ message: 'Workflow.make: "steps" must be an array or a { steps, sources?, policy? } object.',
2748
+ detail: { steps: input }
2749
+ });
2750
+ };
2751
+ var recordSourcesForFragment = (sources, fragmentId, step) => {
2752
+ sources[step.key] = { fragmentId };
2753
+ if (step.kind !== "call") return;
2754
+ for (const inner of step.onSuccess) recordSourcesForFragment(sources, fragmentId, inner);
2755
+ for (const inner of step.onFailure) recordSourcesForFragment(sources, fragmentId, inner);
2756
+ };
2757
+ var onAction = (actionTag) => ({
2758
+ kind: "action",
2759
+ actionTag
2760
+ });
2761
+ var onStart = () => ({
2762
+ kind: "lifecycle",
2763
+ phase: "onStart"
2764
+ });
2765
+ var onInit = () => ({
2766
+ kind: "lifecycle",
2767
+ phase: "onInit"
2768
+ });
2769
+ var payload = () => ({ kind: "payload" });
2770
+ var payloadPath = (pointer) => ({ kind: "payload.path", pointer });
2771
+ var constValue = (value) => ({ kind: "const", value });
2772
+ var object = (fields) => ({ kind: "object", fields });
2773
+ var merge = (items) => ({ kind: "merge", items });
2774
+ var dispatch = (args) => ({
2775
+ kind: "dispatch",
2776
+ key: args.key,
2777
+ actionTag: args.actionTag,
2778
+ ...args.payload ? { payload: args.payload } : null
2779
+ });
2780
+ var delay = (args) => ({
2781
+ kind: "delay",
2782
+ key: args.key,
2783
+ ms: args.ms
2784
+ });
2785
+ var callById = (args) => ({
2786
+ kind: "call",
2787
+ key: args.key,
2788
+ serviceId: args.serviceId,
2789
+ ...args.input ? { input: args.input } : null,
2790
+ ...args.timeoutMs !== void 0 ? { timeoutMs: args.timeoutMs } : null,
2791
+ ...args.retry ? { retry: args.retry } : null,
2792
+ onSuccess: args.onSuccess ?? [],
2793
+ onFailure: args.onFailure ?? []
2794
+ });
2795
+ var call = (args) => {
2796
+ const serviceId = fromTag(args.service);
2797
+ if (!serviceId) {
2798
+ throw makeWorkflowError({
2799
+ code: "WORKFLOW_INVALID_SERVICE_ID",
2800
+ message: "call(service): serviceId derived from tag must be a non-empty string (see 078 ServiceId contract).",
2801
+ detail: { tag: String(args.service) }
2802
+ });
2803
+ }
2804
+ return callById({
2805
+ ...args,
2806
+ serviceId
2807
+ });
2808
+ };
2809
+ var fragment = (fragmentId, steps) => ({
2810
+ fragmentId,
2811
+ steps
2812
+ });
2813
+ var withPolicy = (patch, part) => {
2814
+ let normalized;
2815
+ if (isReadonlyArray(part)) {
2816
+ normalized = { steps: part };
2817
+ } else {
2818
+ const partUnknown = part;
2819
+ if (!isRecord4(partUnknown) || !isReadonlyArray(partUnknown.steps)) {
2820
+ throw makeWorkflowError({
2821
+ code: "WORKFLOW_INVALID_DEF",
2822
+ message: "withPolicy: invalid workflow part (expected steps[] / fragment / composeResult).",
2823
+ detail: { part }
2824
+ });
2825
+ }
2826
+ normalized = {
2827
+ steps: part.steps,
2828
+ ...part.sources ? { sources: part.sources } : null,
2829
+ ...part.policy ? { policy: part.policy } : null
2830
+ };
2831
+ }
2832
+ const steps = applyCallDefaults(normalized.steps, patch);
2833
+ const patchPolicy = (() => {
2834
+ const concurrency = patch.concurrency;
2835
+ const priority = patch.priority;
2836
+ return concurrency !== void 0 || priority !== void 0 ? { concurrency, priority } : void 0;
2837
+ })();
2838
+ const nextPolicy = mergePolicy(patchPolicy, normalized.policy);
2839
+ return {
2840
+ steps,
2841
+ ...normalized.sources ? { sources: normalized.sources } : null,
2842
+ ...nextPolicy ? { policy: nextPolicy } : null
2843
+ };
2844
+ };
2845
+ var compose = (...parts) => {
2846
+ const steps = [];
2847
+ const sources = {};
2848
+ let policy = void 0;
2849
+ const ownersByKey = /* @__PURE__ */ new Map();
2850
+ const recordOwner = (stepKey, fragmentId) => {
2851
+ const list = ownersByKey.get(stepKey) ?? [];
2852
+ list.push({ stepKey, ...fragmentId ? { fragmentId } : null });
2853
+ ownersByKey.set(stepKey, list);
2854
+ };
2855
+ const recordOwners = (step, resolveFragmentId) => {
2856
+ recordOwner(step.key, resolveFragmentId(step.key));
2857
+ if (step.kind !== "call") return;
2858
+ for (const inner of step.onSuccess) recordOwners(inner, resolveFragmentId);
2859
+ for (const inner of step.onFailure) recordOwners(inner, resolveFragmentId);
2860
+ };
2861
+ for (const part of parts) {
2862
+ if (isReadonlyArray(part)) {
2863
+ steps.push(...part);
2864
+ for (const step of part) recordOwners(step, () => void 0);
2865
+ continue;
2866
+ }
2867
+ const partSteps = part.steps;
2868
+ steps.push(...partSteps);
2869
+ const partSources = part.sources;
2870
+ if (partSources && typeof partSources === "object") {
2871
+ for (const k of Object.keys(partSources).sort()) {
2872
+ sources[k] = { ...partSources[k] };
2873
+ }
2874
+ }
2875
+ const fragmentId = "fragmentId" in part ? part.fragmentId : void 0;
2876
+ if (typeof fragmentId === "string" && fragmentId.length > 0) {
2877
+ for (const step of partSteps) {
2878
+ recordSourcesForFragment(sources, fragmentId, step);
2879
+ }
2880
+ }
2881
+ const resolveFragmentIdForPart = (stepKey) => {
2882
+ if (typeof fragmentId === "string" && fragmentId.length > 0) return fragmentId;
2883
+ const fromSources = partSources?.[stepKey]?.fragmentId;
2884
+ return typeof fromSources === "string" && fromSources.length > 0 ? fromSources : void 0;
2885
+ };
2886
+ for (const step of partSteps) recordOwners(step, resolveFragmentIdForPart);
2887
+ policy = mergePolicy(policy, part.policy);
2888
+ }
2889
+ const finalSources = Object.keys(sources).length > 0 ? sources : void 0;
2890
+ const duplicateKeys = Array.from(ownersByKey.entries()).filter(([, owners]) => owners.length > 1).map(([k]) => k).sort();
2891
+ if (duplicateKeys.length > 0) {
2892
+ const k = duplicateKeys[0];
2893
+ throw makeWorkflowError({
2894
+ code: "WORKFLOW_DUPLICATE_STEP_KEY",
2895
+ message: `Duplicate stepKey "${k}" detected during composition.`,
2896
+ source: { stepKey: k },
2897
+ detail: { duplicateKey: k, owners: ownersByKey.get(k) ?? [] }
2898
+ });
2899
+ }
2900
+ return {
2901
+ steps,
2902
+ ...finalSources ? { sources: finalSources } : null,
2903
+ ...policy ? { policy } : null
2904
+ };
2905
+ };
2906
+ var make = (input) => {
2907
+ const localId = asNonEmptyString4(input.localId);
2908
+ if (!localId) {
2909
+ throw makeWorkflowError({
2910
+ code: "WORKFLOW_INVALID_DEF",
2911
+ message: "Workflow.make: localId must be a non-empty string.",
2912
+ detail: { localId: input.localId }
2913
+ });
2914
+ }
2915
+ const stepsInput = resolveStepsInput(input.steps);
2916
+ const merged = mergePolicy(input.policy, stepsInput.policy);
2917
+ const def = normalizeWorkflowDefV1({
2918
+ astVersion: 1,
2919
+ localId,
2920
+ trigger: input.trigger,
2921
+ ...merged ? { policy: merged } : null,
2922
+ steps: stepsInput.steps,
2923
+ ...stepsInput.sources ? { sources: stepsInput.sources } : null,
2924
+ ...input.meta ? { meta: input.meta } : null
2925
+ });
2926
+ const staticIrCache = /* @__PURE__ */ new Map();
2927
+ return {
2928
+ _tag: "Workflow",
2929
+ def,
2930
+ toJSON: () => def,
2931
+ validate: () => validateWorkflowDefV1(def),
2932
+ exportStaticIr: (moduleId) => {
2933
+ const cached = staticIrCache.get(moduleId);
2934
+ if (cached) return cached;
2935
+ const ir = compileWorkflowStaticIrV1({ moduleId, def });
2936
+ staticIrCache.set(moduleId, ir);
2937
+ return ir;
2938
+ },
2939
+ install: (moduleTag) => installOne({
2940
+ moduleTag,
2941
+ program: { _tag: "Workflow", def }
2942
+ })
2943
+ };
2944
+ };
2945
+ var fromJSON = (def) => make({
2946
+ localId: def.localId,
2947
+ trigger: def.trigger,
2948
+ ...def.policy ? { policy: def.policy } : null,
2949
+ steps: {
2950
+ steps: def.steps,
2951
+ ...def.sources ? { sources: def.sources } : null
2952
+ },
2953
+ ...def.meta ? { meta: def.meta } : null
2954
+ });
2955
+ // Annotate the CommonJS export names for ESM import in node:
2956
+ 0 && (module.exports = {
2957
+ KernelPorts,
2958
+ call,
2959
+ callById,
2960
+ compose,
2961
+ constValue,
2962
+ delay,
2963
+ dispatch,
2964
+ forModule,
2965
+ fragment,
2966
+ fromJSON,
2967
+ make,
2968
+ merge,
2969
+ object,
2970
+ onAction,
2971
+ onInit,
2972
+ onStart,
2973
+ payload,
2974
+ payloadPath,
2975
+ withPolicy
2976
+ });
2977
+ //# sourceMappingURL=Workflow.cjs.map