@logixjs/core 0.0.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (398) hide show
  1. package/LICENSE +201 -0
  2. package/dist/{Action-mqVvtEHt.d.ts → Action-DYl88bwj.d.ts} +1 -1
  3. package/dist/{Action-BkRHy2vg.d.cts → Action-DkxsI_DK.d.cts} +1 -1
  4. package/dist/Action.cjs.map +1 -1
  5. package/dist/Action.d.cts +1 -1
  6. package/dist/Action.d.ts +1 -1
  7. package/dist/Action.js +2 -2
  8. package/dist/{Actions-AsQ07yTP.d.cts → Actions-Dicm7jdc.d.cts} +2 -2
  9. package/dist/{Actions-AsQ07yTP.d.ts → Actions-Dicm7jdc.d.ts} +2 -2
  10. package/dist/Actions.cjs.map +1 -1
  11. package/dist/Actions.d.cts +1 -1
  12. package/dist/Actions.d.ts +1 -1
  13. package/dist/Actions.js +1 -1
  14. package/dist/{Bound-BN1DQ_lM.d.ts → Bound-1OJLzVIS.d.ts} +2 -2
  15. package/dist/{Bound-BPIfH9SS.d.cts → Bound-BMLrtQ1V.d.cts} +2 -2
  16. package/dist/Bound.cjs +1737 -399
  17. package/dist/Bound.cjs.map +1 -1
  18. package/dist/Bound.d.cts +5 -5
  19. package/dist/Bound.d.ts +5 -5
  20. package/dist/Bound.js +19 -17
  21. package/dist/{Debug-B5q5Bkzx.d.ts → Debug-DKrWP5H1.d.ts} +40 -22
  22. package/dist/{Debug-Bq8Sqjcr.d.cts → Debug-hIT44XsY.d.cts} +40 -22
  23. package/dist/Debug.cjs +1348 -318
  24. package/dist/Debug.cjs.map +1 -1
  25. package/dist/Debug.d.cts +12 -11
  26. package/dist/Debug.d.ts +12 -11
  27. package/dist/Debug.js +20 -11
  28. package/dist/EffectOp.cjs +15 -6
  29. package/dist/EffectOp.cjs.map +1 -1
  30. package/dist/EffectOp.js +3 -3
  31. package/dist/Env.cjs +772 -6
  32. package/dist/Env.cjs.map +1 -1
  33. package/dist/Env.js +5 -2
  34. package/dist/ExternalStore-DqJKKRJ4.d.ts +61 -0
  35. package/dist/ExternalStore-JC-gAgEI.d.cts +61 -0
  36. package/dist/ExternalStore.cjs +774 -0
  37. package/dist/ExternalStore.cjs.map +1 -0
  38. package/dist/ExternalStore.d.cts +8 -0
  39. package/dist/ExternalStore.d.ts +8 -0
  40. package/dist/ExternalStore.js +19 -0
  41. package/dist/ExternalStore.js.map +1 -0
  42. package/dist/{Flow-BhpjE22E.d.ts → Flow-CZmXRDqp.d.cts} +13 -4
  43. package/dist/{Flow-1fZT8MpX.d.cts → Flow-DIVDxz7R.d.ts} +13 -4
  44. package/dist/Flow.cjs +765 -148
  45. package/dist/Flow.cjs.map +1 -1
  46. package/dist/Flow.d.cts +6 -6
  47. package/dist/Flow.d.ts +6 -6
  48. package/dist/Flow.js +9 -8
  49. package/dist/{Handle-D_cLW1Z3.d.ts → Handle-Bo6cAFut.d.ts} +1 -1
  50. package/dist/{Handle-D8D1zPb_.d.cts → Handle-CfDvSqN7.d.cts} +1 -1
  51. package/dist/Handle.d.cts +5 -5
  52. package/dist/Handle.d.ts +5 -5
  53. package/dist/{Kernel-8kC-jOda.d.cts → Kernel-CuXBF9S_.d.cts} +16 -7
  54. package/dist/{Kernel-CnGE1Fyk.d.ts → Kernel-D9guNwRL.d.ts} +16 -7
  55. package/dist/Kernel.cjs +814 -26
  56. package/dist/Kernel.cjs.map +1 -1
  57. package/dist/Kernel.d.cts +13 -12
  58. package/dist/Kernel.d.ts +13 -12
  59. package/dist/Kernel.js +7 -4
  60. package/dist/{Link-Db7975nU.d.ts → Link-CUM0yUCH.d.ts} +10 -3
  61. package/dist/{Link-fX8x1eCK.d.cts → Link-NAfR6uGD.d.cts} +10 -3
  62. package/dist/Link.cjs +1294 -121
  63. package/dist/Link.cjs.map +1 -1
  64. package/dist/Link.d.cts +5 -5
  65. package/dist/Link.d.ts +5 -5
  66. package/dist/Link.js +37 -29
  67. package/dist/{Logic-DRh4sDZj.d.cts → Logic-09VQpIj3.d.cts} +7 -4
  68. package/dist/{Logic-BRjEMr-W.d.ts → Logic-DKg7ghGy.d.ts} +7 -4
  69. package/dist/Logic.cjs +2 -1
  70. package/dist/Logic.cjs.map +1 -1
  71. package/dist/Logic.d.cts +5 -5
  72. package/dist/Logic.d.ts +5 -5
  73. package/dist/Logic.js +1 -1
  74. package/dist/{MatchBuilder-CJk5oCkR.d.cts → MatchBuilder-CsW5jgrL.d.ts} +1 -1
  75. package/dist/{MatchBuilder-0QOc-nlU.d.ts → MatchBuilder-Dksk07F4.d.cts} +1 -1
  76. package/dist/MatchBuilder.cjs +2 -2
  77. package/dist/MatchBuilder.cjs.map +1 -1
  78. package/dist/MatchBuilder.d.cts +6 -6
  79. package/dist/MatchBuilder.d.ts +6 -6
  80. package/dist/MatchBuilder.js +2 -2
  81. package/dist/Middleware-D8tUDLv_.d.cts +100 -0
  82. package/dist/Middleware-DS7CbTTN.d.ts +100 -0
  83. package/dist/Middleware.cjs +678 -58
  84. package/dist/Middleware.cjs.map +1 -1
  85. package/dist/Middleware.d.cts +2 -86
  86. package/dist/Middleware.d.ts +2 -86
  87. package/dist/Middleware.js +15 -12
  88. package/dist/{Module-DnzluX2J.d.ts → Module-B_Cntyms.d.ts} +54 -25
  89. package/dist/{Module-B_0xRDMR.d.cts → Module-CmNOVXzf.d.cts} +54 -25
  90. package/dist/Module.cjs +9331 -3317
  91. package/dist/Module.cjs.map +1 -1
  92. package/dist/Module.d.cts +7 -6
  93. package/dist/Module.d.ts +7 -6
  94. package/dist/Module.js +39 -31
  95. package/dist/ModuleTag-CGho_InD.d.ts +113 -0
  96. package/dist/ModuleTag-CITb8L_G.d.cts +113 -0
  97. package/dist/ModuleTag.cjs +7248 -2847
  98. package/dist/ModuleTag.cjs.map +1 -1
  99. package/dist/ModuleTag.d.cts +6 -6
  100. package/dist/ModuleTag.d.ts +6 -6
  101. package/dist/ModuleTag.js +35 -29
  102. package/dist/Observability-Bdhnx2Dv.d.ts +385 -0
  103. package/dist/Observability-DXGAFBIT.d.cts +385 -0
  104. package/dist/Observability.cjs +5093 -1556
  105. package/dist/Observability.cjs.map +1 -1
  106. package/dist/Observability.d.cts +6 -7
  107. package/dist/Observability.d.ts +6 -7
  108. package/dist/Observability.js +28 -23
  109. package/dist/{Platform-CHX8o-U4.d.ts → Platform-B4s8tg6C.d.cts} +4 -5
  110. package/dist/{Platform-C49Pv956.d.cts → Platform-BV_0MW7g.d.cts} +5 -2
  111. package/dist/{Platform-C49Pv956.d.ts → Platform-BV_0MW7g.d.ts} +5 -2
  112. package/dist/{Platform-CVlv0xLQ.d.cts → Platform-W0Mefy_e.d.ts} +4 -5
  113. package/dist/Platform.cjs +2 -1
  114. package/dist/Platform.cjs.map +1 -1
  115. package/dist/Platform.d.cts +2 -3
  116. package/dist/Platform.d.ts +2 -3
  117. package/dist/Platform.js +2 -2
  118. package/dist/{Process-CM9xbMdP.d.ts → Process-CO8G7HO9.d.cts} +30 -5
  119. package/dist/{Process-mL8fHDSB.d.cts → Process-Cyf6VNDR.d.ts} +30 -5
  120. package/dist/Process.cjs +1288 -120
  121. package/dist/Process.cjs.map +1 -1
  122. package/dist/Process.d.cts +6 -6
  123. package/dist/Process.d.ts +6 -6
  124. package/dist/Process.js +34 -26
  125. package/dist/ReadQuery-C_or5nLC.d.ts +128 -0
  126. package/dist/ReadQuery-DXLzCE0E.d.cts +614 -0
  127. package/dist/ReadQuery-DXLzCE0E.d.ts +614 -0
  128. package/dist/ReadQuery-Yve1lmUo.d.cts +128 -0
  129. package/dist/ReadQuery.cjs +290 -5
  130. package/dist/ReadQuery.cjs.map +1 -1
  131. package/dist/ReadQuery.d.cts +3 -2
  132. package/dist/ReadQuery.d.ts +3 -2
  133. package/dist/ReadQuery.js +23 -5
  134. package/dist/{Reflection-CQnKwPXj.d.ts → Reflection-B2Xi1e4Q.d.ts} +89 -7
  135. package/dist/{Reflection-Kabo1mlU.d.cts → Reflection-DNB4V4_e.d.cts} +89 -7
  136. package/dist/Reflection.cjs +3227 -1617
  137. package/dist/Reflection.cjs.map +1 -1
  138. package/dist/Reflection.d.cts +17 -15
  139. package/dist/Reflection.d.ts +17 -15
  140. package/dist/Reflection.js +33 -25
  141. package/dist/{Resource-Dy1xD_DG.d.cts → Resource-pKvQQ4x5.d.cts} +3 -3
  142. package/dist/{Resource-Dy1xD_DG.d.ts → Resource-pKvQQ4x5.d.ts} +3 -3
  143. package/dist/Resource.cjs +781 -15
  144. package/dist/Resource.cjs.map +1 -1
  145. package/dist/Resource.d.cts +1 -1
  146. package/dist/Resource.d.ts +1 -1
  147. package/dist/Resource.js +6 -3
  148. package/dist/{Root-7ADUMk4t.d.cts → Root-CCVuFHB6.d.cts} +3 -3
  149. package/dist/{Root-7ADUMk4t.d.ts → Root-CCVuFHB6.d.ts} +3 -3
  150. package/dist/Root.cjs +786 -20
  151. package/dist/Root.cjs.map +1 -1
  152. package/dist/Root.d.cts +2 -2
  153. package/dist/Root.d.ts +2 -2
  154. package/dist/Root.js +7 -3
  155. package/dist/{Runtime-CtyzZG4i.d.ts → Runtime-CRmvwK4I.d.ts} +70 -14
  156. package/dist/{Runtime-B-aL-f29.d.cts → Runtime-C_wJM9mN.d.cts} +70 -14
  157. package/dist/Runtime.cjs +4942 -1601
  158. package/dist/Runtime.cjs.map +1 -1
  159. package/dist/Runtime.d.cts +17 -15
  160. package/dist/Runtime.d.ts +17 -15
  161. package/dist/Runtime.js +44 -32
  162. package/dist/{ScopeRegistry-D1owDNSm.d.cts → ScopeRegistry-BhYzqWri.d.cts} +6 -6
  163. package/dist/{ScopeRegistry-D1owDNSm.d.ts → ScopeRegistry-BhYzqWri.d.ts} +6 -6
  164. package/dist/ScopeRegistry.cjs +776 -10
  165. package/dist/ScopeRegistry.cjs.map +1 -1
  166. package/dist/ScopeRegistry.d.cts +1 -1
  167. package/dist/ScopeRegistry.d.ts +1 -1
  168. package/dist/ScopeRegistry.js +6 -3
  169. package/dist/{State-CU50R26M.d.cts → State-rNFsFPTl.d.cts} +2 -2
  170. package/dist/{State-CU50R26M.d.ts → State-rNFsFPTl.d.ts} +2 -2
  171. package/dist/State.cjs.map +1 -1
  172. package/dist/State.d.cts +1 -1
  173. package/dist/State.d.ts +1 -1
  174. package/dist/State.js +1 -1
  175. package/dist/{StateTrait-BGsZghTz.d.ts → StateTrait-CijdwNb6.d.ts} +25 -8
  176. package/dist/{StateTrait-OWhbj12c.d.cts → StateTrait-Dltto6PU.d.cts} +25 -8
  177. package/dist/StateTrait.cjs +1890 -528
  178. package/dist/StateTrait.cjs.map +1 -1
  179. package/dist/StateTrait.d.cts +9 -7
  180. package/dist/StateTrait.d.ts +9 -7
  181. package/dist/StateTrait.js +18 -14
  182. package/dist/{TraitLifecycle-CwV5WPFX.d.cts → TraitLifecycle-BKzDqzLu.d.cts} +2 -2
  183. package/dist/{TraitLifecycle-LdIWmKlg.d.ts → TraitLifecycle-Cvo94uDB.d.ts} +2 -2
  184. package/dist/TraitLifecycle.cjs +630 -67
  185. package/dist/TraitLifecycle.cjs.map +1 -1
  186. package/dist/TraitLifecycle.d.cts +6 -6
  187. package/dist/TraitLifecycle.d.ts +6 -6
  188. package/dist/TraitLifecycle.js +8 -7
  189. package/dist/Workflow-C_OWr4dV.d.ts +415 -0
  190. package/dist/Workflow-DmydkHO8.d.cts +415 -0
  191. package/dist/Workflow.cjs +3150 -0
  192. package/dist/Workflow.cjs.map +1 -0
  193. package/dist/Workflow.d.cts +7 -0
  194. package/dist/Workflow.d.ts +7 -0
  195. package/dist/Workflow.js +58 -0
  196. package/dist/Workflow.js.map +1 -0
  197. package/dist/{action-DiMDD_0v.d.cts → action-BQxjPFEw.d.cts} +5 -5
  198. package/dist/{action-DiMDD_0v.d.ts → action-BQxjPFEw.d.ts} +5 -5
  199. package/dist/chunk-2XRLXDWR.js +276 -0
  200. package/dist/chunk-2XRLXDWR.js.map +1 -0
  201. package/dist/chunk-3L6QGFMM.js +701 -0
  202. package/dist/chunk-3L6QGFMM.js.map +1 -0
  203. package/dist/{chunk-GMPEOUP2.js → chunk-4MZ7BT3R.js} +2 -2
  204. package/dist/chunk-4MZ7BT3R.js.map +1 -0
  205. package/dist/{chunk-3IYZ5IGG.js → chunk-5WKUGEBY.js} +2 -2
  206. package/dist/{chunk-3RMKLXHX.js → chunk-63ZQ5RIN.js} +2 -2
  207. package/dist/{chunk-M3WTHJHJ.js → chunk-67DIEA53.js} +385 -148
  208. package/dist/chunk-67DIEA53.js.map +1 -0
  209. package/dist/{chunk-YS3AZQ2G.js → chunk-6HFAW2MH.js} +1 -1
  210. package/dist/chunk-6HFAW2MH.js.map +1 -0
  211. package/dist/{chunk-EY4NZKDR.js → chunk-6Y2TKCNY.js} +2 -2
  212. package/dist/{chunk-76WT3HOR.js → chunk-6YZOXFPQ.js} +25 -24
  213. package/dist/chunk-6YZOXFPQ.js.map +1 -0
  214. package/dist/{chunk-G5ZBFPNU.js → chunk-A2RQOJC7.js} +2 -2
  215. package/dist/{chunk-AUIR5O6W.js → chunk-AFSB6NKM.js} +13 -19
  216. package/dist/chunk-AFSB6NKM.js.map +1 -0
  217. package/dist/{chunk-JCXGZRMU.js → chunk-AO4JEOKD.js} +22 -23
  218. package/dist/chunk-AO4JEOKD.js.map +1 -0
  219. package/dist/{chunk-TAAPQVZN.js → chunk-AYELIQXR.js} +2 -2
  220. package/dist/{chunk-QMM6O4CD.js → chunk-BLHZW7DG.js} +15 -3
  221. package/dist/{chunk-QMM6O4CD.js.map → chunk-BLHZW7DG.js.map} +1 -1
  222. package/dist/{chunk-TQOBJYDP.js → chunk-CD4N74YC.js} +1 -1
  223. package/dist/chunk-CD4N74YC.js.map +1 -0
  224. package/dist/{chunk-ANLBCBDC.js → chunk-CGE2HBTH.js} +11 -11
  225. package/dist/chunk-CGE2HBTH.js.map +1 -0
  226. package/dist/{chunk-OFADUJWJ.js → chunk-CYYSQMLO.js} +5 -5
  227. package/dist/chunk-CYYSQMLO.js.map +1 -0
  228. package/dist/{chunk-66ALHVEX.js → chunk-EB46EYI7.js} +3 -3
  229. package/dist/{chunk-NZJKFF45.js → chunk-EKCDHWRK.js} +4 -4
  230. package/dist/chunk-EKCDHWRK.js.map +1 -0
  231. package/dist/{chunk-BABLDP24.js → chunk-EPQFNJU3.js} +152 -7
  232. package/dist/chunk-EPQFNJU3.js.map +1 -0
  233. package/dist/{chunk-OGWBVHB3.js → chunk-ESR6HGOY.js} +73 -14
  234. package/dist/chunk-ESR6HGOY.js.map +1 -0
  235. package/dist/{chunk-NBD3KUOZ.js → chunk-F6RP62H3.js} +150 -98
  236. package/dist/chunk-F6RP62H3.js.map +1 -0
  237. package/dist/chunk-FBYW3QDI.js +252 -0
  238. package/dist/chunk-FBYW3QDI.js.map +1 -0
  239. package/dist/{chunk-IPF7E66P.js → chunk-FYAODKVP.js} +2 -2
  240. package/dist/chunk-GNEN7NKO.js +908 -0
  241. package/dist/chunk-GNEN7NKO.js.map +1 -0
  242. package/dist/chunk-GWSM4KLB.js +763 -0
  243. package/dist/chunk-GWSM4KLB.js.map +1 -0
  244. package/dist/{chunk-4SO6JMZL.js → chunk-HDMXCUZL.js} +1 -1
  245. package/dist/chunk-HDMXCUZL.js.map +1 -0
  246. package/dist/{chunk-ZFY7U2FR.js → chunk-HJM5Y5NU.js} +43 -3
  247. package/dist/chunk-HJM5Y5NU.js.map +1 -0
  248. package/dist/{chunk-ZGDVUPTM.js → chunk-IOZ3VKPK.js} +129 -68
  249. package/dist/chunk-IOZ3VKPK.js.map +1 -0
  250. package/dist/{chunk-PYOE4VSI.js → chunk-IVXSVHO4.js} +303 -247
  251. package/dist/chunk-IVXSVHO4.js.map +1 -0
  252. package/dist/chunk-J3CWXIPV.js +242 -0
  253. package/dist/chunk-J3CWXIPV.js.map +1 -0
  254. package/dist/chunk-K6JQW266.js +42 -0
  255. package/dist/chunk-K6JQW266.js.map +1 -0
  256. package/dist/chunk-KMZYQF6Q.js +202 -0
  257. package/dist/chunk-KMZYQF6Q.js.map +1 -0
  258. package/dist/{chunk-JWOYLO27.js → chunk-LPPZDFTD.js} +22 -12
  259. package/dist/chunk-LPPZDFTD.js.map +1 -0
  260. package/dist/{chunk-PAYXCY6A.js → chunk-MYB2B5WX.js} +997 -576
  261. package/dist/chunk-MYB2B5WX.js.map +1 -0
  262. package/dist/chunk-MYKNINNN.js +228 -0
  263. package/dist/chunk-MYKNINNN.js.map +1 -0
  264. package/dist/chunk-NSQIRMVF.js +27 -0
  265. package/dist/{chunk-QCHIQWAJ.js.map → chunk-NSQIRMVF.js.map} +1 -1
  266. package/dist/chunk-NUDBM4MM.js +30 -0
  267. package/dist/chunk-NUDBM4MM.js.map +1 -0
  268. package/dist/chunk-NZMWWDAY.js +23 -0
  269. package/dist/chunk-NZMWWDAY.js.map +1 -0
  270. package/dist/{chunk-RNFE3ML2.js → chunk-OCUV2Y25.js} +4 -3
  271. package/dist/chunk-OCUV2Y25.js.map +1 -0
  272. package/dist/chunk-P4ZJOQA7.js +271 -0
  273. package/dist/chunk-P4ZJOQA7.js.map +1 -0
  274. package/dist/chunk-P6C5EZ3D.js +342 -0
  275. package/dist/chunk-P6C5EZ3D.js.map +1 -0
  276. package/dist/{chunk-CW6T36TN.js → chunk-PBD7BJUN.js} +62 -4
  277. package/dist/chunk-PBD7BJUN.js.map +1 -0
  278. package/dist/chunk-PBIUCQY3.js +696 -0
  279. package/dist/chunk-PBIUCQY3.js.map +1 -0
  280. package/dist/chunk-PD6YECQH.js +845 -0
  281. package/dist/chunk-PD6YECQH.js.map +1 -0
  282. package/dist/{chunk-M7IYCTJV.js → chunk-R4LFQGP3.js} +2 -2
  283. package/dist/chunk-RHJIGDUE.js +21 -0
  284. package/dist/chunk-RHJIGDUE.js.map +1 -0
  285. package/dist/{chunk-KP7MUZNX.js → chunk-RLXO27MW.js} +30 -8
  286. package/dist/chunk-RLXO27MW.js.map +1 -0
  287. package/dist/{chunk-DFNM3WX2.js → chunk-S44BEV4B.js} +168 -45
  288. package/dist/chunk-S44BEV4B.js.map +1 -0
  289. package/dist/chunk-S4S5N4BJ.js +1461 -0
  290. package/dist/chunk-S4S5N4BJ.js.map +1 -0
  291. package/dist/{chunk-BZ2SHDN2.js → chunk-SGTRAXXX.js} +3 -3
  292. package/dist/chunk-SGTRAXXX.js.map +1 -0
  293. package/dist/{chunk-M2RGJPXX.js → chunk-SJAE5PB5.js} +3 -3
  294. package/dist/{chunk-JGIWG6SR.js → chunk-SNPNHU3H.js} +3937 -1776
  295. package/dist/chunk-SNPNHU3H.js.map +1 -0
  296. package/dist/{chunk-IHVBV5C2.js → chunk-SOOBFXRR.js} +94 -71
  297. package/dist/chunk-SOOBFXRR.js.map +1 -0
  298. package/dist/{chunk-ZDTRWK5F.js → chunk-TAHFWKS6.js} +2 -2
  299. package/dist/chunk-UEFFTVPY.js +9 -0
  300. package/dist/chunk-UEFFTVPY.js.map +1 -0
  301. package/dist/{chunk-24VULZ7A.js → chunk-UR5BXLBP.js} +3 -3
  302. package/dist/chunk-UR5BXLBP.js.map +1 -0
  303. package/dist/{chunk-DMBALCE2.js → chunk-V2SBGVDO.js} +471 -186
  304. package/dist/chunk-V2SBGVDO.js.map +1 -0
  305. package/dist/chunk-VJLWD47W.js +23 -0
  306. package/dist/chunk-VJLWD47W.js.map +1 -0
  307. package/dist/{chunk-4CQAV7YB.js → chunk-W647DX5Z.js} +2 -2
  308. package/dist/{chunk-THATMZXD.js → chunk-WFIIU3YZ.js} +2 -2
  309. package/dist/{chunk-THATMZXD.js.map → chunk-WFIIU3YZ.js.map} +1 -1
  310. package/dist/chunk-YZDJMAKL.js +82 -0
  311. package/dist/chunk-YZDJMAKL.js.map +1 -0
  312. package/dist/{chunk-3TMODYZV.js → chunk-Z5XH6VHY.js} +5 -5
  313. package/dist/chunk-Z5XH6VHY.js.map +1 -0
  314. package/dist/{chunk-BE3HW4FY.js → chunk-ZBBMZMA6.js} +377 -170
  315. package/dist/chunk-ZBBMZMA6.js.map +1 -0
  316. package/dist/index.cjs +21224 -11714
  317. package/dist/index.cjs.map +1 -1
  318. package/dist/index.d.cts +195 -49
  319. package/dist/index.d.ts +195 -49
  320. package/dist/index.js +150 -74
  321. package/dist/index.js.map +1 -1
  322. package/dist/{ir-BMP7yxJJ.d.cts → ir-BSosEwc8.d.cts} +1 -1
  323. package/dist/{ir-DUOz6H-5.d.ts → ir-D-uqwL_4.d.ts} +1 -1
  324. package/dist/{module-B8CBqIZ_.d.cts → module-Ds4tarcI.d.cts} +230 -140
  325. package/dist/{module-k7m3txak.d.ts → module-Zd1Gn-Nj.d.ts} +230 -140
  326. package/package.json +20 -4
  327. package/dist/ModuleTag-C8FHY_sY.d.ts +0 -93
  328. package/dist/ModuleTag-EGbgBMpZ.d.cts +0 -93
  329. package/dist/Observability-COqEvp2C.d.cts +0 -713
  330. package/dist/Observability-cY4kLn0S.d.ts +0 -713
  331. package/dist/ReadQuery-BlMwhe-F.d.ts +0 -30
  332. package/dist/ReadQuery-CL5XlXts.d.cts +0 -30
  333. package/dist/ReadQuery-SinbStGF.d.cts +0 -38
  334. package/dist/ReadQuery-SinbStGF.d.ts +0 -38
  335. package/dist/chunk-24VULZ7A.js.map +0 -1
  336. package/dist/chunk-3QMIVH35.js +0 -43
  337. package/dist/chunk-3QMIVH35.js.map +0 -1
  338. package/dist/chunk-3TMODYZV.js.map +0 -1
  339. package/dist/chunk-4SO6JMZL.js.map +0 -1
  340. package/dist/chunk-76WT3HOR.js.map +0 -1
  341. package/dist/chunk-ANLBCBDC.js.map +0 -1
  342. package/dist/chunk-AUIR5O6W.js.map +0 -1
  343. package/dist/chunk-BABLDP24.js.map +0 -1
  344. package/dist/chunk-BE3HW4FY.js.map +0 -1
  345. package/dist/chunk-BZ2SHDN2.js.map +0 -1
  346. package/dist/chunk-CW6T36TN.js.map +0 -1
  347. package/dist/chunk-DFNM3WX2.js.map +0 -1
  348. package/dist/chunk-DMBALCE2.js.map +0 -1
  349. package/dist/chunk-EGK3KN7B.js +0 -406
  350. package/dist/chunk-EGK3KN7B.js.map +0 -1
  351. package/dist/chunk-GMPEOUP2.js.map +0 -1
  352. package/dist/chunk-IHVBV5C2.js.map +0 -1
  353. package/dist/chunk-JCXGZRMU.js.map +0 -1
  354. package/dist/chunk-JGIWG6SR.js.map +0 -1
  355. package/dist/chunk-JWOYLO27.js.map +0 -1
  356. package/dist/chunk-KIXAU3GM.js +0 -137
  357. package/dist/chunk-KIXAU3GM.js.map +0 -1
  358. package/dist/chunk-KL5ACTCT.js +0 -8
  359. package/dist/chunk-KL5ACTCT.js.map +0 -1
  360. package/dist/chunk-KP7MUZNX.js.map +0 -1
  361. package/dist/chunk-M3BFQ7HK.js +0 -13
  362. package/dist/chunk-M3BFQ7HK.js.map +0 -1
  363. package/dist/chunk-M3WTHJHJ.js.map +0 -1
  364. package/dist/chunk-NBD3KUOZ.js.map +0 -1
  365. package/dist/chunk-NQZ2OSGR.js +0 -151
  366. package/dist/chunk-NQZ2OSGR.js.map +0 -1
  367. package/dist/chunk-NZJKFF45.js.map +0 -1
  368. package/dist/chunk-OFADUJWJ.js.map +0 -1
  369. package/dist/chunk-OGWBVHB3.js.map +0 -1
  370. package/dist/chunk-PAYXCY6A.js.map +0 -1
  371. package/dist/chunk-PYOE4VSI.js.map +0 -1
  372. package/dist/chunk-QCHIQWAJ.js +0 -21
  373. package/dist/chunk-RNFE3ML2.js.map +0 -1
  374. package/dist/chunk-TKZ7MEIA.js +0 -27
  375. package/dist/chunk-TKZ7MEIA.js.map +0 -1
  376. package/dist/chunk-TQOBJYDP.js.map +0 -1
  377. package/dist/chunk-VZB726PE.js +0 -93
  378. package/dist/chunk-VZB726PE.js.map +0 -1
  379. package/dist/chunk-W3TEWHLO.js +0 -568
  380. package/dist/chunk-W3TEWHLO.js.map +0 -1
  381. package/dist/chunk-YS3AZQ2G.js.map +0 -1
  382. package/dist/chunk-ZFLHVFUC.js +0 -192
  383. package/dist/chunk-ZFLHVFUC.js.map +0 -1
  384. package/dist/chunk-ZFY7U2FR.js.map +0 -1
  385. package/dist/chunk-ZGDVUPTM.js.map +0 -1
  386. package/dist/protocol-g_1897M2.d.cts +0 -127
  387. package/dist/protocol-g_1897M2.d.ts +0 -127
  388. /package/dist/{chunk-3IYZ5IGG.js.map → chunk-5WKUGEBY.js.map} +0 -0
  389. /package/dist/{chunk-3RMKLXHX.js.map → chunk-63ZQ5RIN.js.map} +0 -0
  390. /package/dist/{chunk-EY4NZKDR.js.map → chunk-6Y2TKCNY.js.map} +0 -0
  391. /package/dist/{chunk-G5ZBFPNU.js.map → chunk-A2RQOJC7.js.map} +0 -0
  392. /package/dist/{chunk-TAAPQVZN.js.map → chunk-AYELIQXR.js.map} +0 -0
  393. /package/dist/{chunk-66ALHVEX.js.map → chunk-EB46EYI7.js.map} +0 -0
  394. /package/dist/{chunk-IPF7E66P.js.map → chunk-FYAODKVP.js.map} +0 -0
  395. /package/dist/{chunk-M7IYCTJV.js.map → chunk-R4LFQGP3.js.map} +0 -0
  396. /package/dist/{chunk-M2RGJPXX.js.map → chunk-SJAE5PB5.js.map} +0 -0
  397. /package/dist/{chunk-ZDTRWK5F.js.map → chunk-TAHFWKS6.js.map} +0 -0
  398. /package/dist/{chunk-4CQAV7YB.js.map → chunk-W647DX5Z.js.map} +0 -0
package/dist/Bound.cjs CHANGED
@@ -20,21 +20,21 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/Bound.ts
21
21
  var Bound_exports = {};
22
22
  __export(Bound_exports, {
23
- make: () => make4
23
+ make: () => make5
24
24
  });
25
25
  module.exports = __toCommonJS(Bound_exports);
26
26
 
27
27
  // src/internal/runtime/core/BoundApiRuntime.ts
28
- var import_effect16 = require("effect");
28
+ var import_effect20 = require("effect");
29
29
 
30
30
  // src/internal/action.ts
31
31
  var import_effect = require("effect");
32
32
  var isActionToken = (value) => typeof value === "function" && value._kind === "ActionToken" && typeof value.tag === "string" && import_effect.Schema.isSchema(value.schema);
33
33
 
34
34
  // src/internal/runtime/core/TaskRunner.ts
35
- var import_effect6 = require("effect");
35
+ var import_effect10 = require("effect");
36
36
 
37
- // src/internal/runtime/core/DebugSink.ts
37
+ // src/internal/runtime/core/DebugSink.record.ts
38
38
  var import_effect4 = require("effect");
39
39
 
40
40
  // src/internal/observability/jsonValue.ts
@@ -52,18 +52,27 @@ var import_effect2 = require("effect");
52
52
 
53
53
  // src/internal/runtime/core/EffectOpCore.ts
54
54
  var import_effect3 = require("effect");
55
- var currentLinkId = import_effect3.FiberRef.unsafeMake(void 0);
56
- var EffectOpMiddlewareTag = class extends import_effect3.Context.Tag("Logix/EffectOpMiddleware")() {
55
+ var currentLinkId = import_effect3.ServiceMap.Reference("@logixjs/core/CurrentLinkId", {
56
+ defaultValue: () => void 0
57
+ });
58
+ var composeMiddlewareCache = /* @__PURE__ */ new WeakMap();
59
+ var EffectOpMiddlewareTag = class extends import_effect3.ServiceMap.Service()("Logix/EffectOpMiddleware") {
57
60
  };
58
61
  var composeMiddleware = (stack) => {
59
- return (op) => stack.reduceRight(
62
+ const cached = composeMiddlewareCache.get(stack);
63
+ if (cached) {
64
+ return cached;
65
+ }
66
+ const composed = (op) => stack.reduceRight(
60
67
  (eff, mw) => mw({ ...op, effect: eff }),
61
68
  op.effect
62
69
  );
70
+ composeMiddlewareCache.set(stack, composed);
71
+ return composed;
63
72
  };
64
73
  var runWithMiddleware = (op, stack) => {
65
74
  return import_effect3.Effect.gen(function* () {
66
- const existing = yield* import_effect3.FiberRef.get(currentLinkId);
75
+ const existing = yield* import_effect3.Effect.service(currentLinkId);
67
76
  const metaLinkId = op.meta?.linkId;
68
77
  const linkId = typeof metaLinkId === "string" && metaLinkId.length > 0 ? metaLinkId : existing ?? op.id;
69
78
  const nextOp = {
@@ -74,29 +83,51 @@ var runWithMiddleware = (op, stack) => {
74
83
  }
75
84
  };
76
85
  const program = stack.length ? composeMiddleware(stack)(nextOp) : nextOp.effect;
77
- return yield* import_effect3.Effect.locally(currentLinkId, linkId)(program);
86
+ return yield* import_effect3.Effect.provideService(program, currentLinkId, linkId);
78
87
  });
79
88
  };
80
89
 
81
- // src/internal/runtime/core/DebugSink.ts
82
- var currentDebugSinks = import_effect4.FiberRef.unsafeMake([]);
83
- var currentRuntimeLabel = import_effect4.FiberRef.unsafeMake(void 0);
84
- var currentTxnId = import_effect4.FiberRef.unsafeMake(void 0);
85
- var currentOpSeq = import_effect4.FiberRef.unsafeMake(void 0);
86
- var currentDiagnosticsLevel = import_effect4.FiberRef.unsafeMake("off");
87
- var currentTraitConvergeDiagnosticsSampling = import_effect4.FiberRef.unsafeMake({
88
- sampleEveryN: 32,
89
- topK: 3
90
+ // src/internal/runtime/core/DebugSink.record.ts
91
+ var currentDebugSinks = import_effect4.ServiceMap.Reference("@logixjs/core/Debug.currentDebugSinks", {
92
+ defaultValue: () => []
93
+ });
94
+ var currentRuntimeLabel = import_effect4.ServiceMap.Reference("@logixjs/core/Debug.currentRuntimeLabel", {
95
+ defaultValue: () => void 0
96
+ });
97
+ var currentTxnId = import_effect4.ServiceMap.Reference("@logixjs/core/Debug.currentTxnId", {
98
+ defaultValue: () => void 0
99
+ });
100
+ var currentOpSeq = import_effect4.ServiceMap.Reference("@logixjs/core/Debug.currentOpSeq", {
101
+ defaultValue: () => void 0
90
102
  });
103
+ var currentDiagnosticsLevel = import_effect4.ServiceMap.Reference("@logixjs/core/Debug.currentDiagnosticsLevel", {
104
+ defaultValue: () => "off"
105
+ });
106
+ var currentDiagnosticsMaterialization = import_effect4.ServiceMap.Reference(
107
+ "@logixjs/core/Debug.currentDiagnosticsMaterialization",
108
+ {
109
+ defaultValue: () => "eager"
110
+ }
111
+ );
112
+ var currentTraceMode = import_effect4.ServiceMap.Reference("@logixjs/core/Debug.currentTraceMode", {
113
+ defaultValue: () => "on"
114
+ });
115
+ var currentTraitConvergeDiagnosticsSampling = import_effect4.ServiceMap.Reference(
116
+ "@logixjs/core/Debug.currentTraitConvergeDiagnosticsSampling",
117
+ {
118
+ defaultValue: () => ({
119
+ sampleEveryN: 32,
120
+ topK: 3
121
+ })
122
+ }
123
+ );
91
124
  var browserLifecycleSeen = /* @__PURE__ */ new Set();
92
125
  var browserDiagnosticSeen = /* @__PURE__ */ new Set();
93
126
  var lifecycleErrorLog = (event) => {
94
127
  const moduleId = event.moduleId ?? "unknown";
95
128
  const causePretty = (() => {
96
129
  try {
97
- return import_effect4.Cause.pretty(event.cause, {
98
- renderErrorCause: true
99
- });
130
+ return import_effect4.Cause.pretty(event.cause);
100
131
  } catch {
101
132
  try {
102
133
  return JSON.stringify(event.cause, null, 2);
@@ -137,16 +168,16 @@ ${detail}`;
137
168
  }
138
169
  return base.pipe(import_effect4.Effect.annotateLogs(annotations));
139
170
  };
140
- var noopLayer = import_effect4.Layer.locallyScoped(currentDebugSinks, []);
171
+ var noopLayer = import_effect4.Layer.succeed(currentDebugSinks, []);
141
172
  var errorOnlySink = {
142
173
  record: (event) => event.type === "lifecycle:error" ? lifecycleErrorLog(event) : event.type === "diagnostic" && event.severity !== "info" ? diagnosticLog(event) : import_effect4.Effect.void
143
174
  };
144
- var errorOnlyLayer = import_effect4.Layer.locallyScoped(currentDebugSinks, [errorOnlySink]);
175
+ var errorOnlyLayer = import_effect4.Layer.succeed(currentDebugSinks, [errorOnlySink]);
145
176
  var isErrorOnlyOnlySinks = (sinks) => sinks.length === 1 && sinks[0] === errorOnlySink;
146
177
  var consoleSink = {
147
178
  record: (event) => event.type === "lifecycle:error" ? lifecycleErrorLog(event) : event.type === "diagnostic" ? diagnosticLog(event) : import_effect4.Effect.logDebug({ debugEvent: event })
148
179
  };
149
- var consoleLayer = import_effect4.Layer.locallyScoped(currentDebugSinks, [consoleSink]);
180
+ var consoleLayer = import_effect4.Layer.succeed(currentDebugSinks, [consoleSink]);
150
181
  var isBrowser = typeof window !== "undefined" && typeof document !== "undefined";
151
182
  var renderBrowserConsoleEvent = (event) => {
152
183
  if (typeof event.type === "string" && event.type.startsWith("trace:")) {
@@ -172,7 +203,7 @@ var renderBrowserConsoleEvent = (event) => {
172
203
  const moduleId = event.moduleId ?? "unknown";
173
204
  const causePretty = (() => {
174
205
  try {
175
- return import_effect4.Cause.pretty(event.cause, { renderErrorCause: true });
206
+ return import_effect4.Cause.pretty(event.cause);
176
207
  } catch {
177
208
  try {
178
209
  return JSON.stringify(event.cause, null, 2);
@@ -238,7 +269,7 @@ var browserConsoleSink = {
238
269
  return renderBrowserConsoleEvent(event);
239
270
  }
240
271
  };
241
- var browserConsoleLayer = import_effect4.Layer.locallyScoped(currentDebugSinks, [browserConsoleSink]);
272
+ var browserConsoleLayer = import_effect4.Layer.succeed(currentDebugSinks, [browserConsoleSink]);
242
273
  var browserDiagnosticConsoleSink = {
243
274
  record: (event) => {
244
275
  if (!isBrowser) {
@@ -247,36 +278,33 @@ var browserDiagnosticConsoleSink = {
247
278
  return event.type === "lifecycle:error" || event.type === "diagnostic" && event.severity !== "info" ? renderBrowserConsoleEvent(event) : import_effect4.Effect.void;
248
279
  }
249
280
  };
250
- var browserDiagnosticConsoleLayer = import_effect4.Layer.locallyScoped(currentDebugSinks, [browserDiagnosticConsoleSink]);
251
- var browserPrettyLoggerLayer = import_effect4.Logger.replace(
252
- import_effect4.Logger.defaultLogger,
253
- import_effect4.Logger.prettyLogger({ mode: "browser", colors: true })
281
+ var browserDiagnosticConsoleLayer = import_effect4.Layer.succeed(currentDebugSinks, [browserDiagnosticConsoleSink]);
282
+ var browserPrettyLoggerLayer = import_effect4.Layer.effect(
283
+ import_effect4.Logger.CurrentLoggers,
284
+ import_effect4.Effect.gen(function* () {
285
+ const current = yield* import_effect4.Effect.service(import_effect4.Logger.CurrentLoggers);
286
+ return new Set(
287
+ [...current].filter((logger) => logger !== import_effect4.Logger.defaultLogger).concat(import_effect4.Logger.consolePretty({ mode: "browser", colors: true }))
288
+ );
289
+ })
254
290
  );
255
291
  var record = (event) => import_effect4.Effect.gen(function* () {
256
- const sinks = yield* import_effect4.FiberRef.get(currentDebugSinks);
292
+ const sinks = yield* import_effect4.Effect.service(currentDebugSinks);
257
293
  if (isErrorOnlyOnlySinks(sinks)) {
258
294
  if (event.type === "lifecycle:error") {
259
295
  yield* lifecycleErrorLog(event);
260
296
  return;
261
297
  }
262
- if (event.type === "diagnostic") {
263
- if (event.severity !== "info") {
264
- yield* diagnosticLog(event);
265
- } else {
266
- yield* import_effect4.Effect.void;
267
- }
268
- return;
298
+ if (event.type === "diagnostic" && event.severity !== "info") {
299
+ yield* diagnosticLog(event);
269
300
  }
270
- yield* import_effect4.Effect.void;
271
301
  return;
272
302
  }
273
303
  if (sinks.length === 0) {
274
304
  if (isBrowser) {
275
305
  if (event.type === "lifecycle:error" || event.type === "diagnostic") {
276
306
  yield* renderBrowserConsoleEvent(event);
277
- return;
278
307
  }
279
- yield* import_effect4.Effect.void;
280
308
  return;
281
309
  }
282
310
  if (event.type === "lifecycle:error") {
@@ -285,13 +313,15 @@ var record = (event) => import_effect4.Effect.gen(function* () {
285
313
  }
286
314
  if (event.type === "diagnostic") {
287
315
  yield* diagnosticLog(event);
288
- return;
289
316
  }
290
- yield* import_effect4.Effect.void;
291
317
  return;
292
318
  }
319
+ if (typeof event.type === "string" && event.type.startsWith("trace:")) {
320
+ const mode = yield* import_effect4.Effect.service(currentTraceMode);
321
+ if (mode === "off") return;
322
+ }
293
323
  const enriched = event;
294
- const diagnosticsLevel = yield* import_effect4.FiberRef.get(currentDiagnosticsLevel);
324
+ const diagnosticsLevel = yield* import_effect4.Effect.service(currentDiagnosticsLevel);
295
325
  let now;
296
326
  const getNow = () => {
297
327
  if (now === void 0) now = Date.now();
@@ -302,24 +332,24 @@ var record = (event) => import_effect4.Effect.gen(function* () {
302
332
  enriched.timestamp = getNow();
303
333
  }
304
334
  if (diagnosticsLevel !== "off" && enriched.runtimeLabel === void 0) {
305
- const runtimeLabel = yield* import_effect4.FiberRef.get(currentRuntimeLabel);
335
+ const runtimeLabel = yield* import_effect4.Effect.service(currentRuntimeLabel);
306
336
  if (runtimeLabel) {
307
337
  ;
308
338
  enriched.runtimeLabel = runtimeLabel;
309
339
  }
310
340
  }
311
341
  if (enriched.type === "diagnostic" && enriched.txnId === void 0) {
312
- const txnId = yield* import_effect4.FiberRef.get(currentTxnId);
342
+ const txnId = yield* import_effect4.Effect.service(currentTxnId);
313
343
  if (txnId) {
314
344
  ;
315
345
  enriched.txnId = txnId;
316
346
  }
317
347
  }
318
348
  if (diagnosticsLevel !== "off" && enriched.type === "trace:effectop" && enriched.linkId === void 0) {
319
- const linkId = yield* import_effect4.FiberRef.get(currentLinkId);
320
- if (linkId) {
349
+ const maybeLinkId = yield* import_effect4.Effect.serviceOption(currentLinkId);
350
+ if (import_effect4.Option.isSome(maybeLinkId) && maybeLinkId.value) {
321
351
  ;
322
- enriched.linkId = linkId;
352
+ enriched.linkId = maybeLinkId.value;
323
353
  }
324
354
  }
325
355
  if (sinks.length === 1) {
@@ -330,7 +360,508 @@ var record = (event) => import_effect4.Effect.gen(function* () {
330
360
  });
331
361
 
332
362
  // src/internal/runtime/core/env.ts
363
+ var import_effect7 = require("effect");
364
+
365
+ // src/internal/runtime/core/HostScheduler.ts
366
+ var noopCancel = () => {
367
+ };
368
+ var safeNowMs = () => {
369
+ const perf = globalThis.performance;
370
+ if (perf && typeof perf.now === "function") {
371
+ try {
372
+ const v = perf.now();
373
+ if (typeof v === "number" && Number.isFinite(v)) return v;
374
+ } catch {
375
+ }
376
+ }
377
+ return Date.now();
378
+ };
379
+ var safeQueueMicrotask = (cb) => {
380
+ const qm = globalThis.queueMicrotask;
381
+ if (typeof qm === "function") {
382
+ try {
383
+ qm(cb);
384
+ return;
385
+ } catch {
386
+ }
387
+ }
388
+ try {
389
+ Promise.resolve().then(cb);
390
+ } catch {
391
+ setTimeout(cb, 0);
392
+ }
393
+ };
394
+ var safeSetTimeout = (ms, cb) => {
395
+ const id = setTimeout(cb, ms);
396
+ return () => {
397
+ try {
398
+ clearTimeout(id);
399
+ } catch {
400
+ }
401
+ };
402
+ };
403
+ var makeMessageChannelMacrotask = () => {
404
+ const MC = globalThis.MessageChannel;
405
+ if (typeof MC !== "function") return void 0;
406
+ let channel;
407
+ try {
408
+ channel = new MC();
409
+ } catch {
410
+ return void 0;
411
+ }
412
+ const queue = [];
413
+ let scheduled = false;
414
+ const flush = () => {
415
+ scheduled = false;
416
+ const tasks = queue.splice(0, queue.length);
417
+ for (const t of tasks) {
418
+ if (t.canceled) continue;
419
+ try {
420
+ t.cb();
421
+ } catch {
422
+ }
423
+ }
424
+ };
425
+ try {
426
+ channel.port1.onmessage = flush;
427
+ } catch {
428
+ return void 0;
429
+ }
430
+ const schedule = (cb) => {
431
+ const task = { canceled: false, cb };
432
+ queue.push(task);
433
+ if (!scheduled) {
434
+ scheduled = true;
435
+ try {
436
+ channel.port2.postMessage(void 0);
437
+ } catch {
438
+ scheduled = false;
439
+ return safeSetTimeout(0, cb);
440
+ }
441
+ }
442
+ return () => {
443
+ task.canceled = true;
444
+ };
445
+ };
446
+ return schedule;
447
+ };
448
+ var makeSetImmediateMacrotask = () => {
449
+ const si = globalThis.setImmediate;
450
+ const ci = globalThis.clearImmediate;
451
+ if (typeof si !== "function") return void 0;
452
+ return (cb) => {
453
+ let id;
454
+ try {
455
+ id = si(cb);
456
+ } catch {
457
+ return safeSetTimeout(0, cb);
458
+ }
459
+ return () => {
460
+ if (typeof ci !== "function") return;
461
+ try {
462
+ ci(id);
463
+ } catch {
464
+ }
465
+ };
466
+ };
467
+ };
468
+ var makeRaf = () => {
469
+ const raf = globalThis.requestAnimationFrame;
470
+ const cancel = globalThis.cancelAnimationFrame;
471
+ if (typeof raf !== "function") return void 0;
472
+ return (cb) => {
473
+ let id;
474
+ try {
475
+ id = raf(cb);
476
+ } catch {
477
+ return noopCancel;
478
+ }
479
+ return () => {
480
+ if (typeof cancel !== "function") return;
481
+ try {
482
+ cancel(id);
483
+ } catch {
484
+ }
485
+ };
486
+ };
487
+ };
488
+ var makeDefaultHostScheduler = () => {
489
+ const macrotask = makeSetImmediateMacrotask() ?? makeMessageChannelMacrotask() ?? ((cb) => safeSetTimeout(0, cb));
490
+ const raf = makeRaf();
491
+ return {
492
+ nowMs: safeNowMs,
493
+ scheduleMicrotask: safeQueueMicrotask,
494
+ scheduleMacrotask: macrotask,
495
+ scheduleAnimationFrame: (cb) => raf?.(cb) ?? macrotask(cb),
496
+ scheduleTimeout: safeSetTimeout
497
+ };
498
+ };
499
+ var globalHostScheduler;
500
+ var getGlobalHostScheduler = () => {
501
+ globalHostScheduler ?? (globalHostScheduler = makeDefaultHostScheduler());
502
+ return globalHostScheduler;
503
+ };
504
+
505
+ // src/internal/runtime/core/RuntimeStore.ts
506
+ var parseTopicKey = (topicKey) => {
507
+ const idx = topicKey.indexOf("::");
508
+ if (idx <= 0) return void 0;
509
+ const moduleId = topicKey.slice(0, idx);
510
+ const rest = topicKey.slice(idx + 2);
511
+ if (rest.length === 0) return void 0;
512
+ const idx2 = rest.indexOf("::");
513
+ if (idx2 < 0) {
514
+ return { kind: "module", moduleInstanceKey: `${moduleId}::${rest}` };
515
+ }
516
+ const instanceId = rest.slice(0, idx2);
517
+ const suffix = rest.slice(idx2 + 2);
518
+ if (suffix.startsWith("rq:")) {
519
+ const selectorId = suffix.slice("rq:".length);
520
+ if (selectorId.length === 0) return void 0;
521
+ return {
522
+ kind: "readQuery",
523
+ moduleInstanceKey: `${moduleId}::${instanceId}`,
524
+ selectorId
525
+ };
526
+ }
527
+ return { kind: "module", moduleInstanceKey: `${moduleId}::${instanceId}` };
528
+ };
529
+ var EMPTY_LISTENER_SNAPSHOT = [];
530
+ var NO_CHANGED_TOPIC_LISTENERS = [];
531
+ var makeRuntimeStore = () => {
532
+ let tickSeq = 0;
533
+ const moduleStates = /* @__PURE__ */ new Map();
534
+ const topicVersions = /* @__PURE__ */ new Map();
535
+ const topicPriorities = /* @__PURE__ */ new Map();
536
+ const listenersByTopic = /* @__PURE__ */ new Map();
537
+ const subscriberCountByModule = /* @__PURE__ */ new Map();
538
+ const getTopicVersion = (topicKey) => topicVersions.get(topicKey) ?? 0;
539
+ const getTopicPriority = (topicKey) => topicPriorities.get(topicKey) ?? "normal";
540
+ const commitTopicBump = (topicKey, priority) => {
541
+ const prev = topicVersions.get(topicKey) ?? 0;
542
+ topicVersions.set(topicKey, prev + 1);
543
+ topicPriorities.set(topicKey, priority);
544
+ };
545
+ const refreshTopicSnapshot = (state) => {
546
+ state.snapshot = Array.from(state.listeners);
547
+ };
548
+ const subscribeTopic = (topicKey, listener) => {
549
+ const info = parseTopicKey(topicKey);
550
+ const existing = listenersByTopic.get(topicKey);
551
+ const state = existing ?? { listeners: /* @__PURE__ */ new Set(), snapshot: EMPTY_LISTENER_SNAPSHOT };
552
+ const alreadyHas = state.listeners.has(listener);
553
+ if (!alreadyHas) {
554
+ state.listeners.add(listener);
555
+ refreshTopicSnapshot(state);
556
+ }
557
+ if (!existing) {
558
+ listenersByTopic.set(topicKey, state);
559
+ }
560
+ if (!alreadyHas && info) {
561
+ const prev = subscriberCountByModule.get(info.moduleInstanceKey) ?? 0;
562
+ subscriberCountByModule.set(info.moduleInstanceKey, prev + 1);
563
+ }
564
+ return () => {
565
+ const currentState = listenersByTopic.get(topicKey);
566
+ if (!currentState) return;
567
+ const deleted = currentState.listeners.delete(listener);
568
+ if (deleted && info) {
569
+ const prev = subscriberCountByModule.get(info.moduleInstanceKey) ?? 0;
570
+ const next = prev - 1;
571
+ if (next <= 0) {
572
+ subscriberCountByModule.delete(info.moduleInstanceKey);
573
+ } else {
574
+ subscriberCountByModule.set(info.moduleInstanceKey, next);
575
+ }
576
+ }
577
+ if (currentState.listeners.size === 0) {
578
+ listenersByTopic.delete(topicKey);
579
+ } else if (deleted) {
580
+ refreshTopicSnapshot(currentState);
581
+ }
582
+ };
583
+ };
584
+ const getTopicSubscriberCount = (topicKey) => listenersByTopic.get(topicKey)?.listeners.size ?? 0;
585
+ const getModuleSubscriberCount = (moduleInstanceKey) => subscriberCountByModule.get(moduleInstanceKey) ?? 0;
586
+ const registerModuleInstance = (args) => {
587
+ moduleStates.set(args.moduleInstanceKey, args.initialState);
588
+ if (!topicVersions.has(args.moduleInstanceKey)) {
589
+ topicVersions.set(args.moduleInstanceKey, 0);
590
+ topicPriorities.set(args.moduleInstanceKey, "normal");
591
+ }
592
+ };
593
+ const unregisterModuleInstance = (moduleInstanceKey) => {
594
+ moduleStates.delete(moduleInstanceKey);
595
+ };
596
+ const commitTick = (args) => {
597
+ tickSeq = args.tickSeq;
598
+ for (const [key, commit] of args.accepted.modules) {
599
+ moduleStates.set(key, commit.state);
600
+ }
601
+ if (args.accepted.dirtyTopics.size === 0) {
602
+ return {
603
+ changedTopicListeners: NO_CHANGED_TOPIC_LISTENERS
604
+ };
605
+ }
606
+ if (args.onListener) {
607
+ let firstTopicListeners;
608
+ let secondTopicListeners;
609
+ let restTopicListeners;
610
+ for (const [topicKey, priority] of args.accepted.dirtyTopics) {
611
+ commitTopicBump(topicKey, priority);
612
+ const listeners = listenersByTopic.get(topicKey)?.snapshot ?? EMPTY_LISTENER_SNAPSHOT;
613
+ if (listeners.length === 0) {
614
+ continue;
615
+ }
616
+ if (!firstTopicListeners) {
617
+ firstTopicListeners = listeners;
618
+ continue;
619
+ }
620
+ if (!secondTopicListeners) {
621
+ secondTopicListeners = listeners;
622
+ continue;
623
+ }
624
+ if (!restTopicListeners) {
625
+ restTopicListeners = [];
626
+ }
627
+ restTopicListeners.push(listeners);
628
+ }
629
+ if (firstTopicListeners) {
630
+ for (const listener of firstTopicListeners) {
631
+ try {
632
+ args.onListener(listener);
633
+ } catch {
634
+ }
635
+ }
636
+ }
637
+ if (secondTopicListeners) {
638
+ for (const listener of secondTopicListeners) {
639
+ try {
640
+ args.onListener(listener);
641
+ } catch {
642
+ }
643
+ }
644
+ }
645
+ if (restTopicListeners) {
646
+ for (const listeners of restTopicListeners) {
647
+ for (const listener of listeners) {
648
+ try {
649
+ args.onListener(listener);
650
+ } catch {
651
+ }
652
+ }
653
+ }
654
+ }
655
+ return {
656
+ changedTopicListeners: NO_CHANGED_TOPIC_LISTENERS
657
+ };
658
+ }
659
+ let singleTopicListeners;
660
+ let flattenedTopicListeners;
661
+ for (const [topicKey, priority] of args.accepted.dirtyTopics) {
662
+ commitTopicBump(topicKey, priority);
663
+ const listeners = listenersByTopic.get(topicKey)?.snapshot ?? EMPTY_LISTENER_SNAPSHOT;
664
+ if (listeners.length === 0) {
665
+ continue;
666
+ }
667
+ if (flattenedTopicListeners) {
668
+ for (const listener of listeners) {
669
+ flattenedTopicListeners.push(listener);
670
+ }
671
+ continue;
672
+ }
673
+ if (!singleTopicListeners) {
674
+ singleTopicListeners = listeners;
675
+ continue;
676
+ }
677
+ flattenedTopicListeners = Array.from(singleTopicListeners);
678
+ for (const listener of listeners) {
679
+ flattenedTopicListeners.push(listener);
680
+ }
681
+ }
682
+ return {
683
+ changedTopicListeners: flattenedTopicListeners ?? singleTopicListeners ?? NO_CHANGED_TOPIC_LISTENERS
684
+ };
685
+ };
686
+ const getModuleState = (moduleInstanceKey) => moduleStates.get(moduleInstanceKey);
687
+ const dispose = () => {
688
+ moduleStates.clear();
689
+ topicVersions.clear();
690
+ topicPriorities.clear();
691
+ listenersByTopic.clear();
692
+ subscriberCountByModule.clear();
693
+ };
694
+ return {
695
+ getTickSeq: () => tickSeq,
696
+ getModuleState,
697
+ getTopicVersion,
698
+ getTopicPriority,
699
+ subscribeTopic,
700
+ getTopicSubscriberCount,
701
+ getModuleSubscriberCount,
702
+ registerModuleInstance,
703
+ unregisterModuleInstance,
704
+ commitTick,
705
+ dispose
706
+ };
707
+ };
708
+
709
+ // src/internal/runtime/core/TickScheduler.ts
333
710
  var import_effect5 = require("effect");
711
+
712
+ // src/internal/runtime/core/DeclarativeLinkRuntime.ts
713
+ var import_effect6 = require("effect");
714
+ var makeDeclarativeLinkRuntime = () => {
715
+ const moduleAsSourceById = /* @__PURE__ */ new Map();
716
+ const moduleAsSourceIdsBySource = /* @__PURE__ */ new Map();
717
+ const declarativeById = /* @__PURE__ */ new Map();
718
+ const declarativeReadNodesBySource = /* @__PURE__ */ new Map();
719
+ const registerModuleAsSourceLink = (link) => {
720
+ const stored = {
721
+ ...link,
722
+ hasValue: false,
723
+ lastValue: void 0
724
+ };
725
+ moduleAsSourceById.set(link.id, stored);
726
+ const set = moduleAsSourceIdsBySource.get(link.sourceModuleInstanceKey) ?? /* @__PURE__ */ new Set();
727
+ set.add(link.id);
728
+ moduleAsSourceIdsBySource.set(link.sourceModuleInstanceKey, set);
729
+ return () => {
730
+ moduleAsSourceById.delete(link.id);
731
+ const current = moduleAsSourceIdsBySource.get(link.sourceModuleInstanceKey);
732
+ if (!current) return;
733
+ current.delete(link.id);
734
+ if (current.size === 0) {
735
+ moduleAsSourceIdsBySource.delete(link.sourceModuleInstanceKey);
736
+ }
737
+ };
738
+ };
739
+ const registerDeclarativeLink = (link) => {
740
+ const readNodeById = /* @__PURE__ */ new Map();
741
+ for (const n of link.readNodes) {
742
+ readNodeById.set(n.nodeId, n);
743
+ }
744
+ const dispatchNodeById = /* @__PURE__ */ new Map();
745
+ for (const n of link.dispatchNodes) {
746
+ dispatchNodeById.set(n.nodeId, n);
747
+ }
748
+ const incomingByDispatch = /* @__PURE__ */ new Map();
749
+ for (const e of link.ir.edges) {
750
+ const to = e.to;
751
+ const isDispatch = dispatchNodeById.has(to);
752
+ if (!isDispatch) continue;
753
+ incomingByDispatch.set(to, (incomingByDispatch.get(to) ?? 0) + 1);
754
+ const count = incomingByDispatch.get(to) ?? 0;
755
+ if (count > 1) {
756
+ throw new Error(
757
+ `[DeclarativeLinkRuntime] Invalid DeclarativeLinkIR: dispatch node has multiple incoming edges (linkId=${link.linkId}, nodeId=${to}).`
758
+ );
759
+ }
760
+ }
761
+ const dispatchTargetsByReadNode = /* @__PURE__ */ new Map();
762
+ for (const e of link.ir.edges) {
763
+ const from = e.from;
764
+ const to = e.to;
765
+ if (!readNodeById.has(from)) continue;
766
+ if (!dispatchNodeById.has(to)) continue;
767
+ const list = dispatchTargetsByReadNode.get(from) ?? [];
768
+ list.push(to);
769
+ dispatchTargetsByReadNode.set(from, list);
770
+ }
771
+ const stored = {
772
+ ...link,
773
+ readNodeById,
774
+ dispatchNodeById,
775
+ dispatchTargetsByReadNode,
776
+ readNodeState: /* @__PURE__ */ new Map()
777
+ };
778
+ declarativeById.set(link.linkId, stored);
779
+ for (const n of link.readNodes) {
780
+ const list = declarativeReadNodesBySource.get(n.moduleInstanceKey) ?? [];
781
+ list.push({ linkId: link.linkId, nodeId: n.nodeId });
782
+ declarativeReadNodesBySource.set(n.moduleInstanceKey, list);
783
+ }
784
+ return () => {
785
+ declarativeById.delete(link.linkId);
786
+ for (const n of link.readNodes) {
787
+ const list = declarativeReadNodesBySource.get(n.moduleInstanceKey);
788
+ if (!list) continue;
789
+ const next = list.filter((x) => !(x.linkId === link.linkId && x.nodeId === n.nodeId));
790
+ if (next.length === 0) {
791
+ declarativeReadNodesBySource.delete(n.moduleInstanceKey);
792
+ } else {
793
+ declarativeReadNodesBySource.set(n.moduleInstanceKey, next);
794
+ }
795
+ }
796
+ };
797
+ };
798
+ const applyForSources = (args) => import_effect6.Effect.gen(function* () {
799
+ let scheduled = false;
800
+ for (const sourceKey of args.changedModuleInstanceKeys) {
801
+ const ids = moduleAsSourceIdsBySource.get(sourceKey);
802
+ if (!ids || ids.size === 0) continue;
803
+ const commit = args.acceptedModules.get(sourceKey);
804
+ if (!commit) continue;
805
+ for (const id of ids) {
806
+ const link = moduleAsSourceById.get(id);
807
+ if (!link) continue;
808
+ let selected;
809
+ try {
810
+ selected = link.readQuery.select(commit.state);
811
+ } catch {
812
+ continue;
813
+ }
814
+ const nextValue = link.computeValue(selected);
815
+ if (link.hasValue && link.equalsValue(link.lastValue, nextValue)) {
816
+ continue;
817
+ }
818
+ link.hasValue = true;
819
+ link.lastValue = nextValue;
820
+ scheduled = true;
821
+ yield* link.applyValue(nextValue);
822
+ }
823
+ }
824
+ for (const sourceKey of args.changedModuleInstanceKeys) {
825
+ const refs = declarativeReadNodesBySource.get(sourceKey);
826
+ if (!refs || refs.length === 0) continue;
827
+ const commit = args.acceptedModules.get(sourceKey);
828
+ if (!commit) continue;
829
+ for (const ref of refs) {
830
+ const link = declarativeById.get(ref.linkId);
831
+ if (!link) continue;
832
+ const readNode = link.readNodeById.get(ref.nodeId);
833
+ if (!readNode) continue;
834
+ let value;
835
+ try {
836
+ value = readNode.readQuery.select(commit.state);
837
+ } catch {
838
+ continue;
839
+ }
840
+ const state = link.readNodeState.get(ref.nodeId) ?? { hasValue: false, lastValue: void 0 };
841
+ const changed = !state.hasValue || !Object.is(state.lastValue, value);
842
+ if (!changed) continue;
843
+ state.hasValue = true;
844
+ state.lastValue = value;
845
+ link.readNodeState.set(ref.nodeId, state);
846
+ const targets = link.dispatchTargetsByReadNode.get(ref.nodeId) ?? [];
847
+ for (const dispatchNodeId of targets) {
848
+ const node = link.dispatchNodeById.get(dispatchNodeId);
849
+ if (!node) continue;
850
+ scheduled = true;
851
+ yield* node.dispatch(value);
852
+ }
853
+ }
854
+ }
855
+ return { scheduled };
856
+ });
857
+ return {
858
+ registerModuleAsSourceLink,
859
+ registerDeclarativeLink,
860
+ applyForSources
861
+ };
862
+ };
863
+
864
+ // src/internal/runtime/core/env.ts
334
865
  var getNodeEnv = () => {
335
866
  try {
336
867
  const env = globalThis?.process?.env;
@@ -340,22 +871,174 @@ var getNodeEnv = () => {
340
871
  }
341
872
  };
342
873
  var isDevEnv = () => getNodeEnv() !== "production";
343
- var StateTransactionConfigTagImpl = class extends import_effect5.Context.Tag("@logixjs/core/StateTransactionRuntimeConfig")() {
874
+ var StateTransactionConfigTagImpl = class extends import_effect7.ServiceMap.Service()("@logixjs/core/StateTransactionRuntimeConfig") {
875
+ };
876
+ var ReadQueryStrictGateConfigTagImpl = class extends import_effect7.ServiceMap.Service()("@logixjs/core/ReadQueryStrictGateRuntimeConfig") {
344
877
  };
345
- var ReadQueryStrictGateConfigTagImpl = class extends import_effect5.Context.Tag("@logixjs/core/ReadQueryStrictGateRuntimeConfig")() {
878
+ var ReplayModeConfigTagImpl = class extends import_effect7.ServiceMap.Service()("@logixjs/core/ReplayModeConfig") {
346
879
  };
347
- var ReplayModeConfigTagImpl = class extends import_effect5.Context.Tag("@logixjs/core/ReplayModeConfig")() {
880
+ var StateTransactionOverridesTagImpl = class extends import_effect7.ServiceMap.Service()("@logixjs/core/StateTransactionOverrides") {
348
881
  };
349
- var StateTransactionOverridesTagImpl = class extends import_effect5.Context.Tag("@logixjs/core/StateTransactionOverrides")() {
882
+ var SchedulingPolicySurfaceTagImpl = class extends import_effect7.ServiceMap.Service()("@logixjs/core/SchedulingPolicySurface") {
350
883
  };
351
- var ConcurrencyPolicyTagImpl = class extends import_effect5.Context.Tag("@logixjs/core/ConcurrencyPolicy")() {
884
+ var SchedulingPolicySurfaceOverridesTagImpl = class extends import_effect7.ServiceMap.Service()("@logixjs/core/SchedulingPolicySurfaceOverrides") {
352
885
  };
353
- var ConcurrencyPolicyOverridesTagImpl = class extends import_effect5.Context.Tag("@logixjs/core/ConcurrencyPolicyOverrides")() {
886
+ var RuntimeStoreTag = class extends import_effect7.ServiceMap.Service()("@logixjs/core/RuntimeStore") {
887
+ };
888
+ var runtimeStoreLayer = import_effect7.Layer.effect(
889
+ RuntimeStoreTag,
890
+ import_effect7.Effect.acquireRelease(
891
+ import_effect7.Effect.sync(() => makeRuntimeStore()),
892
+ (store) => import_effect7.Effect.sync(() => store.dispose())
893
+ )
894
+ );
895
+ var HostSchedulerTag = class extends import_effect7.ServiceMap.Service()("@logixjs/core/HostScheduler") {
896
+ };
897
+ var hostSchedulerLayer = import_effect7.Layer.succeed(
898
+ HostSchedulerTag,
899
+ getGlobalHostScheduler()
900
+ );
901
+ var DeclarativeLinkRuntimeTag = class extends import_effect7.ServiceMap.Service()("@logixjs/core/DeclarativeLinkRuntime") {
902
+ };
903
+ var declarativeLinkRuntimeLayer = import_effect7.Layer.succeed(
904
+ DeclarativeLinkRuntimeTag,
905
+ makeDeclarativeLinkRuntime()
906
+ );
907
+ var TickSchedulerTag = class extends import_effect7.ServiceMap.Service()("@logixjs/core/TickScheduler") {
908
+ };
909
+
910
+ // src/internal/runtime/core/ModeRunner.ts
911
+ var import_effect9 = require("effect");
912
+
913
+ // src/internal/runtime/core/LatestFiberSlot.ts
914
+ var import_effect8 = require("effect");
915
+ var make = () => import_effect8.Ref.make({
916
+ fiber: void 0,
917
+ runningId: 0,
918
+ nextId: 0
919
+ });
920
+ var beginRun = (slotRef) => import_effect8.Ref.modify(slotRef, (state) => {
921
+ const runId = state.nextId + 1;
922
+ const prevFiber = state.fiber;
923
+ const prevRunningId = state.runningId;
924
+ state.nextId = runId;
925
+ state.runningId = runId;
926
+ return [[prevFiber, prevRunningId, runId], state];
927
+ });
928
+ var setFiberIfCurrent = (slotRef, runId, fiber) => import_effect8.Ref.update(slotRef, (state) => {
929
+ if (state.runningId === runId) {
930
+ state.fiber = fiber;
931
+ }
932
+ return state;
933
+ });
934
+ var clearIfCurrent = (slotRef, runId) => import_effect8.Ref.update(slotRef, (state) => {
935
+ if (state.runningId === runId) {
936
+ state.runningId = 0;
937
+ state.fiber = void 0;
938
+ }
939
+ return state;
940
+ });
941
+
942
+ // src/internal/runtime/core/ModeRunner.ts
943
+ var EXHAUST_ACQUIRE_BUSY = [true, true];
944
+ var EXHAUST_REJECT_BUSY = [false, true];
945
+ var beginSwitchLatestRun = (stateRef) => import_effect9.Ref.modify(stateRef, (state) => {
946
+ const runId = state.nextId + 1;
947
+ state.nextId = runId;
948
+ state.runningId = runId;
949
+ return [runId, state];
950
+ });
951
+ var clearSwitchLatestIfCurrent = (stateRef, runId) => import_effect9.Ref.update(stateRef, (state) => {
952
+ if (state.runningId === runId) {
953
+ state.runningId = 0;
954
+ }
955
+ return state;
956
+ });
957
+ var runLatestSwitch = (stream, runLatest) => import_effect9.Effect.gen(function* () {
958
+ const stateRef = yield* import_effect9.Ref.make({
959
+ runningId: 0,
960
+ nextId: 0
961
+ });
962
+ const makeEffect = (payload) => import_effect9.Effect.gen(function* () {
963
+ const runId = yield* beginSwitchLatestRun(stateRef);
964
+ const isCurrent = import_effect9.Ref.get(stateRef).pipe(import_effect9.Effect.map((state) => state.runningId === runId));
965
+ yield* runLatest(payload, { runId, isCurrent }).pipe(import_effect9.Effect.ensuring(clearSwitchLatestIfCurrent(stateRef, runId)));
966
+ });
967
+ return yield* import_effect9.Stream.runDrain(
968
+ import_effect9.Stream.map(stream, makeEffect).pipe(import_effect9.Stream.switchMap((effect) => import_effect9.Stream.fromEffect(effect)))
969
+ );
970
+ });
971
+ var runLatestFiberSlot = (stream, runLatest, awaitLatestOnEnd) => import_effect9.Effect.gen(function* () {
972
+ const stateRef = yield* make();
973
+ const start = (payload) => import_effect9.Effect.gen(function* () {
974
+ const [prevFiber, prevRunningId, runId] = yield* beginRun(stateRef);
975
+ if (prevFiber && prevRunningId !== 0) {
976
+ yield* import_effect9.Fiber.interrupt(prevFiber);
977
+ }
978
+ const isCurrent = import_effect9.Ref.get(stateRef).pipe(import_effect9.Effect.map((state) => state.runningId === runId));
979
+ const fiber = yield* import_effect9.Effect.forkChild(
980
+ runLatest(payload, { runId, isCurrent }).pipe(import_effect9.Effect.ensuring(clearIfCurrent(stateRef, runId)))
981
+ );
982
+ yield* setFiberIfCurrent(stateRef, runId, fiber);
983
+ });
984
+ yield* import_effect9.Stream.runForEach(stream, start);
985
+ if (!awaitLatestOnEnd) {
986
+ return;
987
+ }
988
+ const finalState = yield* import_effect9.Ref.get(stateRef);
989
+ const finalFiber = finalState.runningId !== 0 ? finalState.fiber : void 0;
990
+ if (finalFiber) {
991
+ yield* import_effect9.Fiber.join(finalFiber);
992
+ }
993
+ });
994
+ var runExhaust = (stream, run2, resolveConcurrencyLimit2) => import_effect9.Effect.gen(function* () {
995
+ const concurrency = yield* resolveConcurrencyLimit2;
996
+ const busyRef = yield* import_effect9.Ref.make(false);
997
+ const mapper = (payload) => import_effect9.Effect.gen(function* () {
998
+ const acquired = yield* import_effect9.Ref.modify(
999
+ busyRef,
1000
+ (busy) => busy ? EXHAUST_REJECT_BUSY : EXHAUST_ACQUIRE_BUSY
1001
+ );
1002
+ if (!acquired) {
1003
+ return;
1004
+ }
1005
+ try {
1006
+ yield* run2(payload);
1007
+ } finally {
1008
+ yield* import_effect9.Ref.set(busyRef, false);
1009
+ }
1010
+ });
1011
+ return yield* import_effect9.Stream.runDrain(stream.pipe(import_effect9.Stream.mapEffect(mapper, { concurrency })));
1012
+ });
1013
+ var runParallel = (stream, run2, resolveConcurrencyLimit2) => import_effect9.Effect.gen(function* () {
1014
+ const concurrency = yield* resolveConcurrencyLimit2;
1015
+ return yield* import_effect9.Stream.runDrain(stream.pipe(import_effect9.Stream.mapEffect(run2, { concurrency })));
1016
+ });
1017
+ var runByMode = (config) => {
1018
+ const runLatest = config.runLatest ?? ((payload) => config.run(payload));
1019
+ if (config.mode === "latest") {
1020
+ const strategy = config.latest?.strategy ?? "switch";
1021
+ if (strategy === "fiber-slot") {
1022
+ return runLatestFiberSlot(config.stream, runLatest, config.latest?.awaitLatestOnEnd ?? false);
1023
+ }
1024
+ return runLatestSwitch(config.stream, runLatest);
1025
+ }
1026
+ if (config.mode === "exhaust") {
1027
+ return runExhaust(config.stream, config.run, config.resolveConcurrencyLimit);
1028
+ }
1029
+ if (config.mode === "parallel") {
1030
+ return runParallel(config.stream, config.run, config.resolveConcurrencyLimit);
1031
+ }
1032
+ return import_effect9.Stream.runForEach(config.stream, config.run);
354
1033
  };
355
1034
 
356
1035
  // src/internal/runtime/core/TaskRunner.ts
357
- var inSyncTransactionFiber = import_effect6.FiberRef.unsafeMake(false);
358
- var forceSourceRefresh = import_effect6.FiberRef.unsafeMake(false);
1036
+ var inSyncTransactionFiber = import_effect10.ServiceMap.Reference("@logixjs/core/TaskRunner.inSyncTransactionFiber", {
1037
+ defaultValue: () => false
1038
+ });
1039
+ var forceSourceRefresh = import_effect10.ServiceMap.Reference("@logixjs/core/TaskRunner.forceSourceRefresh", {
1040
+ defaultValue: () => false
1041
+ });
359
1042
  var resolve = (eff, payload) => typeof eff === "function" ? eff(payload) : eff;
360
1043
  var defaultOrigins = (triggerName) => ({
361
1044
  pending: {
@@ -371,8 +1054,8 @@ var defaultOrigins = (triggerName) => ({
371
1054
  name: "task:failure"
372
1055
  }
373
1056
  });
374
- var shouldNoopInSyncTransactionFiber = (options) => import_effect6.Effect.gen(function* () {
375
- const inTxn = yield* import_effect6.FiberRef.get(inSyncTransactionFiber);
1057
+ var shouldNoopInSyncTransactionFiber = (options) => import_effect10.Effect.gen(function* () {
1058
+ const inTxn = yield* import_effect10.Effect.service(inSyncTransactionFiber);
376
1059
  if (!inTxn) {
377
1060
  return false;
378
1061
  }
@@ -391,8 +1074,8 @@ var shouldNoopInSyncTransactionFiber = (options) => import_effect6.Effect.gen(fu
391
1074
  }
392
1075
  return true;
393
1076
  });
394
- var resolveConcurrencyLimit = (runtime) => runtime.resolveConcurrencyPolicy ? runtime.resolveConcurrencyPolicy().pipe(import_effect6.Effect.map((p) => p.concurrencyLimit)) : import_effect6.Effect.succeed(16);
395
- var runTaskLifecycle = (payload, runtime, config, getCanWriteBack) => import_effect6.Effect.gen(function* () {
1077
+ var resolveConcurrencyLimit = (runtime) => runtime.resolveConcurrencyPolicy ? runtime.resolveConcurrencyPolicy().pipe(import_effect10.Effect.map((p) => p.concurrencyLimit)) : import_effect10.Effect.succeed(16);
1078
+ var runTaskLifecycle = (payload, runtime, config, getCanWriteBack) => import_effect10.Effect.gen(function* () {
396
1079
  const noop = yield* shouldNoopInSyncTransactionFiber({
397
1080
  moduleId: runtime.moduleId,
398
1081
  instanceId: runtime.instanceId,
@@ -413,12 +1096,12 @@ var runTaskLifecycle = (payload, runtime, config, getCanWriteBack) => import_eff
413
1096
  };
414
1097
  const pending = config.pending;
415
1098
  if (pending) {
416
- yield* import_effect6.Effect.uninterruptible(
417
- runtime.runWithStateTransaction(origins.pending, () => import_effect6.Effect.asVoid(resolve(pending, payload)))
1099
+ yield* import_effect10.Effect.uninterruptible(
1100
+ runtime.runWithStateTransaction(origins.pending, () => import_effect10.Effect.asVoid(resolve(pending, payload)))
418
1101
  );
419
1102
  }
420
1103
  const io = resolve(config.effect, payload);
421
- const exit = yield* import_effect6.Effect.exit(io);
1104
+ const exit = yield* import_effect10.Effect.exit(io);
422
1105
  if (getCanWriteBack) {
423
1106
  const ok = yield* getCanWriteBack;
424
1107
  if (!ok) {
@@ -428,96 +1111,59 @@ var runTaskLifecycle = (payload, runtime, config, getCanWriteBack) => import_eff
428
1111
  if (exit._tag === "Success") {
429
1112
  const success = config.success;
430
1113
  if (success) {
431
- yield* runtime.runWithStateTransaction(origins.success, () => import_effect6.Effect.asVoid(success(exit.value, payload)));
1114
+ yield* runtime.runWithStateTransaction(origins.success, () => import_effect10.Effect.asVoid(success(exit.value, payload)));
432
1115
  }
433
1116
  return;
434
1117
  }
435
1118
  const cause = exit.cause;
436
- if (import_effect6.Cause.isInterrupted(cause)) {
1119
+ if (import_effect10.Cause.hasInterruptsOnly(cause)) {
437
1120
  return;
438
1121
  }
439
1122
  const failure = config.failure;
440
1123
  if (failure) {
441
- yield* runtime.runWithStateTransaction(origins.failure, () => import_effect6.Effect.asVoid(failure(cause, payload)));
1124
+ yield* runtime.runWithStateTransaction(origins.failure, () => import_effect10.Effect.asVoid(failure(cause, payload)));
442
1125
  }
443
1126
  }).pipe(
444
1127
  // Watchers must not crash as a whole due to a single task failure: swallow errors, but keep them diagnosable.
445
- import_effect6.Effect.catchAllCause(
446
- (cause) => record({
447
- type: "diagnostic",
448
- moduleId: runtime.moduleId,
449
- instanceId: runtime.instanceId,
450
- code: "task_runner::unhandled_failure",
451
- severity: "error",
452
- message: "TaskRunner encountered an unhandled failure (pending/IO/writeback).",
453
- hint: "Add a failure writeback for this task or handle errors explicitly upstream; avoid fire-and-forget swallowing errors.",
454
- actionTag: config.triggerName,
455
- kind: "task_runner_unhandled_failure",
456
- trigger: {
457
- kind: "task",
458
- name: config.triggerName
459
- }
460
- }).pipe(import_effect6.Effect.zipRight(import_effect6.Effect.logError("TaskRunner error", cause)))
461
- )
1128
+ import_effect10.Effect.catchCause((cause) => record({
1129
+ type: "diagnostic",
1130
+ moduleId: runtime.moduleId,
1131
+ instanceId: runtime.instanceId,
1132
+ code: "task_runner::unhandled_failure",
1133
+ severity: "error",
1134
+ message: "TaskRunner encountered an unhandled failure (pending/IO/writeback).",
1135
+ hint: "Add a failure writeback for this task or handle errors explicitly upstream; avoid fire-and-forget swallowing errors.",
1136
+ actionTag: config.triggerName,
1137
+ kind: "task_runner_unhandled_failure",
1138
+ trigger: {
1139
+ kind: "task",
1140
+ name: config.triggerName
1141
+ }
1142
+ }).pipe(import_effect10.Effect.flatMap(() => import_effect10.Effect.logError("TaskRunner error", cause))))
462
1143
  );
463
- var makeTaskRunner = (stream, mode, runtime, config) => {
464
- if (mode === "latest") {
465
- return import_effect6.Effect.gen(function* () {
466
- const taskIdRef = yield* import_effect6.Ref.make(0);
467
- const currentFiberRef = yield* import_effect6.Ref.make(void 0);
468
- const start = (payload) => import_effect6.Effect.gen(function* () {
469
- const taskId = yield* import_effect6.Ref.updateAndGet(taskIdRef, (n) => n + 1);
470
- const prev = yield* import_effect6.Ref.get(currentFiberRef);
471
- if (prev) {
472
- yield* import_effect6.Fiber.interruptFork(prev);
473
- }
474
- const canWriteBack = import_effect6.Ref.get(taskIdRef).pipe(import_effect6.Effect.map((current) => current === taskId));
475
- const fiber = yield* import_effect6.Effect.fork(
476
- runTaskLifecycle(payload, runtime, config, canWriteBack)
477
- );
478
- yield* import_effect6.Ref.set(currentFiberRef, fiber);
479
- });
480
- return yield* import_effect6.Stream.runForEach(stream, start);
481
- });
482
- }
483
- if (mode === "exhaust") {
484
- return import_effect6.Effect.gen(function* () {
485
- const concurrency = yield* resolveConcurrencyLimit(runtime);
486
- const busyRef = yield* import_effect6.Ref.make(false);
487
- const mapper = (payload) => import_effect6.Effect.gen(function* () {
488
- const acquired = yield* import_effect6.Ref.modify(
489
- busyRef,
490
- (busy) => busy ? [false, busy] : [true, true]
491
- );
492
- if (!acquired) {
493
- return;
494
- }
495
- try {
496
- yield* runTaskLifecycle(payload, runtime, config);
497
- } finally {
498
- yield* import_effect6.Ref.set(busyRef, false);
499
- }
500
- });
501
- return yield* import_effect6.Stream.runDrain(stream.pipe(import_effect6.Stream.mapEffect(mapper, { concurrency })));
502
- });
503
- }
504
- if (mode === "parallel") {
505
- return import_effect6.Effect.gen(function* () {
506
- const concurrency = yield* resolveConcurrencyLimit(runtime);
507
- return yield* import_effect6.Stream.runDrain(
508
- stream.pipe(
509
- import_effect6.Stream.mapEffect((payload) => runTaskLifecycle(payload, runtime, config), {
510
- concurrency
511
- })
512
- )
513
- );
514
- });
515
- }
516
- return import_effect6.Stream.runForEach(
517
- stream,
518
- (payload) => runTaskLifecycle(payload, runtime, config)
519
- );
1144
+ var runTask = (args) => {
1145
+ const mode = args.mode ?? "task";
1146
+ const runtime = args.runtime;
1147
+ const config = args.config;
1148
+ return runByMode({
1149
+ stream: args.stream,
1150
+ mode,
1151
+ run: (payload) => runTaskLifecycle(payload, runtime, config),
1152
+ runLatest: (payload, context) => runTaskLifecycle(payload, runtime, config, context.isCurrent),
1153
+ resolveConcurrencyLimit: resolveConcurrencyLimit(runtime),
1154
+ latest: {
1155
+ strategy: "fiber-slot",
1156
+ // Keep TaskRunner behavior: triggers are acknowledged once started; no need to await final IO on stream completion.
1157
+ awaitLatestOnEnd: false
1158
+ }
1159
+ });
520
1160
  };
1161
+ var makeTaskRunner = (stream, mode, runtime, config) => runTask({
1162
+ stream,
1163
+ mode,
1164
+ runtime,
1165
+ config
1166
+ });
521
1167
 
522
1168
  // src/internal/runtime/core/mutativePatches.ts
523
1169
  var import_mutative = require("mutative");
@@ -530,23 +1176,59 @@ var isFieldPathSegment = (seg) => {
530
1176
  if (seg.includes("[") || seg.includes("]")) return false;
531
1177
  return true;
532
1178
  };
1179
+ var toKey = (path) => {
1180
+ let key = "";
1181
+ for (let i = 0; i < path.length; i++) {
1182
+ if (i > 0) key += "|";
1183
+ const seg = path[i];
1184
+ key += seg.length;
1185
+ key += ":";
1186
+ key += seg;
1187
+ }
1188
+ return key;
1189
+ };
533
1190
 
534
1191
  // src/internal/runtime/core/mutativePatches.ts
1192
+ var isNonNegativeIntString = (text) => {
1193
+ if (!text) return false;
1194
+ for (let i = 0; i < text.length; i++) {
1195
+ const c = text.charCodeAt(i);
1196
+ if (c < 48 || c > 57) return false;
1197
+ }
1198
+ return true;
1199
+ };
535
1200
  var toPatchFieldPath = (path) => {
536
1201
  if (typeof path === "string") {
537
1202
  const trimmed = path.trim();
538
1203
  return trimmed.length > 0 ? "*" : void 0;
539
1204
  }
540
1205
  if (!Array.isArray(path)) return void 0;
1206
+ let allValidString = true;
1207
+ for (let i = 0; i < path.length; i++) {
1208
+ const seg = path[i];
1209
+ if (typeof seg !== "string" || !(isFieldPathSegment(seg) || isNonNegativeIntString(seg))) {
1210
+ allValidString = false;
1211
+ break;
1212
+ }
1213
+ }
1214
+ if (allValidString) return path;
541
1215
  const parts = [];
542
- for (const seg of path) {
1216
+ for (let i = 0; i < path.length; i++) {
1217
+ const seg = path[i];
543
1218
  if (typeof seg === "string") {
544
- if (isFieldPathSegment(seg)) parts.push(seg);
1219
+ if (isFieldPathSegment(seg) || isNonNegativeIntString(seg)) {
1220
+ parts.push(seg);
1221
+ }
545
1222
  continue;
546
1223
  }
1224
+ if (typeof seg === "number" && Number.isFinite(seg)) {
1225
+ const n = Math.floor(seg);
1226
+ if (n >= 0 && n <= 2147483647) {
1227
+ parts.push(String(n));
1228
+ }
1229
+ }
547
1230
  }
548
- if (parts.length === 0) return "*";
549
- return parts;
1231
+ return parts.length === 0 ? "*" : parts;
550
1232
  };
551
1233
  var mutateWithPatchPaths = (base, mutator) => {
552
1234
  const out = (0, import_mutative.create)(base, mutator, {
@@ -560,28 +1242,65 @@ var mutateWithPatchPaths = (base, mutator) => {
560
1242
  }
561
1243
  const nextState = out[0];
562
1244
  const patches = out[1] ?? [];
563
- const dedup = /* @__PURE__ */ new Map();
564
- for (const patch of patches) {
1245
+ if (patches.length > 256) {
1246
+ let sawStar2 = false;
1247
+ const patchPaths2 = [];
1248
+ for (let i = 0; i < patches.length; i++) {
1249
+ const patch = patches[i];
1250
+ const p = toPatchFieldPath(patch?.path);
1251
+ if (!p) continue;
1252
+ if (p === "*") {
1253
+ if (sawStar2) continue;
1254
+ sawStar2 = true;
1255
+ }
1256
+ patchPaths2.push(p);
1257
+ }
1258
+ return {
1259
+ nextState,
1260
+ patchPaths: patchPaths2
1261
+ };
1262
+ }
1263
+ let sawStar = false;
1264
+ const singleSeg = /* @__PURE__ */ new Set();
1265
+ const multiSeg = /* @__PURE__ */ new Set();
1266
+ const patchPaths = [];
1267
+ for (let i = 0; i < patches.length; i++) {
1268
+ const patch = patches[i];
565
1269
  const p = toPatchFieldPath(patch?.path);
566
1270
  if (!p) continue;
567
- const key = p === "*" ? "*" : JSON.stringify(p);
568
- if (!dedup.has(key)) dedup.set(key, p);
1271
+ if (p === "*") {
1272
+ if (sawStar) continue;
1273
+ sawStar = true;
1274
+ patchPaths.push(p);
1275
+ continue;
1276
+ }
1277
+ if (p.length === 1) {
1278
+ const seg = p[0];
1279
+ if (singleSeg.has(seg)) continue;
1280
+ singleSeg.add(seg);
1281
+ patchPaths.push(p);
1282
+ continue;
1283
+ }
1284
+ const key = toKey(p);
1285
+ if (multiSeg.has(key)) continue;
1286
+ multiSeg.add(key);
1287
+ patchPaths.push(p);
569
1288
  }
570
1289
  return {
571
1290
  nextState,
572
- patchPaths: Array.from(dedup.values())
1291
+ patchPaths
573
1292
  };
574
1293
  };
575
1294
 
576
1295
  // src/internal/runtime/core/FlowRuntime.ts
577
- var import_effect9 = require("effect");
1296
+ var import_effect13 = require("effect");
578
1297
 
579
1298
  // src/internal/effect-op.ts
580
- var import_effect8 = require("effect");
1299
+ var import_effect12 = require("effect");
581
1300
 
582
1301
  // src/internal/observability/runSession.ts
583
- var import_effect7 = require("effect");
584
- var RunSessionTagImpl = class extends import_effect7.Context.Tag("@logixjs/core/RunSession")() {
1302
+ var import_effect11 = require("effect");
1303
+ var RunSessionTagImpl = class extends import_effect11.ServiceMap.Service()("@logixjs/core/RunSession") {
585
1304
  };
586
1305
  var RunSessionTag = RunSessionTagImpl;
587
1306
 
@@ -592,7 +1311,7 @@ var nextOpSeq = () => {
592
1311
  return nextGlobalOpSeq;
593
1312
  };
594
1313
  var makeId = (instanceId, opSeq) => instanceId ? `${instanceId}::o${opSeq}` : `o${opSeq}`;
595
- var make = (params) => ({
1314
+ var make2 = (params) => ({
596
1315
  ...params.id ? { id: params.id, meta: params.meta } : (() => {
597
1316
  const meta = params.meta ?? {};
598
1317
  const instanceId = meta.instanceId;
@@ -609,16 +1328,383 @@ var make = (params) => ({
609
1328
  });
610
1329
  var run = (op, stack) => runWithMiddleware(op, stack);
611
1330
 
1331
+ // src/internal/digest.ts
1332
+ var stableStringify = (value) => {
1333
+ if (value === null) return "null";
1334
+ const t = typeof value;
1335
+ if (t === "string") return JSON.stringify(value);
1336
+ if (t === "number") return Number.isFinite(value) ? String(value) : "null";
1337
+ if (t === "boolean") return value ? "true" : "false";
1338
+ if (Array.isArray(value)) {
1339
+ return `[${value.map(stableStringify).join(",")}]`;
1340
+ }
1341
+ if (t === "object") {
1342
+ const record2 = value;
1343
+ const keys = Object.keys(record2).sort();
1344
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(record2[k])}`).join(",")}}`;
1345
+ }
1346
+ return "null";
1347
+ };
1348
+ var fnv1a32 = (input) => {
1349
+ let hash = 2166136261;
1350
+ for (let i = 0; i < input.length; i++) {
1351
+ hash ^= input.charCodeAt(i);
1352
+ hash = hash * 16777619 >>> 0;
1353
+ }
1354
+ return hash.toString(16).padStart(8, "0");
1355
+ };
1356
+
612
1357
  // src/internal/runtime/core/ReadQuery.ts
613
1358
  function isReadQuery(input) {
614
1359
  if (!input || typeof input !== "object" && typeof input !== "function") return false;
615
1360
  const maybe = input;
616
1361
  return typeof maybe.selectorId === "string" && typeof maybe.select === "function" && Array.isArray(maybe.reads);
617
1362
  }
1363
+ var normalizeReads = (reads) => {
1364
+ const unique = [];
1365
+ const seen = /* @__PURE__ */ new Set();
1366
+ for (const r of reads) {
1367
+ const key = typeof r === "number" ? `n:${r}` : `s:${r}`;
1368
+ if (seen.has(key)) continue;
1369
+ seen.add(key);
1370
+ unique.push(r);
1371
+ }
1372
+ return unique.slice().sort();
1373
+ };
1374
+ var toHash32Number = (hex) => Number.parseInt(hex, 16);
1375
+ var makeReadsDigest = (reads) => {
1376
+ const normalized = normalizeReads(reads);
1377
+ return {
1378
+ count: normalized.length,
1379
+ hash: toHash32Number(fnv1a32(stableStringify(normalized)))
1380
+ };
1381
+ };
1382
+ var computeSelectorId = (value) => `rq_${fnv1a32(stableStringify(value))}`;
1383
+ var nextUnstableSelectorSeq = 0;
1384
+ var unstableSelectorIdByFn = /* @__PURE__ */ new WeakMap();
1385
+ var computeUnstableSelectorId = (selector) => {
1386
+ const existing = unstableSelectorIdByFn.get(selector);
1387
+ if (existing) return existing;
1388
+ nextUnstableSelectorSeq += 1;
1389
+ const selectorId = `rq_u${nextUnstableSelectorSeq}`;
1390
+ unstableSelectorIdByFn.set(selector, selectorId);
1391
+ return selectorId;
1392
+ };
1393
+ var unwrapParens = (input) => {
1394
+ const trimmed = input.trim();
1395
+ if (trimmed.startsWith("(") && trimmed.endsWith(")")) {
1396
+ const inner = trimmed.slice(1, -1).trim();
1397
+ if (!inner.startsWith("(") || !inner.endsWith(")")) {
1398
+ return inner;
1399
+ }
1400
+ }
1401
+ return trimmed;
1402
+ };
1403
+ var extractArrow = (source) => {
1404
+ const idx = source.indexOf("=>");
1405
+ if (idx < 0) return void 0;
1406
+ const left = source.slice(0, idx).trim();
1407
+ const right = source.slice(idx + 2).trim();
1408
+ const paramRaw = unwrapParens(left);
1409
+ if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(paramRaw)) return void 0;
1410
+ if (right.startsWith("{")) {
1411
+ const m = right.match(/^\{\s*return\s+(.+?);?\s*\}\s*$/s);
1412
+ if (!m) return void 0;
1413
+ return { param: paramRaw, body: m[1]?.trim() ?? "" };
1414
+ }
1415
+ return { param: paramRaw, body: right };
1416
+ };
1417
+ var extractFunctionReturn = (source) => {
1418
+ const trimmed = source.trim();
1419
+ const m = trimmed.match(
1420
+ /^function\s*(?:[A-Za-z_$][A-Za-z0-9_$]*\s*)?\(\s*([A-Za-z_$][A-Za-z0-9_$]*)\s*\)\s*\{\s*return\s+(.+?);?\s*\}\s*$/s
1421
+ );
1422
+ if (!m) return void 0;
1423
+ const param = m[1]?.trim() ?? "";
1424
+ if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(param)) return void 0;
1425
+ const body = m[2]?.trim() ?? "";
1426
+ if (body.length === 0) return void 0;
1427
+ return { param, body };
1428
+ };
1429
+ var tryParseSelectorSource = (source) => {
1430
+ const arrowOrFn = extractArrow(source) ?? extractFunctionReturn(source);
1431
+ if (!arrowOrFn) return void 0;
1432
+ const expr = unwrapParens(arrowOrFn.body).trim().replace(/;$/, "").trim();
1433
+ {
1434
+ const re = new RegExp(`^${arrowOrFn.param}\\.([A-Za-z0-9_$]+(?:\\.[A-Za-z0-9_$]+)*)$`);
1435
+ const m = expr.match(re);
1436
+ if (m) {
1437
+ return { kind: "path", path: m[1] };
1438
+ }
1439
+ }
1440
+ if (expr.startsWith("{") && expr.endsWith("}")) {
1441
+ const inner = expr.slice(1, -1).trim();
1442
+ if (inner.length === 0) return { kind: "struct", entries: [] };
1443
+ const parts = inner.split(",").map((p) => p.trim()).filter((p) => p.length > 0);
1444
+ const entries = [];
1445
+ for (const part of parts) {
1446
+ const idx = part.indexOf(":");
1447
+ if (idx < 0) return void 0;
1448
+ const key = part.slice(0, idx).trim();
1449
+ const value = part.slice(idx + 1).trim();
1450
+ if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key)) return void 0;
1451
+ const re = new RegExp(`^${arrowOrFn.param}\\.([A-Za-z0-9_$]+(?:\\.[A-Za-z0-9_$]+)*)$`);
1452
+ const m = value.match(re);
1453
+ if (!m) return void 0;
1454
+ entries.push([key, m[1]]);
1455
+ }
1456
+ entries.sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
1457
+ return { kind: "struct", entries };
1458
+ }
1459
+ return void 0;
1460
+ };
1461
+ var READ_QUERY_TEMPLATE_CACHE_MAX = 2048;
1462
+ var readQueryTemplateByFn = /* @__PURE__ */ new WeakMap();
1463
+ var readQueryTemplateBySource = /* @__PURE__ */ new Map();
1464
+ var lruGet = (map, key) => {
1465
+ const value = map.get(key);
1466
+ if (value === void 0) return void 0;
1467
+ map.delete(key);
1468
+ map.set(key, value);
1469
+ return value;
1470
+ };
1471
+ var lruSet = (map, key, value, maxSize) => {
1472
+ if (map.has(key)) map.delete(key);
1473
+ map.set(key, value);
1474
+ if (map.size <= maxSize) return;
1475
+ const oldestKey = map.keys().next().value;
1476
+ if (oldestKey !== void 0) {
1477
+ map.delete(oldestKey);
1478
+ }
1479
+ };
1480
+ var safeToString = (fn) => {
1481
+ try {
1482
+ return fn.toString();
1483
+ } catch {
1484
+ return "";
1485
+ }
1486
+ };
1487
+ var compile = (input) => {
1488
+ if (isReadQuery(input)) {
1489
+ const reads = normalizeReads(input.reads);
1490
+ const readsDigest = reads.length > 0 ? makeReadsDigest(reads) : void 0;
1491
+ const equalsKind = input.equalsKind;
1492
+ const staticIr2 = {
1493
+ selectorId: input.selectorId,
1494
+ debugKey: input.debugKey,
1495
+ lane: "static",
1496
+ producer: "manual",
1497
+ reads,
1498
+ readsDigest,
1499
+ equalsKind
1500
+ };
1501
+ return {
1502
+ ...input,
1503
+ reads,
1504
+ lane: "static",
1505
+ producer: "manual",
1506
+ readsDigest,
1507
+ staticIr: staticIr2
1508
+ };
1509
+ }
1510
+ const selector = input;
1511
+ const debugKey = (typeof selector?.debugKey === "string" && selector.debugKey.length > 0 ? selector.debugKey : void 0) ?? (typeof selector.name === "string" && selector.name.length > 0 ? selector.name : void 0);
1512
+ const declaredReads = Array.isArray(selector?.fieldPaths) ? selector.fieldPaths.filter((x) => typeof x === "string") : void 0;
1513
+ if (declaredReads && declaredReads.length > 0) {
1514
+ const reads = normalizeReads(declaredReads);
1515
+ const readsDigest = makeReadsDigest(reads);
1516
+ const selectorId2 = computeSelectorId({ kind: "reads", reads });
1517
+ const staticIr2 = {
1518
+ selectorId: selectorId2,
1519
+ debugKey,
1520
+ lane: "static",
1521
+ producer: "jit",
1522
+ reads,
1523
+ readsDigest,
1524
+ equalsKind: "objectIs"
1525
+ };
1526
+ return {
1527
+ selectorId: selectorId2,
1528
+ debugKey,
1529
+ reads,
1530
+ select: selector,
1531
+ equalsKind: "objectIs",
1532
+ lane: "static",
1533
+ producer: "jit",
1534
+ readsDigest,
1535
+ staticIr: staticIr2
1536
+ };
1537
+ }
1538
+ const cachedByFn = readQueryTemplateByFn.get(selector);
1539
+ if (cachedByFn) {
1540
+ const staticIr2 = {
1541
+ selectorId: cachedByFn.selectorId,
1542
+ debugKey,
1543
+ lane: "static",
1544
+ producer: "jit",
1545
+ reads: cachedByFn.reads,
1546
+ readsDigest: cachedByFn.readsDigest,
1547
+ equalsKind: cachedByFn.equalsKind
1548
+ };
1549
+ return {
1550
+ selectorId: cachedByFn.selectorId,
1551
+ debugKey,
1552
+ reads: cachedByFn.reads,
1553
+ select: selector,
1554
+ equalsKind: cachedByFn.equalsKind,
1555
+ lane: "static",
1556
+ producer: "jit",
1557
+ readsDigest: cachedByFn.readsDigest,
1558
+ staticIr: staticIr2
1559
+ };
1560
+ }
1561
+ const srcTrimmed = safeToString(selector).trim();
1562
+ const cachedBySource = srcTrimmed.length > 0 ? lruGet(readQueryTemplateBySource, srcTrimmed) : void 0;
1563
+ if (cachedBySource) {
1564
+ readQueryTemplateByFn.set(selector, cachedBySource);
1565
+ const staticIr2 = {
1566
+ selectorId: cachedBySource.selectorId,
1567
+ debugKey,
1568
+ lane: "static",
1569
+ producer: "jit",
1570
+ reads: cachedBySource.reads,
1571
+ readsDigest: cachedBySource.readsDigest,
1572
+ equalsKind: cachedBySource.equalsKind
1573
+ };
1574
+ return {
1575
+ selectorId: cachedBySource.selectorId,
1576
+ debugKey,
1577
+ reads: cachedBySource.reads,
1578
+ select: selector,
1579
+ equalsKind: cachedBySource.equalsKind,
1580
+ lane: "static",
1581
+ producer: "jit",
1582
+ readsDigest: cachedBySource.readsDigest,
1583
+ staticIr: staticIr2
1584
+ };
1585
+ }
1586
+ const parsed = srcTrimmed.length > 0 ? tryParseSelectorSource(srcTrimmed) : void 0;
1587
+ if (parsed?.kind === "path") {
1588
+ const reads = [parsed.path];
1589
+ const readsDigest = makeReadsDigest(reads);
1590
+ const selectorId2 = computeSelectorId({ kind: "path", path: parsed.path });
1591
+ const template = { selectorId: selectorId2, reads, readsDigest, equalsKind: "objectIs" };
1592
+ readQueryTemplateByFn.set(selector, template);
1593
+ lruSet(readQueryTemplateBySource, srcTrimmed, template, READ_QUERY_TEMPLATE_CACHE_MAX);
1594
+ const staticIr2 = {
1595
+ selectorId: selectorId2,
1596
+ debugKey,
1597
+ lane: "static",
1598
+ producer: "jit",
1599
+ reads,
1600
+ readsDigest,
1601
+ equalsKind: "objectIs"
1602
+ };
1603
+ return {
1604
+ selectorId: selectorId2,
1605
+ debugKey,
1606
+ reads,
1607
+ select: selector,
1608
+ equalsKind: "objectIs",
1609
+ lane: "static",
1610
+ producer: "jit",
1611
+ readsDigest,
1612
+ staticIr: staticIr2
1613
+ };
1614
+ }
1615
+ if (parsed?.kind === "struct") {
1616
+ const reads = normalizeReads(parsed.entries.map(([, path]) => path));
1617
+ const readsDigest = makeReadsDigest(reads);
1618
+ const selectorId2 = computeSelectorId({ kind: "struct", entries: parsed.entries });
1619
+ const template = { selectorId: selectorId2, reads, readsDigest, equalsKind: "shallowStruct" };
1620
+ readQueryTemplateByFn.set(selector, template);
1621
+ lruSet(readQueryTemplateBySource, srcTrimmed, template, READ_QUERY_TEMPLATE_CACHE_MAX);
1622
+ const staticIr2 = {
1623
+ selectorId: selectorId2,
1624
+ debugKey,
1625
+ lane: "static",
1626
+ producer: "jit",
1627
+ reads,
1628
+ readsDigest,
1629
+ equalsKind: "shallowStruct"
1630
+ };
1631
+ return {
1632
+ selectorId: selectorId2,
1633
+ debugKey,
1634
+ reads,
1635
+ select: selector,
1636
+ equalsKind: "shallowStruct",
1637
+ lane: "static",
1638
+ producer: "jit",
1639
+ readsDigest,
1640
+ staticIr: staticIr2
1641
+ };
1642
+ }
1643
+ const baseFallbackReason = srcTrimmed.includes("=>") || srcTrimmed.startsWith("function") ? "unsupportedSyntax" : "missingDeps";
1644
+ const lowDiscriminabilitySource = srcTrimmed.length === 0 || srcTrimmed.includes("[native code]");
1645
+ const fallbackReason = !debugKey || lowDiscriminabilitySource ? "unstableSelectorId" : baseFallbackReason;
1646
+ const selectorId = fallbackReason === "unstableSelectorId" ? computeUnstableSelectorId(selector) : computeSelectorId({ kind: "dynamic", debugKey, src: srcTrimmed });
1647
+ const staticIr = {
1648
+ selectorId,
1649
+ debugKey,
1650
+ lane: "dynamic",
1651
+ producer: "dynamic",
1652
+ fallbackReason,
1653
+ equalsKind: "objectIs"
1654
+ };
1655
+ return {
1656
+ selectorId,
1657
+ debugKey,
1658
+ reads: [],
1659
+ select: selector,
1660
+ equalsKind: "objectIs",
1661
+ lane: "dynamic",
1662
+ producer: "dynamic",
1663
+ fallbackReason,
1664
+ staticIr
1665
+ };
1666
+ };
1667
+
1668
+ // src/internal/runtime/core/diagnosticsBudget.ts
1669
+ var DIAGNOSTICS_BUDGET_CONTRACT_V1 = "diagnostics_budget.v1";
1670
+ var normalizePositiveInteger = (value) => {
1671
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return void 0;
1672
+ return Math.floor(value);
1673
+ };
1674
+ var makeRunBudgetEnvelopeV1 = (args) => {
1675
+ const maxEvents = normalizePositiveInteger(args.limits?.maxEvents);
1676
+ const maxBytes = normalizePositiveInteger(args.limits?.maxBytes);
1677
+ const emitted = normalizePositiveInteger(args.usage?.emitted);
1678
+ const dropped = normalizePositiveInteger(args.usage?.dropped);
1679
+ const downgraded = normalizePositiveInteger(args.usage?.downgraded);
1680
+ return {
1681
+ contract: DIAGNOSTICS_BUDGET_CONTRACT_V1,
1682
+ domain: args.domain,
1683
+ runId: args.runId,
1684
+ ...maxEvents !== void 0 || maxBytes !== void 0 ? {
1685
+ limits: {
1686
+ ...maxEvents !== void 0 ? { maxEvents } : null,
1687
+ ...maxBytes !== void 0 ? { maxBytes } : null
1688
+ }
1689
+ } : null,
1690
+ ...emitted !== void 0 || dropped !== void 0 || downgraded !== void 0 ? {
1691
+ usage: {
1692
+ ...emitted !== void 0 ? { emitted } : null,
1693
+ ...dropped !== void 0 ? { dropped } : null,
1694
+ ...downgraded !== void 0 ? { downgraded } : null
1695
+ }
1696
+ } : null
1697
+ };
1698
+ };
1699
+ var makeRunDegradeMarkerV1 = (degraded, reason) => ({
1700
+ contract: DIAGNOSTICS_BUDGET_CONTRACT_V1,
1701
+ degraded,
1702
+ ...degraded && reason ? { reason } : null
1703
+ });
618
1704
 
619
1705
  // src/internal/runtime/core/FlowRuntime.ts
620
- var getMiddlewareStack = () => import_effect9.Effect.serviceOption(EffectOpMiddlewareTag).pipe(
621
- import_effect9.Effect.map((maybe) => import_effect9.Option.isSome(maybe) ? maybe.value.stack : [])
1706
+ var getMiddlewareStack = () => import_effect13.Effect.serviceOption(EffectOpMiddlewareTag).pipe(
1707
+ import_effect13.Effect.map((maybe) => import_effect13.Option.isSome(maybe) ? maybe.value.stack : [])
622
1708
  );
623
1709
  var getRuntimeScope = (runtime) => {
624
1710
  if (!runtime) return {};
@@ -629,13 +1715,74 @@ var getRuntimeScope = (runtime) => {
629
1715
  instanceId: typeof scope.instanceId === "string" ? scope.instanceId : void 0
630
1716
  };
631
1717
  };
632
- var resolveEffect = (eff, payload) => typeof eff === "function" ? eff(payload) : eff;
633
- var make2 = (runtime, runtimeInternals) => {
1718
+ var hasChangesReadQueryWithMeta = (candidate) => {
1719
+ if (candidate == null) return false;
1720
+ if (typeof candidate !== "object" && typeof candidate !== "function") return false;
1721
+ return typeof candidate.changesReadQueryWithMeta === "function";
1722
+ };
1723
+ var preResolveEffectResolver = (eff) => {
1724
+ if (typeof eff === "function") {
1725
+ return eff;
1726
+ }
1727
+ return () => eff;
1728
+ };
1729
+ var resolveFlowRunId = (name, meta, fallbackRunSeq) => {
1730
+ const explicitRunId = meta.runId;
1731
+ if (typeof explicitRunId === "string" && explicitRunId.length > 0) {
1732
+ return explicitRunId;
1733
+ }
1734
+ const instanceId = typeof meta.instanceId === "string" && meta.instanceId.length > 0 ? meta.instanceId : "global";
1735
+ const opSeq = meta.opSeq;
1736
+ if (typeof opSeq === "number" && Number.isFinite(opSeq) && opSeq >= 1) {
1737
+ return `${instanceId}::${name}::r${Math.floor(opSeq)}`;
1738
+ }
1739
+ if (typeof fallbackRunSeq === "number" && Number.isFinite(fallbackRunSeq) && fallbackRunSeq >= 1) {
1740
+ return `${instanceId}::${name}::r${Math.floor(fallbackRunSeq)}`;
1741
+ }
1742
+ return `${instanceId}::${name}`;
1743
+ };
1744
+ var withFlowRunBudgetMeta = (name, meta, fallbackRunSeq) => {
1745
+ const disableObservers = typeof meta.policy === "object" && meta.policy !== null && meta.policy.disableObservers === true;
1746
+ return {
1747
+ ...meta,
1748
+ budgetEnvelope: makeRunBudgetEnvelopeV1({
1749
+ domain: "flow",
1750
+ runId: resolveFlowRunId(name, meta, fallbackRunSeq)
1751
+ }),
1752
+ degrade: makeRunDegradeMarkerV1(disableObservers, disableObservers ? "observer_disabled" : void 0)
1753
+ };
1754
+ };
1755
+ var isRunConfig = (input) => {
1756
+ if (!input || typeof input !== "object") {
1757
+ return false;
1758
+ }
1759
+ const candidate = input;
1760
+ if (!("effect" in candidate)) {
1761
+ return false;
1762
+ }
1763
+ const mode = candidate.mode;
1764
+ if (mode === void 0) {
1765
+ return true;
1766
+ }
1767
+ return mode === "task" || mode === "parallel" || mode === "latest" || mode === "exhaust";
1768
+ };
1769
+ var make3 = (runtime, runtimeInternals) => {
1770
+ let flowBudgetRunSeq = 0;
634
1771
  const scope = getRuntimeScope(runtime);
635
- const resolveConcurrencyLimit2 = () => runtimeInternals ? runtimeInternals.concurrency.resolveConcurrencyPolicy().pipe(import_effect9.Effect.map((p) => p.concurrencyLimit)) : import_effect9.Effect.succeed(16);
636
- const runAsFlowOp = (name, payload, eff, options) => import_effect9.Effect.gen(function* () {
1772
+ const resolveConcurrencyLimit2 = () => runtimeInternals ? runtimeInternals.concurrency.resolveConcurrencyPolicy().pipe(import_effect13.Effect.map((p) => p.concurrencyLimit)) : import_effect13.Effect.succeed(16);
1773
+ const makeFlowOpRunContext = (options) => import_effect13.Effect.gen(function* () {
637
1774
  const stack = yield* getMiddlewareStack();
638
- const meta = {
1775
+ if (stack.length === 0) {
1776
+ return {
1777
+ stack,
1778
+ hasMiddleware: false,
1779
+ metaTemplate: {},
1780
+ hasFiniteTemplateOpSeq: false,
1781
+ allocateOpSeq: void 0
1782
+ };
1783
+ }
1784
+ const sessionOpt = yield* import_effect13.Effect.serviceOption(RunSessionTag);
1785
+ const metaTemplate = {
639
1786
  ...options?.meta ?? {},
640
1787
  policy: options?.policy,
641
1788
  tags: options?.tags,
@@ -643,112 +1790,146 @@ var make2 = (runtime, runtimeInternals) => {
643
1790
  moduleId: scope.moduleId,
644
1791
  instanceId: scope.instanceId
645
1792
  };
646
- if (!(typeof meta.opSeq === "number" && Number.isFinite(meta.opSeq))) {
647
- const sessionOpt = yield* import_effect9.Effect.serviceOption(RunSessionTag);
648
- if (import_effect9.Option.isSome(sessionOpt)) {
649
- const key = meta.instanceId ?? "global";
650
- meta.opSeq = sessionOpt.value.local.nextSeq("opSeq", key);
651
- }
1793
+ const hasFiniteTemplateOpSeq = typeof metaTemplate.opSeq === "number" && Number.isFinite(metaTemplate.opSeq);
1794
+ const runSessionLocal = import_effect13.Option.isSome(sessionOpt) ? sessionOpt.value.local : void 0;
1795
+ const opSeqKey = metaTemplate.instanceId ?? "global";
1796
+ const allocateOpSeq = runSessionLocal ? () => runSessionLocal.nextSeq("opSeq", opSeqKey) : void 0;
1797
+ return {
1798
+ stack,
1799
+ hasMiddleware: true,
1800
+ metaTemplate,
1801
+ hasFiniteTemplateOpSeq,
1802
+ allocateOpSeq
1803
+ };
1804
+ });
1805
+ const buildFlowOpMeta = (context) => {
1806
+ if (context.hasFiniteTemplateOpSeq) {
1807
+ return { ...context.metaTemplate };
652
1808
  }
653
- const op = make({
654
- kind: "flow",
655
- name,
656
- payload,
657
- effect: eff,
658
- meta
1809
+ if (context.allocateOpSeq) {
1810
+ return {
1811
+ ...context.metaTemplate,
1812
+ opSeq: context.allocateOpSeq()
1813
+ };
1814
+ }
1815
+ return context.metaTemplate;
1816
+ };
1817
+ const runAsFlowOp = (context, name, payload, eff) => {
1818
+ if (!context.hasMiddleware) {
1819
+ return eff;
1820
+ }
1821
+ return import_effect13.Effect.gen(function* () {
1822
+ flowBudgetRunSeq += 1;
1823
+ const meta = withFlowRunBudgetMeta(name, buildFlowOpMeta(context), flowBudgetRunSeq);
1824
+ const op = make2({
1825
+ kind: "flow",
1826
+ name,
1827
+ payload,
1828
+ effect: eff,
1829
+ meta
1830
+ });
1831
+ return yield* run(op, context.stack);
1832
+ });
1833
+ };
1834
+ const makeFlowOpMapper = (context, name, resolver) => {
1835
+ if (!context.hasMiddleware) {
1836
+ return resolver;
1837
+ }
1838
+ return (payload) => runAsFlowOp(context, name, payload, resolver(payload));
1839
+ };
1840
+ const runStreamWithMode = (mode, name, resolver, options) => (stream) => import_effect13.Effect.gen(function* () {
1841
+ const context = yield* makeFlowOpRunContext(options);
1842
+ const mapper = makeFlowOpMapper(context, name, resolver);
1843
+ return yield* runByMode({
1844
+ stream,
1845
+ mode,
1846
+ run: mapper,
1847
+ resolveConcurrencyLimit: resolveConcurrencyLimit2(),
1848
+ latest: {
1849
+ strategy: "switch"
1850
+ }
659
1851
  });
660
- return yield* run(op, stack);
661
1852
  });
662
- const runEffect = (eff) => (payload) => resolveEffect(eff, payload);
663
- const runStreamSequential = (eff, options) => (stream) => import_effect9.Stream.runForEach(
664
- stream,
665
- (payload) => runAsFlowOp("flow.run", payload, runEffect(eff)(payload), options)
1853
+ const runStreamParallelWithDiagnostics = (resolver, options) => (stream) => runStreamWithMode("parallel", "flow.runParallel", resolver, options)(stream).pipe(
1854
+ import_effect13.Effect.catchCause((cause) => record({
1855
+ type: "diagnostic",
1856
+ moduleId: scope.moduleId,
1857
+ instanceId: scope.instanceId,
1858
+ code: "flow::unhandled_failure",
1859
+ severity: "error",
1860
+ message: "Flow watcher (runParallel) failed with an unhandled error.",
1861
+ hint: "Handle errors explicitly inside the watcher (catch/catchAll) or write back via TaskRunner failure; avoid silent failures.",
1862
+ kind: "flow_unhandled_failure",
1863
+ trigger: {
1864
+ kind: "flow",
1865
+ name: "runParallel"
1866
+ }
1867
+ }).pipe(import_effect13.Effect.flatMap(() => import_effect13.Effect.failCause(cause))))
666
1868
  );
667
- const runStreamParallel = (eff, options) => (stream) => import_effect9.Effect.gen(function* () {
668
- const concurrency = yield* resolveConcurrencyLimit2();
669
- return yield* import_effect9.Stream.runDrain(
670
- stream.pipe(
671
- import_effect9.Stream.mapEffect(
672
- (payload) => runAsFlowOp("flow.runParallel", payload, runEffect(eff)(payload), options),
673
- { concurrency }
674
- )
675
- )
676
- ).pipe(
677
- import_effect9.Effect.catchAllCause(
678
- (cause) => record({
679
- type: "diagnostic",
680
- moduleId: scope.moduleId,
681
- instanceId: scope.instanceId,
682
- code: "flow::unhandled_failure",
683
- severity: "error",
684
- message: "Flow watcher (runParallel) failed with an unhandled error.",
685
- hint: "Handle errors explicitly inside the watcher (catch/catchAll) or write back via TaskRunner failure; avoid silent failures.",
686
- kind: "flow_unhandled_failure",
687
- trigger: {
688
- kind: "flow",
689
- name: "runParallel"
690
- }
691
- }).pipe(import_effect9.Effect.zipRight(import_effect9.Effect.failCause(cause)))
692
- )
693
- );
694
- });
1869
+ const fromState = (selectorOrQuery) => {
1870
+ const runtimeWithReadQueryMeta = hasChangesReadQueryWithMeta(runtime) ? runtime : void 0;
1871
+ if (isReadQuery(selectorOrQuery)) {
1872
+ if (runtimeWithReadQueryMeta) {
1873
+ return runtimeWithReadQueryMeta.changesReadQueryWithMeta(selectorOrQuery).pipe(import_effect13.Stream.map((evt) => evt.value));
1874
+ }
1875
+ return runtime.changes(selectorOrQuery.select);
1876
+ }
1877
+ if (!runtimeWithReadQueryMeta) {
1878
+ return runtime.changes(selectorOrQuery);
1879
+ }
1880
+ const compiled = compile(selectorOrQuery);
1881
+ if (compiled.lane === "static") {
1882
+ return runtimeWithReadQueryMeta.changesReadQueryWithMeta(compiled).pipe(import_effect13.Stream.map((evt) => evt.value));
1883
+ }
1884
+ return runtime.changes(selectorOrQuery);
1885
+ };
695
1886
  return {
696
- fromAction: (predicate) => runtime.actions$.pipe(import_effect9.Stream.filter(predicate)),
697
- fromState: (selectorOrQuery) => runtime.changes(isReadQuery(selectorOrQuery) ? selectorOrQuery.select : selectorOrQuery),
698
- debounce: (ms) => (stream) => import_effect9.Stream.debounce(stream, ms),
699
- throttle: (ms) => (stream) => import_effect9.Stream.throttle(stream, {
1887
+ fromAction: (predicate) => runtime.actions$.pipe(import_effect13.Stream.filter(predicate)),
1888
+ fromState,
1889
+ debounce: (ms) => (stream) => import_effect13.Stream.debounce(stream, ms),
1890
+ throttle: (ms) => (stream) => import_effect13.Stream.throttle(stream, {
700
1891
  cost: () => 1,
701
1892
  units: 1,
702
1893
  duration: ms,
703
1894
  strategy: "enforce"
704
1895
  }),
705
- filter: (predicate) => (stream) => import_effect9.Stream.filter(stream, predicate),
706
- run: (eff, options) => (stream) => runStreamSequential(eff, options)(stream),
707
- runParallel: (eff, options) => (stream) => runStreamParallel(eff, options)(stream),
708
- runLatest: (eff, options) => (stream) => import_effect9.Stream.runDrain(
709
- import_effect9.Stream.map(
710
- stream,
711
- (payload) => runAsFlowOp(
712
- "flow.runLatest",
713
- payload,
714
- runEffect(eff)(payload),
715
- options
716
- )
717
- ).pipe(
718
- import_effect9.Stream.flatMap((effect) => import_effect9.Stream.fromEffect(effect), {
719
- switch: true
720
- })
721
- )
722
- ),
723
- runExhaust: (eff, options) => (stream) => import_effect9.Effect.gen(function* () {
724
- const concurrency = yield* resolveConcurrencyLimit2();
725
- const busyRef = yield* import_effect9.Ref.make(false);
726
- const mapper = (payload) => import_effect9.Effect.gen(function* () {
727
- const acquired = yield* import_effect9.Ref.modify(
728
- busyRef,
729
- (busy) => busy ? [false, busy] : [true, true]
730
- );
731
- if (!acquired) {
732
- return;
733
- }
734
- try {
735
- yield* runAsFlowOp(
736
- "flow.runExhaust",
737
- payload,
738
- runEffect(eff)(payload),
739
- options
740
- );
741
- } finally {
742
- yield* import_effect9.Ref.set(busyRef, false);
743
- }
744
- });
745
- return yield* import_effect9.Stream.runDrain(stream.pipe(import_effect9.Stream.mapEffect(mapper, { concurrency })));
746
- })
1896
+ filter: (predicate) => (stream) => import_effect13.Stream.filter(stream, predicate),
1897
+ run: (effOrConfig, options) => (stream) => {
1898
+ const mode = isRunConfig(effOrConfig) ? effOrConfig.mode ?? "task" : "task";
1899
+ const resolvedOptions = isRunConfig(effOrConfig) ? effOrConfig.options : options;
1900
+ const effect = isRunConfig(effOrConfig) ? effOrConfig.effect : effOrConfig;
1901
+ const resolver = preResolveEffectResolver(effect);
1902
+ if (mode === "parallel") {
1903
+ return runStreamParallelWithDiagnostics(resolver, resolvedOptions)(stream);
1904
+ }
1905
+ return runStreamWithMode(
1906
+ mode,
1907
+ mode === "latest" ? "flow.runLatest" : mode === "exhaust" ? "flow.runExhaust" : "flow.run",
1908
+ resolver,
1909
+ resolvedOptions
1910
+ )(stream);
1911
+ },
1912
+ runParallel: (eff, options) => (stream) => runStreamParallelWithDiagnostics(
1913
+ preResolveEffectResolver(eff),
1914
+ options
1915
+ )(stream),
1916
+ runLatest: (eff, options) => (stream) => runStreamWithMode(
1917
+ "latest",
1918
+ "flow.runLatest",
1919
+ preResolveEffectResolver(eff),
1920
+ options
1921
+ )(stream),
1922
+ runExhaust: (eff, options) => (stream) => runStreamWithMode(
1923
+ "exhaust",
1924
+ "flow.runExhaust",
1925
+ preResolveEffectResolver(eff),
1926
+ options
1927
+ )(stream)
747
1928
  };
748
1929
  };
749
1930
 
750
1931
  // src/internal/runtime/core/MatchBuilder.ts
751
- var import_effect10 = require("effect");
1932
+ var import_effect14 = require("effect");
752
1933
  var makeMatch = (value) => {
753
1934
  let result;
754
1935
  const chain = {
@@ -767,7 +1948,7 @@ var makeMatch = (value) => {
767
1948
  if (result) {
768
1949
  return result;
769
1950
  }
770
- return import_effect10.Effect.dieMessage("[FluentMatch] Non-exhaustive match: no pattern matched value");
1951
+ return import_effect14.Effect.die(new Error("[FluentMatch] Non-exhaustive match: no pattern matched value"));
771
1952
  }
772
1953
  };
773
1954
  return chain;
@@ -790,24 +1971,27 @@ var makeMatchTag = (value) => {
790
1971
  if (result) {
791
1972
  return result;
792
1973
  }
793
- return import_effect10.Effect.dieMessage("[FluentMatchTag] Non-exhaustive match: no tag handler matched value");
1974
+ return import_effect14.Effect.die(new Error("[FluentMatchTag] Non-exhaustive match: no tag handler matched value"));
794
1975
  }
795
1976
  };
796
1977
  return chain;
797
1978
  };
798
1979
 
799
1980
  // src/internal/runtime/core/Platform.ts
800
- var import_effect11 = require("effect");
801
- var Tag = import_effect11.Context.GenericTag("@logixjs/Platform");
1981
+ var import_effect15 = require("effect");
1982
+ var Tag = class extends import_effect15.ServiceMap.Service()("@logixjs/Platform") {
1983
+ };
802
1984
 
803
1985
  // src/internal/runtime/core/Lifecycle.ts
804
- var import_effect12 = require("effect");
805
- var LifecycleContext = import_effect12.Context.GenericTag("@logixjs/LifecycleManager");
1986
+ var import_effect16 = require("effect");
1987
+ var LifecycleContext = class extends import_effect16.ServiceMap.Service()("@logixjs/LifecycleManager") {
1988
+ };
806
1989
 
807
1990
  // src/internal/runtime/core/LogicDiagnostics.ts
808
- var import_effect13 = require("effect");
809
- var LogicPhaseServiceTag = import_effect13.Context.GenericTag("@logixjs/LogicPhaseService");
810
- var LogicUnitServiceTag = class extends import_effect13.Context.Tag("@logixjs/LogicUnitService")() {
1991
+ var import_effect17 = require("effect");
1992
+ var LogicPhaseServiceTag = class extends import_effect17.ServiceMap.Service()("@logixjs/LogicPhaseService") {
1993
+ };
1994
+ var LogicUnitServiceTag = class extends import_effect17.ServiceMap.Service()("@logixjs/LogicUnitService") {
811
1995
  };
812
1996
  var makeLogicPhaseError = (kind, api, phase, moduleId) => Object.assign(new Error(`[LogicPhaseError] ${api} is not allowed in ${phase} phase (kind=${kind}).`), {
813
1997
  _tag: "LogicPhaseError",
@@ -818,11 +2002,11 @@ var makeLogicPhaseError = (kind, api, phase, moduleId) => Object.assign(new Erro
818
2002
  });
819
2003
 
820
2004
  // src/internal/root.ts
821
- var import_effect15 = require("effect");
2005
+ var import_effect19 = require("effect");
822
2006
 
823
2007
  // src/internal/runtime/core/RootContext.ts
824
- var import_effect14 = require("effect");
825
- var RootContextTagImpl = class extends import_effect14.Context.Tag("@logixjs/core/RootContext")() {
2008
+ var import_effect18 = require("effect");
2009
+ var RootContextTagImpl = class extends import_effect18.ServiceMap.Service()("@logixjs/core/RootContext") {
826
2010
  };
827
2011
  var RootContextTag = RootContextTagImpl;
828
2012
 
@@ -857,19 +2041,19 @@ ${extra}` : "",
857
2041
  err.fix = fix;
858
2042
  return err;
859
2043
  };
860
- var resolve2 = (tag, options) => import_effect15.Effect.gen(function* () {
2044
+ var resolve2 = (tag, options) => import_effect19.Effect.gen(function* () {
861
2045
  const entrypoint = options?.entrypoint ?? "logic.root.resolve";
862
- const root = yield* RootContextTag;
863
- const rootContext = root.context ?? (options?.waitForReady ? yield* root.ready : void 0);
2046
+ const root = yield* import_effect19.Effect.service(RootContextTag).pipe(import_effect19.Effect.orDie);
2047
+ const rootContext = root.context ?? (options?.waitForReady ? yield* import_effect19.Deferred.await(root.ready) : void 0);
864
2048
  if (!rootContext) {
865
- return yield* import_effect15.Effect.die(
2049
+ return yield* import_effect19.Effect.die(
866
2050
  makeMissingRootProviderError(tag, entrypoint, "reason: rootContextNotReady")
867
2051
  );
868
2052
  }
869
2053
  try {
870
- return import_effect15.Context.get(rootContext, tag);
2054
+ return import_effect19.ServiceMap.get(rootContext, tag);
871
2055
  } catch {
872
- return yield* import_effect15.Effect.die(makeMissingRootProviderError(tag, entrypoint));
2056
+ return yield* import_effect19.Effect.die(makeMissingRootProviderError(tag, entrypoint));
873
2057
  }
874
2058
  });
875
2059
 
@@ -919,8 +2103,18 @@ var getRuntimeInternals = (runtime) => {
919
2103
  };
920
2104
 
921
2105
  // src/internal/runtime/core/BoundApiRuntime.ts
2106
+ var DIRECT_STATE_WRITE_EFFECT = /* @__PURE__ */ Symbol.for("logix.directStateWriteEffect");
2107
+ var markDirectStateWriteEffect = (effect, metadata) => {
2108
+ ;
2109
+ effect[DIRECT_STATE_WRITE_EFFECT] = metadata;
2110
+ return effect;
2111
+ };
2112
+ var getDirectStateWriteMetadata = (value) => {
2113
+ if (!value || typeof value !== "object" && typeof value !== "function") return void 0;
2114
+ return value[DIRECT_STATE_WRITE_EFFECT];
2115
+ };
922
2116
  var LogicBuilderFactory = (runtime, runtimeInternals) => {
923
- const flowApi = make2(runtime, runtimeInternals);
2117
+ const flowApi = make3(runtime, runtimeInternals);
924
2118
  return (stream, triggerName) => {
925
2119
  const runWithStateTransaction = (origin, body) => runtimeInternals.txn.runWithStateTransaction(origin, body);
926
2120
  const taskRunnerRuntime = {
@@ -933,7 +2127,7 @@ var LogicBuilderFactory = (runtime, runtimeInternals) => {
933
2127
  debounce: (ms) => LogicBuilderFactory(runtime, runtimeInternals)(flowApi.debounce(ms)(stream), triggerName),
934
2128
  throttle: (ms) => LogicBuilderFactory(runtime, runtimeInternals)(flowApi.throttle(ms)(stream), triggerName),
935
2129
  filter: (predicate) => LogicBuilderFactory(runtime, runtimeInternals)(flowApi.filter(predicate)(stream), triggerName),
936
- map: (f) => LogicBuilderFactory(runtime, runtimeInternals)(stream.pipe(import_effect16.Stream.map(f)), triggerName),
2130
+ map: (f) => LogicBuilderFactory(runtime, runtimeInternals)(stream.pipe(import_effect20.Stream.map(f)), triggerName),
937
2131
  run(eff, options) {
938
2132
  return flowApi.run(eff, options)(stream);
939
2133
  },
@@ -946,8 +2140,30 @@ var LogicBuilderFactory = (runtime, runtimeInternals) => {
946
2140
  runParallel(eff, options) {
947
2141
  return flowApi.runParallel(eff, options)(stream);
948
2142
  },
949
- runFork: (eff) => import_effect16.Effect.forkScoped(flowApi.run(eff)(stream)).pipe(import_effect16.Effect.asVoid),
950
- runParallelFork: (eff) => import_effect16.Effect.forkScoped(flowApi.runParallel(eff)(stream)).pipe(import_effect16.Effect.asVoid),
2143
+ runFork: (eff) => {
2144
+ if (runtimeInternals && triggerName && typeof eff !== "function" && getDirectStateWriteMetadata(eff) != null) {
2145
+ return import_effect20.Effect.sync(() => {
2146
+ const metadata = getDirectStateWriteMetadata(eff);
2147
+ runtimeInternals.txn.registerActionStateWriteback(
2148
+ triggerName,
2149
+ metadata.kind === "update" ? { kind: "update", run: metadata.run } : { kind: "mutate", run: metadata.run }
2150
+ );
2151
+ });
2152
+ }
2153
+ return import_effect20.Effect.forkScoped(flowApi.run(eff)(stream)).pipe(import_effect20.Effect.asVoid);
2154
+ },
2155
+ runParallelFork: (eff) => {
2156
+ if (runtimeInternals && triggerName && typeof eff !== "function" && getDirectStateWriteMetadata(eff) != null) {
2157
+ return import_effect20.Effect.sync(() => {
2158
+ const metadata = getDirectStateWriteMetadata(eff);
2159
+ runtimeInternals.txn.registerActionStateWriteback(
2160
+ triggerName,
2161
+ metadata.kind === "update" ? { kind: "update", run: metadata.run } : { kind: "mutate", run: metadata.run }
2162
+ );
2163
+ });
2164
+ }
2165
+ return import_effect20.Effect.forkScoped(flowApi.runParallel(eff)(stream)).pipe(import_effect20.Effect.asVoid);
2166
+ },
951
2167
  runTask: (config) => makeTaskRunner(stream, "task", taskRunnerRuntime, {
952
2168
  ...config,
953
2169
  triggerName: config.triggerName ?? triggerName
@@ -965,20 +2181,20 @@ var LogicBuilderFactory = (runtime, runtimeInternals) => {
965
2181
  triggerName: config.triggerName ?? triggerName
966
2182
  }),
967
2183
  toStream: () => stream,
968
- update: (reducer) => import_effect16.Stream.runForEach(
2184
+ update: (reducer) => import_effect20.Stream.runForEach(
969
2185
  stream,
970
2186
  (payload) => taskRunnerRuntime.runWithStateTransaction(
971
2187
  {
972
2188
  kind: "watcher:update",
973
2189
  name: triggerName
974
2190
  },
975
- () => import_effect16.Effect.gen(function* () {
2191
+ () => import_effect20.Effect.gen(function* () {
976
2192
  const prev = yield* runtime.getState;
977
2193
  const next = reducer(prev, payload);
978
- if (import_effect16.Effect.isEffect(next)) {
979
- const exit = yield* import_effect16.Effect.exit(next);
2194
+ if (import_effect20.Effect.isEffect(next)) {
2195
+ const exit = yield* import_effect20.Effect.exit(next);
980
2196
  if (exit._tag === "Failure") {
981
- yield* import_effect16.Effect.logError("Flow error", exit.cause);
2197
+ yield* import_effect20.Effect.logError("Flow error", exit.cause);
982
2198
  return;
983
2199
  }
984
2200
  yield* runtime.setState(exit.value);
@@ -987,15 +2203,15 @@ var LogicBuilderFactory = (runtime, runtimeInternals) => {
987
2203
  yield* runtime.setState(next);
988
2204
  })
989
2205
  )
990
- ).pipe(import_effect16.Effect.catchAllCause((cause) => import_effect16.Effect.logError("Flow error", cause))),
991
- mutate: (reducer) => import_effect16.Stream.runForEach(
2206
+ ).pipe(import_effect20.Effect.catchCause((cause) => import_effect20.Effect.logError("Flow error", cause))),
2207
+ mutate: (reducer) => import_effect20.Stream.runForEach(
992
2208
  stream,
993
2209
  (payload) => taskRunnerRuntime.runWithStateTransaction(
994
2210
  {
995
2211
  kind: "watcher:mutate",
996
2212
  name: triggerName
997
2213
  },
998
- () => import_effect16.Effect.gen(function* () {
2214
+ () => import_effect20.Effect.gen(function* () {
999
2215
  const prev = yield* runtime.getState;
1000
2216
  const recordPatch = runtimeInternals.txn.recordStatePatch;
1001
2217
  const updateDraft = runtimeInternals.txn.updateDraft;
@@ -1008,7 +2224,7 @@ var LogicBuilderFactory = (runtime, runtimeInternals) => {
1008
2224
  updateDraft(nextState);
1009
2225
  })
1010
2226
  )
1011
- ).pipe(import_effect16.Effect.catchAllCause((cause) => import_effect16.Effect.logError("Flow error", cause)))
2227
+ ).pipe(import_effect20.Effect.catchCause((cause) => import_effect20.Effect.logError("Flow error", cause)))
1012
2228
  };
1013
2229
  const pipe = function() {
1014
2230
  const fns = arguments;
@@ -1021,7 +2237,7 @@ var LogicBuilderFactory = (runtime, runtimeInternals) => {
1021
2237
  return Object.assign(builder, { pipe });
1022
2238
  };
1023
2239
  };
1024
- function make3(shape, runtime, options) {
2240
+ function make4(shape, runtime, options) {
1025
2241
  const runtimeInternals = getRuntimeInternals(runtime);
1026
2242
  const getPhase = options?.getPhase ?? (() => "run");
1027
2243
  const getCurrentPhase = () => {
@@ -1036,21 +2252,19 @@ function make3(shape, runtime, options) {
1036
2252
  throw makeLogicPhaseError(kind, api2, "setup", options?.moduleId);
1037
2253
  }
1038
2254
  };
1039
- const flowApi = make2(runtime, runtimeInternals);
2255
+ const flowApi = make3(runtime, runtimeInternals);
1040
2256
  const makeIntentBuilder = (runtime_) => LogicBuilderFactory(runtime_, runtimeInternals);
1041
- const withLifecycle = (available, missing) => import_effect16.Effect.serviceOption(LifecycleContext).pipe(
1042
- import_effect16.Effect.flatMap(
1043
- (maybe) => import_effect16.Option.match(maybe, {
1044
- onSome: available,
1045
- onNone: missing
1046
- })
1047
- )
2257
+ const withLifecycle = (available, missing) => import_effect20.Effect.serviceOption(LifecycleContext).pipe(
2258
+ import_effect20.Effect.flatMap((maybe) => import_effect20.Option.match(maybe, {
2259
+ onSome: available,
2260
+ onNone: missing
2261
+ }))
1048
2262
  );
1049
- const withPlatform = (invoke) => import_effect16.Effect.serviceOption(Tag).pipe(
1050
- import_effect16.Effect.flatMap(
1051
- (maybe) => import_effect16.Option.match(maybe, {
2263
+ const withPlatform = (invoke) => import_effect20.Effect.serviceOption(Tag).pipe(
2264
+ import_effect20.Effect.flatMap(
2265
+ (maybe) => import_effect20.Option.match(maybe, {
1052
2266
  onSome: invoke,
1053
- onNone: () => import_effect16.Effect.void
2267
+ onNone: () => import_effect20.Effect.void
1054
2268
  })
1055
2269
  )
1056
2270
  );
@@ -1063,14 +2277,29 @@ function make3(shape, runtime, options) {
1063
2277
  message: `${api2} is setup-only and is not allowed in run phase.`,
1064
2278
  hint: "Move $.lifecycle.* calls to the synchronous part of Module.logic builder (before return) for registration; for dynamic resource cleanup in the run phase, use Effect.acquireRelease / Scope finalizer instead of registering onDestroy late.",
1065
2279
  kind: "lifecycle_in_run"
1066
- });
2280
+ }).pipe(import_effect20.Effect.orDie);
1067
2281
  const createIntentBuilder = (stream, triggerName) => makeIntentBuilder(runtime)(stream, triggerName);
1068
- const onceInRunSession = (key) => import_effect16.Effect.serviceOption(RunSessionTag).pipe(
1069
- import_effect16.Effect.map((maybe) => import_effect16.Option.isSome(maybe) ? maybe.value.local.once(key) : true)
2282
+ const actionMatchesTag = (action, tag) => {
2283
+ const actionTag = action?._tag;
2284
+ if (actionTag === tag) {
2285
+ return true;
2286
+ }
2287
+ const actionType = action?.type;
2288
+ return actionType === tag;
2289
+ };
2290
+ const actionStreamByTag = (tag) => {
2291
+ const topicSelector = runtime.actionsByTag$;
2292
+ if (typeof topicSelector === "function") {
2293
+ return topicSelector(tag);
2294
+ }
2295
+ return runtime.actions$.pipe(import_effect20.Stream.filter((action) => actionMatchesTag(action, tag)));
2296
+ };
2297
+ const onceInRunSession = (key) => import_effect20.Effect.serviceOption(RunSessionTag).pipe(
2298
+ import_effect20.Effect.map((maybe) => import_effect20.Option.isSome(maybe) ? maybe.value.local.once(key) : true)
1070
2299
  );
1071
2300
  let cachedDiagnosticsLevel;
1072
2301
  const isModuleLike = (value) => Boolean(
1073
- value && typeof value === "object" && (value._kind === "ModuleDef" || value._kind === "Module") && "tag" in value && import_effect16.Context.isTag(value.tag)
2302
+ value && typeof value === "object" && (value._kind === "ModuleDef" || value._kind === "Module") && "tag" in value && import_effect20.ServiceMap.isKey(value.tag)
1074
2303
  );
1075
2304
  const buildModuleHandle = (tag, rt) => {
1076
2305
  const actionsProxy = new Proxy(
@@ -1083,7 +2312,7 @@ function make3(shape, runtime, options) {
1083
2312
  }
1084
2313
  );
1085
2314
  const handle = {
1086
- read: (selector) => import_effect16.Effect.map(rt.getState, selector),
2315
+ read: (selector) => import_effect20.Effect.map(rt.getState, selector),
1087
2316
  changes: rt.changes,
1088
2317
  dispatch: rt.dispatch,
1089
2318
  actions$: rt.actions$,
@@ -1093,7 +2322,7 @@ function make3(shape, runtime, options) {
1093
2322
  const extend = tag?.[EXTEND_HANDLE];
1094
2323
  return typeof extend === "function" ? extend(rt, handle) ?? handle : handle;
1095
2324
  };
1096
- const emitModuleDescriptorOnce = (module2, rt) => import_effect16.Effect.gen(function* () {
2325
+ const emitModuleDescriptorOnce = (module2, rt) => import_effect20.Effect.gen(function* () {
1097
2326
  if (cachedDiagnosticsLevel === "off") return;
1098
2327
  const key = `module_descriptor:${String(rt.instanceId ?? "unknown")}`;
1099
2328
  const shouldEmit = yield* onceInRunSession(key);
@@ -1133,7 +2362,7 @@ function make3(shape, runtime, options) {
1133
2362
  data
1134
2363
  });
1135
2364
  });
1136
- const resolveModuleRuntime = (tag) => import_effect16.Effect.gen(function* () {
2365
+ const resolveModuleRuntime = (tag) => import_effect20.Effect.gen(function* () {
1137
2366
  const requestedModuleId = typeof tag?.id === "string" ? tag.id : void 0;
1138
2367
  const fromModuleId = typeof options?.moduleId === "string" ? options.moduleId : runtime.moduleId;
1139
2368
  if (requestedModuleId && requestedModuleId === runtime.moduleId) {
@@ -1144,8 +2373,8 @@ function make3(shape, runtime, options) {
1144
2373
  return fromImports;
1145
2374
  }
1146
2375
  if (typeof options?.moduleId !== "string") {
1147
- const fromEnv = yield* import_effect16.Effect.serviceOption(tag);
1148
- if (import_effect16.Option.isSome(fromEnv)) {
2376
+ const fromEnv = yield* import_effect20.Effect.serviceOption(tag);
2377
+ if (import_effect20.Option.isSome(fromEnv)) {
1149
2378
  return fromEnv.value;
1150
2379
  }
1151
2380
  }
@@ -1180,46 +2409,163 @@ function make3(shape, runtime, options) {
1180
2409
  };
1181
2410
  err.fix = fix;
1182
2411
  err.name = "MissingModuleRuntimeError";
1183
- return yield* import_effect16.Effect.die(err);
2412
+ return yield* import_effect20.Effect.die(err);
1184
2413
  });
1185
- const stateApi = {
1186
- read: runtime.getState,
1187
- update: (f) => import_effect16.Effect.gen(function* () {
1188
- const inTxn = yield* import_effect16.FiberRef.get(inSyncTransactionFiber);
1189
- if (inTxn) {
1190
- const prev = yield* runtime.getState;
1191
- return yield* runtime.setState(f(prev));
1192
- }
1193
- const body = () => import_effect16.Effect.flatMap(runtime.getState, (prev) => runtime.setState(f(prev)));
1194
- return yield* runtimeInternals ? runtimeInternals.txn.runWithStateTransaction({ kind: "state", name: "update" }, body) : body();
1195
- }),
1196
- mutate: (f) => import_effect16.Effect.gen(function* () {
1197
- const recordPatch = runtimeInternals?.txn.recordStatePatch;
1198
- const updateDraft = runtimeInternals?.txn.updateDraft;
1199
- const inTxn = yield* import_effect16.FiberRef.get(inSyncTransactionFiber);
1200
- if (inTxn) {
1201
- const prev = yield* runtime.getState;
1202
- const { nextState, patchPaths } = mutateWithPatchPaths(prev, (draft) => {
1203
- f(draft);
2414
+ let batchedStateWritebackCoordinator;
2415
+ const getOrCreateBatchedStateWritebackCoordinator = () => {
2416
+ if (batchedStateWritebackCoordinator) return batchedStateWritebackCoordinator;
2417
+ if (!runtimeInternals) {
2418
+ throw new Error("[BatchedStateWritebackCoordinator] Missing runtimeInternals (expected in ModuleRuntime-backed $).");
2419
+ }
2420
+ let inFlight = false;
2421
+ const pending = [];
2422
+ const drain = () => {
2423
+ if (pending.length === 0) return [];
2424
+ return pending.splice(0, pending.length);
2425
+ };
2426
+ const ok = { _tag: "ok" };
2427
+ const fail = (cause) => ({ _tag: "failure", cause });
2428
+ const applyBatch = (batch) => import_effect20.Effect.gen(function* () {
2429
+ if (batch.length === 0) return;
2430
+ let current = yield* runtime.getState;
2431
+ for (let i = 0; i < batch.length; i++) {
2432
+ const req = batch[i];
2433
+ if (req.kind === "update") {
2434
+ const next = req.update(current);
2435
+ current = next;
2436
+ yield* runtime.setState(next);
2437
+ continue;
2438
+ }
2439
+ const { nextState, patchPaths } = mutateWithPatchPaths(current, (draft) => {
2440
+ req.mutate(draft);
1204
2441
  });
1205
2442
  for (const path of patchPaths) {
1206
- recordPatch?.(path, "unknown");
2443
+ runtimeInternals.txn.recordStatePatch(path, "unknown");
1207
2444
  }
1208
- updateDraft?.(nextState);
1209
- return;
2445
+ runtimeInternals.txn.updateDraft(nextState);
2446
+ current = nextState;
2447
+ }
2448
+ });
2449
+ const flushInFlight = () => import_effect20.Effect.uninterruptible(
2450
+ import_effect20.Effect.gen(function* () {
2451
+ if (inFlight) return;
2452
+ inFlight = true;
2453
+ try {
2454
+ while (true) {
2455
+ const batch = drain();
2456
+ if (batch.length === 0) {
2457
+ inFlight = false;
2458
+ if (pending.length === 0) return;
2459
+ inFlight = true;
2460
+ continue;
2461
+ }
2462
+ const originName = batch.length === 1 ? batch[0].kind === "update" ? "update" : "mutate" : "writeback:batched";
2463
+ const exit = yield* import_effect20.Effect.exit(
2464
+ runtimeInternals.txn.runWithStateTransaction(
2465
+ {
2466
+ kind: "state",
2467
+ name: originName,
2468
+ details: { batched: true, count: batch.length }
2469
+ },
2470
+ () => applyBatch(batch).pipe(import_effect20.Effect.asVoid)
2471
+ )
2472
+ );
2473
+ const outcome = exit._tag === "Success" ? ok : fail(exit.cause);
2474
+ for (let i = 0; i < batch.length; i++) {
2475
+ yield* import_effect20.Deferred.succeed(batch[i].done, outcome);
2476
+ }
2477
+ if (outcome._tag === "failure") {
2478
+ return;
2479
+ }
2480
+ }
2481
+ } finally {
2482
+ inFlight = false;
2483
+ }
2484
+ })
2485
+ );
2486
+ const waitForMicrotask = () => import_effect20.Effect.promise(
2487
+ () => new Promise((resolve3) => {
2488
+ if (typeof queueMicrotask === "function") {
2489
+ queueMicrotask(resolve3);
2490
+ return;
2491
+ }
2492
+ Promise.resolve().then(resolve3);
2493
+ })
2494
+ );
2495
+ const enqueueAndAwait = (req) => import_effect20.Effect.gen(function* () {
2496
+ pending.push(req);
2497
+ if (!inFlight) {
2498
+ yield* waitForMicrotask();
2499
+ }
2500
+ yield* flushInFlight();
2501
+ const outcome = yield* import_effect20.Deferred.await(req.done);
2502
+ if (outcome._tag === "failure") {
2503
+ return yield* import_effect20.Effect.die(outcome.cause);
1210
2504
  }
1211
- const body = () => import_effect16.Effect.gen(function* () {
1212
- const prev = yield* runtime.getState;
1213
- const { nextState, patchPaths } = mutateWithPatchPaths(prev, (draft) => {
1214
- f(draft);
2505
+ });
2506
+ const coordinator = {
2507
+ enqueueUpdate: (update) => import_effect20.Effect.gen(function* () {
2508
+ const done = yield* import_effect20.Deferred.make();
2509
+ yield* enqueueAndAwait({ kind: "update", update, done });
2510
+ }),
2511
+ enqueueMutate: (mutate) => import_effect20.Effect.gen(function* () {
2512
+ const done = yield* import_effect20.Deferred.make();
2513
+ yield* enqueueAndAwait({ kind: "mutate", mutate, done });
2514
+ })
2515
+ };
2516
+ batchedStateWritebackCoordinator = coordinator;
2517
+ return coordinator;
2518
+ };
2519
+ const stateApi = {
2520
+ read: runtime.getState,
2521
+ update: (f) => markDirectStateWriteEffect(
2522
+ import_effect20.Effect.gen(function* () {
2523
+ const inTxn = yield* import_effect20.Effect.service(inSyncTransactionFiber).pipe(import_effect20.Effect.orDie);
2524
+ if (inTxn) {
2525
+ const prev = yield* runtime.getState;
2526
+ return yield* runtime.setState(f(prev));
2527
+ }
2528
+ const body = () => import_effect20.Effect.flatMap(runtime.getState, (prev) => runtime.setState(f(prev)));
2529
+ if (runtimeInternals && !isDevEnv()) {
2530
+ return yield* getOrCreateBatchedStateWritebackCoordinator().enqueueUpdate(f);
2531
+ }
2532
+ return yield* runtimeInternals ? runtimeInternals.txn.runWithStateTransaction({ kind: "state", name: "update" }, body) : body();
2533
+ }),
2534
+ { kind: "update", run: f }
2535
+ ),
2536
+ mutate: (f) => markDirectStateWriteEffect(
2537
+ import_effect20.Effect.gen(function* () {
2538
+ const recordPatch = runtimeInternals?.txn.recordStatePatch;
2539
+ const updateDraft = runtimeInternals?.txn.updateDraft;
2540
+ const inTxn = yield* import_effect20.Effect.service(inSyncTransactionFiber).pipe(import_effect20.Effect.orDie);
2541
+ if (inTxn) {
2542
+ const prev = yield* runtime.getState;
2543
+ const { nextState, patchPaths } = mutateWithPatchPaths(prev, (draft) => {
2544
+ f(draft);
2545
+ });
2546
+ for (const path of patchPaths) {
2547
+ recordPatch?.(path, "unknown");
2548
+ }
2549
+ updateDraft?.(nextState);
2550
+ return;
2551
+ }
2552
+ const body = () => import_effect20.Effect.gen(function* () {
2553
+ const prev = yield* runtime.getState;
2554
+ const { nextState, patchPaths } = mutateWithPatchPaths(prev, (draft) => {
2555
+ f(draft);
2556
+ });
2557
+ for (const path of patchPaths) {
2558
+ recordPatch?.(path, "unknown");
2559
+ }
2560
+ updateDraft?.(nextState);
1215
2561
  });
1216
- for (const path of patchPaths) {
1217
- recordPatch?.(path, "unknown");
2562
+ if (runtimeInternals && !isDevEnv()) {
2563
+ return yield* getOrCreateBatchedStateWritebackCoordinator().enqueueMutate(f);
1218
2564
  }
1219
- updateDraft?.(nextState);
1220
- });
1221
- return yield* runtimeInternals ? runtimeInternals.txn.runWithStateTransaction({ kind: "state", name: "mutate" }, body) : body();
1222
- }),
2565
+ return yield* runtimeInternals ? runtimeInternals.txn.runWithStateTransaction({ kind: "state", name: "mutate" }, body) : body();
2566
+ }),
2567
+ { kind: "mutate", run: f }
2568
+ ),
1223
2569
  ref: runtime.ref
1224
2570
  };
1225
2571
  const actions = shape.actionMap;
@@ -1257,13 +2603,13 @@ function make3(shape, runtime, options) {
1257
2603
  const matchApi = (value) => makeMatch(value);
1258
2604
  const matchTagApi = (value) => makeMatchTag(value);
1259
2605
  const reducer = (tag, fn) => {
1260
- return import_effect16.Effect.sync(() => {
2606
+ return import_effect20.Effect.sync(() => {
1261
2607
  runtimeInternals.txn.registerReducer(String(tag), fn);
1262
2608
  });
1263
2609
  };
1264
- const effect = (token, handler) => import_effect16.Effect.gen(function* () {
2610
+ const effect = (token, handler) => import_effect20.Effect.gen(function* () {
1265
2611
  if (!isActionToken(token)) {
1266
- return yield* import_effect16.Effect.dieMessage("[BoundApi.effect] token must be an ActionToken");
2612
+ return yield* import_effect20.Effect.die(new Error("[BoundApi.effect] token must be an ActionToken"));
1267
2613
  }
1268
2614
  const phase = getCurrentPhase();
1269
2615
  const logicUnit = options?.logicUnit;
@@ -1303,56 +2649,56 @@ function make3(shape, runtime, options) {
1303
2649
  return emitSetupOnlyViolation("$.lifecycle.onInitRequired");
1304
2650
  }
1305
2651
  runtimeInternals.lifecycle.registerInitRequired(eff);
1306
- return import_effect16.Effect.void;
2652
+ return import_effect20.Effect.void;
1307
2653
  },
1308
2654
  onStart: (eff) => {
1309
2655
  if (getCurrentPhase() === "run") {
1310
2656
  return emitSetupOnlyViolation("$.lifecycle.onStart");
1311
2657
  }
1312
2658
  runtimeInternals.lifecycle.registerStart(eff);
1313
- return import_effect16.Effect.void;
2659
+ return import_effect20.Effect.void;
1314
2660
  },
1315
2661
  onInit: (eff) => {
1316
2662
  if (getCurrentPhase() === "run") {
1317
2663
  return emitSetupOnlyViolation("$.lifecycle.onInit");
1318
2664
  }
1319
2665
  runtimeInternals.lifecycle.registerInitRequired(eff);
1320
- return import_effect16.Effect.void;
2666
+ return import_effect20.Effect.void;
1321
2667
  },
1322
2668
  onDestroy: (eff) => {
1323
2669
  if (getCurrentPhase() === "run") {
1324
2670
  return emitSetupOnlyViolation("$.lifecycle.onDestroy");
1325
2671
  }
1326
2672
  runtimeInternals.lifecycle.registerDestroy(eff);
1327
- return import_effect16.Effect.void;
2673
+ return import_effect20.Effect.void;
1328
2674
  },
1329
2675
  onError: (handler) => {
1330
2676
  if (getCurrentPhase() === "run") {
1331
2677
  return emitSetupOnlyViolation("$.lifecycle.onError");
1332
2678
  }
1333
2679
  runtimeInternals.lifecycle.registerOnError(handler);
1334
- return import_effect16.Effect.void;
2680
+ return import_effect20.Effect.void;
1335
2681
  },
1336
2682
  onSuspend: (eff) => {
1337
2683
  if (getCurrentPhase() === "run") {
1338
2684
  return emitSetupOnlyViolation("$.lifecycle.onSuspend");
1339
2685
  }
1340
- runtimeInternals.lifecycle.registerPlatformSuspend(import_effect16.Effect.asVoid(eff));
1341
- return import_effect16.Effect.void;
2686
+ runtimeInternals.lifecycle.registerPlatformSuspend(import_effect20.Effect.asVoid(eff));
2687
+ return import_effect20.Effect.void;
1342
2688
  },
1343
2689
  onResume: (eff) => {
1344
2690
  if (getCurrentPhase() === "run") {
1345
2691
  return emitSetupOnlyViolation("$.lifecycle.onResume");
1346
2692
  }
1347
- runtimeInternals.lifecycle.registerPlatformResume(import_effect16.Effect.asVoid(eff));
1348
- return import_effect16.Effect.void;
2693
+ runtimeInternals.lifecycle.registerPlatformResume(import_effect20.Effect.asVoid(eff));
2694
+ return import_effect20.Effect.void;
1349
2695
  },
1350
2696
  onReset: (eff) => {
1351
2697
  if (getCurrentPhase() === "run") {
1352
2698
  return emitSetupOnlyViolation("$.lifecycle.onReset");
1353
2699
  }
1354
- runtimeInternals.lifecycle.registerPlatformReset(import_effect16.Effect.asVoid(eff));
1355
- return import_effect16.Effect.void;
2700
+ runtimeInternals.lifecycle.registerPlatformReset(import_effect20.Effect.asVoid(eff));
2701
+ return import_effect20.Effect.void;
1356
2702
  }
1357
2703
  },
1358
2704
  traits: {
@@ -1386,14 +2732,14 @@ function make3(shape, runtime, options) {
1386
2732
  });
1387
2733
  },
1388
2734
  source: {
1389
- refresh: (fieldPath, options2) => import_effect16.Effect.gen(function* () {
2735
+ refresh: (fieldPath, options2) => import_effect20.Effect.gen(function* () {
1390
2736
  const handler = runtimeInternals.traits.getSourceRefreshHandler(fieldPath);
1391
2737
  if (!handler) {
1392
- return yield* import_effect16.Effect.void;
2738
+ return yield* import_effect20.Effect.void;
1393
2739
  }
1394
2740
  const force = options2?.force === true;
1395
- const runHandler = (state) => force ? import_effect16.Effect.locally(forceSourceRefresh, true)(handler(state)) : handler(state);
1396
- const inTxn = yield* import_effect16.FiberRef.get(inSyncTransactionFiber);
2741
+ const runHandler = (state) => force ? import_effect20.Effect.provideService(handler(state), forceSourceRefresh, true) : handler(state);
2742
+ const inTxn = yield* import_effect20.Effect.service(inSyncTransactionFiber).pipe(import_effect20.Effect.orDie);
1397
2743
  if (inTxn) {
1398
2744
  const state = yield* runtime.getState;
1399
2745
  return yield* runHandler(state);
@@ -1403,7 +2749,7 @@ function make3(shape, runtime, options) {
1403
2749
  kind: "source-refresh",
1404
2750
  name: fieldPath
1405
2751
  },
1406
- () => import_effect16.Effect.gen(function* () {
2752
+ () => import_effect20.Effect.gen(function* () {
1407
2753
  const state = yield* runtime.getState;
1408
2754
  return yield* runHandler(state);
1409
2755
  })
@@ -1420,18 +2766,19 @@ function make3(shape, runtime, options) {
1420
2766
  if (isModuleLike(arg)) {
1421
2767
  const domain = arg;
1422
2768
  const tag = domain.tag;
1423
- const resolveAndBuild = resolveModuleRuntime(tag).pipe(import_effect16.Effect.map((rt) => buildModuleHandle(tag, rt)));
2769
+ const resolveAndBuild = resolveModuleRuntime(tag).pipe(import_effect20.Effect.map((rt) => buildModuleHandle(tag, rt)));
1424
2770
  const resolveWithDescriptor = resolveModuleRuntime(tag).pipe(
1425
- import_effect16.Effect.tap((rt) => emitModuleDescriptorOnce(domain, rt)),
1426
- import_effect16.Effect.map((rt) => buildModuleHandle(tag, rt))
2771
+ import_effect20.Effect.tap((rt) => emitModuleDescriptorOnce(domain, rt)),
2772
+ import_effect20.Effect.map((rt) => buildModuleHandle(tag, rt))
1427
2773
  );
1428
- const detectAndSelect = import_effect16.FiberRef.get(currentDiagnosticsLevel).pipe(
1429
- import_effect16.Effect.tap((level) => {
2774
+ const detectAndSelect = import_effect20.Effect.service(currentDiagnosticsLevel).pipe(
2775
+ import_effect20.Effect.map((level) => {
1430
2776
  cachedDiagnosticsLevel = level;
2777
+ return level;
1431
2778
  }),
1432
- import_effect16.Effect.flatMap((level) => level === "off" ? resolveAndBuild : resolveWithDescriptor)
2779
+ import_effect20.Effect.flatMap((level) => level === "off" ? resolveAndBuild : resolveWithDescriptor)
1433
2780
  );
1434
- return import_effect16.Effect.suspend(() => {
2781
+ return import_effect20.Effect.suspend(() => {
1435
2782
  if (cachedDiagnosticsLevel === "off") {
1436
2783
  return resolveAndBuild;
1437
2784
  }
@@ -1441,16 +2788,16 @@ function make3(shape, runtime, options) {
1441
2788
  return detectAndSelect;
1442
2789
  });
1443
2790
  }
1444
- if (import_effect16.Context.isTag(arg)) {
2791
+ if (import_effect20.ServiceMap.isKey(arg)) {
1445
2792
  const candidate = arg;
1446
2793
  if (candidate._kind === "ModuleTag") {
1447
2794
  return resolveModuleRuntime(arg).pipe(
1448
- import_effect16.Effect.map((rt) => buildModuleHandle(arg, rt))
2795
+ import_effect20.Effect.map((rt) => buildModuleHandle(arg, rt))
1449
2796
  );
1450
2797
  }
1451
- return arg;
2798
+ return import_effect20.Effect.service(arg).pipe(import_effect20.Effect.orDie);
1452
2799
  }
1453
- return import_effect16.Effect.die("BoundApi.use: unsupported argument");
2800
+ return import_effect20.Effect.die("BoundApi.use: unsupported argument");
1454
2801
  }
1455
2802
  }),
1456
2803
  onAction: new Proxy(() => {
@@ -1460,39 +2807,33 @@ function make3(shape, runtime, options) {
1460
2807
  const arg = args[0];
1461
2808
  if (isActionToken(arg)) {
1462
2809
  const tag = arg.tag;
2810
+ return createIntentBuilder(actionStreamByTag(tag).pipe(import_effect20.Stream.map((action) => action.payload)), tag);
2811
+ }
2812
+ if (import_effect20.Schema.isSchema(arg)) {
2813
+ const decode = import_effect20.Schema.decodeUnknownSync(arg);
1463
2814
  return createIntentBuilder(
1464
2815
  runtime.actions$.pipe(
1465
- import_effect16.Stream.filter((a) => a._tag === tag || a.type === tag),
1466
- import_effect16.Stream.map((a) => a.payload)
1467
- ),
1468
- tag
2816
+ import_effect20.Stream.filter((a) => {
2817
+ try {
2818
+ decode(a);
2819
+ return true;
2820
+ } catch {
2821
+ return false;
2822
+ }
2823
+ })
2824
+ )
1469
2825
  );
1470
2826
  }
1471
2827
  if (typeof arg === "function") {
1472
- return createIntentBuilder(runtime.actions$.pipe(import_effect16.Stream.filter(arg)));
2828
+ return createIntentBuilder(runtime.actions$.pipe(import_effect20.Stream.filter(arg)));
1473
2829
  }
1474
2830
  if (typeof arg === "string") {
1475
- return createIntentBuilder(
1476
- runtime.actions$.pipe(import_effect16.Stream.filter((a) => a._tag === arg || a.type === arg)),
1477
- arg
1478
- );
2831
+ return createIntentBuilder(actionStreamByTag(arg), arg);
1479
2832
  }
1480
2833
  if (typeof arg === "object" && arg !== null) {
1481
2834
  if ("_tag" in arg) {
1482
- return createIntentBuilder(
1483
- runtime.actions$.pipe(import_effect16.Stream.filter((a) => a._tag === arg._tag)),
1484
- String(arg._tag)
1485
- );
1486
- }
1487
- if (import_effect16.Schema.isSchema(arg)) {
1488
- return createIntentBuilder(
1489
- runtime.actions$.pipe(
1490
- import_effect16.Stream.filter((a) => {
1491
- const result = import_effect16.Schema.decodeUnknownSync(arg)(a);
1492
- return !!result;
1493
- })
1494
- )
1495
- );
2835
+ const tag = String(arg._tag);
2836
+ return createIntentBuilder(actionStreamByTag(tag), tag);
1496
2837
  }
1497
2838
  }
1498
2839
  return createIntentBuilder(runtime.actions$);
@@ -1500,10 +2841,7 @@ function make3(shape, runtime, options) {
1500
2841
  get: (_target, prop) => {
1501
2842
  guardRunOnly("use_in_setup", "$.onAction");
1502
2843
  if (typeof prop === "string") {
1503
- return createIntentBuilder(
1504
- runtime.actions$.pipe(import_effect16.Stream.filter((a) => a._tag === prop || a.type === prop)),
1505
- prop
1506
- );
2844
+ return createIntentBuilder(actionStreamByTag(prop), prop);
1507
2845
  }
1508
2846
  return void 0;
1509
2847
  }
@@ -1522,8 +2860,8 @@ function make3(shape, runtime, options) {
1522
2860
  }
1523
2861
 
1524
2862
  // src/Bound.ts
1525
- function make4(shape, runtime) {
1526
- return make3(shape, runtime);
2863
+ function make5(shape, runtime) {
2864
+ return make4(shape, runtime);
1527
2865
  }
1528
2866
  // Annotate the CommonJS export names for ESM import in node:
1529
2867
  0 && (module.exports = {