@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
@@ -162,11 +162,12 @@ var toJsonValueInternal = (input, options, stats, seen, depth) => {
162
162
  stats.nonSerializable += 1;
163
163
  return truncateString(String(input), options.maxStringLength, stats);
164
164
  }
165
- const entries = Object.entries(input);
166
- const limit = Math.min(entries.length, options.maxObjectKeys);
165
+ const keys = Object.keys(input).sort();
166
+ const limit = Math.min(keys.length, options.maxObjectKeys);
167
167
  const out = {};
168
168
  for (let i = 0; i < limit; i++) {
169
- const [rawKey, rawValue] = entries[i];
169
+ const rawKey = keys[i];
170
+ const rawValue = input[rawKey];
170
171
  const key = truncateString(rawKey, options.maxStringLength, stats);
171
172
  if (rawValue === void 0) {
172
173
  stats.dropped += 1;
@@ -174,9 +175,9 @@ var toJsonValueInternal = (input, options, stats, seen, depth) => {
174
175
  }
175
176
  out[key] = toJsonValueInternal(rawValue, options, stats, seen, depth + 1);
176
177
  }
177
- if (entries.length > limit) {
178
+ if (keys.length > limit) {
178
179
  stats.oversized += 1;
179
- out.__truncatedKeys = entries.length - limit;
180
+ out.__truncatedKeys = keys.length - limit;
180
181
  }
181
182
  return out;
182
183
  };
@@ -304,7 +305,7 @@ var importEvidencePackage = (input) => {
304
305
  };
305
306
 
306
307
  // src/internal/observability/trialRun.ts
307
- var import_effect33 = require("effect");
308
+ var import_effect36 = require("effect");
308
309
 
309
310
  // src/internal/observability/evidenceCollector.ts
310
311
  var import_effect5 = require("effect");
@@ -396,7 +397,7 @@ var makeEvidenceSink = (session) => {
396
397
  };
397
398
  var runSessionLayer = (session) => import_effect.Layer.succeed(RunSessionTag, session ?? makeRunSession());
398
399
 
399
- // src/internal/runtime/core/DebugSink.ts
400
+ // src/internal/runtime/core/DebugSink.record.ts
400
401
  var import_effect4 = require("effect");
401
402
 
402
403
  // src/internal/runtime/core/errorSummary.ts
@@ -500,7 +501,7 @@ var runWithMiddleware = (op, stack) => {
500
501
  });
501
502
  };
502
503
 
503
- // src/internal/runtime/core/DebugSink.ts
504
+ // src/internal/runtime/core/DebugSink.record.ts
504
505
  var currentDebugSinks = import_effect4.FiberRef.unsafeMake([]);
505
506
  var currentRuntimeLabel = import_effect4.FiberRef.unsafeMake(void 0);
506
507
  var currentTxnId = import_effect4.FiberRef.unsafeMake(void 0);
@@ -1056,10 +1057,83 @@ var toRuntimeDebugEventRef = (event, options) => {
1056
1057
  meta: metaProjection.value
1057
1058
  });
1058
1059
  }
1060
+ case "warn:priority-inversion": {
1061
+ const e = event;
1062
+ const metaInput = isLightLike ? {
1063
+ tickSeq: e.tickSeq,
1064
+ reason: e.reason,
1065
+ selectorId: e.selectorId
1066
+ } : {
1067
+ tickSeq: e.tickSeq,
1068
+ reason: e.reason,
1069
+ selectorId: e.selectorId
1070
+ };
1071
+ const metaProjection = projectJsonValue(metaInput);
1072
+ options?.onMetaProjection?.({
1073
+ stats: metaProjection.stats,
1074
+ downgrade: metaProjection.downgrade
1075
+ });
1076
+ downgrade = mergeDowngrade2(downgrade, metaProjection.downgrade);
1077
+ return withDowngrade({
1078
+ ...base,
1079
+ kind: "diagnostic",
1080
+ label: e.type,
1081
+ meta: metaProjection.value
1082
+ });
1083
+ }
1084
+ case "warn:microtask-starvation": {
1085
+ const e = event;
1086
+ const metaInput = isLightLike ? {
1087
+ tickSeq: e.tickSeq,
1088
+ microtaskChainDepth: e.microtaskChainDepth
1089
+ } : {
1090
+ tickSeq: e.tickSeq,
1091
+ microtaskChainDepth: e.microtaskChainDepth
1092
+ };
1093
+ const metaProjection = projectJsonValue(metaInput);
1094
+ options?.onMetaProjection?.({
1095
+ stats: metaProjection.stats,
1096
+ downgrade: metaProjection.downgrade
1097
+ });
1098
+ downgrade = mergeDowngrade2(downgrade, metaProjection.downgrade);
1099
+ return withDowngrade({
1100
+ ...base,
1101
+ kind: "diagnostic",
1102
+ label: e.type,
1103
+ meta: metaProjection.value
1104
+ });
1105
+ }
1059
1106
  default: {
1060
1107
  if (typeof event.type !== "string" || !event.type.startsWith("trace:")) {
1061
1108
  return void 0;
1062
1109
  }
1110
+ if (event.type === "trace:tick") {
1111
+ const data = event.data;
1112
+ const metaInput = isLightLike ? {
1113
+ tickSeq: data?.tickSeq,
1114
+ phase: data?.phase,
1115
+ schedule: data?.schedule,
1116
+ triggerSummary: data?.triggerSummary,
1117
+ anchors: data?.anchors,
1118
+ budget: data?.budget,
1119
+ backlog: data?.backlog,
1120
+ result: data?.result
1121
+ } : {
1122
+ data
1123
+ };
1124
+ const metaProjection2 = projectJsonValue(metaInput);
1125
+ options?.onMetaProjection?.({
1126
+ stats: metaProjection2.stats,
1127
+ downgrade: metaProjection2.downgrade
1128
+ });
1129
+ downgrade = mergeDowngrade2(downgrade, metaProjection2.downgrade);
1130
+ return withDowngrade({
1131
+ ...base,
1132
+ kind: "devtools",
1133
+ label: event.type,
1134
+ meta: metaProjection2.value
1135
+ });
1136
+ }
1063
1137
  if (event.type === "trace:txn-lane") {
1064
1138
  const data = event.data;
1065
1139
  const evidence = data?.evidence ?? data;
@@ -1529,11 +1603,1127 @@ var makeEvidenceCollector = (session) => {
1529
1603
  };
1530
1604
  };
1531
1605
 
1532
- // src/internal/runtime/core/RuntimeKernel.ts
1533
- var import_effect7 = require("effect");
1534
-
1606
+ // src/internal/runtime/core/RuntimeKernel.ts
1607
+ var import_effect11 = require("effect");
1608
+
1609
+ // src/internal/runtime/core/env.ts
1610
+ var import_effect10 = require("effect");
1611
+
1612
+ // src/internal/runtime/core/HostScheduler.ts
1613
+ var noopCancel = () => {
1614
+ };
1615
+ var safeNowMs = () => {
1616
+ const perf = globalThis.performance;
1617
+ if (perf && typeof perf.now === "function") {
1618
+ try {
1619
+ const v = perf.now();
1620
+ if (typeof v === "number" && Number.isFinite(v)) return v;
1621
+ } catch {
1622
+ }
1623
+ }
1624
+ return Date.now();
1625
+ };
1626
+ var safeQueueMicrotask = (cb) => {
1627
+ const qm = globalThis.queueMicrotask;
1628
+ if (typeof qm === "function") {
1629
+ try {
1630
+ qm(cb);
1631
+ return;
1632
+ } catch {
1633
+ }
1634
+ }
1635
+ try {
1636
+ Promise.resolve().then(cb);
1637
+ } catch {
1638
+ setTimeout(cb, 0);
1639
+ }
1640
+ };
1641
+ var safeSetTimeout = (ms, cb) => {
1642
+ const id = setTimeout(cb, ms);
1643
+ return () => {
1644
+ try {
1645
+ clearTimeout(id);
1646
+ } catch {
1647
+ }
1648
+ };
1649
+ };
1650
+ var makeMessageChannelMacrotask = () => {
1651
+ const MC = globalThis.MessageChannel;
1652
+ if (typeof MC !== "function") return void 0;
1653
+ let channel;
1654
+ try {
1655
+ channel = new MC();
1656
+ } catch {
1657
+ return void 0;
1658
+ }
1659
+ const queue = [];
1660
+ let scheduled = false;
1661
+ const flush = () => {
1662
+ scheduled = false;
1663
+ const tasks = queue.splice(0, queue.length);
1664
+ for (const t of tasks) {
1665
+ if (t.canceled) continue;
1666
+ try {
1667
+ t.cb();
1668
+ } catch {
1669
+ }
1670
+ }
1671
+ };
1672
+ try {
1673
+ channel.port1.onmessage = flush;
1674
+ } catch {
1675
+ return void 0;
1676
+ }
1677
+ const schedule = (cb) => {
1678
+ const task = { canceled: false, cb };
1679
+ queue.push(task);
1680
+ if (!scheduled) {
1681
+ scheduled = true;
1682
+ try {
1683
+ channel.port2.postMessage(void 0);
1684
+ } catch {
1685
+ scheduled = false;
1686
+ return safeSetTimeout(0, cb);
1687
+ }
1688
+ }
1689
+ return () => {
1690
+ task.canceled = true;
1691
+ };
1692
+ };
1693
+ return schedule;
1694
+ };
1695
+ var makeSetImmediateMacrotask = () => {
1696
+ const si = globalThis.setImmediate;
1697
+ const ci = globalThis.clearImmediate;
1698
+ if (typeof si !== "function") return void 0;
1699
+ return (cb) => {
1700
+ let id;
1701
+ try {
1702
+ id = si(cb);
1703
+ } catch {
1704
+ return safeSetTimeout(0, cb);
1705
+ }
1706
+ return () => {
1707
+ if (typeof ci !== "function") return;
1708
+ try {
1709
+ ci(id);
1710
+ } catch {
1711
+ }
1712
+ };
1713
+ };
1714
+ };
1715
+ var makeRaf = () => {
1716
+ const raf = globalThis.requestAnimationFrame;
1717
+ const cancel = globalThis.cancelAnimationFrame;
1718
+ if (typeof raf !== "function") return void 0;
1719
+ return (cb) => {
1720
+ let id;
1721
+ try {
1722
+ id = raf(cb);
1723
+ } catch {
1724
+ return noopCancel;
1725
+ }
1726
+ return () => {
1727
+ if (typeof cancel !== "function") return;
1728
+ try {
1729
+ cancel(id);
1730
+ } catch {
1731
+ }
1732
+ };
1733
+ };
1734
+ };
1735
+ var makeDefaultHostScheduler = () => {
1736
+ const macrotask = makeSetImmediateMacrotask() ?? makeMessageChannelMacrotask() ?? ((cb) => safeSetTimeout(0, cb));
1737
+ const raf = makeRaf();
1738
+ return {
1739
+ nowMs: safeNowMs,
1740
+ scheduleMicrotask: safeQueueMicrotask,
1741
+ scheduleMacrotask: macrotask,
1742
+ scheduleAnimationFrame: (cb) => raf?.(cb) ?? macrotask(cb),
1743
+ scheduleTimeout: safeSetTimeout
1744
+ };
1745
+ };
1746
+ var globalHostScheduler;
1747
+ var getGlobalHostScheduler = () => {
1748
+ globalHostScheduler ?? (globalHostScheduler = makeDefaultHostScheduler());
1749
+ return globalHostScheduler;
1750
+ };
1751
+
1752
+ // src/internal/runtime/core/RuntimeStore.ts
1753
+ var makeReadQueryTopicKey = (moduleInstanceKey, selectorId) => `${moduleInstanceKey}::rq:${selectorId}`;
1754
+ var parseTopicKey = (topicKey) => {
1755
+ const idx = topicKey.indexOf("::");
1756
+ if (idx <= 0) return void 0;
1757
+ const moduleId = topicKey.slice(0, idx);
1758
+ const rest = topicKey.slice(idx + 2);
1759
+ if (rest.length === 0) return void 0;
1760
+ const idx2 = rest.indexOf("::");
1761
+ if (idx2 < 0) {
1762
+ return { kind: "module", moduleInstanceKey: `${moduleId}::${rest}` };
1763
+ }
1764
+ const instanceId = rest.slice(0, idx2);
1765
+ const suffix = rest.slice(idx2 + 2);
1766
+ if (suffix.startsWith("rq:")) {
1767
+ const selectorId = suffix.slice("rq:".length);
1768
+ if (selectorId.length === 0) return void 0;
1769
+ return {
1770
+ kind: "readQuery",
1771
+ moduleInstanceKey: `${moduleId}::${instanceId}`,
1772
+ selectorId
1773
+ };
1774
+ }
1775
+ return { kind: "module", moduleInstanceKey: `${moduleId}::${instanceId}` };
1776
+ };
1777
+ var makeRuntimeStore = () => {
1778
+ let tickSeq = 0;
1779
+ const moduleStates = /* @__PURE__ */ new Map();
1780
+ const topicVersions = /* @__PURE__ */ new Map();
1781
+ const topicPriorities = /* @__PURE__ */ new Map();
1782
+ const listenersByTopic = /* @__PURE__ */ new Map();
1783
+ const subscriberCountByModule = /* @__PURE__ */ new Map();
1784
+ const getTopicVersion = (topicKey) => topicVersions.get(topicKey) ?? 0;
1785
+ const getTopicPriority = (topicKey) => topicPriorities.get(topicKey) ?? "normal";
1786
+ const commitTopicBump = (topicKey, priority) => {
1787
+ const prev = topicVersions.get(topicKey) ?? 0;
1788
+ topicVersions.set(topicKey, prev + 1);
1789
+ topicPriorities.set(topicKey, priority);
1790
+ };
1791
+ const subscribeTopic = (topicKey, listener) => {
1792
+ const info = parseTopicKey(topicKey);
1793
+ const existing = listenersByTopic.get(topicKey);
1794
+ const set = existing ?? /* @__PURE__ */ new Set();
1795
+ const alreadyHas = set.has(listener);
1796
+ if (!alreadyHas) {
1797
+ set.add(listener);
1798
+ }
1799
+ if (!existing) {
1800
+ listenersByTopic.set(topicKey, set);
1801
+ }
1802
+ if (!alreadyHas && info) {
1803
+ const prev = subscriberCountByModule.get(info.moduleInstanceKey) ?? 0;
1804
+ subscriberCountByModule.set(info.moduleInstanceKey, prev + 1);
1805
+ }
1806
+ return () => {
1807
+ const current = listenersByTopic.get(topicKey);
1808
+ if (!current) return;
1809
+ const deleted = current.delete(listener);
1810
+ if (deleted && info) {
1811
+ const prev = subscriberCountByModule.get(info.moduleInstanceKey) ?? 0;
1812
+ const next = prev - 1;
1813
+ if (next <= 0) {
1814
+ subscriberCountByModule.delete(info.moduleInstanceKey);
1815
+ } else {
1816
+ subscriberCountByModule.set(info.moduleInstanceKey, next);
1817
+ }
1818
+ }
1819
+ if (current.size === 0) {
1820
+ listenersByTopic.delete(topicKey);
1821
+ }
1822
+ };
1823
+ };
1824
+ const getTopicSubscriberCount = (topicKey) => listenersByTopic.get(topicKey)?.size ?? 0;
1825
+ const getModuleSubscriberCount = (moduleInstanceKey) => subscriberCountByModule.get(moduleInstanceKey) ?? 0;
1826
+ const registerModuleInstance = (args) => {
1827
+ moduleStates.set(args.moduleInstanceKey, args.initialState);
1828
+ if (!topicVersions.has(args.moduleInstanceKey)) {
1829
+ topicVersions.set(args.moduleInstanceKey, 0);
1830
+ topicPriorities.set(args.moduleInstanceKey, "normal");
1831
+ }
1832
+ };
1833
+ const unregisterModuleInstance = (moduleInstanceKey) => {
1834
+ moduleStates.delete(moduleInstanceKey);
1835
+ };
1836
+ const commitTick = (args) => {
1837
+ tickSeq = args.tickSeq;
1838
+ for (const [key, commit] of args.accepted.modules) {
1839
+ moduleStates.set(key, commit.state);
1840
+ }
1841
+ const changedTopics = /* @__PURE__ */ new Map();
1842
+ for (const [topicKey, priority] of args.accepted.dirtyTopics) {
1843
+ commitTopicBump(topicKey, priority);
1844
+ const listeners = Array.from(listenersByTopic.get(topicKey) ?? []);
1845
+ if (listeners.length > 0) {
1846
+ changedTopics.set(topicKey, { priority, listeners });
1847
+ }
1848
+ }
1849
+ return { changedTopics };
1850
+ };
1851
+ const getModuleState = (moduleInstanceKey) => moduleStates.get(moduleInstanceKey);
1852
+ const dispose = () => {
1853
+ moduleStates.clear();
1854
+ topicVersions.clear();
1855
+ topicPriorities.clear();
1856
+ listenersByTopic.clear();
1857
+ subscriberCountByModule.clear();
1858
+ };
1859
+ return {
1860
+ getTickSeq: () => tickSeq,
1861
+ getModuleState,
1862
+ getTopicVersion,
1863
+ getTopicPriority,
1864
+ subscribeTopic,
1865
+ getTopicSubscriberCount,
1866
+ getModuleSubscriberCount,
1867
+ registerModuleInstance,
1868
+ unregisterModuleInstance,
1869
+ commitTick,
1870
+ dispose
1871
+ };
1872
+ };
1873
+
1874
+ // src/internal/runtime/core/TickScheduler.ts
1875
+ var import_effect8 = require("effect");
1876
+
1877
+ // src/internal/runtime/core/DevtoolsHub.ts
1878
+ var import_effect6 = require("effect");
1879
+ var lastRunTs = 0;
1880
+ var lastRunTsSeq = 0;
1881
+ var nextRunId = () => {
1882
+ const ts = Date.now();
1883
+ if (ts === lastRunTs) {
1884
+ lastRunTsSeq += 1;
1885
+ } else {
1886
+ lastRunTs = ts;
1887
+ lastRunTsSeq = 0;
1888
+ }
1889
+ return lastRunTsSeq === 0 ? `run-${ts}` : `run-${ts}.${lastRunTsSeq}`;
1890
+ };
1891
+ var currentRunId = nextRunId();
1892
+ var devtoolsEnabled = false;
1893
+ var isDevtoolsEnabled = () => devtoolsEnabled;
1894
+
1895
+ // src/internal/runtime/core/JobQueue.ts
1896
+ var maxPriority = (a, b) => a === "normal" || b === "normal" ? "normal" : "low";
1897
+ var makeJobQueue = () => {
1898
+ let pendingModules = /* @__PURE__ */ new Map();
1899
+ let pendingDirtyTopics = /* @__PURE__ */ new Map();
1900
+ const hasPending = () => pendingModules.size > 0 || pendingDirtyTopics.size > 0;
1901
+ const enqueueModuleCommit = (commit) => {
1902
+ const prev = pendingModules.get(commit.moduleInstanceKey);
1903
+ if (!prev) {
1904
+ pendingModules.set(commit.moduleInstanceKey, commit);
1905
+ return false;
1906
+ }
1907
+ pendingModules.set(commit.moduleInstanceKey, {
1908
+ ...commit,
1909
+ meta: {
1910
+ ...commit.meta,
1911
+ priority: maxPriority(prev.meta.priority, commit.meta.priority)
1912
+ }
1913
+ });
1914
+ return true;
1915
+ };
1916
+ const markTopicDirty = (topicKey, priority) => {
1917
+ const prev = pendingDirtyTopics.get(topicKey);
1918
+ pendingDirtyTopics.set(topicKey, prev ? maxPriority(prev, priority) : priority);
1919
+ return prev != null;
1920
+ };
1921
+ const drain = () => {
1922
+ if (!hasPending()) return void 0;
1923
+ const drained = {
1924
+ modules: pendingModules,
1925
+ dirtyTopics: pendingDirtyTopics
1926
+ };
1927
+ pendingModules = /* @__PURE__ */ new Map();
1928
+ pendingDirtyTopics = /* @__PURE__ */ new Map();
1929
+ return drained;
1930
+ };
1931
+ const requeue = (drain2) => {
1932
+ for (const [, commit] of drain2.modules) {
1933
+ enqueueModuleCommit(commit);
1934
+ }
1935
+ for (const [k, p] of drain2.dirtyTopics) {
1936
+ markTopicDirty(k, p);
1937
+ }
1938
+ };
1939
+ return {
1940
+ hasPending,
1941
+ enqueueModuleCommit,
1942
+ markTopicDirty,
1943
+ drain,
1944
+ requeue
1945
+ };
1946
+ };
1947
+
1948
+ // src/internal/runtime/core/TaskRunner.ts
1949
+ var import_effect7 = require("effect");
1950
+ var inSyncTransactionFiber = import_effect7.FiberRef.unsafeMake(false);
1951
+ var forceSourceRefresh = import_effect7.FiberRef.unsafeMake(false);
1952
+ var resolve = (eff, payload) => typeof eff === "function" ? eff(payload) : eff;
1953
+ var defaultOrigins = (triggerName) => ({
1954
+ pending: {
1955
+ kind: "task:pending",
1956
+ name: triggerName
1957
+ },
1958
+ success: {
1959
+ kind: "service-callback",
1960
+ name: "task:success"
1961
+ },
1962
+ failure: {
1963
+ kind: "service-callback",
1964
+ name: "task:failure"
1965
+ }
1966
+ });
1967
+ var shouldNoopInSyncTransactionFiber = (options) => import_effect7.Effect.gen(function* () {
1968
+ const inTxn = yield* import_effect7.FiberRef.get(inSyncTransactionFiber);
1969
+ if (!inTxn) {
1970
+ return false;
1971
+ }
1972
+ if (isDevEnv()) {
1973
+ yield* record({
1974
+ type: "diagnostic",
1975
+ moduleId: options.moduleId,
1976
+ instanceId: options.instanceId,
1977
+ code: options.code,
1978
+ severity: options.severity,
1979
+ message: options.message,
1980
+ hint: options.hint,
1981
+ actionTag: options.actionTag,
1982
+ kind: options.kind
1983
+ });
1984
+ }
1985
+ return true;
1986
+ });
1987
+ var resolveConcurrencyLimit = (runtime) => runtime.resolveConcurrencyPolicy ? runtime.resolveConcurrencyPolicy().pipe(import_effect7.Effect.map((p) => p.concurrencyLimit)) : import_effect7.Effect.succeed(16);
1988
+ var runTaskLifecycle = (payload, runtime, config, getCanWriteBack) => import_effect7.Effect.gen(function* () {
1989
+ const noop = yield* shouldNoopInSyncTransactionFiber({
1990
+ moduleId: runtime.moduleId,
1991
+ instanceId: runtime.instanceId,
1992
+ code: "logic::invalid_usage",
1993
+ severity: "error",
1994
+ message: "run*Task is not allowed inside a synchronous StateTransaction body (it may deadlock the txnQueue).",
1995
+ hint: "Call run*Task from the run section of a watcher (e.g. $.onAction/$.onState/$.on); do not call it directly inside a reducer / trait.run / synchronous transaction body. For long-lived flows, use a multi-entry pattern (pending \u2192 IO \u2192 writeback).",
1996
+ kind: "run_task_in_transaction"
1997
+ });
1998
+ if (noop) {
1999
+ return;
2000
+ }
2001
+ const defaults = defaultOrigins(config.triggerName);
2002
+ const origins = {
2003
+ pending: config.origin?.pending ?? defaults.pending,
2004
+ success: config.origin?.success ?? defaults.success,
2005
+ failure: config.origin?.failure ?? defaults.failure
2006
+ };
2007
+ const pending = config.pending;
2008
+ if (pending) {
2009
+ yield* import_effect7.Effect.uninterruptible(
2010
+ runtime.runWithStateTransaction(origins.pending, () => import_effect7.Effect.asVoid(resolve(pending, payload)))
2011
+ );
2012
+ }
2013
+ const io = resolve(config.effect, payload);
2014
+ const exit = yield* import_effect7.Effect.exit(io);
2015
+ if (getCanWriteBack) {
2016
+ const ok = yield* getCanWriteBack;
2017
+ if (!ok) {
2018
+ return;
2019
+ }
2020
+ }
2021
+ if (exit._tag === "Success") {
2022
+ const success = config.success;
2023
+ if (success) {
2024
+ yield* runtime.runWithStateTransaction(origins.success, () => import_effect7.Effect.asVoid(success(exit.value, payload)));
2025
+ }
2026
+ return;
2027
+ }
2028
+ const cause = exit.cause;
2029
+ if (import_effect7.Cause.isInterrupted(cause)) {
2030
+ return;
2031
+ }
2032
+ const failure = config.failure;
2033
+ if (failure) {
2034
+ yield* runtime.runWithStateTransaction(origins.failure, () => import_effect7.Effect.asVoid(failure(cause, payload)));
2035
+ }
2036
+ }).pipe(
2037
+ // Watchers must not crash as a whole due to a single task failure: swallow errors, but keep them diagnosable.
2038
+ import_effect7.Effect.catchAllCause(
2039
+ (cause) => record({
2040
+ type: "diagnostic",
2041
+ moduleId: runtime.moduleId,
2042
+ instanceId: runtime.instanceId,
2043
+ code: "task_runner::unhandled_failure",
2044
+ severity: "error",
2045
+ message: "TaskRunner encountered an unhandled failure (pending/IO/writeback).",
2046
+ hint: "Add a failure writeback for this task or handle errors explicitly upstream; avoid fire-and-forget swallowing errors.",
2047
+ actionTag: config.triggerName,
2048
+ kind: "task_runner_unhandled_failure",
2049
+ trigger: {
2050
+ kind: "task",
2051
+ name: config.triggerName
2052
+ }
2053
+ }).pipe(import_effect7.Effect.zipRight(import_effect7.Effect.logError("TaskRunner error", cause)))
2054
+ )
2055
+ );
2056
+ var makeTaskRunner = (stream, mode, runtime, config) => {
2057
+ if (mode === "latest") {
2058
+ return import_effect7.Effect.gen(function* () {
2059
+ const taskIdRef = yield* import_effect7.Ref.make(0);
2060
+ const currentFiberRef = yield* import_effect7.Ref.make(void 0);
2061
+ const start = (payload) => import_effect7.Effect.gen(function* () {
2062
+ const taskId = yield* import_effect7.Ref.updateAndGet(taskIdRef, (n) => n + 1);
2063
+ const prev = yield* import_effect7.Ref.get(currentFiberRef);
2064
+ if (prev) {
2065
+ yield* import_effect7.Fiber.interruptFork(prev);
2066
+ }
2067
+ const canWriteBack = import_effect7.Ref.get(taskIdRef).pipe(import_effect7.Effect.map((current) => current === taskId));
2068
+ const fiber = yield* import_effect7.Effect.fork(
2069
+ runTaskLifecycle(payload, runtime, config, canWriteBack)
2070
+ );
2071
+ yield* import_effect7.Ref.set(currentFiberRef, fiber);
2072
+ });
2073
+ return yield* import_effect7.Stream.runForEach(stream, start);
2074
+ });
2075
+ }
2076
+ if (mode === "exhaust") {
2077
+ return import_effect7.Effect.gen(function* () {
2078
+ const concurrency = yield* resolveConcurrencyLimit(runtime);
2079
+ const busyRef = yield* import_effect7.Ref.make(false);
2080
+ const mapper = (payload) => import_effect7.Effect.gen(function* () {
2081
+ const acquired = yield* import_effect7.Ref.modify(
2082
+ busyRef,
2083
+ (busy) => busy ? [false, busy] : [true, true]
2084
+ );
2085
+ if (!acquired) {
2086
+ return;
2087
+ }
2088
+ try {
2089
+ yield* runTaskLifecycle(payload, runtime, config);
2090
+ } finally {
2091
+ yield* import_effect7.Ref.set(busyRef, false);
2092
+ }
2093
+ });
2094
+ return yield* import_effect7.Stream.runDrain(stream.pipe(import_effect7.Stream.mapEffect(mapper, { concurrency })));
2095
+ });
2096
+ }
2097
+ if (mode === "parallel") {
2098
+ return import_effect7.Effect.gen(function* () {
2099
+ const concurrency = yield* resolveConcurrencyLimit(runtime);
2100
+ return yield* import_effect7.Stream.runDrain(
2101
+ stream.pipe(
2102
+ import_effect7.Stream.mapEffect((payload) => runTaskLifecycle(payload, runtime, config), {
2103
+ concurrency
2104
+ })
2105
+ )
2106
+ );
2107
+ });
2108
+ }
2109
+ return import_effect7.Stream.runForEach(
2110
+ stream,
2111
+ (payload) => runTaskLifecycle(payload, runtime, config)
2112
+ );
2113
+ };
2114
+
2115
+ // src/internal/runtime/core/TickScheduler.ts
2116
+ var batchDepth = 0;
2117
+ var batchWaiters = /* @__PURE__ */ new Set();
2118
+ var waitForBatchEndIfNeeded = () => batchDepth === 0 ? import_effect8.Effect.void : import_effect8.Effect.async((resume, signal) => {
2119
+ let done = false;
2120
+ const cleanup = () => {
2121
+ if (done) return;
2122
+ done = true;
2123
+ batchWaiters.delete(waiter);
2124
+ try {
2125
+ signal.removeEventListener("abort", onAbort);
2126
+ } catch {
2127
+ }
2128
+ };
2129
+ const onAbort = () => {
2130
+ cleanup();
2131
+ };
2132
+ const waiter = {
2133
+ resolve: () => {
2134
+ cleanup();
2135
+ resume(import_effect8.Effect.void);
2136
+ }
2137
+ };
2138
+ batchWaiters.add(waiter);
2139
+ try {
2140
+ signal.addEventListener("abort", onAbort, { once: true });
2141
+ } catch {
2142
+ }
2143
+ });
2144
+ var clampSampleRate = (sampleRate) => {
2145
+ if (typeof sampleRate !== "number" || !Number.isFinite(sampleRate)) return 0;
2146
+ if (sampleRate <= 0) return 0;
2147
+ if (sampleRate >= 1) return 1;
2148
+ return sampleRate;
2149
+ };
2150
+ var shouldSampleTick = (tickSeq, sampleRate) => {
2151
+ if (sampleRate <= 0) return false;
2152
+ if (sampleRate >= 1) return true;
2153
+ const x = tickSeq >>> 0;
2154
+ const h = Math.imul(x ^ 2654435769, 2246822507) >>> 0;
2155
+ return h / 4294967295 < sampleRate;
2156
+ };
2157
+ var toTriggerKind = (originKind) => {
2158
+ if (originKind === "action") return "dispatch";
2159
+ if (originKind === "trait-external-store") return "externalStore";
2160
+ if (originKind?.includes("timer")) return "timer";
2161
+ return "unknown";
2162
+ };
2163
+ var toLane = (priority) => priority === "low" ? "nonUrgent" : "urgent";
2164
+ var maxPriority2 = (a, b) => a === "normal" || b === "normal" ? "normal" : "low";
2165
+ var mergeDrain = (base, next) => {
2166
+ const modules = new Map(base.modules);
2167
+ for (const [k, commit] of next.modules) {
2168
+ const prev = modules.get(k);
2169
+ if (!prev) {
2170
+ modules.set(k, commit);
2171
+ } else {
2172
+ modules.set(k, {
2173
+ ...commit,
2174
+ meta: {
2175
+ ...commit.meta,
2176
+ priority: maxPriority2(prev.meta.priority, commit.meta.priority)
2177
+ }
2178
+ });
2179
+ }
2180
+ }
2181
+ const dirtyTopics = new Map(base.dirtyTopics);
2182
+ for (const [k, p] of next.dirtyTopics) {
2183
+ const prev = dirtyTopics.get(k);
2184
+ dirtyTopics.set(k, prev ? maxPriority2(prev, p) : p);
2185
+ }
2186
+ return { modules, dirtyTopics };
2187
+ };
2188
+ var emptyDrain = () => ({ modules: /* @__PURE__ */ new Map(), dirtyTopics: /* @__PURE__ */ new Map() });
2189
+ var makeTickScheduler = (args) => {
2190
+ const store = args.runtimeStore;
2191
+ const hostScheduler = args.hostScheduler;
2192
+ const declarativeLinks = args.declarativeLinkRuntime;
2193
+ const queue = args.queue ?? makeJobQueue();
2194
+ const config = {
2195
+ maxSteps: args.config?.maxSteps ?? 64,
2196
+ urgentStepCap: args.config?.urgentStepCap ?? 512,
2197
+ maxDrainRounds: args.config?.maxDrainRounds ?? 8,
2198
+ microtaskChainDepthLimit: args.config?.microtaskChainDepthLimit ?? 32
2199
+ };
2200
+ const telemetry = args.config?.telemetry;
2201
+ const telemetrySampleRate = clampSampleRate(telemetry?.sampleRate);
2202
+ let tickSeq = 0;
2203
+ let scheduled = false;
2204
+ let microtaskChainDepth = 0;
2205
+ let nextForcedReason;
2206
+ let coalescedModules = 0;
2207
+ let coalescedTopics = 0;
2208
+ const yieldMicrotask = import_effect8.Effect.async((resume) => {
2209
+ hostScheduler.scheduleMicrotask(() => resume(import_effect8.Effect.void));
2210
+ });
2211
+ const yieldMacrotask = import_effect8.Effect.async((resume, signal) => {
2212
+ const cancel = hostScheduler.scheduleMacrotask(() => resume(import_effect8.Effect.void));
2213
+ try {
2214
+ signal.addEventListener(
2215
+ "abort",
2216
+ () => {
2217
+ cancel();
2218
+ },
2219
+ { once: true }
2220
+ );
2221
+ } catch {
2222
+ }
2223
+ });
2224
+ const scheduleTick = () => import_effect8.Effect.gen(function* () {
2225
+ if (scheduled) return;
2226
+ scheduled = true;
2227
+ const waitedForBatch = batchDepth > 0;
2228
+ const forcedReason = nextForcedReason;
2229
+ nextForcedReason = void 0;
2230
+ const shouldYieldForStarvation = forcedReason == null && microtaskChainDepth >= Math.max(1, config.microtaskChainDepthLimit);
2231
+ const reason = forcedReason ?? (shouldYieldForStarvation ? "microtask_starvation" : void 0);
2232
+ const boundary = reason ? "macrotask" : "microtask";
2233
+ const startedAs = waitedForBatch ? "batch" : boundary;
2234
+ const depthAtSchedule = microtaskChainDepth;
2235
+ yield* import_effect8.Effect.forkDaemon(
2236
+ import_effect8.Effect.locally(inSyncTransactionFiber, false)(
2237
+ import_effect8.Effect.gen(function* () {
2238
+ try {
2239
+ yield* waitForBatchEndIfNeeded();
2240
+ if (boundary === "microtask") {
2241
+ yield* yieldMicrotask;
2242
+ microtaskChainDepth += 1;
2243
+ } else {
2244
+ yield* yieldMacrotask;
2245
+ microtaskChainDepth = 0;
2246
+ }
2247
+ const schedule = {
2248
+ startedAs,
2249
+ microtaskChainDepth: boundary === "macrotask" ? depthAtSchedule : microtaskChainDepth,
2250
+ ...boundary === "macrotask" ? { forcedMacrotask: true, reason: reason ?? "unknown" } : {}
2251
+ };
2252
+ const outcome = yield* flushTick(schedule);
2253
+ if (!outcome.stable) {
2254
+ nextForcedReason = outcome.degradeReason === "budget_steps" ? "budget" : outcome.degradeReason === "cycle_detected" ? "cycle_detected" : "unknown";
2255
+ }
2256
+ } finally {
2257
+ scheduled = false;
2258
+ if (queue.hasPending()) {
2259
+ yield* scheduleTick();
2260
+ } else {
2261
+ microtaskChainDepth = 0;
2262
+ }
2263
+ }
2264
+ })
2265
+ )
2266
+ );
2267
+ });
2268
+ const flushTick = (schedule) => import_effect8.Effect.gen(function* () {
2269
+ if (!queue.hasPending()) {
2270
+ return { stable: true };
2271
+ }
2272
+ tickSeq += 1;
2273
+ const currentTickSeq = tickSeq;
2274
+ const diagnosticsLevel2 = yield* import_effect8.FiberRef.get(currentDiagnosticsLevel);
2275
+ const shouldEmitTrace = isDevtoolsEnabled() && diagnosticsLevel2 !== "off";
2276
+ const captured = {
2277
+ drainRounds: 0,
2278
+ stable: true,
2279
+ accepted: emptyDrain()
2280
+ };
2281
+ while (captured.drainRounds < config.maxDrainRounds) {
2282
+ const drained = queue.drain();
2283
+ if (!drained) break;
2284
+ captured.drainRounds += 1;
2285
+ captured.accepted = mergeDrain(captured.accepted, drained);
2286
+ if (declarativeLinks && drained.modules.size > 0) {
2287
+ const changedModuleInstanceKeys = Array.from(drained.modules.keys());
2288
+ yield* declarativeLinks.applyForSources({
2289
+ tickSeq: currentTickSeq,
2290
+ acceptedModules: captured.accepted.modules,
2291
+ changedModuleInstanceKeys
2292
+ });
2293
+ }
2294
+ }
2295
+ if (queue.hasPending()) {
2296
+ captured.stable = false;
2297
+ captured.degradeReason = "cycle_detected";
2298
+ }
2299
+ const urgentModules = [];
2300
+ const nonUrgentModules = [];
2301
+ for (const commit of captured.accepted.modules.values()) {
2302
+ if (toLane(commit.meta.priority) === "urgent") {
2303
+ urgentModules.push(commit);
2304
+ } else {
2305
+ nonUrgentModules.push(commit);
2306
+ }
2307
+ }
2308
+ const urgentCapExceeded = urgentModules.length > config.urgentStepCap;
2309
+ const urgentAccepted = urgentCapExceeded ? urgentModules.slice(0, config.urgentStepCap) : urgentModules;
2310
+ const urgentDeferred = urgentCapExceeded ? urgentModules.slice(config.urgentStepCap) : [];
2311
+ const nonUrgentBudget = Math.max(0, config.maxSteps);
2312
+ const nonUrgentAccepted = urgentCapExceeded ? [] : nonUrgentModules.slice(0, nonUrgentBudget);
2313
+ const nonUrgentDeferred = urgentCapExceeded ? nonUrgentModules : nonUrgentModules.slice(nonUrgentBudget);
2314
+ if (urgentCapExceeded) {
2315
+ captured.stable = false;
2316
+ captured.degradeReason = "cycle_detected";
2317
+ } else if (nonUrgentDeferred.length > 0) {
2318
+ captured.stable = false;
2319
+ captured.degradeReason = captured.degradeReason ?? "budget_steps";
2320
+ }
2321
+ const acceptedModules = /* @__PURE__ */ new Map();
2322
+ const deferredModules = /* @__PURE__ */ new Map();
2323
+ for (const c of urgentAccepted) acceptedModules.set(c.moduleInstanceKey, c);
2324
+ for (const c of nonUrgentAccepted) acceptedModules.set(c.moduleInstanceKey, c);
2325
+ for (const c of urgentDeferred) deferredModules.set(c.moduleInstanceKey, c);
2326
+ for (const c of nonUrgentDeferred) deferredModules.set(c.moduleInstanceKey, c);
2327
+ const acceptedTopics = /* @__PURE__ */ new Map();
2328
+ const deferredTopics = /* @__PURE__ */ new Map();
2329
+ for (const [topicKey, priority] of captured.accepted.dirtyTopics) {
2330
+ const info = storeTopicToModuleInstanceKey(topicKey);
2331
+ if (!info) continue;
2332
+ if (acceptedModules.has(info)) {
2333
+ acceptedTopics.set(topicKey, priority);
2334
+ } else if (deferredModules.has(info)) {
2335
+ deferredTopics.set(topicKey, priority);
2336
+ } else {
2337
+ acceptedTopics.set(topicKey, priority);
2338
+ }
2339
+ }
2340
+ const acceptedDrain = {
2341
+ modules: acceptedModules,
2342
+ dirtyTopics: acceptedTopics
2343
+ };
2344
+ const deferredDrain = deferredModules.size > 0 || deferredTopics.size > 0 ? {
2345
+ modules: deferredModules,
2346
+ dirtyTopics: deferredTopics
2347
+ } : void 0;
2348
+ captured.deferred = deferredDrain;
2349
+ let startedAtMs;
2350
+ let triggerSummary;
2351
+ let anchor;
2352
+ let backlog;
2353
+ let result;
2354
+ if (shouldEmitTrace) {
2355
+ startedAtMs = Date.now();
2356
+ triggerSummary = (() => {
2357
+ const triggers = Array.from(captured.accepted.modules.values());
2358
+ const counts = /* @__PURE__ */ new Map();
2359
+ let primary = void 0;
2360
+ for (const t of triggers) {
2361
+ const kind = toTriggerKind(t.meta.originKind);
2362
+ counts.set(kind, (counts.get(kind) ?? 0) + 1);
2363
+ if (!primary) {
2364
+ primary = {
2365
+ kind,
2366
+ moduleId: t.moduleId,
2367
+ instanceId: t.instanceId,
2368
+ fieldPath: kind === "externalStore" ? t.meta.originName : void 0,
2369
+ actionTag: kind === "dispatch" ? t.meta.originName : void 0
2370
+ };
2371
+ }
2372
+ }
2373
+ return {
2374
+ total: triggers.length,
2375
+ kinds: Array.from(counts.entries()).map(([kind, count]) => ({ kind, count })),
2376
+ primary,
2377
+ coalescedCount: {
2378
+ modules: coalescedModules,
2379
+ topics: coalescedTopics
2380
+ }
2381
+ };
2382
+ })();
2383
+ anchor = (() => {
2384
+ const first = captured.accepted.modules.values().next().value;
2385
+ if (!first) return void 0;
2386
+ return {
2387
+ moduleId: first.moduleId,
2388
+ instanceId: first.instanceId,
2389
+ txnSeq: first.meta.txnSeq,
2390
+ txnId: first.meta.txnId,
2391
+ ...typeof first.opSeq === "number" ? { opSeq: first.opSeq } : null
2392
+ };
2393
+ })();
2394
+ backlog = (() => {
2395
+ const deferredWork = captured.deferred;
2396
+ if (!deferredWork) return void 0;
2397
+ const pendingDeferredWork = deferredWork.modules.size + deferredWork.dirtyTopics.size;
2398
+ const deferredModulesList = Array.from(deferredWork.modules.values());
2399
+ const pendingExternalInputs = deferredModulesList.filter((m) => toTriggerKind(m.meta.originKind) === "externalStore").length;
2400
+ const primaryDeferred = deferredModulesList.find((m) => toTriggerKind(m.meta.originKind) === "externalStore") ?? deferredModulesList[0];
2401
+ const kind = primaryDeferred ? toTriggerKind(primaryDeferred.meta.originKind) : "unknown";
2402
+ const deferredPrimary = primaryDeferred != null ? {
2403
+ kind: kind === "externalStore" ? "externalStore" : "unknown",
2404
+ moduleId: primaryDeferred.moduleId,
2405
+ instanceId: primaryDeferred.instanceId,
2406
+ fieldPath: kind === "externalStore" ? primaryDeferred.meta.originName : void 0,
2407
+ storeId: void 0
2408
+ } : void 0;
2409
+ return {
2410
+ pendingExternalInputs,
2411
+ pendingDeferredWork,
2412
+ deferredPrimary
2413
+ };
2414
+ })();
2415
+ result = {
2416
+ stable: captured.stable,
2417
+ ...captured.stable ? null : { degradeReason: captured.degradeReason ?? "unknown" }
2418
+ };
2419
+ }
2420
+ if (shouldEmitTrace && schedule.forcedMacrotask && schedule.reason === "microtask_starvation") {
2421
+ yield* record({
2422
+ type: "warn:microtask-starvation",
2423
+ moduleId: anchor?.moduleId,
2424
+ instanceId: anchor?.instanceId,
2425
+ tickSeq: currentTickSeq,
2426
+ microtaskChainDepth: schedule.microtaskChainDepth
2427
+ });
2428
+ }
2429
+ if (shouldEmitTrace) {
2430
+ yield* record({
2431
+ type: "trace:tick",
2432
+ moduleId: anchor?.moduleId,
2433
+ instanceId: anchor?.instanceId,
2434
+ data: {
2435
+ tickSeq: currentTickSeq,
2436
+ phase: "start",
2437
+ timestampMs: startedAtMs,
2438
+ schedule,
2439
+ triggerSummary,
2440
+ anchors: anchor,
2441
+ budget: {
2442
+ maxSteps: config.maxSteps,
2443
+ elapsedMs: 0,
2444
+ steps: 0,
2445
+ txnCount: acceptedModules.size
2446
+ }
2447
+ }
2448
+ });
2449
+ }
2450
+ if (!captured.stable && shouldEmitTrace) {
2451
+ yield* record({
2452
+ type: "trace:tick",
2453
+ moduleId: anchor?.moduleId,
2454
+ instanceId: anchor?.instanceId,
2455
+ data: {
2456
+ tickSeq: currentTickSeq,
2457
+ phase: "budgetExceeded",
2458
+ timestampMs: Date.now(),
2459
+ schedule,
2460
+ triggerSummary,
2461
+ anchors: anchor,
2462
+ budget: {
2463
+ maxSteps: config.maxSteps,
2464
+ elapsedMs: Math.max(0, Date.now() - startedAtMs),
2465
+ steps: config.maxSteps,
2466
+ txnCount: acceptedModules.size
2467
+ },
2468
+ backlog,
2469
+ result
2470
+ }
2471
+ });
2472
+ }
2473
+ if (deferredDrain) {
2474
+ queue.requeue(deferredDrain);
2475
+ }
2476
+ const committed = store.commitTick({
2477
+ tickSeq: currentTickSeq,
2478
+ accepted: acceptedDrain
2479
+ });
2480
+ for (const { listeners } of committed.changedTopics.values()) {
2481
+ for (const listener of listeners) {
2482
+ try {
2483
+ listener();
2484
+ } catch {
2485
+ }
2486
+ }
2487
+ }
2488
+ if (!captured.stable && shouldEmitTrace && backlog?.deferredPrimary) {
2489
+ const primary = backlog.deferredPrimary;
2490
+ if (primary.kind === "externalStore") {
2491
+ const moduleInstanceKey = primary.moduleId && primary.instanceId ? `${primary.moduleId}::${primary.instanceId}` : void 0;
2492
+ if (moduleInstanceKey && store.getModuleSubscriberCount(moduleInstanceKey) > 0) {
2493
+ yield* record({
2494
+ type: "warn:priority-inversion",
2495
+ moduleId: primary.moduleId,
2496
+ instanceId: primary.instanceId,
2497
+ tickSeq: currentTickSeq,
2498
+ reason: "deferredBacklog"
2499
+ });
2500
+ }
2501
+ }
2502
+ }
2503
+ if (shouldEmitTrace) {
2504
+ yield* record({
2505
+ type: "trace:tick",
2506
+ moduleId: anchor?.moduleId,
2507
+ instanceId: anchor?.instanceId,
2508
+ data: {
2509
+ tickSeq: currentTickSeq,
2510
+ phase: "settled",
2511
+ timestampMs: Date.now(),
2512
+ schedule,
2513
+ triggerSummary,
2514
+ anchors: anchor,
2515
+ budget: {
2516
+ maxSteps: config.maxSteps,
2517
+ elapsedMs: Math.max(0, Date.now() - startedAtMs),
2518
+ steps: acceptedModules.size,
2519
+ txnCount: acceptedModules.size
2520
+ },
2521
+ backlog,
2522
+ result
2523
+ }
2524
+ });
2525
+ }
2526
+ if (telemetry?.onTickDegraded && (schedule.forcedMacrotask || !captured.stable) && shouldSampleTick(currentTickSeq, telemetrySampleRate)) {
2527
+ try {
2528
+ telemetry.onTickDegraded({
2529
+ tickSeq: currentTickSeq,
2530
+ stable: captured.stable,
2531
+ degradeReason: captured.stable ? void 0 : captured.degradeReason ?? "unknown",
2532
+ forcedMacrotask: schedule.forcedMacrotask,
2533
+ scheduleReason: schedule.reason,
2534
+ microtaskChainDepth: schedule.microtaskChainDepth,
2535
+ deferredWorkCount: deferredDrain ? deferredDrain.modules.size + deferredDrain.dirtyTopics.size : 0
2536
+ });
2537
+ } catch {
2538
+ }
2539
+ }
2540
+ coalescedModules = 0;
2541
+ coalescedTopics = 0;
2542
+ return { stable: captured.stable, degradeReason: captured.degradeReason };
2543
+ });
2544
+ const flushNow = flushTick({ startedAs: "unknown" }).pipe(import_effect8.Effect.asVoid);
2545
+ const storeTopicToModuleInstanceKey = (topicKey) => {
2546
+ const idx = topicKey.indexOf("::rq:");
2547
+ if (idx > 0) {
2548
+ return topicKey.slice(0, idx);
2549
+ }
2550
+ if (topicKey.includes("::")) {
2551
+ return topicKey;
2552
+ }
2553
+ return void 0;
2554
+ };
2555
+ const onSelectorChanged = ({ moduleInstanceKey, selectorId, priority }) => {
2556
+ const coalesced = queue.markTopicDirty(makeReadQueryTopicKey(moduleInstanceKey, selectorId), priority);
2557
+ if (coalesced) coalescedTopics += 1;
2558
+ };
2559
+ const onModuleCommit = (commit) => import_effect8.Effect.gen(function* () {
2560
+ const coalescedCommit = queue.enqueueModuleCommit(commit);
2561
+ if (coalescedCommit) coalescedModules += 1;
2562
+ const coalescedTopic = queue.markTopicDirty(commit.moduleInstanceKey, commit.meta.priority);
2563
+ if (coalescedTopic) coalescedTopics += 1;
2564
+ yield* scheduleTick();
2565
+ });
2566
+ return {
2567
+ getTickSeq: () => tickSeq,
2568
+ onModuleCommit,
2569
+ onSelectorChanged,
2570
+ flushNow
2571
+ };
2572
+ };
2573
+
2574
+ // src/internal/runtime/core/DeclarativeLinkRuntime.ts
2575
+ var import_effect9 = require("effect");
2576
+ var makeDeclarativeLinkRuntime = () => {
2577
+ const moduleAsSourceById = /* @__PURE__ */ new Map();
2578
+ const moduleAsSourceIdsBySource = /* @__PURE__ */ new Map();
2579
+ const declarativeById = /* @__PURE__ */ new Map();
2580
+ const declarativeReadNodesBySource = /* @__PURE__ */ new Map();
2581
+ const registerModuleAsSourceLink = (link) => {
2582
+ const stored = {
2583
+ ...link,
2584
+ hasValue: false,
2585
+ lastValue: void 0
2586
+ };
2587
+ moduleAsSourceById.set(link.id, stored);
2588
+ const set = moduleAsSourceIdsBySource.get(link.sourceModuleInstanceKey) ?? /* @__PURE__ */ new Set();
2589
+ set.add(link.id);
2590
+ moduleAsSourceIdsBySource.set(link.sourceModuleInstanceKey, set);
2591
+ return () => {
2592
+ moduleAsSourceById.delete(link.id);
2593
+ const current = moduleAsSourceIdsBySource.get(link.sourceModuleInstanceKey);
2594
+ if (!current) return;
2595
+ current.delete(link.id);
2596
+ if (current.size === 0) {
2597
+ moduleAsSourceIdsBySource.delete(link.sourceModuleInstanceKey);
2598
+ }
2599
+ };
2600
+ };
2601
+ const registerDeclarativeLink = (link) => {
2602
+ const readNodeById = /* @__PURE__ */ new Map();
2603
+ for (const n of link.readNodes) {
2604
+ readNodeById.set(n.nodeId, n);
2605
+ }
2606
+ const dispatchNodeById = /* @__PURE__ */ new Map();
2607
+ for (const n of link.dispatchNodes) {
2608
+ dispatchNodeById.set(n.nodeId, n);
2609
+ }
2610
+ const incomingByDispatch = /* @__PURE__ */ new Map();
2611
+ for (const e of link.ir.edges) {
2612
+ const to = e.to;
2613
+ const isDispatch = dispatchNodeById.has(to);
2614
+ if (!isDispatch) continue;
2615
+ incomingByDispatch.set(to, (incomingByDispatch.get(to) ?? 0) + 1);
2616
+ const count = incomingByDispatch.get(to) ?? 0;
2617
+ if (count > 1) {
2618
+ throw new Error(
2619
+ `[DeclarativeLinkRuntime] Invalid DeclarativeLinkIR: dispatch node has multiple incoming edges (linkId=${link.linkId}, nodeId=${to}).`
2620
+ );
2621
+ }
2622
+ }
2623
+ const dispatchTargetsByReadNode = /* @__PURE__ */ new Map();
2624
+ for (const e of link.ir.edges) {
2625
+ const from = e.from;
2626
+ const to = e.to;
2627
+ if (!readNodeById.has(from)) continue;
2628
+ if (!dispatchNodeById.has(to)) continue;
2629
+ const list = dispatchTargetsByReadNode.get(from) ?? [];
2630
+ list.push(to);
2631
+ dispatchTargetsByReadNode.set(from, list);
2632
+ }
2633
+ const stored = {
2634
+ ...link,
2635
+ readNodeById,
2636
+ dispatchNodeById,
2637
+ dispatchTargetsByReadNode,
2638
+ readNodeState: /* @__PURE__ */ new Map()
2639
+ };
2640
+ declarativeById.set(link.linkId, stored);
2641
+ for (const n of link.readNodes) {
2642
+ const list = declarativeReadNodesBySource.get(n.moduleInstanceKey) ?? [];
2643
+ list.push({ linkId: link.linkId, nodeId: n.nodeId });
2644
+ declarativeReadNodesBySource.set(n.moduleInstanceKey, list);
2645
+ }
2646
+ return () => {
2647
+ declarativeById.delete(link.linkId);
2648
+ for (const n of link.readNodes) {
2649
+ const list = declarativeReadNodesBySource.get(n.moduleInstanceKey);
2650
+ if (!list) continue;
2651
+ const next = list.filter((x) => !(x.linkId === link.linkId && x.nodeId === n.nodeId));
2652
+ if (next.length === 0) {
2653
+ declarativeReadNodesBySource.delete(n.moduleInstanceKey);
2654
+ } else {
2655
+ declarativeReadNodesBySource.set(n.moduleInstanceKey, next);
2656
+ }
2657
+ }
2658
+ };
2659
+ };
2660
+ const applyForSources = (args) => import_effect9.Effect.gen(function* () {
2661
+ let scheduled = false;
2662
+ for (const sourceKey of args.changedModuleInstanceKeys) {
2663
+ const ids = moduleAsSourceIdsBySource.get(sourceKey);
2664
+ if (!ids || ids.size === 0) continue;
2665
+ const commit = args.acceptedModules.get(sourceKey);
2666
+ if (!commit) continue;
2667
+ for (const id of ids) {
2668
+ const link = moduleAsSourceById.get(id);
2669
+ if (!link) continue;
2670
+ let selected;
2671
+ try {
2672
+ selected = link.readQuery.select(commit.state);
2673
+ } catch {
2674
+ continue;
2675
+ }
2676
+ const nextValue = link.computeValue(selected);
2677
+ if (link.hasValue && link.equalsValue(link.lastValue, nextValue)) {
2678
+ continue;
2679
+ }
2680
+ link.hasValue = true;
2681
+ link.lastValue = nextValue;
2682
+ scheduled = true;
2683
+ yield* link.applyValue(nextValue);
2684
+ }
2685
+ }
2686
+ for (const sourceKey of args.changedModuleInstanceKeys) {
2687
+ const refs = declarativeReadNodesBySource.get(sourceKey);
2688
+ if (!refs || refs.length === 0) continue;
2689
+ const commit = args.acceptedModules.get(sourceKey);
2690
+ if (!commit) continue;
2691
+ for (const ref of refs) {
2692
+ const link = declarativeById.get(ref.linkId);
2693
+ if (!link) continue;
2694
+ const readNode = link.readNodeById.get(ref.nodeId);
2695
+ if (!readNode) continue;
2696
+ let value;
2697
+ try {
2698
+ value = readNode.readQuery.select(commit.state);
2699
+ } catch {
2700
+ continue;
2701
+ }
2702
+ const state = link.readNodeState.get(ref.nodeId) ?? { hasValue: false, lastValue: void 0 };
2703
+ const changed = !state.hasValue || !Object.is(state.lastValue, value);
2704
+ if (!changed) continue;
2705
+ state.hasValue = true;
2706
+ state.lastValue = value;
2707
+ link.readNodeState.set(ref.nodeId, state);
2708
+ const targets = link.dispatchTargetsByReadNode.get(ref.nodeId) ?? [];
2709
+ for (const dispatchNodeId of targets) {
2710
+ const node = link.dispatchNodeById.get(dispatchNodeId);
2711
+ if (!node) continue;
2712
+ scheduled = true;
2713
+ yield* node.dispatch(value);
2714
+ }
2715
+ }
2716
+ }
2717
+ return { scheduled };
2718
+ });
2719
+ return {
2720
+ registerModuleAsSourceLink,
2721
+ registerDeclarativeLink,
2722
+ applyForSources
2723
+ };
2724
+ };
2725
+
1535
2726
  // src/internal/runtime/core/env.ts
1536
- var import_effect6 = require("effect");
1537
2727
  var getNodeEnv = () => {
1538
2728
  try {
1539
2729
  const env = globalThis?.process?.env;
@@ -1543,33 +2733,65 @@ var getNodeEnv = () => {
1543
2733
  }
1544
2734
  };
1545
2735
  var isDevEnv = () => getNodeEnv() !== "production";
1546
- var StateTransactionConfigTagImpl = class extends import_effect6.Context.Tag("@logixjs/core/StateTransactionRuntimeConfig")() {
2736
+ var StateTransactionConfigTagImpl = class extends import_effect10.Context.Tag("@logixjs/core/StateTransactionRuntimeConfig")() {
1547
2737
  };
1548
2738
  var StateTransactionConfigTag = StateTransactionConfigTagImpl;
1549
- var ReadQueryStrictGateConfigTagImpl = class extends import_effect6.Context.Tag("@logixjs/core/ReadQueryStrictGateRuntimeConfig")() {
2739
+ var ReadQueryStrictGateConfigTagImpl = class extends import_effect10.Context.Tag("@logixjs/core/ReadQueryStrictGateRuntimeConfig")() {
1550
2740
  };
1551
2741
  var ReadQueryStrictGateConfigTag = ReadQueryStrictGateConfigTagImpl;
1552
- var ReplayModeConfigTagImpl = class extends import_effect6.Context.Tag("@logixjs/core/ReplayModeConfig")() {
2742
+ var ReplayModeConfigTagImpl = class extends import_effect10.Context.Tag("@logixjs/core/ReplayModeConfig")() {
1553
2743
  };
1554
- var StateTransactionOverridesTagImpl = class extends import_effect6.Context.Tag("@logixjs/core/StateTransactionOverrides")() {
2744
+ var StateTransactionOverridesTagImpl = class extends import_effect10.Context.Tag("@logixjs/core/StateTransactionOverrides")() {
1555
2745
  };
1556
- var ConcurrencyPolicyTagImpl = class extends import_effect6.Context.Tag("@logixjs/core/ConcurrencyPolicy")() {
2746
+ var ConcurrencyPolicyTagImpl = class extends import_effect10.Context.Tag("@logixjs/core/ConcurrencyPolicy")() {
1557
2747
  };
1558
2748
  var ConcurrencyPolicyTag = ConcurrencyPolicyTagImpl;
1559
- var ConcurrencyPolicyOverridesTagImpl = class extends import_effect6.Context.Tag("@logixjs/core/ConcurrencyPolicyOverrides")() {
2749
+ var ConcurrencyPolicyOverridesTagImpl = class extends import_effect10.Context.Tag("@logixjs/core/ConcurrencyPolicyOverrides")() {
2750
+ };
2751
+ var RuntimeStoreTag = class extends import_effect10.Context.Tag("@logixjs/core/RuntimeStore")() {
2752
+ };
2753
+ var runtimeStoreLayer = import_effect10.Layer.scoped(
2754
+ RuntimeStoreTag,
2755
+ import_effect10.Effect.acquireRelease(
2756
+ import_effect10.Effect.sync(() => makeRuntimeStore()),
2757
+ (store) => import_effect10.Effect.sync(() => store.dispose())
2758
+ )
2759
+ );
2760
+ var HostSchedulerTag = class extends import_effect10.Context.Tag("@logixjs/core/HostScheduler")() {
2761
+ };
2762
+ var hostSchedulerLayer = import_effect10.Layer.succeed(
2763
+ HostSchedulerTag,
2764
+ getGlobalHostScheduler()
2765
+ );
2766
+ var DeclarativeLinkRuntimeTag = class extends import_effect10.Context.Tag("@logixjs/core/DeclarativeLinkRuntime")() {
1560
2767
  };
2768
+ var declarativeLinkRuntimeLayer = import_effect10.Layer.succeed(
2769
+ DeclarativeLinkRuntimeTag,
2770
+ makeDeclarativeLinkRuntime()
2771
+ );
2772
+ var TickSchedulerTag = class extends import_effect10.Context.Tag("@logixjs/core/TickScheduler")() {
2773
+ };
2774
+ var tickSchedulerLayer = (config) => import_effect10.Layer.effect(
2775
+ TickSchedulerTag,
2776
+ import_effect10.Effect.gen(function* () {
2777
+ const store = yield* RuntimeStoreTag;
2778
+ const declarativeLinkRuntime = yield* DeclarativeLinkRuntimeTag;
2779
+ const hostScheduler = yield* HostSchedulerTag;
2780
+ return makeTickScheduler({ runtimeStore: store, declarativeLinkRuntime, hostScheduler, config });
2781
+ })
2782
+ );
1561
2783
 
1562
2784
  // src/internal/runtime/core/RuntimeKernel.ts
1563
- var RuntimeServicesRuntimeConfigTagImpl = class extends import_effect7.Context.Tag("@logixjs/core/RuntimeServicesRuntimeConfig")() {
2785
+ var RuntimeServicesRuntimeConfigTagImpl = class extends import_effect11.Context.Tag("@logixjs/core/RuntimeServicesRuntimeConfig")() {
1564
2786
  };
1565
- var RuntimeServicesProviderOverridesTagImpl = class extends import_effect7.Context.Tag("@logixjs/core/RuntimeServicesProviderOverrides")() {
2787
+ var RuntimeServicesProviderOverridesTagImpl = class extends import_effect11.Context.Tag("@logixjs/core/RuntimeServicesProviderOverrides")() {
1566
2788
  };
1567
- var RuntimeServicesInstanceOverridesTagImpl = class extends import_effect7.Context.Tag("@logixjs/core/RuntimeServicesInstanceOverrides")() {
2789
+ var RuntimeServicesInstanceOverridesTagImpl = class extends import_effect11.Context.Tag("@logixjs/core/RuntimeServicesInstanceOverrides")() {
1568
2790
  };
1569
2791
  var RuntimeServicesInstanceOverridesTag = RuntimeServicesInstanceOverridesTagImpl;
1570
- var FullCutoverGateModeTagImpl = class extends import_effect7.Context.Tag("@logixjs/core/FullCutoverGateMode")() {
2792
+ var FullCutoverGateModeTagImpl = class extends import_effect11.Context.Tag("@logixjs/core/FullCutoverGateMode")() {
1571
2793
  };
1572
- var RuntimeServicesRegistryTagImpl = class extends import_effect7.Context.Tag("@logixjs/core/RuntimeServicesRegistry")() {
2794
+ var RuntimeServicesRegistryTagImpl = class extends import_effect11.Context.Tag("@logixjs/core/RuntimeServicesRegistry")() {
1573
2795
  };
1574
2796
  var RUNTIME_SERVICES_EVIDENCE = /* @__PURE__ */ Symbol.for("@logixjs/core/runtimeServicesEvidence");
1575
2797
  var formatScope = (moduleId, instanceId) => {
@@ -1604,24 +2826,24 @@ var getRuntimeServicesEvidence = (runtime) => {
1604
2826
  };
1605
2827
 
1606
2828
  // src/internal/runtime/core/ConvergeStaticIrCollector.ts
1607
- var import_effect8 = require("effect");
1608
- var currentConvergeStaticIrCollectors = import_effect8.FiberRef.unsafeMake([]);
1609
- var appendConvergeStaticIrCollectors = (collectors) => import_effect8.Layer.fiberRefLocallyScopedWith(currentConvergeStaticIrCollectors, (current) => [
2829
+ var import_effect12 = require("effect");
2830
+ var currentConvergeStaticIrCollectors = import_effect12.FiberRef.unsafeMake([]);
2831
+ var appendConvergeStaticIrCollectors = (collectors) => import_effect12.Layer.fiberRefLocallyScopedWith(currentConvergeStaticIrCollectors, (current) => [
1610
2832
  ...current,
1611
2833
  ...collectors
1612
2834
  ]);
1613
2835
 
1614
2836
  // src/internal/observability/trialRunModule.ts
1615
- var import_effect32 = require("effect");
2837
+ var import_effect35 = require("effect");
1616
2838
 
1617
2839
  // src/internal/platform/BuildEnv.ts
1618
- var import_effect11 = require("effect");
2840
+ var import_effect15 = require("effect");
1619
2841
 
1620
2842
  // src/internal/platform/ConstructionGuard.ts
1621
- var import_effect9 = require("effect");
2843
+ var import_effect13 = require("effect");
1622
2844
 
1623
2845
  // src/internal/platform/RuntimeHost.ts
1624
- var import_effect10 = require("effect");
2846
+ var import_effect14 = require("effect");
1625
2847
  var detectKind = () => {
1626
2848
  const isBrowser2 = typeof window !== "undefined" && typeof document !== "undefined";
1627
2849
  if (isBrowser2) return "browser";
@@ -1634,9 +2856,9 @@ var make = (kind) => ({
1634
2856
  isNode: kind === "node",
1635
2857
  isBrowser: kind === "browser"
1636
2858
  });
1637
- var RuntimeHost = class extends import_effect10.Context.Tag("@logixjs/RuntimeHost")() {
2859
+ var RuntimeHost = class extends import_effect14.Context.Tag("@logixjs/RuntimeHost")() {
1638
2860
  };
1639
- var layer = (service) => import_effect10.Layer.succeed(RuntimeHost, service);
2861
+ var layer = (service) => import_effect14.Layer.succeed(RuntimeHost, service);
1640
2862
  var defaultLayer = layer(make(detectKind()));
1641
2863
 
1642
2864
  // src/internal/platform/BuildEnv.ts
@@ -1647,18 +2869,18 @@ var toConfigProviderFromRecord = (record2) => {
1647
2869
  if (v === void 0) continue;
1648
2870
  map.set(k, String(v));
1649
2871
  }
1650
- return import_effect11.ConfigProvider.fromMap(map);
2872
+ return import_effect15.ConfigProvider.fromMap(map);
1651
2873
  };
1652
2874
  var layer2 = (options = {}) => {
1653
2875
  const runtimeHost = options.runtimeHost ? layer(options.runtimeHost) : options.runtimeHostKind ? layer(make(options.runtimeHostKind)) : defaultLayer;
1654
2876
  const configProvider = options.configProvider ? options.configProvider : toConfigProviderFromRecord(options.config);
1655
- const config = import_effect11.Layer.setConfigProvider(configProvider);
1656
- return import_effect11.Layer.mergeAll(runtimeHost, config);
2877
+ const config = import_effect15.Layer.setConfigProvider(configProvider);
2878
+ return import_effect15.Layer.mergeAll(runtimeHost, config);
1657
2879
  };
1658
2880
 
1659
2881
  // src/internal/runtime/core/KernelRef.ts
1660
- var import_effect12 = require("effect");
1661
- var KernelImplementationRefTagImpl = class extends import_effect12.Context.Tag("@logixjs/core/KernelImplementationRef")() {
2882
+ var import_effect16 = require("effect");
2883
+ var KernelImplementationRefTagImpl = class extends import_effect16.Context.Tag("@logixjs/core/KernelImplementationRef")() {
1662
2884
  };
1663
2885
  var KERNEL_IMPLEMENTATION_REF = /* @__PURE__ */ Symbol.for("@logixjs/core/kernelImplementationRef");
1664
2886
  var formatScope2 = (moduleId, instanceId) => {
@@ -1683,181 +2905,14 @@ var getKernelImplementationRef = (runtime) => {
1683
2905
  };
1684
2906
 
1685
2907
  // src/internal/runtime/core/runner/ProgramRunner.kernel.ts
1686
- var import_effect26 = require("effect");
2908
+ var import_effect29 = require("effect");
1687
2909
 
1688
2910
  // src/internal/runtime/core/BoundApiRuntime.ts
1689
- var import_effect23 = require("effect");
2911
+ var import_effect26 = require("effect");
1690
2912
 
1691
2913
  // src/internal/action.ts
1692
- var import_effect13 = require("effect");
1693
- var isActionToken = (value) => typeof value === "function" && value._kind === "ActionToken" && typeof value.tag === "string" && import_effect13.Schema.isSchema(value.schema);
1694
-
1695
- // src/internal/runtime/core/TaskRunner.ts
1696
- var import_effect14 = require("effect");
1697
- var inSyncTransactionFiber = import_effect14.FiberRef.unsafeMake(false);
1698
- var forceSourceRefresh = import_effect14.FiberRef.unsafeMake(false);
1699
- var resolve = (eff, payload) => typeof eff === "function" ? eff(payload) : eff;
1700
- var defaultOrigins = (triggerName) => ({
1701
- pending: {
1702
- kind: "task:pending",
1703
- name: triggerName
1704
- },
1705
- success: {
1706
- kind: "service-callback",
1707
- name: "task:success"
1708
- },
1709
- failure: {
1710
- kind: "service-callback",
1711
- name: "task:failure"
1712
- }
1713
- });
1714
- var shouldNoopInSyncTransactionFiber = (options) => import_effect14.Effect.gen(function* () {
1715
- const inTxn = yield* import_effect14.FiberRef.get(inSyncTransactionFiber);
1716
- if (!inTxn) {
1717
- return false;
1718
- }
1719
- if (isDevEnv()) {
1720
- yield* record({
1721
- type: "diagnostic",
1722
- moduleId: options.moduleId,
1723
- instanceId: options.instanceId,
1724
- code: options.code,
1725
- severity: options.severity,
1726
- message: options.message,
1727
- hint: options.hint,
1728
- actionTag: options.actionTag,
1729
- kind: options.kind
1730
- });
1731
- }
1732
- return true;
1733
- });
1734
- var resolveConcurrencyLimit = (runtime) => runtime.resolveConcurrencyPolicy ? runtime.resolveConcurrencyPolicy().pipe(import_effect14.Effect.map((p) => p.concurrencyLimit)) : import_effect14.Effect.succeed(16);
1735
- var runTaskLifecycle = (payload, runtime, config, getCanWriteBack) => import_effect14.Effect.gen(function* () {
1736
- const noop = yield* shouldNoopInSyncTransactionFiber({
1737
- moduleId: runtime.moduleId,
1738
- instanceId: runtime.instanceId,
1739
- code: "logic::invalid_usage",
1740
- severity: "error",
1741
- message: "run*Task is not allowed inside a synchronous StateTransaction body (it may deadlock the txnQueue).",
1742
- hint: "Call run*Task from the run section of a watcher (e.g. $.onAction/$.onState/$.on); do not call it directly inside a reducer / trait.run / synchronous transaction body. For long-lived flows, use a multi-entry pattern (pending \u2192 IO \u2192 writeback).",
1743
- kind: "run_task_in_transaction"
1744
- });
1745
- if (noop) {
1746
- return;
1747
- }
1748
- const defaults = defaultOrigins(config.triggerName);
1749
- const origins = {
1750
- pending: config.origin?.pending ?? defaults.pending,
1751
- success: config.origin?.success ?? defaults.success,
1752
- failure: config.origin?.failure ?? defaults.failure
1753
- };
1754
- const pending = config.pending;
1755
- if (pending) {
1756
- yield* import_effect14.Effect.uninterruptible(
1757
- runtime.runWithStateTransaction(origins.pending, () => import_effect14.Effect.asVoid(resolve(pending, payload)))
1758
- );
1759
- }
1760
- const io = resolve(config.effect, payload);
1761
- const exit = yield* import_effect14.Effect.exit(io);
1762
- if (getCanWriteBack) {
1763
- const ok = yield* getCanWriteBack;
1764
- if (!ok) {
1765
- return;
1766
- }
1767
- }
1768
- if (exit._tag === "Success") {
1769
- const success = config.success;
1770
- if (success) {
1771
- yield* runtime.runWithStateTransaction(origins.success, () => import_effect14.Effect.asVoid(success(exit.value, payload)));
1772
- }
1773
- return;
1774
- }
1775
- const cause = exit.cause;
1776
- if (import_effect14.Cause.isInterrupted(cause)) {
1777
- return;
1778
- }
1779
- const failure = config.failure;
1780
- if (failure) {
1781
- yield* runtime.runWithStateTransaction(origins.failure, () => import_effect14.Effect.asVoid(failure(cause, payload)));
1782
- }
1783
- }).pipe(
1784
- // Watchers must not crash as a whole due to a single task failure: swallow errors, but keep them diagnosable.
1785
- import_effect14.Effect.catchAllCause(
1786
- (cause) => record({
1787
- type: "diagnostic",
1788
- moduleId: runtime.moduleId,
1789
- instanceId: runtime.instanceId,
1790
- code: "task_runner::unhandled_failure",
1791
- severity: "error",
1792
- message: "TaskRunner encountered an unhandled failure (pending/IO/writeback).",
1793
- hint: "Add a failure writeback for this task or handle errors explicitly upstream; avoid fire-and-forget swallowing errors.",
1794
- actionTag: config.triggerName,
1795
- kind: "task_runner_unhandled_failure",
1796
- trigger: {
1797
- kind: "task",
1798
- name: config.triggerName
1799
- }
1800
- }).pipe(import_effect14.Effect.zipRight(import_effect14.Effect.logError("TaskRunner error", cause)))
1801
- )
1802
- );
1803
- var makeTaskRunner = (stream, mode, runtime, config) => {
1804
- if (mode === "latest") {
1805
- return import_effect14.Effect.gen(function* () {
1806
- const taskIdRef = yield* import_effect14.Ref.make(0);
1807
- const currentFiberRef = yield* import_effect14.Ref.make(void 0);
1808
- const start = (payload) => import_effect14.Effect.gen(function* () {
1809
- const taskId = yield* import_effect14.Ref.updateAndGet(taskIdRef, (n) => n + 1);
1810
- const prev = yield* import_effect14.Ref.get(currentFiberRef);
1811
- if (prev) {
1812
- yield* import_effect14.Fiber.interruptFork(prev);
1813
- }
1814
- const canWriteBack = import_effect14.Ref.get(taskIdRef).pipe(import_effect14.Effect.map((current) => current === taskId));
1815
- const fiber = yield* import_effect14.Effect.fork(
1816
- runTaskLifecycle(payload, runtime, config, canWriteBack)
1817
- );
1818
- yield* import_effect14.Ref.set(currentFiberRef, fiber);
1819
- });
1820
- return yield* import_effect14.Stream.runForEach(stream, start);
1821
- });
1822
- }
1823
- if (mode === "exhaust") {
1824
- return import_effect14.Effect.gen(function* () {
1825
- const concurrency = yield* resolveConcurrencyLimit(runtime);
1826
- const busyRef = yield* import_effect14.Ref.make(false);
1827
- const mapper = (payload) => import_effect14.Effect.gen(function* () {
1828
- const acquired = yield* import_effect14.Ref.modify(
1829
- busyRef,
1830
- (busy) => busy ? [false, busy] : [true, true]
1831
- );
1832
- if (!acquired) {
1833
- return;
1834
- }
1835
- try {
1836
- yield* runTaskLifecycle(payload, runtime, config);
1837
- } finally {
1838
- yield* import_effect14.Ref.set(busyRef, false);
1839
- }
1840
- });
1841
- return yield* import_effect14.Stream.runDrain(stream.pipe(import_effect14.Stream.mapEffect(mapper, { concurrency })));
1842
- });
1843
- }
1844
- if (mode === "parallel") {
1845
- return import_effect14.Effect.gen(function* () {
1846
- const concurrency = yield* resolveConcurrencyLimit(runtime);
1847
- return yield* import_effect14.Stream.runDrain(
1848
- stream.pipe(
1849
- import_effect14.Stream.mapEffect((payload) => runTaskLifecycle(payload, runtime, config), {
1850
- concurrency
1851
- })
1852
- )
1853
- );
1854
- });
1855
- }
1856
- return import_effect14.Stream.runForEach(
1857
- stream,
1858
- (payload) => runTaskLifecycle(payload, runtime, config)
1859
- );
1860
- };
2914
+ var import_effect17 = require("effect");
2915
+ var isActionToken = (value) => typeof value === "function" && value._kind === "ActionToken" && typeof value.tag === "string" && import_effect17.Schema.isSchema(value.schema);
1861
2916
 
1862
2917
  // src/internal/runtime/core/mutativePatches.ts
1863
2918
  var import_mutative = require("mutative");
@@ -1963,10 +3018,10 @@ var mutateWithPatchPaths = (base, mutator) => {
1963
3018
  };
1964
3019
 
1965
3020
  // src/internal/runtime/core/FlowRuntime.ts
1966
- var import_effect16 = require("effect");
3021
+ var import_effect19 = require("effect");
1967
3022
 
1968
3023
  // src/internal/effect-op.ts
1969
- var import_effect15 = require("effect");
3024
+ var import_effect18 = require("effect");
1970
3025
  var nextGlobalOpSeq = 0;
1971
3026
  var nextOpSeq = () => {
1972
3027
  nextGlobalOpSeq += 1;
@@ -2002,7 +3057,7 @@ var stableStringify = (value) => {
2002
3057
  }
2003
3058
  if (t === "object") {
2004
3059
  const record2 = value;
2005
- const keys = Object.keys(record2).sort((a, b) => a.localeCompare(b));
3060
+ const keys = Object.keys(record2).sort();
2006
3061
  return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(record2[k])}`).join(",")}}`;
2007
3062
  }
2008
3063
  return "null";
@@ -2024,8 +3079,8 @@ function isReadQuery(input) {
2024
3079
  }
2025
3080
 
2026
3081
  // src/internal/runtime/core/FlowRuntime.ts
2027
- var getMiddlewareStack = () => import_effect16.Effect.serviceOption(EffectOpMiddlewareTag).pipe(
2028
- import_effect16.Effect.map((maybe) => import_effect16.Option.isSome(maybe) ? maybe.value.stack : [])
3082
+ var getMiddlewareStack = () => import_effect19.Effect.serviceOption(EffectOpMiddlewareTag).pipe(
3083
+ import_effect19.Effect.map((maybe) => import_effect19.Option.isSome(maybe) ? maybe.value.stack : [])
2029
3084
  );
2030
3085
  var getRuntimeScope = (runtime) => {
2031
3086
  if (!runtime) return {};
@@ -2039,8 +3094,8 @@ var getRuntimeScope = (runtime) => {
2039
3094
  var resolveEffect = (eff, payload) => typeof eff === "function" ? eff(payload) : eff;
2040
3095
  var make3 = (runtime, runtimeInternals) => {
2041
3096
  const scope = getRuntimeScope(runtime);
2042
- const resolveConcurrencyLimit2 = () => runtimeInternals ? runtimeInternals.concurrency.resolveConcurrencyPolicy().pipe(import_effect16.Effect.map((p) => p.concurrencyLimit)) : import_effect16.Effect.succeed(16);
2043
- const runAsFlowOp = (name, payload, eff, options) => import_effect16.Effect.gen(function* () {
3097
+ const resolveConcurrencyLimit2 = () => runtimeInternals ? runtimeInternals.concurrency.resolveConcurrencyPolicy().pipe(import_effect19.Effect.map((p) => p.concurrencyLimit)) : import_effect19.Effect.succeed(16);
3098
+ const runAsFlowOp = (name, payload, eff, options) => import_effect19.Effect.gen(function* () {
2044
3099
  const stack = yield* getMiddlewareStack();
2045
3100
  const meta = {
2046
3101
  ...options?.meta ?? {},
@@ -2051,8 +3106,8 @@ var make3 = (runtime, runtimeInternals) => {
2051
3106
  instanceId: scope.instanceId
2052
3107
  };
2053
3108
  if (!(typeof meta.opSeq === "number" && Number.isFinite(meta.opSeq))) {
2054
- const sessionOpt = yield* import_effect16.Effect.serviceOption(RunSessionTag);
2055
- if (import_effect16.Option.isSome(sessionOpt)) {
3109
+ const sessionOpt = yield* import_effect19.Effect.serviceOption(RunSessionTag);
3110
+ if (import_effect19.Option.isSome(sessionOpt)) {
2056
3111
  const key = meta.instanceId ?? "global";
2057
3112
  meta.opSeq = sessionOpt.value.local.nextSeq("opSeq", key);
2058
3113
  }
@@ -2067,21 +3122,21 @@ var make3 = (runtime, runtimeInternals) => {
2067
3122
  return yield* run(op, stack);
2068
3123
  });
2069
3124
  const runEffect = (eff) => (payload) => resolveEffect(eff, payload);
2070
- const runStreamSequential = (eff, options) => (stream) => import_effect16.Stream.runForEach(
3125
+ const runStreamSequential = (eff, options) => (stream) => import_effect19.Stream.runForEach(
2071
3126
  stream,
2072
3127
  (payload) => runAsFlowOp("flow.run", payload, runEffect(eff)(payload), options)
2073
3128
  );
2074
- const runStreamParallel = (eff, options) => (stream) => import_effect16.Effect.gen(function* () {
3129
+ const runStreamParallel = (eff, options) => (stream) => import_effect19.Effect.gen(function* () {
2075
3130
  const concurrency = yield* resolveConcurrencyLimit2();
2076
- return yield* import_effect16.Stream.runDrain(
3131
+ return yield* import_effect19.Stream.runDrain(
2077
3132
  stream.pipe(
2078
- import_effect16.Stream.mapEffect(
3133
+ import_effect19.Stream.mapEffect(
2079
3134
  (payload) => runAsFlowOp("flow.runParallel", payload, runEffect(eff)(payload), options),
2080
3135
  { concurrency }
2081
3136
  )
2082
3137
  )
2083
3138
  ).pipe(
2084
- import_effect16.Effect.catchAllCause(
3139
+ import_effect19.Effect.catchAllCause(
2085
3140
  (cause) => record({
2086
3141
  type: "diagnostic",
2087
3142
  moduleId: scope.moduleId,
@@ -2095,25 +3150,25 @@ var make3 = (runtime, runtimeInternals) => {
2095
3150
  kind: "flow",
2096
3151
  name: "runParallel"
2097
3152
  }
2098
- }).pipe(import_effect16.Effect.zipRight(import_effect16.Effect.failCause(cause)))
3153
+ }).pipe(import_effect19.Effect.zipRight(import_effect19.Effect.failCause(cause)))
2099
3154
  )
2100
3155
  );
2101
3156
  });
2102
3157
  return {
2103
- fromAction: (predicate) => runtime.actions$.pipe(import_effect16.Stream.filter(predicate)),
3158
+ fromAction: (predicate) => runtime.actions$.pipe(import_effect19.Stream.filter(predicate)),
2104
3159
  fromState: (selectorOrQuery) => runtime.changes(isReadQuery(selectorOrQuery) ? selectorOrQuery.select : selectorOrQuery),
2105
- debounce: (ms) => (stream) => import_effect16.Stream.debounce(stream, ms),
2106
- throttle: (ms) => (stream) => import_effect16.Stream.throttle(stream, {
3160
+ debounce: (ms) => (stream) => import_effect19.Stream.debounce(stream, ms),
3161
+ throttle: (ms) => (stream) => import_effect19.Stream.throttle(stream, {
2107
3162
  cost: () => 1,
2108
3163
  units: 1,
2109
3164
  duration: ms,
2110
3165
  strategy: "enforce"
2111
3166
  }),
2112
- filter: (predicate) => (stream) => import_effect16.Stream.filter(stream, predicate),
3167
+ filter: (predicate) => (stream) => import_effect19.Stream.filter(stream, predicate),
2113
3168
  run: (eff, options) => (stream) => runStreamSequential(eff, options)(stream),
2114
3169
  runParallel: (eff, options) => (stream) => runStreamParallel(eff, options)(stream),
2115
- runLatest: (eff, options) => (stream) => import_effect16.Stream.runDrain(
2116
- import_effect16.Stream.map(
3170
+ runLatest: (eff, options) => (stream) => import_effect19.Stream.runDrain(
3171
+ import_effect19.Stream.map(
2117
3172
  stream,
2118
3173
  (payload) => runAsFlowOp(
2119
3174
  "flow.runLatest",
@@ -2122,16 +3177,16 @@ var make3 = (runtime, runtimeInternals) => {
2122
3177
  options
2123
3178
  )
2124
3179
  ).pipe(
2125
- import_effect16.Stream.flatMap((effect) => import_effect16.Stream.fromEffect(effect), {
3180
+ import_effect19.Stream.flatMap((effect) => import_effect19.Stream.fromEffect(effect), {
2126
3181
  switch: true
2127
3182
  })
2128
3183
  )
2129
3184
  ),
2130
- runExhaust: (eff, options) => (stream) => import_effect16.Effect.gen(function* () {
3185
+ runExhaust: (eff, options) => (stream) => import_effect19.Effect.gen(function* () {
2131
3186
  const concurrency = yield* resolveConcurrencyLimit2();
2132
- const busyRef = yield* import_effect16.Ref.make(false);
2133
- const mapper = (payload) => import_effect16.Effect.gen(function* () {
2134
- const acquired = yield* import_effect16.Ref.modify(
3187
+ const busyRef = yield* import_effect19.Ref.make(false);
3188
+ const mapper = (payload) => import_effect19.Effect.gen(function* () {
3189
+ const acquired = yield* import_effect19.Ref.modify(
2135
3190
  busyRef,
2136
3191
  (busy) => busy ? [false, busy] : [true, true]
2137
3192
  );
@@ -2146,16 +3201,16 @@ var make3 = (runtime, runtimeInternals) => {
2146
3201
  options
2147
3202
  );
2148
3203
  } finally {
2149
- yield* import_effect16.Ref.set(busyRef, false);
3204
+ yield* import_effect19.Ref.set(busyRef, false);
2150
3205
  }
2151
3206
  });
2152
- return yield* import_effect16.Stream.runDrain(stream.pipe(import_effect16.Stream.mapEffect(mapper, { concurrency })));
3207
+ return yield* import_effect19.Stream.runDrain(stream.pipe(import_effect19.Stream.mapEffect(mapper, { concurrency })));
2153
3208
  })
2154
3209
  };
2155
3210
  };
2156
3211
 
2157
3212
  // src/internal/runtime/core/MatchBuilder.ts
2158
- var import_effect17 = require("effect");
3213
+ var import_effect20 = require("effect");
2159
3214
  var makeMatch = (value) => {
2160
3215
  let result;
2161
3216
  const chain = {
@@ -2174,7 +3229,7 @@ var makeMatch = (value) => {
2174
3229
  if (result) {
2175
3230
  return result;
2176
3231
  }
2177
- return import_effect17.Effect.dieMessage("[FluentMatch] Non-exhaustive match: no pattern matched value");
3232
+ return import_effect20.Effect.dieMessage("[FluentMatch] Non-exhaustive match: no pattern matched value");
2178
3233
  }
2179
3234
  };
2180
3235
  return chain;
@@ -2197,24 +3252,24 @@ var makeMatchTag = (value) => {
2197
3252
  if (result) {
2198
3253
  return result;
2199
3254
  }
2200
- return import_effect17.Effect.dieMessage("[FluentMatchTag] Non-exhaustive match: no tag handler matched value");
3255
+ return import_effect20.Effect.dieMessage("[FluentMatchTag] Non-exhaustive match: no tag handler matched value");
2201
3256
  }
2202
3257
  };
2203
3258
  return chain;
2204
3259
  };
2205
3260
 
2206
3261
  // src/internal/runtime/core/Platform.ts
2207
- var import_effect18 = require("effect");
2208
- var Tag = import_effect18.Context.GenericTag("@logixjs/Platform");
3262
+ var import_effect21 = require("effect");
3263
+ var Tag = import_effect21.Context.GenericTag("@logixjs/Platform");
2209
3264
 
2210
3265
  // src/internal/runtime/core/Lifecycle.ts
2211
- var import_effect19 = require("effect");
2212
- var LifecycleContext = import_effect19.Context.GenericTag("@logixjs/LifecycleManager");
3266
+ var import_effect22 = require("effect");
3267
+ var LifecycleContext = import_effect22.Context.GenericTag("@logixjs/LifecycleManager");
2213
3268
 
2214
3269
  // src/internal/runtime/core/LogicDiagnostics.ts
2215
- var import_effect20 = require("effect");
2216
- var LogicPhaseServiceTag = import_effect20.Context.GenericTag("@logixjs/LogicPhaseService");
2217
- var LogicUnitServiceTag = class extends import_effect20.Context.Tag("@logixjs/LogicUnitService")() {
3270
+ var import_effect23 = require("effect");
3271
+ var LogicPhaseServiceTag = import_effect23.Context.GenericTag("@logixjs/LogicPhaseService");
3272
+ var LogicUnitServiceTag = class extends import_effect23.Context.Tag("@logixjs/LogicUnitService")() {
2218
3273
  };
2219
3274
  var makeLogicPhaseError = (kind, api, phase, moduleId) => Object.assign(new Error(`[LogicPhaseError] ${api} is not allowed in ${phase} phase (kind=${kind}).`), {
2220
3275
  _tag: "LogicPhaseError",
@@ -2225,11 +3280,11 @@ var makeLogicPhaseError = (kind, api, phase, moduleId) => Object.assign(new Erro
2225
3280
  });
2226
3281
 
2227
3282
  // src/internal/root.ts
2228
- var import_effect22 = require("effect");
3283
+ var import_effect25 = require("effect");
2229
3284
 
2230
3285
  // src/internal/runtime/core/RootContext.ts
2231
- var import_effect21 = require("effect");
2232
- var RootContextTagImpl = class extends import_effect21.Context.Tag("@logixjs/core/RootContext")() {
3286
+ var import_effect24 = require("effect");
3287
+ var RootContextTagImpl = class extends import_effect24.Context.Tag("@logixjs/core/RootContext")() {
2233
3288
  };
2234
3289
  var RootContextTag = RootContextTagImpl;
2235
3290
 
@@ -2264,19 +3319,19 @@ ${extra}` : "",
2264
3319
  err.fix = fix;
2265
3320
  return err;
2266
3321
  };
2267
- var resolve2 = (tag, options) => import_effect22.Effect.gen(function* () {
3322
+ var resolve2 = (tag, options) => import_effect25.Effect.gen(function* () {
2268
3323
  const entrypoint = options?.entrypoint ?? "logic.root.resolve";
2269
3324
  const root = yield* RootContextTag;
2270
3325
  const rootContext = root.context ?? (options?.waitForReady ? yield* root.ready : void 0);
2271
3326
  if (!rootContext) {
2272
- return yield* import_effect22.Effect.die(
3327
+ return yield* import_effect25.Effect.die(
2273
3328
  makeMissingRootProviderError(tag, entrypoint, "reason: rootContextNotReady")
2274
3329
  );
2275
3330
  }
2276
3331
  try {
2277
- return import_effect22.Context.get(rootContext, tag);
3332
+ return import_effect25.Context.get(rootContext, tag);
2278
3333
  } catch {
2279
- return yield* import_effect22.Effect.die(makeMissingRootProviderError(tag, entrypoint));
3334
+ return yield* import_effect25.Effect.die(makeMissingRootProviderError(tag, entrypoint));
2280
3335
  }
2281
3336
  });
2282
3337
 
@@ -2346,7 +3401,7 @@ var LogicBuilderFactory = (runtime, runtimeInternals) => {
2346
3401
  debounce: (ms) => LogicBuilderFactory(runtime, runtimeInternals)(flowApi.debounce(ms)(stream), triggerName),
2347
3402
  throttle: (ms) => LogicBuilderFactory(runtime, runtimeInternals)(flowApi.throttle(ms)(stream), triggerName),
2348
3403
  filter: (predicate) => LogicBuilderFactory(runtime, runtimeInternals)(flowApi.filter(predicate)(stream), triggerName),
2349
- map: (f) => LogicBuilderFactory(runtime, runtimeInternals)(stream.pipe(import_effect23.Stream.map(f)), triggerName),
3404
+ map: (f) => LogicBuilderFactory(runtime, runtimeInternals)(stream.pipe(import_effect26.Stream.map(f)), triggerName),
2350
3405
  run(eff, options) {
2351
3406
  return flowApi.run(eff, options)(stream);
2352
3407
  },
@@ -2359,8 +3414,8 @@ var LogicBuilderFactory = (runtime, runtimeInternals) => {
2359
3414
  runParallel(eff, options) {
2360
3415
  return flowApi.runParallel(eff, options)(stream);
2361
3416
  },
2362
- runFork: (eff) => import_effect23.Effect.forkScoped(flowApi.run(eff)(stream)).pipe(import_effect23.Effect.asVoid),
2363
- runParallelFork: (eff) => import_effect23.Effect.forkScoped(flowApi.runParallel(eff)(stream)).pipe(import_effect23.Effect.asVoid),
3417
+ runFork: (eff) => import_effect26.Effect.forkScoped(flowApi.run(eff)(stream)).pipe(import_effect26.Effect.asVoid),
3418
+ runParallelFork: (eff) => import_effect26.Effect.forkScoped(flowApi.runParallel(eff)(stream)).pipe(import_effect26.Effect.asVoid),
2364
3419
  runTask: (config) => makeTaskRunner(stream, "task", taskRunnerRuntime, {
2365
3420
  ...config,
2366
3421
  triggerName: config.triggerName ?? triggerName
@@ -2378,20 +3433,20 @@ var LogicBuilderFactory = (runtime, runtimeInternals) => {
2378
3433
  triggerName: config.triggerName ?? triggerName
2379
3434
  }),
2380
3435
  toStream: () => stream,
2381
- update: (reducer) => import_effect23.Stream.runForEach(
3436
+ update: (reducer) => import_effect26.Stream.runForEach(
2382
3437
  stream,
2383
3438
  (payload) => taskRunnerRuntime.runWithStateTransaction(
2384
3439
  {
2385
3440
  kind: "watcher:update",
2386
3441
  name: triggerName
2387
3442
  },
2388
- () => import_effect23.Effect.gen(function* () {
3443
+ () => import_effect26.Effect.gen(function* () {
2389
3444
  const prev = yield* runtime.getState;
2390
3445
  const next = reducer(prev, payload);
2391
- if (import_effect23.Effect.isEffect(next)) {
2392
- const exit = yield* import_effect23.Effect.exit(next);
3446
+ if (import_effect26.Effect.isEffect(next)) {
3447
+ const exit = yield* import_effect26.Effect.exit(next);
2393
3448
  if (exit._tag === "Failure") {
2394
- yield* import_effect23.Effect.logError("Flow error", exit.cause);
3449
+ yield* import_effect26.Effect.logError("Flow error", exit.cause);
2395
3450
  return;
2396
3451
  }
2397
3452
  yield* runtime.setState(exit.value);
@@ -2400,15 +3455,15 @@ var LogicBuilderFactory = (runtime, runtimeInternals) => {
2400
3455
  yield* runtime.setState(next);
2401
3456
  })
2402
3457
  )
2403
- ).pipe(import_effect23.Effect.catchAllCause((cause) => import_effect23.Effect.logError("Flow error", cause))),
2404
- mutate: (reducer) => import_effect23.Stream.runForEach(
3458
+ ).pipe(import_effect26.Effect.catchAllCause((cause) => import_effect26.Effect.logError("Flow error", cause))),
3459
+ mutate: (reducer) => import_effect26.Stream.runForEach(
2405
3460
  stream,
2406
3461
  (payload) => taskRunnerRuntime.runWithStateTransaction(
2407
3462
  {
2408
3463
  kind: "watcher:mutate",
2409
3464
  name: triggerName
2410
3465
  },
2411
- () => import_effect23.Effect.gen(function* () {
3466
+ () => import_effect26.Effect.gen(function* () {
2412
3467
  const prev = yield* runtime.getState;
2413
3468
  const recordPatch = runtimeInternals.txn.recordStatePatch;
2414
3469
  const updateDraft = runtimeInternals.txn.updateDraft;
@@ -2421,7 +3476,7 @@ var LogicBuilderFactory = (runtime, runtimeInternals) => {
2421
3476
  updateDraft(nextState);
2422
3477
  })
2423
3478
  )
2424
- ).pipe(import_effect23.Effect.catchAllCause((cause) => import_effect23.Effect.logError("Flow error", cause)))
3479
+ ).pipe(import_effect26.Effect.catchAllCause((cause) => import_effect26.Effect.logError("Flow error", cause)))
2425
3480
  };
2426
3481
  const pipe = function() {
2427
3482
  const fns = arguments;
@@ -2451,19 +3506,19 @@ function make4(shape, runtime, options) {
2451
3506
  };
2452
3507
  const flowApi = make3(runtime, runtimeInternals);
2453
3508
  const makeIntentBuilder = (runtime_) => LogicBuilderFactory(runtime_, runtimeInternals);
2454
- const withLifecycle = (available, missing) => import_effect23.Effect.serviceOption(LifecycleContext).pipe(
2455
- import_effect23.Effect.flatMap(
2456
- (maybe) => import_effect23.Option.match(maybe, {
3509
+ const withLifecycle = (available, missing) => import_effect26.Effect.serviceOption(LifecycleContext).pipe(
3510
+ import_effect26.Effect.flatMap(
3511
+ (maybe) => import_effect26.Option.match(maybe, {
2457
3512
  onSome: available,
2458
3513
  onNone: missing
2459
3514
  })
2460
3515
  )
2461
3516
  );
2462
- const withPlatform = (invoke) => import_effect23.Effect.serviceOption(Tag).pipe(
2463
- import_effect23.Effect.flatMap(
2464
- (maybe) => import_effect23.Option.match(maybe, {
3517
+ const withPlatform = (invoke) => import_effect26.Effect.serviceOption(Tag).pipe(
3518
+ import_effect26.Effect.flatMap(
3519
+ (maybe) => import_effect26.Option.match(maybe, {
2465
3520
  onSome: invoke,
2466
- onNone: () => import_effect23.Effect.void
3521
+ onNone: () => import_effect26.Effect.void
2467
3522
  })
2468
3523
  )
2469
3524
  );
@@ -2478,12 +3533,12 @@ function make4(shape, runtime, options) {
2478
3533
  kind: "lifecycle_in_run"
2479
3534
  });
2480
3535
  const createIntentBuilder = (stream, triggerName) => makeIntentBuilder(runtime)(stream, triggerName);
2481
- const onceInRunSession = (key) => import_effect23.Effect.serviceOption(RunSessionTag).pipe(
2482
- import_effect23.Effect.map((maybe) => import_effect23.Option.isSome(maybe) ? maybe.value.local.once(key) : true)
3536
+ const onceInRunSession = (key) => import_effect26.Effect.serviceOption(RunSessionTag).pipe(
3537
+ import_effect26.Effect.map((maybe) => import_effect26.Option.isSome(maybe) ? maybe.value.local.once(key) : true)
2483
3538
  );
2484
3539
  let cachedDiagnosticsLevel;
2485
3540
  const isModuleLike = (value) => Boolean(
2486
- value && typeof value === "object" && (value._kind === "ModuleDef" || value._kind === "Module") && "tag" in value && import_effect23.Context.isTag(value.tag)
3541
+ value && typeof value === "object" && (value._kind === "ModuleDef" || value._kind === "Module") && "tag" in value && import_effect26.Context.isTag(value.tag)
2487
3542
  );
2488
3543
  const buildModuleHandle = (tag, rt) => {
2489
3544
  const actionsProxy = new Proxy(
@@ -2496,7 +3551,7 @@ function make4(shape, runtime, options) {
2496
3551
  }
2497
3552
  );
2498
3553
  const handle = {
2499
- read: (selector) => import_effect23.Effect.map(rt.getState, selector),
3554
+ read: (selector) => import_effect26.Effect.map(rt.getState, selector),
2500
3555
  changes: rt.changes,
2501
3556
  dispatch: rt.dispatch,
2502
3557
  actions$: rt.actions$,
@@ -2506,7 +3561,7 @@ function make4(shape, runtime, options) {
2506
3561
  const extend = tag?.[EXTEND_HANDLE];
2507
3562
  return typeof extend === "function" ? extend(rt, handle) ?? handle : handle;
2508
3563
  };
2509
- const emitModuleDescriptorOnce = (module2, rt) => import_effect23.Effect.gen(function* () {
3564
+ const emitModuleDescriptorOnce = (module2, rt) => import_effect26.Effect.gen(function* () {
2510
3565
  if (cachedDiagnosticsLevel === "off") return;
2511
3566
  const key = `module_descriptor:${String(rt.instanceId ?? "unknown")}`;
2512
3567
  const shouldEmit = yield* onceInRunSession(key);
@@ -2546,7 +3601,7 @@ function make4(shape, runtime, options) {
2546
3601
  data
2547
3602
  });
2548
3603
  });
2549
- const resolveModuleRuntime = (tag) => import_effect23.Effect.gen(function* () {
3604
+ const resolveModuleRuntime = (tag) => import_effect26.Effect.gen(function* () {
2550
3605
  const requestedModuleId = typeof tag?.id === "string" ? tag.id : void 0;
2551
3606
  const fromModuleId = typeof options?.moduleId === "string" ? options.moduleId : runtime.moduleId;
2552
3607
  if (requestedModuleId && requestedModuleId === runtime.moduleId) {
@@ -2557,8 +3612,8 @@ function make4(shape, runtime, options) {
2557
3612
  return fromImports;
2558
3613
  }
2559
3614
  if (typeof options?.moduleId !== "string") {
2560
- const fromEnv = yield* import_effect23.Effect.serviceOption(tag);
2561
- if (import_effect23.Option.isSome(fromEnv)) {
3615
+ const fromEnv = yield* import_effect26.Effect.serviceOption(tag);
3616
+ if (import_effect26.Option.isSome(fromEnv)) {
2562
3617
  return fromEnv.value;
2563
3618
  }
2564
3619
  }
@@ -2593,23 +3648,23 @@ function make4(shape, runtime, options) {
2593
3648
  };
2594
3649
  err.fix = fix;
2595
3650
  err.name = "MissingModuleRuntimeError";
2596
- return yield* import_effect23.Effect.die(err);
3651
+ return yield* import_effect26.Effect.die(err);
2597
3652
  });
2598
3653
  const stateApi = {
2599
3654
  read: runtime.getState,
2600
- update: (f) => import_effect23.Effect.gen(function* () {
2601
- const inTxn = yield* import_effect23.FiberRef.get(inSyncTransactionFiber);
3655
+ update: (f) => import_effect26.Effect.gen(function* () {
3656
+ const inTxn = yield* import_effect26.FiberRef.get(inSyncTransactionFiber);
2602
3657
  if (inTxn) {
2603
3658
  const prev = yield* runtime.getState;
2604
3659
  return yield* runtime.setState(f(prev));
2605
3660
  }
2606
- const body = () => import_effect23.Effect.flatMap(runtime.getState, (prev) => runtime.setState(f(prev)));
3661
+ const body = () => import_effect26.Effect.flatMap(runtime.getState, (prev) => runtime.setState(f(prev)));
2607
3662
  return yield* runtimeInternals ? runtimeInternals.txn.runWithStateTransaction({ kind: "state", name: "update" }, body) : body();
2608
3663
  }),
2609
- mutate: (f) => import_effect23.Effect.gen(function* () {
3664
+ mutate: (f) => import_effect26.Effect.gen(function* () {
2610
3665
  const recordPatch = runtimeInternals?.txn.recordStatePatch;
2611
3666
  const updateDraft = runtimeInternals?.txn.updateDraft;
2612
- const inTxn = yield* import_effect23.FiberRef.get(inSyncTransactionFiber);
3667
+ const inTxn = yield* import_effect26.FiberRef.get(inSyncTransactionFiber);
2613
3668
  if (inTxn) {
2614
3669
  const prev = yield* runtime.getState;
2615
3670
  const { nextState, patchPaths } = mutateWithPatchPaths(prev, (draft) => {
@@ -2621,7 +3676,7 @@ function make4(shape, runtime, options) {
2621
3676
  updateDraft?.(nextState);
2622
3677
  return;
2623
3678
  }
2624
- const body = () => import_effect23.Effect.gen(function* () {
3679
+ const body = () => import_effect26.Effect.gen(function* () {
2625
3680
  const prev = yield* runtime.getState;
2626
3681
  const { nextState, patchPaths } = mutateWithPatchPaths(prev, (draft) => {
2627
3682
  f(draft);
@@ -2670,13 +3725,13 @@ function make4(shape, runtime, options) {
2670
3725
  const matchApi = (value) => makeMatch(value);
2671
3726
  const matchTagApi = (value) => makeMatchTag(value);
2672
3727
  const reducer = (tag, fn) => {
2673
- return import_effect23.Effect.sync(() => {
3728
+ return import_effect26.Effect.sync(() => {
2674
3729
  runtimeInternals.txn.registerReducer(String(tag), fn);
2675
3730
  });
2676
3731
  };
2677
- const effect = (token, handler) => import_effect23.Effect.gen(function* () {
3732
+ const effect = (token, handler) => import_effect26.Effect.gen(function* () {
2678
3733
  if (!isActionToken(token)) {
2679
- return yield* import_effect23.Effect.dieMessage("[BoundApi.effect] token must be an ActionToken");
3734
+ return yield* import_effect26.Effect.dieMessage("[BoundApi.effect] token must be an ActionToken");
2680
3735
  }
2681
3736
  const phase = getCurrentPhase();
2682
3737
  const logicUnit = options?.logicUnit;
@@ -2716,56 +3771,56 @@ function make4(shape, runtime, options) {
2716
3771
  return emitSetupOnlyViolation("$.lifecycle.onInitRequired");
2717
3772
  }
2718
3773
  runtimeInternals.lifecycle.registerInitRequired(eff);
2719
- return import_effect23.Effect.void;
3774
+ return import_effect26.Effect.void;
2720
3775
  },
2721
3776
  onStart: (eff) => {
2722
3777
  if (getCurrentPhase() === "run") {
2723
3778
  return emitSetupOnlyViolation("$.lifecycle.onStart");
2724
3779
  }
2725
3780
  runtimeInternals.lifecycle.registerStart(eff);
2726
- return import_effect23.Effect.void;
3781
+ return import_effect26.Effect.void;
2727
3782
  },
2728
3783
  onInit: (eff) => {
2729
3784
  if (getCurrentPhase() === "run") {
2730
3785
  return emitSetupOnlyViolation("$.lifecycle.onInit");
2731
3786
  }
2732
3787
  runtimeInternals.lifecycle.registerInitRequired(eff);
2733
- return import_effect23.Effect.void;
3788
+ return import_effect26.Effect.void;
2734
3789
  },
2735
3790
  onDestroy: (eff) => {
2736
3791
  if (getCurrentPhase() === "run") {
2737
3792
  return emitSetupOnlyViolation("$.lifecycle.onDestroy");
2738
3793
  }
2739
3794
  runtimeInternals.lifecycle.registerDestroy(eff);
2740
- return import_effect23.Effect.void;
3795
+ return import_effect26.Effect.void;
2741
3796
  },
2742
3797
  onError: (handler) => {
2743
3798
  if (getCurrentPhase() === "run") {
2744
3799
  return emitSetupOnlyViolation("$.lifecycle.onError");
2745
3800
  }
2746
3801
  runtimeInternals.lifecycle.registerOnError(handler);
2747
- return import_effect23.Effect.void;
3802
+ return import_effect26.Effect.void;
2748
3803
  },
2749
3804
  onSuspend: (eff) => {
2750
3805
  if (getCurrentPhase() === "run") {
2751
3806
  return emitSetupOnlyViolation("$.lifecycle.onSuspend");
2752
3807
  }
2753
- runtimeInternals.lifecycle.registerPlatformSuspend(import_effect23.Effect.asVoid(eff));
2754
- return import_effect23.Effect.void;
3808
+ runtimeInternals.lifecycle.registerPlatformSuspend(import_effect26.Effect.asVoid(eff));
3809
+ return import_effect26.Effect.void;
2755
3810
  },
2756
3811
  onResume: (eff) => {
2757
3812
  if (getCurrentPhase() === "run") {
2758
3813
  return emitSetupOnlyViolation("$.lifecycle.onResume");
2759
3814
  }
2760
- runtimeInternals.lifecycle.registerPlatformResume(import_effect23.Effect.asVoid(eff));
2761
- return import_effect23.Effect.void;
3815
+ runtimeInternals.lifecycle.registerPlatformResume(import_effect26.Effect.asVoid(eff));
3816
+ return import_effect26.Effect.void;
2762
3817
  },
2763
3818
  onReset: (eff) => {
2764
3819
  if (getCurrentPhase() === "run") {
2765
3820
  return emitSetupOnlyViolation("$.lifecycle.onReset");
2766
3821
  }
2767
- runtimeInternals.lifecycle.registerPlatformReset(import_effect23.Effect.asVoid(eff));
2768
- return import_effect23.Effect.void;
3822
+ runtimeInternals.lifecycle.registerPlatformReset(import_effect26.Effect.asVoid(eff));
3823
+ return import_effect26.Effect.void;
2769
3824
  }
2770
3825
  },
2771
3826
  traits: {
@@ -2799,14 +3854,14 @@ function make4(shape, runtime, options) {
2799
3854
  });
2800
3855
  },
2801
3856
  source: {
2802
- refresh: (fieldPath, options2) => import_effect23.Effect.gen(function* () {
3857
+ refresh: (fieldPath, options2) => import_effect26.Effect.gen(function* () {
2803
3858
  const handler = runtimeInternals.traits.getSourceRefreshHandler(fieldPath);
2804
3859
  if (!handler) {
2805
- return yield* import_effect23.Effect.void;
3860
+ return yield* import_effect26.Effect.void;
2806
3861
  }
2807
3862
  const force = options2?.force === true;
2808
- const runHandler = (state) => force ? import_effect23.Effect.locally(forceSourceRefresh, true)(handler(state)) : handler(state);
2809
- const inTxn = yield* import_effect23.FiberRef.get(inSyncTransactionFiber);
3863
+ const runHandler = (state) => force ? import_effect26.Effect.locally(forceSourceRefresh, true)(handler(state)) : handler(state);
3864
+ const inTxn = yield* import_effect26.FiberRef.get(inSyncTransactionFiber);
2810
3865
  if (inTxn) {
2811
3866
  const state = yield* runtime.getState;
2812
3867
  return yield* runHandler(state);
@@ -2816,7 +3871,7 @@ function make4(shape, runtime, options) {
2816
3871
  kind: "source-refresh",
2817
3872
  name: fieldPath
2818
3873
  },
2819
- () => import_effect23.Effect.gen(function* () {
3874
+ () => import_effect26.Effect.gen(function* () {
2820
3875
  const state = yield* runtime.getState;
2821
3876
  return yield* runHandler(state);
2822
3877
  })
@@ -2833,18 +3888,18 @@ function make4(shape, runtime, options) {
2833
3888
  if (isModuleLike(arg)) {
2834
3889
  const domain = arg;
2835
3890
  const tag = domain.tag;
2836
- const resolveAndBuild = resolveModuleRuntime(tag).pipe(import_effect23.Effect.map((rt) => buildModuleHandle(tag, rt)));
3891
+ const resolveAndBuild = resolveModuleRuntime(tag).pipe(import_effect26.Effect.map((rt) => buildModuleHandle(tag, rt)));
2837
3892
  const resolveWithDescriptor = resolveModuleRuntime(tag).pipe(
2838
- import_effect23.Effect.tap((rt) => emitModuleDescriptorOnce(domain, rt)),
2839
- import_effect23.Effect.map((rt) => buildModuleHandle(tag, rt))
3893
+ import_effect26.Effect.tap((rt) => emitModuleDescriptorOnce(domain, rt)),
3894
+ import_effect26.Effect.map((rt) => buildModuleHandle(tag, rt))
2840
3895
  );
2841
- const detectAndSelect = import_effect23.FiberRef.get(currentDiagnosticsLevel).pipe(
2842
- import_effect23.Effect.tap((level) => {
3896
+ const detectAndSelect = import_effect26.FiberRef.get(currentDiagnosticsLevel).pipe(
3897
+ import_effect26.Effect.tap((level) => {
2843
3898
  cachedDiagnosticsLevel = level;
2844
3899
  }),
2845
- import_effect23.Effect.flatMap((level) => level === "off" ? resolveAndBuild : resolveWithDescriptor)
3900
+ import_effect26.Effect.flatMap((level) => level === "off" ? resolveAndBuild : resolveWithDescriptor)
2846
3901
  );
2847
- return import_effect23.Effect.suspend(() => {
3902
+ return import_effect26.Effect.suspend(() => {
2848
3903
  if (cachedDiagnosticsLevel === "off") {
2849
3904
  return resolveAndBuild;
2850
3905
  }
@@ -2854,16 +3909,16 @@ function make4(shape, runtime, options) {
2854
3909
  return detectAndSelect;
2855
3910
  });
2856
3911
  }
2857
- if (import_effect23.Context.isTag(arg)) {
3912
+ if (import_effect26.Context.isTag(arg)) {
2858
3913
  const candidate = arg;
2859
3914
  if (candidate._kind === "ModuleTag") {
2860
3915
  return resolveModuleRuntime(arg).pipe(
2861
- import_effect23.Effect.map((rt) => buildModuleHandle(arg, rt))
3916
+ import_effect26.Effect.map((rt) => buildModuleHandle(arg, rt))
2862
3917
  );
2863
3918
  }
2864
3919
  return arg;
2865
3920
  }
2866
- return import_effect23.Effect.die("BoundApi.use: unsupported argument");
3921
+ return import_effect26.Effect.die("BoundApi.use: unsupported argument");
2867
3922
  }
2868
3923
  }),
2869
3924
  onAction: new Proxy(() => {
@@ -2875,33 +3930,33 @@ function make4(shape, runtime, options) {
2875
3930
  const tag = arg.tag;
2876
3931
  return createIntentBuilder(
2877
3932
  runtime.actions$.pipe(
2878
- import_effect23.Stream.filter((a) => a._tag === tag || a.type === tag),
2879
- import_effect23.Stream.map((a) => a.payload)
3933
+ import_effect26.Stream.filter((a) => a._tag === tag || a.type === tag),
3934
+ import_effect26.Stream.map((a) => a.payload)
2880
3935
  ),
2881
3936
  tag
2882
3937
  );
2883
3938
  }
2884
3939
  if (typeof arg === "function") {
2885
- return createIntentBuilder(runtime.actions$.pipe(import_effect23.Stream.filter(arg)));
3940
+ return createIntentBuilder(runtime.actions$.pipe(import_effect26.Stream.filter(arg)));
2886
3941
  }
2887
3942
  if (typeof arg === "string") {
2888
3943
  return createIntentBuilder(
2889
- runtime.actions$.pipe(import_effect23.Stream.filter((a) => a._tag === arg || a.type === arg)),
3944
+ runtime.actions$.pipe(import_effect26.Stream.filter((a) => a._tag === arg || a.type === arg)),
2890
3945
  arg
2891
3946
  );
2892
3947
  }
2893
3948
  if (typeof arg === "object" && arg !== null) {
2894
3949
  if ("_tag" in arg) {
2895
3950
  return createIntentBuilder(
2896
- runtime.actions$.pipe(import_effect23.Stream.filter((a) => a._tag === arg._tag)),
3951
+ runtime.actions$.pipe(import_effect26.Stream.filter((a) => a._tag === arg._tag)),
2897
3952
  String(arg._tag)
2898
3953
  );
2899
3954
  }
2900
- if (import_effect23.Schema.isSchema(arg)) {
3955
+ if (import_effect26.Schema.isSchema(arg)) {
2901
3956
  return createIntentBuilder(
2902
3957
  runtime.actions$.pipe(
2903
- import_effect23.Stream.filter((a) => {
2904
- const result = import_effect23.Schema.decodeUnknownSync(arg)(a);
3958
+ import_effect26.Stream.filter((a) => {
3959
+ const result = import_effect26.Schema.decodeUnknownSync(arg)(a);
2905
3960
  return !!result;
2906
3961
  })
2907
3962
  )
@@ -2914,7 +3969,7 @@ function make4(shape, runtime, options) {
2914
3969
  guardRunOnly("use_in_setup", "$.onAction");
2915
3970
  if (typeof prop === "string") {
2916
3971
  return createIntentBuilder(
2917
- runtime.actions$.pipe(import_effect23.Stream.filter((a) => a._tag === prop || a.type === prop)),
3972
+ runtime.actions$.pipe(import_effect26.Stream.filter((a) => a._tag === prop || a.type === prop)),
2918
3973
  prop
2919
3974
  );
2920
3975
  }
@@ -2935,7 +3990,7 @@ function make4(shape, runtime, options) {
2935
3990
  }
2936
3991
 
2937
3992
  // src/internal/runtime/core/runner/ProgramRunner.closeScope.ts
2938
- var import_effect24 = require("effect");
3993
+ var import_effect27 = require("effect");
2939
3994
 
2940
3995
  // src/internal/runtime/core/runner/ProgramRunner.errors.ts
2941
3996
  var summarizeCause = (cause) => {
@@ -3010,17 +4065,22 @@ var DisposeTimeoutError = class extends ProgramRunnerErrorBase {
3010
4065
 
3011
4066
  // src/internal/runtime/core/runner/ProgramRunner.closeScope.ts
3012
4067
  var closeProgramScope = (params) => {
3013
- return import_effect24.Effect.gen(function* () {
4068
+ return import_effect27.Effect.gen(function* () {
3014
4069
  const start = Date.now();
3015
- const fiber = yield* import_effect24.Effect.forkDaemon(import_effect24.Scope.close(params.scope, import_effect24.Exit.void));
4070
+ const hostSchedulerOpt = yield* import_effect27.Effect.serviceOption(HostSchedulerTag);
4071
+ const hostScheduler = import_effect27.Option.isSome(hostSchedulerOpt) ? hostSchedulerOpt.value : getGlobalHostScheduler();
4072
+ const yieldMicrotask = import_effect27.Effect.async((resume) => {
4073
+ hostScheduler.scheduleMicrotask(() => resume(import_effect27.Effect.void));
4074
+ });
4075
+ const fiber = yield* import_effect27.Effect.forkDaemon(import_effect27.Scope.close(params.scope, import_effect27.Exit.void));
3016
4076
  while (true) {
3017
- const exitOpt = yield* import_effect24.Fiber.poll(fiber);
3018
- if (import_effect24.Option.isSome(exitOpt)) {
4077
+ const exitOpt = yield* import_effect27.Fiber.poll(fiber);
4078
+ if (import_effect27.Option.isSome(exitOpt)) {
3019
4079
  const exit = exitOpt.value;
3020
4080
  if (exit._tag === "Success") {
3021
4081
  return;
3022
4082
  }
3023
- return yield* import_effect24.Effect.die(new DisposeError(params.identity, exit.cause));
4083
+ return yield* import_effect27.Effect.die(new DisposeError(params.identity, exit.cause));
3024
4084
  }
3025
4085
  const elapsedMs = Date.now() - start;
3026
4086
  if (elapsedMs >= params.timeoutMs) {
@@ -3029,18 +4089,18 @@ var closeProgramScope = (params) => {
3029
4089
  elapsedMs
3030
4090
  });
3031
4091
  if (typeof params.onError === "function") {
3032
- yield* params.onError(import_effect24.Cause.die(error)).pipe(import_effect24.Effect.catchAllCause(() => import_effect24.Effect.void));
4092
+ yield* params.onError(import_effect27.Cause.die(error)).pipe(import_effect27.Effect.catchAllCause(() => import_effect27.Effect.void));
3033
4093
  }
3034
- yield* import_effect24.Fiber.interruptFork(fiber);
3035
- return yield* import_effect24.Effect.die(error);
4094
+ yield* import_effect27.Fiber.interruptFork(fiber);
4095
+ return yield* import_effect27.Effect.die(error);
3036
4096
  }
3037
- yield* import_effect24.Effect.promise(() => new Promise((r) => queueMicrotask(r)));
4097
+ yield* yieldMicrotask;
3038
4098
  }
3039
4099
  });
3040
4100
  };
3041
4101
 
3042
4102
  // src/internal/runtime/core/runner/ProgramRunner.signals.ts
3043
- var import_effect25 = require("effect");
4103
+ var import_effect28 = require("effect");
3044
4104
  var getProcess = () => globalThis.process;
3045
4105
  var isNodeProcess = (value) => typeof value === "object" && value !== null && typeof value.on === "function";
3046
4106
  var removeListener = (proc, event, handler) => {
@@ -3054,24 +4114,24 @@ var removeListener = (proc, event, handler) => {
3054
4114
  };
3055
4115
  var installGracefulShutdownHandlers = (params) => {
3056
4116
  if (!params.enabled) {
3057
- return import_effect25.Effect.void;
4117
+ return import_effect28.Effect.void;
3058
4118
  }
3059
4119
  const proc = getProcess();
3060
4120
  if (!isNodeProcess(proc)) {
3061
- return import_effect25.Effect.void;
4121
+ return import_effect28.Effect.void;
3062
4122
  }
3063
4123
  const handler = () => {
3064
- void import_effect25.Effect.runPromise(import_effect25.Scope.close(params.scope, import_effect25.Exit.void));
4124
+ void import_effect28.Effect.runPromise(import_effect28.Scope.close(params.scope, import_effect28.Exit.void));
3065
4125
  };
3066
- return import_effect25.Effect.gen(function* () {
3067
- yield* import_effect25.Scope.addFinalizer(
4126
+ return import_effect28.Effect.gen(function* () {
4127
+ yield* import_effect28.Scope.addFinalizer(
3068
4128
  params.scope,
3069
- import_effect25.Effect.sync(() => {
4129
+ import_effect28.Effect.sync(() => {
3070
4130
  removeListener(proc, "SIGINT", handler);
3071
4131
  removeListener(proc, "SIGTERM", handler);
3072
4132
  })
3073
4133
  );
3074
- yield* import_effect25.Effect.sync(() => {
4134
+ yield* import_effect28.Effect.sync(() => {
3075
4135
  proc.on("SIGINT", handler);
3076
4136
  proc.on("SIGTERM", handler);
3077
4137
  });
@@ -3079,14 +4139,14 @@ var installGracefulShutdownHandlers = (params) => {
3079
4139
  };
3080
4140
 
3081
4141
  // src/internal/runtime/core/runner/ProgramRunner.kernel.ts
3082
- var makeProgramRunnerKernel = (makeRuntime, rootImpl, options) => import_effect26.Effect.gen(function* () {
4142
+ var makeProgramRunnerKernel = (makeRuntime, rootImpl, options) => import_effect29.Effect.gen(function* () {
3083
4143
  const identity = {
3084
4144
  moduleId: String(rootImpl.module.id),
3085
4145
  instanceId: "unknown"
3086
4146
  };
3087
- const scope = yield* import_effect26.Scope.make();
4147
+ const scope = yield* import_effect29.Scope.make();
3088
4148
  const runtime = makeRuntime(rootImpl, options);
3089
- yield* import_effect26.Scope.addFinalizer(scope, import_effect26.Effect.promise(() => runtime.dispose()).pipe(import_effect26.Effect.asVoid));
4149
+ yield* import_effect29.Scope.addFinalizer(scope, import_effect29.Effect.promise(() => runtime.dispose()).pipe(import_effect29.Effect.asVoid));
3090
4150
  const setInstanceId = (value) => {
3091
4151
  identity.instanceId = typeof value === "string" && value.length > 0 ? value : String(value ?? "unknown");
3092
4152
  };
@@ -3115,7 +4175,197 @@ var makeProgramRunnerKernel = (makeRuntime, rootImpl, options) => import_effect2
3115
4175
  });
3116
4176
 
3117
4177
  // src/internal/reflection/manifest.ts
3118
- var import_effect27 = require("effect");
4178
+ var import_effect30 = require("effect");
4179
+
4180
+ // src/internal/external-store-descriptor.ts
4181
+ var EXTERNAL_STORE_DESCRIPTOR = /* @__PURE__ */ Symbol.for("@logixjs/core/externalStoreDescriptor");
4182
+ var getExternalStoreDescriptor = (store) => {
4183
+ if (!store || typeof store !== "object" && typeof store !== "function") return void 0;
4184
+ return store[EXTERNAL_STORE_DESCRIPTOR];
4185
+ };
4186
+
4187
+ // src/internal/state-trait/meta.ts
4188
+ var uniqSortedStrings = (input) => {
4189
+ const set = /* @__PURE__ */ new Set();
4190
+ for (const item of input) {
4191
+ const v = item.trim();
4192
+ if (!v) continue;
4193
+ set.add(v);
4194
+ }
4195
+ return Array.from(set).sort();
4196
+ };
4197
+ var isPlainRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4198
+ var sanitizeJsonValue = (input, depth, stats) => {
4199
+ if (input === null) return null;
4200
+ if (typeof input === "string") return input;
4201
+ if (typeof input === "boolean") return input;
4202
+ if (typeof input === "number") {
4203
+ if (!Number.isFinite(input)) {
4204
+ stats.dropped += 1;
4205
+ stats.nonSerializable += 1;
4206
+ stats.nonFiniteNumber += 1;
4207
+ return void 0;
4208
+ }
4209
+ return input;
4210
+ }
4211
+ if (depth >= 6) {
4212
+ stats.dropped += 1;
4213
+ stats.depthExceeded += 1;
4214
+ return void 0;
4215
+ }
4216
+ if (Array.isArray(input)) {
4217
+ const out = [];
4218
+ for (const item of input) {
4219
+ const v = sanitizeJsonValue(item, depth + 1, stats);
4220
+ if (v !== void 0) out.push(v);
4221
+ }
4222
+ return out;
4223
+ }
4224
+ if (isPlainRecord2(input)) {
4225
+ const keys = Object.keys(input).sort();
4226
+ const out = {};
4227
+ for (const key of keys) {
4228
+ const v = sanitizeJsonValue(input[key], depth + 1, stats);
4229
+ if (v !== void 0) out[key] = v;
4230
+ }
4231
+ return out;
4232
+ }
4233
+ stats.dropped += 1;
4234
+ stats.nonSerializable += 1;
4235
+ return void 0;
4236
+ };
4237
+ var pushSample = (target, value, limit) => {
4238
+ if (target.length >= limit) return;
4239
+ target.push(value);
4240
+ };
4241
+ var sanitizeWithReport = (input) => {
4242
+ if (input === null || input === void 0) return {};
4243
+ if (typeof input !== "object" || Array.isArray(input)) {
4244
+ return { report: { invalidInput: true } };
4245
+ }
4246
+ const record2 = input;
4247
+ const out = {};
4248
+ const reportUnknownKeys = [];
4249
+ let unknownKeyCount = 0;
4250
+ const reportDroppedKeys = [];
4251
+ let droppedTagItems = 0;
4252
+ const reportIgnoredAnnotationKeys = [];
4253
+ let ignoredAnnotationKeyCount = 0;
4254
+ const reportDroppedAnnotationKeys = [];
4255
+ let droppedAnnotationKeyCount = 0;
4256
+ const stats = { dropped: 0, nonSerializable: 0, depthExceeded: 0, nonFiniteNumber: 0 };
4257
+ const allowed = /* @__PURE__ */ new Set([
4258
+ "label",
4259
+ "description",
4260
+ "group",
4261
+ "docsUrl",
4262
+ "cacheGroup",
4263
+ "canonical",
4264
+ "tags",
4265
+ "annotations"
4266
+ ]);
4267
+ for (const key of Object.keys(record2)) {
4268
+ if (allowed.has(key) || key.startsWith("x-")) continue;
4269
+ unknownKeyCount += 1;
4270
+ pushSample(reportUnknownKeys, key, 8);
4271
+ }
4272
+ const pickString = (key) => {
4273
+ const value = record2[key];
4274
+ if (typeof value !== "string") return;
4275
+ const trimmed = value.trim();
4276
+ if (!trimmed) return;
4277
+ out[key] = trimmed;
4278
+ };
4279
+ pickString("label");
4280
+ pickString("description");
4281
+ pickString("group");
4282
+ pickString("docsUrl");
4283
+ pickString("cacheGroup");
4284
+ const canonical = record2.canonical;
4285
+ if (canonical !== void 0 && canonical !== null && typeof canonical !== "boolean") {
4286
+ pushSample(reportDroppedKeys, "canonical", 8);
4287
+ } else if (typeof canonical === "boolean") {
4288
+ out.canonical = canonical;
4289
+ }
4290
+ const tagsRaw = record2.tags;
4291
+ if (typeof tagsRaw === "string") {
4292
+ const tags = uniqSortedStrings([tagsRaw]);
4293
+ if (tags.length > 0) out.tags = tags;
4294
+ } else if (Array.isArray(tagsRaw)) {
4295
+ const raw = tagsRaw.filter((x) => typeof x === "string");
4296
+ droppedTagItems += tagsRaw.length - raw.length;
4297
+ const tags = uniqSortedStrings(raw);
4298
+ if (tags.length > 0) out.tags = tags;
4299
+ droppedTagItems += raw.length - tags.length;
4300
+ } else if (tagsRaw !== void 0 && tagsRaw !== null) {
4301
+ pushSample(reportDroppedKeys, "tags", 8);
4302
+ }
4303
+ const annotations = {};
4304
+ const annotationKeys = Object.keys(record2).filter((k) => k.startsWith("x-")).sort();
4305
+ for (const key of annotationKeys) {
4306
+ const v = sanitizeJsonValue(record2[key], 0, stats);
4307
+ if (v !== void 0) {
4308
+ annotations[key] = v;
4309
+ } else {
4310
+ droppedAnnotationKeyCount += 1;
4311
+ pushSample(reportDroppedAnnotationKeys, key, 8);
4312
+ }
4313
+ }
4314
+ const annotationsRaw = record2.annotations;
4315
+ if (annotationsRaw !== void 0 && annotationsRaw !== null && !isPlainRecord2(annotationsRaw)) {
4316
+ pushSample(reportDroppedKeys, "annotations", 8);
4317
+ } else if (isPlainRecord2(annotationsRaw)) {
4318
+ const keys = Object.keys(annotationsRaw).sort();
4319
+ for (const key of keys) {
4320
+ if (!key.startsWith("x-")) {
4321
+ ignoredAnnotationKeyCount += 1;
4322
+ pushSample(reportIgnoredAnnotationKeys, key, 8);
4323
+ continue;
4324
+ }
4325
+ const v = sanitizeJsonValue(annotationsRaw[key], 0, stats);
4326
+ if (v !== void 0) {
4327
+ annotations[key] = v;
4328
+ } else {
4329
+ droppedAnnotationKeyCount += 1;
4330
+ pushSample(reportDroppedAnnotationKeys, key, 8);
4331
+ }
4332
+ }
4333
+ }
4334
+ if (Object.keys(annotations).length > 0) out.annotations = annotations;
4335
+ for (const key of ["label", "description", "group", "docsUrl", "cacheGroup"]) {
4336
+ const value = record2[key];
4337
+ if (value !== void 0 && value !== null && typeof value !== "string") {
4338
+ pushSample(reportDroppedKeys, key, 8);
4339
+ }
4340
+ }
4341
+ const meta = Object.keys(out).length > 0 ? out : void 0;
4342
+ const report = (() => {
4343
+ const hasUnknownKeys = unknownKeyCount > 0;
4344
+ const hasDroppedKeys = reportDroppedKeys.length > 0;
4345
+ const hasDroppedTagItems = droppedTagItems > 0;
4346
+ const hasIgnoredAnnotationKeys = ignoredAnnotationKeyCount > 0;
4347
+ const hasDroppedAnnotations = droppedAnnotationKeyCount > 0 || stats.dropped > 0;
4348
+ if (!hasUnknownKeys && !hasDroppedKeys && !hasDroppedTagItems && !hasIgnoredAnnotationKeys && !hasDroppedAnnotations) {
4349
+ return void 0;
4350
+ }
4351
+ return {
4352
+ ...hasUnknownKeys ? { unknownKeys: reportUnknownKeys, unknownKeyCount } : {},
4353
+ ...hasDroppedKeys ? { droppedKeys: uniqSortedStrings(reportDroppedKeys) } : {},
4354
+ ...hasDroppedTagItems ? { droppedTagItems } : {},
4355
+ ...hasIgnoredAnnotationKeys ? { ignoredAnnotationKeys: uniqSortedStrings(reportIgnoredAnnotationKeys), ignoredAnnotationKeyCount } : {},
4356
+ ...hasDroppedAnnotations ? {
4357
+ droppedAnnotationKeys: uniqSortedStrings(reportDroppedAnnotationKeys),
4358
+ droppedAnnotationKeyCount,
4359
+ droppedAnnotationValues: stats.dropped,
4360
+ droppedAnnotationNonSerializable: stats.nonSerializable,
4361
+ droppedAnnotationDepthExceeded: stats.depthExceeded,
4362
+ droppedAnnotationNonFiniteNumber: stats.nonFiniteNumber
4363
+ } : {}
4364
+ };
4365
+ })();
4366
+ return report ? { meta, report } : { meta };
4367
+ };
4368
+ var sanitize = (input) => sanitizeWithReport(input).meta;
3119
4369
 
3120
4370
  // src/internal/state-trait/ir.ts
3121
4371
  var normalizeFieldPaths = (paths) => {
@@ -3136,6 +4386,8 @@ var toNodeKind = (step) => {
3136
4386
  return "link";
3137
4387
  case "source-refresh":
3138
4388
  return "source";
4389
+ case "external-store-sync":
4390
+ return "externalStore";
3139
4391
  case "check-validate":
3140
4392
  return "check";
3141
4393
  }
@@ -3160,6 +4412,9 @@ var getReadsForEntry = (entry) => {
3160
4412
  const from = entry.meta.from;
3161
4413
  return from ? [from] : [];
3162
4414
  }
4415
+ if (entry.kind === "externalStore") {
4416
+ return [];
4417
+ }
3163
4418
  if (entry.kind === "check") {
3164
4419
  const rules = entry.meta?.rules ?? {};
3165
4420
  const out = [];
@@ -3207,11 +4462,40 @@ var exportStaticIr = (params) => {
3207
4462
  const write = normalizeFieldPath2(target);
3208
4463
  const writes = write ? [write] : [];
3209
4464
  const meta = target ? metaByField.get(target) : void 0;
4465
+ const externalStorePolicy = () => {
4466
+ if (kind !== "externalStore") return void 0;
4467
+ if (!entry || entry.kind !== "externalStore") return void 0;
4468
+ const descriptor = getExternalStoreDescriptor(entry.meta.store);
4469
+ const storeId = descriptor?.storeId;
4470
+ const priorityRaw = entry.meta?.priority;
4471
+ const lane = priorityRaw === "nonUrgent" ? "nonUrgent" : "urgent";
4472
+ const meta2 = sanitize(entry.meta.meta);
4473
+ const source = descriptor?.kind === "module" ? {
4474
+ kind: "module",
4475
+ storeId,
4476
+ moduleId: descriptor.moduleId,
4477
+ ...descriptor.instanceId ? { instanceKey: descriptor.instanceId } : {},
4478
+ selectorId: descriptor.readQuery.staticIr.selectorId,
4479
+ readsDigest: descriptor.readQuery.staticIr.readsDigest,
4480
+ fallbackReason: descriptor.readQuery.staticIr.fallbackReason
4481
+ } : descriptor ? { kind: "external", storeId } : { kind: "external", storeId: "unknown" };
4482
+ const coalesceWindowMs = entry.meta?.coalesceWindowMs;
4483
+ return {
4484
+ traitId: step.id,
4485
+ storeId: storeId ?? "unknown",
4486
+ source,
4487
+ ownership: "external-owned",
4488
+ lane,
4489
+ ...typeof coalesceWindowMs === "number" && Number.isFinite(coalesceWindowMs) && coalesceWindowMs > 0 ? { coalesceWindowMs } : {},
4490
+ ...meta2 ? { meta: meta2 } : {}
4491
+ };
4492
+ };
3210
4493
  const base2 = {
3211
4494
  nodeId: step.id,
3212
4495
  kind,
3213
4496
  reads,
3214
4497
  writes: kind === "check" ? [] : writes,
4498
+ ...kind === "externalStore" ? { policy: externalStorePolicy() } : {},
3215
4499
  meta
3216
4500
  };
3217
4501
  if (kind !== "check" && target && !write) {
@@ -3323,7 +4607,7 @@ var resolveActions = (input) => {
3323
4607
  for (const actionTag of actionTags) {
3324
4608
  const token = actionMap[actionTag];
3325
4609
  const source = resolveTokenSource(token) ?? moduleSource;
3326
- const payloadKind = isActionToken(token) && import_effect27.Schema.isSchema(token.schema) ? token.schema === import_effect27.Schema.Void ? "void" : "nonVoid" : "unknown";
4610
+ const payloadKind = isActionToken(token) && import_effect30.Schema.isSchema(token.schema) ? token.schema === import_effect30.Schema.Void ? "void" : "nonVoid" : "unknown";
3327
4611
  const primaryReducer = reducers && typeof reducers[actionTag] === "function" ? { kind: "declared" } : void 0;
3328
4612
  out.push({
3329
4613
  actionTag,
@@ -3376,7 +4660,7 @@ var resolveEffects = (input) => {
3376
4660
  deduped.push(item);
3377
4661
  }
3378
4662
  deduped.sort(
3379
- (a, b) => a.actionTag < b.actionTag ? -1 : a.actionTag > b.actionTag ? 1 : a.sourceKey.localeCompare(b.sourceKey)
4663
+ (a, b) => a.actionTag < b.actionTag ? -1 : a.actionTag > b.actionTag ? 1 : a.sourceKey < b.sourceKey ? -1 : a.sourceKey > b.sourceKey ? 1 : 0
3380
4664
  );
3381
4665
  return deduped.length > 0 ? deduped : void 0;
3382
4666
  };
@@ -3421,7 +4705,7 @@ var resolveLogicUnits = (input) => {
3421
4705
  const name = typeof unit.name === "string" ? unit.name : void 0;
3422
4706
  out.push({ kind, id, derived, name });
3423
4707
  }
3424
- out.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : a.kind.localeCompare(b.kind));
4708
+ out.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : a.kind < b.kind ? -1 : a.kind > b.kind ? 1 : 0);
3425
4709
  return out.length > 0 ? out : void 0;
3426
4710
  };
3427
4711
  var digestOf = (base) => `manifest:067:${fnv1a32(stableStringify(base))}`;
@@ -3556,13 +4840,13 @@ var extractManifest = (module2, options) => {
3556
4840
  };
3557
4841
 
3558
4842
  // src/internal/runtime/Runtime.ts
3559
- var import_effect31 = require("effect");
4843
+ var import_effect34 = require("effect");
3560
4844
 
3561
4845
  // src/internal/runtime/AppRuntime.ts
3562
- var import_effect30 = require("effect");
4846
+ var import_effect33 = require("effect");
3563
4847
 
3564
- // src/internal/runtime/core/process/ProcessRuntime.ts
3565
- var import_effect29 = require("effect");
4848
+ // src/internal/runtime/core/process/ProcessRuntime.make.ts
4849
+ var import_effect32 = require("effect");
3566
4850
 
3567
4851
  // src/internal/runtime/core/process/identity.ts
3568
4852
  var scopeKeyFromScope = (scope) => {
@@ -3582,7 +4866,7 @@ var processInstanceIdFromIdentity = (identity) => {
3582
4866
  };
3583
4867
 
3584
4868
  // src/internal/runtime/core/process/concurrency.ts
3585
- var import_effect28 = require("effect");
4869
+ var import_effect31 = require("effect");
3586
4870
  var DEFAULT_SERIAL_QUEUE_GUARD_LIMIT = 4096;
3587
4871
  var DEFAULT_PARALLEL_LIMIT = 16;
3588
4872
  var resolveQueueLimit = (maxQueue, options) => {
@@ -3593,37 +4877,37 @@ var resolveQueueLimit = (maxQueue, options) => {
3593
4877
  guard: configured === "unbounded" ? defaultGuard : configured
3594
4878
  };
3595
4879
  };
3596
- var runProcessTriggerStream = (args) => import_effect28.Effect.gen(function* () {
4880
+ var runProcessTriggerStream = (args) => import_effect31.Effect.gen(function* () {
3597
4881
  const policy = args.policy;
3598
4882
  const defaultQueueGuard = args.defaultQueueGuard ?? DEFAULT_SERIAL_QUEUE_GUARD_LIMIT;
3599
4883
  if (policy.mode === "latest") {
3600
- const stateRef = yield* import_effect28.Ref.make({ fiber: void 0, runningId: 0, nextId: 0 });
3601
- const onTrigger2 = (trigger0) => import_effect28.Effect.gen(function* () {
4884
+ const stateRef = yield* import_effect31.Ref.make({ fiber: void 0, runningId: 0, nextId: 0 });
4885
+ const onTrigger2 = (trigger0) => import_effect31.Effect.gen(function* () {
3602
4886
  const trigger = args.assignTriggerSeq(trigger0);
3603
- const [prevFiber, prevRunningId, runId] = yield* import_effect28.Ref.modify(stateRef, (s) => {
4887
+ const [prevFiber, prevRunningId, runId] = yield* import_effect31.Ref.modify(stateRef, (s) => {
3604
4888
  const nextId = s.nextId + 1;
3605
4889
  return [[s.fiber, s.runningId, nextId], { ...s, nextId, runningId: nextId }];
3606
4890
  });
3607
4891
  if (prevFiber && prevRunningId !== 0) {
3608
- const done = yield* import_effect28.Fiber.poll(prevFiber);
3609
- if (import_effect28.Option.isNone(done)) {
3610
- yield* import_effect28.Fiber.interruptFork(prevFiber);
4892
+ const done = yield* import_effect31.Fiber.poll(prevFiber);
4893
+ if (import_effect31.Option.isNone(done)) {
4894
+ yield* import_effect31.Fiber.interruptFork(prevFiber);
3611
4895
  }
3612
4896
  }
3613
- const fiber = yield* import_effect28.Effect.forkScoped(
3614
- args.run(trigger).pipe(import_effect28.Effect.ensuring(import_effect28.Ref.update(stateRef, (s) => s.runningId === runId ? { ...s, runningId: 0 } : s)))
4897
+ const fiber = yield* import_effect31.Effect.forkScoped(
4898
+ args.run(trigger).pipe(import_effect31.Effect.ensuring(import_effect31.Ref.update(stateRef, (s) => s.runningId === runId ? { ...s, runningId: 0 } : s)))
3615
4899
  );
3616
- yield* import_effect28.Ref.update(stateRef, (s) => ({ ...s, fiber }));
4900
+ yield* import_effect31.Ref.update(stateRef, (s) => ({ ...s, fiber }));
3617
4901
  });
3618
- return yield* import_effect28.Stream.runForEach(args.stream, onTrigger2);
4902
+ return yield* import_effect31.Stream.runForEach(args.stream, onTrigger2);
3619
4903
  }
3620
- const busyRef = yield* import_effect28.Ref.make(false);
3621
- const serialStateRef = yield* import_effect28.Ref.make({
4904
+ const busyRef = yield* import_effect31.Ref.make(false);
4905
+ const serialStateRef = yield* import_effect31.Ref.make({
3622
4906
  running: false,
3623
4907
  queue: [],
3624
4908
  peak: 0
3625
4909
  });
3626
- const parallelStateRef = yield* import_effect28.Ref.make({
4910
+ const parallelStateRef = yield* import_effect31.Ref.make({
3627
4911
  active: 0,
3628
4912
  queue: [],
3629
4913
  peak: 0
@@ -3631,57 +4915,57 @@ var runProcessTriggerStream = (args) => import_effect28.Effect.gen(function* ()
3631
4915
  const serialQueueLimit = resolveQueueLimit(policy.maxQueue, { defaultGuard: defaultQueueGuard });
3632
4916
  const parallelQueueLimit = resolveQueueLimit(void 0, { defaultGuard: defaultQueueGuard });
3633
4917
  const parallelLimit = typeof policy.maxParallel === "number" && Number.isFinite(policy.maxParallel) && policy.maxParallel >= 1 ? Math.floor(policy.maxParallel) : args.defaultParallelLimit ?? DEFAULT_PARALLEL_LIMIT;
3634
- const drainSerial = () => import_effect28.Effect.suspend(
3635
- () => import_effect28.Ref.modify(serialStateRef, (state) => {
4918
+ const drainSerial = () => import_effect31.Effect.suspend(
4919
+ () => import_effect31.Ref.modify(serialStateRef, (state) => {
3636
4920
  if (state.running || state.queue.length === 0) {
3637
- return [import_effect28.Option.none(), state];
4921
+ return [import_effect31.Option.none(), state];
3638
4922
  }
3639
4923
  const [next, ...rest] = state.queue;
3640
- return [import_effect28.Option.some(next), { ...state, running: true, queue: rest }];
4924
+ return [import_effect31.Option.some(next), { ...state, running: true, queue: rest }];
3641
4925
  }).pipe(
3642
- import_effect28.Effect.flatMap(
3643
- (next) => import_effect28.Option.match(next, {
3644
- onNone: () => import_effect28.Effect.void,
3645
- onSome: (trigger) => import_effect28.Effect.forkScoped(
4926
+ import_effect31.Effect.flatMap(
4927
+ (next) => import_effect31.Option.match(next, {
4928
+ onNone: () => import_effect31.Effect.void,
4929
+ onSome: (trigger) => import_effect31.Effect.forkScoped(
3646
4930
  args.run(trigger).pipe(
3647
- import_effect28.Effect.ensuring(import_effect28.Ref.update(serialStateRef, (s) => ({ ...s, running: false }))),
3648
- import_effect28.Effect.zipRight(drainSerial())
4931
+ import_effect31.Effect.ensuring(import_effect31.Ref.update(serialStateRef, (s) => ({ ...s, running: false }))),
4932
+ import_effect31.Effect.zipRight(drainSerial())
3649
4933
  )
3650
- ).pipe(import_effect28.Effect.asVoid)
4934
+ ).pipe(import_effect31.Effect.asVoid)
3651
4935
  })
3652
4936
  )
3653
4937
  )
3654
4938
  );
3655
- const drainParallel = () => import_effect28.Effect.suspend(
3656
- () => import_effect28.Ref.modify(parallelStateRef, (state) => {
4939
+ const drainParallel = () => import_effect31.Effect.suspend(
4940
+ () => import_effect31.Ref.modify(parallelStateRef, (state) => {
3657
4941
  if (state.active >= parallelLimit || state.queue.length === 0) {
3658
- return [import_effect28.Option.none(), state];
4942
+ return [import_effect31.Option.none(), state];
3659
4943
  }
3660
4944
  const [next, ...rest] = state.queue;
3661
- return [import_effect28.Option.some(next), { ...state, active: state.active + 1, queue: rest }];
4945
+ return [import_effect31.Option.some(next), { ...state, active: state.active + 1, queue: rest }];
3662
4946
  }).pipe(
3663
- import_effect28.Effect.flatMap(
3664
- (next) => import_effect28.Option.match(next, {
3665
- onNone: () => import_effect28.Effect.void,
3666
- onSome: (trigger) => import_effect28.Effect.forkScoped(
4947
+ import_effect31.Effect.flatMap(
4948
+ (next) => import_effect31.Option.match(next, {
4949
+ onNone: () => import_effect31.Effect.void,
4950
+ onSome: (trigger) => import_effect31.Effect.forkScoped(
3667
4951
  args.run(trigger).pipe(
3668
- import_effect28.Effect.ensuring(
3669
- import_effect28.Ref.update(parallelStateRef, (s) => ({
4952
+ import_effect31.Effect.ensuring(
4953
+ import_effect31.Ref.update(parallelStateRef, (s) => ({
3670
4954
  ...s,
3671
4955
  active: Math.max(0, s.active - 1)
3672
4956
  }))
3673
4957
  ),
3674
- import_effect28.Effect.zipRight(drainParallel())
4958
+ import_effect31.Effect.zipRight(drainParallel())
3675
4959
  )
3676
- ).pipe(import_effect28.Effect.asVoid, import_effect28.Effect.zipRight(drainParallel()))
4960
+ ).pipe(import_effect31.Effect.asVoid, import_effect31.Effect.zipRight(drainParallel()))
3677
4961
  })
3678
4962
  )
3679
4963
  )
3680
4964
  );
3681
- const onTrigger = (trigger0) => import_effect28.Effect.gen(function* () {
4965
+ const onTrigger = (trigger0) => import_effect31.Effect.gen(function* () {
3682
4966
  const trigger = args.assignTriggerSeq(trigger0);
3683
4967
  if (policy.mode === "drop") {
3684
- const acquired = yield* import_effect28.Ref.modify(
4968
+ const acquired = yield* import_effect31.Ref.modify(
3685
4969
  busyRef,
3686
4970
  (busy) => busy ? [false, busy] : [true, true]
3687
4971
  );
@@ -3689,16 +4973,16 @@ var runProcessTriggerStream = (args) => import_effect28.Effect.gen(function* ()
3689
4973
  yield* args.onDrop(trigger);
3690
4974
  return;
3691
4975
  }
3692
- yield* import_effect28.Effect.forkScoped(args.run(trigger).pipe(import_effect28.Effect.ensuring(import_effect28.Ref.set(busyRef, false))));
4976
+ yield* import_effect31.Effect.forkScoped(args.run(trigger).pipe(import_effect31.Effect.ensuring(import_effect31.Ref.set(busyRef, false))));
3693
4977
  return;
3694
4978
  }
3695
4979
  if (policy.mode === "parallel") {
3696
- const nextSize2 = yield* import_effect28.Ref.modify(parallelStateRef, (state) => {
4980
+ const nextSize2 = yield* import_effect31.Ref.modify(parallelStateRef, (state) => {
3697
4981
  const queue = [...state.queue, trigger];
3698
4982
  return [queue.length, { ...state, queue, peak: Math.max(state.peak, queue.length) }];
3699
4983
  });
3700
4984
  if (nextSize2 > parallelQueueLimit.guard) {
3701
- const state = yield* import_effect28.Ref.get(parallelStateRef);
4985
+ const state = yield* import_effect31.Ref.get(parallelStateRef);
3702
4986
  yield* args.onQueueOverflow({
3703
4987
  mode: "parallel",
3704
4988
  currentLength: nextSize2,
@@ -3711,12 +4995,12 @@ var runProcessTriggerStream = (args) => import_effect28.Effect.gen(function* ()
3711
4995
  yield* drainParallel();
3712
4996
  return;
3713
4997
  }
3714
- const nextSize = yield* import_effect28.Ref.modify(serialStateRef, (state) => {
4998
+ const nextSize = yield* import_effect31.Ref.modify(serialStateRef, (state) => {
3715
4999
  const queue = [...state.queue, trigger];
3716
5000
  return [queue.length, { ...state, queue, peak: Math.max(state.peak, queue.length) }];
3717
5001
  });
3718
5002
  if (nextSize > serialQueueLimit.guard) {
3719
- const state = yield* import_effect28.Ref.get(serialStateRef);
5003
+ const state = yield* import_effect31.Ref.get(serialStateRef);
3720
5004
  yield* args.onQueueOverflow({
3721
5005
  mode: "serial",
3722
5006
  currentLength: nextSize,
@@ -3728,7 +5012,7 @@ var runProcessTriggerStream = (args) => import_effect28.Effect.gen(function* ()
3728
5012
  }
3729
5013
  yield* drainSerial();
3730
5014
  });
3731
- return yield* import_effect28.Stream.runForEach(args.stream, onTrigger);
5015
+ return yield* import_effect31.Stream.runForEach(args.stream, onTrigger);
3732
5016
  });
3733
5017
 
3734
5018
  // src/internal/runtime/core/process/events.ts
@@ -4103,11 +5387,11 @@ var onFailure = (policy, state, nowMs) => {
4103
5387
  };
4104
5388
  };
4105
5389
 
4106
- // src/internal/runtime/core/process/ProcessRuntime.ts
4107
- var ProcessRuntimeTag = class extends import_effect29.Context.Tag("@logixjs/core/ProcessRuntime")() {
5390
+ // src/internal/runtime/core/process/ProcessRuntime.make.ts
5391
+ var ProcessRuntimeTag = class extends import_effect32.Context.Tag("@logixjs/core/ProcessRuntime")() {
4108
5392
  };
4109
- var currentProcessTrigger = import_effect29.FiberRef.unsafeMake(void 0);
4110
- var currentProcessEventBudget = import_effect29.FiberRef.unsafeMake(
5393
+ var currentProcessTrigger = import_effect32.FiberRef.unsafeMake(void 0);
5394
+ var currentProcessEventBudget = import_effect32.FiberRef.unsafeMake(
4111
5395
  void 0
4112
5396
  );
4113
5397
  var RUNTIME_BOOT_EVENT = "runtime:boot";
@@ -4166,13 +5450,13 @@ var actionIdFromUnknown = (action) => {
4166
5450
  if (typeof anyAction.type === "string" && anyAction.type.length > 0) return anyAction.type;
4167
5451
  return void 0;
4168
5452
  };
4169
- var make5 = (options) => import_effect29.Effect.gen(function* () {
4170
- const runtimeScope = yield* import_effect29.Effect.scope;
5453
+ var make5 = (options) => import_effect32.Effect.gen(function* () {
5454
+ const runtimeScope = yield* import_effect32.Effect.scope;
4171
5455
  const maxEventHistory = typeof options?.maxEventHistory === "number" && Number.isFinite(options.maxEventHistory) && options.maxEventHistory >= 0 ? Math.floor(options.maxEventHistory) : 500;
4172
5456
  const installations = /* @__PURE__ */ new Map();
4173
5457
  const instances = /* @__PURE__ */ new Map();
4174
5458
  const eventsBuffer = [];
4175
- const eventsHub = yield* import_effect29.PubSub.sliding(Math.max(1, Math.min(2048, maxEventHistory)));
5459
+ const eventsHub = yield* import_effect32.PubSub.sliding(Math.max(1, Math.min(2048, maxEventHistory)));
4176
5460
  const trimEvents = () => {
4177
5461
  if (maxEventHistory <= 0) {
4178
5462
  eventsBuffer.length = 0;
@@ -4182,8 +5466,8 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4182
5466
  const excess = eventsBuffer.length - maxEventHistory;
4183
5467
  eventsBuffer.splice(0, excess);
4184
5468
  };
4185
- const recordDebugEvent = (event) => import_effect29.Effect.gen(function* () {
4186
- const diagnosticsLevel2 = yield* import_effect29.FiberRef.get(currentDiagnosticsLevel);
5469
+ const recordDebugEvent = (event) => import_effect32.Effect.gen(function* () {
5470
+ const diagnosticsLevel2 = yield* import_effect32.FiberRef.get(currentDiagnosticsLevel);
4187
5471
  if (diagnosticsLevel2 === "off") {
4188
5472
  return;
4189
5473
  }
@@ -4206,16 +5490,16 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4206
5490
  txnId
4207
5491
  });
4208
5492
  });
4209
- const publishEvent = (event) => import_effect29.Effect.gen(function* () {
5493
+ const publishEvent = (event) => import_effect32.Effect.gen(function* () {
4210
5494
  eventsBuffer.push(event);
4211
5495
  trimEvents();
4212
- yield* import_effect29.PubSub.publish(eventsHub, event);
5496
+ yield* import_effect32.PubSub.publish(eventsHub, event);
4213
5497
  yield* recordDebugEvent(event);
4214
5498
  });
4215
- const emit = (event) => import_effect29.Effect.gen(function* () {
4216
- const budgetRef = yield* import_effect29.FiberRef.get(currentProcessEventBudget);
5499
+ const emit = (event) => import_effect32.Effect.gen(function* () {
5500
+ const budgetRef = yield* import_effect32.FiberRef.get(currentProcessEventBudget);
4217
5501
  if (budgetRef) {
4218
- const decision = yield* import_effect29.Ref.modify(budgetRef, (state) => {
5502
+ const decision = yield* import_effect32.Ref.modify(budgetRef, (state) => {
4219
5503
  const [nextDecision, nextState] = applyProcessRunEventBudget(state, event);
4220
5504
  return [nextDecision, nextState];
4221
5505
  });
@@ -4229,7 +5513,7 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4229
5513
  });
4230
5514
  const emitErrorDiagnostic = (scope, processId, code, message, hint) => {
4231
5515
  if (!isDevEnv()) {
4232
- return import_effect29.Effect.void;
5516
+ return import_effect32.Effect.void;
4233
5517
  }
4234
5518
  const moduleId = scope.type === "moduleInstance" ? scope.moduleId : void 0;
4235
5519
  const instanceId = scope.type === "moduleInstance" ? scope.instanceId : void 0;
@@ -4258,15 +5542,15 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4258
5542
  const missing = [];
4259
5543
  for (const dep of requires) {
4260
5544
  if (typeof dep !== "string" || dep.length === 0) continue;
4261
- const tag = import_effect29.Context.Tag(`@logixjs/Module/${dep}`)();
4262
- const found = import_effect29.Context.getOption(installation.env, tag);
4263
- if (import_effect29.Option.isNone(found)) {
5545
+ const tag = import_effect32.Context.Tag(`@logixjs/Module/${dep}`)();
5546
+ const found = import_effect32.Context.getOption(installation.env, tag);
5547
+ if (import_effect32.Option.isNone(found)) {
4264
5548
  missing.push(dep);
4265
5549
  }
4266
5550
  }
4267
5551
  return missing;
4268
5552
  };
4269
- const stopInstance = (instance, reason) => import_effect29.Effect.gen(function* () {
5553
+ const stopInstance = (instance, reason) => import_effect32.Effect.gen(function* () {
4270
5554
  if (instance.status.status === "stopped" || instance.status.status === "failed" || instance.status.status === "stopping") {
4271
5555
  return;
4272
5556
  }
@@ -4277,9 +5561,9 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4277
5561
  stoppedReason: reason
4278
5562
  };
4279
5563
  if (fiber) {
4280
- yield* import_effect29.Fiber.interrupt(fiber);
5564
+ yield* import_effect32.Fiber.interrupt(fiber);
4281
5565
  }
4282
- yield* import_effect29.Queue.shutdown(instance.platformTriggersQueue);
5566
+ yield* import_effect32.Queue.shutdown(instance.platformTriggersQueue);
4283
5567
  instance.status = {
4284
5568
  ...instance.status,
4285
5569
  status: "stopped",
@@ -4300,7 +5584,7 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4300
5584
  yield* startInstallation(instance.installationKey);
4301
5585
  }
4302
5586
  });
4303
- const startInstallation = (installationKey) => import_effect29.Effect.gen(function* () {
5587
+ const startInstallation = (installationKey) => import_effect32.Effect.gen(function* () {
4304
5588
  const installation = installations.get(installationKey);
4305
5589
  if (!installation) return;
4306
5590
  installation.pendingStart = void 0;
@@ -4319,7 +5603,7 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4319
5603
  runSeq
4320
5604
  };
4321
5605
  const processInstanceId = processInstanceIdFromIdentity(identity);
4322
- const platformTriggersQueue = yield* import_effect29.Queue.sliding(64);
5606
+ const platformTriggersQueue = yield* import_effect32.Queue.sliding(64);
4323
5607
  const instanceState = {
4324
5608
  installationKey,
4325
5609
  processInstanceId,
@@ -4338,15 +5622,15 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4338
5622
  instances.set(processInstanceId, instanceState);
4339
5623
  installation.currentInstanceId = processInstanceId;
4340
5624
  if (installation.forkScope !== runtimeScope) {
4341
- yield* import_effect29.Scope.addFinalizer(
5625
+ yield* import_effect32.Scope.addFinalizer(
4342
5626
  installation.forkScope,
4343
- import_effect29.Effect.suspend(() => {
5627
+ import_effect32.Effect.suspend(() => {
4344
5628
  const status = instanceState.status.status;
4345
5629
  if (status === "stopped" || status === "failed" || status === "stopping") {
4346
- return import_effect29.Effect.void;
5630
+ return import_effect32.Effect.void;
4347
5631
  }
4348
5632
  return stopInstance(instanceState, "scopeDisposed");
4349
- }).pipe(import_effect29.Effect.catchAllCause(() => import_effect29.Effect.void))
5633
+ }).pipe(import_effect32.Effect.catchAllCause(() => import_effect32.Effect.void))
4350
5634
  );
4351
5635
  }
4352
5636
  yield* emit({
@@ -4409,12 +5693,12 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4409
5693
  let nextEnv = baseEnv;
4410
5694
  for (const moduleId of ids) {
4411
5695
  if (typeof moduleId !== "string" || moduleId.length === 0) continue;
4412
- const tag = import_effect29.Context.Tag(`@logixjs/Module/${moduleId}`)();
4413
- const found = import_effect29.Context.getOption(baseEnv, tag);
4414
- if (import_effect29.Option.isNone(found)) continue;
5696
+ const tag = import_effect32.Context.Tag(`@logixjs/Module/${moduleId}`)();
5697
+ const found = import_effect32.Context.getOption(baseEnv, tag);
5698
+ if (import_effect32.Option.isNone(found)) continue;
4415
5699
  const runtime = found.value;
4416
- const recordDispatch = (action) => import_effect29.Effect.gen(function* () {
4417
- const trigger = yield* import_effect29.FiberRef.get(currentProcessTrigger);
5700
+ const recordDispatch = (action) => import_effect32.Effect.gen(function* () {
5701
+ const trigger = yield* import_effect32.FiberRef.get(currentProcessTrigger);
4418
5702
  if (!trigger) return;
4419
5703
  const actionId = actionIdFromUnknown(action) ?? "unknown";
4420
5704
  const dispatchModuleId = typeof runtime.moduleId === "string" ? runtime.moduleId : moduleId;
@@ -4436,27 +5720,27 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4436
5720
  });
4437
5721
  const wrapped = {
4438
5722
  ...runtime,
4439
- dispatch: (action) => runtime.dispatch(action).pipe(import_effect29.Effect.tap(() => recordDispatch(action))),
4440
- dispatchLowPriority: (action) => runtime.dispatchLowPriority(action).pipe(import_effect29.Effect.tap(() => recordDispatch(action))),
4441
- dispatchBatch: (actions) => runtime.dispatchBatch(actions).pipe(import_effect29.Effect.tap(() => import_effect29.Effect.forEach(actions, recordDispatch, { discard: true })))
5723
+ dispatch: (action) => runtime.dispatch(action).pipe(import_effect32.Effect.tap(() => recordDispatch(action))),
5724
+ dispatchLowPriority: (action) => runtime.dispatchLowPriority(action).pipe(import_effect32.Effect.tap(() => recordDispatch(action))),
5725
+ dispatchBatch: (actions) => runtime.dispatchBatch(actions).pipe(import_effect32.Effect.tap(() => import_effect32.Effect.forEach(actions, recordDispatch, { discard: true })))
4442
5726
  };
4443
- nextEnv = import_effect29.Context.add(tag, wrapped)(nextEnv);
5727
+ nextEnv = import_effect32.Context.add(tag, wrapped)(nextEnv);
4444
5728
  }
4445
5729
  return nextEnv;
4446
5730
  };
4447
5731
  const wrappedEnv = makeWrappedEnv();
4448
- const providedProcess = import_effect29.Effect.provide(installation.process, wrappedEnv);
4449
- const makeTriggerStream = (spec) => import_effect29.Effect.gen(function* () {
5732
+ const providedProcess = import_effect32.Effect.provide(installation.process, wrappedEnv);
5733
+ const makeTriggerStream = (spec) => import_effect32.Effect.gen(function* () {
4450
5734
  if (spec.kind === "timer") {
4451
- const interval = import_effect29.Duration.decodeUnknown(spec.timerId);
4452
- if (import_effect29.Option.isNone(interval)) {
5735
+ const interval = import_effect32.Duration.decodeUnknown(spec.timerId);
5736
+ if (import_effect32.Option.isNone(interval)) {
4453
5737
  const err = new Error(`[ProcessRuntime] invalid timerId (expected DurationInput): ${spec.timerId}`);
4454
5738
  err.code = "process::invalid_timer_id";
4455
5739
  err.hint = "timerId must be a valid DurationInput string, e.g. '10 millis', '1 seconds', '5 minutes'.";
4456
- return yield* import_effect29.Effect.fail(err);
5740
+ return yield* import_effect32.Effect.fail(err);
4457
5741
  }
4458
- return import_effect29.Stream.tick(interval.value).pipe(
4459
- import_effect29.Stream.map(
5742
+ return import_effect32.Stream.tick(interval.value).pipe(
5743
+ import_effect32.Stream.map(
4460
5744
  () => ({
4461
5745
  kind: "timer",
4462
5746
  name: spec.name,
@@ -4466,10 +5750,10 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4466
5750
  );
4467
5751
  }
4468
5752
  if (spec.kind === "moduleAction") {
4469
- const tag2 = import_effect29.Context.Tag(`@logixjs/Module/${spec.moduleId}`)();
4470
- const found2 = import_effect29.Context.getOption(baseEnv, tag2);
4471
- if (import_effect29.Option.isNone(found2)) {
4472
- return yield* import_effect29.Effect.fail(new Error(`Missing module runtime in scope: ${spec.moduleId}`));
5753
+ const tag2 = import_effect32.Context.Tag(`@logixjs/Module/${spec.moduleId}`)();
5754
+ const found2 = import_effect32.Context.getOption(baseEnv, tag2);
5755
+ if (import_effect32.Option.isNone(found2)) {
5756
+ return yield* import_effect32.Effect.fail(new Error(`Missing module runtime in scope: ${spec.moduleId}`));
4473
5757
  }
4474
5758
  const runtime2 = found2.value;
4475
5759
  if (!shouldRecordChainEvents) {
@@ -4478,11 +5762,11 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4478
5762
  const err = new Error("ModuleRuntime does not provide actions$ (required for moduleAction trigger).");
4479
5763
  err.code = "process::missing_action_stream";
4480
5764
  err.hint = `moduleId=${spec.moduleId}`;
4481
- return yield* import_effect29.Effect.fail(err);
5765
+ return yield* import_effect32.Effect.fail(err);
4482
5766
  }
4483
5767
  return stream2.pipe(
4484
- import_effect29.Stream.filter((action) => actionIdFromUnknown(action) === spec.actionId),
4485
- import_effect29.Stream.map(
5768
+ import_effect32.Stream.filter((action) => actionIdFromUnknown(action) === spec.actionId),
5769
+ import_effect32.Stream.map(
4486
5770
  () => ({
4487
5771
  kind: "moduleAction",
4488
5772
  name: spec.name,
@@ -4501,11 +5785,11 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4501
5785
  );
4502
5786
  err.code = "process::missing_action_meta_stream";
4503
5787
  err.hint = `moduleId=${spec.moduleId}`;
4504
- return yield* import_effect29.Effect.fail(err);
5788
+ return yield* import_effect32.Effect.fail(err);
4505
5789
  }
4506
5790
  return stream.pipe(
4507
- import_effect29.Stream.filter((evt) => actionIdFromUnknown(evt.value) === spec.actionId),
4508
- import_effect29.Stream.map((evt) => {
5791
+ import_effect32.Stream.filter((evt) => actionIdFromUnknown(evt.value) === spec.actionId),
5792
+ import_effect32.Stream.map((evt) => {
4509
5793
  const txnSeq = evt?.meta?.txnSeq;
4510
5794
  return {
4511
5795
  kind: "moduleAction",
@@ -4518,21 +5802,21 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4518
5802
  })
4519
5803
  );
4520
5804
  }
4521
- const tag = import_effect29.Context.Tag(`@logixjs/Module/${spec.moduleId}`)();
4522
- const found = import_effect29.Context.getOption(baseEnv, tag);
4523
- if (import_effect29.Option.isNone(found)) {
4524
- return yield* import_effect29.Effect.fail(new Error(`Missing module runtime in scope: ${spec.moduleId}`));
5805
+ const tag = import_effect32.Context.Tag(`@logixjs/Module/${spec.moduleId}`)();
5806
+ const found = import_effect32.Context.getOption(baseEnv, tag);
5807
+ if (import_effect32.Option.isNone(found)) {
5808
+ return yield* import_effect32.Effect.fail(new Error(`Missing module runtime in scope: ${spec.moduleId}`));
4525
5809
  }
4526
5810
  const runtime = found.value;
4527
5811
  const schemaAst = resolveRuntimeStateSchemaAst(runtime);
4528
5812
  const selectorResult = makeSchemaSelector(spec.path, schemaAst);
4529
5813
  if (!selectorResult.ok) {
4530
- return yield* import_effect29.Effect.fail(withModuleHint(selectorResult.error, spec.moduleId));
5814
+ return yield* import_effect32.Effect.fail(withModuleHint(selectorResult.error, spec.moduleId));
4531
5815
  }
4532
5816
  const selectorBase = selectorResult.selector;
4533
- const prevRef = yield* import_effect29.Ref.make(import_effect29.Option.none());
5817
+ const prevRef = yield* import_effect32.Ref.make(import_effect32.Option.none());
4534
5818
  const enableSelectorDiagnostics = shouldRecordChainEvents;
4535
- const selectorDiagnosticsRef = enableSelectorDiagnostics ? yield* import_effect29.Ref.make({
5819
+ const selectorDiagnosticsRef = enableSelectorDiagnostics ? yield* import_effect32.Ref.make({
4536
5820
  windowStartedMs: Date.now(),
4537
5821
  triggersInWindow: 0,
4538
5822
  lastWarningAtMs: 0
@@ -4571,11 +5855,11 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4571
5855
  } : selectorBase;
4572
5856
  const maybeWarnSelector = (trigger) => {
4573
5857
  if (!selectorDiagnosticsRef) {
4574
- return import_effect29.Effect.void;
5858
+ return import_effect32.Effect.void;
4575
5859
  }
4576
- return import_effect29.Effect.gen(function* () {
5860
+ return import_effect32.Effect.gen(function* () {
4577
5861
  const now = Date.now();
4578
- const decision = yield* import_effect29.Ref.modify(selectorDiagnosticsRef, (s) => {
5862
+ const decision = yield* import_effect32.Ref.modify(selectorDiagnosticsRef, (s) => {
4579
5863
  const windowExpired = now - s.windowStartedMs >= triggerWindowMs;
4580
5864
  const windowStartedMs = windowExpired ? now : s.windowStartedMs;
4581
5865
  const triggersInWindow = windowExpired ? 1 : s.triggersInWindow + 1;
@@ -4643,18 +5927,18 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4643
5927
  });
4644
5928
  };
4645
5929
  const baseStream = runtime.changesWithMeta(selector).pipe(
4646
- import_effect29.Stream.mapEffect(
4647
- (evt) => import_effect29.Ref.get(prevRef).pipe(
4648
- import_effect29.Effect.flatMap((prev) => {
4649
- if (import_effect29.Option.isSome(prev) && Object.is(prev.value, evt.value)) {
4650
- return import_effect29.Effect.succeed(import_effect29.Option.none());
5930
+ import_effect32.Stream.mapEffect(
5931
+ (evt) => import_effect32.Ref.get(prevRef).pipe(
5932
+ import_effect32.Effect.flatMap((prev) => {
5933
+ if (import_effect32.Option.isSome(prev) && Object.is(prev.value, evt.value)) {
5934
+ return import_effect32.Effect.succeed(import_effect32.Option.none());
4651
5935
  }
4652
- return import_effect29.Ref.set(prevRef, import_effect29.Option.some(evt.value)).pipe(import_effect29.Effect.as(import_effect29.Option.some(evt)));
5936
+ return import_effect32.Ref.set(prevRef, import_effect32.Option.some(evt.value)).pipe(import_effect32.Effect.as(import_effect32.Option.some(evt)));
4653
5937
  })
4654
5938
  )
4655
5939
  ),
4656
- import_effect29.Stream.filterMap((opt) => opt),
4657
- import_effect29.Stream.map((evt) => {
5940
+ import_effect32.Stream.filterMap((opt) => opt),
5941
+ import_effect32.Stream.map((evt) => {
4658
5942
  const txnSeq = evt?.meta?.txnSeq;
4659
5943
  return {
4660
5944
  kind: "moduleStateChange",
@@ -4666,20 +5950,20 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4666
5950
  };
4667
5951
  })
4668
5952
  );
4669
- return enableSelectorDiagnostics ? baseStream.pipe(import_effect29.Stream.tap(maybeWarnSelector)) : baseStream;
5953
+ return enableSelectorDiagnostics ? baseStream.pipe(import_effect32.Stream.tap(maybeWarnSelector)) : baseStream;
4670
5954
  });
4671
- const makeRun = (trigger, fatal) => import_effect29.Effect.locally(
5955
+ const makeRun = (trigger, fatal) => import_effect32.Effect.locally(
4672
5956
  currentProcessTrigger,
4673
5957
  trigger
4674
5958
  )(
4675
5959
  providedProcess.pipe(
4676
- import_effect29.Effect.catchAllCause((cause) => {
4677
- if (import_effect29.Cause.isInterruptedOnly(cause)) {
4678
- return import_effect29.Effect.void;
5960
+ import_effect32.Effect.catchAllCause((cause) => {
5961
+ if (import_effect32.Cause.isInterruptedOnly(cause)) {
5962
+ return import_effect32.Effect.void;
4679
5963
  }
4680
- return import_effect29.Deferred.succeed(fatal, cause).pipe(
4681
- import_effect29.Effect.asVoid,
4682
- import_effect29.Effect.catchAll(() => import_effect29.Effect.void)
5964
+ return import_effect32.Deferred.succeed(fatal, cause).pipe(
5965
+ import_effect32.Effect.asVoid,
5966
+ import_effect32.Effect.catchAll(() => import_effect32.Effect.void)
4683
5967
  );
4684
5968
  })
4685
5969
  )
@@ -4688,12 +5972,12 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4688
5972
  if (!shouldRecordChainEvents) {
4689
5973
  return makeRun(trigger, fatal);
4690
5974
  }
4691
- return import_effect29.Effect.gen(function* () {
4692
- const budgetRef = yield* import_effect29.Ref.make(makeProcessRunEventBudgetState());
4693
- return yield* import_effect29.Effect.locally(
5975
+ return import_effect32.Effect.gen(function* () {
5976
+ const budgetRef = yield* import_effect32.Ref.make(makeProcessRunEventBudgetState());
5977
+ return yield* import_effect32.Effect.locally(
4694
5978
  currentProcessEventBudget,
4695
5979
  budgetRef
4696
- )(emitTriggerEvent(trigger, "info").pipe(import_effect29.Effect.zipRight(makeRun(trigger, fatal))));
5980
+ )(emitTriggerEvent(trigger, "info").pipe(import_effect32.Effect.zipRight(makeRun(trigger, fatal))));
4697
5981
  });
4698
5982
  };
4699
5983
  const assignTriggerSeq = (trigger) => {
@@ -4707,7 +5991,7 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4707
5991
  };
4708
5992
  const emitTriggerEvent = (trigger, severity) => {
4709
5993
  if (!shouldRecordChainEvents) {
4710
- return import_effect29.Effect.void;
5994
+ return import_effect32.Effect.void;
4711
5995
  }
4712
5996
  const evt = {
4713
5997
  type: "process:trigger",
@@ -4726,16 +6010,16 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4726
6010
  const bootTriggerSpec = installation.definition.triggers.find(
4727
6011
  (t) => t.kind === "platformEvent" && t.platformEvent === RUNTIME_BOOT_EVENT
4728
6012
  );
4729
- const instanceProgram = import_effect29.Effect.gen(function* () {
4730
- const fatal = yield* import_effect29.Deferred.make();
4731
- const platformEventStream = import_effect29.Stream.fromQueue(
6013
+ const instanceProgram = import_effect32.Effect.gen(function* () {
6014
+ const fatal = yield* import_effect32.Deferred.make();
6015
+ const platformEventStream = import_effect32.Stream.fromQueue(
4732
6016
  instanceState.platformTriggersQueue
4733
6017
  );
4734
6018
  const nonPlatformTriggers = installation.definition.triggers.filter(
4735
6019
  (t) => t.kind !== "platformEvent"
4736
6020
  );
4737
- const streams = yield* import_effect29.Effect.forEach(nonPlatformTriggers, makeTriggerStream);
4738
- const triggerStream = import_effect29.Stream.mergeAll([platformEventStream, ...streams], {
6021
+ const streams = yield* import_effect32.Effect.forEach(nonPlatformTriggers, makeTriggerStream);
6022
+ const triggerStream = import_effect32.Stream.mergeAll([platformEventStream, ...streams], {
4739
6023
  concurrency: "unbounded"
4740
6024
  });
4741
6025
  const reportQueueOverflow = (info) => {
@@ -4750,12 +6034,12 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4750
6034
  "fix:",
4751
6035
  "- Configure concurrency.maxQueue (serial) to a finite value, or switch to mode=latest/drop to avoid unbounded backlog."
4752
6036
  ].join("\n");
4753
- return import_effect29.Deferred.succeed(fatal, import_effect29.Cause.fail(err)).pipe(
4754
- import_effect29.Effect.asVoid,
4755
- import_effect29.Effect.catchAll(() => import_effect29.Effect.void)
6037
+ return import_effect32.Deferred.succeed(fatal, import_effect32.Cause.fail(err)).pipe(
6038
+ import_effect32.Effect.asVoid,
6039
+ import_effect32.Effect.catchAll(() => import_effect32.Effect.void)
4756
6040
  );
4757
6041
  };
4758
- const runnerFiber = yield* import_effect29.Effect.forkScoped(
6042
+ const runnerFiber = yield* import_effect32.Effect.forkScoped(
4759
6043
  runProcessTriggerStream({
4760
6044
  stream: triggerStream,
4761
6045
  policy,
@@ -4766,21 +6050,21 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4766
6050
  })
4767
6051
  );
4768
6052
  if (autoStart) {
4769
- yield* import_effect29.Queue.offer(instanceState.platformTriggersQueue, {
6053
+ yield* import_effect32.Queue.offer(instanceState.platformTriggersQueue, {
4770
6054
  kind: "platformEvent",
4771
6055
  name: bootTriggerSpec?.name,
4772
6056
  platformEvent: RUNTIME_BOOT_EVENT
4773
6057
  });
4774
6058
  }
4775
- const cause = yield* import_effect29.Deferred.await(fatal);
4776
- yield* import_effect29.Fiber.interrupt(runnerFiber);
4777
- return yield* import_effect29.Effect.failCause(cause);
6059
+ const cause = yield* import_effect32.Deferred.await(fatal);
6060
+ yield* import_effect32.Fiber.interrupt(runnerFiber);
6061
+ return yield* import_effect32.Effect.failCause(cause);
4778
6062
  });
4779
- const fiber = yield* import_effect29.Effect.forkIn(installation.forkScope)(
4780
- import_effect29.Effect.scoped(instanceProgram).pipe(
4781
- import_effect29.Effect.catchAllCause(
4782
- (cause) => import_effect29.Effect.gen(function* () {
4783
- if (import_effect29.Cause.isInterruptedOnly(cause)) {
6063
+ const fiber = yield* import_effect32.Effect.forkIn(installation.forkScope)(
6064
+ import_effect32.Effect.scoped(instanceProgram).pipe(
6065
+ import_effect32.Effect.catchAllCause(
6066
+ (cause) => import_effect32.Effect.gen(function* () {
6067
+ if (import_effect32.Cause.isInterruptedOnly(cause)) {
4784
6068
  if (instanceState.status.status === "stopping") {
4785
6069
  return;
4786
6070
  }
@@ -4790,7 +6074,7 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4790
6074
  stoppedReason: "scopeDisposed"
4791
6075
  };
4792
6076
  instanceState.fiber = void 0;
4793
- yield* import_effect29.Effect.uninterruptible(
6077
+ yield* import_effect32.Effect.uninterruptible(
4794
6078
  emit({
4795
6079
  type: "process:stop",
4796
6080
  identity,
@@ -4806,9 +6090,9 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4806
6090
  }
4807
6091
  return;
4808
6092
  }
4809
- const primary = import_effect29.Option.getOrElse(
4810
- import_effect29.Cause.failureOption(cause),
4811
- () => import_effect29.Option.getOrElse(import_effect29.Cause.dieOption(cause), () => cause)
6093
+ const primary = import_effect32.Option.getOrElse(
6094
+ import_effect32.Cause.failureOption(cause),
6095
+ () => import_effect32.Option.getOrElse(import_effect32.Cause.dieOption(cause), () => cause)
4812
6096
  );
4813
6097
  const summary = toSerializableErrorSummary(primary);
4814
6098
  const error = summary.errorSummary;
@@ -4860,16 +6144,16 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4860
6144
  ...instanceState.status,
4861
6145
  status: "running"
4862
6146
  };
4863
- yield* import_effect29.Effect.yieldNow();
6147
+ yield* import_effect32.Effect.yieldNow();
4864
6148
  });
4865
- const install = (process2, options2) => import_effect29.Effect.gen(function* () {
6149
+ const install = (process2, options2) => import_effect32.Effect.gen(function* () {
4866
6150
  const meta = getMeta(process2);
4867
6151
  if (!meta) {
4868
6152
  return void 0;
4869
6153
  }
4870
- const env = yield* import_effect29.Effect.context();
4871
- const forkScopeOpt = yield* import_effect29.Effect.serviceOption(import_effect29.Scope.Scope);
4872
- const forkScope = import_effect29.Option.isSome(forkScopeOpt) ? forkScopeOpt.value : runtimeScope;
6154
+ const env = yield* import_effect32.Effect.context();
6155
+ const forkScopeOpt = yield* import_effect32.Effect.serviceOption(import_effect32.Scope.Scope);
6156
+ const forkScope = import_effect32.Option.isSome(forkScopeOpt) ? forkScopeOpt.value : runtimeScope;
4873
6157
  const scopeKey = scopeKeyFromScope(options2.scope);
4874
6158
  const identity = {
4875
6159
  processId: meta.definition.processId,
@@ -4897,9 +6181,9 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4897
6181
  const mode = options2.mode ?? "switch";
4898
6182
  if (mode === "switch" && current && current.forkScope !== forkScope) {
4899
6183
  existing.pendingStart = { forkScope };
4900
- yield* import_effect29.Scope.addFinalizer(
6184
+ yield* import_effect32.Scope.addFinalizer(
4901
6185
  forkScope,
4902
- import_effect29.Effect.sync(() => {
6186
+ import_effect32.Effect.sync(() => {
4903
6187
  const installation2 = installations.get(installationKey);
4904
6188
  if (!installation2) return;
4905
6189
  if (installation2.pendingStart?.forkScope === forkScope) {
@@ -4920,9 +6204,9 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4920
6204
  const mode = options2.mode ?? "switch";
4921
6205
  if (mode === "switch") {
4922
6206
  existing.pendingStart = { forkScope };
4923
- yield* import_effect29.Scope.addFinalizer(
6207
+ yield* import_effect32.Scope.addFinalizer(
4924
6208
  forkScope,
4925
- import_effect29.Effect.sync(() => {
6209
+ import_effect32.Effect.sync(() => {
4926
6210
  const installation2 = installations.get(installationKey);
4927
6211
  if (!installation2) return;
4928
6212
  if (installation2.pendingStart?.forkScope === forkScope) {
@@ -4947,7 +6231,7 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4947
6231
  installedAt: existing.installedAt
4948
6232
  };
4949
6233
  }
4950
- const derived = import_effect29.Effect.suspend(() => process2);
6234
+ const derived = import_effect32.Effect.suspend(() => process2);
4951
6235
  attachMeta(derived, {
4952
6236
  ...meta,
4953
6237
  installationScope: options2.scope
@@ -4976,7 +6260,7 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4976
6260
  installedAt: installation.installedAt
4977
6261
  };
4978
6262
  });
4979
- const listInstallations = (filter) => import_effect29.Effect.sync(() => {
6263
+ const listInstallations = (filter) => import_effect32.Effect.sync(() => {
4980
6264
  const scopeType = filter?.scopeType;
4981
6265
  const scopeKey = filter?.scopeKey;
4982
6266
  const out = [];
@@ -4991,26 +6275,26 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
4991
6275
  }
4992
6276
  return out;
4993
6277
  });
4994
- const getInstanceStatus = (processInstanceId) => import_effect29.Effect.sync(() => instances.get(processInstanceId)?.status);
4995
- const controlInstance = (processInstanceId, request) => import_effect29.Effect.suspend(() => {
6278
+ const getInstanceStatus = (processInstanceId) => import_effect32.Effect.sync(() => instances.get(processInstanceId)?.status);
6279
+ const controlInstance = (processInstanceId, request) => import_effect32.Effect.suspend(() => {
4996
6280
  const instance = instances.get(processInstanceId);
4997
6281
  if (!instance) {
4998
- return import_effect29.Effect.void;
6282
+ return import_effect32.Effect.void;
4999
6283
  }
5000
6284
  return shouldNoopDueToSyncTxn(instance.scope, "process_control_in_transaction").pipe(
5001
- import_effect29.Effect.flatMap((noop) => {
6285
+ import_effect32.Effect.flatMap((noop) => {
5002
6286
  if (noop) {
5003
- return import_effect29.Effect.void;
6287
+ return import_effect32.Effect.void;
5004
6288
  }
5005
6289
  if (request.action === "stop") {
5006
6290
  return stopInstance(instance, "manualStop");
5007
6291
  }
5008
6292
  if (request.action === "restart") {
5009
6293
  return stopInstance(instance, "manualStop").pipe(
5010
- import_effect29.Effect.flatMap(() => {
6294
+ import_effect32.Effect.flatMap(() => {
5011
6295
  const installation = installations.get(instance.installationKey);
5012
6296
  if (!installation) {
5013
- return import_effect29.Effect.void;
6297
+ return import_effect32.Effect.void;
5014
6298
  }
5015
6299
  installation.currentInstanceId = void 0;
5016
6300
  return startInstallation(instance.installationKey);
@@ -5019,20 +6303,20 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
5019
6303
  }
5020
6304
  if (request.action === "start") {
5021
6305
  if (instance.status.status === "running" || instance.status.status === "starting") {
5022
- return import_effect29.Effect.void;
6306
+ return import_effect32.Effect.void;
5023
6307
  }
5024
6308
  const installation = installations.get(instance.installationKey);
5025
6309
  if (!installation) {
5026
- return import_effect29.Effect.void;
6310
+ return import_effect32.Effect.void;
5027
6311
  }
5028
6312
  installation.currentInstanceId = void 0;
5029
6313
  return startInstallation(instance.installationKey);
5030
6314
  }
5031
- return import_effect29.Effect.void;
6315
+ return import_effect32.Effect.void;
5032
6316
  })
5033
6317
  );
5034
6318
  });
5035
- const deliverPlatformEvent = (event) => import_effect29.Effect.gen(function* () {
6319
+ const deliverPlatformEvent = (event) => import_effect32.Effect.gen(function* () {
5036
6320
  const noop = yield* shouldNoopInSyncTransactionFiber({
5037
6321
  code: "process::invalid_usage",
5038
6322
  severity: "error",
@@ -5043,25 +6327,25 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
5043
6327
  if (noop) return;
5044
6328
  const targets = Array.from(instances.values());
5045
6329
  const eventName = event.eventName;
5046
- yield* import_effect29.Effect.forEach(
6330
+ yield* import_effect32.Effect.forEach(
5047
6331
  targets,
5048
- (instance) => import_effect29.Effect.suspend(() => {
6332
+ (instance) => import_effect32.Effect.suspend(() => {
5049
6333
  if (instance.status.status !== "starting" && instance.status.status !== "running") {
5050
- return import_effect29.Effect.void;
6334
+ return import_effect32.Effect.void;
5051
6335
  }
5052
6336
  const installation = installations.get(instance.installationKey);
5053
6337
  if (!installation) {
5054
- return import_effect29.Effect.void;
6338
+ return import_effect32.Effect.void;
5055
6339
  }
5056
6340
  const specs = installation.definition.triggers.filter(
5057
6341
  (t) => t.kind === "platformEvent" && t.platformEvent === eventName
5058
6342
  );
5059
6343
  if (specs.length === 0) {
5060
- return import_effect29.Effect.void;
6344
+ return import_effect32.Effect.void;
5061
6345
  }
5062
- return import_effect29.Effect.forEach(
6346
+ return import_effect32.Effect.forEach(
5063
6347
  specs,
5064
- (spec) => import_effect29.Queue.offer(instance.platformTriggersQueue, {
6348
+ (spec) => import_effect32.Queue.offer(instance.platformTriggersQueue, {
5065
6349
  kind: "platformEvent",
5066
6350
  name: spec.name,
5067
6351
  platformEvent: spec.platformEvent
@@ -5072,10 +6356,10 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
5072
6356
  { discard: true }
5073
6357
  );
5074
6358
  });
5075
- const eventsStream = import_effect29.Stream.fromPubSub(eventsHub);
5076
- const getEventsSnapshot = () => import_effect29.Effect.sync(() => eventsBuffer.slice());
5077
- yield* import_effect29.Effect.addFinalizer(
5078
- () => import_effect29.Effect.gen(function* () {
6359
+ const eventsStream = import_effect32.Stream.fromPubSub(eventsHub);
6360
+ const getEventsSnapshot = () => import_effect32.Effect.sync(() => eventsBuffer.slice());
6361
+ yield* import_effect32.Effect.addFinalizer(
6362
+ () => import_effect32.Effect.gen(function* () {
5079
6363
  for (const installation of installations.values()) {
5080
6364
  installation.pendingStart = void 0;
5081
6365
  }
@@ -5085,10 +6369,10 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
5085
6369
  }
5086
6370
  }
5087
6371
  }).pipe(
5088
- import_effect29.Effect.catchAllCause(
5089
- (cause) => import_effect29.Effect.sync(() => {
6372
+ import_effect32.Effect.catchAllCause(
6373
+ (cause) => import_effect32.Effect.sync(() => {
5090
6374
  if (isDevEnv()) {
5091
- console.warn("[ProcessRuntime] finalizer failed", import_effect29.Cause.pretty(cause));
6375
+ console.warn("[ProcessRuntime] finalizer failed", import_effect32.Cause.pretty(cause));
5092
6376
  }
5093
6377
  })
5094
6378
  )
@@ -5104,7 +6388,7 @@ var make5 = (options) => import_effect29.Effect.gen(function* () {
5104
6388
  getEventsSnapshot
5105
6389
  };
5106
6390
  });
5107
- var layer3 = (options) => import_effect29.Layer.scoped(ProcessRuntimeTag, make5(options));
6391
+ var layer3 = (options) => import_effect32.Layer.scoped(ProcessRuntimeTag, make5(options));
5108
6392
 
5109
6393
  // src/internal/runtime/AppRuntime.ts
5110
6394
  var getTagKey = (tag) => {
@@ -5200,82 +6484,100 @@ Ensure all modules in the application Runtime have unique IDs.`
5200
6484
  seenIds.add(id);
5201
6485
  }
5202
6486
  validateTags(config.modules);
5203
- const stateTxnLayer = config.stateTransaction ? import_effect30.Layer.succeed(StateTransactionConfigTag, config.stateTransaction) : import_effect30.Layer.empty;
5204
- const concurrencyPolicyLayer = config.concurrencyPolicy ? import_effect30.Layer.succeed(ConcurrencyPolicyTag, config.concurrencyPolicy) : import_effect30.Layer.empty;
5205
- const readQueryStrictGateLayer = config.readQueryStrictGate ? import_effect30.Layer.succeed(ReadQueryStrictGateConfigTag, config.readQueryStrictGate) : import_effect30.Layer.empty;
6487
+ const stateTxnLayer = config.stateTransaction ? import_effect33.Layer.succeed(StateTransactionConfigTag, config.stateTransaction) : import_effect33.Layer.empty;
6488
+ const concurrencyPolicyLayer = config.concurrencyPolicy ? import_effect33.Layer.succeed(ConcurrencyPolicyTag, config.concurrencyPolicy) : import_effect33.Layer.empty;
6489
+ const readQueryStrictGateLayer = config.readQueryStrictGate ? import_effect33.Layer.succeed(ReadQueryStrictGateConfigTag, config.readQueryStrictGate) : import_effect33.Layer.empty;
5206
6490
  const appModuleIds = config.modules.map((entry) => String(entry.module.id));
5207
6491
  const appId = appModuleIds.length === 1 ? appModuleIds[0] : appModuleIds.slice().sort().join("~");
5208
- const baseLayer = import_effect30.Layer.mergeAll(
5209
- config.layer,
6492
+ const pinnedHostSchedulerLayer = config.hostScheduler !== void 0 ? import_effect33.Layer.succeed(HostSchedulerTag, config.hostScheduler) : void 0;
6493
+ const tickServicesLayer = import_effect33.Layer.provideMerge(pinnedHostSchedulerLayer ?? hostSchedulerLayer)(
6494
+ import_effect33.Layer.provideMerge(runtimeStoreLayer)(import_effect33.Layer.provideMerge(declarativeLinkRuntimeLayer)(tickSchedulerLayer()))
6495
+ );
6496
+ const appLayer = config.layer.pipe(import_effect33.Layer.provide(tickServicesLayer));
6497
+ const baseLayer = import_effect33.Layer.mergeAll(
6498
+ tickServicesLayer,
6499
+ appLayer,
6500
+ // If a HostScheduler override is requested, pin it as the final HostSchedulerTag value to avoid accidental divergence.
6501
+ // (Build-time capture is handled above by injecting it into tickServicesLayer.)
6502
+ pinnedHostSchedulerLayer ?? import_effect33.Layer.empty,
5210
6503
  stateTxnLayer,
5211
6504
  concurrencyPolicyLayer,
5212
6505
  readQueryStrictGateLayer,
5213
6506
  layer3(),
5214
- import_effect30.Layer.effect(
6507
+ import_effect33.Layer.effect(
5215
6508
  RootContextTag,
5216
- import_effect30.Effect.gen(function* () {
5217
- const ready = yield* import_effect30.Deferred.make();
6509
+ import_effect33.Effect.gen(function* () {
6510
+ const ready = yield* import_effect33.Deferred.make();
5218
6511
  return { context: void 0, ready, appId, appModuleIds };
5219
6512
  })
5220
6513
  )
5221
6514
  );
5222
- const moduleLayers = config.modules.map(
5223
- (entry) => (
5224
- // Ensure each module layer can see the app Env (baseLayer) to avoid missing root env during initialization.
5225
- import_effect30.Layer.provide(entry.layer, baseLayer)
5226
- )
5227
- );
5228
- const envLayer = moduleLayers.length > 0 ? import_effect30.Layer.mergeAll(baseLayer, ...moduleLayers) : baseLayer;
5229
- const finalLayer = import_effect30.Layer.unwrapScoped(
5230
- import_effect30.Effect.gen(function* () {
5231
- const scope = yield* import_effect30.Effect.scope;
5232
- const [patch, env] = yield* import_effect30.Effect.diffFiberRefs(import_effect30.Layer.buildWithScope(envLayer, scope));
5233
- const rootContext = import_effect30.Context.get(env, RootContextTag);
5234
- rootContext.context = env;
5235
- yield* import_effect30.Deferred.succeed(rootContext.ready, env);
5236
- const processRuntime = import_effect30.Context.get(
5237
- env,
5238
- ProcessRuntimeTag
5239
- );
5240
- yield* import_effect30.Effect.forEach(
5241
- config.processes,
5242
- (process2) => import_effect30.Effect.gen(function* () {
5243
- const installation = yield* import_effect30.Effect.provide(
5244
- processRuntime.install(process2, {
5245
- scope: { type: "app", appId },
5246
- enabled: true,
5247
- installedAt: "appRuntime"
6515
+ const finalLayer = import_effect33.Layer.unwrapScoped(
6516
+ import_effect33.Effect.gen(function* () {
6517
+ const scope = yield* import_effect33.Effect.scope;
6518
+ const [patch, env] = yield* import_effect33.Effect.diffFiberRefs(
6519
+ import_effect33.Effect.gen(function* () {
6520
+ const baseEnv = yield* import_effect33.Layer.buildWithScope(baseLayer, scope);
6521
+ const moduleEnv = config.modules.length > 0 ? yield* import_effect33.Effect.provide(
6522
+ import_effect33.Layer.buildWithScope(
6523
+ config.modules.length === 1 ? config.modules[0].layer : config.modules.slice(1).reduce((acc, entry) => import_effect33.Layer.merge(acc, entry.layer), config.modules[0].layer),
6524
+ scope
6525
+ ),
6526
+ baseEnv
6527
+ ) : void 0;
6528
+ const mergedEnv = moduleEnv ? import_effect33.Context.merge(baseEnv, moduleEnv) : baseEnv;
6529
+ const rootContext = import_effect33.Context.get(mergedEnv, RootContextTag);
6530
+ rootContext.context = mergedEnv;
6531
+ yield* import_effect33.Deferred.succeed(rootContext.ready, mergedEnv);
6532
+ const processRuntime = import_effect33.Context.get(
6533
+ mergedEnv,
6534
+ ProcessRuntimeTag
6535
+ );
6536
+ yield* import_effect33.Effect.forEach(
6537
+ config.processes,
6538
+ (process2) => import_effect33.Effect.gen(function* () {
6539
+ const installation = yield* import_effect33.Effect.provide(
6540
+ processRuntime.install(process2, {
6541
+ scope: { type: "app", appId },
6542
+ enabled: true,
6543
+ installedAt: "appRuntime"
6544
+ }),
6545
+ mergedEnv
6546
+ );
6547
+ if (installation === void 0) {
6548
+ yield* import_effect33.Effect.forkScoped(
6549
+ import_effect33.Effect.provide(
6550
+ config.onError ? import_effect33.Effect.catchAllCause(process2, config.onError) : process2,
6551
+ mergedEnv
6552
+ )
6553
+ );
6554
+ }
5248
6555
  }),
5249
- env
6556
+ { discard: true }
5250
6557
  );
5251
- if (installation === void 0) {
5252
- yield* import_effect30.Effect.forkScoped(
5253
- import_effect30.Effect.provide(config.onError ? import_effect30.Effect.catchAllCause(process2, config.onError) : process2, env)
5254
- );
5255
- }
5256
- }),
5257
- { discard: true }
6558
+ return mergedEnv;
6559
+ })
5258
6560
  );
5259
- const fiberRefsLayer = import_effect30.Layer.scopedDiscard(import_effect30.Effect.patchFiberRefs(patch));
5260
- return import_effect30.Layer.mergeAll(import_effect30.Layer.succeedContext(env), fiberRefsLayer);
6561
+ const fiberRefsLayer = import_effect33.Layer.scopedDiscard(import_effect33.Effect.patchFiberRefs(patch));
6562
+ return import_effect33.Layer.mergeAll(import_effect33.Layer.succeedContext(env), fiberRefsLayer);
5261
6563
  })
5262
6564
  );
5263
6565
  return {
5264
6566
  definition: config,
5265
6567
  layer: finalLayer,
5266
- makeRuntime: () => import_effect30.ManagedRuntime.make(finalLayer)
6568
+ makeRuntime: () => import_effect33.ManagedRuntime.make(finalLayer)
5267
6569
  };
5268
6570
  };
5269
6571
  var provide = (module2, resource) => {
5270
- const layer4 = isLayer(resource) ? resource : import_effect30.Layer.succeed(module2, resource);
6572
+ const layer4 = isLayer(resource) ? resource : import_effect33.Layer.succeed(module2, resource);
5271
6573
  return { module: module2, layer: layer4 };
5272
6574
  };
5273
- var isLayer = (value) => typeof value === "object" && value !== null && import_effect30.Layer.LayerTypeId in value;
6575
+ var isLayer = (value) => typeof value === "object" && value !== null && import_effect33.Layer.LayerTypeId in value;
5274
6576
 
5275
6577
  // src/internal/runtime/Runtime.ts
5276
6578
  var make6 = (rootImpl, options) => {
5277
6579
  const appConfig = {
5278
- layer: options?.layer ?? import_effect31.Layer.empty,
6580
+ layer: options?.layer ?? import_effect34.Layer.empty,
5279
6581
  modules: [provide(rootImpl.module, rootImpl.layer)],
5280
6582
  processes: rootImpl.processes ?? [],
5281
6583
  onError: options?.onError
@@ -5317,9 +6619,7 @@ var toErrorSummaryWithCode = (cause, code, hint) => {
5317
6619
  var defaultArtifactBudgetBytes = 50 * 1024;
5318
6620
  var budgetOf = (budgets) => typeof budgets?.maxBytes === "number" && Number.isFinite(budgets.maxBytes) && budgets.maxBytes > 0 ? budgets.maxBytes : defaultArtifactBudgetBytes;
5319
6621
  var makeConflictEnvelope = (artifactKey, exporterIds) => {
5320
- const ids = Array.from(new Set(exporterIds.map((s) => String(s)).filter((s) => s.length > 0))).sort(
5321
- (a, b) => a.localeCompare(b)
5322
- );
6622
+ const ids = Array.from(new Set(exporterIds.map((s) => String(s)).filter((s) => s.length > 0))).sort();
5323
6623
  return {
5324
6624
  artifactKey,
5325
6625
  envelope: {
@@ -5361,7 +6661,7 @@ var collectTrialRunArtifacts = (options) => {
5361
6661
  if (ka > kb) return 1;
5362
6662
  const ia = String(a?.exporterId ?? "");
5363
6663
  const ib = String(b?.exporterId ?? "");
5364
- return ia.localeCompare(ib);
6664
+ return ia < ib ? -1 : ia > ib ? 1 : 0;
5365
6665
  });
5366
6666
  const conflicts = /* @__PURE__ */ new Map();
5367
6667
  for (const ex of exportersSorted) {
@@ -5440,11 +6740,11 @@ var collectTrialRunArtifacts = (options) => {
5440
6740
  });
5441
6741
  }
5442
6742
  }
5443
- for (const conflictKey of Array.from(conflictKeys).sort((a, b) => a.localeCompare(b))) {
6743
+ for (const conflictKey of Array.from(conflictKeys).sort()) {
5444
6744
  collected.push(makeConflictEnvelope(conflictKey, conflicts.get(conflictKey) ?? []));
5445
6745
  }
5446
6746
  if (collected.length === 0) return void 0;
5447
- collected.sort((a, b) => a.artifactKey.localeCompare(b.artifactKey));
6747
+ collected.sort((a, b) => a.artifactKey < b.artifactKey ? -1 : a.artifactKey > b.artifactKey ? 1 : 0);
5448
6748
  return Object.fromEntries(collected.map((c) => [c.artifactKey, c.envelope]));
5449
6749
  };
5450
6750
 
@@ -5496,7 +6796,7 @@ var parseMissingConfigKeys = (message) => {
5496
6796
  if (typeof key === "string" && key.length > 0) out.push(key);
5497
6797
  }
5498
6798
  }
5499
- return Array.from(new Set(out)).sort((a, b) => a.localeCompare(b));
6799
+ return Array.from(new Set(out)).sort();
5500
6800
  };
5501
6801
  var parseMissingServiceIds = (message) => {
5502
6802
  const out = [];
@@ -5506,12 +6806,12 @@ var parseMissingServiceIds = (message) => {
5506
6806
  const id = match[1]?.replace(/[,:.;]+$/, "");
5507
6807
  if (typeof id === "string" && id.length > 0) out.push(id);
5508
6808
  }
5509
- return Array.from(new Set(out)).sort((a, b) => a.localeCompare(b));
6809
+ return Array.from(new Set(out)).sort();
5510
6810
  };
5511
6811
  var parseMissingDependencyFromCause = (cause) => {
5512
6812
  const missingServices = [];
5513
6813
  const missingConfigKeys = [];
5514
- const candidates = [...Array.from(import_effect32.Cause.failures(cause)), ...Array.from(import_effect32.Cause.defects(cause))];
6814
+ const candidates = [...Array.from(import_effect35.Cause.failures(cause)), ...Array.from(import_effect35.Cause.defects(cause))];
5515
6815
  for (const candidate of candidates) {
5516
6816
  if (isRecord6(candidate) && candidate._tag === "ConstructionGuardError") {
5517
6817
  const missingService = candidate.missingService;
@@ -5539,7 +6839,7 @@ var parseMissingDependencyFromCause = (cause) => {
5539
6839
  }
5540
6840
  }
5541
6841
  try {
5542
- messages.push(import_effect32.Cause.pretty(cause, { renderErrorCause: true }));
6842
+ messages.push(import_effect35.Cause.pretty(cause, { renderErrorCause: true }));
5543
6843
  } catch {
5544
6844
  }
5545
6845
  const merged = messages.filter((s) => s.length > 0).join("\n");
@@ -5548,19 +6848,17 @@ var parseMissingDependencyFromCause = (cause) => {
5548
6848
  missingConfigKeys.push(...parseMissingConfigKeys(merged));
5549
6849
  }
5550
6850
  return {
5551
- missingServices: Array.from(new Set(missingServices)).sort((a, b) => a.localeCompare(b)),
5552
- missingConfigKeys: Array.from(new Set(missingConfigKeys)).sort((a, b) => a.localeCompare(b))
6851
+ missingServices: Array.from(new Set(missingServices)).sort(),
6852
+ missingConfigKeys: Array.from(new Set(missingConfigKeys)).sort()
5553
6853
  };
5554
6854
  };
5555
6855
  var buildEnvironmentIr = (params) => {
5556
- const providedConfigKeys = Object.keys(params.buildEnvConfig ?? {}).filter((k) => k.length > 0 && params.buildEnvConfig[k] !== void 0).sort((a, b) => a.localeCompare(b));
5557
- const missingServices = Array.from(new Set(params.missingServices ?? [])).sort((a, b) => a.localeCompare(b));
5558
- const missingConfigKeys = Array.from(new Set(params.missingConfigKeys ?? [])).sort((a, b) => a.localeCompare(b));
6856
+ const providedConfigKeys = Object.keys(params.buildEnvConfig ?? {}).filter((k) => k.length > 0 && params.buildEnvConfig[k] !== void 0).sort();
6857
+ const missingServices = Array.from(new Set(params.missingServices ?? [])).sort();
6858
+ const missingConfigKeys = Array.from(new Set(params.missingConfigKeys ?? [])).sort();
5559
6859
  const runtimeServiceIds = params.runtimeServicesEvidence?.bindings?.map((b) => b.serviceId).filter((s) => typeof s === "string") ?? [];
5560
- const tagIds = Array.from(/* @__PURE__ */ new Set([...runtimeServiceIds, ...missingServices])).sort((a, b) => a.localeCompare(b));
5561
- const configKeys = Array.from(/* @__PURE__ */ new Set([...providedConfigKeys, ...missingConfigKeys])).sort(
5562
- (a, b) => a.localeCompare(b)
5563
- );
6860
+ const tagIds = Array.from(/* @__PURE__ */ new Set([...runtimeServiceIds, ...missingServices])).sort();
6861
+ const configKeys = Array.from(/* @__PURE__ */ new Set([...providedConfigKeys, ...missingConfigKeys])).sort();
5564
6862
  return {
5565
6863
  tagIds,
5566
6864
  configKeys,
@@ -5582,25 +6880,25 @@ var toErrorSummaryWithCode2 = (cause, code, hint) => {
5582
6880
  var makeTrialRunTimeoutError = () => Object.assign(new Error("[Logix] trialRunModule timed out"), {
5583
6881
  name: "TrialRunTimeoutError"
5584
6882
  });
5585
- var awaitFiberExitWithTimeout = (fiber, timeoutMs) => import_effect32.Effect.gen(function* () {
6883
+ var awaitFiberExitWithTimeout = (fiber, timeoutMs) => import_effect35.Effect.gen(function* () {
5586
6884
  const hasTimeout = typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0;
5587
6885
  const start = hasTimeout ? Date.now() : 0;
5588
6886
  while (true) {
5589
- const exitOpt = yield* import_effect32.Fiber.poll(fiber);
5590
- if (import_effect32.Option.isSome(exitOpt)) {
6887
+ const exitOpt = yield* import_effect35.Fiber.poll(fiber);
6888
+ if (import_effect35.Option.isSome(exitOpt)) {
5591
6889
  return exitOpt.value;
5592
6890
  }
5593
6891
  if (hasTimeout) {
5594
6892
  const elapsedMs = Date.now() - start;
5595
6893
  if (elapsedMs >= timeoutMs) {
5596
- yield* import_effect32.Fiber.interruptFork(fiber);
5597
- return import_effect32.Exit.fail(makeTrialRunTimeoutError());
6894
+ yield* import_effect35.Fiber.interruptFork(fiber);
6895
+ return import_effect35.Exit.fail(makeTrialRunTimeoutError());
5598
6896
  }
5599
6897
  }
5600
- yield* import_effect32.Effect.promise(() => new Promise((r) => setTimeout(r, 1)));
6898
+ yield* import_effect35.Effect.promise(() => new Promise((r) => setTimeout(r, 1)));
5601
6899
  }
5602
6900
  });
5603
- var trialRunModule = (root, options) => import_effect32.Effect.gen(function* () {
6901
+ var trialRunModule = (root, options) => import_effect35.Effect.gen(function* () {
5604
6902
  const rootImpl = resolveRootImpl(root);
5605
6903
  const session = makeRunSession({
5606
6904
  runId: options?.runId,
@@ -5625,9 +6923,9 @@ var trialRunModule = (root, options) => import_effect32.Effect.gen(function* ()
5625
6923
  config: buildEnvConfig,
5626
6924
  configProvider: options?.buildEnv?.configProvider
5627
6925
  });
5628
- const trialLayer = import_effect32.Layer.mergeAll(
6926
+ const trialLayer = import_effect35.Layer.mergeAll(
5629
6927
  buildEnvLayer,
5630
- options?.layer ?? import_effect32.Layer.empty,
6928
+ options?.layer ?? import_effect35.Layer.empty,
5631
6929
  sessionLayer,
5632
6930
  collectorLayer,
5633
6931
  diagnosticsLayer,
@@ -5647,7 +6945,7 @@ var trialRunModule = (root, options) => import_effect32.Effect.gen(function* ()
5647
6945
  let kernelImplementationRef;
5648
6946
  let runtimeServicesEvidence;
5649
6947
  let instanceId;
5650
- if (import_effect32.Exit.isSuccess(bootExit)) {
6948
+ if (import_effect35.Exit.isSuccess(bootExit)) {
5651
6949
  const moduleRuntime = bootExit.value;
5652
6950
  instanceId = typeof moduleRuntime?.instanceId === "string" && moduleRuntime.instanceId.length > 0 ? moduleRuntime.instanceId : void 0;
5653
6951
  kernel.setInstanceId(instanceId);
@@ -5664,8 +6962,8 @@ var trialRunModule = (root, options) => import_effect32.Effect.gen(function* ()
5664
6962
  }
5665
6963
  }
5666
6964
  } else {
5667
- const failure = import_effect32.Cause.failureOption(bootExit.cause);
5668
- if (import_effect32.Option.isSome(failure)) {
6965
+ const failure = import_effect35.Cause.failureOption(bootExit.cause);
6966
+ if (import_effect35.Option.isSome(failure)) {
5669
6967
  const err = failure.value;
5670
6968
  const instanceIdFromErr = typeof err?.instanceId === "string" ? err.instanceId : void 0;
5671
6969
  if (instanceIdFromErr && instanceIdFromErr.length > 0) {
@@ -5673,7 +6971,7 @@ var trialRunModule = (root, options) => import_effect32.Effect.gen(function* ()
5673
6971
  }
5674
6972
  }
5675
6973
  }
5676
- const closeExit = yield* import_effect32.Effect.exit(
6974
+ const closeExit = yield* import_effect35.Effect.exit(
5677
6975
  kernel.close({
5678
6976
  timeoutMs: typeof options?.closeScopeTimeout === "number" && Number.isFinite(options.closeScopeTimeout) && options.closeScopeTimeout > 0 ? options.closeScopeTimeout : 1e3
5679
6977
  })
@@ -5698,16 +6996,16 @@ var trialRunModule = (root, options) => import_effect32.Effect.gen(function* ()
5698
6996
  return void 0;
5699
6997
  }
5700
6998
  })();
5701
- let ok = import_effect32.Exit.isSuccess(bootExit) && import_effect32.Exit.isSuccess(closeExit);
6999
+ let ok = import_effect35.Exit.isSuccess(bootExit) && import_effect35.Exit.isSuccess(closeExit);
5702
7000
  let error;
5703
7001
  let summary;
5704
- const depsFromBootFailure = import_effect32.Exit.isFailure(bootExit) ? parseMissingDependencyFromCause(bootExit.cause) : { missingServices: [], missingConfigKeys: [] };
7002
+ const depsFromBootFailure = import_effect35.Exit.isFailure(bootExit) ? parseMissingDependencyFromCause(bootExit.cause) : { missingServices: [], missingConfigKeys: [] };
5705
7003
  const missingServices = depsFromBootFailure.missingServices;
5706
7004
  const missingConfigKeys = depsFromBootFailure.missingConfigKeys;
5707
- const closeError = import_effect32.Exit.isFailure(closeExit) ? import_effect32.Option.getOrUndefined(import_effect32.Cause.dieOption(closeExit.cause)) : void 0;
5708
- if (!import_effect32.Exit.isSuccess(bootExit)) {
5709
- const failure = import_effect32.Option.getOrUndefined(import_effect32.Cause.failureOption(bootExit.cause));
5710
- const defect = import_effect32.Option.getOrUndefined(import_effect32.Cause.dieOption(bootExit.cause));
7005
+ const closeError = import_effect35.Exit.isFailure(closeExit) ? import_effect35.Option.getOrUndefined(import_effect35.Cause.dieOption(closeExit.cause)) : void 0;
7006
+ if (!import_effect35.Exit.isSuccess(bootExit)) {
7007
+ const failure = import_effect35.Option.getOrUndefined(import_effect35.Cause.failureOption(bootExit.cause));
7008
+ const defect = import_effect35.Option.getOrUndefined(import_effect35.Cause.dieOption(bootExit.cause));
5711
7009
  const base = failure ?? defect ?? bootExit.cause;
5712
7010
  if (missingServices.length > 0 || missingConfigKeys.length > 0) {
5713
7011
  ok = false;
@@ -5728,9 +7026,9 @@ var trialRunModule = (root, options) => import_effect32.Effect.gen(function* ()
5728
7026
  error = toErrorSummaryWithCode2(base, "RuntimeFailure");
5729
7027
  }
5730
7028
  }
5731
- if (import_effect32.Exit.isFailure(closeExit)) {
5732
- const died = import_effect32.Option.getOrUndefined(import_effect32.Cause.dieOption(closeExit.cause));
5733
- const failure = import_effect32.Option.getOrUndefined(import_effect32.Cause.failureOption(closeExit.cause));
7029
+ if (import_effect35.Exit.isFailure(closeExit)) {
7030
+ const died = import_effect35.Option.getOrUndefined(import_effect35.Cause.dieOption(closeExit.cause));
7031
+ const failure = import_effect35.Option.getOrUndefined(import_effect35.Cause.failureOption(closeExit.cause));
5734
7032
  const base = died ?? failure ?? closeExit.cause;
5735
7033
  const closeErrorSummary = (() => {
5736
7034
  const tag = isRecord6(base) ? base._tag : void 0;
@@ -5810,7 +7108,7 @@ var defaultHost2 = () => {
5810
7108
  if (typeof window !== "undefined" && typeof document !== "undefined") return "browser";
5811
7109
  return "node";
5812
7110
  };
5813
- var trialRun = (program, options) => import_effect33.Effect.gen(function* () {
7111
+ var trialRun = (program, options) => import_effect36.Effect.gen(function* () {
5814
7112
  const session = makeRunSession({
5815
7113
  runId: options?.runId,
5816
7114
  source: options?.source ?? { host: defaultHost2(), label: "trial-run" },
@@ -5827,12 +7125,12 @@ var trialRun = (program, options) => import_effect33.Effect.gen(function* () {
5827
7125
  const convergeLayer = appendConvergeStaticIrCollectors([convergeCollector]);
5828
7126
  const collectorLayer = evidenceCollectorLayer(collector);
5829
7127
  const sessionLayer = runSessionLayer(session);
5830
- const overridesLayer = options?.runtimeServicesInstanceOverrides != null ? import_effect33.Layer.succeed(
7128
+ const overridesLayer = options?.runtimeServicesInstanceOverrides != null ? import_effect36.Layer.succeed(
5831
7129
  RuntimeServicesInstanceOverridesTag,
5832
7130
  options.runtimeServicesInstanceOverrides
5833
- ) : import_effect33.Layer.empty;
5834
- const trialLayer = import_effect33.Layer.mergeAll(
5835
- options?.layer ?? import_effect33.Layer.empty,
7131
+ ) : import_effect36.Layer.empty;
7132
+ const trialLayer = import_effect36.Layer.mergeAll(
7133
+ options?.layer ?? import_effect36.Layer.empty,
5836
7134
  sessionLayer,
5837
7135
  collectorLayer,
5838
7136
  overridesLayer,
@@ -5840,9 +7138,9 @@ var trialRun = (program, options) => import_effect33.Effect.gen(function* () {
5840
7138
  sinksLayer,
5841
7139
  convergeLayer
5842
7140
  );
5843
- const scope = yield* import_effect33.Scope.make();
5844
- const exit = yield* import_effect33.Effect.exit(program).pipe(import_effect33.Effect.provideService(import_effect33.Scope.Scope, scope), import_effect33.Effect.provide(trialLayer));
5845
- yield* import_effect33.Scope.close(scope, exit);
7141
+ const scope = yield* import_effect36.Scope.make();
7142
+ const exit = yield* import_effect36.Effect.exit(program).pipe(import_effect36.Effect.provideService(import_effect36.Scope.Scope, scope), import_effect36.Effect.provide(trialLayer));
7143
+ yield* import_effect36.Scope.close(scope, exit);
5846
7144
  const evidence = collector.exportEvidencePackage({
5847
7145
  maxEvents: options?.maxEvents
5848
7146
  });