@ultrst-armada/krnl 1.0.2 → 1.0.3

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 +12 -8
  3. package/packages/cli/dist/bin/krnl.cjs +793 -330
  4. package/packages/cli/dist/bin/krnl.js +50 -65
  5. package/packages/cli/dist/chunk-6SHSECXR.js +1628 -0
  6. package/packages/cli/dist/index.cjs +746 -262
  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 +2905 -139
  12. package/packages/core/dist/index.d.cts +611 -27
  13. package/packages/core/dist/index.d.ts +611 -27
  14. package/packages/core/dist/index.js +2897 -139
  15. package/packages/core/package.json +14 -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
@@ -1,2777 +0,0 @@
1
- import {
2
- FileLock,
3
- KrnlFS,
4
- KrnlHTTP,
5
- ObjectKit
6
- } from "./chunk-MLVWARD4.js";
7
- import {
8
- KrnlTelemetry,
9
- telemetry
10
- } from "./chunk-DI27MOR7.js";
11
-
12
- // src/core/K_LIB_Krnl_Error_Concepts.ts
13
- var krnlErrorCodes = Object.freeze({
14
- // Enum errors (0-99)
15
- ENUM_ID_NOT_FOUND: -1,
16
- // State errors (100-199)
17
- STATE_NOT_FOUND: 100,
18
- STATE_DUPLICATE_NAME: 101,
19
- STATE_INDEX_OUT_OF_RANGE: 102,
20
- // Functionality errors (200-299)
21
- FUNCTIONALITY_NOT_DEFINED: 200,
22
- FUNCTIONALITY_ALREADY_DEFINED: 201,
23
- FUNCTIONALITY_INSTANCE_NOT_FOUND: 202,
24
- REMOTE_EXECUTION_FAILED: 203,
25
- // Interface errors (300-399)
26
- EMITTER_NOT_FOUND: 300,
27
- COLLECTOR_NOT_FOUND: 301,
28
- COLLECTOR_NOT_SUBSCRIBED: 302,
29
- // Hierarchy errors (400-499)
30
- ENTITY_NOT_FOUND: 400,
31
- // Networking/RPC errors (500-599)
32
- ERR_NET_RPC_TIMEOUT_EXCEEDED: 500,
33
- ERR_NET_RPC_NETWORK_ERROR: 501,
34
- ERR_NET_RPC_INTERNAL_SERVER_ERROR: 502,
35
- ERR_SYS_ENTITY_BUSY_RESERVED: 503,
36
- ERR_COM_INGRESS_ROUTE_NOT_FOUND: 504,
37
- ERR_KRNL_UNRESOLVED_REMOTE_TARGET: 505
38
- });
39
- var krnlErrorMessages = Object.freeze({
40
- // Enum
41
- [krnlErrorCodes.ENUM_ID_NOT_FOUND]: "ERR_LIB_ENUM_ID_NOT_FOUND",
42
- // State
43
- [krnlErrorCodes.STATE_NOT_FOUND]: "ERR_LIB_STATE_NOT_FOUND",
44
- [krnlErrorCodes.STATE_DUPLICATE_NAME]: "ERR_LIB_STATE_DUPLICATE_NAME",
45
- [krnlErrorCodes.STATE_INDEX_OUT_OF_RANGE]: "ERR_LIB_STATE_INDEX_OUT_OF_RANGE",
46
- // Functionality
47
- [krnlErrorCodes.FUNCTIONALITY_NOT_DEFINED]: "ERR_LIB_FUNCTIONALITY_NOT_DEFINED",
48
- [krnlErrorCodes.FUNCTIONALITY_ALREADY_DEFINED]: "ERR_LIB_FUNCTIONALITY_ALREADY_DEFINED",
49
- [krnlErrorCodes.FUNCTIONALITY_INSTANCE_NOT_FOUND]: "ERR_LIB_FUNCTIONALITY_INSTANCE_NOT_FOUND",
50
- [krnlErrorCodes.REMOTE_EXECUTION_FAILED]: "ERR_LIB_REMOTE_EXECUTION_FAILED",
51
- // Interface
52
- [krnlErrorCodes.EMITTER_NOT_FOUND]: "ERR_INT_EMITTER_NOT_FOUND",
53
- [krnlErrorCodes.COLLECTOR_NOT_FOUND]: "ERR_INT_COLLECTOR_NOT_FOUND",
54
- [krnlErrorCodes.COLLECTOR_NOT_SUBSCRIBED]: "ERR_INT_COLLECTOR_NOT_SUBSCRIBED",
55
- // Hierarchy
56
- [krnlErrorCodes.ENTITY_NOT_FOUND]: "ERR_SYS_ENTITY_NOT_FOUND",
57
- // Networking/RPC
58
- [krnlErrorCodes.ERR_NET_RPC_TIMEOUT_EXCEEDED]: "ERR_NET_RPC_TIMEOUT_EXCEEDED",
59
- [krnlErrorCodes.ERR_NET_RPC_NETWORK_ERROR]: "ERR_NET_RPC_NETWORK_ERROR",
60
- [krnlErrorCodes.ERR_NET_RPC_INTERNAL_SERVER_ERROR]: "ERR_NET_RPC_INTERNAL_SERVER_ERROR",
61
- [krnlErrorCodes.ERR_SYS_ENTITY_BUSY_RESERVED]: "ERR_SYS_ENTITY_BUSY_RESERVED",
62
- [krnlErrorCodes.ERR_COM_INGRESS_ROUTE_NOT_FOUND]: "ERR_COM_INGRESS_ROUTE_NOT_FOUND",
63
- [krnlErrorCodes.ERR_KRNL_UNRESOLVED_REMOTE_TARGET]: "ERR_KRNL_UNRESOLVED_REMOTE_TARGET"
64
- });
65
- var CUSTOM_ERROR_CODE = -999;
66
- var krnlError = class extends Error {
67
- code;
68
- errorMessage;
69
- constructor(code) {
70
- const isNumeric = typeof code === "number";
71
- const numericCode = isNumeric ? code : CUSTOM_ERROR_CODE;
72
- const message = isNumeric ? krnlErrorMessages[numericCode] ?? `Error: ${code}` : code;
73
- super(message);
74
- this.code = numericCode;
75
- this.errorMessage = this.message;
76
- }
77
- };
78
-
79
- // src/core/K_LIB_Krnl_Messaging_Concepts.ts
80
- var krnlGlobalEmitterAddress = class {
81
- systemID = 0;
82
- // ["qwnsr", "brnda", "symba", "mosy"]
83
- subSystemID = 0;
84
- // ["qwnsrControl", "qwnsrBlocks"]
85
- entityAddress = [];
86
- // nesting of type
87
- emitterID = 0;
88
- };
89
- var krnlLocalEmitterAddress = class {
90
- isOwnerEntity = true;
91
- siblingID = 0;
92
- emitterID = 0;
93
- };
94
- var krnlMessage = class {
95
- data = null;
96
- timestamp = 0;
97
- // Tracing metadata aligned with core lingo
98
- sourceEmitterAddress = null;
99
- targetCollectorAddress = null;
100
- traceCorrelationId = null;
101
- originSystemAddress = null;
102
- };
103
- var krnlEmitter = class {
104
- subscribers;
105
- localAddress;
106
- constructor() {
107
- this.subscribers = [];
108
- this.localAddress = null;
109
- }
110
- /**
111
- * Pushes data into the emitter and notifies all subscribers.
112
- */
113
- pushDataStreamToEmitter(data, time = {}, transform = (msg) => msg) {
114
- const msg = new krnlMessage();
115
- msg.data = data;
116
- msg.timestamp = typeof time === "number" ? time : time?.timestamp || Date.now();
117
- const transformed = transform(msg);
118
- for (let i = 0; i < this.subscribers.length; i++) {
119
- this.subscribers[i](transformed);
120
- }
121
- }
122
- /**
123
- * Subscribes a handler to this emitter. Handler is called on every push.
124
- */
125
- subscribe(handler) {
126
- this.subscribers.push(handler);
127
- return () => {
128
- const idx = this.subscribers.indexOf(handler);
129
- if (idx >= 0) this.subscribers.splice(idx, 1);
130
- };
131
- }
132
- /**
133
- * Subscribes once and auto-unsubscribes after first message.
134
- */
135
- subscribeOnce(handler) {
136
- let unsubscribe = null;
137
- const wrapped = (msg) => {
138
- if (unsubscribe) unsubscribe();
139
- handler(msg);
140
- };
141
- unsubscribe = this.subscribe(wrapped);
142
- return unsubscribe;
143
- }
144
- /**
145
- * Resets the emitter and removes all subscribers.
146
- */
147
- disconnectEmitter() {
148
- this.subscribers = [];
149
- }
150
- };
151
- var krnlCollector = class {
152
- emitter;
153
- unsubscribe;
154
- _directHandler;
155
- constructor() {
156
- this.emitter = null;
157
- this.unsubscribe = null;
158
- }
159
- /**
160
- * Subscribes this collector to an emitter. Messages are forwarded to the handler.
161
- */
162
- subscribeTo(emitter, handler = null, options = {}) {
163
- const { mode = "stream" } = options;
164
- const resolvedHandler = typeof handler === "function" ? handler : (msg) => {
165
- if (typeof this._directHandler === "function") {
166
- return this._directHandler(msg);
167
- }
168
- return msg;
169
- };
170
- this.disconnectCollector();
171
- this.emitter = emitter;
172
- this.unsubscribe = mode === "once" ? emitter.subscribeOnce(resolvedHandler) : emitter.subscribe(resolvedHandler);
173
- return this.unsubscribe;
174
- }
175
- /**
176
- * Collects a single message from the emitter and auto-disconnects.
177
- */
178
- collectNext(emitter, timeoutMs = null) {
179
- return new Promise((resolve, reject) => {
180
- let timeout = null;
181
- const cleanup = () => {
182
- if (timeout) clearTimeout(timeout);
183
- this.disconnectCollector();
184
- };
185
- this.subscribeTo(emitter, (msg) => {
186
- cleanup();
187
- resolve(msg);
188
- }, { mode: "once" });
189
- if (typeof timeoutMs === "number" && timeoutMs > 0) {
190
- timeout = setTimeout(() => {
191
- cleanup();
192
- reject(new Error(`Collector timeout after ${timeoutMs}ms`));
193
- }, timeoutMs);
194
- }
195
- });
196
- }
197
- /**
198
- * Pipes messages from a connected emitter through a transform function.
199
- */
200
- pipeTo(target, fn) {
201
- const pipeEmitter = new krnlEmitter();
202
- this.emitter = pipeEmitter;
203
- const unsub = pipeEmitter.subscribe((msg) => {
204
- fn(msg);
205
- });
206
- this.unsubscribe = unsub;
207
- return () => {
208
- this.disconnectCollector();
209
- };
210
- }
211
- /**
212
- * Pushes data directly into this collector's connected emitter.
213
- */
214
- pushDataStreamToEmitter(data) {
215
- if (this.emitter === null) {
216
- throw new krnlError(krnlErrorCodes.COLLECTOR_NOT_SUBSCRIBED);
217
- }
218
- this.emitter.pushDataStreamToEmitter(data);
219
- }
220
- /**
221
- * Disconnects from the current emitter.
222
- */
223
- disconnectCollector() {
224
- if (this.unsubscribe) {
225
- this.unsubscribe();
226
- this.unsubscribe = null;
227
- this.emitter = null;
228
- }
229
- }
230
- };
231
- var krnlInterface = class {
232
- ownerEntity;
233
- emitters;
234
- collectors;
235
- constructor(ownerEntity) {
236
- this.ownerEntity = ownerEntity;
237
- this.emitters = /* @__PURE__ */ new Map();
238
- this.collectors = /* @__PURE__ */ new Map();
239
- }
240
- /**
241
- * Creates and registers a new emitter.
242
- */
243
- createEmitter(name) {
244
- const emitter = new krnlEmitter();
245
- this.emitters.set(name, emitter);
246
- emitter.localAddress = {
247
- isOwnerEntity: false,
248
- siblingID: 0,
249
- emitterID: this.emitters.size - 1
250
- };
251
- return emitter;
252
- }
253
- /**
254
- * Creates and registers a new collector.
255
- */
256
- createCollector(name) {
257
- const collector = new krnlCollector();
258
- this.collectors.set(name, collector);
259
- return collector;
260
- }
261
- /**
262
- * Gets an emitter by name.
263
- */
264
- getEmitter(name) {
265
- const emitter = this.emitters.get(name);
266
- if (!emitter) throw new krnlError(krnlErrorCodes.EMITTER_NOT_FOUND);
267
- return emitter;
268
- }
269
- /**
270
- * Gets a collector by name.
271
- */
272
- getCollector(name) {
273
- const collector = this.collectors.get(name);
274
- if (!collector) throw new krnlError(krnlErrorCodes.COLLECTOR_NOT_FOUND);
275
- return collector;
276
- }
277
- /**
278
- * Removes an emitter by name.
279
- */
280
- removeEmitter(name) {
281
- const emitter = this.emitters.get(name);
282
- if (emitter) {
283
- emitter.disconnectEmitter();
284
- this.emitters.delete(name);
285
- }
286
- }
287
- /**
288
- * Removes a collector by name.
289
- */
290
- removeCollector(name) {
291
- const collector = this.collectors.get(name);
292
- if (collector) {
293
- collector.disconnectCollector();
294
- this.collectors.delete(name);
295
- }
296
- }
297
- /**
298
- * Gets all emitters in scope (self + owner + siblings).
299
- */
300
- getEmittersInScope() {
301
- const interfaces = this.getInterfacesInScope();
302
- const result = [];
303
- for (let i = 0; i < interfaces.length; i++) {
304
- for (const emitter of interfaces[i].emitters.values()) {
305
- result.push(emitter);
306
- }
307
- }
308
- return result;
309
- }
310
- /**
311
- * Gets all interfaces in scope (self, owner, and siblings).
312
- */
313
- getInterfacesInScope() {
314
- const owner = this.ownerEntity.hierarchyManager ? this.ownerEntity.hierarchyManager.getOwnerEntity() : null;
315
- if (!owner) return [this];
316
- const scopes = [this];
317
- if (owner.interface) scopes.push(owner.interface);
318
- const siblings = owner.hierarchyManager ? owner.hierarchyManager.getAllOwnedComponentEntities() : [];
319
- for (let i = 0; i < siblings.length; i++) {
320
- if (siblings[i] !== this.ownerEntity && siblings[i].interface) {
321
- scopes.push(siblings[i].interface);
322
- }
323
- }
324
- return scopes;
325
- }
326
- /**
327
- * Disconnects all emitters and collectors.
328
- */
329
- dispose() {
330
- for (const emitter of this.emitters.values()) {
331
- emitter.disconnectEmitter();
332
- }
333
- for (const collector of this.collectors.values()) {
334
- collector.disconnectCollector();
335
- }
336
- this.emitters.clear();
337
- this.collectors.clear();
338
- }
339
- };
340
-
341
- // src/core/K_LIB_Krnl_Entity_Compositional_Hierarchy.ts
342
- var krnlEntityCompositionalHierarchyManager = class {
343
- self;
344
- owner;
345
- EntityClass;
346
- ownedComponents;
347
- componentBaseNames;
348
- componentInstanceCounters;
349
- /**
350
- * @param self - The entity this manager belongs to.
351
- * @param owner - The parent entity (if any).
352
- * @param EntityClass - Reference to the Entity base class for instantiation.
353
- */
354
- constructor(self, owner, EntityClass) {
355
- this.self = self;
356
- this.owner = owner;
357
- this.EntityClass = EntityClass;
358
- this.ownedComponents = /* @__PURE__ */ new Map();
359
- this.componentBaseNames = /* @__PURE__ */ new Map();
360
- this.componentInstanceCounters = /* @__PURE__ */ new Map();
361
- }
362
- /**
363
- * Spawns a unique component entity within this host.
364
- */
365
- createComponentEntity(name, CustomClass = null, options = {}) {
366
- const ClassToUse = CustomClass || this.EntityClass;
367
- const shouldBeSingleton = options.Singleton ?? ClassToUse.Singleton ?? true;
368
- if (shouldBeSingleton && this.ownedComponents.has(name)) {
369
- return this.ownedComponents.get(name);
370
- }
371
- const currentCount = this.componentInstanceCounters.get(name) || 0;
372
- const nextCount = currentCount + 1;
373
- this.componentInstanceCounters.set(name, nextCount);
374
- const resolvedName = shouldBeSingleton ? name : `${name}#${nextCount}`;
375
- const newEntity = new ClassToUse(resolvedName, this.self, {
376
- Singleton: shouldBeSingleton,
377
- baseName: name,
378
- instanceNumber: nextCount
379
- });
380
- this.ownedComponents.set(resolvedName, newEntity);
381
- const group = this.componentBaseNames.get(name) || [];
382
- group.push(newEntity);
383
- this.componentBaseNames.set(name, group);
384
- if (this.self._onComponentAdded) {
385
- this.self._onComponentAdded(newEntity);
386
- }
387
- return newEntity;
388
- }
389
- /**
390
- * Registers a pre-existing entity instance as a component of this host.
391
- */
392
- addComponentEntityInstance(instance) {
393
- this.ownedComponents.set(instance.id, instance);
394
- instance.hierarchyManager.owner = this.self;
395
- const base = instance.baseName || instance.id;
396
- const group = this.componentBaseNames.get(base) || [];
397
- group.push(instance);
398
- this.componentBaseNames.set(base, group);
399
- if (typeof instance._onAdoptedByParent === "function") {
400
- try {
401
- const p = instance._onAdoptedByParent();
402
- if (p && typeof p.catch === "function") {
403
- p.catch((err) => console.warn(`[Hierarchy] Error in _onAdoptedByParent on '${instance.id}':`, err.message || err));
404
- }
405
- } catch (err) {
406
- console.warn(`[Hierarchy] Error in _onAdoptedByParent on '${instance.id}':`, err.message || err);
407
- }
408
- }
409
- if (instance._promoteAllExistingFunctionalities) {
410
- instance._promoteAllExistingFunctionalities();
411
- }
412
- }
413
- /**
414
- * Returns a list of all component entities owned by this host.
415
- */
416
- getAllOwnedComponentEntities() {
417
- return Array.from(this.ownedComponents.values());
418
- }
419
- /**
420
- * Returns all component entity instances created from the same base component name.
421
- */
422
- getOwnedComponentEntitiesByName(name) {
423
- return [...this.componentBaseNames.get(name) || []];
424
- }
425
- /**
426
- * Returns the parent entity.
427
- */
428
- getOwnerEntity() {
429
- return this.owner;
430
- }
431
- /**
432
- * Recursively disposes of all owned components.
433
- */
434
- dispose() {
435
- this.ownedComponents.forEach((entity) => {
436
- if (entity.dispose) entity.dispose();
437
- });
438
- this.ownedComponents.clear();
439
- this.componentBaseNames.clear();
440
- this.componentInstanceCounters.clear();
441
- }
442
- /**
443
- * Disposes a specific component instance by ID/name.
444
- */
445
- disposeComponentEntity(entityId) {
446
- const entity = this.ownedComponents.get(entityId);
447
- if (!entity) return false;
448
- if (entity.dispose) entity.dispose();
449
- this.ownedComponents.delete(entityId);
450
- const base = entity.baseName || entity.entityName;
451
- const group = this.componentBaseNames.get(base) || [];
452
- this.componentBaseNames.set(base, group.filter((e) => e !== entity));
453
- return true;
454
- }
455
- };
456
-
457
- // src/backend/FunctionalityTable.ts
458
- var FunctionalityTable = class {
459
- tableName;
460
- service;
461
- provider;
462
- isTableInitialized = false;
463
- constructor(tableName, provider) {
464
- this.tableName = tableName;
465
- this.provider = provider;
466
- this.service = provider.engine;
467
- }
468
- async ensureInitialized() {
469
- if (!this.isTableInitialized) {
470
- await this.provider.ensureTable(this.tableName);
471
- this.isTableInitialized = true;
472
- }
473
- }
474
- async find(filter, options) {
475
- await this.ensureInitialized();
476
- return await this.provider.find(this.tableName, filter, options);
477
- }
478
- async findOne(filter) {
479
- await this.ensureInitialized();
480
- return await this.provider.findOne(this.tableName, filter);
481
- }
482
- async create(record) {
483
- await this.ensureInitialized();
484
- const result = await this.provider.insert(this.tableName, record);
485
- return Array.isArray(result) ? result[0] : result;
486
- }
487
- async insert(record) {
488
- await this.ensureInitialized();
489
- return await this.provider.insert(this.tableName, record);
490
- }
491
- async update(filter, patch) {
492
- await this.ensureInitialized();
493
- return await this.provider.update(this.tableName, filter, patch);
494
- }
495
- async delete(filter) {
496
- await this.ensureInitialized();
497
- return await this.provider.delete(this.tableName, filter);
498
- }
499
- async upsert(record, keyField = "id") {
500
- await this.ensureInitialized();
501
- const keyVal = record[keyField];
502
- if (keyVal !== void 0 && keyVal !== null) {
503
- const existing = await this.findOne({ [keyField]: keyVal });
504
- if (existing) {
505
- await this.update({ [keyField]: keyVal }, record);
506
- return { ...existing, ...record };
507
- }
508
- }
509
- return await this.create(record);
510
- }
511
- async count(filter) {
512
- await this.ensureInitialized();
513
- return await this.provider.count(this.tableName, filter);
514
- }
515
- async query(rawQueryOrFilter, params) {
516
- await this.ensureInitialized();
517
- if (typeof rawQueryOrFilter === "string") {
518
- return await this.provider.query(rawQueryOrFilter, params);
519
- }
520
- return await this.provider.find(this.tableName, rawQueryOrFilter);
521
- }
522
- async clear() {
523
- await this.ensureInitialized();
524
- await this.provider.clear(this.tableName);
525
- }
526
- };
527
-
528
- // src/backend/providers/data/SQLiteDataProvider.ts
529
- import path from "path";
530
- var SQLiteDataProvider = class {
531
- engine = "sqlite";
532
- filePath;
533
- enableWAL;
534
- isConnected = false;
535
- tables = /* @__PURE__ */ new Map();
536
- constructor(config = "./workspace.sqlite") {
537
- if (typeof config === "string") {
538
- this.filePath = path.resolve(config);
539
- this.enableWAL = true;
540
- } else {
541
- this.filePath = path.resolve(config.filePath || "./workspace.sqlite");
542
- this.enableWAL = config.enableWAL !== false;
543
- }
544
- }
545
- async connect() {
546
- if (this.isConnected) return;
547
- const dir = path.dirname(this.filePath);
548
- await KrnlFS.ensureDir(dir);
549
- if (await KrnlFS.fileExists(this.filePath)) {
550
- try {
551
- const raw = await KrnlFS.readJSON(this.filePath);
552
- if (raw && typeof raw === "object") {
553
- for (const [tbl, rows] of Object.entries(raw)) {
554
- if (Array.isArray(rows)) {
555
- this.tables.set(tbl, rows);
556
- }
557
- }
558
- }
559
- } catch {
560
- this.tables.clear();
561
- }
562
- }
563
- this.isConnected = true;
564
- }
565
- async disconnect() {
566
- if (!this.isConnected) return;
567
- await this.persist();
568
- this.isConnected = false;
569
- }
570
- async testConnection() {
571
- const t0 = Date.now();
572
- try {
573
- await this.connect();
574
- const latencyMs = Date.now() - t0;
575
- return {
576
- ok: true,
577
- latencyMs,
578
- details: {
579
- engine: "sqlite",
580
- filePath: this.filePath,
581
- wal: this.enableWAL,
582
- tablesCount: this.tables.size
583
- }
584
- };
585
- } catch (err) {
586
- return {
587
- ok: false,
588
- latencyMs: Date.now() - t0,
589
- details: { error: err.message }
590
- };
591
- }
592
- }
593
- async ensureTable(tableName, _schema) {
594
- await this.connect();
595
- if (!this.tables.has(tableName)) {
596
- this.tables.set(tableName, []);
597
- await this.persist();
598
- }
599
- }
600
- async persist() {
601
- const release = await FileLock.acquire(this.filePath);
602
- try {
603
- const dump = {};
604
- for (const [tbl, rows] of this.tables.entries()) {
605
- dump[tbl] = rows;
606
- }
607
- await KrnlFS.writeJSON(this.filePath, dump, 2);
608
- } finally {
609
- release();
610
- }
611
- }
612
- getTableRows(table) {
613
- if (!this.tables.has(table)) {
614
- this.tables.set(table, []);
615
- }
616
- return this.tables.get(table);
617
- }
618
- matchesFilter(row, filter) {
619
- if (typeof filter === "string") {
620
- return row.id === filter || row._id === filter;
621
- }
622
- if (!filter || Object.keys(filter).length === 0) return true;
623
- for (const [key, expected] of Object.entries(filter)) {
624
- const actual = row[key];
625
- if (expected && typeof expected === "object" && !Array.isArray(expected)) {
626
- if ("$gt" in expected && !(actual > expected.$gt)) return false;
627
- if ("$gte" in expected && !(actual >= expected.$gte)) return false;
628
- if ("$lt" in expected && !(actual < expected.$lt)) return false;
629
- if ("$lte" in expected && !(actual <= expected.$lte)) return false;
630
- if ("$ne" in expected && actual === expected.$ne) return false;
631
- if ("$in" in expected && Array.isArray(expected.$in) && !expected.$in.includes(actual)) return false;
632
- if ("$nin" in expected && Array.isArray(expected.$nin) && expected.$nin.includes(actual)) return false;
633
- } else if (actual !== expected) {
634
- return false;
635
- }
636
- }
637
- return true;
638
- }
639
- async find(table, filter, options) {
640
- await this.connect();
641
- const rows = this.getTableRows(table);
642
- let results = rows.filter((r) => this.matchesFilter(r, filter || {}));
643
- if (options?.sort) {
644
- const sortEntries = Object.entries(options.sort);
645
- results.sort((a, b) => {
646
- for (const [key, dir] of sortEntries) {
647
- if (a[key] < b[key]) return dir === 1 ? -1 : 1;
648
- if (a[key] > b[key]) return dir === 1 ? 1 : -1;
649
- }
650
- return 0;
651
- });
652
- }
653
- if (options?.offset) {
654
- results = results.slice(options.offset);
655
- }
656
- if (options?.limit) {
657
- results = results.slice(0, options.limit);
658
- }
659
- return ObjectKit.deepClone(results);
660
- }
661
- async findOne(table, filter) {
662
- const list = await this.find(table, typeof filter === "string" ? { id: filter } : filter, { limit: 1 });
663
- return list[0] || null;
664
- }
665
- async insert(table, data) {
666
- await this.connect();
667
- const rows = this.getTableRows(table);
668
- const items = Array.isArray(data) ? data : [data];
669
- const inserted = [];
670
- for (const item of items) {
671
- const record = ObjectKit.deepClone(item);
672
- if (!record.id && !record._id) {
673
- record.id = `rec_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
674
- }
675
- if (!record.createdAt) {
676
- record.createdAt = Date.now();
677
- }
678
- record.updatedAt = Date.now();
679
- rows.push(record);
680
- inserted.push(record);
681
- }
682
- await this.persist();
683
- return Array.isArray(data) ? inserted : inserted[0];
684
- }
685
- async update(table, filter, patch) {
686
- await this.connect();
687
- const rows = this.getTableRows(table);
688
- let affected = 0;
689
- for (let i = 0; i < rows.length; i++) {
690
- if (this.matchesFilter(rows[i], filter)) {
691
- rows[i] = ObjectKit.deepMerge(rows[i], {
692
- ...patch,
693
- updatedAt: Date.now()
694
- });
695
- affected++;
696
- }
697
- }
698
- if (affected > 0) {
699
- await this.persist();
700
- }
701
- return { affectedRows: affected };
702
- }
703
- async delete(table, filter) {
704
- await this.connect();
705
- const rows = this.getTableRows(table);
706
- const initialLen = rows.length;
707
- const remaining = rows.filter((r) => !this.matchesFilter(r, filter));
708
- const affected = initialLen - remaining.length;
709
- if (affected > 0) {
710
- this.tables.set(table, remaining);
711
- await this.persist();
712
- }
713
- return { affectedRows: affected };
714
- }
715
- async count(table, filter) {
716
- await this.connect();
717
- const rows = this.getTableRows(table);
718
- if (!filter || Object.keys(filter).length === 0) {
719
- return rows.length;
720
- }
721
- return rows.filter((r) => this.matchesFilter(r, filter)).length;
722
- }
723
- async clear(table) {
724
- await this.connect();
725
- this.tables.set(table, []);
726
- await this.persist();
727
- }
728
- async query(queryStr, _params) {
729
- await this.connect();
730
- const normalized = queryStr.trim().toLowerCase();
731
- if (normalized.startsWith("select * from")) {
732
- const parts = queryStr.trim().split(/\s+/);
733
- const tableName = parts[3]?.replace(/['";]/g, "");
734
- if (tableName) {
735
- return this.find(tableName);
736
- }
737
- }
738
- return [];
739
- }
740
- async execute(commandStr, _params) {
741
- await this.connect();
742
- const normalized = commandStr.trim().toLowerCase();
743
- if (normalized.startsWith("create table")) {
744
- const parts = commandStr.trim().split(/\s+/);
745
- const tableName = parts[2]?.replace(/['";(]/g, "");
746
- if (tableName) {
747
- await this.ensureTable(tableName);
748
- return { affectedRows: 0 };
749
- }
750
- }
751
- return { affectedRows: 0 };
752
- }
753
- };
754
-
755
- // src/backend/providers/data/PostgresDataProvider.ts
756
- var PostgresDataProvider = class {
757
- engine = "postgres";
758
- config;
759
- isConnected = false;
760
- constructor(config) {
761
- this.config = config;
762
- }
763
- async connect() {
764
- this.isConnected = true;
765
- }
766
- async disconnect() {
767
- this.isConnected = false;
768
- }
769
- async testConnection() {
770
- const t0 = Date.now();
771
- try {
772
- if (this.config.endpoint) {
773
- const res = await KrnlHTTP.get(this.config.endpoint, { timeout: 5e3 });
774
- return {
775
- ok: res.status === "success" || res.code === 200,
776
- latencyMs: Date.now() - t0,
777
- details: {
778
- engine: "postgres",
779
- endpoint: this.config.endpoint,
780
- ssl: this.config.ssl ?? true
781
- }
782
- };
783
- }
784
- const hasConnectionInfo = Boolean(
785
- this.config.connectionString || this.config.host && this.config.database
786
- );
787
- return {
788
- ok: hasConnectionInfo,
789
- latencyMs: Date.now() - t0,
790
- details: {
791
- engine: "postgres",
792
- host: this.config.host,
793
- database: this.config.database,
794
- ssl: this.config.ssl ?? true,
795
- poolSize: this.config.poolSize ?? 10
796
- }
797
- };
798
- } catch (err) {
799
- return {
800
- ok: false,
801
- latencyMs: Date.now() - t0,
802
- details: { error: err.message }
803
- };
804
- }
805
- }
806
- async ensureTable(_tableName, _schema) {
807
- }
808
- async find(_table, _filter, _options) {
809
- return [];
810
- }
811
- async findOne(_table, _filter) {
812
- return null;
813
- }
814
- async insert(_table, data) {
815
- return data;
816
- }
817
- async update(_table, _filter, _patch) {
818
- return { affectedRows: 0 };
819
- }
820
- async delete(_table, _filter) {
821
- return { affectedRows: 0 };
822
- }
823
- async count(_table, _filter) {
824
- return 0;
825
- }
826
- async clear(_table) {
827
- }
828
- async query(_queryStr, _params) {
829
- return [];
830
- }
831
- async execute(_commandStr, _params) {
832
- return { affectedRows: 0 };
833
- }
834
- };
835
-
836
- // src/backend/providers/data/SupabaseDataProvider.ts
837
- var SupabaseDataProvider = class {
838
- engine = "supabase";
839
- endpoint;
840
- apiKey;
841
- isConnected = false;
842
- constructor(config) {
843
- this.endpoint = (config.endpoint || "").replace(/\/+$/, "");
844
- this.apiKey = config.apiKey || "";
845
- }
846
- getHeaders() {
847
- return {
848
- "apikey": this.apiKey,
849
- "Authorization": `Bearer ${this.apiKey}`,
850
- "Content-Type": "application/json",
851
- "Prefer": "return=representation"
852
- };
853
- }
854
- async connect() {
855
- this.isConnected = true;
856
- }
857
- async disconnect() {
858
- this.isConnected = false;
859
- }
860
- async testConnection() {
861
- const t0 = Date.now();
862
- try {
863
- const res = await KrnlHTTP.get(`${this.endpoint}/rest/v1/`, {
864
- headers: this.getHeaders(),
865
- timeout: 5e3
866
- });
867
- const latencyMs = Date.now() - t0;
868
- return {
869
- ok: res.status === "success" || res.code === 200 || res.code === 404,
870
- latencyMs,
871
- details: {
872
- engine: "supabase",
873
- endpoint: this.endpoint,
874
- status: res.status,
875
- code: res.code
876
- }
877
- };
878
- } catch (err) {
879
- return {
880
- ok: false,
881
- latencyMs: Date.now() - t0,
882
- details: { error: err.message }
883
- };
884
- }
885
- }
886
- async ensureTable(_tableName, _schema) {
887
- }
888
- buildQueryString(filter, options) {
889
- const params = [];
890
- if (filter) {
891
- for (const [key, val] of Object.entries(filter)) {
892
- if (val === null || val === void 0) {
893
- params.push(`${key}=is.null`);
894
- } else if (typeof val === "object") {
895
- if ("$gt" in val) params.push(`${key}=gt.${encodeURIComponent(val.$gt)}`);
896
- if ("$gte" in val) params.push(`${key}=gte.${encodeURIComponent(val.$gte)}`);
897
- if ("$lt" in val) params.push(`${key}=lt.${encodeURIComponent(val.$lt)}`);
898
- if ("$lte" in val) params.push(`${key}=lte.${encodeURIComponent(val.$lte)}`);
899
- if ("$ne" in val) params.push(`${key}=neq.${encodeURIComponent(val.$ne)}`);
900
- } else {
901
- params.push(`${key}=eq.${encodeURIComponent(String(val))}`);
902
- }
903
- }
904
- }
905
- if (options?.limit) {
906
- params.push(`limit=${options.limit}`);
907
- }
908
- if (options?.offset) {
909
- params.push(`offset=${options.offset}`);
910
- }
911
- if (options?.sort) {
912
- const order = Object.entries(options.sort).map(([col, dir]) => `${col}.${dir === 1 ? "asc" : "desc"}`).join(",");
913
- params.push(`order=${order}`);
914
- }
915
- return params.length > 0 ? `?${params.join("&")}` : "";
916
- }
917
- async find(table, filter, options) {
918
- const qs = this.buildQueryString(filter, options);
919
- const url = `${this.endpoint}/rest/v1/${table}${qs}`;
920
- const res = await KrnlHTTP.get(url, { headers: this.getHeaders() });
921
- if (res.status === "success" && Array.isArray(res.data)) {
922
- return res.data;
923
- }
924
- return [];
925
- }
926
- async findOne(table, filter) {
927
- const filterObj = typeof filter === "string" ? { id: filter } : filter;
928
- const list = await this.find(table, filterObj, { limit: 1 });
929
- return list[0] || null;
930
- }
931
- async insert(table, data) {
932
- const url = `${this.endpoint}/rest/v1/${table}`;
933
- const res = await KrnlHTTP.post(url, data, { headers: this.getHeaders() });
934
- if (res.status === "success" && res.data) {
935
- return Array.isArray(data) ? res.data : res.data[0];
936
- }
937
- return data;
938
- }
939
- async update(table, filter, patch) {
940
- const filterObj = typeof filter === "string" ? { id: filter } : filter;
941
- const qs = this.buildQueryString(filterObj);
942
- const url = `${this.endpoint}/rest/v1/${table}${qs}`;
943
- const res = await KrnlHTTP.request(url, {
944
- method: "PATCH",
945
- headers: this.getHeaders(),
946
- body: JSON.stringify(patch)
947
- });
948
- const affected = res.status === "success" && Array.isArray(res.data) ? res.data.length : 0;
949
- return { affectedRows: affected };
950
- }
951
- async delete(table, filter) {
952
- const filterObj = typeof filter === "string" ? { id: filter } : filter;
953
- const qs = this.buildQueryString(filterObj);
954
- const url = `${this.endpoint}/rest/v1/${table}${qs}`;
955
- const res = await KrnlHTTP.del(url, { headers: this.getHeaders() });
956
- const affected = res.status === "success" && Array.isArray(res.data) ? res.data.length : 0;
957
- return { affectedRows: affected };
958
- }
959
- async count(table, filter) {
960
- const qs = this.buildQueryString(filter);
961
- const url = `${this.endpoint}/rest/v1/${table}${qs}`;
962
- const headers = { ...this.getHeaders(), "Prefer": "count=exact", "Range-Unit": "items", "Range": "0-0" };
963
- const res = await KrnlHTTP.get(url, { headers });
964
- return res.status === "success" && Array.isArray(res.data) ? res.data.length : 0;
965
- }
966
- async clear(table) {
967
- await this.delete(table, {});
968
- }
969
- async query(queryStr, _params) {
970
- return this.find(queryStr);
971
- }
972
- async execute(_commandStr, _params) {
973
- return { affectedRows: 0 };
974
- }
975
- };
976
-
977
- // src/backend/providers/data/PocketBaseDataProvider.ts
978
- var PocketBaseDataProvider = class {
979
- engine = "pocketbase";
980
- endpoint;
981
- apiKey;
982
- isConnected = false;
983
- constructor(config) {
984
- this.endpoint = (config.endpoint || "http://127.0.0.1:8090").replace(/\/+$/, "");
985
- this.apiKey = config.apiKey;
986
- }
987
- getHeaders() {
988
- const headers = {
989
- "Content-Type": "application/json"
990
- };
991
- if (this.apiKey) {
992
- headers["Authorization"] = this.apiKey;
993
- }
994
- return headers;
995
- }
996
- async connect() {
997
- this.isConnected = true;
998
- }
999
- async disconnect() {
1000
- this.isConnected = false;
1001
- }
1002
- async testConnection() {
1003
- const t0 = Date.now();
1004
- try {
1005
- const res = await KrnlHTTP.get(`${this.endpoint}/api/health`, {
1006
- headers: this.getHeaders(),
1007
- timeout: 5e3
1008
- });
1009
- const latencyMs = Date.now() - t0;
1010
- return {
1011
- ok: res.status === "success" && (res.data?.code === 200 || res.code === 200),
1012
- latencyMs,
1013
- details: {
1014
- engine: "pocketbase",
1015
- endpoint: this.endpoint,
1016
- data: res.data
1017
- }
1018
- };
1019
- } catch (err) {
1020
- return {
1021
- ok: false,
1022
- latencyMs: Date.now() - t0,
1023
- details: { error: err.message }
1024
- };
1025
- }
1026
- }
1027
- async ensureTable(_tableName, _schema) {
1028
- }
1029
- buildFilterParam(filter) {
1030
- if (!filter || Object.keys(filter).length === 0) return "";
1031
- const expressions = [];
1032
- for (const [key, val] of Object.entries(filter)) {
1033
- if (typeof val === "string") {
1034
- expressions.push(`${key}='${val.replace(/'/g, "\\'")}'`);
1035
- } else if (typeof val === "number" || typeof val === "boolean") {
1036
- expressions.push(`${key}=${val}`);
1037
- }
1038
- }
1039
- return expressions.length > 0 ? encodeURIComponent(expressions.join(" && ")) : "";
1040
- }
1041
- async find(table, filter, options) {
1042
- const params = [];
1043
- const filterStr = this.buildFilterParam(filter);
1044
- if (filterStr) params.push(`filter=${filterStr}`);
1045
- const perPage = options?.limit || 50;
1046
- const page = options?.offset ? Math.floor(options.offset / perPage) + 1 : 1;
1047
- params.push(`page=${page}&perPage=${perPage}`);
1048
- if (options?.sort) {
1049
- const sortParts = Object.entries(options.sort).map(([col, dir]) => `${dir === -1 ? "-" : "+"}${col}`);
1050
- params.push(`sort=${encodeURIComponent(sortParts.join(","))}`);
1051
- }
1052
- const qs = params.length > 0 ? `?${params.join("&")}` : "";
1053
- const url = `${this.endpoint}/api/collections/${table}/records${qs}`;
1054
- const res = await KrnlHTTP.get(url, { headers: this.getHeaders() });
1055
- if (res.status === "success" && res.data?.items) {
1056
- return res.data.items;
1057
- }
1058
- return [];
1059
- }
1060
- async findOne(table, filter) {
1061
- if (typeof filter === "string") {
1062
- const url = `${this.endpoint}/api/collections/${table}/records/${filter}`;
1063
- const res = await KrnlHTTP.get(url, { headers: this.getHeaders() });
1064
- return res.status === "success" && res.data ? res.data : null;
1065
- }
1066
- const list = await this.find(table, filter, { limit: 1 });
1067
- return list[0] || null;
1068
- }
1069
- async insert(table, data) {
1070
- const url = `${this.endpoint}/api/collections/${table}/records`;
1071
- if (Array.isArray(data)) {
1072
- const results = [];
1073
- for (const item of data) {
1074
- const res = await KrnlHTTP.post(url, item, { headers: this.getHeaders() });
1075
- if (res.status === "success" && res.data) results.push(res.data);
1076
- }
1077
- return results;
1078
- } else {
1079
- const res = await KrnlHTTP.post(url, data, { headers: this.getHeaders() });
1080
- return res.status === "success" && res.data ? res.data : data;
1081
- }
1082
- }
1083
- async update(table, filter, patch) {
1084
- let targetId = null;
1085
- if (typeof filter === "string") {
1086
- targetId = filter;
1087
- } else {
1088
- const existing = await this.findOne(table, filter);
1089
- targetId = existing?.id || null;
1090
- }
1091
- if (!targetId) return { affectedRows: 0 };
1092
- const url = `${this.endpoint}/api/collections/${table}/records/${targetId}`;
1093
- const res = await KrnlHTTP.request(url, {
1094
- method: "PATCH",
1095
- headers: this.getHeaders(),
1096
- body: JSON.stringify(patch)
1097
- });
1098
- return { affectedRows: res.status === "success" ? 1 : 0 };
1099
- }
1100
- async delete(table, filter) {
1101
- let targetId = null;
1102
- if (typeof filter === "string") {
1103
- targetId = filter;
1104
- } else {
1105
- const existing = await this.findOne(table, filter);
1106
- targetId = existing?.id || null;
1107
- }
1108
- if (!targetId) return { affectedRows: 0 };
1109
- const url = `${this.endpoint}/api/collections/${table}/records/${targetId}`;
1110
- const res = await KrnlHTTP.del(url, { headers: this.getHeaders() });
1111
- return { affectedRows: res.status === "success" ? 1 : 0 };
1112
- }
1113
- async count(table, filter) {
1114
- const filterStr = this.buildFilterParam(filter);
1115
- const qs = `?page=1&perPage=1${filterStr ? `&filter=${filterStr}` : ""}`;
1116
- const url = `${this.endpoint}/api/collections/${table}/records${qs}`;
1117
- const res = await KrnlHTTP.get(url, { headers: this.getHeaders() });
1118
- return res.status === "success" && typeof res.data?.totalItems === "number" ? res.data.totalItems : 0;
1119
- }
1120
- async clear(table) {
1121
- const all = await this.find(table);
1122
- for (const item of all) {
1123
- if (item.id) await this.delete(table, item.id);
1124
- }
1125
- }
1126
- async query(queryStr, _params) {
1127
- return this.find(queryStr);
1128
- }
1129
- async execute(_commandStr, _params) {
1130
- return { affectedRows: 0 };
1131
- }
1132
- };
1133
-
1134
- // src/backend/providers/data/FirebaseDataProvider.ts
1135
- var FirebaseDataProvider = class {
1136
- engine = "firebase";
1137
- projectId;
1138
- apiKey;
1139
- isConnected = false;
1140
- constructor(config) {
1141
- this.projectId = config.projectId || "";
1142
- this.apiKey = config.apiKey;
1143
- }
1144
- get baseUrl() {
1145
- return `https://firestore.googleapis.com/v1/projects/${this.projectId}/databases/(default)/documents`;
1146
- }
1147
- get urlSuffix() {
1148
- return this.apiKey ? `?key=${this.apiKey}` : "";
1149
- }
1150
- async connect() {
1151
- this.isConnected = true;
1152
- }
1153
- async disconnect() {
1154
- this.isConnected = false;
1155
- }
1156
- async testConnection() {
1157
- const t0 = Date.now();
1158
- try {
1159
- const url = `${this.baseUrl}${this.urlSuffix}`;
1160
- const res = await KrnlHTTP.get(url, { timeout: 5e3 });
1161
- const latencyMs = Date.now() - t0;
1162
- return {
1163
- ok: res.status === "success" || res.code === 200 || res.code === 404,
1164
- latencyMs,
1165
- details: {
1166
- engine: "firebase",
1167
- projectId: this.projectId,
1168
- status: res.status
1169
- }
1170
- };
1171
- } catch (err) {
1172
- return {
1173
- ok: false,
1174
- latencyMs: Date.now() - t0,
1175
- details: { error: err.message }
1176
- };
1177
- }
1178
- }
1179
- async ensureTable(_tableName, _schema) {
1180
- }
1181
- /**
1182
- * Translates plain JavaScript object into Firestore document value structure
1183
- */
1184
- toFirestoreFields(obj) {
1185
- const fields = {};
1186
- for (const [key, val] of Object.entries(obj)) {
1187
- fields[key] = this.toFirestoreValue(val);
1188
- }
1189
- return fields;
1190
- }
1191
- toFirestoreValue(val) {
1192
- if (val === null || val === void 0) return { nullValue: null };
1193
- if (typeof val === "boolean") return { booleanValue: val };
1194
- if (typeof val === "number") {
1195
- return Number.isInteger(val) ? { integerValue: String(val) } : { doubleValue: val };
1196
- }
1197
- if (typeof val === "string") return { stringValue: val };
1198
- if (Array.isArray(val)) {
1199
- return { arrayValue: { values: val.map((v) => this.toFirestoreValue(v)) } };
1200
- }
1201
- if (typeof val === "object") {
1202
- return { mapValue: { fields: this.toFirestoreFields(val) } };
1203
- }
1204
- return { stringValue: String(val) };
1205
- }
1206
- /**
1207
- * Translates Firestore document into standard JavaScript object
1208
- */
1209
- fromFirestoreDoc(doc) {
1210
- if (!doc || !doc.fields) return null;
1211
- const result = {};
1212
- const docName = doc.name || "";
1213
- const id = docName.split("/").pop();
1214
- if (id) result.id = id;
1215
- for (const [key, fieldObj] of Object.entries(doc.fields)) {
1216
- result[key] = this.fromFirestoreValue(fieldObj);
1217
- }
1218
- return result;
1219
- }
1220
- fromFirestoreValue(fieldObj) {
1221
- if (!fieldObj || typeof fieldObj !== "object") return null;
1222
- if ("stringValue" in fieldObj) return fieldObj.stringValue;
1223
- if ("integerValue" in fieldObj) return parseInt(fieldObj.integerValue, 10);
1224
- if ("doubleValue" in fieldObj) return fieldObj.doubleValue;
1225
- if ("booleanValue" in fieldObj) return fieldObj.booleanValue;
1226
- if ("nullValue" in fieldObj) return null;
1227
- if ("arrayValue" in fieldObj) {
1228
- return (fieldObj.arrayValue.values || []).map((v) => this.fromFirestoreValue(v));
1229
- }
1230
- if ("mapValue" in fieldObj) {
1231
- const obj = {};
1232
- for (const [k, v] of Object.entries(fieldObj.mapValue.fields || {})) {
1233
- obj[k] = this.fromFirestoreValue(v);
1234
- }
1235
- return obj;
1236
- }
1237
- return null;
1238
- }
1239
- async find(table, filter, options) {
1240
- const url = `${this.baseUrl}/${table}${this.urlSuffix}`;
1241
- const res = await KrnlHTTP.get(url);
1242
- if (res.status === "success" && Array.isArray(res.data?.documents)) {
1243
- let items = res.data.documents.map((d) => this.fromFirestoreDoc(d)).filter(Boolean);
1244
- if (filter && Object.keys(filter).length > 0) {
1245
- items = items.filter((item) => {
1246
- for (const [k, v] of Object.entries(filter)) {
1247
- if (item[k] !== v) return false;
1248
- }
1249
- return true;
1250
- });
1251
- }
1252
- if (options?.offset) items = items.slice(options.offset);
1253
- if (options?.limit) items = items.slice(0, options.limit);
1254
- return items;
1255
- }
1256
- return [];
1257
- }
1258
- async findOne(table, filter) {
1259
- if (typeof filter === "string") {
1260
- const url = `${this.baseUrl}/${table}/${filter}${this.urlSuffix}`;
1261
- const res = await KrnlHTTP.get(url);
1262
- return res.status === "success" && res.data ? this.fromFirestoreDoc(res.data) : null;
1263
- }
1264
- const list = await this.find(table, filter, { limit: 1 });
1265
- return list[0] || null;
1266
- }
1267
- async insert(table, data) {
1268
- const items = Array.isArray(data) ? data : [data];
1269
- const results = [];
1270
- for (const item of items) {
1271
- const docObj = { ...item };
1272
- const docId = docObj.id || docObj._id || `doc_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1273
- delete docObj.id;
1274
- delete docObj._id;
1275
- const url = `${this.baseUrl}/${table}?documentId=${docId}${this.apiKey ? `&key=${this.apiKey}` : ""}`;
1276
- const body = { fields: this.toFirestoreFields(docObj) };
1277
- const res = await KrnlHTTP.post(url, body);
1278
- if (res.status === "success" && res.data) {
1279
- results.push(this.fromFirestoreDoc(res.data));
1280
- } else {
1281
- results.push({ id: docId, ...docObj });
1282
- }
1283
- }
1284
- return Array.isArray(data) ? results : results[0];
1285
- }
1286
- async update(table, filter, patch) {
1287
- let docId = null;
1288
- if (typeof filter === "string") {
1289
- docId = filter;
1290
- } else {
1291
- const existing = await this.findOne(table, filter);
1292
- docId = existing?.id || null;
1293
- }
1294
- if (!docId) return { affectedRows: 0 };
1295
- const patchFields = this.toFirestoreFields(patch);
1296
- const updateMask = Object.keys(patch).map((k) => `updateMask.fieldPaths=${k}`).join("&");
1297
- const url = `${this.baseUrl}/${table}/${docId}?${updateMask}${this.apiKey ? `&key=${this.apiKey}` : ""}`;
1298
- const res = await KrnlHTTP.request(url, {
1299
- method: "PATCH",
1300
- headers: { "Content-Type": "application/json" },
1301
- body: JSON.stringify({ fields: patchFields })
1302
- });
1303
- return { affectedRows: res.status === "success" ? 1 : 0 };
1304
- }
1305
- async delete(table, filter) {
1306
- let docId = null;
1307
- if (typeof filter === "string") {
1308
- docId = filter;
1309
- } else {
1310
- const existing = await this.findOne(table, filter);
1311
- docId = existing?.id || null;
1312
- }
1313
- if (!docId) return { affectedRows: 0 };
1314
- const url = `${this.baseUrl}/${table}/${docId}${this.urlSuffix}`;
1315
- const res = await KrnlHTTP.del(url);
1316
- return { affectedRows: res.status === "success" ? 1 : 0 };
1317
- }
1318
- async count(table, filter) {
1319
- const list = await this.find(table, filter);
1320
- return list.length;
1321
- }
1322
- async clear(table) {
1323
- const all = await this.find(table);
1324
- for (const item of all) {
1325
- if (item.id) await this.delete(table, item.id);
1326
- }
1327
- }
1328
- async query(queryStr, _params) {
1329
- return this.find(queryStr);
1330
- }
1331
- async execute(_commandStr, _params) {
1332
- return { affectedRows: 0 };
1333
- }
1334
- };
1335
-
1336
- // src/backend/providers/storage/FilesystemStorageProvider.ts
1337
- import path2 from "path";
1338
- import fsp from "fs/promises";
1339
- var FilesystemStorageProvider = class {
1340
- driver = "filesystem";
1341
- basePath;
1342
- constructor(config = "./storage") {
1343
- if (typeof config === "string") {
1344
- this.basePath = path2.resolve(config);
1345
- } else {
1346
- this.basePath = path2.resolve(config.basePath || "./storage");
1347
- }
1348
- }
1349
- async uploadFile(targetPath, content, _mimeType) {
1350
- const fullPath = path2.join(this.basePath, targetPath);
1351
- await KrnlFS.ensureDir(path2.dirname(fullPath));
1352
- let buf;
1353
- if (Buffer.isBuffer(content)) {
1354
- buf = content;
1355
- } else if (typeof content === "string") {
1356
- buf = Buffer.from(content, "utf8");
1357
- } else if (content instanceof Uint8Array) {
1358
- buf = Buffer.from(content);
1359
- } else {
1360
- buf = Buffer.from(await content.arrayBuffer());
1361
- }
1362
- await KrnlFS.writeFileAtomic(fullPath, buf);
1363
- const size = buf.byteLength;
1364
- return {
1365
- url: `file://${fullPath}`,
1366
- size
1367
- };
1368
- }
1369
- async downloadFile(targetPath) {
1370
- const fullPath = path2.join(this.basePath, targetPath);
1371
- return await fsp.readFile(fullPath);
1372
- }
1373
- async deleteFile(targetPath) {
1374
- const fullPath = path2.join(this.basePath, targetPath);
1375
- try {
1376
- await KrnlFS.deleteFile(fullPath);
1377
- return true;
1378
- } catch {
1379
- return false;
1380
- }
1381
- }
1382
- getPublicUrl(targetPath) {
1383
- return `file://${path2.join(this.basePath, targetPath)}`;
1384
- }
1385
- async listFiles(prefix = "") {
1386
- const startDir = path2.join(this.basePath, prefix);
1387
- if (!await KrnlFS.dirExists(startDir)) {
1388
- return [];
1389
- }
1390
- const results = [];
1391
- for await (const file of KrnlFS.walkDir(startDir)) {
1392
- const stat = await KrnlFS.getFileStat(file);
1393
- results.push({
1394
- path: path2.relative(this.basePath, file),
1395
- size: stat.size,
1396
- updatedAt: stat.modifiedAt.getTime()
1397
- });
1398
- }
1399
- return results;
1400
- }
1401
- };
1402
-
1403
- // src/backend/providers/storage/SupabaseStorageProvider.ts
1404
- var SupabaseStorageProvider = class {
1405
- driver = "supabase_storage";
1406
- endpoint;
1407
- apiKey;
1408
- bucket;
1409
- constructor(config) {
1410
- this.endpoint = (config.endpoint || "").replace(/\/+$/, "");
1411
- this.apiKey = config.apiKey || "";
1412
- this.bucket = config.bucket || "default";
1413
- }
1414
- getHeaders(mimeType) {
1415
- const headers = {
1416
- "apikey": this.apiKey,
1417
- "Authorization": `Bearer ${this.apiKey}`
1418
- };
1419
- if (mimeType) {
1420
- headers["Content-Type"] = mimeType;
1421
- }
1422
- return headers;
1423
- }
1424
- async uploadFile(targetPath, content, mimeType = "application/octet-stream") {
1425
- const cleanPath = targetPath.replace(/^\/+/, "");
1426
- const url = `${this.endpoint}/storage/v1/object/${this.bucket}/${cleanPath}`;
1427
- let body = content;
1428
- let size = 0;
1429
- if (Buffer.isBuffer(content)) {
1430
- size = content.byteLength;
1431
- } else if (typeof content === "string") {
1432
- size = Buffer.byteLength(content);
1433
- }
1434
- await KrnlHTTP.request(url, {
1435
- method: "POST",
1436
- headers: this.getHeaders(mimeType),
1437
- body
1438
- });
1439
- return {
1440
- url: this.getPublicUrl(cleanPath),
1441
- size
1442
- };
1443
- }
1444
- async downloadFile(targetPath) {
1445
- const cleanPath = targetPath.replace(/^\/+/, "");
1446
- const url = `${this.endpoint}/storage/v1/object/authenticated/${this.bucket}/${cleanPath}`;
1447
- const res = await fetch(url, { headers: this.getHeaders() });
1448
- const arrayBuf = await res.arrayBuffer();
1449
- return Buffer.from(arrayBuf);
1450
- }
1451
- async deleteFile(targetPath) {
1452
- const cleanPath = targetPath.replace(/^\/+/, "");
1453
- const url = `${this.endpoint}/storage/v1/object/${this.bucket}/${cleanPath}`;
1454
- const res = await KrnlHTTP.del(url, { headers: this.getHeaders() });
1455
- return res.status === "success";
1456
- }
1457
- getPublicUrl(targetPath) {
1458
- const cleanPath = targetPath.replace(/^\/+/, "");
1459
- return `${this.endpoint}/storage/v1/object/public/${this.bucket}/${cleanPath}`;
1460
- }
1461
- async listFiles(prefix = "") {
1462
- const url = `${this.endpoint}/storage/v1/object/list/${this.bucket}`;
1463
- const res = await KrnlHTTP.post(url, { prefix, limit: 100 }, { headers: this.getHeaders("application/json") });
1464
- if (res.status === "success" && Array.isArray(res.data)) {
1465
- return res.data.map((item) => ({
1466
- path: item.name,
1467
- size: item.metadata?.size || 0,
1468
- updatedAt: item.updated_at ? new Date(item.updated_at).getTime() : Date.now()
1469
- }));
1470
- }
1471
- return [];
1472
- }
1473
- };
1474
-
1475
- // src/backend/providers/storage/S3StorageProvider.ts
1476
- var S3StorageProvider = class {
1477
- driver = "s3";
1478
- endpoint;
1479
- bucket;
1480
- region;
1481
- accessKey;
1482
- secretKey;
1483
- constructor(config) {
1484
- this.bucket = config.bucket || "default-bucket";
1485
- this.region = config.region || "us-east-1";
1486
- this.accessKey = config.accessKey;
1487
- this.secretKey = config.secretKey;
1488
- this.endpoint = config.endpoint ? config.endpoint.replace(/\/+$/, "") : `https://${this.bucket}.s3.${this.region}.amazonaws.com`;
1489
- }
1490
- getBaseUrl() {
1491
- return this.endpoint.includes(this.bucket) ? this.endpoint : `${this.endpoint}/${this.bucket}`;
1492
- }
1493
- async uploadFile(targetPath, content, mimeType = "application/octet-stream") {
1494
- const cleanPath = targetPath.replace(/^\/+/, "");
1495
- const url = `${this.getBaseUrl()}/${cleanPath}`;
1496
- let body = content;
1497
- let size = 0;
1498
- if (Buffer.isBuffer(content)) {
1499
- size = content.byteLength;
1500
- } else if (typeof content === "string") {
1501
- size = Buffer.byteLength(content);
1502
- }
1503
- await KrnlHTTP.request(url, {
1504
- method: "PUT",
1505
- headers: {
1506
- "Content-Type": mimeType
1507
- },
1508
- body
1509
- });
1510
- return {
1511
- url: this.getPublicUrl(cleanPath),
1512
- size
1513
- };
1514
- }
1515
- async downloadFile(targetPath) {
1516
- const cleanPath = targetPath.replace(/^\/+/, "");
1517
- const url = `${this.getBaseUrl()}/${cleanPath}`;
1518
- const res = await fetch(url);
1519
- const arrayBuf = await res.arrayBuffer();
1520
- return Buffer.from(arrayBuf);
1521
- }
1522
- async deleteFile(targetPath) {
1523
- const cleanPath = targetPath.replace(/^\/+/, "");
1524
- const url = `${this.getBaseUrl()}/${cleanPath}`;
1525
- const res = await KrnlHTTP.del(url);
1526
- return res.status === "success";
1527
- }
1528
- getPublicUrl(targetPath) {
1529
- const cleanPath = targetPath.replace(/^\/+/, "");
1530
- return `${this.getBaseUrl()}/${cleanPath}`;
1531
- }
1532
- async listFiles(_prefix = "") {
1533
- return [];
1534
- }
1535
- };
1536
-
1537
- // src/backend/providers/storage/PocketBaseStorageProvider.ts
1538
- var PocketBaseStorageProvider = class {
1539
- driver = "pocketbase_storage";
1540
- endpoint;
1541
- bucket;
1542
- constructor(config) {
1543
- this.endpoint = (config.endpoint || "http://127.0.0.1:8090").replace(/\/+$/, "");
1544
- this.bucket = config.bucket || "files";
1545
- }
1546
- async uploadFile(targetPath, content, mimeType = "application/octet-stream") {
1547
- const cleanPath = targetPath.replace(/^\/+/, "");
1548
- const url = `${this.endpoint}/api/collections/${this.bucket}/records`;
1549
- let size = 0;
1550
- if (Buffer.isBuffer(content)) size = content.byteLength;
1551
- else if (typeof content === "string") size = Buffer.byteLength(content);
1552
- const formData = new FormData();
1553
- const blob = new Blob([content], { type: mimeType });
1554
- formData.append("file", blob, cleanPath);
1555
- await fetch(url, {
1556
- method: "POST",
1557
- body: formData
1558
- });
1559
- return {
1560
- url: this.getPublicUrl(cleanPath),
1561
- size
1562
- };
1563
- }
1564
- async downloadFile(targetPath) {
1565
- const cleanPath = targetPath.replace(/^\/+/, "");
1566
- const url = `${this.endpoint}/api/files/${this.bucket}/${cleanPath}`;
1567
- const res = await fetch(url);
1568
- const arrayBuf = await res.arrayBuffer();
1569
- return Buffer.from(arrayBuf);
1570
- }
1571
- async deleteFile(targetPath) {
1572
- const cleanPath = targetPath.replace(/^\/+/, "");
1573
- const url = `${this.endpoint}/api/collections/${this.bucket}/records/${cleanPath}`;
1574
- const res = await KrnlHTTP.del(url);
1575
- return res.status === "success";
1576
- }
1577
- getPublicUrl(targetPath) {
1578
- const cleanPath = targetPath.replace(/^\/+/, "");
1579
- return `${this.endpoint}/api/files/${this.bucket}/${cleanPath}`;
1580
- }
1581
- async listFiles(_prefix = "") {
1582
- return [];
1583
- }
1584
- };
1585
-
1586
- // src/backend/providers/storage/FirebaseStorageProvider.ts
1587
- var FirebaseStorageProvider = class {
1588
- driver = "firebase_storage";
1589
- bucket;
1590
- apiKey;
1591
- constructor(config) {
1592
- this.bucket = config.bucket || `${config.projectId || "default"}.appspot.com`;
1593
- this.apiKey = config.apiKey;
1594
- }
1595
- get baseUrl() {
1596
- return `https://firebasestorage.googleapis.com/v0/b/${this.bucket}/o`;
1597
- }
1598
- async uploadFile(targetPath, content, mimeType = "application/octet-stream") {
1599
- const cleanPath = encodeURIComponent(targetPath.replace(/^\/+/, ""));
1600
- const url = `${this.baseUrl}?name=${cleanPath}${this.apiKey ? `&key=${this.apiKey}` : ""}`;
1601
- let body = content;
1602
- let size = 0;
1603
- if (Buffer.isBuffer(content)) size = content.byteLength;
1604
- else if (typeof content === "string") size = Buffer.byteLength(content);
1605
- await fetch(url, {
1606
- method: "POST",
1607
- headers: {
1608
- "Content-Type": mimeType
1609
- },
1610
- body
1611
- });
1612
- return {
1613
- url: this.getPublicUrl(targetPath),
1614
- size
1615
- };
1616
- }
1617
- async downloadFile(targetPath) {
1618
- const cleanPath = encodeURIComponent(targetPath.replace(/^\/+/, ""));
1619
- const url = `${this.baseUrl}/${cleanPath}?alt=media${this.apiKey ? `&key=${this.apiKey}` : ""}`;
1620
- const res = await fetch(url);
1621
- const arrayBuf = await res.arrayBuffer();
1622
- return Buffer.from(arrayBuf);
1623
- }
1624
- async deleteFile(targetPath) {
1625
- const cleanPath = encodeURIComponent(targetPath.replace(/^\/+/, ""));
1626
- const url = `${this.baseUrl}/${cleanPath}${this.apiKey ? `&key=${this.apiKey}` : ""}`;
1627
- const res = await KrnlHTTP.del(url);
1628
- return res.status === "success";
1629
- }
1630
- getPublicUrl(targetPath) {
1631
- const cleanPath = encodeURIComponent(targetPath.replace(/^\/+/, ""));
1632
- return `${this.baseUrl}/${cleanPath}?alt=media`;
1633
- }
1634
- async listFiles(_prefix = "") {
1635
- return [];
1636
- }
1637
- };
1638
-
1639
- // src/backend/WorkspaceBackendFactory.ts
1640
- var WorkspaceBackendFactory = class _WorkspaceBackendFactory {
1641
- static create(config) {
1642
- const dataProvider = _WorkspaceBackendFactory.resolveDataProvider(config);
1643
- const storageProvider = _WorkspaceBackendFactory.resolveStorageProvider(config);
1644
- return {
1645
- id: config.id,
1646
- mode: config.mode,
1647
- data: dataProvider,
1648
- storage: storageProvider,
1649
- async initialize() {
1650
- await dataProvider.connect();
1651
- },
1652
- async dispose() {
1653
- await dataProvider.disconnect();
1654
- }
1655
- };
1656
- }
1657
- static createLocal(filePath = "./workspace.sqlite", storagePath = "./storage") {
1658
- return _WorkspaceBackendFactory.create({
1659
- id: "local-workspace",
1660
- provider: "sqlite",
1661
- mode: "local",
1662
- database: { type: "sqlite", filePath, enableWAL: true },
1663
- storage: { type: "filesystem", basePath: storagePath }
1664
- });
1665
- }
1666
- static resolveDataProvider(config) {
1667
- const dbConfig = config.database || { type: config.provider };
1668
- switch (dbConfig.type) {
1669
- case "sqlite":
1670
- return new SQLiteDataProvider(dbConfig);
1671
- case "postgres":
1672
- return new PostgresDataProvider(dbConfig);
1673
- case "supabase":
1674
- return new SupabaseDataProvider({
1675
- ...dbConfig,
1676
- endpoint: dbConfig.endpoint || config.endpoint,
1677
- apiKey: dbConfig.apiKey || config.auth?.apiKey
1678
- });
1679
- case "pocketbase":
1680
- return new PocketBaseDataProvider({
1681
- ...dbConfig,
1682
- endpoint: dbConfig.endpoint || config.endpoint,
1683
- apiKey: dbConfig.apiKey || config.auth?.token
1684
- });
1685
- case "firebase":
1686
- return new FirebaseDataProvider({
1687
- ...dbConfig,
1688
- apiKey: dbConfig.apiKey || config.auth?.apiKey
1689
- });
1690
- default:
1691
- return new SQLiteDataProvider("./workspace.sqlite");
1692
- }
1693
- }
1694
- static resolveStorageProvider(config) {
1695
- const storageConfig = config.storage || { type: "filesystem" };
1696
- switch (storageConfig.type) {
1697
- case "filesystem":
1698
- return new FilesystemStorageProvider(storageConfig);
1699
- case "supabase_storage":
1700
- return new SupabaseStorageProvider({
1701
- ...storageConfig,
1702
- endpoint: storageConfig.endpoint || config.endpoint,
1703
- apiKey: storageConfig.apiKey || config.auth?.apiKey
1704
- });
1705
- case "s3":
1706
- return new S3StorageProvider({
1707
- ...storageConfig,
1708
- endpoint: storageConfig.endpoint || config.endpoint
1709
- });
1710
- case "pocketbase_storage":
1711
- return new PocketBaseStorageProvider({
1712
- ...storageConfig,
1713
- endpoint: storageConfig.endpoint || config.endpoint
1714
- });
1715
- case "firebase_storage":
1716
- return new FirebaseStorageProvider({
1717
- ...storageConfig,
1718
- apiKey: storageConfig.apiKey || config.auth?.apiKey
1719
- });
1720
- default:
1721
- return new FilesystemStorageProvider("./storage");
1722
- }
1723
- }
1724
- };
1725
-
1726
- // src/backend/control_plane/LocalSQLiteAccountProvider.ts
1727
- import path3 from "path";
1728
- var LocalSQLiteAccountProvider = class {
1729
- filePath;
1730
- isLoaded = false;
1731
- db = { users: {}, workspaces: {} };
1732
- constructor(filePath = "./accounts.sqlite") {
1733
- this.filePath = path3.resolve(filePath);
1734
- }
1735
- async load() {
1736
- if (this.isLoaded) return;
1737
- await KrnlFS.ensureDir(path3.dirname(this.filePath));
1738
- if (await KrnlFS.fileExists(this.filePath)) {
1739
- try {
1740
- const raw = await KrnlFS.readJSON(this.filePath);
1741
- if (raw && typeof raw === "object") {
1742
- this.db = {
1743
- users: raw.users || {},
1744
- workspaces: raw.workspaces || {}
1745
- };
1746
- }
1747
- } catch {
1748
- this.db = { users: {}, workspaces: {} };
1749
- }
1750
- }
1751
- this.isLoaded = true;
1752
- }
1753
- async persist() {
1754
- const release = await FileLock.acquire(this.filePath);
1755
- try {
1756
- await KrnlFS.writeJSON(this.filePath, this.db, 2);
1757
- } finally {
1758
- release();
1759
- }
1760
- }
1761
- async getUser(userId) {
1762
- await this.load();
1763
- const user = this.db.users[userId];
1764
- if (!user) return null;
1765
- const { passwordHash, ...profile } = user;
1766
- return profile;
1767
- }
1768
- async registerUser(credentials) {
1769
- await this.load();
1770
- const userId = credentials.username || credentials.email || `usr_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`;
1771
- const profile = {
1772
- id: userId,
1773
- email: credentials.email,
1774
- username: credentials.username || credentials.email,
1775
- role: credentials.role || "USER",
1776
- passwordHash: credentials.password,
1777
- metadata: credentials.metadata || {},
1778
- createdAt: Date.now()
1779
- };
1780
- this.db.users[userId] = profile;
1781
- if (!this.db.workspaces[userId]) {
1782
- this.db.workspaces[userId] = [];
1783
- }
1784
- await this.persist();
1785
- const { passwordHash, ...safeProfile } = profile;
1786
- return safeProfile;
1787
- }
1788
- async authenticate(credentials) {
1789
- await this.load();
1790
- const userId = credentials.username || credentials.email;
1791
- let user = userId ? this.db.users[userId] : null;
1792
- if (!user && (credentials.email || credentials.username)) {
1793
- const isFirst = Object.keys(this.db.users).length === 0;
1794
- user = await this.registerUser({
1795
- ...credentials,
1796
- role: isFirst ? "ADMIN" : "USER"
1797
- });
1798
- }
1799
- if (!user) {
1800
- throw new Error("Invalid user credentials.");
1801
- }
1802
- const token = `sess::${user.id}::${Date.now()}::${Math.random().toString(36).substring(2, 9)}`;
1803
- const { passwordHash, ...profile } = user;
1804
- return {
1805
- userId: user.id,
1806
- role: user.role,
1807
- token,
1808
- expiresAt: Date.now() + 864e5,
1809
- user: profile
1810
- };
1811
- }
1812
- async verifySession(token) {
1813
- if (!token) return null;
1814
- await this.load();
1815
- const parts = token.split("::");
1816
- if (parts.length >= 4 && parts[0] === "sess") {
1817
- const userId = parts[1];
1818
- const user = this.db.users[userId];
1819
- if (user) {
1820
- const { passwordHash, ...profile } = user;
1821
- return {
1822
- userId: user.id,
1823
- role: user.role,
1824
- token,
1825
- expiresAt: Date.now() + 864e5,
1826
- user: profile
1827
- };
1828
- }
1829
- }
1830
- return null;
1831
- }
1832
- async listWorkspaces(userId) {
1833
- await this.load();
1834
- return this.db.workspaces[userId] || [];
1835
- }
1836
- async createWorkspace(userId, descriptor) {
1837
- await this.load();
1838
- if (!this.db.workspaces[userId]) {
1839
- this.db.workspaces[userId] = [];
1840
- }
1841
- const newWs = {
1842
- id: descriptor.id || `ws_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`,
1843
- ownerId: userId,
1844
- name: descriptor.name || "Default Workspace",
1845
- backendConfig: descriptor.backendConfig || {
1846
- id: "default",
1847
- provider: "sqlite",
1848
- mode: "local",
1849
- database: { type: "sqlite", filePath: "./workspace.sqlite" },
1850
- storage: { type: "filesystem", basePath: "./storage" }
1851
- },
1852
- createdAt: Date.now(),
1853
- updatedAt: Date.now()
1854
- };
1855
- this.db.workspaces[userId].push(newWs);
1856
- await this.persist();
1857
- return newWs;
1858
- }
1859
- async deleteWorkspace(userId, workspaceId) {
1860
- await this.load();
1861
- const list = this.db.workspaces[userId] || [];
1862
- const idx = list.findIndex((w) => w.id === workspaceId);
1863
- if (idx !== -1) {
1864
- list.splice(idx, 1);
1865
- await this.persist();
1866
- return true;
1867
- }
1868
- return false;
1869
- }
1870
- };
1871
-
1872
- // src/backend/control_plane/HostedAccountProvider.ts
1873
- var HostedAccountProvider = class {
1874
- endpoint;
1875
- apiKey;
1876
- constructor(config) {
1877
- this.endpoint = (config.endpoint || "").replace(/\/+$/, "");
1878
- this.apiKey = config.apiKey || config.token;
1879
- }
1880
- getHeaders() {
1881
- const headers = { "Content-Type": "application/json" };
1882
- if (this.apiKey) {
1883
- headers["Authorization"] = `Bearer ${this.apiKey}`;
1884
- headers["apikey"] = this.apiKey;
1885
- }
1886
- return headers;
1887
- }
1888
- async getUser(userId) {
1889
- const res = await KrnlHTTP.get(`${this.endpoint}/api/auth/users/${userId}`, { headers: this.getHeaders() });
1890
- return res.status === "success" && res.data ? res.data : null;
1891
- }
1892
- async authenticate(credentials) {
1893
- const res = await KrnlHTTP.post(`${this.endpoint}/api/auth/login`, credentials, { headers: this.getHeaders() });
1894
- if (res.status === "success" && res.data) {
1895
- return res.data;
1896
- }
1897
- throw new Error(res.message || "Authentication failed against hosted account backend.");
1898
- }
1899
- async verifySession(token) {
1900
- if (!token) return null;
1901
- const res = await KrnlHTTP.post(`${this.endpoint}/api/auth/verify`, { token }, { headers: this.getHeaders() });
1902
- return res.status === "success" && res.data ? res.data : null;
1903
- }
1904
- async listWorkspaces(userId) {
1905
- const res = await KrnlHTTP.get(`${this.endpoint}/api/workspaces?userId=${userId}`, { headers: this.getHeaders() });
1906
- return res.status === "success" && Array.isArray(res.data) ? res.data : [];
1907
- }
1908
- async createWorkspace(userId, descriptor) {
1909
- const res = await KrnlHTTP.post(`${this.endpoint}/api/workspaces`, { userId, ...descriptor }, { headers: this.getHeaders() });
1910
- if (res.status === "success" && res.data) {
1911
- return res.data;
1912
- }
1913
- throw new Error(res.message || "Failed to create workspace on hosted account backend.");
1914
- }
1915
- async deleteWorkspace(_userId, workspaceId) {
1916
- const res = await KrnlHTTP.del(`${this.endpoint}/api/workspaces/${workspaceId}`, { headers: this.getHeaders() });
1917
- return res.status === "success";
1918
- }
1919
- };
1920
-
1921
- // src/backend/control_plane/ControlPlaneManager.ts
1922
- var ControlPlaneManager = class _ControlPlaneManager {
1923
- accountProvider;
1924
- constructor(providerOrPath) {
1925
- if (!providerOrPath || typeof providerOrPath === "string") {
1926
- this.accountProvider = new LocalSQLiteAccountProvider(providerOrPath || "./accounts.sqlite");
1927
- } else {
1928
- this.accountProvider = providerOrPath;
1929
- }
1930
- }
1931
- static createLocal(filePath = "./accounts.sqlite") {
1932
- return new _ControlPlaneManager(new LocalSQLiteAccountProvider(filePath));
1933
- }
1934
- static createHosted(endpoint, apiKey) {
1935
- return new _ControlPlaneManager(new HostedAccountProvider({ endpoint, apiKey }));
1936
- }
1937
- async login(credentials) {
1938
- return await this.accountProvider.authenticate(credentials);
1939
- }
1940
- async verifyToken(token) {
1941
- return await this.accountProvider.verifySession(token);
1942
- }
1943
- async getUser(userId) {
1944
- return await this.accountProvider.getUser(userId);
1945
- }
1946
- async getUserWorkspaces(userId) {
1947
- return await this.accountProvider.listWorkspaces(userId);
1948
- }
1949
- async registerWorkspace(userId, descriptor) {
1950
- return await this.accountProvider.createWorkspace(userId, descriptor);
1951
- }
1952
- };
1953
-
1954
- // src/backend/control_plane/AdminGuard.ts
1955
- var AdminGuard = class {
1956
- static async verify(authHeaderOrToken, accountProvider) {
1957
- const token = authHeaderOrToken?.startsWith("Bearer ") ? authHeaderOrToken.substring(7).trim() : authHeaderOrToken?.trim() || null;
1958
- const session = await accountProvider.verifySession(token);
1959
- if (!session) {
1960
- throw new Error("[AccessDenied] Authentication required: Invalid or missing session token.");
1961
- }
1962
- if (session.role !== "ADMIN") {
1963
- throw new Error(`[AccessDenied] Forbidden: Administrative role required. Current role: "${session.role}".`);
1964
- }
1965
- return session;
1966
- }
1967
- static enforce(session) {
1968
- if (!session) {
1969
- throw new Error("[AccessDenied] Authentication required: Session is null.");
1970
- }
1971
- if (session.role !== "ADMIN") {
1972
- throw new Error(`[AccessDenied] Forbidden: Administrative privileges required. Current role: "${session.role}".`);
1973
- }
1974
- }
1975
- };
1976
-
1977
- // src/core/K_LIB_Krnl_Functionality_Types.ts
1978
- function cloneState(source) {
1979
- return ObjectKit.deepClone(source);
1980
- }
1981
- var krnlTransportAdapter = class {
1982
- };
1983
- var MemoryTransportAdapter = class extends krnlTransportAdapter {
1984
- targetEntity;
1985
- constructor(targetEntity) {
1986
- super();
1987
- this.targetEntity = targetEntity;
1988
- }
1989
- async call(targetFunction, input, opts) {
1990
- if (!this.targetEntity || typeof this.targetEntity.call !== "function") {
1991
- throw new Error("MemoryTransportAdapter: Invalid target entity.");
1992
- }
1993
- return await this.targetEntity.call(targetFunction, input, opts);
1994
- }
1995
- };
1996
- var krnlLocalFunctionality = class {
1997
- id;
1998
- visibility;
1999
- initialState;
2000
- api;
2001
- isLocal = true;
2002
- sourcePath;
2003
- helpers;
2004
- emitters;
2005
- schema;
2006
- uiSpec;
2007
- description;
2008
- method;
2009
- tests;
2010
- examples;
2011
- intelligenceSpec;
2012
- /** Port-based access control policy. Absent = unrestricted. */
2013
- accessPolicy;
2014
- /** Shared secret for allow_with_key / ask_key_unlisted gates. */
2015
- accessKey;
2016
- /** Optional Functionality Manifest declaring dependencies, capabilities, and resources */
2017
- manifest;
2018
- lifecycle;
2019
- state;
2020
- hostEntity;
2021
- intention;
2022
- ai;
2023
- requires;
2024
- _hasBeenExecuted = false;
2025
- backend;
2026
- table;
2027
- constructor(config = {}) {
2028
- const {
2029
- id,
2030
- visibility = "public",
2031
- // Default: public (bubbles up)
2032
- initialState = {},
2033
- api = (input) => input,
2034
- helpers = {},
2035
- emitters = {},
2036
- events = {},
2037
- schema = null,
2038
- onMount = null,
2039
- onTeardown = null,
2040
- sourcePath = null,
2041
- accessPolicy = null,
2042
- accessKey = null,
2043
- tests = [],
2044
- requires = null,
2045
- manifest = null,
2046
- backend = null
2047
- } = config;
2048
- if (!id) throw new Error("LocalFunctionality requires an ID.");
2049
- this.id = id;
2050
- this.visibility = visibility;
2051
- this.initialState = initialState;
2052
- this.api = api;
2053
- this.sourcePath = sourcePath;
2054
- if (requires) this.requires = requires;
2055
- this.manifest = manifest || config.manifest || null;
2056
- this.backend = backend || config.backend || null;
2057
- this.table = null;
2058
- this.helpers = new Map(Object.entries(helpers));
2059
- this.emitters = /* @__PURE__ */ new Map();
2060
- this.schema = schema;
2061
- this.description = config.description || "";
2062
- this.method = config.method || "POST";
2063
- this.tests = tests;
2064
- this.examples = config.examples || null;
2065
- this.uiSpec = config.uiSpec || null;
2066
- this.intention = config.intention || null;
2067
- this.intelligenceSpec = config.intelligenceSpec || null;
2068
- if (accessPolicy) this.accessPolicy = accessPolicy;
2069
- if (accessKey) this.accessKey = accessKey;
2070
- this.lifecycle = {
2071
- beginning: onMount || events.beginning,
2072
- during: events.during,
2073
- end: events.end,
2074
- failure: events.failure,
2075
- teardown: onTeardown || events.teardown
2076
- };
2077
- if (!emitters["state:changed"]) {
2078
- this.emitters.set("state:changed", new krnlEmitter());
2079
- }
2080
- Object.entries(emitters).forEach(([eid, e]) => {
2081
- this.emitters.set(eid, e instanceof krnlEmitter ? e : new krnlEmitter());
2082
- });
2083
- this.state = this._createObservedState(cloneState(initialState));
2084
- }
2085
- _createObservedState(initialState) {
2086
- const self = this;
2087
- const proxyCache = /* @__PURE__ */ new WeakMap();
2088
- const handler = {
2089
- get(target, prop, receiver) {
2090
- const value = Reflect.get(target, prop, receiver);
2091
- if (typeof value === "object" && value !== null) {
2092
- if (!proxyCache.has(value)) {
2093
- proxyCache.set(value, new Proxy(value, handler));
2094
- }
2095
- return proxyCache.get(value);
2096
- }
2097
- return value;
2098
- },
2099
- set(target, prop, value, receiver) {
2100
- const result = Reflect.set(target, prop, value, receiver);
2101
- if (result) {
2102
- self._notifyStateChanged(prop, value);
2103
- }
2104
- return result;
2105
- },
2106
- deleteProperty(target, prop) {
2107
- const result = Reflect.deleteProperty(target, prop);
2108
- if (result) {
2109
- self._notifyStateChanged(prop, void 0);
2110
- }
2111
- return result;
2112
- }
2113
- };
2114
- return new Proxy(initialState, handler);
2115
- }
2116
- _notifyStateChanged(prop, value) {
2117
- const stateEmitter = this.emitters.get("state:changed");
2118
- if (stateEmitter) {
2119
- stateEmitter.pushDataStreamToEmitter({
2120
- prop,
2121
- value,
2122
- state: this.state,
2123
- // This is the proxied state
2124
- functionalityId: this.id
2125
- });
2126
- }
2127
- }
2128
- /**
2129
- * Updates the visibility and handles interface registration/deregistration.
2130
- * This is the mechanism used to STOP bubbling at a certain level.
2131
- */
2132
- setVisibility(v) {
2133
- const oldVisibility = this.visibility;
2134
- this.visibility = v;
2135
- if (!this.hostEntity) return;
2136
- if (oldVisibility === "private" && v === "public") {
2137
- this._registerInInterface();
2138
- const owner = this.hostEntity.hierarchyManager.getOwnerEntity();
2139
- if (owner) owner._onComponentFunctionalityAdded(this.hostEntity, this);
2140
- } else if (oldVisibility === "public" && v === "private") {
2141
- this._unregisterFromInterface();
2142
- const owner = this.hostEntity.hierarchyManager.getOwnerEntity();
2143
- if (owner && owner._onComponentFunctionalityRemoved) {
2144
- owner._onComponentFunctionalityRemoved(this.hostEntity, this.id);
2145
- }
2146
- }
2147
- }
2148
- _unregisterFromInterface() {
2149
- const entity = this.hostEntity;
2150
- if (!entity) return;
2151
- entity.interface.removeCollector(this.id);
2152
- this.emitters.forEach((_, eid) => {
2153
- entity.interface.removeEmitter(`${this.id}:${eid}`);
2154
- });
2155
- }
2156
- _registerInInterface() {
2157
- const entity = this.hostEntity;
2158
- const mainCollector = entity.interface.createCollector(this.id);
2159
- mainCollector._directHandler = async (msg) => {
2160
- const caller = msg.metadata?.caller || "anonymous";
2161
- return await this.execute(msg.data, { caller });
2162
- };
2163
- this.emitters.forEach((emitter, eid) => {
2164
- const interfaceEmitter = entity.interface.createEmitter(`${this.id}:${eid}`);
2165
- emitter.subscribe((msg) => interfaceEmitter.pushDataStreamToEmitter(msg.data, msg.time));
2166
- });
2167
- }
2168
- /**
2169
- * checkAccess — port-based access gate.
2170
- *
2171
- * f(p, k) ∈ { PASS, REJECT }
2172
- * FORBID if p ∈ P_forbid
2173
- * PASS if p ∈ P_allow
2174
- * KEY(k) if p ∈ P_allow_with_key
2175
- * default_connection_behaviour(p, k) otherwise (unlisted)
2176
- */
2177
- checkAccess(callerPort, key) {
2178
- const p = this.accessPolicy;
2179
- if (!p) return { allowed: true };
2180
- if (p.forbid.includes(callerPort))
2181
- return { allowed: false, reason: `Port ${callerPort} is explicitly forbidden from accessing this endpoint.` };
2182
- if (p.allow.includes(callerPort))
2183
- return { allowed: true };
2184
- if (p.allow_with_key.includes(callerPort)) {
2185
- if (key && key === this.accessKey) return { allowed: true };
2186
- return {
2187
- allowed: false,
2188
- reason: key ? `Invalid access key for port ${callerPort}.` : `Port ${callerPort} requires an access key (x-krnl-access-key header).`
2189
- };
2190
- }
2191
- switch (p.default_connection_behaviour) {
2192
- case "allow_unlisted":
2193
- return { allowed: true };
2194
- case "ask_key_unlisted":
2195
- if (key && key === this.accessKey) return { allowed: true };
2196
- return {
2197
- allowed: false,
2198
- reason: key ? `Invalid access key for this endpoint.` : `This endpoint requires an access key. Provide it via the 'x-krnl-access-key' header.`
2199
- };
2200
- case "forbid_unlisted":
2201
- return { allowed: false, reason: `Port ${callerPort} is not permitted. This is a restricted (internal) endpoint.` };
2202
- }
2203
- }
2204
- bindToEntity(entity) {
2205
- this.hostEntity = entity;
2206
- if (this.backend) {
2207
- this._initializeBackendTable(entity);
2208
- }
2209
- if (this.visibility === "public") {
2210
- this._registerInInterface();
2211
- }
2212
- if (typeof this.lifecycle.beginning === "function") {
2213
- this.lifecycle.beginning({
2214
- state: this.state,
2215
- emitters: this.emitters,
2216
- helpers: this.helpers,
2217
- entity: this.hostEntity,
2218
- functionality: this,
2219
- table: this.table,
2220
- backend: this.table?.provider
2221
- });
2222
- }
2223
- return this;
2224
- }
2225
- _initializeBackendTable(entity) {
2226
- try {
2227
- let service = "sqlite";
2228
- let tableName = this.id;
2229
- let credentials = void 0;
2230
- if (typeof this.backend === "string") {
2231
- service = this.backend;
2232
- } else if (typeof this.backend === "object" && this.backend !== null) {
2233
- if (this.backend.service) service = this.backend.service;
2234
- if (this.backend.table) tableName = this.backend.table;
2235
- if (this.backend.credentials) credentials = this.backend.credentials;
2236
- }
2237
- if (!credentials && entity && typeof entity.getBackendCredentials === "function") {
2238
- credentials = entity.getBackendCredentials(service);
2239
- }
2240
- const provider = WorkspaceBackendFactory.resolveDataProvider({
2241
- id: `provider-${this.id}`,
2242
- provider: service,
2243
- mode: "local",
2244
- database: {
2245
- type: service,
2246
- filePath: credentials?.filePath || `./${tableName}.sqlite`,
2247
- enableWAL: credentials?.enableWAL ?? true,
2248
- ...credentials
2249
- }
2250
- });
2251
- this.table = new FunctionalityTable(tableName, provider);
2252
- } catch (err) {
2253
- console.warn(`[KrnlBackendWarning] Failed to initialize table for functionality "${this.id}":`, err.message);
2254
- }
2255
- }
2256
- teardown() {
2257
- if (typeof this.lifecycle.teardown === "function") {
2258
- this.lifecycle.teardown({
2259
- state: this.state,
2260
- emitters: this.emitters,
2261
- helpers: this.helpers,
2262
- entity: this.hostEntity,
2263
- functionality: this,
2264
- table: this.table,
2265
- backend: this.table?.provider
2266
- });
2267
- }
2268
- }
2269
- async execute(input, opts = {}) {
2270
- const caller = opts.caller || "default";
2271
- const activeState = this.state;
2272
- const activeTelemetry = this.hostEntity?.telemetry || telemetry;
2273
- const trace = activeTelemetry.enabled ? activeTelemetry.startTrace(this.id) : null;
2274
- if (this.accessPolicy && opts.callerPort !== void 0) {
2275
- const access = this.checkAccess(opts.callerPort, opts.accessKey);
2276
- if (!access.allowed) {
2277
- if (trace) activeTelemetry.endTrace(this.id, trace, false);
2278
- return { status: "error", message: `[AccessDenied] ${access.reason}`, payload: null };
2279
- }
2280
- }
2281
- if (this.requires) {
2282
- const gateError = await this._checkRequires();
2283
- if (gateError) {
2284
- if (trace) activeTelemetry.endTrace(this.id, trace, false);
2285
- return { status: "error", message: `[DependencyGate] ${gateError}`, payload: null };
2286
- }
2287
- }
2288
- if (this.schema && this.schema.input) {
2289
- try {
2290
- if (typeof this.schema.input.verify === "function") {
2291
- const verifyError = this.schema.input.verify(input);
2292
- if (verifyError) {
2293
- throw new Error(`Protobuf verification failed: ${verifyError}`);
2294
- }
2295
- } else if (typeof this.schema.input.parse === "function") {
2296
- input = this.schema.input.parse(input);
2297
- } else if (typeof this.schema.input === "function") {
2298
- if (!this.schema.input(input)) {
2299
- throw new Error(`Input validation failed.`);
2300
- }
2301
- }
2302
- } catch (err) {
2303
- const msg = err.errors ? JSON.stringify(err.errors) : err.message;
2304
- throw new Error(`[KrnlSchemaError] Input validation failed for "${this.id}": ${msg}`);
2305
- }
2306
- }
2307
- try {
2308
- if (typeof this.lifecycle.during === "function") {
2309
- this.lifecycle.during({ input, opts, state: activeState, entity: this.hostEntity });
2310
- }
2311
- let result = await this.api(input, {
2312
- state: activeState,
2313
- emitters: this.emitters,
2314
- helpers: this.helpers,
2315
- entity: this.hostEntity,
2316
- functionality: this,
2317
- caller,
2318
- table: this.table,
2319
- backend: this.table?.provider
2320
- });
2321
- if (this.schema && this.schema.output) {
2322
- try {
2323
- if (typeof this.schema.output.verify === "function") {
2324
- const verifyError = this.schema.output.verify(result);
2325
- if (verifyError) {
2326
- console.warn(`[KrnlSchemaWarning] Output validation failed for "${this.id}": Protobuf verification failed: ${verifyError}`);
2327
- }
2328
- } else if (typeof this.schema.output.parse === "function") {
2329
- this.schema.output.parse(result);
2330
- } else if (typeof this.schema.output === "function") {
2331
- if (!this.schema.output(result)) {
2332
- console.warn(`[KrnlSchemaWarning] Output validation failed for "${this.id}".`);
2333
- }
2334
- }
2335
- } catch (err) {
2336
- const msg = err.errors ? JSON.stringify(err.errors) : err.message;
2337
- console.warn(`[KrnlSchemaWarning] Output validation failed for "${this.id}": ${msg}`);
2338
- }
2339
- }
2340
- if (trace) activeTelemetry.endTrace(this.id, trace, true);
2341
- const interactionEvent = {
2342
- type: "frontend:interaction",
2343
- fid: this.id,
2344
- timestamp: Date.now(),
2345
- input,
2346
- output: result
2347
- };
2348
- const stateEmitter = this.emitters.get("state:changed");
2349
- stateEmitter?.pushDataStreamToEmitter(interactionEvent);
2350
- let rootSystem = this.hostEntity;
2351
- while (rootSystem && !rootSystem._frontend) {
2352
- rootSystem = rootSystem.hierarchyManager?.getOwnerEntity?.();
2353
- }
2354
- const frontend = rootSystem?._frontend;
2355
- if (frontend) {
2356
- frontend.interactionsHistory.push(interactionEvent);
2357
- if (frontend.interactionsHistory.length > 50) {
2358
- frontend.interactionsHistory.shift();
2359
- }
2360
- }
2361
- this._hasBeenExecuted = true;
2362
- return {
2363
- status: "success",
2364
- payload: result
2365
- };
2366
- } catch (err) {
2367
- if (trace) activeTelemetry.endTrace(this.id, trace, false);
2368
- const interactionEvent = {
2369
- type: "frontend:interaction",
2370
- fid: this.id,
2371
- timestamp: Date.now(),
2372
- input,
2373
- output: { status: "error", message: err.message, payload: null }
2374
- };
2375
- const stateEmitter = this.emitters.get("state:changed");
2376
- stateEmitter?.pushDataStreamToEmitter(interactionEvent);
2377
- let rootSystem = this.hostEntity;
2378
- while (rootSystem && !rootSystem._frontend) {
2379
- rootSystem = rootSystem.hierarchyManager?.getOwnerEntity?.();
2380
- }
2381
- const frontend = rootSystem?._frontend;
2382
- if (frontend) {
2383
- frontend.interactionsHistory.push(interactionEvent);
2384
- if (frontend.interactionsHistory.length > 50) {
2385
- frontend.interactionsHistory.shift();
2386
- }
2387
- }
2388
- if (typeof this.lifecycle.failure === "function") {
2389
- this.lifecycle.failure({ error: err, input, caller });
2390
- }
2391
- return {
2392
- status: "error",
2393
- message: err.message,
2394
- payload: null
2395
- };
2396
- }
2397
- }
2398
- async _checkRequires() {
2399
- const r = this.requires;
2400
- const entity = this.hostEntity;
2401
- for (const fid of r.functionalitiesExecuted ?? []) {
2402
- const sibling = entity?.localFunctionalities?.get(fid);
2403
- if (!sibling?._hasBeenExecuted) {
2404
- return `Requires functionality '${fid}' to have been executed first.`;
2405
- }
2406
- }
2407
- for (const flag of r.flags ?? []) {
2408
- if (!entity?._krnlFlags?.has(flag)) {
2409
- return `Requires flag '${flag}' to be set. Check boot sequence or entity initialization.`;
2410
- }
2411
- }
2412
- if (typeof r.check === "function") {
2413
- const result = await r.check(entity);
2414
- if (result) return result;
2415
- }
2416
- return null;
2417
- }
2418
- };
2419
- var krnlRemoteFunctionality = class {
2420
- id;
2421
- targetFunction;
2422
- targetEntity;
2423
- visibility;
2424
- uiSpec;
2425
- schema;
2426
- isLocal = false;
2427
- transport;
2428
- hostEntity;
2429
- constructor(config = {}) {
2430
- const { id, targetEntity, targetFunction, transport, visibility = "public", uiSpec, schema } = config;
2431
- this.id = id;
2432
- this.targetFunction = targetFunction || id;
2433
- this.targetEntity = targetEntity;
2434
- this.visibility = visibility;
2435
- const targetLocalAtom = targetEntity?.localFunctionalities?.get?.(this.targetFunction);
2436
- this.uiSpec = uiSpec || targetLocalAtom?.uiSpec || targetLocalAtom?.ui_spec;
2437
- this.schema = schema || targetLocalAtom?.schema;
2438
- if (transport) {
2439
- this.transport = transport;
2440
- } else if (targetEntity) {
2441
- this.transport = new MemoryTransportAdapter(targetEntity);
2442
- } else {
2443
- throw new Error("RemoteFunctionality requires either a transport or a targetEntity.");
2444
- }
2445
- }
2446
- setVisibility(v) {
2447
- const oldVisibility = this.visibility;
2448
- this.visibility = v;
2449
- if (this.hostEntity && oldVisibility === "private" && v === "public") {
2450
- this._registerInInterface();
2451
- const owner = this.hostEntity.hierarchyManager.getOwnerEntity();
2452
- if (owner) owner._onComponentFunctionalityAdded(this.hostEntity, this);
2453
- } else if (this.hostEntity && oldVisibility === "public" && v === "private") {
2454
- this._unregisterFromInterface();
2455
- const owner = this.hostEntity.hierarchyManager.getOwnerEntity();
2456
- if (owner && owner._onComponentFunctionalityRemoved) {
2457
- owner._onComponentFunctionalityRemoved(this.hostEntity, this.id);
2458
- }
2459
- }
2460
- }
2461
- _unregisterFromInterface() {
2462
- if (!this.hostEntity) return;
2463
- this.hostEntity.interface.removeCollector(this.id);
2464
- }
2465
- _registerInInterface() {
2466
- const mainCollector = this.hostEntity.interface.createCollector(this.id);
2467
- mainCollector._directHandler = async (msg) => {
2468
- const caller = msg.metadata?.caller || "anonymous";
2469
- return await this.execute(msg.data, { caller });
2470
- };
2471
- }
2472
- bindToEntity(entity) {
2473
- this.hostEntity = entity;
2474
- if (this.visibility === "public") {
2475
- this._registerInInterface();
2476
- }
2477
- }
2478
- async execute(input, opts = {}) {
2479
- return await this.transport.call(this.targetFunction, input, { ...opts, caller: this.hostEntity.entityName });
2480
- }
2481
- };
2482
-
2483
- // src/core/K_ENT_Krnl_Entity_Base.ts
2484
- var krnlEntityBase = class _krnlEntityBase {
2485
- __krnlEntityInstance;
2486
- id;
2487
- entityName;
2488
- Singleton;
2489
- baseName;
2490
- instanceNumber;
2491
- telemetry;
2492
- _telemetryEnabled = false;
2493
- get telemetryEnabled() {
2494
- return this._telemetryEnabled;
2495
- }
2496
- set telemetryEnabled(val) {
2497
- this._telemetryEnabled = val;
2498
- this.telemetry.enabled = val;
2499
- }
2500
- systemType = "BaseEntity";
2501
- interface;
2502
- localFunctionalities;
2503
- remoteFunctionalities;
2504
- collectors;
2505
- hierarchyManager;
2506
- intention;
2507
- backendSettings;
2508
- /**
2509
- * Configures backend services and credentials for this entity and cascading child functionalities.
2510
- */
2511
- configureBackend(settings) {
2512
- this.backendSettings = {
2513
- ...this.backendSettings,
2514
- ...settings
2515
- };
2516
- return this;
2517
- }
2518
- /**
2519
- * Resolves backend credentials for a specific service, cascading from parent entities if necessary.
2520
- */
2521
- getBackendCredentials(service) {
2522
- if (this.backendSettings) {
2523
- if (service && this.backendSettings[service]) {
2524
- return this.backendSettings[service];
2525
- }
2526
- const defaultSvc = this.backendSettings.defaultService;
2527
- if (defaultSvc && this.backendSettings[defaultSvc]) {
2528
- return this.backendSettings[defaultSvc];
2529
- }
2530
- }
2531
- const owner = this.hierarchyManager?.getOwnerEntity();
2532
- if (owner && typeof owner.getBackendCredentials === "function") {
2533
- return owner.getBackendCredentials(service);
2534
- }
2535
- return void 0;
2536
- }
2537
- // Extension points for decorators/middleware
2538
- async _decorateResult(result, fid, input) {
2539
- return result;
2540
- }
2541
- async _decorateError(error, fid, input) {
2542
- return error;
2543
- }
2544
- /**
2545
- * @param name - The unique identity of the entity.
2546
- * @param owner - The parent entity (if any).
2547
- */
2548
- constructor(name, owner = null, options = {}) {
2549
- this.__krnlEntityInstance = true;
2550
- this.id = name || "UnnamedEntity";
2551
- this.entityName = this.id;
2552
- this.Singleton = options.Singleton ?? this.constructor.Singleton ?? true;
2553
- this.baseName = options.baseName || this.entityName;
2554
- this.instanceNumber = options.instanceNumber || 1;
2555
- this.telemetry = new KrnlTelemetry();
2556
- this.telemetryEnabled = options.telemetryEnabled || false;
2557
- this.intention = options.intention || null;
2558
- this.interface = new krnlInterface(this);
2559
- this.localFunctionalities = /* @__PURE__ */ new Map();
2560
- this.remoteFunctionalities = /* @__PURE__ */ new Map();
2561
- this.collectors = /* @__PURE__ */ new Set();
2562
- this.hierarchyManager = new krnlEntityCompositionalHierarchyManager(
2563
- this,
2564
- // Host.
2565
- owner,
2566
- // Parent.
2567
- _krnlEntityBase
2568
- // Base class for nesting.
2569
- );
2570
- }
2571
- /**
2572
- * Registers a local logic block.
2573
- * If the functionality is 'public', it is automatically promoted to the owner.
2574
- */
2575
- addLocal(localFunctionality) {
2576
- const functionality = localFunctionality instanceof krnlLocalFunctionality ? localFunctionality : new krnlLocalFunctionality(localFunctionality);
2577
- functionality.bindToEntity(this);
2578
- this.localFunctionalities.set(functionality.id, functionality);
2579
- const owner = this.hierarchyManager.getOwnerEntity();
2580
- if (owner && owner._onComponentFunctionalityAdded) {
2581
- owner._onComponentFunctionalityAdded(this, functionality);
2582
- }
2583
- return functionality;
2584
- }
2585
- /**
2586
- * Registers a proxy for a functionality on another entity.
2587
- * If the proxy is 'public', it is promoted to the owner (Recursive Bubbling).
2588
- */
2589
- addRemote(remoteFunctionality) {
2590
- const functionality = remoteFunctionality instanceof krnlRemoteFunctionality ? remoteFunctionality : new krnlRemoteFunctionality(remoteFunctionality);
2591
- functionality.bindToEntity(this);
2592
- this.remoteFunctionalities.set(functionality.id, functionality);
2593
- const owner = this.hierarchyManager.getOwnerEntity();
2594
- if (owner && owner._onComponentFunctionalityAdded) {
2595
- owner._onComponentFunctionalityAdded(this, functionality);
2596
- }
2597
- return functionality;
2598
- }
2599
- /**
2600
- * INTERFACE PROMOTION
2601
- * Handles the automatic bubbling of component logic to the owner.
2602
- */
2603
- _onComponentFunctionalityAdded(component, functionality) {
2604
- if (component._isIngressNetworkMember) return;
2605
- if (functionality.visibility !== "public") return;
2606
- const existing = this.remoteFunctionalities.get(functionality.id);
2607
- if (existing) {
2608
- existing.targetEntity = component;
2609
- existing.targetFunction = functionality.id;
2610
- return;
2611
- }
2612
- this.addRemote({
2613
- id: functionality.id,
2614
- targetEntity: component,
2615
- targetFunction: functionality.id,
2616
- visibility: "public"
2617
- // Bubbles up further by default.
2618
- });
2619
- }
2620
- /**
2621
- * Removes a promoted remote functionality and recursively propagates removal upward.
2622
- */
2623
- _onComponentFunctionalityRemoved(component, functionalityId) {
2624
- const existing = this.remoteFunctionalities.get(functionalityId);
2625
- if (!existing) return;
2626
- if (existing.targetEntity !== component) return;
2627
- this.remoteFunctionalities.delete(functionalityId);
2628
- const owner = this.hierarchyManager.getOwnerEntity();
2629
- if (owner && owner._onComponentFunctionalityRemoved) {
2630
- owner._onComponentFunctionalityRemoved(this, functionalityId);
2631
- }
2632
- }
2633
- /**
2634
- * Internal helper to trigger promotion of all existing functionalities.
2635
- */
2636
- _promoteAllExistingFunctionalities() {
2637
- const owner = this.hierarchyManager.getOwnerEntity();
2638
- if (!owner || !owner._onComponentFunctionalityAdded) return;
2639
- this.localFunctionalities.forEach((f) => {
2640
- owner._onComponentFunctionalityAdded(this, f);
2641
- });
2642
- this.remoteFunctionalities.forEach((f) => {
2643
- owner._onComponentFunctionalityAdded(this, f);
2644
- });
2645
- }
2646
- /**
2647
- * Executes a functionality by ID.
2648
- */
2649
- async call(fid, input, opts = {}) {
2650
- const unwrap = opts.unwrap !== false;
2651
- try {
2652
- let result;
2653
- if (this.localFunctionalities.has(fid)) {
2654
- result = await this.localFunctionalities.get(fid).execute(input, opts);
2655
- } else if (this.remoteFunctionalities.has(fid)) {
2656
- result = await this.remoteFunctionalities.get(fid).execute(input, opts);
2657
- } else {
2658
- throw new krnlError(krnlErrorCodes.FUNCTIONALITY_NOT_DEFINED);
2659
- }
2660
- result = await this._decorateResult(result, fid, input);
2661
- if (unwrap && result && typeof result === "object" && result.status === "success" && "payload" in result && !result.skipUnwrap) {
2662
- return result.payload;
2663
- }
2664
- if (result && typeof result === "object" && result.status === "error") {
2665
- throw new krnlError(result.message || krnlErrorCodes.REMOTE_EXECUTION_FAILED);
2666
- }
2667
- return result;
2668
- } catch (err) {
2669
- let finalErr = err;
2670
- finalErr = await this._decorateError(err, fid, input);
2671
- if (finalErr && typeof finalErr === "object" && finalErr.status === "error") {
2672
- const wrapper = new krnlError(finalErr.message || krnlErrorCodes.REMOTE_EXECUTION_FAILED);
2673
- Object.assign(wrapper, finalErr);
2674
- throw wrapper;
2675
- }
2676
- throw finalErr;
2677
- }
2678
- }
2679
- getLocal(fid) {
2680
- return this.localFunctionalities.get(fid);
2681
- }
2682
- getRemote(fid) {
2683
- return this.remoteFunctionalities.get(fid);
2684
- }
2685
- resolveLocalFunctionality(fid) {
2686
- if (this.localFunctionalities.has(fid)) {
2687
- return this.localFunctionalities.get(fid);
2688
- }
2689
- let current = this.remoteFunctionalities.get(fid);
2690
- const visited = /* @__PURE__ */ new Set();
2691
- while (current) {
2692
- if (visited.has(current)) {
2693
- break;
2694
- }
2695
- visited.add(current);
2696
- if (current.isLocal) {
2697
- return current;
2698
- }
2699
- const target = current.targetEntity || current.transport && (current.transport.targetEntity || current.transport.target || current.transport.instance);
2700
- if (target) {
2701
- const targetFid = current.targetFunction || fid;
2702
- if (target.localFunctionalities && target.localFunctionalities.has(targetFid)) {
2703
- return target.localFunctionalities.get(targetFid);
2704
- }
2705
- if (target.remoteFunctionalities && target.remoteFunctionalities.has(targetFid)) {
2706
- current = target.remoteFunctionalities.get(targetFid);
2707
- continue;
2708
- }
2709
- }
2710
- break;
2711
- }
2712
- return null;
2713
- }
2714
- addChild(instance) {
2715
- return this.hierarchyManager.addComponentEntityInstance(instance);
2716
- }
2717
- getTelemetry() {
2718
- const summary = this.telemetry.getSummary();
2719
- return {
2720
- entity: this.entityName,
2721
- timestamp: Date.now(),
2722
- metrics: summary.metrics,
2723
- callLogs: summary.callLogs,
2724
- libraryUsage: summary.libraryUsage,
2725
- dataUsage: summary.dataUsage
2726
- };
2727
- }
2728
- disposeOwnedComponent(entityId) {
2729
- return this.hierarchyManager.disposeComponentEntity(entityId);
2730
- }
2731
- dispose() {
2732
- if (this.hierarchyManager) this.hierarchyManager.dispose();
2733
- if (this.interface) this.interface.dispose();
2734
- this.localFunctionalities.forEach((func) => {
2735
- if (typeof func.teardown === "function") {
2736
- func.teardown();
2737
- }
2738
- });
2739
- this.localFunctionalities.clear();
2740
- this.remoteFunctionalities.clear();
2741
- }
2742
- };
2743
-
2744
- export {
2745
- krnlErrorCodes,
2746
- krnlErrorMessages,
2747
- CUSTOM_ERROR_CODE,
2748
- krnlError,
2749
- krnlGlobalEmitterAddress,
2750
- krnlLocalEmitterAddress,
2751
- krnlMessage,
2752
- krnlEmitter,
2753
- krnlCollector,
2754
- krnlInterface,
2755
- krnlEntityCompositionalHierarchyManager,
2756
- FunctionalityTable,
2757
- SQLiteDataProvider,
2758
- PostgresDataProvider,
2759
- SupabaseDataProvider,
2760
- PocketBaseDataProvider,
2761
- FirebaseDataProvider,
2762
- FilesystemStorageProvider,
2763
- SupabaseStorageProvider,
2764
- S3StorageProvider,
2765
- PocketBaseStorageProvider,
2766
- FirebaseStorageProvider,
2767
- WorkspaceBackendFactory,
2768
- LocalSQLiteAccountProvider,
2769
- HostedAccountProvider,
2770
- ControlPlaneManager,
2771
- AdminGuard,
2772
- krnlTransportAdapter,
2773
- MemoryTransportAdapter,
2774
- krnlLocalFunctionality,
2775
- krnlRemoteFunctionality,
2776
- krnlEntityBase
2777
- };