@ultrst-armada/krnl 0.0.0-stage → 1.0.1

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 (236) hide show
  1. package/README.md +95 -2
  2. package/package.json +75 -4
  3. package/packages/cli/dist/K_ENT_Entity-PQ5MURQY-ZG6FZXXX.js +13 -0
  4. package/packages/cli/dist/K_LIB_Krnl_Aiko_Client-OPZAVZCW-K4CRQYA5.js +8 -0
  5. package/packages/cli/dist/K_LIB_Krnl_Ep_Tools-ROOE2TQF-LNPXZYOE.js +110 -0
  6. package/packages/cli/dist/K_LIB_Krnl_Frontend_Builder-2ZDUH6PF-3ALZPNX4.js +11 -0
  7. package/packages/cli/dist/K_LIB_Krnl_Frontend_Generator-UYNRNX2X-PJTICYSW.js +11 -0
  8. package/packages/cli/dist/K_LIB_Krnl_Registry_Client-NXV6D2QW-M5TYU55O.js +8 -0
  9. package/packages/cli/dist/K_LIB_Krnl_SubApp_Engine-7HR5HWW2-H6STOXRK.js +20 -0
  10. package/packages/cli/dist/K_LIB_Krnl_SubApp_Registry-7XYGDKJK-XPJXSF7D.js +19 -0
  11. package/packages/cli/dist/K_LIB_Krnl_SubApp_Worker_Host-CQVTGGG7-CUYGTWOW.js +7 -0
  12. package/packages/cli/dist/K_LIB_Krnl_System_App_Adapter-M6FJKLGU-VR6T4N6J.js +17 -0
  13. package/packages/cli/dist/K_LIB_Krnl_System_Base_Functionality_APIs-ZZUZ6ZG5-RLJ4QWDP.js +58 -0
  14. package/packages/cli/dist/K_LIB_Krnl_System_Magnetic_Loader-XBQO2KXF-BOQGUASC.js +22 -0
  15. package/packages/cli/dist/K_LIB_Krnl_System_Unified_Http_Adapter-RCEGP3OG-XJI7KIT5.js +8 -0
  16. package/packages/cli/dist/K_LIB_Krnl_Telemetry-77FRZ3KV-K5VCWAFW.js +9 -0
  17. package/packages/cli/dist/bin/krnl.cjs +9758 -0
  18. package/packages/cli/dist/bin/krnl.d.cts +1 -0
  19. package/packages/cli/dist/bin/krnl.d.ts +1 -0
  20. package/packages/cli/dist/bin/krnl.js +2006 -0
  21. package/packages/cli/dist/chunk-3TRM6CYL.js +152 -0
  22. package/packages/cli/dist/chunk-5JDK35TG.js +3872 -0
  23. package/packages/cli/dist/chunk-63PTK33I.js +997 -0
  24. package/packages/cli/dist/chunk-6NIKAMUZ.js +82 -0
  25. package/packages/cli/dist/chunk-BOXWWXQG.js +400 -0
  26. package/packages/cli/dist/chunk-EEKLK7QJ.js +565 -0
  27. package/packages/cli/dist/chunk-EG7T2IAD.js +107 -0
  28. package/packages/cli/dist/chunk-F5EHXE2O.js +1036 -0
  29. package/packages/cli/dist/chunk-F65ANSQG.js +269 -0
  30. package/packages/cli/dist/chunk-FDNCADFE.js +71 -0
  31. package/packages/cli/dist/chunk-GDLRMDAN.js +127 -0
  32. package/packages/cli/dist/chunk-HWMTCMOS.js +656 -0
  33. package/packages/cli/dist/chunk-I74QIQOD.js +5536 -0
  34. package/packages/cli/dist/chunk-JTLSTO25.js +71 -0
  35. package/packages/cli/dist/chunk-JULBBJ27.js +1033 -0
  36. package/packages/cli/dist/chunk-OHVMVRBP.js +117 -0
  37. package/packages/cli/dist/chunk-P2PCLEKX.js +666 -0
  38. package/packages/cli/dist/chunk-PJQIUOX2.js +7767 -0
  39. package/packages/cli/dist/chunk-PPOF3DJW.js +471 -0
  40. package/packages/cli/dist/chunk-Q45257P6.js +173 -0
  41. package/packages/cli/dist/chunk-QNROWGBI.js +1036 -0
  42. package/packages/cli/dist/chunk-RJNYUXZD.js +977 -0
  43. package/packages/cli/dist/chunk-SRTOPJ5W.js +104 -0
  44. package/packages/cli/dist/chunk-TCEX3MPS.js +702 -0
  45. package/packages/cli/dist/chunk-TNOAJO2J.js +675 -0
  46. package/packages/cli/dist/chunk-UR2SUCSF.js +701 -0
  47. package/packages/cli/dist/chunk-X5LOIFM7.js +68 -0
  48. package/packages/cli/dist/chunk-XIRFOO3H.js +589 -0
  49. package/packages/cli/dist/chunk-ZAAV3JXQ.js +809 -0
  50. package/packages/cli/dist/index.cjs +7798 -0
  51. package/packages/cli/dist/index.d.cts +7 -0
  52. package/packages/cli/dist/index.d.ts +7 -0
  53. package/packages/cli/dist/index.js +29 -0
  54. package/packages/cli/package.json +34 -0
  55. package/packages/core/dist/K_ENT_Entity-4MB7CU4A.js +12 -0
  56. package/packages/core/dist/K_ENT_Entity-DEJGIDGH.js +12 -0
  57. package/packages/core/dist/K_ENT_Entity-FXZO5UZ2.js +12 -0
  58. package/packages/core/dist/K_ENT_Entity-HDSCXC5F.js +12 -0
  59. package/packages/core/dist/K_ENT_Entity-JILABHLW.js +12 -0
  60. package/packages/core/dist/K_ENT_Entity-PQ5MURQY.js +13 -0
  61. package/packages/core/dist/K_ENT_Entity-ROAKDIHW.js +12 -0
  62. package/packages/core/dist/K_ENT_Entity-TBVFSKDV.js +12 -0
  63. package/packages/core/dist/K_ENT_Entity-ZFLKG3JO.js +12 -0
  64. package/packages/core/dist/K_LIB_Krnl_Aiko_Client-OPZAVZCW.js +8 -0
  65. package/packages/core/dist/K_LIB_Krnl_Ep_Tools-ROOE2TQF.js +110 -0
  66. package/packages/core/dist/K_LIB_Krnl_Frontend_Builder-2ZDUH6PF.js +9 -0
  67. package/packages/core/dist/K_LIB_Krnl_Frontend_Generator-UYNRNX2X.js +9 -0
  68. package/packages/core/dist/K_LIB_Krnl_Registry_Client-NXV6D2QW.js +8 -0
  69. package/packages/core/dist/K_LIB_Krnl_SubApp_Engine-7HR5HWW2.js +20 -0
  70. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-4C6GBQAG.js +18 -0
  71. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-6V23A6F6.js +18 -0
  72. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-7XYGDKJK.js +19 -0
  73. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-DYLLC5G2.js +18 -0
  74. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-F4FOFAUP.js +18 -0
  75. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-FBOXXMI3.js +18 -0
  76. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-Q73BWLNP.js +18 -0
  77. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-QM2C4MVA.js +18 -0
  78. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-QUGI6SMP.js +18 -0
  79. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-RGMTBHNP.js +18 -0
  80. package/packages/core/dist/K_LIB_Krnl_SubApp_Registry-RWR7UNDW.js +18 -0
  81. package/packages/core/dist/K_LIB_Krnl_SubApp_Worker_Host-CQVTGGG7.js +7 -0
  82. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-32MFJJ5Z.js +17 -0
  83. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-4J4CEWRY.js +17 -0
  84. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-A366YHF2.js +17 -0
  85. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-LK4LYJHI.js +17 -0
  86. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-M6FJKLGU.js +17 -0
  87. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-NW3K63II.js +17 -0
  88. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-QDHTI5ZV.js +17 -0
  89. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-VHCT6VIW.js +17 -0
  90. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-WBRKF24R.js +17 -0
  91. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-XKYQYT6Q.js +17 -0
  92. package/packages/core/dist/K_LIB_Krnl_System_App_Adapter-Z2PWZYDZ.js +17 -0
  93. package/packages/core/dist/K_LIB_Krnl_System_Base_Functionality_APIs-ZZUZ6ZG5.js +58 -0
  94. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-2EZU7QF4.js +21 -0
  95. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-6G3AQNAV.js +21 -0
  96. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-B2NZMQUG.js +21 -0
  97. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-C2RABMZP.js +21 -0
  98. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-HHE3NZ4F.js +21 -0
  99. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-LHFGR6WK.js +21 -0
  100. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-M74BLM3N.js +21 -0
  101. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-PT6ZA6EA.js +21 -0
  102. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-SP52V3CX.js +21 -0
  103. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-XBQO2KXF.js +22 -0
  104. package/packages/core/dist/K_LIB_Krnl_System_Magnetic_Loader-YNSEUHJJ.js +21 -0
  105. package/packages/core/dist/K_LIB_Krnl_System_Unified_Http_Adapter-M6SBHIVA.js +8 -0
  106. package/packages/core/dist/K_LIB_Krnl_System_Unified_Http_Adapter-RCEGP3OG.js +8 -0
  107. package/packages/core/dist/K_LIB_Krnl_Telemetry-77FRZ3KV.js +9 -0
  108. package/packages/core/dist/chunk-33L2J7V7.js +82 -0
  109. package/packages/core/dist/chunk-3ES4K2ZP.js +817 -0
  110. package/packages/core/dist/chunk-3SMHVVLL.js +82 -0
  111. package/packages/core/dist/chunk-3UEZ7JQA.js +4877 -0
  112. package/packages/core/dist/chunk-3XIE6KBD.js +4877 -0
  113. package/packages/core/dist/chunk-46ZLCML6.js +107 -0
  114. package/packages/core/dist/chunk-4UEL3DWJ.js +107 -0
  115. package/packages/core/dist/chunk-54GWZ5PC.js +82 -0
  116. package/packages/core/dist/chunk-6QCYRS5L.js +127 -0
  117. package/packages/core/dist/chunk-6ULMHNXR.js +104 -0
  118. package/packages/core/dist/chunk-7WUETJEV.js +117 -0
  119. package/packages/core/dist/chunk-A5KRAYDB.js +107 -0
  120. package/packages/core/dist/chunk-ANEAZ3PO.js +107 -0
  121. package/packages/core/dist/chunk-BE76RL6F.js +82 -0
  122. package/packages/core/dist/chunk-CIARVYDO.js +107 -0
  123. package/packages/core/dist/chunk-CR2ANE62.js +107 -0
  124. package/packages/core/dist/chunk-DI27MOR7.js +173 -0
  125. package/packages/core/dist/chunk-E6RLFHM5.js +596 -0
  126. package/packages/core/dist/chunk-EELAPMNV.js +4877 -0
  127. package/packages/core/dist/chunk-ENZ2RQVJ.js +107 -0
  128. package/packages/core/dist/chunk-F2U6CX4F.js +4877 -0
  129. package/packages/core/dist/chunk-FKG64OHL.js +82 -0
  130. package/packages/core/dist/chunk-FYAZJYM5.js +772 -0
  131. package/packages/core/dist/chunk-G4NP4RDQ.js +82 -0
  132. package/packages/core/dist/chunk-GADIRLRS.js +473 -0
  133. package/packages/core/dist/chunk-GR6CSLQJ.js +772 -0
  134. package/packages/core/dist/chunk-HDS7AT6O.js +772 -0
  135. package/packages/core/dist/chunk-HIMEZUU2.js +71 -0
  136. package/packages/core/dist/chunk-IB4UHG5I.js +596 -0
  137. package/packages/core/dist/chunk-J7ZYNVRS.js +772 -0
  138. package/packages/core/dist/chunk-JVLZU4K7.js +604 -0
  139. package/packages/core/dist/chunk-JYXXI7Q3.js +82 -0
  140. package/packages/core/dist/chunk-K54K2KZW.js +192 -0
  141. package/packages/core/dist/chunk-K6VHLBNH.js +3316 -0
  142. package/packages/core/dist/chunk-KCBP7ZYA.js +596 -0
  143. package/packages/core/dist/chunk-KFQGP6VL.js +33 -0
  144. package/packages/core/dist/chunk-KIUEUI7K.js +82 -0
  145. package/packages/core/dist/chunk-LB67NIZP.js +949 -0
  146. package/packages/core/dist/chunk-LDTYFUNW.js +596 -0
  147. package/packages/core/dist/chunk-MLVWARD4.js +596 -0
  148. package/packages/core/dist/chunk-MPYVXHKO.js +2777 -0
  149. package/packages/core/dist/chunk-MRQ3MITU.js +772 -0
  150. package/packages/core/dist/chunk-MVUN7I7O.js +107 -0
  151. package/packages/core/dist/chunk-NDDOIRW7.js +596 -0
  152. package/packages/core/dist/chunk-O3KDB5MH.js +3330 -0
  153. package/packages/core/dist/chunk-OEINUDSE.js +400 -0
  154. package/packages/core/dist/chunk-OPDENPT4.js +4877 -0
  155. package/packages/core/dist/chunk-P6XEM2LA.js +429 -0
  156. package/packages/core/dist/chunk-QKMRSQV4.js +82 -0
  157. package/packages/core/dist/chunk-R6CCWALL.js +4877 -0
  158. package/packages/core/dist/chunk-RAMMOO73.js +774 -0
  159. package/packages/core/dist/chunk-S3FTZFG6.js +772 -0
  160. package/packages/core/dist/chunk-T2ZVN434.js +4877 -0
  161. package/packages/core/dist/chunk-TFHLDMIA.js +107 -0
  162. package/packages/core/dist/chunk-TI3QUCIJ.js +107 -0
  163. package/packages/core/dist/chunk-TR2BAIGI.js +107 -0
  164. package/packages/core/dist/chunk-UGVVJKC6.js +4877 -0
  165. package/packages/core/dist/chunk-V2DX7YIU.js +984 -0
  166. package/packages/core/dist/chunk-W4IHYUYD.js +772 -0
  167. package/packages/core/dist/chunk-W6WBG5OY.js +4877 -0
  168. package/packages/core/dist/chunk-WN3M7O7H.js +3312 -0
  169. package/packages/core/dist/chunk-WR3NCU7U.js +4877 -0
  170. package/packages/core/dist/chunk-XC6B6L27.js +82 -0
  171. package/packages/core/dist/chunk-XNSE64ZY.js +3316 -0
  172. package/packages/core/dist/chunk-XROES2WN.js +634 -0
  173. package/packages/core/dist/chunk-XSCKNRCZ.js +5020 -0
  174. package/packages/core/dist/chunk-XVABPAUZ.js +82 -0
  175. package/packages/core/dist/chunk-YOBCB5C5.js +596 -0
  176. package/packages/core/dist/chunk-YUK6Q563.js +666 -0
  177. package/packages/core/dist/chunk-YXGL3ZEU.js +1030 -0
  178. package/packages/core/dist/chunk-ZINJ5OUX.js +596 -0
  179. package/packages/core/dist/chunk-ZPFD4BIQ.js +604 -0
  180. package/packages/core/dist/chunk-ZQZBFG6F.js +4826 -0
  181. package/packages/core/dist/chunk-ZZFRJGXM.js +4877 -0
  182. package/packages/core/dist/index.cjs +760 -0
  183. package/packages/core/dist/index.d.cts +360 -0
  184. package/packages/core/dist/index.d.ts +360 -0
  185. package/packages/core/dist/index.js +707 -0
  186. package/packages/core/package.json +34 -0
  187. package/packages/create-krnl/dist/K_ENT_Entity-PQ5MURQY-R2OH4VXE.js +14 -0
  188. package/packages/create-krnl/dist/K_LIB_Krnl_Aiko_Client-OPZAVZCW-AZM5HF4M.js +9 -0
  189. package/packages/create-krnl/dist/K_LIB_Krnl_Ep_Tools-ROOE2TQF-X5N6SV2S.js +111 -0
  190. package/packages/create-krnl/dist/K_LIB_Krnl_Frontend_Builder-2ZDUH6PF-5PFHF4JU.js +12 -0
  191. package/packages/create-krnl/dist/K_LIB_Krnl_Frontend_Generator-UYNRNX2X-ED33OQPH.js +12 -0
  192. package/packages/create-krnl/dist/K_LIB_Krnl_Registry_Client-NXV6D2QW-YGQLVR4P.js +9 -0
  193. package/packages/create-krnl/dist/K_LIB_Krnl_SubApp_Engine-7HR5HWW2-VM7CTU2L.js +21 -0
  194. package/packages/create-krnl/dist/K_LIB_Krnl_SubApp_Registry-7XYGDKJK-Y2GQFJ7I.js +21 -0
  195. package/packages/create-krnl/dist/K_LIB_Krnl_SubApp_Worker_Host-CQVTGGG7-L3JQWO54.js +8 -0
  196. package/packages/create-krnl/dist/K_LIB_Krnl_System_App_Adapter-M6FJKLGU-KQARASPR.js +19 -0
  197. package/packages/create-krnl/dist/K_LIB_Krnl_System_Base_Functionality_APIs-ZZUZ6ZG5-OF3IGLVL.js +59 -0
  198. package/packages/create-krnl/dist/K_LIB_Krnl_System_Magnetic_Loader-XBQO2KXF-JOLHKOEX.js +24 -0
  199. package/packages/create-krnl/dist/K_LIB_Krnl_System_Unified_Http_Adapter-RCEGP3OG-L46LSHKQ.js +10 -0
  200. package/packages/create-krnl/dist/K_LIB_Krnl_Telemetry-77FRZ3KV-4JUPRR3X.js +10 -0
  201. package/packages/create-krnl/dist/chunk-3TRM6CYL.js +152 -0
  202. package/packages/create-krnl/dist/chunk-3URCB3QS.js +127 -0
  203. package/packages/create-krnl/dist/chunk-5JDK35TG.js +3872 -0
  204. package/packages/create-krnl/dist/chunk-A2XAXDOW.js +812 -0
  205. package/packages/create-krnl/dist/chunk-AN6TMQHG.js +1033 -0
  206. package/packages/create-krnl/dist/chunk-BOXWWXQG.js +400 -0
  207. package/packages/create-krnl/dist/chunk-BPTBREBG.js +38 -0
  208. package/packages/create-krnl/dist/chunk-FDNCADFE.js +71 -0
  209. package/packages/create-krnl/dist/chunk-JTLSTO25.js +71 -0
  210. package/packages/create-krnl/dist/chunk-M3NCUIPL.js +107 -0
  211. package/packages/create-krnl/dist/chunk-N2EONSOC.js +7769 -0
  212. package/packages/create-krnl/dist/chunk-OHVMVRBP.js +117 -0
  213. package/packages/create-krnl/dist/chunk-Q45257P6.js +173 -0
  214. package/packages/create-krnl/dist/chunk-QGM4M3NI.js +37 -0
  215. package/packages/create-krnl/dist/chunk-RJNYUXZD.js +977 -0
  216. package/packages/create-krnl/dist/chunk-SRTOPJ5W.js +104 -0
  217. package/packages/create-krnl/dist/chunk-UPBIGEC3.js +666 -0
  218. package/packages/create-krnl/dist/chunk-V2DB7UD7.js +82 -0
  219. package/packages/create-krnl/dist/chunk-WMHLIUI6.js +3644 -0
  220. package/packages/create-krnl/dist/chunk-XIRFOO3H.js +589 -0
  221. package/packages/create-krnl/dist/chunk-Y2CEEVZP.js +5536 -0
  222. package/packages/create-krnl/dist/index.cjs +395 -0
  223. package/packages/create-krnl/dist/index.js +372 -0
  224. package/packages/create-krnl/dist/main-DXUMPBND.js +2217 -0
  225. package/packages/create-krnl/dist/wrapper-SDF2VKX3.js +31 -0
  226. package/packages/create-krnl/package.json +23 -0
  227. package/packages/eslint-plugin/dist/index.cjs +439 -0
  228. package/packages/eslint-plugin/dist/index.d.cts +336 -0
  229. package/packages/eslint-plugin/dist/index.d.ts +336 -0
  230. package/packages/eslint-plugin/dist/index.js +416 -0
  231. package/packages/eslint-plugin/package.json +24 -0
  232. package/packages/validate/dist/index.cjs +499 -0
  233. package/packages/validate/dist/index.d.cts +49 -0
  234. package/packages/validate/dist/index.d.ts +49 -0
  235. package/packages/validate/dist/index.js +462 -0
  236. package/packages/validate/package.json +27 -0
@@ -0,0 +1,666 @@
1
+ import {
2
+ KrnlEntityRegistry
3
+ } from "./chunk-FDNCADFE.js";
4
+ import {
5
+ krnlSystemEntityBase
6
+ } from "./chunk-PJQIUOX2.js";
7
+
8
+ // ../core/dist/chunk-YUK6Q563.js
9
+ import fs from "fs";
10
+ import path from "path";
11
+ import { pathToFileURL, fileURLToPath } from "url";
12
+ import { AsyncLocalStorage } from "async_hooks";
13
+ var magneticStorage = new AsyncLocalStorage();
14
+ if (!globalThis.__krnlSubAppLocalStorage) {
15
+ globalThis.__krnlSubAppLocalStorage = new AsyncLocalStorage();
16
+ }
17
+ var subappLocalStorage = globalThis.__krnlSubAppLocalStorage;
18
+ var KrnlMagneticLoader = class _KrnlMagneticLoader {
19
+ /**
20
+ * Scans and dynamically loads entities, functionalities, and subapps for the given entity or system.
21
+ */
22
+ static async loadAll(entity, rawBaseDir) {
23
+ let baseDir = rawBaseDir;
24
+ if (typeof baseDir === "string" && baseDir.startsWith("file:")) {
25
+ baseDir = fileURLToPath(baseDir);
26
+ }
27
+ if (typeof baseDir === "string" && fs.existsSync(baseDir) && fs.statSync(baseDir).isFile()) {
28
+ baseDir = path.dirname(baseDir);
29
+ }
30
+ const entityLabel = entity.entityName || entity.id || "Entity";
31
+ console.log(`[MagneticLoader] loadAll called for entity '${entityLabel}' with baseDir '${baseDir}'`);
32
+ KrnlEntityRegistry.register(entity);
33
+ const candidateFuncDirs = [
34
+ path.join(baseDir, "functionalities"),
35
+ path.join(baseDir, "..", "functionalities"),
36
+ path.join(process.cwd(), "src", "functionalities"),
37
+ path.join(process.cwd(), "functionalities")
38
+ ];
39
+ let functionalitiesDir = null;
40
+ for (const cand of candidateFuncDirs) {
41
+ if (fs.existsSync(cand) && fs.statSync(cand).isDirectory()) {
42
+ functionalitiesDir = cand;
43
+ break;
44
+ }
45
+ }
46
+ if (functionalitiesDir) {
47
+ const funcDirs = await fs.promises.readdir(functionalitiesDir, { withFileTypes: true });
48
+ for (const dirent of funcDirs) {
49
+ if (dirent.isDirectory()) {
50
+ await this.loadFunctionality(entity, path.join(functionalitiesDir, dirent.name), dirent.name);
51
+ }
52
+ }
53
+ }
54
+ const entitiesDir = path.join(baseDir, "entities");
55
+ if (fs.existsSync(entitiesDir)) {
56
+ console.warn(`[MagneticLoader] Deprecation: Nested 'entities/' found under '${baseDir}'. Krnl uses a flat multi-entity architecture where all entities are placed directly in 'src/' at the same level.`);
57
+ const entDirs = await fs.promises.readdir(entitiesDir, { withFileTypes: true });
58
+ for (const dirent of entDirs) {
59
+ if (dirent.isDirectory()) {
60
+ await this.loadEntity(entity, path.join(entitiesDir, dirent.name), dirent.name);
61
+ }
62
+ }
63
+ }
64
+ const subappsDir = path.join(baseDir, "subapps");
65
+ const isSubApp = subappLocalStorage.getStore() || entity._isSubApp || entity._isIngressNetworkMember;
66
+ const krnlJsonPath = path.join(baseDir, "krnl.json");
67
+ let subappMetaMap = {};
68
+ if (fs.existsSync(krnlJsonPath)) {
69
+ try {
70
+ const parsed = JSON.parse(fs.readFileSync(krnlJsonPath, "utf-8"));
71
+ subappMetaMap = parsed.subapps || {};
72
+ } catch (_) {
73
+ }
74
+ }
75
+ if (Object.keys(subappMetaMap).length > 0) {
76
+ if (!fs.existsSync(subappsDir)) {
77
+ fs.mkdirSync(subappsDir, { recursive: true });
78
+ }
79
+ for (const [subappName, subMeta] of Object.entries(subappMetaMap)) {
80
+ const gitUrl = subMeta.git || subMeta.repo || subMeta.repository;
81
+ if (gitUrl) {
82
+ const targetAppPath = path.join(subappsDir, subappName);
83
+ if (!fs.existsSync(targetAppPath)) {
84
+ console.log(`[MagneticLoader] Cloning sub-app '${subappName}' from git repository '${gitUrl}'...`);
85
+ try {
86
+ let cloneUrl = gitUrl;
87
+ if (cloneUrl.startsWith("github:")) {
88
+ const parts = cloneUrl.replace("github:", "").split("#");
89
+ const repoPath = parts[0];
90
+ const branch = parts[1];
91
+ cloneUrl = `https://github.com/${repoPath}.git`;
92
+ if (branch) {
93
+ cloneUrl += ` -b ${branch}`;
94
+ }
95
+ }
96
+ const { exec } = await import("child_process");
97
+ const { promisify } = await import("util");
98
+ const execPromise = promisify(exec);
99
+ await execPromise(`git clone ${cloneUrl} "${targetAppPath}"`);
100
+ console.log(`[MagneticLoader] Sub-app '${subappName}' cloned successfully from '${gitUrl}'.`);
101
+ } catch (cloneErr) {
102
+ console.error(`[MagneticLoader] Failed to clone sub-app '${subappName}' from '${gitUrl}':`, cloneErr.message || cloneErr);
103
+ }
104
+ }
105
+ }
106
+ }
107
+ }
108
+ const candidateSubappDirs = [
109
+ path.join(baseDir, "subapps"),
110
+ path.join(baseDir, "sub-apps"),
111
+ path.join(baseDir, "src", "sub-apps")
112
+ ].filter((d) => fs.existsSync(d));
113
+ const loadedSubAppPaths = /* @__PURE__ */ new Set();
114
+ for (const subappsDir2 of candidateSubappDirs) {
115
+ await this.syncParentSubAppDependencies(baseDir, subappsDir2);
116
+ const apps = await fs.promises.readdir(subappsDir2, { withFileTypes: true });
117
+ const subappConfigs = [];
118
+ for (const dirent of apps) {
119
+ if (dirent.isDirectory()) {
120
+ const appPath = path.join(subappsDir2, dirent.name);
121
+ if (loadedSubAppPaths.has(appPath)) continue;
122
+ loadedSubAppPaths.add(appPath);
123
+ const buildOk = await this.ensureSubAppBuilt(appPath, dirent.name, entity, baseDir);
124
+ if (!buildOk) {
125
+ continue;
126
+ }
127
+ if (typeof entity.loadSubApp === "function") {
128
+ const { KrnlSubAppDiscovery } = await import("./K_LIB_Krnl_SubApp_Engine-7HR5HWW2-H6STOXRK.js");
129
+ const desc = await KrnlSubAppDiscovery.locateDescriptor(appPath, dirent.name);
130
+ if (desc && (fs.existsSync(path.join(appPath, "subapp.json")) || fs.existsSync(desc.registrationPath))) {
131
+ try {
132
+ const subMeta = subappMetaMap[dirent.name] || subappMetaMap[dirent.name.toLowerCase()];
133
+ const inst = await entity.loadSubApp(desc, subMeta || {});
134
+ if (inst.state === "READY") {
135
+ console.log(`[MagneticLoader] Loaded sub-app '${dirent.name}' using registration contract on '${entity.entityName || entity.id}'.`);
136
+ continue;
137
+ }
138
+ } catch (loadErr) {
139
+ console.warn(`[MagneticLoader] SubApp registration contract load warning for '${dirent.name}':`, loadErr.message);
140
+ }
141
+ }
142
+ }
143
+ const config = await this.detectSubApp(appPath, dirent.name);
144
+ if (config) {
145
+ subappConfigs.push(config);
146
+ }
147
+ }
148
+ }
149
+ if (subappConfigs.length > 0 && typeof entity.loadSubApps === "function") {
150
+ for (const cfg of subappConfigs) {
151
+ const subMeta = subappMetaMap[cfg.prefix] || subappMetaMap[Object.keys(subappMetaMap).find((k) => k.toLowerCase() === cfg.prefix) || ""];
152
+ cfg.executionMode = subMeta?.executionMode ?? "local";
153
+ }
154
+ console.log(`[MagneticLoader] Loading ${subappConfigs.length} sub-app(s) on '${entity.entityName}' (no networking).`);
155
+ await entity.loadSubApps(subappConfigs);
156
+ }
157
+ }
158
+ let frontendDir = path.join(baseDir, "frontend");
159
+ const oldFrontendsDir = path.join(baseDir, "frontends");
160
+ if (!fs.existsSync(frontendDir) && fs.existsSync(oldFrontendsDir)) {
161
+ try {
162
+ fs.renameSync(oldFrontendsDir, frontendDir);
163
+ console.log(`[MagneticLoader] Renamed legacy 'frontends/' directory to 'frontend/' on '${entity.entityName}'.`);
164
+ } catch (err) {
165
+ console.warn(`[MagneticLoader] Failed to rename 'frontends/' -> 'frontend/': ${err.message}`);
166
+ }
167
+ }
168
+ if (entity._frontendEnabled && !fs.existsSync(frontendDir)) {
169
+ try {
170
+ fs.mkdirSync(frontendDir, { recursive: true });
171
+ } catch (_) {
172
+ }
173
+ }
174
+ if (fs.existsSync(frontendDir)) {
175
+ if (!isSubApp) {
176
+ entity.enableFrontend({ frontendDir });
177
+ }
178
+ const hasLocalFuncs = entity.localFunctionalities && entity.localFunctionalities.size > 0;
179
+ const indexExists = fs.existsSync(path.join(frontendDir, "src", "index.tsx"));
180
+ if (entity._subAppRegistry) {
181
+ for (const [prefix, entry] of entity._subAppRegistry.entries()) {
182
+ const subAppDir = entry.entity?._entityDataDir || entry.entity?._sourceDir;
183
+ if (subAppDir) {
184
+ const subFrontend = path.join(subAppDir, "frontend");
185
+ if (fs.existsSync(subFrontend) && entity._frontend) {
186
+ entity._frontend.registerSubAppFrontend(prefix, subFrontend);
187
+ }
188
+ }
189
+ }
190
+ }
191
+ if (!isSubApp || hasLocalFuncs || !indexExists) {
192
+ try {
193
+ const { KrnlFrontendGenerator } = await import("./K_LIB_Krnl_Frontend_Generator-UYNRNX2X-PJTICYSW.js");
194
+ await KrnlFrontendGenerator.generate(entity, frontendDir);
195
+ } catch (err) {
196
+ console.error(`[MagneticLoader] Frontend generator error on '${entity.entityName}':`, err.message || err);
197
+ }
198
+ try {
199
+ const { KrnlFrontendBuilder } = await import("./K_LIB_Krnl_Frontend_Builder-2ZDUH6PF-3ALZPNX4.js");
200
+ await KrnlFrontendBuilder.build(frontendDir);
201
+ if (process.env.NODE_ENV !== "production" && !isSubApp) {
202
+ KrnlFrontendBuilder.watch(frontendDir).catch((err) => {
203
+ console.warn(`[MagneticLoader] esbuild watcher error on '${entity.entityName}':`, err.message || err);
204
+ });
205
+ }
206
+ } catch (err) {
207
+ console.error(`[MagneticLoader] Frontend builder error on '${entity.entityName}':`, err.message || err);
208
+ }
209
+ }
210
+ }
211
+ const candidateAdapterDirs = [
212
+ path.join(baseDir, "protocol_adapters"),
213
+ path.join(baseDir, "..", "protocol_adapters"),
214
+ path.join(process.cwd(), "src", "protocol_adapters"),
215
+ path.join(process.cwd(), "protocol_adapters")
216
+ ];
217
+ for (const adaptersDir of candidateAdapterDirs) {
218
+ if (fs.existsSync(adaptersDir) && fs.statSync(adaptersDir).isDirectory() && typeof entity.attachAdapter === "function") {
219
+ try {
220
+ const adapterFiles = await fs.promises.readdir(adaptersDir);
221
+ for (const file of adapterFiles) {
222
+ if (file.endsWith(".js") || file.endsWith(".ts")) {
223
+ const mod = await import(pathToFileURL(path.join(adaptersDir, file)).href);
224
+ const AdapterClass = mod.default || mod[path.basename(file, path.extname(file))];
225
+ if (AdapterClass && typeof AdapterClass === "function") {
226
+ const adapterInstance = new AdapterClass();
227
+ entity.attachAdapter(adapterInstance);
228
+ console.log(`[MagneticLoader] Attached protocol adapter '${adapterInstance.name || file}' to entity '${entityLabel}'.`);
229
+ }
230
+ }
231
+ }
232
+ } catch (err) {
233
+ console.warn(`[MagneticLoader] Error scanning protocol_adapters in '${adaptersDir}':`, err.message || err);
234
+ }
235
+ break;
236
+ }
237
+ }
238
+ if (entity.localFunctionalities && typeof entity.initializeAiLayer === "function") {
239
+ const hasAiConfig = [...entity.localFunctionalities.values()].some((f) => f.ai?.enabled);
240
+ let hasAiStore = false;
241
+ const storePath = path.join(baseDir, "krnl_runtime_state.db");
242
+ if (fs.existsSync(storePath)) {
243
+ try {
244
+ const storeContent = JSON.parse(fs.readFileSync(storePath, "utf-8"));
245
+ if (storeContent?.endpointAgentProfiles && Object.keys(storeContent.endpointAgentProfiles).length > 0) {
246
+ hasAiStore = true;
247
+ }
248
+ } catch (e) {
249
+ }
250
+ }
251
+ if (hasAiConfig || hasAiStore) {
252
+ console.log(`[MagneticLoader] Automatically initializing AI Layer on '${entityLabel}'...`);
253
+ await entity.initializeAiLayer(baseDir);
254
+ entity.setFlag?.("krnl:ai_layer_ready");
255
+ }
256
+ }
257
+ for (const cand of ["libraries", "library"]) {
258
+ const librariesDir = path.join(baseDir, cand);
259
+ if (fs.existsSync(librariesDir)) {
260
+ await this.loadLibraries(entity, librariesDir);
261
+ }
262
+ }
263
+ entity.setFlag?.("krnl:magnetic_load_complete");
264
+ }
265
+ static async loadLibraries(entity, libDir) {
266
+ if (!fs.existsSync(libDir)) return;
267
+ entity.libraries = entity.libraries || {};
268
+ const scanRecursive = async (currDir) => {
269
+ const entries = await fs.promises.readdir(currDir, { withFileTypes: true });
270
+ for (const entry of entries) {
271
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
272
+ const fullPath = path.join(currDir, entry.name);
273
+ if (entry.isDirectory()) {
274
+ await scanRecursive(fullPath);
275
+ } else if (/\.(ts|js|mjs)$/.test(entry.name) && !entry.name.endsWith(".d.ts")) {
276
+ try {
277
+ const raw = path.basename(entry.name, path.extname(entry.name));
278
+ const mod = await import(pathToFileURL(fullPath).href);
279
+ entity.libraries[raw] = mod.default || mod;
280
+ console.log(`[MagneticLoader] Dynamically loaded library '${raw}' from '${fullPath}'`);
281
+ } catch (e) {
282
+ console.warn(`[MagneticLoader] Warning: Could not dynamically load library at '${fullPath}': ${e.message}`);
283
+ }
284
+ }
285
+ }
286
+ };
287
+ await scanRecursive(libDir);
288
+ }
289
+ static async loadFunctionality(entity, funcDir, funcName) {
290
+ const descriptorPath = path.join(funcDir, `${funcName}.js`);
291
+ let atom = null;
292
+ if (fs.existsSync(descriptorPath)) {
293
+ const mod = await import(pathToFileURL(descriptorPath).href);
294
+ atom = mod[`${funcName}Atom`] || mod.default || mod.Atom;
295
+ }
296
+ if (!atom) {
297
+ atom = {
298
+ id: funcName,
299
+ visibility: "public",
300
+ emitters: {}
301
+ };
302
+ const statePath = path.join(funcDir, "state_data", "state.js");
303
+ if (fs.existsSync(statePath)) {
304
+ const mod = await import(pathToFileURL(statePath).href);
305
+ atom.initialState = mod[`${funcName.toLowerCase()}InitialState`] || mod.initialState || mod.default;
306
+ }
307
+ const logicPath = path.join(funcDir, "main_function", "logic.js");
308
+ if (fs.existsSync(logicPath)) {
309
+ const mod = await import(pathToFileURL(logicPath).href);
310
+ atom.api = mod.main || mod.default;
311
+ }
312
+ const lifecyclePath = path.join(funcDir, "main_function", "lifecycle.js");
313
+ if (fs.existsSync(lifecyclePath)) {
314
+ const mod = await import(pathToFileURL(lifecyclePath).href);
315
+ atom.onMount = mod.onMount;
316
+ atom.onTeardown = mod.onTeardown;
317
+ }
318
+ const manifestPath = path.join(funcDir, "manifest.json");
319
+ if (fs.existsSync(manifestPath)) {
320
+ try {
321
+ const parsedManifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
322
+ atom.manifest = parsedManifest;
323
+ } catch (e) {
324
+ console.warn(`[MagneticLoader] Error parsing manifest.json in '${funcDir}':`, e.message);
325
+ }
326
+ }
327
+ const eventsDir2 = path.join(funcDir, "events");
328
+ if (fs.existsSync(eventsDir2)) {
329
+ const eventFiles = await fs.promises.readdir(eventsDir2);
330
+ for (const file of eventFiles) {
331
+ if (file.endsWith(".js")) {
332
+ const name = path.basename(file, ".js");
333
+ atom.emitters[name] = {};
334
+ }
335
+ }
336
+ }
337
+ }
338
+ if (atom && !atom.manifest) {
339
+ const manifestPath = path.join(funcDir, "manifest.json");
340
+ if (fs.existsSync(manifestPath)) {
341
+ try {
342
+ atom.manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
343
+ } catch (_) {
344
+ }
345
+ }
346
+ }
347
+ const helpers = {};
348
+ const helpersDir = path.join(funcDir, "helper_functions");
349
+ if (fs.existsSync(helpersDir)) {
350
+ const files = await fs.promises.readdir(helpersDir);
351
+ for (const file of files) {
352
+ if (file.endsWith(".js")) {
353
+ const name = path.basename(file, ".js");
354
+ const mod = await import(pathToFileURL(path.join(helpersDir, file)).href);
355
+ helpers[name] = mod[name] || mod.default || mod;
356
+ this.registerGlobalWrapper(name);
357
+ }
358
+ }
359
+ }
360
+ const events = {};
361
+ const eventsDir = path.join(funcDir, "events");
362
+ if (fs.existsSync(eventsDir)) {
363
+ const files = await fs.promises.readdir(eventsDir);
364
+ for (const file of files) {
365
+ if (file.endsWith(".js")) {
366
+ const name = path.basename(file, ".js");
367
+ const mod = await import(pathToFileURL(path.join(eventsDir, file)).href);
368
+ events[name] = mod[name] || mod.default || mod;
369
+ this.registerGlobalWrapper(name);
370
+ }
371
+ }
372
+ }
373
+ const originalApi = atom.api;
374
+ if (originalApi) {
375
+ atom.api = async (input, context) => {
376
+ return await magneticStorage.run({ helpers, events }, async () => {
377
+ return await originalApi(input, context);
378
+ });
379
+ };
380
+ }
381
+ entity.addLocal(atom);
382
+ }
383
+ static async loadEntity(parent, entDir, entName) {
384
+ let fileToImport = null;
385
+ const candidates = [`${entName}.js`, "assembler.js", "index.js"];
386
+ for (const cand of candidates) {
387
+ const p = path.join(entDir, cand);
388
+ if (fs.existsSync(p)) {
389
+ fileToImport = p;
390
+ break;
391
+ }
392
+ }
393
+ let childInstance = null;
394
+ if (fileToImport) {
395
+ const mod = await import(pathToFileURL(fileToImport).href);
396
+ const ClassToUse = mod[entName] || mod.default || mod.Entity;
397
+ if (ClassToUse && parent.hierarchyManager) {
398
+ childInstance = parent.hierarchyManager.createComponentEntity(entName, ClassToUse);
399
+ console.log(`[MagneticLoader] Magnetically instantiated child entity: ${entName} under ${parent.entityName || parent.id}`);
400
+ }
401
+ }
402
+ if (!childInstance && parent.hierarchyManager) {
403
+ const { Entity } = await import("./K_ENT_Entity-PQ5MURQY-ZG6FZXXX.js");
404
+ childInstance = parent.hierarchyManager.createComponentEntity(entName, Entity);
405
+ console.log(`[MagneticLoader] Auto-created child entity container: ${entName} under ${parent.entityName || parent.id}`);
406
+ }
407
+ if (childInstance) {
408
+ await _KrnlMagneticLoader.loadAll(childInstance, entDir);
409
+ }
410
+ }
411
+ static async ensureSubAppBuilt(appPath, appName, entity, parentBaseDir) {
412
+ const packageJsonPath = path.join(appPath, "package.json");
413
+ if (!fs.existsSync(packageJsonPath)) {
414
+ return true;
415
+ }
416
+ const subNodeModules = path.join(appPath, "node_modules");
417
+ const candidateParentDirs = [
418
+ parentBaseDir ? path.join(parentBaseDir, "node_modules") : null,
419
+ parentBaseDir ? path.resolve(parentBaseDir, "..", "node_modules") : null,
420
+ path.join(process.cwd(), "node_modules")
421
+ ].filter(Boolean);
422
+ const parentNodeModules = candidateParentDirs.find((d) => fs.existsSync(d));
423
+ if (!fs.existsSync(subNodeModules) && parentNodeModules) {
424
+ try {
425
+ fs.symlinkSync(parentNodeModules, subNodeModules, "junction");
426
+ console.log(`[MagneticLoader] Symlinked sub-app node_modules for '${appName}' -> '${parentNodeModules}'`);
427
+ } catch (symErr) {
428
+ console.warn(`[MagneticLoader] Symlinking node_modules for '${appName}' failed, falling back:`, symErr.message);
429
+ }
430
+ }
431
+ const assemblerPath = path.join(appPath, "assembler.js");
432
+ let distPath = path.join(appPath, "dist", `${appName}.js`);
433
+ if (fs.existsSync(packageJsonPath)) {
434
+ try {
435
+ const pkgJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
436
+ if (pkgJson.main) {
437
+ distPath = path.resolve(appPath, pkgJson.main);
438
+ }
439
+ } catch (_) {
440
+ }
441
+ }
442
+ let gitUpdated = false;
443
+ const gitDir = path.join(appPath, ".git");
444
+ if (fs.existsSync(gitDir)) {
445
+ console.log(`[MagneticLoader] Checking for git remote updates for sub-app '${appName}'...`);
446
+ try {
447
+ const { exec } = await import("child_process");
448
+ const { promisify } = await import("util");
449
+ const execPromise = promisify(exec);
450
+ await execPromise("git fetch", { cwd: appPath, timeout: 3e3 });
451
+ const { stdout } = await execPromise("git status -uno", { cwd: appPath, timeout: 3e3 });
452
+ if (stdout.includes("Your branch is behind") || stdout.includes("can be fast-forwarded")) {
453
+ console.log(`[MagneticLoader] Remote updates found for sub-app '${appName}'. Pulling changes...`);
454
+ const pullResult = await execPromise("git pull", { cwd: appPath, timeout: 5e3 });
455
+ console.log(`[MagneticLoader] Git pull result for '${appName}':`, pullResult.stdout);
456
+ gitUpdated = true;
457
+ } else {
458
+ console.log(`[MagneticLoader] Sub-app '${appName}' git repository is up to date.`);
459
+ }
460
+ } catch (err) {
461
+ console.warn(`[MagneticLoader] Warning: git update check failed for '${appName}':`, err.message || err);
462
+ }
463
+ }
464
+ if (!fs.existsSync(assemblerPath) || !fs.existsSync(distPath) || !fs.existsSync(path.join(appPath, "node_modules")) || gitUpdated) {
465
+ console.log(`[MagneticLoader] Sub-app '${appName}' ${gitUpdated ? "was updated via git" : "is missing build artifacts"}. Initiating auto-build...`);
466
+ try {
467
+ const pkgJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
468
+ const hasBuildScript = pkgJson.scripts && pkgJson.scripts.build;
469
+ if (!hasBuildScript) {
470
+ throw new Error(`package.json is missing a 'build' script.`);
471
+ }
472
+ const nodeModulesPath = path.join(appPath, "node_modules");
473
+ if (!fs.existsSync(nodeModulesPath)) {
474
+ let installCmd = "npm install --no-audit --no-fund";
475
+ if (fs.existsSync(path.join(appPath, "pnpm-lock.yaml"))) {
476
+ installCmd = "pnpm install";
477
+ } else if (fs.existsSync(path.join(appPath, "yarn.lock"))) {
478
+ installCmd = "yarn install";
479
+ }
480
+ console.log(`[MagneticLoader] Installing dependencies for '${appName}' using '${installCmd}'...`);
481
+ const { exec: exec2 } = await import("child_process");
482
+ const { promisify: promisify2 } = await import("util");
483
+ const execPromise2 = promisify2(exec2);
484
+ await execPromise2(installCmd, { cwd: appPath });
485
+ } else {
486
+ const pkgJson2 = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
487
+ const hasKrnlts = pkgJson2.dependencies && pkgJson2.dependencies.krnlts || pkgJson2.devDependencies && pkgJson2.devDependencies.krnlts;
488
+ if (hasKrnlts) {
489
+ let updateCmd = "npm update krnlts";
490
+ if (fs.existsSync(path.join(appPath, "pnpm-lock.yaml"))) {
491
+ updateCmd = "pnpm update krnlts";
492
+ } else if (fs.existsSync(path.join(appPath, "yarn.lock"))) {
493
+ updateCmd = "yarn upgrade krnlts";
494
+ }
495
+ console.log(`[MagneticLoader] Automatically updating krnlts dependency for '${appName}' using '${updateCmd}'...`);
496
+ try {
497
+ const { exec: exec2 } = await import("child_process");
498
+ const { promisify: promisify2 } = await import("util");
499
+ const execPromise2 = promisify2(exec2);
500
+ await execPromise2(updateCmd, { cwd: appPath });
501
+ } catch (err) {
502
+ console.warn(`[MagneticLoader] Warning: auto-updating krnlts for '${appName}' failed:`, err.message || err);
503
+ }
504
+ }
505
+ }
506
+ let buildCmd = "npm run build";
507
+ if (fs.existsSync(path.join(appPath, "pnpm-lock.yaml"))) {
508
+ buildCmd = "pnpm run build";
509
+ } else if (fs.existsSync(path.join(appPath, "yarn.lock"))) {
510
+ buildCmd = "yarn build";
511
+ }
512
+ console.log(`[MagneticLoader] Building '${appName}' using '${buildCmd}'...`);
513
+ const { exec } = await import("child_process");
514
+ const { promisify } = await import("util");
515
+ const execPromise = promisify(exec);
516
+ await execPromise(buildCmd, { cwd: appPath });
517
+ if (!fs.existsSync(assemblerPath)) {
518
+ console.log(`[MagneticLoader] Automatically generating assembler.js for '${appName}'...`);
519
+ const code = `export { ${appName} as default } from "./dist/${appName}.js";
520
+ `;
521
+ fs.writeFileSync(assemblerPath, code, "utf-8");
522
+ }
523
+ console.log(`[MagneticLoader] Sub-app '${appName}' successfully built and prepared.`);
524
+ } catch (err) {
525
+ const errMsg = err.message || String(err);
526
+ console.error(`[MagneticLoader] Failed to build sub-app '${appName}':`, errMsg);
527
+ entity._subappErrors = entity._subappErrors || [];
528
+ entity._subappErrors.push({
529
+ subapp: appName,
530
+ error: errMsg
531
+ });
532
+ return false;
533
+ }
534
+ }
535
+ return true;
536
+ }
537
+ static async detectSubApp(appPath, appName) {
538
+ const assemblerPath = path.join(appPath, "assembler.js");
539
+ if (fs.existsSync(assemblerPath)) {
540
+ const mod = await import(pathToFileURL(assemblerPath).href);
541
+ const ServiceClass = mod[appName] || mod.default;
542
+ if (ServiceClass) {
543
+ const isKrnlSubclass = ServiceClass.prototype && (ServiceClass.prototype instanceof krnlSystemEntityBase || typeof ServiceClass.prototype.boot === "function");
544
+ return {
545
+ ServiceClass,
546
+ prefix: appName.toLowerCase(),
547
+ isKrnl: !!isKrnlSubclass,
548
+ entryPath: isKrnlSubclass ? assemblerPath : appPath
549
+ };
550
+ }
551
+ }
552
+ const packageJsonPath = path.join(appPath, "package.json");
553
+ if (fs.existsSync(packageJsonPath)) {
554
+ if (fs.existsSync(path.join(appPath, "KrnlFrontendModule.ts"))) {
555
+ return null;
556
+ }
557
+ return {
558
+ prefix: appName.toLowerCase(),
559
+ isKrnl: false,
560
+ entryPath: appPath
561
+ };
562
+ }
563
+ return null;
564
+ }
565
+ /**
566
+ * Automatically reconciles parent application package.json when sub-apps are added or removed.
567
+ * - Packages needed by new sub-apps are added to parent package.json.
568
+ * - Packages no longer needed by any sub-app are removed from parent package.json.
569
+ */
570
+ static async syncParentSubAppDependencies(baseDir, subappsDir) {
571
+ try {
572
+ const candidateParentPaths = [
573
+ path.join(baseDir, "package.json"),
574
+ path.resolve(baseDir, "..", "package.json"),
575
+ path.join(process.cwd(), "package.json")
576
+ ];
577
+ const parentPkgPath = candidateParentPaths.find((p) => fs.existsSync(p));
578
+ if (!parentPkgPath) return;
579
+ const parentDir = path.dirname(parentPkgPath);
580
+ const parentKrnlJsonPath = path.join(baseDir, "krnl.json");
581
+ let krnlJson = {};
582
+ if (fs.existsSync(parentKrnlJsonPath)) {
583
+ try {
584
+ krnlJson = JSON.parse(fs.readFileSync(parentKrnlJsonPath, "utf-8"));
585
+ } catch (_) {
586
+ }
587
+ }
588
+ const previousManaged = krnlJson.managedSubAppDependencies || {};
589
+ const activeSubAppDeps = {};
590
+ const subEntries = await fs.promises.readdir(subappsDir, { withFileTypes: true });
591
+ for (const dirent of subEntries) {
592
+ if (dirent.isDirectory()) {
593
+ const subPkgPath = path.join(subappsDir, dirent.name, "package.json");
594
+ if (fs.existsSync(subPkgPath)) {
595
+ try {
596
+ const subPkg = JSON.parse(fs.readFileSync(subPkgPath, "utf-8"));
597
+ const combined = { ...subPkg.dependencies, ...subPkg.devDependencies };
598
+ for (const [pkgName, pkgVer] of Object.entries(combined)) {
599
+ if (pkgName !== "krnlts" && pkgName !== "tsup" && !pkgName.startsWith("@types/")) {
600
+ activeSubAppDeps[pkgName] = pkgVer;
601
+ }
602
+ }
603
+ } catch (_) {
604
+ }
605
+ }
606
+ }
607
+ }
608
+ const parentPkg = JSON.parse(fs.readFileSync(parentPkgPath, "utf-8"));
609
+ parentPkg.dependencies = parentPkg.dependencies || {};
610
+ let modified = false;
611
+ for (const [pkgName, pkgVer] of Object.entries(activeSubAppDeps)) {
612
+ if (!parentPkg.dependencies[pkgName]) {
613
+ console.log(`[MagneticLoader] Adding new sub-app dependency '${pkgName}@${pkgVer}' to parent package.json...`);
614
+ parentPkg.dependencies[pkgName] = pkgVer;
615
+ previousManaged[pkgName] = pkgVer;
616
+ modified = true;
617
+ }
618
+ }
619
+ for (const [pkgName] of Object.entries(previousManaged)) {
620
+ if (!activeSubAppDeps[pkgName]) {
621
+ console.log(`[MagneticLoader] Removing stale sub-app dependency '${pkgName}' from parent package.json...`);
622
+ delete parentPkg.dependencies[pkgName];
623
+ delete previousManaged[pkgName];
624
+ modified = true;
625
+ }
626
+ }
627
+ if (modified) {
628
+ fs.writeFileSync(parentPkgPath, JSON.stringify(parentPkg, null, 2) + "\n", "utf-8");
629
+ krnlJson.managedSubAppDependencies = previousManaged;
630
+ if (fs.existsSync(parentKrnlJsonPath)) {
631
+ fs.writeFileSync(parentKrnlJsonPath, JSON.stringify(krnlJson, null, 2) + "\n", "utf-8");
632
+ }
633
+ console.log(`[MagneticLoader] Parent package.json dependencies updated. Running npm install...`);
634
+ const { exec } = await import("child_process");
635
+ const { promisify } = await import("util");
636
+ const execPromise = promisify(exec);
637
+ await execPromise("npm install --no-audit --no-fund", { cwd: parentDir });
638
+ console.log(`[MagneticLoader] Parent dependencies synced successfully.`);
639
+ }
640
+ } catch (err) {
641
+ console.warn(`[MagneticLoader] Sub-app dependency reconciliation warning:`, err.message || err);
642
+ }
643
+ }
644
+ static registerGlobalWrapper(name) {
645
+ if (!globalThis[name]) {
646
+ Object.defineProperty(globalThis, name, {
647
+ value: (...args) => {
648
+ const store = magneticStorage.getStore();
649
+ const fn = store?.helpers?.[name] || store?.events?.[name];
650
+ if (!fn) {
651
+ throw new Error(`[MagneticSystem] Dynamic asset '${name}' called outside active functionality context.`);
652
+ }
653
+ return fn(...args);
654
+ },
655
+ configurable: true,
656
+ writable: true
657
+ });
658
+ }
659
+ }
660
+ };
661
+
662
+ export {
663
+ magneticStorage,
664
+ subappLocalStorage,
665
+ KrnlMagneticLoader
666
+ };