@ultrst-armada/krnl 1.0.2 → 1.0.4

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 (237) hide show
  1. package/README.md +67 -65
  2. package/package.json +15 -8
  3. package/packages/cli/dist/bin/krnl.cjs +808 -331
  4. package/packages/cli/dist/bin/krnl.js +50 -65
  5. package/packages/cli/dist/chunk-GHWYEAPD.js +1642 -0
  6. package/packages/cli/dist/index.cjs +761 -263
  7. package/packages/cli/dist/index.d.cts +45 -2
  8. package/packages/cli/dist/index.d.ts +45 -2
  9. package/packages/cli/dist/index.js +5 -1
  10. package/packages/cli/package.json +17 -10
  11. package/packages/core/dist/index.cjs +2912 -140
  12. package/packages/core/dist/index.d.cts +614 -27
  13. package/packages/core/dist/index.d.ts +614 -27
  14. package/packages/core/dist/index.js +2903 -140
  15. package/packages/core/package.json +15 -6
  16. package/packages/create-krnl/dist/index.cjs +102 -65
  17. package/packages/create-krnl/dist/index.js +102 -65
  18. package/packages/create-krnl/package.json +5 -3
  19. package/packages/eslint-plugin/dist/index.cjs +17 -55
  20. package/packages/eslint-plugin/dist/index.d.cts +8 -43
  21. package/packages/eslint-plugin/dist/index.d.ts +8 -43
  22. package/packages/eslint-plugin/dist/index.js +17 -55
  23. package/packages/eslint-plugin/package.json +5 -4
  24. package/packages/validate/dist/index.cjs +378 -85
  25. package/packages/validate/dist/index.d.cts +11 -1
  26. package/packages/validate/dist/index.d.ts +11 -1
  27. package/packages/validate/dist/index.js +375 -82
  28. package/packages/validate/package.json +14 -7
  29. package/packages/cli/dist/K_ENT_Entity-PQ5MURQY-ZG6FZXXX.js +0 -13
  30. package/packages/cli/dist/K_LIB_Krnl_Aiko_Client-OPZAVZCW-K4CRQYA5.js +0 -8
  31. package/packages/cli/dist/K_LIB_Krnl_Ep_Tools-ROOE2TQF-LNPXZYOE.js +0 -110
  32. package/packages/cli/dist/K_LIB_Krnl_Frontend_Builder-2ZDUH6PF-3ALZPNX4.js +0 -11
  33. package/packages/cli/dist/K_LIB_Krnl_Frontend_Generator-UYNRNX2X-PJTICYSW.js +0 -11
  34. package/packages/cli/dist/K_LIB_Krnl_Registry_Client-NXV6D2QW-M5TYU55O.js +0 -8
  35. package/packages/cli/dist/K_LIB_Krnl_SubApp_Engine-7HR5HWW2-H6STOXRK.js +0 -20
  36. package/packages/cli/dist/K_LIB_Krnl_SubApp_Registry-7XYGDKJK-XPJXSF7D.js +0 -19
  37. package/packages/cli/dist/K_LIB_Krnl_SubApp_Worker_Host-CQVTGGG7-CUYGTWOW.js +0 -7
  38. package/packages/cli/dist/K_LIB_Krnl_System_App_Adapter-M6FJKLGU-VR6T4N6J.js +0 -17
  39. package/packages/cli/dist/K_LIB_Krnl_System_Base_Functionality_APIs-ZZUZ6ZG5-RLJ4QWDP.js +0 -58
  40. package/packages/cli/dist/K_LIB_Krnl_System_Magnetic_Loader-XBQO2KXF-BOQGUASC.js +0 -22
  41. package/packages/cli/dist/K_LIB_Krnl_System_Unified_Http_Adapter-RCEGP3OG-XJI7KIT5.js +0 -8
  42. package/packages/cli/dist/K_LIB_Krnl_Telemetry-77FRZ3KV-K5VCWAFW.js +0 -9
  43. package/packages/cli/dist/chunk-3TRM6CYL.js +0 -152
  44. package/packages/cli/dist/chunk-5JDK35TG.js +0 -3872
  45. package/packages/cli/dist/chunk-63PTK33I.js +0 -997
  46. package/packages/cli/dist/chunk-6NIKAMUZ.js +0 -82
  47. package/packages/cli/dist/chunk-BOXWWXQG.js +0 -400
  48. package/packages/cli/dist/chunk-EEKLK7QJ.js +0 -565
  49. package/packages/cli/dist/chunk-EG7T2IAD.js +0 -107
  50. package/packages/cli/dist/chunk-ESTKOQ7T.js +0 -1146
  51. package/packages/cli/dist/chunk-F5EHXE2O.js +0 -1036
  52. package/packages/cli/dist/chunk-F65ANSQG.js +0 -269
  53. package/packages/cli/dist/chunk-FDNCADFE.js +0 -71
  54. package/packages/cli/dist/chunk-FZ6X7PHR.js +0 -1146
  55. package/packages/cli/dist/chunk-GDLRMDAN.js +0 -127
  56. package/packages/cli/dist/chunk-HWMTCMOS.js +0 -656
  57. package/packages/cli/dist/chunk-I74QIQOD.js +0 -5536
  58. package/packages/cli/dist/chunk-JTLSTO25.js +0 -71
  59. package/packages/cli/dist/chunk-JULBBJ27.js +0 -1033
  60. package/packages/cli/dist/chunk-OHVMVRBP.js +0 -117
  61. package/packages/cli/dist/chunk-P2PCLEKX.js +0 -666
  62. package/packages/cli/dist/chunk-PJQIUOX2.js +0 -7767
  63. package/packages/cli/dist/chunk-PPOF3DJW.js +0 -471
  64. package/packages/cli/dist/chunk-Q45257P6.js +0 -173
  65. package/packages/cli/dist/chunk-QNROWGBI.js +0 -1036
  66. package/packages/cli/dist/chunk-RJNYUXZD.js +0 -977
  67. package/packages/cli/dist/chunk-SRTOPJ5W.js +0 -104
  68. package/packages/cli/dist/chunk-TCEX3MPS.js +0 -702
  69. package/packages/cli/dist/chunk-TNOAJO2J.js +0 -675
  70. package/packages/cli/dist/chunk-UR2SUCSF.js +0 -701
  71. package/packages/cli/dist/chunk-X5LOIFM7.js +0 -68
  72. package/packages/cli/dist/chunk-XIRFOO3H.js +0 -589
  73. package/packages/cli/dist/chunk-ZAAV3JXQ.js +0 -809
  74. package/packages/core/dist/K_ENT_Entity-4MB7CU4A.js +0 -12
  75. package/packages/core/dist/K_ENT_Entity-DEJGIDGH.js +0 -12
  76. package/packages/core/dist/K_ENT_Entity-FXZO5UZ2.js +0 -12
  77. package/packages/core/dist/K_ENT_Entity-HDSCXC5F.js +0 -12
  78. package/packages/core/dist/K_ENT_Entity-JILABHLW.js +0 -12
  79. package/packages/core/dist/K_ENT_Entity-PQ5MURQY.js +0 -13
  80. package/packages/core/dist/K_ENT_Entity-ROAKDIHW.js +0 -12
  81. package/packages/core/dist/K_ENT_Entity-TBVFSKDV.js +0 -12
  82. package/packages/core/dist/K_ENT_Entity-ZFLKG3JO.js +0 -12
  83. package/packages/core/dist/K_LIB_Krnl_Aiko_Client-OPZAVZCW.js +0 -8
  84. package/packages/core/dist/K_LIB_Krnl_Ep_Tools-ROOE2TQF.js +0 -110
  85. package/packages/core/dist/K_LIB_Krnl_Frontend_Builder-2ZDUH6PF.js +0 -9
  86. package/packages/core/dist/K_LIB_Krnl_Frontend_Generator-UYNRNX2X.js +0 -9
  87. package/packages/core/dist/K_LIB_Krnl_Registry_Client-NXV6D2QW.js +0 -8
  88. package/packages/core/dist/K_LIB_Krnl_SubApp_Engine-7HR5HWW2.js +0 -20
  89. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-4C6GBQAG.js +0 -18
  90. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-6V23A6F6.js +0 -18
  91. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-7XYGDKJK.js +0 -19
  92. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-DYLLC5G2.js +0 -18
  93. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-F4FOFAUP.js +0 -18
  94. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-FBOXXMI3.js +0 -18
  95. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-Q73BWLNP.js +0 -18
  96. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-QM2C4MVA.js +0 -18
  97. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-QUGI6SMP.js +0 -18
  98. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-RGMTBHNP.js +0 -18
  99. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-RWR7UNDW.js +0 -18
  100. package/packages/core/dist/K_LIB_Krnl_SubApp_Worker_Host-CQVTGGG7.js +0 -7
  101. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-32MFJJ5Z.js +0 -17
  102. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-4J4CEWRY.js +0 -17
  103. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-A366YHF2.js +0 -17
  104. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-LK4LYJHI.js +0 -17
  105. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-M6FJKLGU.js +0 -17
  106. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-NW3K63II.js +0 -17
  107. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-QDHTI5ZV.js +0 -17
  108. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-VHCT6VIW.js +0 -17
  109. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-WBRKF24R.js +0 -17
  110. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-XKYQYT6Q.js +0 -17
  111. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-Z2PWZYDZ.js +0 -17
  112. package/packages/core/dist/K_LIB_Krnl_System_Base_Functionality_APIs-ZZUZ6ZG5.js +0 -58
  113. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-2EZU7QF4.js +0 -21
  114. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-6G3AQNAV.js +0 -21
  115. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-B2NZMQUG.js +0 -21
  116. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-C2RABMZP.js +0 -21
  117. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-HHE3NZ4F.js +0 -21
  118. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-LHFGR6WK.js +0 -21
  119. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-M74BLM3N.js +0 -21
  120. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-PT6ZA6EA.js +0 -21
  121. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-SP52V3CX.js +0 -21
  122. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-XBQO2KXF.js +0 -22
  123. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-YNSEUHJJ.js +0 -21
  124. package/packages/core/dist/K_LIB_Krnl_System_Unified_Http_Adapter-M6SBHIVA.js +0 -8
  125. package/packages/core/dist/K_LIB_Krnl_System_Unified_Http_Adapter-RCEGP3OG.js +0 -8
  126. package/packages/core/dist/K_LIB_Krnl_Telemetry-77FRZ3KV.js +0 -9
  127. package/packages/core/dist/chunk-33L2J7V7.js +0 -82
  128. package/packages/core/dist/chunk-3ES4K2ZP.js +0 -817
  129. package/packages/core/dist/chunk-3SMHVVLL.js +0 -82
  130. package/packages/core/dist/chunk-3UEZ7JQA.js +0 -4877
  131. package/packages/core/dist/chunk-3XIE6KBD.js +0 -4877
  132. package/packages/core/dist/chunk-46ZLCML6.js +0 -107
  133. package/packages/core/dist/chunk-4UEL3DWJ.js +0 -107
  134. package/packages/core/dist/chunk-54GWZ5PC.js +0 -82
  135. package/packages/core/dist/chunk-6QCYRS5L.js +0 -127
  136. package/packages/core/dist/chunk-6ULMHNXR.js +0 -104
  137. package/packages/core/dist/chunk-7WUETJEV.js +0 -117
  138. package/packages/core/dist/chunk-A5KRAYDB.js +0 -107
  139. package/packages/core/dist/chunk-ANEAZ3PO.js +0 -107
  140. package/packages/core/dist/chunk-BE76RL6F.js +0 -82
  141. package/packages/core/dist/chunk-CIARVYDO.js +0 -107
  142. package/packages/core/dist/chunk-CR2ANE62.js +0 -107
  143. package/packages/core/dist/chunk-DI27MOR7.js +0 -173
  144. package/packages/core/dist/chunk-E6RLFHM5.js +0 -596
  145. package/packages/core/dist/chunk-EELAPMNV.js +0 -4877
  146. package/packages/core/dist/chunk-ENZ2RQVJ.js +0 -107
  147. package/packages/core/dist/chunk-F2U6CX4F.js +0 -4877
  148. package/packages/core/dist/chunk-FKG64OHL.js +0 -82
  149. package/packages/core/dist/chunk-FYAZJYM5.js +0 -772
  150. package/packages/core/dist/chunk-G4NP4RDQ.js +0 -82
  151. package/packages/core/dist/chunk-GADIRLRS.js +0 -473
  152. package/packages/core/dist/chunk-GR6CSLQJ.js +0 -772
  153. package/packages/core/dist/chunk-HDS7AT6O.js +0 -772
  154. package/packages/core/dist/chunk-HIMEZUU2.js +0 -71
  155. package/packages/core/dist/chunk-IB4UHG5I.js +0 -596
  156. package/packages/core/dist/chunk-J7ZYNVRS.js +0 -772
  157. package/packages/core/dist/chunk-JVLZU4K7.js +0 -604
  158. package/packages/core/dist/chunk-JYXXI7Q3.js +0 -82
  159. package/packages/core/dist/chunk-K54K2KZW.js +0 -192
  160. package/packages/core/dist/chunk-K6VHLBNH.js +0 -3316
  161. package/packages/core/dist/chunk-KCBP7ZYA.js +0 -596
  162. package/packages/core/dist/chunk-KFQGP6VL.js +0 -33
  163. package/packages/core/dist/chunk-KIUEUI7K.js +0 -82
  164. package/packages/core/dist/chunk-LB67NIZP.js +0 -949
  165. package/packages/core/dist/chunk-LDTYFUNW.js +0 -596
  166. package/packages/core/dist/chunk-MLVWARD4.js +0 -596
  167. package/packages/core/dist/chunk-MPYVXHKO.js +0 -2777
  168. package/packages/core/dist/chunk-MRQ3MITU.js +0 -772
  169. package/packages/core/dist/chunk-MVUN7I7O.js +0 -107
  170. package/packages/core/dist/chunk-NDDOIRW7.js +0 -596
  171. package/packages/core/dist/chunk-O3KDB5MH.js +0 -3330
  172. package/packages/core/dist/chunk-OEINUDSE.js +0 -400
  173. package/packages/core/dist/chunk-OPDENPT4.js +0 -4877
  174. package/packages/core/dist/chunk-P6XEM2LA.js +0 -429
  175. package/packages/core/dist/chunk-QKMRSQV4.js +0 -82
  176. package/packages/core/dist/chunk-R6CCWALL.js +0 -4877
  177. package/packages/core/dist/chunk-RAMMOO73.js +0 -774
  178. package/packages/core/dist/chunk-S3FTZFG6.js +0 -772
  179. package/packages/core/dist/chunk-T2ZVN434.js +0 -4877
  180. package/packages/core/dist/chunk-TFHLDMIA.js +0 -107
  181. package/packages/core/dist/chunk-TI3QUCIJ.js +0 -107
  182. package/packages/core/dist/chunk-TR2BAIGI.js +0 -107
  183. package/packages/core/dist/chunk-UGVVJKC6.js +0 -4877
  184. package/packages/core/dist/chunk-V2DX7YIU.js +0 -984
  185. package/packages/core/dist/chunk-W4IHYUYD.js +0 -772
  186. package/packages/core/dist/chunk-W6WBG5OY.js +0 -4877
  187. package/packages/core/dist/chunk-WN3M7O7H.js +0 -3312
  188. package/packages/core/dist/chunk-WR3NCU7U.js +0 -4877
  189. package/packages/core/dist/chunk-XC6B6L27.js +0 -82
  190. package/packages/core/dist/chunk-XNSE64ZY.js +0 -3316
  191. package/packages/core/dist/chunk-XROES2WN.js +0 -634
  192. package/packages/core/dist/chunk-XSCKNRCZ.js +0 -5020
  193. package/packages/core/dist/chunk-XVABPAUZ.js +0 -82
  194. package/packages/core/dist/chunk-YOBCB5C5.js +0 -596
  195. package/packages/core/dist/chunk-YUK6Q563.js +0 -666
  196. package/packages/core/dist/chunk-YXGL3ZEU.js +0 -1030
  197. package/packages/core/dist/chunk-ZINJ5OUX.js +0 -596
  198. package/packages/core/dist/chunk-ZPFD4BIQ.js +0 -604
  199. package/packages/core/dist/chunk-ZQZBFG6F.js +0 -4826
  200. package/packages/core/dist/chunk-ZZFRJGXM.js +0 -4877
  201. package/packages/create-krnl/dist/K_ENT_Entity-PQ5MURQY-R2OH4VXE.js +0 -14
  202. package/packages/create-krnl/dist/K_LIB_Krnl_Aiko_Client-OPZAVZCW-AZM5HF4M.js +0 -9
  203. package/packages/create-krnl/dist/K_LIB_Krnl_Ep_Tools-ROOE2TQF-X5N6SV2S.js +0 -111
  204. package/packages/create-krnl/dist/K_LIB_Krnl_Frontend_Builder-2ZDUH6PF-5PFHF4JU.js +0 -12
  205. package/packages/create-krnl/dist/K_LIB_Krnl_Frontend_Generator-UYNRNX2X-ED33OQPH.js +0 -12
  206. package/packages/create-krnl/dist/K_LIB_Krnl_Registry_Client-NXV6D2QW-YGQLVR4P.js +0 -9
  207. package/packages/create-krnl/dist/K_LIB_Krnl_SubApp_Engine-7HR5HWW2-VM7CTU2L.js +0 -21
  208. package/packages/create-krnl/dist/K_LIB_Krnl_SubApp_Registry-7XYGDKJK-Y2GQFJ7I.js +0 -21
  209. package/packages/create-krnl/dist/K_LIB_Krnl_SubApp_Worker_Host-CQVTGGG7-L3JQWO54.js +0 -8
  210. package/packages/create-krnl/dist/K_LIB_Krnl_System_App_Adapter-M6FJKLGU-KQARASPR.js +0 -19
  211. package/packages/create-krnl/dist/K_LIB_Krnl_System_Base_Functionality_APIs-ZZUZ6ZG5-OF3IGLVL.js +0 -59
  212. package/packages/create-krnl/dist/K_LIB_Krnl_System_Magnetic_Loader-XBQO2KXF-JOLHKOEX.js +0 -24
  213. package/packages/create-krnl/dist/K_LIB_Krnl_System_Unified_Http_Adapter-RCEGP3OG-L46LSHKQ.js +0 -10
  214. package/packages/create-krnl/dist/K_LIB_Krnl_Telemetry-77FRZ3KV-4JUPRR3X.js +0 -10
  215. package/packages/create-krnl/dist/chunk-3TRM6CYL.js +0 -152
  216. package/packages/create-krnl/dist/chunk-3URCB3QS.js +0 -127
  217. package/packages/create-krnl/dist/chunk-5JDK35TG.js +0 -3872
  218. package/packages/create-krnl/dist/chunk-A2XAXDOW.js +0 -812
  219. package/packages/create-krnl/dist/chunk-AN6TMQHG.js +0 -1033
  220. package/packages/create-krnl/dist/chunk-BOXWWXQG.js +0 -400
  221. package/packages/create-krnl/dist/chunk-BPTBREBG.js +0 -38
  222. package/packages/create-krnl/dist/chunk-FDNCADFE.js +0 -71
  223. package/packages/create-krnl/dist/chunk-JTLSTO25.js +0 -71
  224. package/packages/create-krnl/dist/chunk-M3NCUIPL.js +0 -107
  225. package/packages/create-krnl/dist/chunk-N2EONSOC.js +0 -7769
  226. package/packages/create-krnl/dist/chunk-OHVMVRBP.js +0 -117
  227. package/packages/create-krnl/dist/chunk-Q45257P6.js +0 -173
  228. package/packages/create-krnl/dist/chunk-QGM4M3NI.js +0 -37
  229. package/packages/create-krnl/dist/chunk-RJNYUXZD.js +0 -977
  230. package/packages/create-krnl/dist/chunk-SRTOPJ5W.js +0 -104
  231. package/packages/create-krnl/dist/chunk-UPBIGEC3.js +0 -666
  232. package/packages/create-krnl/dist/chunk-V2DB7UD7.js +0 -82
  233. package/packages/create-krnl/dist/chunk-WMHLIUI6.js +0 -3644
  234. package/packages/create-krnl/dist/chunk-XIRFOO3H.js +0 -589
  235. package/packages/create-krnl/dist/chunk-Y2CEEVZP.js +0 -5536
  236. package/packages/create-krnl/dist/main-DXUMPBND.js +0 -2217
  237. package/packages/create-krnl/dist/wrapper-SDF2VKX3.js +0 -31
@@ -56,171 +56,2541 @@ var ServiceEventBus = class {
56
56
  };
57
57
 
58
58
  // src/lifecycle/LifecycleManager.ts
59
+ var TRANSITIONS = {
60
+ uninitialized: ["initializing"],
61
+ initializing: ["ready", "uninitialized"],
62
+ ready: ["starting"],
63
+ starting: ["running", "ready"],
64
+ running: ["stopping"],
65
+ stopping: ["stopped", "running"],
66
+ stopped: ["starting"]
67
+ };
59
68
  var LifecycleManager = class {
60
69
  status = "uninitialized";
61
70
  getStatus() {
62
71
  return this.status;
63
72
  }
64
- setStatus(next) {
65
- this.status = next;
73
+ canTransitionTo(next) {
74
+ return TRANSITIONS[this.status].includes(next);
75
+ }
76
+ transitionTo(next) {
77
+ if (!this.canTransitionTo(next)) {
78
+ throw new Error("[Lifecycle] Invalid transition '" + this.status + "' -> '" + next + "'.");
79
+ }
80
+ this.status = next;
81
+ }
82
+ setStatus(next) {
83
+ this.transitionTo(next);
84
+ }
85
+ assertRunning(serviceName) {
86
+ if (this.status !== "running") {
87
+ throw new Error(
88
+ "[Service:" + serviceName + "] Cannot invoke operation while status is '" + this.status + "' (expected 'running')."
89
+ );
90
+ }
91
+ }
92
+ };
93
+
94
+ // src/services/ServiceInstance.ts
95
+ var ServiceInstance = class {
96
+ constructor(definition) {
97
+ this.definition = definition;
98
+ this.id = definition.id;
99
+ this.name = definition.name;
100
+ this.version = definition.version;
101
+ this.lifecycle = new LifecycleManager();
102
+ this.eventBus = new ServiceEventBus();
103
+ if (definition.state) {
104
+ this.stateStore = new ServiceStateStore(definition.state.initial);
105
+ }
106
+ }
107
+ definition;
108
+ id;
109
+ name;
110
+ version;
111
+ stateStore;
112
+ eventBus;
113
+ lifecycle;
114
+ initialized = false;
115
+ disposed = false;
116
+ getDefinition() {
117
+ return this.definition;
118
+ }
119
+ getStatus() {
120
+ return this.lifecycle.getStatus();
121
+ }
122
+ async start() {
123
+ if (this.disposed) throw new Error("[Service:" + this.name + "] Cannot start a disposed service.");
124
+ const current = this.lifecycle.getStatus();
125
+ if (current === "running") return;
126
+ if (current === "initializing" || current === "starting" || current === "stopping") {
127
+ throw new Error("[Service:" + this.name + "] Cannot start while status is '" + current + "'.");
128
+ }
129
+ if (!this.initialized) {
130
+ this.lifecycle.transitionTo("initializing");
131
+ try {
132
+ await this.definition.lifecycle?.onInit?.();
133
+ this.initialized = true;
134
+ this.lifecycle.transitionTo("ready");
135
+ } catch (error) {
136
+ this.lifecycle.transitionTo("uninitialized");
137
+ throw error;
138
+ }
139
+ }
140
+ this.lifecycle.transitionTo("starting");
141
+ try {
142
+ await this.definition.lifecycle?.onStart?.();
143
+ this.lifecycle.transitionTo("running");
144
+ } catch (error) {
145
+ this.lifecycle.transitionTo("ready");
146
+ throw error;
147
+ }
148
+ }
149
+ async stop() {
150
+ const current = this.lifecycle.getStatus();
151
+ if (current === "stopped") return;
152
+ if (current !== "running") {
153
+ throw new Error("[Service:" + this.name + "] Cannot stop while status is '" + current + "'.");
154
+ }
155
+ this.lifecycle.transitionTo("stopping");
156
+ try {
157
+ await this.definition.lifecycle?.onStop?.();
158
+ this.lifecycle.transitionTo("stopped");
159
+ } catch (error) {
160
+ this.lifecycle.transitionTo("running");
161
+ throw error;
162
+ }
163
+ }
164
+ async dispose() {
165
+ if (this.disposed) return;
166
+ if (this.lifecycle.getStatus() === "running") await this.stop();
167
+ await this.definition.lifecycle?.onDispose?.();
168
+ this.disposed = true;
169
+ }
170
+ async call(op, input, ctx = {}) {
171
+ this.lifecycle.assertRunning(this.name);
172
+ const operation = this.definition.operations[op];
173
+ if (!operation) {
174
+ throw new Error("[Service:" + this.name + "] Operation '" + op + "' not found.");
175
+ }
176
+ return await operation.handler(input, ctx);
177
+ }
178
+ getState() {
179
+ return this.stateStore?.getState() ?? Object.freeze({});
180
+ }
181
+ setState(mutation) {
182
+ if (!this.stateStore) {
183
+ this.stateStore = new ServiceStateStore({ ...mutation });
184
+ return;
185
+ }
186
+ this.stateStore.setState(mutation);
187
+ }
188
+ on(event, handler) {
189
+ return this.eventBus.on(event, handler);
190
+ }
191
+ emit(event, payload) {
192
+ this.eventBus.emit(event, payload);
193
+ }
194
+ };
195
+
196
+ // src/services/ServiceProxy.ts
197
+ var ServiceProxy = class {
198
+ constructor(definition, adapter, endpoint) {
199
+ this.definition = definition;
200
+ this.adapter = adapter;
201
+ this.endpoint = endpoint;
202
+ if (!definition) {
203
+ throw new Error("[ServiceProxy] Missing service definition.");
204
+ }
205
+ if (!adapter || typeof adapter.send !== "function") {
206
+ throw new Error("[ServiceProxy:" + (definition.name || "unknown") + "] Missing or invalid protocol adapter.");
207
+ }
208
+ if (!endpoint || typeof endpoint.address !== "string" || endpoint.address.length === 0) {
209
+ throw new Error("[ServiceProxy:" + (definition.name || "unknown") + "] Missing or invalid endpoint descriptor.");
210
+ }
211
+ this.id = definition.id;
212
+ this.name = definition.name;
213
+ this.version = definition.version;
214
+ this.stateCache = { ...definition.state?.initial ?? {} };
215
+ }
216
+ definition;
217
+ adapter;
218
+ endpoint;
219
+ id;
220
+ name;
221
+ version;
222
+ stateCache;
223
+ eventHandlers = /* @__PURE__ */ new Map();
224
+ lifecycle = new LifecycleManager();
225
+ disposed = false;
226
+ getDefinition() {
227
+ return this.definition;
228
+ }
229
+ getStatus() {
230
+ return this.lifecycle.getStatus();
231
+ }
232
+ async start() {
233
+ if (this.disposed) {
234
+ throw new Error("[ServiceProxy:" + this.name + "] Cannot start a disposed service proxy.");
235
+ }
236
+ const status = this.lifecycle.getStatus();
237
+ if (status === "running") return;
238
+ if (status === "stopping" || status === "starting" || status === "initializing") {
239
+ throw new Error("[ServiceProxy:" + this.name + "] Cannot start while status is '" + status + "'.");
240
+ }
241
+ if (status === "uninitialized") {
242
+ this.lifecycle.transitionTo("initializing");
243
+ this.lifecycle.transitionTo("ready");
244
+ }
245
+ this.lifecycle.transitionTo("starting");
246
+ this.lifecycle.transitionTo("running");
247
+ }
248
+ async stop() {
249
+ const status = this.lifecycle.getStatus();
250
+ if (status === "stopped") return;
251
+ if (status !== "running") {
252
+ throw new Error("[ServiceProxy:" + this.name + "] Cannot stop while status is '" + status + "'.");
253
+ }
254
+ this.lifecycle.transitionTo("stopping");
255
+ this.lifecycle.transitionTo("stopped");
256
+ }
257
+ async dispose() {
258
+ if (this.disposed) return;
259
+ if (this.lifecycle.getStatus() === "running") await this.stop();
260
+ this.disposed = true;
261
+ }
262
+ async call(op, input, ctx = {}) {
263
+ if (!this.definition.operations[op]) {
264
+ throw new Error("[ServiceProxy:" + this.name + "] Operation '" + op + "' not found.");
265
+ }
266
+ if (this.lifecycle.getStatus() !== "running") {
267
+ await this.start();
268
+ }
269
+ if (!this.adapter.send) {
270
+ throw new Error("[ServiceProxy:" + this.name + "] Adapter does not support send().");
271
+ }
272
+ const envelope = {
273
+ id: "req-" + Date.now() + "-" + Math.random().toString(36).slice(2, 7),
274
+ type: "request",
275
+ operation: op,
276
+ payload: input,
277
+ timestamp: Date.now()
278
+ };
279
+ const response = await this.adapter.send(this.endpoint, envelope);
280
+ if (response.error) {
281
+ throw new Error("[ServiceProxy:" + this.name + "] Remote error: " + response.error);
282
+ }
283
+ return response.payload;
284
+ }
285
+ getState() {
286
+ return Object.freeze({ ...this.stateCache });
287
+ }
288
+ setState(mutation) {
289
+ this.stateCache = { ...this.stateCache, ...mutation };
290
+ }
291
+ on(event, handler) {
292
+ if (!this.eventHandlers.has(event)) this.eventHandlers.set(event, /* @__PURE__ */ new Set());
293
+ const handlers = this.eventHandlers.get(event);
294
+ handlers.add(handler);
295
+ return () => handlers.delete(handler);
296
+ }
297
+ emit(event, payload) {
298
+ const handlers = this.eventHandlers.get(event);
299
+ if (!handlers) return;
300
+ for (const handler of Array.from(handlers)) {
301
+ try {
302
+ handler(payload);
303
+ } catch (error) {
304
+ console.error("[ServiceProxy:" + this.name + "] Event handler error for '" + event + "':", error);
305
+ }
306
+ }
307
+ }
308
+ };
309
+
310
+ // src/services/ServiceGenerators.ts
311
+ function assertRecord(value, field) {
312
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
313
+ throw new Error("[KrnlTS] Invalid service definition: '" + field + "' must be an object.");
314
+ }
315
+ }
316
+ function assertNonEmptyString(value, field) {
317
+ if (typeof value !== "string" || value.trim().length === 0) {
318
+ throw new Error("[KrnlTS] Invalid service definition: '" + field + "' must be a non-empty string.");
319
+ }
320
+ }
321
+ function validateServiceDefinition(definition) {
322
+ if (!definition || typeof definition !== "object") {
323
+ throw new Error("[KrnlTS] Invalid service definition: expected an object.");
324
+ }
325
+ assertNonEmptyString(definition.id, "id");
326
+ assertNonEmptyString(definition.name, "name");
327
+ assertNonEmptyString(definition.version, "version");
328
+ if (!definition.operations || typeof definition.operations !== "object") {
329
+ throw new Error("[Service:" + definition.name + "] Invalid operations: expected an object.");
330
+ }
331
+ for (const [key, operation] of Object.entries(definition.operations)) {
332
+ if (!operation || typeof operation !== "object") {
333
+ throw new Error("[Service:" + definition.name + "] Invalid operation '" + key + "'.");
334
+ }
335
+ assertNonEmptyString(operation.id, "operations." + key + ".id");
336
+ assertNonEmptyString(operation.name, "operations." + key + ".name");
337
+ if (operation.inputSchema !== void 0) assertRecord(operation.inputSchema, "operations." + key + ".inputSchema");
338
+ if (operation.outputSchema !== void 0) assertRecord(operation.outputSchema, "operations." + key + ".outputSchema");
339
+ if (typeof operation.handler !== "function") {
340
+ throw new Error("[Service:" + definition.name + "] Operation '" + key + "' must define a handler.");
341
+ }
342
+ }
343
+ for (const [key, event] of Object.entries(definition.events ?? {})) {
344
+ if (!event || typeof event !== "object") {
345
+ throw new Error("[Service:" + definition.name + "] Invalid event '" + key + "'.");
346
+ }
347
+ assertNonEmptyString(event.name, "events." + key + ".name");
348
+ }
349
+ for (const [key, schema] of Object.entries(definition.inputs ?? {})) assertRecord(schema, "inputs." + key);
350
+ for (const [key, schema] of Object.entries(definition.outputs ?? {})) assertRecord(schema, "outputs." + key);
351
+ if (definition.state?.schema !== void 0) assertRecord(definition.state.schema, "state.schema");
352
+ for (const capability of definition.capabilities ?? []) {
353
+ assertNonEmptyString(capability.id, "capability.id");
354
+ assertNonEmptyString(capability.name, "capability.name");
355
+ if (!Array.isArray(capability.protocols)) {
356
+ throw new Error("[Service:" + definition.name + "] Capability '" + capability.name + "' protocols must be an array.");
357
+ }
358
+ }
359
+ for (const dependency of definition.dependencies ?? []) {
360
+ assertNonEmptyString(dependency.serviceId, "dependency.serviceId");
361
+ }
362
+ return definition;
363
+ }
364
+ function createServiceDefinition(definition) {
365
+ return validateServiceDefinition(definition);
366
+ }
367
+ function createService(definition) {
368
+ return new ServiceInstance(validateServiceDefinition(definition));
369
+ }
370
+ function createServiceProxy(definition, adapter, endpoint) {
371
+ validateServiceDefinition(definition);
372
+ if (!adapter || typeof adapter.send !== "function") {
373
+ throw new Error("[ServiceProxy:" + definition.name + "] Adapter must implement send().");
374
+ }
375
+ if (!endpoint || typeof endpoint.address !== "string" || endpoint.address.length === 0) {
376
+ throw new Error("[ServiceProxy:" + definition.name + "] Endpoint must have an address.");
377
+ }
378
+ return new ServiceProxy(definition, adapter, endpoint);
379
+ }
380
+
381
+ // ../../node_modules/.pnpm/p-queue@10.0.0/node_modules/p-queue/dist/lower-bound.js
382
+ function lowerBound(array, value, comparator) {
383
+ let first = 0;
384
+ let count = array.length;
385
+ while (count > 0) {
386
+ const step = Math.trunc(count / 2);
387
+ let it = first + step;
388
+ if (comparator(array[it], value) <= 0) {
389
+ first = ++it;
390
+ count -= step + 1;
391
+ } else {
392
+ count = step;
393
+ }
394
+ }
395
+ return first;
396
+ }
397
+
398
+ // ../../node_modules/.pnpm/p-queue@10.0.0/node_modules/p-queue/dist/priority-queue.js
399
+ var compactionThreshold = 100;
400
+ var PriorityQueue = class {
401
+ // The slots before `#head` are `undefined`.
402
+ #queue = [];
403
+ // The queue is stored as a sorted array, but dequeued slots are left before `#head` until compaction. Only items from `#head` onward are live, which keeps repeated dequeues amortized O(1).
404
+ #head = 0;
405
+ #compact() {
406
+ if (this.#head === 0) {
407
+ return;
408
+ }
409
+ this.#queue.splice(0, this.#head);
410
+ this.#head = 0;
411
+ }
412
+ // Only the live items, because a dequeued item with the same id or function is no longer part of the queue.
413
+ #findIndex(isMatch) {
414
+ for (let index = this.#head; index < this.#queue.length; index++) {
415
+ if (isMatch(this.#queue[index])) {
416
+ return index;
417
+ }
418
+ }
419
+ return -1;
420
+ }
421
+ // Not `dequeue()`, which a subclass can override, because `remove()` also uses it.
422
+ #removeFirst() {
423
+ const item = this.#queue[this.#head];
424
+ this.#queue[this.#head] = void 0;
425
+ this.#head++;
426
+ if (this.#head === this.#queue.length) {
427
+ this.#queue.length = 0;
428
+ this.#head = 0;
429
+ } else if (this.#head > compactionThreshold && this.#head > this.#queue.length / 2) {
430
+ this.#compact();
431
+ }
432
+ return item.run;
433
+ }
434
+ enqueue(run, options) {
435
+ const { priority = 0, id } = options ?? {};
436
+ const { size } = this;
437
+ const element = {
438
+ priority,
439
+ id,
440
+ run
441
+ };
442
+ if (size === 0) {
443
+ this.#queue.length = 0;
444
+ this.#head = 0;
445
+ this.#queue.push(element);
446
+ return;
447
+ }
448
+ if (this.#queue.at(-1).priority >= priority) {
449
+ this.#queue.push(element);
450
+ return;
451
+ }
452
+ this.#compact();
453
+ const index = lowerBound(this.#queue, element, (a, b) => a.priority === b.priority ? 0 : b.priority - a.priority);
454
+ this.#queue.splice(index, 0, element);
455
+ }
456
+ setPriority(id, priority) {
457
+ const index = this.#findIndex((element) => element.id === id);
458
+ if (index === -1) {
459
+ throw new ReferenceError(`No promise function with the id "${id}" exists in the queue.`);
460
+ }
461
+ if (this.#queue[index].priority === priority) {
462
+ return;
463
+ }
464
+ const [item] = this.#queue.splice(index, 1);
465
+ this.enqueue(item.run, { priority, id });
466
+ }
467
+ remove(idOrRun) {
468
+ const index = this.#findIndex((element) => (typeof idOrRun === "string" ? element.id : element.run) === idOrRun);
469
+ if (index === this.#head) {
470
+ this.#removeFirst();
471
+ } else if (index !== -1) {
472
+ this.#queue.splice(index, 1);
473
+ }
474
+ }
475
+ dequeue() {
476
+ return this.#head === this.#queue.length ? void 0 : this.#removeFirst();
477
+ }
478
+ filter(options) {
479
+ const result = [];
480
+ for (let index = this.#head; index < this.#queue.length; index++) {
481
+ const element = this.#queue[index];
482
+ if (element.priority === options.priority) {
483
+ result.push(element.run);
484
+ }
485
+ }
486
+ return result;
487
+ }
488
+ get size() {
489
+ return this.#queue.length - this.#head;
490
+ }
491
+ };
492
+
493
+ // ../../node_modules/.pnpm/p-queue@10.0.0/node_modules/p-queue/dist/index.js
494
+ var maximumTimerDelay = 2147483647;
495
+ var asyncHooks = globalThis.process?.getBuiltinModule?.("node:async_hooks");
496
+ var bindAsyncContext = (function_) => {
497
+ if (asyncHooks === void 0) {
498
+ return function_;
499
+ }
500
+ const asyncResource = new asyncHooks.AsyncResource("PQueueTask");
501
+ return () => asyncResource.runInAsyncScope(function_);
502
+ };
503
+ var validateTimeout = (timeout) => {
504
+ if (timeout !== void 0 && !(Number.isFinite(timeout) && timeout > 0 && timeout <= maximumTimerDelay)) {
505
+ throw new TypeError(`Expected \`timeout\` to be a positive finite number up to ${maximumTimerDelay}, got \`${timeout}\` (${typeof timeout})`);
506
+ }
507
+ };
508
+ var validateLimit = (name, value) => {
509
+ if (!(typeof value === "number" && value >= 1 && (value === Infinity || Number.isInteger(value)))) {
510
+ throw new TypeError(`Expected \`${name}\` to be an integer from 1 and up or \`Infinity\`, got \`${String(value)}\` (${typeof value})`);
511
+ }
512
+ };
513
+ var validateRateLimit = (interval, intervalCap, isStrict) => {
514
+ validateLimit("intervalCap", intervalCap);
515
+ if (!(Number.isFinite(interval) && interval >= 0)) {
516
+ throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${String(interval)}\` (${typeof interval})`);
517
+ }
518
+ if (intervalCap !== Infinity && interval > maximumTimerDelay) {
519
+ throw new TypeError(`Expected \`interval\` to be at most ${maximumTimerDelay} with an \`intervalCap\`, got \`${interval}\``);
520
+ }
521
+ if (isStrict && interval === 0) {
522
+ throw new TypeError("The `strict` option requires a non-zero `interval`");
523
+ }
524
+ if (isStrict && intervalCap === Infinity) {
525
+ throw new TypeError("The `strict` option requires a finite `intervalCap`");
526
+ }
527
+ };
528
+ var PQueue = class extends EventTarget {
529
+ #carryoverIntervalCount;
530
+ #isIntervalIgnored;
531
+ #intervalCount = 0;
532
+ #intervalCap;
533
+ #rateLimitedInInterval = false;
534
+ #rateLimitFlushScheduled = false;
535
+ #interval;
536
+ /*
537
+ Timestamp when the current interval window ends. Kept accurate at every window transition: `#initializeIntervalIfNeeded` sets it when a window starts and `#onInterval` advances it as the recurring timer rolls into each new window. This is the source of truth for whether a task added after the queue goes idle belongs to a fresh window, so it must not go stale.
538
+ */
539
+ #intervalEnd = 0;
540
+ // Recurring timer that drives windows while the queue is actively processing. Absent (`undefined`) once the queue goes idle.
541
+ #intervalId;
542
+ // One-shot timer used while idle to resume at the next window boundary, since `#intervalId` is cleared when idle.
543
+ #timeoutId;
544
+ #strict;
545
+ // Circular buffer implementation for better performance
546
+ #strictTicks = [];
547
+ #strictTicksStartIndex = 0;
548
+ #queue;
549
+ #queueClass;
550
+ #pending = 0;
551
+ // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194
552
+ #concurrency;
553
+ #isPaused;
554
+ // Use to assign a unique identifier to a promise function, if not explicitly specified
555
+ #idAssigner = 1n;
556
+ // Track currently running tasks for debugging
557
+ #runningTasks = /* @__PURE__ */ new Set();
558
+ // The `abort` listener of each signal, with the callbacks of the tasks that use the signal.
559
+ #abortListeners = /* @__PURE__ */ new Map();
560
+ // The waiting tasks, so that `.clear()` can reject their promises.
561
+ #waitingTasks = /* @__PURE__ */ new Set();
562
+ #timeout;
563
+ constructor(options) {
564
+ super();
565
+ globalThis.process?.getBuiltinModule?.("node:events")?.setMaxListeners(Infinity, this);
566
+ const { carryoverIntervalCount = false, intervalCap = Infinity, interval = 0, concurrency = Infinity, autoStart = true, queueClass = PriorityQueue, strict = false, timeout } = options ?? {};
567
+ validateRateLimit(interval, intervalCap, strict);
568
+ this.#carryoverIntervalCount = carryoverIntervalCount;
569
+ this.#isIntervalIgnored = intervalCap === Infinity || interval === 0;
570
+ this.#intervalCap = intervalCap;
571
+ this.#interval = interval;
572
+ this.#strict = strict;
573
+ this.#queueClass = queueClass;
574
+ this.#queue = new this.#queueClass();
575
+ this.concurrency = concurrency;
576
+ this.timeout = timeout;
577
+ this.#isPaused = !autoStart;
578
+ this.#setupRateLimitTracking();
579
+ }
580
+ // Calls `callback` when `signal` aborts, and returns a function that stops it. The tasks that share a signal share one listener on it, because Node.js searches all the listeners of a signal to add or remove one, so a listener for each task takes O(n²) time with many tasks.
581
+ #onAbort(signal, callback) {
582
+ let listener = this.#abortListeners.get(signal);
583
+ if (!listener) {
584
+ const callbacks = /* @__PURE__ */ new Set();
585
+ const dispatch = () => {
586
+ this.#abortListeners.delete(signal);
587
+ for (const abortCallback of callbacks) {
588
+ abortCallback();
589
+ }
590
+ };
591
+ listener = { callbacks, dispatch };
592
+ this.#abortListeners.set(signal, listener);
593
+ signal.addEventListener("abort", dispatch, { once: true });
594
+ }
595
+ const currentListener = listener;
596
+ currentListener.callbacks.add(callback);
597
+ return () => {
598
+ currentListener.callbacks.delete(callback);
599
+ if (currentListener.callbacks.size > 0 || this.#abortListeners.get(signal) !== currentListener) {
600
+ return;
601
+ }
602
+ this.#abortListeners.delete(signal);
603
+ signal.removeEventListener("abort", currentListener.dispatch);
604
+ };
605
+ }
606
+ #emit(event, detail) {
607
+ this.dispatchEvent(new CustomEvent(event, { detail }));
608
+ }
609
+ async #onEvent(events, shouldHandle) {
610
+ const eventList = Array.isArray(events) ? events : [events];
611
+ return new Promise((resolve) => {
612
+ const controller = new AbortController();
613
+ const listener = () => {
614
+ if (shouldHandle && !shouldHandle()) {
615
+ return;
616
+ }
617
+ controller.abort();
618
+ resolve();
619
+ };
620
+ for (const event of eventList) {
621
+ this.addEventListener(event, listener, { signal: controller.signal });
622
+ }
623
+ });
624
+ }
625
+ // From the current state. `#rateLimitedInInterval` is what the events last reported, and it updates in a microtask.
626
+ get #isRateLimitedNow() {
627
+ if (this.#isIntervalIgnored || this.#queue.size === 0) {
628
+ return false;
629
+ }
630
+ const now = Date.now();
631
+ if (this.#strict) {
632
+ this.#cleanupStrictTicks(now);
633
+ return this.#getActiveTicksCount() >= this.#intervalCap;
634
+ }
635
+ const isWindowOver = this.#intervalId === void 0 && this.#intervalEnd <= now;
636
+ const count = isWindowOver ? this.#intervalCountAtWindowStart : this.#intervalCount;
637
+ return count >= this.#intervalCap;
638
+ }
639
+ // The tasks that still run count against the new window with `carryoverIntervalCount`.
640
+ get #intervalCountAtWindowStart() {
641
+ return this.#carryoverIntervalCount ? this.#pending : 0;
642
+ }
643
+ #updateRateLimitState() {
644
+ const shouldBeRateLimited = this.#isRateLimitedNow;
645
+ if (shouldBeRateLimited === this.#rateLimitedInInterval) {
646
+ return;
647
+ }
648
+ this.#rateLimitedInInterval = shouldBeRateLimited;
649
+ this.#emit(shouldBeRateLimited ? "rateLimit" : "rateLimitCleared");
650
+ }
651
+ #rollbackIntervalConsumption() {
652
+ if (this.#isIntervalIgnored) {
653
+ return;
654
+ }
655
+ this.#rollbackIntervalSlot();
656
+ this.#scheduleRateLimitUpdate();
657
+ }
658
+ #scheduleRateLimitUpdate() {
659
+ if (this.#isIntervalIgnored || this.#rateLimitFlushScheduled) {
660
+ return;
661
+ }
662
+ this.#rateLimitFlushScheduled = true;
663
+ queueMicrotask(() => {
664
+ this.#rateLimitFlushScheduled = false;
665
+ this.#updateRateLimitState();
666
+ });
667
+ }
668
+ #setupRateLimitTracking() {
669
+ if (this.#isIntervalIgnored) {
670
+ return;
671
+ }
672
+ this.addEventListener("add", () => {
673
+ if (this.#queue.size > 0) {
674
+ this.#scheduleRateLimitUpdate();
675
+ }
676
+ });
677
+ this.addEventListener("next", () => {
678
+ this.#scheduleRateLimitUpdate();
679
+ });
680
+ }
681
+ #cleanupStrictTicks(now) {
682
+ while (this.#strictTicksStartIndex < this.#strictTicks.length) {
683
+ const oldestTick = this.#strictTicks[this.#strictTicksStartIndex];
684
+ if (oldestTick !== void 0 && now - oldestTick >= this.#interval) {
685
+ this.#strictTicksStartIndex++;
686
+ } else {
687
+ break;
688
+ }
689
+ }
690
+ const shouldCompact = this.#strictTicksStartIndex > 100 && this.#strictTicksStartIndex > this.#strictTicks.length / 2 || this.#strictTicksStartIndex === this.#strictTicks.length;
691
+ if (!shouldCompact) {
692
+ return;
693
+ }
694
+ this.#strictTicks = this.#strictTicks.slice(this.#strictTicksStartIndex);
695
+ this.#strictTicksStartIndex = 0;
696
+ }
697
+ // Helper methods for interval consumption
698
+ #consumeIntervalSlot(now) {
699
+ if (this.#strict) {
700
+ this.#strictTicks.push(now);
701
+ } else {
702
+ this.#intervalCount++;
703
+ }
704
+ }
705
+ #rollbackIntervalSlot() {
706
+ if (this.#strict) {
707
+ if (this.#strictTicks.length > this.#strictTicksStartIndex) {
708
+ this.#strictTicks.pop();
709
+ }
710
+ return;
711
+ }
712
+ if (this.#intervalCount > 0) {
713
+ this.#intervalCount--;
714
+ }
715
+ }
716
+ #getActiveTicksCount() {
717
+ return this.#strictTicks.length - this.#strictTicksStartIndex;
718
+ }
719
+ get #doesIntervalAllowAnother() {
720
+ if (this.#isIntervalIgnored) {
721
+ return true;
722
+ }
723
+ const count = this.#strict ? this.#getActiveTicksCount() : this.#intervalCount;
724
+ return count < this.#intervalCap;
725
+ }
726
+ get #doesConcurrentAllowAnother() {
727
+ return this.#pending < this.#concurrency;
728
+ }
729
+ #next() {
730
+ this.#pending--;
731
+ if (this.#pending === 0) {
732
+ this.#emit("pendingZero");
733
+ }
734
+ this.#processQueue();
735
+ this.#emit("next");
736
+ }
737
+ #onResumeInterval() {
738
+ this.#timeoutId = void 0;
739
+ this.#onInterval();
740
+ if (!this.#isPaused) {
741
+ this.#initializeIntervalIfNeeded();
742
+ }
743
+ }
744
+ #isIntervalPausedAt(now) {
745
+ if (this.#strict) {
746
+ this.#cleanupStrictTicks(now);
747
+ const activeTicksCount = this.#getActiveTicksCount();
748
+ if (activeTicksCount >= this.#intervalCap) {
749
+ const oldestTick = this.#strictTicks[this.#strictTicksStartIndex];
750
+ const delay = this.#interval - (now - oldestTick);
751
+ this.#createIntervalTimeout(delay);
752
+ return true;
753
+ }
754
+ return false;
755
+ }
756
+ if (this.#intervalId === void 0) {
757
+ const delay = this.#intervalEnd - now;
758
+ if (delay <= 0) {
759
+ this.#intervalCount = this.#intervalCountAtWindowStart;
760
+ } else {
761
+ this.#createIntervalTimeout(delay);
762
+ return true;
763
+ }
764
+ }
765
+ return false;
766
+ }
767
+ #createIntervalTimeout(delay) {
768
+ if (this.#timeoutId !== void 0) {
769
+ return;
770
+ }
771
+ this.#timeoutId = setTimeout(() => {
772
+ this.#onResumeInterval();
773
+ }, delay);
774
+ }
775
+ #clearIntervalTimer() {
776
+ if (this.#intervalId === void 0) {
777
+ return;
778
+ }
779
+ clearInterval(this.#intervalId);
780
+ this.#intervalId = void 0;
781
+ }
782
+ #clearTimeoutTimer() {
783
+ if (this.#timeoutId === void 0) {
784
+ return;
785
+ }
786
+ clearTimeout(this.#timeoutId);
787
+ this.#timeoutId = void 0;
788
+ }
789
+ // Emits `empty`, and `idle` when no tasks run. For when the queue has no waiting tasks.
790
+ #emitEmptyAndIdle() {
791
+ this.#clearIntervalTimer();
792
+ this.#emit("empty");
793
+ if (this.#pending > 0 || this.#queue.size > 0) {
794
+ return;
795
+ }
796
+ this.#clearTimeoutTimer();
797
+ if (this.#strict) {
798
+ this.#cleanupStrictTicks(Date.now());
799
+ }
800
+ this.#emit("idle");
801
+ }
802
+ #tryToStartAnother() {
803
+ let isStarted;
804
+ do {
805
+ isStarted = this.#startNextTask();
806
+ } while (isStarted === void 0);
807
+ return isStarted;
808
+ }
809
+ // Returns `undefined` when it skipped a task whose signal aborted while it waited.
810
+ #startNextTask() {
811
+ if (this.#queue.size === 0) {
812
+ this.#emitEmptyAndIdle();
813
+ return false;
814
+ }
815
+ if (this.#isPaused) {
816
+ if (!this.#doesIntervalAllowAnother) {
817
+ this.#isIntervalPausedAt(Date.now());
818
+ }
819
+ return false;
820
+ }
821
+ const now = Date.now();
822
+ const canInitializeInterval = !this.#isIntervalPausedAt(now);
823
+ if (this.#doesIntervalAllowAnother && this.#doesConcurrentAllowAnother) {
824
+ const job = this.#queue.dequeue();
825
+ if (!this.#isIntervalIgnored) {
826
+ this.#consumeIntervalSlot(now);
827
+ this.#scheduleRateLimitUpdate();
828
+ }
829
+ if (canInitializeInterval) {
830
+ this.#initializeIntervalIfNeeded();
831
+ }
832
+ const pendingBefore = this.#pending;
833
+ job();
834
+ if (this.#pending === pendingBefore) {
835
+ this.#emit("next");
836
+ return;
837
+ }
838
+ this.#emit("active");
839
+ return true;
840
+ }
841
+ return false;
842
+ }
843
+ #initializeIntervalIfNeeded() {
844
+ if (this.#isIntervalIgnored || this.#intervalId !== void 0 || this.#strict) {
845
+ return;
846
+ }
847
+ this.#clearTimeoutTimer();
848
+ this.#intervalId = setInterval(() => {
849
+ this.#onInterval();
850
+ }, this.#interval);
851
+ this.#intervalEnd = Date.now() + this.#interval;
852
+ }
853
+ #onInterval() {
854
+ if (!this.#strict) {
855
+ if (this.#intervalId !== void 0) {
856
+ if (this.#intervalCount === 0 && this.#pending === 0) {
857
+ this.#clearIntervalTimer();
858
+ } else {
859
+ this.#intervalEnd = Date.now() + this.#interval;
860
+ }
861
+ }
862
+ this.#intervalCount = this.#intervalCountAtWindowStart;
863
+ }
864
+ this.#processQueue();
865
+ this.#scheduleRateLimitUpdate();
866
+ }
867
+ /**
868
+ Executes all queued functions until it reaches the limit.
869
+ */
870
+ #processQueue() {
871
+ while (this.#tryToStartAnother()) {
872
+ }
873
+ }
874
+ // On an empty queue, `#processQueue()` emits `empty` and `idle`. An `idle` listener that sets `concurrency` or calls `.start()` would then recurse without end.
875
+ #processWaitingTasks() {
876
+ if (this.#queue.size > 0) {
877
+ this.#processQueue();
878
+ }
879
+ }
880
+ async #add(function_, options, waitingTask) {
881
+ const id = options.id ?? (this.#idAssigner++).toString();
882
+ options = {
883
+ timeout: this.#timeout,
884
+ ...options,
885
+ id
886
+ };
887
+ validateTimeout(options.timeout);
888
+ if (options.priority !== void 0 && (typeof options.priority !== "number" || Number.isNaN(options.priority))) {
889
+ throw new TypeError(`Expected \`priority\` to be a number, got \`${String(options.priority)}\` (${typeof options.priority})`);
890
+ }
891
+ waitingTask.id = id;
892
+ waitingTask.priority = options.priority ?? 0;
893
+ return new Promise((resolve, reject) => {
894
+ if (options.signal?.aborted) {
895
+ reject(options.signal.reason);
896
+ return;
897
+ }
898
+ const run = bindAsyncContext(async () => {
899
+ waitingTask.stopListeningForAbort?.();
900
+ this.#waitingTasks.delete(waitingTask);
901
+ if (options.signal?.aborted) {
902
+ this.#rollbackIntervalConsumption();
903
+ reject(options.signal.reason);
904
+ return;
905
+ }
906
+ this.#pending++;
907
+ const runningTask = {
908
+ id,
909
+ priority: waitingTask.priority,
910
+ startTime: Date.now(),
911
+ timeout: options.timeout
912
+ };
913
+ this.#runningTasks.add(runningTask);
914
+ let { signal } = options;
915
+ let stopListeningForAbort;
916
+ let stopForwardingAbort;
917
+ let timeoutId;
918
+ try {
919
+ if (options.timeout !== void 0) {
920
+ const { signal: userSignal, timeout } = options;
921
+ const taskController = new AbortController();
922
+ timeoutId = setTimeout(() => {
923
+ taskController.abort(new TimeoutError(`Task timed out after ${timeout}ms (queue has ${this.#pending} running, ${this.#queue.size} waiting)`));
924
+ }, timeout);
925
+ if (userSignal) {
926
+ stopForwardingAbort = this.#onAbort(userSignal, () => {
927
+ taskController.abort(userSignal.reason);
928
+ });
929
+ }
930
+ signal = taskController.signal;
931
+ }
932
+ let operation;
933
+ if (signal) {
934
+ const abortSignal = signal;
935
+ const abortPromise = new Promise((_resolve, rejectWithReason) => {
936
+ stopListeningForAbort = this.#onAbort(abortSignal, () => {
937
+ rejectWithReason(abortSignal.reason);
938
+ });
939
+ });
940
+ operation = Promise.race([abortPromise, (async () => function_({ signal }))()]);
941
+ } else {
942
+ try {
943
+ operation = function_({ signal });
944
+ } catch (error) {
945
+ operation = Promise.reject(error);
946
+ }
947
+ }
948
+ const result = await operation;
949
+ resolve(result);
950
+ this.#emit("completed", result);
951
+ } catch (error) {
952
+ reject(error);
953
+ this.#emit("error", error);
954
+ } finally {
955
+ clearTimeout(timeoutId);
956
+ stopListeningForAbort?.();
957
+ stopForwardingAbort?.();
958
+ this.#runningTasks.delete(runningTask);
959
+ queueMicrotask(() => {
960
+ this.#next();
961
+ });
962
+ }
963
+ });
964
+ const hasWaitingTasks = this.#queue.size > 0;
965
+ this.#queue.enqueue(run, options);
966
+ waitingTask.reject = reject;
967
+ this.#waitingTasks.add(waitingTask);
968
+ if (options.signal) {
969
+ const { signal } = options;
970
+ waitingTask.stopListeningForAbort = this.#onAbort(signal, () => {
971
+ this.#waitingTasks.delete(waitingTask);
972
+ if (this.#queue instanceof PriorityQueue) {
973
+ this.#queue.remove(run);
974
+ } else {
975
+ this.#queue.remove(id);
976
+ }
977
+ reject(signal.reason);
978
+ this.#processQueue();
979
+ this.#emit("next");
980
+ });
981
+ }
982
+ this.#emit("add");
983
+ if (hasWaitingTasks) {
984
+ this.#processQueue();
985
+ } else {
986
+ this.#tryToStartAnother();
987
+ }
988
+ });
989
+ }
990
+ /**
991
+ Get or set the default timeout. A change applies to tasks added after it.
992
+
993
+ @example
994
+ ```
995
+ const queue = new PQueue({timeout: 5000});
996
+
997
+ queue.timeout = 10000;
998
+ ```
999
+ */
1000
+ get timeout() {
1001
+ return this.#timeout;
1002
+ }
1003
+ // Validated here, not only in `.add()`, so that an invalid value throws where it is set, instead of making every later `.add()` reject.
1004
+ set timeout(timeout) {
1005
+ validateTimeout(timeout);
1006
+ this.#timeout = timeout;
1007
+ }
1008
+ get concurrency() {
1009
+ return this.#concurrency;
1010
+ }
1011
+ set concurrency(newConcurrency) {
1012
+ validateLimit("concurrency", newConcurrency);
1013
+ this.#concurrency = newConcurrency;
1014
+ this.#processWaitingTasks();
1015
+ }
1016
+ /**
1017
+ Changes the priority of a waiting task, found by its `id`. Throws a `ReferenceError` if no waiting task has that `id`, for example because it already started. Throws a `TypeError` if `priority` is not a finite number. Tasks only wait when the queue has a `concurrency` limit, is paused, or is rate-limited.
1018
+
1019
+ @example
1020
+ ```
1021
+ // Raise the priority to run a task earlier
1022
+ import PQueue from 'p-queue';
1023
+
1024
+ const queue = new PQueue({concurrency: 1});
1025
+
1026
+ queue.add(async () => '🦄', {priority: 1});
1027
+ queue.add(async () => '🦀', {priority: 0, id: '🦀'});
1028
+ queue.add(async () => '🦄', {priority: 1});
1029
+ queue.add(async () => '🦄', {priority: 1});
1030
+
1031
+ queue.setPriority('🦀', 2);
1032
+ // '🦀' runs second
1033
+ ```
1034
+
1035
+ @example
1036
+ ```
1037
+ // Lower the priority to run a task later
1038
+ import PQueue from 'p-queue';
1039
+
1040
+ const queue = new PQueue({concurrency: 1});
1041
+
1042
+ queue.add(async () => '🦄', {priority: 1});
1043
+ queue.add(async () => '🦀', {priority: 1, id: '🦀'});
1044
+ queue.add(async () => '🦄');
1045
+ queue.add(async () => '🦄', {priority: 0});
1046
+
1047
+ queue.setPriority('🦀', -1);
1048
+ // '🦀' runs last
1049
+ ```
1050
+ */
1051
+ setPriority(id, priority) {
1052
+ if (typeof priority !== "number" || !Number.isFinite(priority)) {
1053
+ throw new TypeError(`Expected \`priority\` to be a finite number, got \`${priority}\` (${typeof priority})`);
1054
+ }
1055
+ for (const waitingTask of this.#waitingTasks) {
1056
+ if (waitingTask.id === id) {
1057
+ this.#queue.setPriority(id, priority);
1058
+ waitingTask.priority = priority;
1059
+ return;
1060
+ }
1061
+ }
1062
+ throw new ReferenceError(`No promise function with the id "${id}" exists in the queue.`);
1063
+ }
1064
+ /**
1065
+ Adds a sync or async task to the queue.
1066
+
1067
+ Returns a promise that settles with the result of `fn` when the task completes, not when it is added. The function gets `{signal}` as its first argument. The signal is set when the task has a `signal` or a `timeout`, and aborts when either one does. Pass it on, for example to `fetch()`, to stop the work. The function runs in the async context of the `.add()` call (in Node.js 22.3 and later, Deno, and Bun), so it sees the [`AsyncLocalStorage`](https://nodejs.org/api/async_context.html#class-asynclocalstorage) values of the caller, also when it starts later.
1068
+
1069
+ If you `await` each `.add()` call before the next, the tasks run one after the other, whatever the `concurrency`.
1070
+
1071
+ Handle rejections of the returned promise. Otherwise, they are unhandled rejections, which can make the process exit.
1072
+ */
1073
+ add(function_, options = {}) {
1074
+ const waitingTask = {};
1075
+ const promise = this.#add(function_, options, waitingTask);
1076
+ waitingTask.promise = promise;
1077
+ if (waitingTask.isCleared) {
1078
+ promise.catch(() => void 0);
1079
+ }
1080
+ return promise;
1081
+ }
1082
+ async addAll(functions, options) {
1083
+ return Promise.all(functions.map(async (function_) => this.add(function_, options)));
1084
+ }
1085
+ /**
1086
+ Starts (or resumes) running queued tasks. Only needed if the queue is paused, with `autoStart: false` or `.pause()`.
1087
+
1088
+ @returns `this` (the instance).
1089
+ */
1090
+ start() {
1091
+ if (!this.#isPaused) {
1092
+ return this;
1093
+ }
1094
+ this.#isPaused = false;
1095
+ this.#processWaitingTasks();
1096
+ return this;
1097
+ }
1098
+ /**
1099
+ Stops starting new tasks. Running tasks continue.
1100
+ */
1101
+ pause() {
1102
+ this.#isPaused = true;
1103
+ }
1104
+ /**
1105
+ Removes all waiting tasks. Running tasks continue.
1106
+
1107
+ The promises returned by `.add()` for the removed tasks reject with an `AbortError`, which is a `DOMException`. The removed tasks do not run, and they do not emit the `error` event.
1108
+
1109
+ If you ignore such a promise, its rejection is not reported as unhandled. This does not apply to a promise made from it, like the one from `queue.add(fn).then(…)` or from `.addAll()`, so handle the rejection of that promise.
1110
+
1111
+ @example
1112
+ ```
1113
+ import PQueue from 'p-queue';
1114
+
1115
+ const queue = new PQueue({concurrency: 1});
1116
+
1117
+ queue.add(() => doWork());
1118
+ const promise = queue.add(() => doWork());
1119
+
1120
+ queue.clear();
1121
+
1122
+ try {
1123
+ await promise;
1124
+ } catch (error) {
1125
+ console.log(error.name);
1126
+ //=> 'AbortError'
1127
+ }
1128
+ ```
1129
+ */
1130
+ clear() {
1131
+ if (this.#queue.size === 0) {
1132
+ return;
1133
+ }
1134
+ this.#queue = new this.#queueClass();
1135
+ const error = new DOMException("The queue was cleared", "AbortError");
1136
+ for (const waitingTask of this.#waitingTasks) {
1137
+ waitingTask.stopListeningForAbort?.();
1138
+ waitingTask.isCleared = true;
1139
+ waitingTask.promise?.catch(() => void 0);
1140
+ waitingTask.reject(error);
1141
+ }
1142
+ this.#waitingTasks.clear();
1143
+ this.#emitEmptyAndIdle();
1144
+ this.#updateRateLimitState();
1145
+ this.#emit("next");
1146
+ }
1147
+ /**
1148
+ Returns a promise that resolves when the queue is empty. Tasks can still be running.
1149
+
1150
+ The promise resolves once. Call `.onEmpty()` again to wait for the next time, or use the `empty` event to get every time.
1151
+ */
1152
+ async onEmpty() {
1153
+ if (this.#queue.size === 0) {
1154
+ return;
1155
+ }
1156
+ await this.#onEvent(["empty", "active"], () => this.#queue.size === 0);
1157
+ }
1158
+ /**
1159
+ Returns a promise that resolves when `queue.size < limit`.
1160
+
1161
+ Await it before you add a task, to keep the queue from growing beyond a size. It counts only waiting tasks, not running tasks.
1162
+ */
1163
+ async onSizeLessThan(limit) {
1164
+ if (this.#queue.size < limit) {
1165
+ return;
1166
+ }
1167
+ await this.#onEvent(["next", "active"], () => this.#queue.size < limit);
1168
+ }
1169
+ /**
1170
+ Returns a promise that resolves when the queue is empty and all tasks have completed: `queue.size === 0 && queue.pending === 0`.
1171
+
1172
+ Unlike `.onEmpty()`, it waits for running tasks to finish.
1173
+
1174
+ The promise resolves once. Call `.onIdle()` again to wait for the next time, or use the `idle` event to get every time.
1175
+ */
1176
+ async onIdle() {
1177
+ if (this.#pending === 0 && this.#queue.size === 0) {
1178
+ return;
1179
+ }
1180
+ await this.#onEvent("idle");
1181
+ }
1182
+ /**
1183
+ Returns a promise that resolves when no tasks are running: `queue.pending === 0`.
1184
+
1185
+ Unlike `.onIdle()`, it ignores queued tasks. Use it to let running tasks finish before you change shared state. A task that timed out, or whose `signal` aborted while it ran, no longer counts, although its function can still run.
1186
+
1187
+ @example
1188
+ ```
1189
+ queue.pause();
1190
+ await queue.onPendingZero();
1191
+ // No tasks are running, but the queue can still have tasks
1192
+ ```
1193
+ */
1194
+ async onPendingZero() {
1195
+ if (this.#pending === 0) {
1196
+ return;
1197
+ }
1198
+ await this.#onEvent("pendingZero");
1199
+ }
1200
+ /**
1201
+ Returns a promise that resolves when the queue becomes rate-limited by `intervalCap`. If the queue is already rate-limited, it resolves immediately.
1202
+
1203
+ Useful for backpressure, when tasks are added faster than they run.
1204
+
1205
+ @example
1206
+ ```
1207
+ const queue = new PQueue({intervalCap: 5, interval: 1000});
1208
+
1209
+ for (let index = 0; index < 10; index++) {
1210
+ queue.add(() => someTask());
1211
+ }
1212
+
1213
+ await queue.onRateLimit();
1214
+ console.log('The queue is rate-limited');
1215
+ ```
1216
+ */
1217
+ async onRateLimit() {
1218
+ this.#updateRateLimitState();
1219
+ if (this.isRateLimited) {
1220
+ return;
1221
+ }
1222
+ await this.#onEvent("rateLimit");
1223
+ }
1224
+ /**
1225
+ Returns a promise that resolves when the queue is no longer rate-limited. If the queue is not rate-limited, it resolves immediately.
1226
+
1227
+ @example
1228
+ ```
1229
+ const queue = new PQueue({intervalCap: 5, interval: 1000});
1230
+
1231
+ for (let index = 0; index < 10; index++) {
1232
+ queue.add(() => someTask());
1233
+ }
1234
+
1235
+ await queue.onRateLimitCleared();
1236
+ console.log('The rate limit is cleared');
1237
+ ```
1238
+ */
1239
+ async onRateLimitCleared() {
1240
+ this.#updateRateLimitState();
1241
+ if (!this.isRateLimited) {
1242
+ return;
1243
+ }
1244
+ await this.#onEvent("rateLimitCleared");
1245
+ }
1246
+ /**
1247
+ Returns a promise that rejects when a task fails: it throws, times out, or its `signal` aborts while it runs. It rejects with the error of the task, or with `null` if the error is `undefined`, like the `error` event.
1248
+
1249
+ Use `Promise.race([queue.onError(), queue.onIdle()])` to stop at the first error, and to resolve normally when the queue becomes idle. Each call adds an `error` listener that stays until a task fails, so to get every error, for example in a loop, use the `error` event instead.
1250
+
1251
+ Important: The promises returned by `.add()` still reject. Handle each of them (for example with `.catch(() => {})`) to prevent unhandled rejections.
1252
+
1253
+ @example
1254
+ ```
1255
+ import PQueue from 'p-queue';
1256
+
1257
+ const queue = new PQueue({concurrency: 2});
1258
+
1259
+ // Do not start the remaining tasks. Pause in an `error` listener, because it runs before the next task starts, and the code after `await` runs later.
1260
+ queue.addEventListener('error', () => {
1261
+ queue.pause();
1262
+ }, {once: true});
1263
+
1264
+ queue.add(() => fetchData(1)).catch(() => {});
1265
+ queue.add(() => fetchData(2)).catch(() => {});
1266
+ queue.add(() => fetchData(3)).catch(() => {});
1267
+
1268
+ try {
1269
+ await Promise.race([
1270
+ queue.onError(),
1271
+ queue.onIdle()
1272
+ ]);
1273
+ } catch (error) {
1274
+ console.error('Queue failed:', error);
1275
+ }
1276
+ ```
1277
+ */
1278
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
1279
+ onError() {
1280
+ return new Promise((_resolve, reject) => {
1281
+ this.addEventListener("error", (event) => {
1282
+ reject(event.detail);
1283
+ }, { once: true });
1284
+ });
1285
+ }
1286
+ /**
1287
+ The number of tasks waiting to run.
1288
+ */
1289
+ get size() {
1290
+ return this.#queue.size;
1291
+ }
1292
+ /**
1293
+ The number of waiting tasks with the given `priority`.
1294
+
1295
+ @example
1296
+ ```
1297
+ import PQueue from 'p-queue';
1298
+
1299
+ const queue = new PQueue();
1300
+
1301
+ // Paused, so the tasks stay queued. Without it they all start synchronously and the queue is empty by the time `sizeBy` reads it.
1302
+ queue.pause();
1303
+
1304
+ queue.add(async () => '🦄', {priority: 1});
1305
+ queue.add(async () => '🦄', {priority: 0});
1306
+ queue.add(async () => '🦄', {priority: 1});
1307
+
1308
+ console.log(queue.sizeBy({priority: 1}));
1309
+ //=> 2
1310
+
1311
+ console.log(queue.sizeBy({priority: 0}));
1312
+ //=> 1
1313
+ ```
1314
+ */
1315
+ sizeBy(options) {
1316
+ return this.#queue.filter(options).length;
1317
+ }
1318
+ /**
1319
+ The number of running tasks.
1320
+ */
1321
+ get pending() {
1322
+ return this.#pending;
1323
+ }
1324
+ /**
1325
+ Whether the queue is paused.
1326
+ */
1327
+ get isPaused() {
1328
+ return this.#isPaused;
1329
+ }
1330
+ /**
1331
+ Whether the queue is rate-limited: the number of tasks started in the current interval, plus the tasks still running from earlier intervals with `carryoverIntervalCount`, has reached `intervalCap`, and tasks are waiting.
1332
+ */
1333
+ get isRateLimited() {
1334
+ return this.#isRateLimitedNow;
1335
+ }
1336
+ /**
1337
+ Whether tasks are waiting because all concurrency slots are in use, or because the queue is rate-limited.
1338
+
1339
+ Useful to detect backpressure and tasks that hang.
1340
+
1341
+ @example
1342
+ ```
1343
+ import PQueue from 'p-queue';
1344
+
1345
+ const queue = new PQueue({concurrency: 2});
1346
+
1347
+ // Backpressure
1348
+ if (queue.isSaturated) {
1349
+ await queue.onSizeLessThan(queue.concurrency);
1350
+ }
1351
+
1352
+ // Monitoring
1353
+ setInterval(() => {
1354
+ if (queue.isSaturated) {
1355
+ console.warn(`Queue saturated: ${queue.pending} running, ${queue.size} waiting`);
1356
+ }
1357
+ }, 60000);
1358
+ ```
1359
+ */
1360
+ get isSaturated() {
1361
+ return this.#queue.size > 0 && (this.#pending >= this.#concurrency || this.isRateLimited);
1362
+ }
1363
+ /**
1364
+ An array with the running tasks. Each task has its `id`, `priority`, `startTime`, `timeout`, and `timeoutRemaining` (the milliseconds until it times out). Without a timeout, `timeout` and `timeoutRemaining` are `undefined`.
1365
+
1366
+ @example
1367
+ ```
1368
+ import PQueue from 'p-queue';
1369
+
1370
+ const queue = new PQueue({concurrency: 2, timeout: 10000});
1371
+
1372
+ queue.add(() => fetchUser(123), {id: 'user-123'});
1373
+ queue.add(() => fetchPosts(456), {id: 'posts-456', priority: 1});
1374
+
1375
+ console.log(queue.runningTasks);
1376
+ // => [{
1377
+ // id: 'user-123',
1378
+ // priority: 0,
1379
+ // startTime: 1759253001716,
1380
+ // timeout: 10000,
1381
+ // timeoutRemaining: 10000
1382
+ // }, {
1383
+ // id: 'posts-456',
1384
+ // priority: 1,
1385
+ // startTime: 1759253001716,
1386
+ // timeout: 10000,
1387
+ // timeoutRemaining: 10000
1388
+ // }]
1389
+ ```
1390
+ */
1391
+ get runningTasks() {
1392
+ return Array.from(this.#runningTasks, (task) => ({
1393
+ ...task,
1394
+ timeoutRemaining: task.timeout === void 0 ? void 0 : Math.max(0, task.startTime + task.timeout - Date.now())
1395
+ }));
1396
+ }
1397
+ };
1398
+ var TimeoutError = class extends DOMException {
1399
+ constructor(message) {
1400
+ super(message, "TimeoutError");
1401
+ }
1402
+ };
1403
+
1404
+ // src/orchestration/canonical/KrnlQ.ts
1405
+ import { randomUUID } from "crypto";
1406
+
1407
+ // src/orchestration/canonical/model.ts
1408
+ function validateOrchestrationDAG(steps) {
1409
+ const errors = [];
1410
+ const stepMap = /* @__PURE__ */ new Map();
1411
+ for (const step of steps) {
1412
+ if (!step.id || typeof step.id !== "string" || step.id.trim() === "") {
1413
+ errors.push("Step must have a non-empty string ID.");
1414
+ continue;
1415
+ }
1416
+ if (stepMap.has(step.id)) {
1417
+ errors.push(`Duplicate step ID detected: "${step.id}"`);
1418
+ }
1419
+ stepMap.set(step.id, step);
1420
+ if (step.timeoutPolicy) {
1421
+ if (typeof step.timeoutPolicy.timeoutMs !== "number" || step.timeoutPolicy.timeoutMs <= 0) {
1422
+ errors.push(`Step "${step.id}" has invalid timeoutMs: must be a positive number.`);
1423
+ }
1424
+ }
1425
+ if (step.retryPolicy) {
1426
+ if (typeof step.retryPolicy.maxAttempts !== "number" || step.retryPolicy.maxAttempts < 1) {
1427
+ errors.push(`Step "${step.id}" has invalid maxAttempts: must be >= 1.`);
1428
+ }
1429
+ if (step.retryPolicy.backoffMs !== void 0 && step.retryPolicy.backoffMs < 0) {
1430
+ errors.push(`Step "${step.id}" has negative backoffMs.`);
1431
+ }
1432
+ if (step.retryPolicy.initialDelayMs !== void 0 && step.retryPolicy.initialDelayMs < 0) {
1433
+ errors.push(`Step "${step.id}" has negative initialDelayMs.`);
1434
+ }
1435
+ }
1436
+ if (step.concurrency !== void 0 && (typeof step.concurrency !== "number" || step.concurrency < 1)) {
1437
+ errors.push(`Step "${step.id}" has invalid concurrency: must be >= 1.`);
1438
+ }
1439
+ if (step.type === "task" || step.type === "sequential") {
1440
+ if (!step.target && !step.handler) {
1441
+ errors.push(`Step "${step.id}" requires a non-empty target or handler.`);
1442
+ }
1443
+ }
1444
+ }
1445
+ for (const step of steps) {
1446
+ if (step.dependsOn) {
1447
+ for (const dep of step.dependsOn) {
1448
+ if (!stepMap.has(dep)) {
1449
+ errors.push(`Step "${step.id}" depends on unknown step "${dep}".`);
1450
+ }
1451
+ }
1452
+ }
1453
+ }
1454
+ if (errors.length > 0) {
1455
+ return { valid: false, order: [], errors };
1456
+ }
1457
+ const inDegree = /* @__PURE__ */ new Map();
1458
+ const graph = /* @__PURE__ */ new Map();
1459
+ for (const step of steps) {
1460
+ inDegree.set(step.id, 0);
1461
+ graph.set(step.id, []);
1462
+ }
1463
+ for (const step of steps) {
1464
+ if (step.dependsOn) {
1465
+ for (const dep of step.dependsOn) {
1466
+ inDegree.set(step.id, (inDegree.get(step.id) || 0) + 1);
1467
+ graph.get(dep)?.push(step.id);
1468
+ }
1469
+ }
1470
+ }
1471
+ const queue = [];
1472
+ for (const [id, deg] of inDegree.entries()) {
1473
+ if (deg === 0) queue.push(id);
1474
+ }
1475
+ const order = [];
1476
+ while (queue.length > 0) {
1477
+ const current = queue.shift();
1478
+ order.push(current);
1479
+ const neighbors = graph.get(current) || [];
1480
+ for (const neighbor of neighbors) {
1481
+ const newDeg = (inDegree.get(neighbor) || 0) - 1;
1482
+ inDegree.set(neighbor, newDeg);
1483
+ if (newDeg === 0) {
1484
+ queue.push(neighbor);
1485
+ }
1486
+ }
1487
+ }
1488
+ if (order.length !== steps.length) {
1489
+ errors.push("Circular dependency cycle detected in orchestration DAG.");
1490
+ return { valid: false, order: [], errors };
1491
+ }
1492
+ return { valid: true, order, errors: [] };
1493
+ }
1494
+
1495
+ // src/orchestration/canonical/WorkerExecutionBoundary.ts
1496
+ var WorkerExecutionBoundary = class _WorkerExecutionBoundary {
1497
+ constructor(workerId, handler) {
1498
+ this.workerId = workerId;
1499
+ this.handler = handler;
1500
+ }
1501
+ workerId;
1502
+ handler;
1503
+ async processJob(command, metadata) {
1504
+ if (!this.handler) {
1505
+ return {
1506
+ correlationId: command.correlationId,
1507
+ status: "COMPLETED",
1508
+ data: command.payload,
1509
+ executionTimestamp: Date.now()
1510
+ };
1511
+ }
1512
+ const context = {
1513
+ isWorkerContext: true,
1514
+ workerId: this.workerId,
1515
+ timestamp: Date.now(),
1516
+ correlationId: command.correlationId,
1517
+ metadata
1518
+ };
1519
+ _WorkerExecutionBoundary.assertWorkerContext(context);
1520
+ return await this.handler(command, context);
1521
+ }
1522
+ static assertWorkerContext(context) {
1523
+ if (!context || !context.isWorkerContext) {
1524
+ throw new Error(
1525
+ "[WorkerExecutionBoundary] Violation: DIRECT_CALL -> SERVICE_BOUNDARY is strictly forbidden. All operations must execute inside KrnlWorker context."
1526
+ );
1527
+ }
1528
+ }
1529
+ };
1530
+
1531
+ // src/orchestration/canonical/KrnlWorkerPool.ts
1532
+ var KrnlWorkerPool = class {
1533
+ constructor(queueName, workerId = `worker_${queueName}_${Math.random().toString(36).substring(2, 7)}`) {
1534
+ this.queueName = queueName;
1535
+ this.workerId = workerId;
1536
+ this.workerBoundary = new WorkerExecutionBoundary(this.workerId);
1537
+ }
1538
+ queueName;
1539
+ workerId;
1540
+ state = "created";
1541
+ activeJobsCount = 0;
1542
+ startedAt = Date.now();
1543
+ workerBoundary;
1544
+ getState() {
1545
+ return this.state;
1546
+ }
1547
+ getActiveJobs() {
1548
+ return this.activeJobsCount;
1549
+ }
1550
+ getWorkerBoundary() {
1551
+ return this.workerBoundary;
1552
+ }
1553
+ getInfo() {
1554
+ return {
1555
+ id: this.workerId,
1556
+ queueName: this.queueName,
1557
+ state: this.state,
1558
+ startedAt: this.startedAt,
1559
+ activeJobs: this.activeJobsCount
1560
+ };
1561
+ }
1562
+ start() {
1563
+ if (this.state === "stopped") {
1564
+ throw new Error(`[KrnlWorkerPool:${this.workerId}] Cannot start stopped worker.`);
1565
+ }
1566
+ this.state = "started";
1567
+ }
1568
+ createContext(correlationId, metadata) {
1569
+ return {
1570
+ isWorkerContext: true,
1571
+ workerId: this.workerId,
1572
+ timestamp: Date.now(),
1573
+ correlationId: correlationId || `corr_${Math.random().toString(36).substring(2, 11)}`,
1574
+ metadata
1575
+ };
1576
+ }
1577
+ async runWithContext(correlationId, metadata, fn) {
1578
+ if (this.state === "stopped" || this.state === "draining") {
1579
+ throw new Error(`[KrnlWorkerPool:${this.workerId}] Worker is not accepting new jobs (state: ${this.state}).`);
1580
+ }
1581
+ this.state = "running";
1582
+ this.activeJobsCount++;
1583
+ const ctx = this.createContext(correlationId, metadata);
1584
+ WorkerExecutionBoundary.assertWorkerContext(ctx);
1585
+ try {
1586
+ return await fn(ctx);
1587
+ } finally {
1588
+ this.activeJobsCount--;
1589
+ if (this.activeJobsCount === 0 && this.state === "running") {
1590
+ this.state = "started";
1591
+ }
1592
+ }
1593
+ }
1594
+ async drain() {
1595
+ this.state = "draining";
1596
+ while (this.activeJobsCount > 0) {
1597
+ await new Promise((resolve) => setTimeout(resolve, 50));
1598
+ }
1599
+ }
1600
+ async stop() {
1601
+ await this.drain();
1602
+ this.state = "stopped";
1603
+ }
1604
+ };
1605
+
1606
+ // src/orchestration/canonical/KrnlQ.ts
1607
+ function generateSecureId(prefix) {
1608
+ try {
1609
+ return `${prefix}_${randomUUID()}`;
1610
+ } catch {
1611
+ return `${prefix}_${Math.random().toString(36).substring(2, 11)}_${Date.now()}`;
1612
+ }
1613
+ }
1614
+ var KrnlQueue = class {
1615
+ queueName;
1616
+ queue;
1617
+ workerPool;
1618
+ jobs = /* @__PURE__ */ new Map();
1619
+ idempotencyStore = /* @__PURE__ */ new Map();
1620
+ activeOrchestrations = /* @__PURE__ */ new Map();
1621
+ maxRetainedJobs;
1622
+ constructor(options = {}) {
1623
+ this.queueName = options.queueName ?? "krnl_default_queue";
1624
+ this.maxRetainedJobs = options.maxRetainedJobs ?? 1e3;
1625
+ const concurrency = options.concurrency ?? 10;
1626
+ this.queue = new PQueue({
1627
+ concurrency,
1628
+ autoStart: options.autoStart ?? true
1629
+ });
1630
+ this.workerPool = new KrnlWorkerPool(this.queueName);
1631
+ this.workerPool.start();
1632
+ }
1633
+ get concurrency() {
1634
+ return this.queue.concurrency;
1635
+ }
1636
+ set concurrency(value) {
1637
+ this.queue.concurrency = value;
1638
+ }
1639
+ get size() {
1640
+ return this.queue.size;
1641
+ }
1642
+ get pending() {
1643
+ return this.queue.pending;
1644
+ }
1645
+ get isPaused() {
1646
+ return this.queue.isPaused;
1647
+ }
1648
+ getWorkerBoundary() {
1649
+ return this.workerPool.getWorkerBoundary();
1650
+ }
1651
+ getWorkerPool() {
1652
+ return this.workerPool;
1653
+ }
1654
+ pause() {
1655
+ this.queue.pause();
1656
+ }
1657
+ resume() {
1658
+ this.queue.start();
1659
+ }
1660
+ clear() {
1661
+ this.queue.clear();
1662
+ for (const job of this.jobs.values()) {
1663
+ if (job.status === "waiting") {
1664
+ job.status = "cancelled";
1665
+ job.completedAt = Date.now();
1666
+ job.abortController.abort();
1667
+ const cancelErr = new Error("The operation was aborted");
1668
+ cancelErr.name = "AbortError";
1669
+ job.rejectPromise(cancelErr);
1670
+ }
1671
+ }
1672
+ }
1673
+ pruneJobs() {
1674
+ if (this.jobs.size <= this.maxRetainedJobs) return;
1675
+ const excess = this.jobs.size - this.maxRetainedJobs;
1676
+ let pruned = 0;
1677
+ for (const [id, record] of this.jobs.entries()) {
1678
+ if (record.status === "completed" || record.status === "failed" || record.status === "cancelled") {
1679
+ this.jobs.delete(id);
1680
+ pruned++;
1681
+ if (pruned >= excess) break;
1682
+ }
1683
+ }
1684
+ }
1685
+ async drain() {
1686
+ await this.queue.onIdle();
1687
+ }
1688
+ async shutdown(options = { drain: true }) {
1689
+ if (options.drain) {
1690
+ await this.drain();
1691
+ } else {
1692
+ this.clear();
1693
+ }
1694
+ for (const active of this.activeOrchestrations.values()) {
1695
+ active.abortController.abort();
1696
+ active.context.isCancelled = true;
1697
+ }
1698
+ this.activeOrchestrations.clear();
1699
+ await this.workerPool.stop();
1700
+ }
1701
+ async close() {
1702
+ await this.shutdown({ drain: false });
1703
+ }
1704
+ async dispose() {
1705
+ await this.shutdown({ drain: false });
1706
+ }
1707
+ async start() {
1708
+ this.resume();
1709
+ }
1710
+ async stop() {
1711
+ this.pause();
1712
+ }
1713
+ /**
1714
+ * Enqueues a job returning a strong handle.
1715
+ */
1716
+ enqueue(jobDef) {
1717
+ this.pruneJobs();
1718
+ const jobId = jobDef.id || generateSecureId("job");
1719
+ const abortController = new AbortController();
1720
+ if (jobDef.options?.abortSignal) {
1721
+ if (jobDef.options.abortSignal.aborted) {
1722
+ abortController.abort();
1723
+ } else {
1724
+ jobDef.options.abortSignal.addEventListener("abort", () => abortController.abort(), { once: true });
1725
+ }
1726
+ }
1727
+ let resolvePromise;
1728
+ let rejectPromise;
1729
+ const promise = new Promise((res, rej) => {
1730
+ resolvePromise = res;
1731
+ rejectPromise = rej;
1732
+ });
1733
+ const record = {
1734
+ id: jobId,
1735
+ name: jobDef.name,
1736
+ status: "waiting",
1737
+ createdAt: Date.now(),
1738
+ abortController,
1739
+ resolvePromise,
1740
+ rejectPromise,
1741
+ promise
1742
+ };
1743
+ this.jobs.set(jobId, record);
1744
+ const priority = jobDef.options?.priority ?? 0;
1745
+ this.queue.add(
1746
+ async () => {
1747
+ if (record.status === "cancelled" || abortController.signal.aborted) {
1748
+ record.status = "cancelled";
1749
+ const cancelErr = new Error("The operation was aborted");
1750
+ cancelErr.name = "AbortError";
1751
+ rejectPromise(cancelErr);
1752
+ return;
1753
+ }
1754
+ record.status = "active";
1755
+ record.startedAt = Date.now();
1756
+ const idemKey = jobDef.options?.idempotencyKey;
1757
+ if (idemKey && this.idempotencyStore.has(idemKey)) {
1758
+ const cached = this.idempotencyStore.get(idemKey);
1759
+ record.status = cached.status === "COMPLETED" ? "completed" : "failed";
1760
+ record.completedAt = Date.now();
1761
+ if (cached.status === "COMPLETED") {
1762
+ record.result = cached.data;
1763
+ resolvePromise(cached.data);
1764
+ } else {
1765
+ record.error = cached.error;
1766
+ rejectPromise(new Error(cached.error));
1767
+ }
1768
+ return;
1769
+ }
1770
+ const retries = jobDef.options?.retries ?? 0;
1771
+ const maxAttempts = retries + 1;
1772
+ const timeoutMs = jobDef.options?.timeoutMs;
1773
+ const backoffMs = jobDef.options?.backoffMs ?? 100;
1774
+ const backoffPolicy = jobDef.options?.backoffPolicy ?? "exponential";
1775
+ let attempt = 0;
1776
+ let lastError;
1777
+ while (attempt < maxAttempts) {
1778
+ if (abortController.signal.aborted) {
1779
+ record.status = "cancelled";
1780
+ const cancelErr = new Error("The operation was aborted");
1781
+ cancelErr.name = "AbortError";
1782
+ rejectPromise(cancelErr);
1783
+ return;
1784
+ }
1785
+ attempt++;
1786
+ try {
1787
+ const result = await this.workerPool.runWithContext(
1788
+ jobDef.options?.correlationId,
1789
+ jobDef.options?.metadata,
1790
+ async (workerCtx) => {
1791
+ let timer;
1792
+ try {
1793
+ const workPromise = jobDef.handler(jobDef.payload, workerCtx);
1794
+ if (timeoutMs && timeoutMs > 0) {
1795
+ const timeoutPromise = new Promise((_, rej) => {
1796
+ timer = setTimeout(() => {
1797
+ const err = new Error(`Job "${jobDef.name}" timed out after ${timeoutMs}ms.`);
1798
+ err.name = "TimeoutError";
1799
+ rej(err);
1800
+ }, timeoutMs);
1801
+ });
1802
+ return await Promise.race([workPromise, timeoutPromise]);
1803
+ }
1804
+ return await workPromise;
1805
+ } finally {
1806
+ if (timer) clearTimeout(timer);
1807
+ }
1808
+ }
1809
+ );
1810
+ record.status = "completed";
1811
+ record.completedAt = Date.now();
1812
+ record.result = result;
1813
+ if (idemKey) {
1814
+ this.idempotencyStore.set(idemKey, {
1815
+ correlationId: jobDef.options?.correlationId || jobId,
1816
+ status: "COMPLETED",
1817
+ data: result,
1818
+ executionTimestamp: Date.now()
1819
+ });
1820
+ }
1821
+ resolvePromise(result);
1822
+ return;
1823
+ } catch (err) {
1824
+ lastError = err;
1825
+ if (abortController.signal.aborted || err?.name === "AbortError") {
1826
+ record.status = "cancelled";
1827
+ record.completedAt = Date.now();
1828
+ rejectPromise(err);
1829
+ return;
1830
+ }
1831
+ if (attempt < maxAttempts) {
1832
+ const delay = backoffPolicy === "exponential" ? backoffMs * Math.pow(2, attempt - 1) : backoffMs * attempt;
1833
+ await new Promise((r) => setTimeout(r, delay));
1834
+ }
1835
+ }
1836
+ }
1837
+ record.status = "failed";
1838
+ record.completedAt = Date.now();
1839
+ record.error = lastError?.message || String(lastError);
1840
+ if (idemKey) {
1841
+ this.idempotencyStore.set(idemKey, {
1842
+ correlationId: jobDef.options?.correlationId || jobId,
1843
+ status: "FAILED",
1844
+ error: record.error,
1845
+ executionTimestamp: Date.now()
1846
+ });
1847
+ }
1848
+ rejectPromise(lastError);
1849
+ },
1850
+ { priority }
1851
+ );
1852
+ return {
1853
+ id: jobId,
1854
+ name: jobDef.name,
1855
+ getStatus: () => record.status,
1856
+ result: () => record.promise,
1857
+ cancel: () => this.cancel(jobId)
1858
+ };
1859
+ }
1860
+ cancel(jobId) {
1861
+ const job = this.jobs.get(jobId);
1862
+ if (!job) return false;
1863
+ if (job.status === "completed" || job.status === "failed" || job.status === "cancelled") {
1864
+ return false;
1865
+ }
1866
+ job.status = "cancelled";
1867
+ job.abortController.abort();
1868
+ return true;
1869
+ }
1870
+ getJob(jobId) {
1871
+ return this.jobs.get(jobId);
1872
+ }
1873
+ /**
1874
+ * Dispatches a single command through the KrnlQ worker boundary.
1875
+ */
1876
+ async executeCommand(command, handler) {
1877
+ if (command.idempotencyKey && this.idempotencyStore.has(command.idempotencyKey)) {
1878
+ return this.idempotencyStore.get(command.idempotencyKey);
1879
+ }
1880
+ try {
1881
+ const handle = this.enqueue({
1882
+ id: command.id,
1883
+ name: command.type,
1884
+ payload: command.payload,
1885
+ handler,
1886
+ options: {
1887
+ idempotencyKey: command.idempotencyKey,
1888
+ correlationId: command.correlationId
1889
+ }
1890
+ });
1891
+ const data = await handle.result();
1892
+ const res = {
1893
+ correlationId: command.correlationId,
1894
+ status: "COMPLETED",
1895
+ data,
1896
+ executionTimestamp: Date.now()
1897
+ };
1898
+ return res;
1899
+ } catch (err) {
1900
+ const isAbort = err?.name === "AbortError" || err?.message === "The operation was aborted";
1901
+ const res = {
1902
+ correlationId: command.correlationId,
1903
+ status: isAbort ? "CANCELLED" : "FAILED",
1904
+ error: err?.message || String(err),
1905
+ executionTimestamp: Date.now()
1906
+ };
1907
+ return res;
1908
+ }
1909
+ }
1910
+ /**
1911
+ * Executes a full Canonical Orchestration DAG through KrnlQ and worker boundary.
1912
+ * This is a first-class queued job scheduled via this.enqueue() to respect concurrency and worker limits.
1913
+ */
1914
+ async executeOrchestration(descriptor, steps, input, options = {}) {
1915
+ const startedAt = Date.now();
1916
+ const correlationId = options.correlationId || generateSecureId("corr");
1917
+ const executionId = generateSecureId("exec");
1918
+ if (options.idempotencyKey && this.idempotencyStore.has(options.idempotencyKey)) {
1919
+ const cached = this.idempotencyStore.get(options.idempotencyKey);
1920
+ return cached.data;
1921
+ }
1922
+ const validation = validateOrchestrationDAG(steps);
1923
+ if (!validation.valid) {
1924
+ return {
1925
+ orchestrationId: descriptor.id,
1926
+ correlationId,
1927
+ status: "FAILED",
1928
+ stepResults: {},
1929
+ error: `Invalid DAG: ${validation.errors.join("; ")}`,
1930
+ startedAt,
1931
+ completedAt: Date.now(),
1932
+ executionMetadata: { validationErrors: validation.errors }
1933
+ };
1934
+ }
1935
+ const abortController = new AbortController();
1936
+ if (options.abortSignal) {
1937
+ if (options.abortSignal.aborted) {
1938
+ abortController.abort();
1939
+ } else {
1940
+ options.abortSignal.addEventListener("abort", () => abortController.abort(), { once: true });
1941
+ }
1942
+ }
1943
+ const context = {
1944
+ correlationId,
1945
+ parentCorrelationId: options.parentCorrelationId,
1946
+ orchestrationId: descriptor.id,
1947
+ executionId,
1948
+ idempotencyKey: options.idempotencyKey,
1949
+ scope: descriptor.scope || "functionality",
1950
+ results: { input },
1951
+ metadata: { ...options.metadata },
1952
+ timestamp: startedAt,
1953
+ isCancelled: abortController.signal.aborted,
1954
+ abortSignal: abortController.signal
1955
+ };
1956
+ abortController.signal.addEventListener("abort", () => {
1957
+ context.isCancelled = true;
1958
+ });
1959
+ this.activeOrchestrations.set(executionId, { abortController, context });
1960
+ const handle = this.enqueue({
1961
+ id: executionId,
1962
+ name: descriptor.name || descriptor.id,
1963
+ payload: input,
1964
+ options: {
1965
+ idempotencyKey: options.idempotencyKey,
1966
+ correlationId,
1967
+ metadata: options.metadata,
1968
+ abortSignal: abortController.signal
1969
+ },
1970
+ handler: async () => {
1971
+ const timeoutMs = options.timeoutMs || descriptor.timeoutMs;
1972
+ let timeoutTimer;
1973
+ let isWorkflowTimeout = false;
1974
+ if (timeoutMs && timeoutMs > 0) {
1975
+ timeoutTimer = setTimeout(() => {
1976
+ isWorkflowTimeout = true;
1977
+ context.isCancelled = true;
1978
+ abortController.abort();
1979
+ }, timeoutMs);
1980
+ }
1981
+ const stepResults = {};
1982
+ const executedSteps = /* @__PURE__ */ new Set();
1983
+ const executedComps = [];
1984
+ let finalOutput = void 0;
1985
+ let orchestrationStatus = "COMPLETED";
1986
+ let errorMessage;
1987
+ try {
1988
+ while (executedSteps.size < steps.length) {
1989
+ if (context.isCancelled) {
1990
+ orchestrationStatus = "CANCELLED";
1991
+ errorMessage = "Orchestration execution cancelled.";
1992
+ break;
1993
+ }
1994
+ const readySteps = steps.filter((step) => {
1995
+ if (executedSteps.has(step.id)) return false;
1996
+ if (!step.dependsOn || step.dependsOn.length === 0) return true;
1997
+ return step.dependsOn.every((dep) => executedSteps.has(dep));
1998
+ });
1999
+ if (readySteps.length === 0) {
2000
+ break;
2001
+ }
2002
+ const batch = readySteps.slice(0, this.concurrency);
2003
+ const batchPromises = batch.map(async (step) => {
2004
+ const stepRes = await this.executeSingleStep(step, context, options.nestedRunner);
2005
+ stepResults[step.id] = stepRes;
2006
+ executedSteps.add(step.id);
2007
+ if (stepRes.status === "COMPLETED") {
2008
+ context.results[step.id] = stepRes.output;
2009
+ finalOutput = stepRes.output;
2010
+ if (step.compensation?.handler) {
2011
+ executedComps.push(() => step.compensation.handler(context));
2012
+ }
2013
+ } else if (stepRes.status === "SKIPPED") {
2014
+ } else if (stepRes.status === "CANCELLED") {
2015
+ const cancelErr = new Error("The operation was aborted");
2016
+ cancelErr.name = "AbortError";
2017
+ throw cancelErr;
2018
+ } else {
2019
+ throw new Error(stepRes.error || `Step "${step.id}" failed with status ${stepRes.status}`);
2020
+ }
2021
+ });
2022
+ await Promise.all(batchPromises);
2023
+ }
2024
+ } catch (err) {
2025
+ const isExplicitStepFailure = err && err.name !== "AbortError" && err.message !== "The operation was aborted";
2026
+ const wasCancelled = (context.isCancelled || abortController.signal.aborted || err?.name === "AbortError") && !isExplicitStepFailure;
2027
+ if (isWorkflowTimeout) {
2028
+ orchestrationStatus = "TIMED_OUT";
2029
+ errorMessage = `Orchestration timed out after ${timeoutMs}ms.`;
2030
+ } else if (isExplicitStepFailure) {
2031
+ orchestrationStatus = "FAILED";
2032
+ errorMessage = err?.message || String(err);
2033
+ } else if (wasCancelled) {
2034
+ orchestrationStatus = "CANCELLED";
2035
+ errorMessage = "The operation was aborted";
2036
+ } else {
2037
+ orchestrationStatus = "FAILED";
2038
+ errorMessage = err?.message || String(err);
2039
+ }
2040
+ if (executedComps.length > 0) {
2041
+ for (let i = executedComps.length - 1; i >= 0; i--) {
2042
+ try {
2043
+ await executedComps[i]();
2044
+ } catch (compErr) {
2045
+ console.error(`[KrnlQ] Compensation failed:`, compErr);
2046
+ }
2047
+ }
2048
+ }
2049
+ } finally {
2050
+ if (timeoutTimer) clearTimeout(timeoutTimer);
2051
+ this.activeOrchestrations.delete(executionId);
2052
+ }
2053
+ const result = {
2054
+ orchestrationId: descriptor.id,
2055
+ correlationId,
2056
+ status: orchestrationStatus,
2057
+ output: finalOutput,
2058
+ stepResults,
2059
+ error: errorMessage,
2060
+ startedAt,
2061
+ completedAt: Date.now(),
2062
+ executionMetadata: {
2063
+ executionId,
2064
+ scope: descriptor.scope,
2065
+ stepsCount: steps.length,
2066
+ executedCount: executedSteps.size
2067
+ }
2068
+ };
2069
+ if (options.idempotencyKey) {
2070
+ this.idempotencyStore.set(options.idempotencyKey, {
2071
+ correlationId,
2072
+ status: orchestrationStatus === "COMPLETED" ? "COMPLETED" : "FAILED",
2073
+ data: result,
2074
+ executionTimestamp: Date.now()
2075
+ });
2076
+ }
2077
+ return result;
2078
+ }
2079
+ });
2080
+ return await handle.result();
2081
+ }
2082
+ async executeSingleStep(step, context, nestedRunner) {
2083
+ const stepStart = Date.now();
2084
+ let attempts = 0;
2085
+ const maxAttempts = step.retryPolicy?.maxAttempts ?? 1;
2086
+ if (step.condition) {
2087
+ try {
2088
+ const conditionPass = await step.condition(context);
2089
+ if (!conditionPass) {
2090
+ return {
2091
+ stepId: step.id,
2092
+ status: "SKIPPED",
2093
+ attempts: 0,
2094
+ startedAt: stepStart,
2095
+ completedAt: Date.now()
2096
+ };
2097
+ }
2098
+ } catch (condErr) {
2099
+ return {
2100
+ stepId: step.id,
2101
+ status: "FAILED",
2102
+ attempts: 1,
2103
+ error: `Condition evaluation failed: ${condErr?.message || String(condErr)}`,
2104
+ startedAt: stepStart,
2105
+ completedAt: Date.now()
2106
+ };
2107
+ }
2108
+ }
2109
+ let lastError;
2110
+ let stepCancelled = false;
2111
+ const stepTimeoutMs = step.timeoutPolicy?.timeoutMs;
2112
+ while (attempts < maxAttempts) {
2113
+ if (context.isCancelled) {
2114
+ return {
2115
+ stepId: step.id,
2116
+ status: "CANCELLED",
2117
+ attempts,
2118
+ startedAt: stepStart,
2119
+ completedAt: Date.now()
2120
+ };
2121
+ }
2122
+ attempts++;
2123
+ const stepAbortController = new AbortController();
2124
+ if (context.abortSignal) {
2125
+ if (context.abortSignal.aborted) {
2126
+ stepAbortController.abort();
2127
+ } else {
2128
+ context.abortSignal.addEventListener("abort", () => stepAbortController.abort(), { once: true });
2129
+ }
2130
+ }
2131
+ const stepContext = {
2132
+ ...context,
2133
+ abortSignal: stepAbortController.signal
2134
+ };
2135
+ try {
2136
+ let stepOutput;
2137
+ let stepTimer;
2138
+ stepCancelled = false;
2139
+ const runPromise = (async () => {
2140
+ if (step.type === "nested" && step.nestedOrchestrationId && nestedRunner) {
2141
+ const childContext = {
2142
+ ...stepContext,
2143
+ parentCorrelationId: context.correlationId,
2144
+ correlationId: `${context.correlationId}.${step.id}`
2145
+ };
2146
+ return await nestedRunner(step.nestedOrchestrationId, context.results, childContext);
2147
+ }
2148
+ if (step.type === "fanOut" && step.getItems) {
2149
+ const items = await step.getItems(stepContext);
2150
+ if (!Array.isArray(items)) throw new Error(`[fanOut] getItems must return an array.`);
2151
+ const concurrency = step.concurrency || 5;
2152
+ const results = [];
2153
+ for (let i = 0; i < items.length; i += concurrency) {
2154
+ const slice = items.slice(i, i + concurrency);
2155
+ const sliceRes = await Promise.all(
2156
+ slice.map((item) => step.handler ? step.handler(item, stepContext) : Promise.resolve(item))
2157
+ );
2158
+ results.push(...sliceRes);
2159
+ }
2160
+ return results;
2161
+ }
2162
+ if (step.handler) {
2163
+ return await step.handler(context.results, stepContext);
2164
+ }
2165
+ return context.results;
2166
+ })();
2167
+ const abortPromise = new Promise((_, reject) => {
2168
+ if (stepAbortController.signal.aborted || context.isCancelled) {
2169
+ const err = new Error("The operation was aborted");
2170
+ err.name = "AbortError";
2171
+ reject(err);
2172
+ }
2173
+ stepAbortController.signal.addEventListener("abort", () => {
2174
+ const err = new Error("The operation was aborted");
2175
+ err.name = "AbortError";
2176
+ reject(err);
2177
+ });
2178
+ });
2179
+ const promisesToRace = [runPromise, abortPromise];
2180
+ if (stepTimeoutMs && stepTimeoutMs > 0) {
2181
+ const timeoutPromise = new Promise((_, reject) => {
2182
+ stepTimer = setTimeout(() => {
2183
+ stepCancelled = true;
2184
+ const tErr = new Error(`Step "${step.id}" timed out after ${stepTimeoutMs}ms.`);
2185
+ tErr.name = "TimeoutError";
2186
+ reject(tErr);
2187
+ }, stepTimeoutMs);
2188
+ });
2189
+ promisesToRace.push(timeoutPromise);
2190
+ }
2191
+ stepOutput = await Promise.race(promisesToRace);
2192
+ if (stepTimer) clearTimeout(stepTimer);
2193
+ return {
2194
+ stepId: step.id,
2195
+ status: "COMPLETED",
2196
+ attempts,
2197
+ output: stepOutput,
2198
+ startedAt: stepStart,
2199
+ completedAt: Date.now()
2200
+ };
2201
+ } catch (err) {
2202
+ if (stepCancelled || err?.name === "TimeoutError") {
2203
+ return {
2204
+ stepId: step.id,
2205
+ status: "TIMED_OUT",
2206
+ attempts,
2207
+ error: err?.message || `Step "${step.id}" timed out after ${stepTimeoutMs}ms.`,
2208
+ startedAt: stepStart,
2209
+ completedAt: Date.now()
2210
+ };
2211
+ }
2212
+ if (context.isCancelled || context.abortSignal?.aborted || err?.name === "AbortError" || err?.message === "Operation cancelled" || err?.message === "The operation was aborted") {
2213
+ return {
2214
+ stepId: step.id,
2215
+ status: "CANCELLED",
2216
+ attempts,
2217
+ startedAt: stepStart,
2218
+ completedAt: Date.now()
2219
+ };
2220
+ }
2221
+ lastError = err;
2222
+ if (step.catchHandler && attempts >= maxAttempts) {
2223
+ try {
2224
+ const recovered = await step.catchHandler(err, stepContext);
2225
+ return {
2226
+ stepId: step.id,
2227
+ status: "COMPLETED",
2228
+ attempts,
2229
+ output: recovered,
2230
+ startedAt: stepStart,
2231
+ completedAt: Date.now()
2232
+ };
2233
+ } catch (catchErr) {
2234
+ lastError = catchErr;
2235
+ }
2236
+ }
2237
+ if (attempts < maxAttempts && step.retryPolicy) {
2238
+ const backoffDelay = this.computeBackoff(step.retryPolicy, attempts);
2239
+ await new Promise((r) => setTimeout(r, backoffDelay));
2240
+ }
2241
+ }
2242
+ }
2243
+ return {
2244
+ stepId: step.id,
2245
+ status: "FAILED",
2246
+ attempts,
2247
+ error: lastError?.message || String(lastError),
2248
+ startedAt: stepStart,
2249
+ completedAt: Date.now()
2250
+ };
2251
+ }
2252
+ computeBackoff(policy, attempt) {
2253
+ const base = policy.backoffMs || 100;
2254
+ let delay;
2255
+ if (policy.backoff === "exponential") {
2256
+ delay = base * Math.pow(2, attempt - 1);
2257
+ } else {
2258
+ delay = base * attempt;
2259
+ }
2260
+ if (policy.maxBackoffMs && delay > policy.maxBackoffMs) {
2261
+ delay = policy.maxBackoffMs;
2262
+ }
2263
+ if (policy.jitter) {
2264
+ delay += Math.floor(Math.random() * (base * 0.5));
2265
+ }
2266
+ return delay;
66
2267
  }
67
- assertRunning(serviceName) {
68
- if (this.status !== "running") {
69
- throw new Error(`[Service:${serviceName}] Cannot invoke operation while status is '${this.status}' (expected 'running').`);
2268
+ cancelExecution(executionId) {
2269
+ const active = this.activeOrchestrations.get(executionId);
2270
+ if (active) {
2271
+ active.context.isCancelled = true;
2272
+ active.abortController.abort();
2273
+ return true;
70
2274
  }
2275
+ return false;
71
2276
  }
72
2277
  };
73
2278
 
74
- // src/services/ServiceInstance.ts
75
- var ServiceInstance = class {
76
- constructor(definition) {
77
- this.definition = definition;
78
- this.id = definition.id;
79
- this.name = definition.name;
80
- this.version = definition.version;
81
- this.lifecycle = new LifecycleManager();
82
- this.eventBus = new ServiceEventBus();
83
- if (definition.state?.initial) {
84
- this.stateStore = new ServiceStateStore(definition.state.initial);
85
- }
86
- }
87
- definition;
2279
+ // src/services/ServiceFacade.ts
2280
+ var ServiceFacade = class {
88
2281
  id;
89
2282
  name;
90
2283
  version;
91
- stateStore;
92
- eventBus;
93
- lifecycle;
94
- getDefinition() {
95
- return this.definition;
96
- }
97
- async start() {
98
- this.lifecycle.setStatus("starting");
99
- if (this.definition.lifecycle?.onInit) {
100
- await this.definition.lifecycle.onInit();
2284
+ description;
2285
+ functionalities;
2286
+ functionalityOrchestrations;
2287
+ libraries;
2288
+ dependencies;
2289
+ capabilities;
2290
+ defaultFrontend;
2291
+ instance;
2292
+ queue;
2293
+ constructor(config) {
2294
+ if (!config || !config.id || typeof config.id !== "string") {
2295
+ throw new Error("[ServiceFacade] ServiceFacade requires a valid id.");
101
2296
  }
102
- if (this.definition.lifecycle?.onStart) {
103
- await this.definition.lifecycle.onStart();
2297
+ this.id = config.id;
2298
+ this.name = config.name || config.id;
2299
+ this.version = config.version || "1.0.0";
2300
+ this.description = config.description || "";
2301
+ this.functionalities = config.functionalities ? { ...config.functionalities } : {};
2302
+ this.functionalityOrchestrations = config.functionalityOrchestrations ? { ...config.functionalityOrchestrations } : config.orchestrations ? { ...config.orchestrations } : {};
2303
+ this.libraries = config.libraries ? { ...config.libraries } : {};
2304
+ this.dependencies = Object.freeze(config.dependencies ? [...config.dependencies] : []);
2305
+ this.capabilities = Object.freeze(config.capabilities ? [...config.capabilities] : []);
2306
+ this.defaultFrontend = config.defaultFrontend ? Object.freeze({ ...config.defaultFrontend }) : void 0;
2307
+ if (config.instance) {
2308
+ this.instance = config.instance;
2309
+ } else if (config.definition) {
2310
+ this.instance = new ServiceInstance(config.definition);
2311
+ } else {
2312
+ this.instance = new ServiceInstance({
2313
+ id: this.id,
2314
+ name: this.name,
2315
+ version: this.version,
2316
+ operations: {}
2317
+ });
104
2318
  }
105
- this.lifecycle.setStatus("running");
2319
+ this.queue = new KrnlQueue({
2320
+ queueName: `krnl_queue_${this.id}`,
2321
+ concurrency: config.concurrency ?? config.queueOptions?.concurrency ?? 10,
2322
+ autoStart: config.queueOptions?.autoStart ?? true
2323
+ });
2324
+ }
2325
+ get orchestrations() {
2326
+ return this.functionalityOrchestrations;
2327
+ }
2328
+ getInstance() {
2329
+ return this.instance;
2330
+ }
2331
+ getQueue() {
2332
+ return this.queue;
2333
+ }
2334
+ getExecutionEngine() {
2335
+ return this.queue;
2336
+ }
2337
+ getWorkerBoundary() {
2338
+ return this.queue.getWorkerBoundary();
2339
+ }
2340
+ getStatus() {
2341
+ return this.instance.getStatus();
2342
+ }
2343
+ async start() {
2344
+ await this.instance.start();
2345
+ await this.queue.start();
106
2346
  }
107
2347
  async stop() {
108
- this.lifecycle.setStatus("stopping");
109
- if (this.definition.lifecycle?.onStop) {
110
- await this.definition.lifecycle.onStop();
2348
+ await this.queue.stop();
2349
+ await this.instance.stop();
2350
+ }
2351
+ async dispose() {
2352
+ await this.queue.dispose();
2353
+ await this.instance.dispose();
2354
+ }
2355
+ /**
2356
+ * External caller callable boundary for single functionality / operation execution.
2357
+ * Path: External Caller -> Service Facade -> KrnlQ Job -> Worker -> Functionality -> Result.
2358
+ * Strictly avoids synchronous unmediated execution outside the queue.
2359
+ */
2360
+ async call(op, input, ctx) {
2361
+ const correlationId = ctx?.correlationId || `corr_${Math.random().toString(36).substring(2, 11)}`;
2362
+ const commandId = `cmd_${this.id}_${op}_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`;
2363
+ const command = {
2364
+ id: commandId,
2365
+ type: `${this.id}.${op}`,
2366
+ payload: input ?? {},
2367
+ correlationId,
2368
+ idempotencyKey: ctx?.idempotencyKey,
2369
+ createdAt: Date.now()
2370
+ };
2371
+ const result = await this.queue.executeCommand(command, async (payload, workerCtx) => {
2372
+ WorkerExecutionBoundary.assertWorkerContext(workerCtx);
2373
+ if (this.functionalities[op] && typeof this.functionalities[op].execute === "function") {
2374
+ return await this.functionalities[op].execute(payload, {
2375
+ correlationId: workerCtx.correlationId,
2376
+ state: this.instance.getState()
2377
+ });
2378
+ }
2379
+ return await this.instance.call(op, payload, {
2380
+ correlationId: workerCtx.correlationId,
2381
+ idempotencyKey: command.idempotencyKey
2382
+ });
2383
+ });
2384
+ if (result.status === "FAILED") {
2385
+ throw new Error(result.error || `[ServiceFacade:${this.id}] Operation '${op}' execution failed.`);
2386
+ }
2387
+ return result.data;
2388
+ }
2389
+ /**
2390
+ * External caller callable boundary for functionality orchestration execution.
2391
+ * Path: External Caller -> Service Facade -> KrnlQ Command -> Worker -> FunctionalityOrchestration -> Result.
2392
+ */
2393
+ async orchestrate(orchestrationName, input, options = {}) {
2394
+ const orch = this.functionalityOrchestrations[orchestrationName];
2395
+ if (!orch) {
2396
+ throw new Error(
2397
+ `[ServiceFacade:${this.id}] FunctionalityOrchestration "${orchestrationName}" not found.`
2398
+ );
111
2399
  }
112
- if (this.definition.lifecycle?.onDispose) {
113
- await this.definition.lifecycle.onDispose();
2400
+ const correlationId = options.correlationId || `corr_${Math.random().toString(36).substring(2, 11)}`;
2401
+ const commandId = `cmd_orch_${this.id}_${orchestrationName}_${Date.now()}`;
2402
+ const command = {
2403
+ id: commandId,
2404
+ type: `${this.id}.orchestrations.${orchestrationName}`,
2405
+ payload: input ?? {},
2406
+ correlationId,
2407
+ idempotencyKey: options.idempotencyKey,
2408
+ createdAt: Date.now()
2409
+ };
2410
+ const cmdResult = await this.queue.executeCommand(
2411
+ command,
2412
+ async (payload, workerCtx) => {
2413
+ WorkerExecutionBoundary.assertWorkerContext(workerCtx);
2414
+ const resolveStepInput = (step, results) => {
2415
+ const deps = step.dependsOn;
2416
+ if (!deps || deps.length === 0) {
2417
+ return results["input"];
2418
+ }
2419
+ if (deps.length === 1) {
2420
+ const depRes = results[deps[0]];
2421
+ const initialInput = results["input"];
2422
+ if (typeof depRes === "object" && depRes !== null && typeof initialInput === "object" && initialInput !== null && !Array.isArray(depRes) && !Array.isArray(initialInput)) {
2423
+ return { ...initialInput, ...depRes };
2424
+ }
2425
+ return depRes !== void 0 ? depRes : results["input"];
2426
+ }
2427
+ const joined = {};
2428
+ for (const dep of deps) {
2429
+ joined[dep] = results[dep];
2430
+ }
2431
+ return joined;
2432
+ };
2433
+ const rawSteps = orch.getSteps();
2434
+ const boundSteps = rawSteps.map((s) => {
2435
+ let compensation = s.compensation;
2436
+ if (s.compensation?.target && !s.compensation.handler) {
2437
+ compensation = {
2438
+ ...s.compensation,
2439
+ handler: async (compCtx) => {
2440
+ await this.call(s.compensation.target, compCtx.results[s.id], {
2441
+ correlationId: compCtx.correlationId
2442
+ });
2443
+ }
2444
+ };
2445
+ }
2446
+ if (s.type === "task" && s.target) {
2447
+ return {
2448
+ ...s,
2449
+ compensation,
2450
+ handler: async (_stepInput, stepCtx) => {
2451
+ const resolvedInput = resolveStepInput(s, stepCtx.results);
2452
+ const stepPayload = typeof resolvedInput === "object" && resolvedInput !== null && !Array.isArray(resolvedInput) ? { ...stepCtx.results, ...resolvedInput } : { ...stepCtx.results };
2453
+ if (stepCtx.results.input) {
2454
+ stepPayload.input = stepCtx.results.input;
2455
+ }
2456
+ return await this.call(s.target, stepPayload, {
2457
+ correlationId: stepCtx.correlationId
2458
+ });
2459
+ }
2460
+ };
2461
+ }
2462
+ return {
2463
+ ...s,
2464
+ compensation
2465
+ };
2466
+ });
2467
+ const nestedRunner = async (childOrchId, childInput, childCtx) => {
2468
+ const childOrch = this.functionalityOrchestrations[childOrchId];
2469
+ if (!childOrch) {
2470
+ throw new Error(
2471
+ `[ServiceFacade:${this.id}] Nested FunctionalityOrchestration "${childOrchId}" not found in service.`
2472
+ );
2473
+ }
2474
+ const nestedResult = await this.orchestrate(childOrchId, childInput, {
2475
+ correlationId: childCtx.correlationId,
2476
+ timeoutMs: childOrch.timeoutMs,
2477
+ abortSignal: options.abortSignal
2478
+ });
2479
+ if (nestedResult.status !== "COMPLETED") {
2480
+ throw new Error(nestedResult.error || `Nested orchestration "${childOrchId}" failed.`);
2481
+ }
2482
+ return nestedResult.output;
2483
+ };
2484
+ return await this.queue.executeOrchestration(
2485
+ { id: orch.id, name: orch.name, version: orch.version, timeoutMs: orch.timeoutMs, scope: "functionality" },
2486
+ boundSteps,
2487
+ payload,
2488
+ {
2489
+ correlationId: workerCtx.correlationId,
2490
+ idempotencyKey: command.idempotencyKey,
2491
+ timeoutMs: options.timeoutMs || orch.timeoutMs,
2492
+ metadata: options.metadata,
2493
+ nestedRunner,
2494
+ abortSignal: options.abortSignal
2495
+ }
2496
+ );
2497
+ }
2498
+ );
2499
+ if (cmdResult.status === "FAILED") {
2500
+ throw new Error(cmdResult.error || `[ServiceFacade:${this.id}] Orchestration failed.`);
114
2501
  }
115
- this.lifecycle.setStatus("stopped");
2502
+ return cmdResult.data;
116
2503
  }
117
- async call(op, input, ctx = {}) {
118
- this.lifecycle.assertRunning(this.name);
119
- const operation = this.definition.operations[op];
120
- if (!operation) {
121
- throw new Error(`[Service:${this.name}] Operation '${op}' not found.`);
2504
+ /**
2505
+ * Executes a callable operation or orchestration through KrnlQ and worker boundary.
2506
+ * Path: External Caller -> Service Facade -> KrnlQ Command -> Worker -> Functionality / Orchestration -> Result.
2507
+ * Strictly queue-mediated; zero unmediated bypasses.
2508
+ */
2509
+ async execute(target, input, options) {
2510
+ if (this.functionalityOrchestrations[target]) {
2511
+ const res = await this.orchestrate(target, input, options);
2512
+ if (res.status === "FAILED") {
2513
+ throw new Error(res.error || `[ServiceFacade:${this.id}] Orchestration "${target}" failed.`);
2514
+ }
2515
+ return res;
122
2516
  }
123
- return await operation.handler(input, ctx);
2517
+ return this.call(target, input, {
2518
+ correlationId: options?.correlationId,
2519
+ idempotencyKey: options?.idempotencyKey
2520
+ });
124
2521
  }
125
2522
  getState() {
126
- if (!this.stateStore) {
127
- return Object.freeze({});
128
- }
129
- return this.stateStore.getState();
2523
+ return this.instance.getState();
130
2524
  }
131
2525
  setState(mutation) {
132
- if (!this.stateStore) {
133
- this.stateStore = new ServiceStateStore(mutation);
134
- return;
135
- }
136
- this.stateStore.setState(mutation);
2526
+ this.instance.setState(mutation);
137
2527
  }
138
2528
  on(event, handler) {
139
- return this.eventBus.on(event, handler);
2529
+ return this.instance.on(event, handler);
140
2530
  }
141
2531
  emit(event, payload) {
142
- this.eventBus.emit(event, payload);
143
- }
144
- };
145
-
146
- // src/services/ServiceProxy.ts
147
- var ServiceProxy = class {
148
- constructor(definition, adapter, endpoint) {
149
- this.definition = definition;
150
- this.adapter = adapter;
151
- this.endpoint = endpoint;
152
- this.id = definition.id;
153
- this.name = definition.name;
154
- this.version = definition.version;
155
- this.stateCache = definition.state?.initial || {};
2532
+ this.instance.emit(event, payload);
156
2533
  }
157
- definition;
158
- adapter;
159
- endpoint;
160
- id;
161
- name;
162
- version;
163
- stateCache;
164
- eventHandlers = /* @__PURE__ */ new Map();
165
- getDefinition() {
166
- return this.definition;
2534
+ registerFunctionality(name, functionality) {
2535
+ if (!name || typeof name !== "string") {
2536
+ throw new Error("[ServiceFacade] Functionality name must be a non-empty string.");
2537
+ }
2538
+ this.functionalities[name] = functionality;
2539
+ return this;
167
2540
  }
168
- async start() {
2541
+ registerFunctionalityOrchestration(name, orchestration) {
2542
+ if (!name || typeof name !== "string") {
2543
+ throw new Error("[ServiceFacade] FunctionalityOrchestration name must be a non-empty string.");
2544
+ }
2545
+ if (!orchestration) {
2546
+ throw new Error("[ServiceFacade] FunctionalityOrchestration instance is required.");
2547
+ }
2548
+ this.functionalityOrchestrations[name] = orchestration;
2549
+ return this;
169
2550
  }
170
- async stop() {
2551
+ /** @deprecated Use registerFunctionalityOrchestration */
2552
+ registerOrchestration(name, orchestration) {
2553
+ return this.registerFunctionalityOrchestration(name, orchestration);
171
2554
  }
172
- async call(op, input, ctx = {}) {
173
- if (!this.adapter.send) {
174
- throw new Error(`[ServiceProxy:${this.name}] Adapter does not support send().`);
2555
+ registerLibrary(name, library) {
2556
+ if (!name || typeof name !== "string") {
2557
+ throw new Error("[ServiceFacade] Library name must be a non-empty string.");
175
2558
  }
176
- const envelope = {
177
- id: `req-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
178
- type: "request",
179
- operation: op,
180
- payload: input,
181
- timestamp: Date.now()
182
- };
183
- const response = await this.adapter.send(this.endpoint, envelope);
184
- if (response.error) {
185
- throw new Error(`[ServiceProxy:${this.name}] Remote error: ${response.error}`);
2559
+ if (library === void 0 || library === null) {
2560
+ throw new Error(`[ServiceFacade] Library "${name}" must not be null or undefined.`);
186
2561
  }
187
- return response.payload;
2562
+ this.libraries[name] = library;
2563
+ return this;
188
2564
  }
189
- getState() {
190
- return Object.freeze({ ...this.stateCache });
2565
+ getLibrary(name) {
2566
+ const lib = this.libraries[name];
2567
+ if (lib === void 0 || lib === null) {
2568
+ throw new Error(`[ServiceFacade:${this.id}] Library "${name}" not found on service facade.`);
2569
+ }
2570
+ return lib;
191
2571
  }
192
- setState(mutation) {
193
- this.stateCache = { ...this.stateCache, ...mutation };
2572
+ get namespace() {
2573
+ return this.getNamespace();
194
2574
  }
195
- on(event, handler) {
196
- if (!this.eventHandlers.has(event)) {
197
- this.eventHandlers.set(event, /* @__PURE__ */ new Set());
198
- }
199
- const handlers = this.eventHandlers.get(event);
200
- handlers.add(handler);
201
- return () => {
202
- handlers.delete(handler);
2575
+ getNamespace() {
2576
+ return {
2577
+ serviceId: this.id,
2578
+ serviceName: this.name,
2579
+ version: this.version,
2580
+ description: this.description,
2581
+ libraries: { ...this.libraries },
2582
+ functionalities: { ...this.functionalities },
2583
+ functionalityOrchestrations: { ...this.functionalityOrchestrations },
2584
+ capabilities: this.capabilities,
2585
+ dependencies: this.dependencies
203
2586
  };
204
2587
  }
205
- emit(event, payload) {
206
- const handlers = this.eventHandlers.get(event);
207
- if (handlers) {
208
- for (const handler of Array.from(handlers)) {
209
- handler(payload);
210
- }
211
- }
2588
+ getServiceFacadeMetadata() {
2589
+ return this.getNamespace();
212
2590
  }
213
2591
  };
214
-
215
- // src/services/ServiceGenerators.ts
216
- function createServiceDefinition(definition) {
217
- return definition;
218
- }
219
- function createService(definition) {
220
- return new ServiceInstance(definition);
221
- }
222
- function createServiceProxy(definition, adapter, endpoint) {
223
- return new ServiceProxy(definition, adapter, endpoint);
2592
+ function createServiceFacade(config) {
2593
+ return new ServiceFacade(config);
224
2594
  }
225
2595
 
226
2596
  // src/protocols/HttpProtocolAdapter.ts
@@ -398,10 +2768,14 @@ var WebSocketProtocolAdapter = class {
398
2768
  };
399
2769
  }
400
2770
  async send(endpoint, envelope) {
401
- let WS = globalThis.WebSocket;
402
- if (!WS) {
2771
+ let WS;
2772
+ const isNode = Boolean(globalThis.process?.versions?.node);
2773
+ if (isNode) {
403
2774
  const wsMod = await import("ws").catch(() => null);
404
- WS = wsMod?.WebSocket || wsMod?.default?.WebSocket || wsMod;
2775
+ WS = wsMod?.WebSocket || wsMod?.default?.WebSocket || wsMod?.default || wsMod;
2776
+ }
2777
+ if (!WS) {
2778
+ WS = globalThis.WebSocket;
405
2779
  }
406
2780
  if (!WS) {
407
2781
  throw new Error("No WebSocket client implementation available in this environment.");
@@ -607,23 +2981,74 @@ var MemoryTransport = class {
607
2981
  };
608
2982
 
609
2983
  // src/registry/ServiceRegistry.ts
2984
+ var PROTOCOLS = ["http", "https", "ws", "wss", "udp", "p2p", "signaling", "memory"];
2985
+ function validateEndpoint(endpoint) {
2986
+ if (!endpoint || typeof endpoint !== "object") throw new Error("[ServiceRegistry] Invalid endpoint.");
2987
+ if (!PROTOCOLS.includes(endpoint.protocol)) throw new Error("[ServiceRegistry] Unsupported endpoint protocol.");
2988
+ if (typeof endpoint.address !== "string" || endpoint.address.trim() === "") throw new Error("[ServiceRegistry] Endpoint address must be non-empty.");
2989
+ if (endpoint.port !== void 0 && (!Number.isInteger(endpoint.port) || endpoint.port < 0 || endpoint.port > 65535)) throw new Error("[ServiceRegistry] Endpoint port is invalid.");
2990
+ if (!Array.isArray(endpoint.capabilities)) throw new Error("[ServiceRegistry] Endpoint capabilities must be an array.");
2991
+ }
610
2992
  var ServiceRegistry = class {
611
2993
  services = /* @__PURE__ */ new Map();
2994
+ /**
2995
+ * Registers a service definition and its endpoints into the registry.
2996
+ *
2997
+ * @param definition Validated service definition.
2998
+ * @param endpoints Optional list of active endpoint descriptors.
2999
+ * @throws Error if definition or endpoints fail validation.
3000
+ * @throws Error if service is already registered under the same ID.
3001
+ */
612
3002
  register(definition, endpoints = []) {
3003
+ validateServiceDefinition(definition);
3004
+ for (const endpoint of endpoints) validateEndpoint(endpoint);
3005
+ const existing = this.services.get(definition.id);
3006
+ if (existing) {
3007
+ throw new Error(
3008
+ "[ServiceRegistry] Service '" + definition.id + "' is already registered at version '" + existing.definition.version + "'. Use replace() to explicitly replace an existing service."
3009
+ );
3010
+ }
613
3011
  this.services.set(definition.id, {
614
3012
  definition,
615
- endpoints,
3013
+ endpoints: endpoints.map((endpoint) => ({ ...endpoint, capabilities: [...endpoint.capabilities] })),
616
3014
  registeredAt: Date.now()
617
3015
  });
618
3016
  }
3017
+ /**
3018
+ * Explicitly replaces or updates a service definition and its endpoints in the registry.
3019
+ * Preserves original registeredAt timestamp if the service was previously registered.
3020
+ *
3021
+ * @param definition Validated service definition.
3022
+ * @param endpoints Optional list of active endpoint descriptors.
3023
+ */
3024
+ replace(definition, endpoints = []) {
3025
+ validateServiceDefinition(definition);
3026
+ for (const endpoint of endpoints) validateEndpoint(endpoint);
3027
+ const existing = this.services.get(definition.id);
3028
+ this.services.set(definition.id, {
3029
+ definition,
3030
+ endpoints: endpoints.map((endpoint) => ({ ...endpoint, capabilities: [...endpoint.capabilities] })),
3031
+ registeredAt: existing?.registeredAt ?? Date.now()
3032
+ });
3033
+ }
619
3034
  unregister(serviceId) {
620
- this.services.delete(serviceId);
3035
+ return this.services.delete(serviceId);
621
3036
  }
622
3037
  get(serviceId) {
623
- return this.services.get(serviceId);
3038
+ const record = this.services.get(serviceId);
3039
+ if (!record) return void 0;
3040
+ return {
3041
+ definition: record.definition,
3042
+ endpoints: record.endpoints.map((endpoint) => ({ ...endpoint, capabilities: [...endpoint.capabilities] })),
3043
+ registeredAt: record.registeredAt
3044
+ };
624
3045
  }
625
3046
  list() {
626
- return Array.from(this.services.values());
3047
+ return Array.from(this.services.values()).map((record) => ({
3048
+ definition: record.definition,
3049
+ endpoints: record.endpoints.map((endpoint) => ({ ...endpoint, capabilities: [...endpoint.capabilities] })),
3050
+ registeredAt: record.registeredAt
3051
+ }));
627
3052
  }
628
3053
  findByCapability(capabilityName) {
629
3054
  return this.list().filter(
@@ -637,32 +3062,75 @@ var ServiceRuntime = class {
637
3062
  instances = /* @__PURE__ */ new Map();
638
3063
  registry;
639
3064
  constructor(registry) {
640
- this.registry = registry || new ServiceRegistry();
3065
+ this.registry = registry ?? new ServiceRegistry();
641
3066
  }
642
3067
  register(service) {
643
- this.instances.set(service.id, service);
3068
+ const existing = this.instances.get(service.id);
3069
+ if (existing && existing !== service) {
3070
+ throw new Error("[ServiceRuntime] Service '" + service.id + "' is already registered.");
3071
+ }
644
3072
  this.registry.register(service.getDefinition());
3073
+ this.instances.set(service.id, service);
645
3074
  return this;
646
3075
  }
3076
+ unregister(serviceId) {
3077
+ const removed = this.instances.delete(serviceId);
3078
+ this.registry.unregister(serviceId);
3079
+ return removed;
3080
+ }
647
3081
  get(serviceId) {
648
3082
  return this.instances.get(serviceId);
649
3083
  }
3084
+ list() {
3085
+ return Array.from(this.instances.values());
3086
+ }
650
3087
  async execute(target, operation, input, ctx) {
651
3088
  const service = this.instances.get(target);
652
3089
  if (!service) {
653
- throw new Error(`[ServiceRuntime] Target service '${target}' not found.`);
3090
+ throw new Error("[ServiceRuntime] Target service '" + target + "' not found.");
654
3091
  }
655
- return await service.call(operation, input, ctx);
3092
+ return service.call(operation, input, ctx);
656
3093
  }
657
3094
  async startAll() {
658
- for (const service of this.instances.values()) {
659
- await service.start();
3095
+ const started = [];
3096
+ try {
3097
+ for (const service of this.instances.values()) {
3098
+ await service.start();
3099
+ started.push(service);
3100
+ }
3101
+ } catch (error) {
3102
+ for (const service of started.reverse()) {
3103
+ try {
3104
+ await service.stop();
3105
+ } catch {
3106
+ }
3107
+ }
3108
+ throw error;
3109
+ }
3110
+ }
3111
+ async disposeAll() {
3112
+ let firstError;
3113
+ const services = Array.from(this.instances.values()).reverse();
3114
+ for (const service of services) {
3115
+ try {
3116
+ await service.dispose();
3117
+ } catch (error) {
3118
+ firstError ??= error;
3119
+ }
660
3120
  }
3121
+ if (firstError) throw firstError;
661
3122
  }
662
3123
  async stopAll() {
663
- for (const service of this.instances.values()) {
664
- await service.stop();
3124
+ let firstError;
3125
+ const services = Array.from(this.instances.values()).reverse();
3126
+ for (const service of services) {
3127
+ try {
3128
+ await service.stop();
3129
+ } catch (error) {
3130
+ firstError ??= error;
3131
+ }
665
3132
  }
3133
+ if (firstError) throw firstError;
666
3134
  }
667
3135
  };
668
3136
 
@@ -688,6 +3156,7 @@ var ServiceDiscovery = class {
688
3156
  // src/discovery/KrnlPackageReconciler.ts
689
3157
  import * as fs from "fs";
690
3158
  import * as path from "path";
3159
+ import { tryParseJson } from "@dinilmusick/gutts";
691
3160
  var KrnlPackageReconciler = class {
692
3161
  /**
693
3162
  * Scans all manifest.json files across backend and frontend and reconciles root package.json.
@@ -699,7 +3168,7 @@ var KrnlPackageReconciler = class {
699
3168
  for (const mPath of manifests) {
700
3169
  try {
701
3170
  const raw = fs.readFileSync(mPath, "utf8");
702
- const json = JSON.parse(raw);
3171
+ const json = tryParseJson(raw) ?? {};
703
3172
  if (json.dependencies && typeof json.dependencies === "object") {
704
3173
  for (const [pkg, ver] of Object.entries(json.dependencies)) {
705
3174
  if (!aggregatedDeps[pkg]) aggregatedDeps[pkg] = [];
@@ -773,10 +3242,13 @@ var KrnlPackageReconciler = class {
773
3242
  */
774
3243
  static findManifests(projectRoot) {
775
3244
  const searchDirs = [
3245
+ path.join(projectRoot, "krnl", "backend", "services"),
776
3246
  path.join(projectRoot, "krnl", "backend", "libraries"),
777
3247
  path.join(projectRoot, "krnl", "backend", "functionalities"),
778
3248
  path.join(projectRoot, "krnl", "frontend", "libraries"),
779
3249
  path.join(projectRoot, "krnl", "frontend", "functionalities"),
3250
+ path.join(projectRoot, "src", "backend", "services"),
3251
+ path.join(projectRoot, "src", "services"),
780
3252
  path.join(projectRoot, "src", "functionalities"),
781
3253
  path.join(projectRoot, "src", "libraries")
782
3254
  ];
@@ -816,15 +3288,301 @@ var ProtocolResolver = class {
816
3288
  return definition.protocols || ["http"];
817
3289
  }
818
3290
  };
3291
+
3292
+ // src/orchestration/FunctionalityOrchestration.ts
3293
+ var FunctionalityOrchestration = class {
3294
+ id;
3295
+ name;
3296
+ version;
3297
+ description;
3298
+ timeoutMs;
3299
+ scope = "functionality";
3300
+ steps = [];
3301
+ flows = /* @__PURE__ */ new Map();
3302
+ constructor(descriptor) {
3303
+ if (!descriptor || typeof descriptor !== "object" || !descriptor.id) {
3304
+ throw new Error("[FunctionalityOrchestration] Valid descriptor with non-empty id is required.");
3305
+ }
3306
+ this.id = descriptor.id;
3307
+ this.name = descriptor.name || descriptor.id;
3308
+ this.version = descriptor.version || "1.0.0";
3309
+ this.description = descriptor.description || "";
3310
+ this.timeoutMs = descriptor.timeoutMs;
3311
+ }
3312
+ /**
3313
+ * Adds a sequential functionality step to the DAG.
3314
+ */
3315
+ thenFunctionality(funcName, options = {}) {
3316
+ if (!funcName) {
3317
+ throw new Error("[FunctionalityOrchestration] Functionality name must be a non-empty string.");
3318
+ }
3319
+ if (typeof funcName !== "string") {
3320
+ if (typeof funcName === "object" && ("call" in funcName || "getStatus" in funcName || "definition" in funcName || "instance" in funcName || "id" in funcName)) {
3321
+ throw new Error(
3322
+ "[FunctionalityOrchestration] Invariant Violation: FunctionalityOrchestration only composes functionalities within the service, not independent services."
3323
+ );
3324
+ }
3325
+ throw new Error("[FunctionalityOrchestration] Functionality name must be a non-empty string.");
3326
+ }
3327
+ this.assertServiceBoundary(funcName);
3328
+ const stepId = options.id || `step_${funcName}_${this.steps.length + 1}`;
3329
+ const previousStep = this.steps.length > 0 ? this.steps[this.steps.length - 1].id : void 0;
3330
+ const dependsOn = options.dependsOn || (previousStep ? [previousStep] : []);
3331
+ const step = {
3332
+ id: stepId,
3333
+ name: funcName,
3334
+ type: "task",
3335
+ target: funcName,
3336
+ dependsOn,
3337
+ retryPolicy: options.retry,
3338
+ timeoutPolicy: options.timeoutMs ? { timeoutMs: options.timeoutMs } : void 0,
3339
+ compensation: options.compensation ? { name: options.compensation, target: options.compensation } : void 0,
3340
+ catchHandler: options.catchHandler
3341
+ };
3342
+ this.steps.push(step);
3343
+ return this;
3344
+ }
3345
+ /**
3346
+ * Adds parallel functionality steps to the DAG.
3347
+ */
3348
+ parallel(name, functionalityNames, options = {}) {
3349
+ if (!name || typeof name !== "string") {
3350
+ throw new Error("[FunctionalityOrchestration] Parallel group name must be a non-empty string.");
3351
+ }
3352
+ if (!functionalityNames || functionalityNames.length === 0) {
3353
+ throw new Error("[FunctionalityOrchestration] Parallel step requires at least one functionality.");
3354
+ }
3355
+ const previousStep = this.steps.length > 0 ? this.steps[this.steps.length - 1].id : void 0;
3356
+ const baseDependsOn = options.dependsOn || (previousStep ? [previousStep] : []);
3357
+ const parallelStepIds = [];
3358
+ for (const funcName of functionalityNames) {
3359
+ this.assertServiceBoundary(funcName);
3360
+ const stepId = `${name}_${funcName}`;
3361
+ parallelStepIds.push(stepId);
3362
+ this.steps.push({
3363
+ id: stepId,
3364
+ name: funcName,
3365
+ type: "task",
3366
+ target: funcName,
3367
+ dependsOn: baseDependsOn
3368
+ });
3369
+ }
3370
+ const joinId = `${name}_join`;
3371
+ this.steps.push({
3372
+ id: joinId,
3373
+ name: `${name} Join`,
3374
+ type: "fanIn",
3375
+ dependsOn: parallelStepIds
3376
+ });
3377
+ return this;
3378
+ }
3379
+ /**
3380
+ * Adds conditional branching to the DAG.
3381
+ */
3382
+ branch(name, condition, thenFunc, elseFunc, options = {}) {
3383
+ this.assertServiceBoundary(thenFunc);
3384
+ if (elseFunc) this.assertServiceBoundary(elseFunc);
3385
+ const previousStep = this.steps.length > 0 ? this.steps[this.steps.length - 1].id : void 0;
3386
+ const baseDependsOn = options.dependsOn || (previousStep ? [previousStep] : []);
3387
+ const thenStepId = `${name}_then_${thenFunc}`;
3388
+ this.steps.push({
3389
+ id: thenStepId,
3390
+ name: thenFunc,
3391
+ type: "task",
3392
+ target: thenFunc,
3393
+ condition,
3394
+ dependsOn: baseDependsOn
3395
+ });
3396
+ let joinDeps = [thenStepId];
3397
+ if (elseFunc) {
3398
+ const elseStepId = `${name}_else_${elseFunc}`;
3399
+ this.steps.push({
3400
+ id: elseStepId,
3401
+ name: elseFunc,
3402
+ type: "task",
3403
+ target: elseFunc,
3404
+ condition: async (ctx) => !await condition(ctx),
3405
+ dependsOn: baseDependsOn
3406
+ });
3407
+ joinDeps.push(elseStepId);
3408
+ }
3409
+ const joinId = `${name}_join`;
3410
+ this.steps.push({
3411
+ id: joinId,
3412
+ name: `${name} Join`,
3413
+ type: "fanIn",
3414
+ dependsOn: joinDeps
3415
+ });
3416
+ return this;
3417
+ }
3418
+ /**
3419
+ * Adds fan-out step processing items through a functionality.
3420
+ */
3421
+ fanOut(name, funcName, getItems, options = {}) {
3422
+ this.assertServiceBoundary(funcName);
3423
+ const previousStep = this.steps.length > 0 ? this.steps[this.steps.length - 1].id : void 0;
3424
+ const dependsOn = options.dependsOn || (previousStep ? [previousStep] : []);
3425
+ this.steps.push({
3426
+ id: name,
3427
+ name,
3428
+ type: "fanOut",
3429
+ target: funcName,
3430
+ getItems,
3431
+ concurrency: options.concurrency ?? 5,
3432
+ dependsOn
3433
+ });
3434
+ return this;
3435
+ }
3436
+ /**
3437
+ * Nested orchestration: Invokes a child FunctionalityOrchestration within the same service boundary.
3438
+ */
3439
+ thenFunctionalityOrchestration(childOrchId, options = {}) {
3440
+ if (!childOrchId || typeof childOrchId !== "string") {
3441
+ throw new Error("[FunctionalityOrchestration] Child orchestration id must be a non-empty string.");
3442
+ }
3443
+ const stepId = options.id || `nested_${childOrchId}_${this.steps.length + 1}`;
3444
+ const previousStep = this.steps.length > 0 ? this.steps[this.steps.length - 1].id : void 0;
3445
+ const dependsOn = options.dependsOn || (previousStep ? [previousStep] : []);
3446
+ this.steps.push({
3447
+ id: stepId,
3448
+ name: childOrchId,
3449
+ type: "nested",
3450
+ nestedOrchestrationId: childOrchId,
3451
+ dependsOn,
3452
+ retryPolicy: options.retry,
3453
+ timeoutPolicy: options.timeoutMs ? { timeoutMs: options.timeoutMs } : void 0
3454
+ });
3455
+ return this;
3456
+ }
3457
+ getSteps() {
3458
+ return Object.freeze([...this.steps]);
3459
+ }
3460
+ /**
3461
+ * Converts this FunctionalityOrchestration to a pure serializable OrchestrationDefinition.
3462
+ */
3463
+ toDefinition() {
3464
+ return {
3465
+ id: this.id,
3466
+ name: this.name,
3467
+ version: this.version,
3468
+ description: this.description,
3469
+ timeoutMs: this.timeoutMs,
3470
+ scope: "functionality",
3471
+ dependencies: [],
3472
+ steps: this.steps.map((s) => ({
3473
+ id: s.id,
3474
+ name: s.name,
3475
+ type: s.type,
3476
+ target: s.target,
3477
+ dependsOn: s.dependsOn ? [...s.dependsOn] : void 0,
3478
+ retryPolicy: s.retryPolicy ? { ...s.retryPolicy } : void 0,
3479
+ timeoutPolicy: s.timeoutPolicy ? { ...s.timeoutPolicy } : void 0,
3480
+ compensationTarget: s.compensation?.target ?? s.compensation?.name,
3481
+ compensationOperation: s.compensation?.operation ?? s.compensation?.name,
3482
+ nestedOrchestrationId: s.nestedOrchestrationId,
3483
+ concurrency: s.concurrency
3484
+ }))
3485
+ };
3486
+ }
3487
+ /**
3488
+ * Named flow builder interface.
3489
+ */
3490
+ flow(name) {
3491
+ if (!name || typeof name !== "string" || name.trim() === "") {
3492
+ throw new Error("[FunctionalityOrchestration] Flow name must be a non-empty string.");
3493
+ }
3494
+ const steps = [];
3495
+ const self = this;
3496
+ const flowInstance = {
3497
+ name,
3498
+ steps,
3499
+ visibility: "internal",
3500
+ thenFunctionality(funcName, options) {
3501
+ if (!funcName) {
3502
+ throw new Error("[FunctionalityFlow] Functionality name must be a non-empty string.");
3503
+ }
3504
+ if (typeof funcName !== "string") {
3505
+ if (typeof funcName === "object" && ("call" in funcName || "getStatus" in funcName || "definition" in funcName || "instance" in funcName || "id" in funcName)) {
3506
+ throw new Error(
3507
+ "[FunctionalityOrchestration] Invariant Violation: FunctionalityOrchestration only composes functionalities within the service, not independent services."
3508
+ );
3509
+ }
3510
+ throw new Error("[FunctionalityFlow] Functionality name must be a non-empty string.");
3511
+ }
3512
+ self.assertServiceBoundary(funcName);
3513
+ const stepId = `${name}_${funcName}_${steps.length + 1}`;
3514
+ steps.push({
3515
+ id: stepId,
3516
+ type: "functionality",
3517
+ target: funcName,
3518
+ dependsOn: options?.dependsOn,
3519
+ retryPolicy: options?.retry,
3520
+ timeoutPolicy: options?.timeoutMs ? { timeoutMs: options?.timeoutMs } : void 0
3521
+ });
3522
+ self.thenFunctionality(funcName, {
3523
+ id: stepId,
3524
+ retry: options?.retry,
3525
+ timeoutMs: options?.timeoutMs,
3526
+ dependsOn: options?.dependsOn
3527
+ });
3528
+ return flowInstance;
3529
+ },
3530
+ thenFunctionalityOrchestration(childName, flowName) {
3531
+ if (!childName || typeof childName !== "string") {
3532
+ throw new Error("[FunctionalityFlow] Orchestration name must be a non-empty string.");
3533
+ }
3534
+ const stepId = `${name}_orch_${childName}_${steps.length + 1}`;
3535
+ steps.push({
3536
+ id: stepId,
3537
+ type: "functionalityOrchestration",
3538
+ target: childName,
3539
+ flow: flowName
3540
+ });
3541
+ self.thenFunctionalityOrchestration(childName, { id: stepId });
3542
+ return flowInstance;
3543
+ },
3544
+ register(options) {
3545
+ if (options?.visibility) flowInstance.visibility = options.visibility;
3546
+ return flowInstance;
3547
+ }
3548
+ };
3549
+ this.flows.set(name, flowInstance);
3550
+ return flowInstance;
3551
+ }
3552
+ getFlow(name) {
3553
+ return this.flows.get(name);
3554
+ }
3555
+ listFlows() {
3556
+ return Array.from(this.flows.values());
3557
+ }
3558
+ clearFlows() {
3559
+ this.flows.clear();
3560
+ this.steps.length = 0;
3561
+ }
3562
+ assertServiceBoundary(target) {
3563
+ if (target.endsWith("ServiceFacade") || target.startsWith("service.") || target.includes("Service.") || target.endsWith("Service") && !target.includes("Functionality") && !target.includes("Atom") || target.startsWith("Service") && !target.includes("Functionality") && !target.includes("Atom")) {
3564
+ throw new Error(
3565
+ `[FunctionalityOrchestration] Plane Isolation Invariant Violation: Invariant Violation: FunctionalityOrchestration only composes functionalities within the service, not independent services. External Service composition is forbidden. Target "${target}" is not an internal functionality.`
3566
+ );
3567
+ }
3568
+ }
3569
+ };
3570
+
3571
+ // src/index.ts
3572
+ import * as gutts from "@dinilmusick/gutts";
819
3573
  export {
3574
+ FunctionalityOrchestration,
820
3575
  HttpProtocolAdapter,
821
3576
  KrnlPackageReconciler,
3577
+ KrnlQueue,
3578
+ KrnlWorkerPool,
822
3579
  LifecycleManager,
823
3580
  MemoryTransport,
824
3581
  P2PProtocolAdapter,
825
3582
  ProtocolResolver,
826
3583
  ServiceDiscovery,
827
3584
  ServiceEventBus,
3585
+ ServiceFacade,
828
3586
  ServiceInstance,
829
3587
  ServiceProxy,
830
3588
  ServiceRegistry,
@@ -832,7 +3590,12 @@ export {
832
3590
  ServiceStateStore,
833
3591
  UdpProtocolAdapter,
834
3592
  WebSocketProtocolAdapter,
3593
+ WorkerExecutionBoundary,
835
3594
  createService,
836
3595
  createServiceDefinition,
837
- createServiceProxy
3596
+ createServiceFacade,
3597
+ createServiceProxy,
3598
+ gutts,
3599
+ validateOrchestrationDAG,
3600
+ validateServiceDefinition
838
3601
  };