@holoscript/core 7.0.0 → 8.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 (350) hide show
  1. package/README.md +4 -4
  2. package/bin/holoscript.cjs +3 -0
  3. package/dist/GLTFPipeline-N6B6PJ6G.cjs +38 -0
  4. package/dist/GLTFPipeline-P3WMNYCN.js +17 -0
  5. package/dist/HoloScriptPlusParser-7FBIFUFC.js +693 -0
  6. package/dist/HoloScriptPlusParser-A2W7OCN2.cjs +698 -0
  7. package/dist/HoloScriptPlusParser-F2Z56FJR.js +10 -0
  8. package/dist/HoloScriptPlusParser-WKHRIH6T.cjs +27 -0
  9. package/dist/HoloScriptRuntime-CBYJX3LZ.js +10 -0
  10. package/dist/HoloScriptRuntime-VJ374RER.cjs +19 -0
  11. package/dist/USDZExporter-3FWJ25JI.cjs +1037 -0
  12. package/dist/USDZExporter-D2HQLQYK.js +1035 -0
  13. package/dist/agents/index.cjs +19 -0
  14. package/dist/agents/index.d.ts +100 -0
  15. package/dist/agents/index.js +17 -0
  16. package/dist/chunk-2BSMSUCE.js +1941 -0
  17. package/dist/chunk-2IWC4FP7.cjs +1189 -0
  18. package/dist/chunk-2M2DPHKB.js +762 -0
  19. package/dist/chunk-2X7NGX3M.js +2426 -0
  20. package/dist/chunk-2YSNA2F2.cjs +1274 -0
  21. package/dist/chunk-3FOKASKO.cjs +348 -0
  22. package/dist/chunk-3WZEJHUQ.cjs +116 -0
  23. package/dist/chunk-4C57PR42.js +468 -0
  24. package/dist/chunk-4GU5GCIY.js +1384 -0
  25. package/dist/chunk-4N4SXXWF.js +769 -0
  26. package/dist/chunk-4PDEPEQW.cjs +41 -0
  27. package/dist/chunk-4R6SBXDB.js +45 -0
  28. package/dist/chunk-4SDKXQ4C.js +811 -0
  29. package/dist/chunk-4V2E7U7Q.cjs +2015 -0
  30. package/dist/chunk-5FSKKMR7.cjs +2092 -0
  31. package/dist/chunk-5GLCTO44.js +161 -0
  32. package/dist/chunk-5H2G27PK.cjs +627 -0
  33. package/dist/chunk-5JEU52DW.js +382 -0
  34. package/dist/chunk-5NWINHR5.cjs +689 -0
  35. package/dist/chunk-5S7RKFGR.cjs +446 -0
  36. package/dist/chunk-5WUNN6ZN.cjs +428 -0
  37. package/dist/chunk-6CTRH7HT.cjs +1985 -0
  38. package/dist/chunk-6EX3I5P4.cjs +130 -0
  39. package/dist/chunk-6Q7RC2MK.cjs +1418 -0
  40. package/dist/chunk-7H33U5SM.cjs +413 -0
  41. package/dist/chunk-7M3PNU2M.cjs +672 -0
  42. package/dist/chunk-7T25IEZ2.js +449 -0
  43. package/dist/chunk-7V4JI5TB.cjs +6947 -0
  44. package/dist/chunk-A6KINLZJ.js +236 -0
  45. package/dist/chunk-ADADVMXY.js +404 -0
  46. package/dist/chunk-AIA52I7T.cjs +543 -0
  47. package/dist/chunk-ALC6K7GL.cjs +4402 -0
  48. package/dist/chunk-ANXZFVY2.js +113 -0
  49. package/dist/chunk-AOVGZ25K.cjs +56583 -0
  50. package/dist/chunk-AVJHHUC5.cjs +718 -0
  51. package/dist/chunk-BGY3SDG3.js +4396 -0
  52. package/dist/chunk-BOVPWH4H.js +3857 -0
  53. package/dist/chunk-BRQJKJGT.cjs +20 -0
  54. package/dist/chunk-C37BHB7N.cjs +636 -0
  55. package/dist/chunk-CBJY23VL.js +126 -0
  56. package/dist/chunk-CCATWPXM.js +778 -0
  57. package/dist/chunk-CIWWXYHZ.cjs +50 -0
  58. package/dist/chunk-CMT5NMMS.js +669 -0
  59. package/dist/chunk-CR4FMIWL.cjs +1049 -0
  60. package/dist/chunk-CR7XRXRN.cjs +639 -0
  61. package/dist/chunk-CSD27UNQ.js +2176 -0
  62. package/dist/chunk-D3STJ56J.js +714 -0
  63. package/dist/chunk-DAJXW4KX.js +725 -0
  64. package/dist/chunk-DHO2YRIM.js +756 -0
  65. package/dist/chunk-DTGBOSEM.cjs +319 -0
  66. package/dist/chunk-E6XXE66V.js +2252 -0
  67. package/dist/chunk-E7JP3BS3.cjs +61 -0
  68. package/dist/chunk-EKBKLK7P.js +1169 -0
  69. package/dist/chunk-EKYL4PE3.cjs +404 -0
  70. package/dist/chunk-EXKSFGSX.cjs +274 -0
  71. package/dist/chunk-EXUP2BUM.cjs +1173 -0
  72. package/dist/chunk-FDSGHPAK.js +130 -0
  73. package/dist/chunk-FEWUHQNM.cjs +144 -0
  74. package/dist/chunk-FFAOS5HQ.js +70 -0
  75. package/dist/chunk-FGGJQRLZ.js +270 -0
  76. package/dist/chunk-FHP6LXJS.js +415 -0
  77. package/dist/chunk-FJPADH77.cjs +666 -0
  78. package/dist/chunk-FL33V6U7.js +421 -0
  79. package/dist/chunk-FYSPZT4V.cjs +169 -0
  80. package/dist/chunk-GIOYPNTH.js +5575 -0
  81. package/dist/chunk-GJNCFRJU.cjs +125 -0
  82. package/dist/chunk-GMP623FG.cjs +1508 -0
  83. package/dist/chunk-GQHQOPXZ.cjs +5580 -0
  84. package/dist/chunk-GTU2Z2WW.cjs +262 -0
  85. package/dist/chunk-GYZE55MO.js +2007 -0
  86. package/dist/chunk-GZG4KA4E.js +529 -0
  87. package/dist/chunk-H652NHX5.js +600 -0
  88. package/dist/chunk-HCCQLAA4.cjs +74 -0
  89. package/dist/chunk-HKEXJUWS.cjs +4007 -0
  90. package/dist/chunk-HNDK4IQU.cjs +5737 -0
  91. package/dist/chunk-HR2OSYVQ.js +56165 -0
  92. package/dist/chunk-HYNTS5CP.js +422 -0
  93. package/dist/chunk-I6XZ5DZF.cjs +488 -0
  94. package/dist/chunk-ILRBGFVD.cjs +72 -0
  95. package/dist/chunk-IUDGEUDO.cjs +1409 -0
  96. package/dist/chunk-IUTY5WQ2.cjs +424 -0
  97. package/dist/chunk-IVY74O6C.js +247 -0
  98. package/dist/chunk-IWC5DM2M.cjs +611 -0
  99. package/dist/chunk-J32ZJZJH.js +554 -0
  100. package/dist/chunk-J52VSAQ7.js +6884 -0
  101. package/dist/chunk-J6M4FPK5.js +421 -0
  102. package/dist/chunk-J7XZV333.js +844 -0
  103. package/dist/chunk-JBNDTXXV.cjs +2433 -0
  104. package/dist/chunk-JC5YBPSF.cjs +984 -0
  105. package/dist/chunk-JD7CIZ33.js +1949 -0
  106. package/dist/chunk-JIBL5LRK.js +4287 -0
  107. package/dist/chunk-JIYN45TV.cjs +2525 -0
  108. package/dist/chunk-K574J76X.cjs +457 -0
  109. package/dist/chunk-KHDZJE5D.cjs +2196 -0
  110. package/dist/chunk-KKFZ3B6J.cjs +557 -0
  111. package/dist/chunk-KKP7JKN4.cjs +6002 -0
  112. package/dist/chunk-KPJL34Y7.cjs +186 -0
  113. package/dist/chunk-KQCN6AKJ.cjs +3042 -0
  114. package/dist/chunk-L5LKKENW.cjs +424 -0
  115. package/dist/chunk-LHAXPADA.js +882 -0
  116. package/dist/chunk-LM2VU56C.cjs +37 -0
  117. package/dist/chunk-M56JSP4A.js +400 -0
  118. package/dist/chunk-MBOOR7X4.js +18 -0
  119. package/dist/chunk-MQWAT42R.cjs +4310 -0
  120. package/dist/chunk-MXFUTKCO.js +56 -0
  121. package/dist/chunk-MYY4PMWX.cjs +264 -0
  122. package/dist/chunk-N75IH2HY.js +258 -0
  123. package/dist/chunk-NCWCUZNS.cjs +72 -0
  124. package/dist/chunk-NG77ATEW.cjs +778 -0
  125. package/dist/chunk-NW5G5FBQ.js +215 -0
  126. package/dist/chunk-OBIYPYYS.cjs +1993 -0
  127. package/dist/chunk-OH2FAIVU.js +608 -0
  128. package/dist/chunk-OIQYIIO3.cjs +473 -0
  129. package/dist/chunk-OL46QLBJ.js +61 -0
  130. package/dist/chunk-OMXII44L.js +5386 -0
  131. package/dist/chunk-OSYNRVOV.cjs +243 -0
  132. package/dist/chunk-PGANYCAG.cjs +220 -0
  133. package/dist/chunk-PHENW4MQ.js +65 -0
  134. package/dist/chunk-PY37LNDP.js +686 -0
  135. package/dist/chunk-Q56TT7IL.js +483 -0
  136. package/dist/chunk-QD32ADK6.js +1046 -0
  137. package/dist/chunk-QPOQ7VPI.js +1491 -0
  138. package/dist/chunk-QPSKHBJP.js +5963 -0
  139. package/dist/chunk-QXH7QDSZ.js +1989 -0
  140. package/dist/chunk-R24NNAEG.js +1399 -0
  141. package/dist/chunk-R75BSDH7.cjs +50 -0
  142. package/dist/chunk-RARB3MBR.js +207 -0
  143. package/dist/chunk-ROHLEP2W.cjs +847 -0
  144. package/dist/chunk-S3MDHNKB.cjs +490 -0
  145. package/dist/chunk-S6YWHCKV.cjs +410 -0
  146. package/dist/chunk-SIEXCILW.js +229 -0
  147. package/dist/chunk-SLU6UPJI.cjs +410 -0
  148. package/dist/chunk-SMIWS6DE.cjs +212 -0
  149. package/dist/chunk-T5J7ZKP3.cjs +4885 -0
  150. package/dist/chunk-TDCNJHWO.js +341 -0
  151. package/dist/chunk-TG7O4WBC.js +406 -0
  152. package/dist/chunk-THCK6ECW.js +2085 -0
  153. package/dist/chunk-TJHVSBP2.js +439 -0
  154. package/dist/chunk-TVHSPJ4N.cjs +606 -0
  155. package/dist/chunk-TWUXUCEW.cjs +781 -0
  156. package/dist/chunk-U44IKGG7.cjs +5390 -0
  157. package/dist/chunk-UFZZ7TSN.cjs +886 -0
  158. package/dist/chunk-UJXISJBN.js +487 -0
  159. package/dist/chunk-UOIGFQXC.cjs +9750 -0
  160. package/dist/chunk-URG2SJLK.js +2521 -0
  161. package/dist/chunk-UWJHCOH2.js +623 -0
  162. package/dist/chunk-V6MKC2FZ.js +979 -0
  163. package/dist/chunk-VJ3L7CHT.cjs +169 -0
  164. package/dist/chunk-VMLKSV26.js +1216 -0
  165. package/dist/chunk-VVKVQZI6.js +55 -0
  166. package/dist/chunk-W6RW64BB.cjs +1219 -0
  167. package/dist/chunk-WKX5AMOY.js +309 -0
  168. package/dist/chunk-WNNE3PO3.js +34 -0
  169. package/dist/chunk-WRKUDAZJ.js +3038 -0
  170. package/dist/chunk-WRLUBRKS.cjs +1943 -0
  171. package/dist/chunk-WRNEH5MO.js +3169 -0
  172. package/dist/chunk-WRWEX5ZF.js +658 -0
  173. package/dist/chunk-X3GJPRVK.cjs +3246 -0
  174. package/dist/chunk-X3UVCWNL.cjs +2257 -0
  175. package/dist/chunk-XB274MW5.cjs +814 -0
  176. package/dist/chunk-XHIV6326.cjs +793 -0
  177. package/dist/chunk-XIVIE43A.cjs +729 -0
  178. package/dist/chunk-XJAN7CZG.cjs +432 -0
  179. package/dist/chunk-XKTPFXGA.js +164 -0
  180. package/dist/chunk-XL6INWKT.js +121 -0
  181. package/dist/chunk-XSFNHP2E.js +632 -0
  182. package/dist/chunk-XT6JY5W5.js +9684 -0
  183. package/dist/chunk-XUILI4KB.cjs +430 -0
  184. package/dist/chunk-YF2I3MV3.js +46 -0
  185. package/dist/chunk-YIMN575O.js +4847 -0
  186. package/dist/chunk-YIVFJNYV.js +176 -0
  187. package/dist/chunk-YKGPCZEE.cjs +237 -0
  188. package/dist/chunk-YN2YWTXW.js +5731 -0
  189. package/dist/chunk-YN6V7R3L.cjs +327 -0
  190. package/dist/chunk-YQELFNJV.js +39 -0
  191. package/dist/chunk-YVD3CSO3.js +1183 -0
  192. package/dist/chunk-YVOAF4ML.js +623 -0
  193. package/dist/chunk-YWOBW2PV.cjs +759 -0
  194. package/dist/chunk-YYXH45E2.js +426 -0
  195. package/dist/chunk-ZDSYWBIE.cjs +69 -0
  196. package/dist/chunk-ZU7NIRT6.js +325 -0
  197. package/dist/chunk-ZZ7RO2UQ.js +1243 -0
  198. package/dist/cli/holoscript-runner.cjs +2255 -0
  199. package/dist/cli/holoscript-runner.js +2230 -0
  200. package/dist/codebase/index.cjs +336 -0
  201. package/dist/codebase/index.js +331 -0
  202. package/dist/compiler/agent-inference.cjs +31 -0
  203. package/dist/compiler/agent-inference.js +8 -0
  204. package/dist/compiler/android-xr.cjs +24 -0
  205. package/dist/compiler/android-xr.js +14 -0
  206. package/dist/compiler/android.cjs +24 -0
  207. package/dist/compiler/android.js +14 -0
  208. package/dist/compiler/ar.cjs +23 -0
  209. package/dist/compiler/ar.js +11 -0
  210. package/dist/compiler/babylon.cjs +21 -0
  211. package/dist/compiler/babylon.js +15 -0
  212. package/dist/compiler/business-quest.cjs +43 -0
  213. package/dist/compiler/business-quest.js +4 -0
  214. package/dist/compiler/coco.cjs +27 -0
  215. package/dist/compiler/coco.js +4 -0
  216. package/dist/compiler/context.cjs +25 -0
  217. package/dist/compiler/context.d.ts +28 -0
  218. package/dist/compiler/context.js +8 -0
  219. package/dist/compiler/domain-block-utils.cjs +609 -0
  220. package/dist/compiler/domain-block-utils.js +11 -0
  221. package/dist/compiler/dtdl.cjs +27 -0
  222. package/dist/compiler/dtdl.js +11 -0
  223. package/dist/compiler/gltf-pipeline.cjs +39 -0
  224. package/dist/compiler/gltf-pipeline.js +4 -0
  225. package/dist/compiler/godot.cjs +18 -0
  226. package/dist/compiler/godot.js +12 -0
  227. package/dist/compiler/incremental.cjs +34 -0
  228. package/dist/compiler/incremental.js +9 -0
  229. package/dist/compiler/index.cjs +5408 -0
  230. package/dist/compiler/index.d.ts +334 -21
  231. package/dist/compiler/index.js +5069 -0
  232. package/dist/compiler/ios.cjs +23 -0
  233. package/dist/compiler/ios.js +13 -0
  234. package/dist/compiler/llm-provider-capabilities.cjs +25 -0
  235. package/dist/compiler/llm-provider-capabilities.d.ts +43 -0
  236. package/dist/compiler/llm-provider-capabilities.js +8 -0
  237. package/dist/compiler/multi-layer.cjs +24 -0
  238. package/dist/compiler/multi-layer.js +15 -0
  239. package/dist/compiler/nodetoy.cjs +23 -0
  240. package/dist/compiler/nodetoy.d.ts +69 -0
  241. package/dist/compiler/nodetoy.js +4 -0
  242. package/dist/compiler/openxr.cjs +19 -0
  243. package/dist/compiler/openxr.js +13 -0
  244. package/dist/compiler/playcanvas.cjs +19 -0
  245. package/dist/compiler/playcanvas.js +13 -0
  246. package/dist/compiler/r3f.cjs +39 -0
  247. package/dist/compiler/r3f.d.ts +22 -0
  248. package/dist/compiler/r3f.js +17 -0
  249. package/dist/compiler/remotion.cjs +23 -0
  250. package/dist/compiler/remotion.js +4 -0
  251. package/dist/compiler/reproducibility.cjs +39 -0
  252. package/dist/compiler/reproducibility.js +4 -0
  253. package/dist/compiler/sdf.cjs +24 -0
  254. package/dist/compiler/sdf.js +12 -0
  255. package/dist/compiler/semantic-scene.cjs +31 -0
  256. package/dist/compiler/semantic-scene.js +4 -0
  257. package/dist/compiler/state.cjs +21 -0
  258. package/dist/compiler/state.js +11 -0
  259. package/dist/compiler/trait-composition.cjs +30 -0
  260. package/dist/compiler/trait-composition.js +9 -0
  261. package/dist/compiler/unity.cjs +19 -0
  262. package/dist/compiler/unity.js +13 -0
  263. package/dist/compiler/unreal.cjs +23 -0
  264. package/dist/compiler/unreal.js +13 -0
  265. package/dist/compiler/urdf.cjs +52 -0
  266. package/dist/compiler/urdf.js +12 -0
  267. package/dist/compiler/usd-physics.cjs +26 -0
  268. package/dist/compiler/usd-physics.js +9 -0
  269. package/dist/compiler/visionos.cjs +19 -0
  270. package/dist/compiler/visionos.js +13 -0
  271. package/dist/compiler/vrchat.cjs +22 -0
  272. package/dist/compiler/vrchat.js +12 -0
  273. package/dist/compiler/vrr.cjs +24 -0
  274. package/dist/compiler/vrr.js +12 -0
  275. package/dist/compiler/wasm.cjs +36 -0
  276. package/dist/compiler/wasm.js +12 -0
  277. package/dist/compiler/webgpu.cjs +18 -0
  278. package/dist/compiler/webgpu.js +12 -0
  279. package/dist/coordinators/index.cjs +1266 -0
  280. package/dist/coordinators/index.d.ts +72 -1
  281. package/dist/coordinators/index.js +1259 -0
  282. package/dist/debugger.cjs +24 -0
  283. package/dist/debugger.js +11 -0
  284. package/dist/dist-ACXG6IH5.cjs +3113 -0
  285. package/dist/dist-VD4L6V7Q.js +3076 -0
  286. package/dist/entries/interop.cjs +64 -0
  287. package/dist/entries/interop.js +7 -0
  288. package/dist/entries/scripting.cjs +55 -0
  289. package/dist/entries/scripting.js +10 -0
  290. package/dist/hololand/index.cjs +146 -0
  291. package/dist/hololand/index.d.ts +70 -0
  292. package/dist/hololand/index.js +5 -0
  293. package/dist/index.cjs +44660 -0
  294. package/dist/index.d.ts +978 -21
  295. package/dist/index.js +41422 -0
  296. package/dist/math/tropical-spmv.cjs +45 -0
  297. package/dist/math/tropical-spmv.js +4 -0
  298. package/dist/math/vec3.cjs +57 -0
  299. package/dist/math/vec3.js +4 -0
  300. package/dist/ml-dsa-FSKBTE3W.cjs +1265 -0
  301. package/dist/ml-dsa-Z7JDKW4L.js +1265 -0
  302. package/dist/paper-0c-spike/index.cjs +150 -0
  303. package/dist/paper-0c-spike/index.js +141 -0
  304. package/dist/parser.cjs +61 -0
  305. package/dist/parser.d.ts +11 -0
  306. package/dist/parser.js +12 -0
  307. package/dist/playwright-3AT3AKTV.cjs +98673 -0
  308. package/dist/playwright-VZPDVUEQ.js +98660 -0
  309. package/dist/reconstruction/index.cjs +153 -0
  310. package/dist/reconstruction/index.d.ts +29 -2
  311. package/dist/reconstruction/index.js +8 -0
  312. package/dist/runtime.cjs +316 -0
  313. package/dist/runtime.d.ts +61 -0
  314. package/dist/runtime.js +31 -0
  315. package/dist/self-improvement/index.cjs +563 -0
  316. package/dist/self-improvement/index.js +545 -0
  317. package/dist/src-4ROC227P.cjs +2094 -0
  318. package/dist/src-HCCCSYP7.js +2073 -0
  319. package/dist/storage/index.cjs +38 -0
  320. package/dist/storage/index.js +5 -0
  321. package/dist/testing.cjs +25 -0
  322. package/dist/testing.d.ts +70 -0
  323. package/dist/testing.js +4 -0
  324. package/dist/traitDocs/traitDocs.cjs +33 -0
  325. package/dist/traitDocs/traitDocs.js +7 -0
  326. package/dist/traits/botanical-lotus.cjs +177 -0
  327. package/dist/traits/botanical-lotus.d.ts +502 -0
  328. package/dist/traits/botanical-lotus.js +7 -0
  329. package/dist/traits/engines/index.cjs +520 -0
  330. package/dist/traits/engines/index.js +380 -0
  331. package/dist/traits/index.cjs +24548 -0
  332. package/dist/traits/index.d.ts +171 -35
  333. package/dist/traits/index.js +21638 -0
  334. package/dist/traits/simulation-solver-factory.cjs +13 -0
  335. package/dist/traits/simulation-solver-factory.d.ts +23 -0
  336. package/dist/traits/simulation-solver-factory.js +4 -0
  337. package/dist/traits/webcam-gaze.cjs +35 -0
  338. package/dist/traits/webcam-gaze.d.ts +17 -0
  339. package/dist/traits/webcam-gaze.js +4 -0
  340. package/dist/type-checker.cjs +19 -0
  341. package/dist/type-checker.js +6 -0
  342. package/dist/world/index.cjs +947 -0
  343. package/dist/world/index.d.ts +147 -0
  344. package/dist/world/index.js +939 -0
  345. package/dist/world-model/index.cjs +1446 -0
  346. package/dist/world-model/index.d.ts +119 -0
  347. package/dist/world-model/index.js +1414 -0
  348. package/dist/wot/index.cjs +29 -0
  349. package/dist/wot/index.js +4 -0
  350. package/package.json +93 -49
@@ -0,0 +1,2015 @@
1
+ 'use strict';
2
+
3
+ var chunkR75BSDH7_cjs = require('./chunk-R75BSDH7.cjs');
4
+ var chunkKKP7JKN4_cjs = require('./chunk-KKP7JKN4.cjs');
5
+ var chunkE7JP3BS3_cjs = require('./chunk-E7JP3BS3.cjs');
6
+ var crypto = require('crypto');
7
+
8
+ // src/compiler/TraitDependencyGraph.ts
9
+ chunkE7JP3BS3_cjs.init_safeJsonParse();
10
+ function hashConfig(config) {
11
+ const keys = Object.keys(config).sort();
12
+ const parts = [];
13
+ for (const key of keys) {
14
+ const value = config[key];
15
+ parts.push(`${key}:${JSON.stringify(value)}`);
16
+ }
17
+ const str = parts.join("|");
18
+ let hash = 5381;
19
+ for (let i = 0; i < str.length; i++) {
20
+ hash = (hash << 5) + hash ^ str.charCodeAt(i);
21
+ }
22
+ return (hash >>> 0).toString(36);
23
+ }
24
+ var TraitDependencyGraph = class _TraitDependencyGraph {
25
+ constructor() {
26
+ /** Trait → required traits (what this trait depends on) */
27
+ this.traitDependencies = /* @__PURE__ */ new Map();
28
+ /** Trait → conflicting traits */
29
+ this.traitConflicts = /* @__PURE__ */ new Map();
30
+ /** Object → trait info (current state) */
31
+ this.objectTraits = /* @__PURE__ */ new Map();
32
+ /** Trait → objects using this trait */
33
+ this.traitToObjects = /* @__PURE__ */ new Map();
34
+ /** Source → objects defined in this source */
35
+ this.sourceToObjects = /* @__PURE__ */ new Map();
36
+ /** Template → objects extending this template */
37
+ this.templateToObjects = /* @__PURE__ */ new Map();
38
+ /** Previous state for diff comparison */
39
+ this.previousObjectTraits = /* @__PURE__ */ new Map();
40
+ // ---------------------------------------------------------------------------
41
+ // IMPORT GRAPH — cross-file dependency edges
42
+ // ---------------------------------------------------------------------------
43
+ /**
44
+ * File → set of files it directly imports.
45
+ * Edge: `importer → importee`
46
+ * e.g., 'a.hs' → { 'b.hs', 'c.hs' }
47
+ */
48
+ this.importEdges = /* @__PURE__ */ new Map();
49
+ /**
50
+ * Reverse map: file → set of files that import it.
51
+ * Edge: `importee → importers`
52
+ * e.g., 'b.hs' → { 'a.hs', 'd.hs' }
53
+ */
54
+ this.reverseImportEdges = /* @__PURE__ */ new Map();
55
+ }
56
+ // ===========================================================================
57
+ // TRAIT REGISTRATION
58
+ // ===========================================================================
59
+ /**
60
+ * Register a trait definition with its dependencies and conflicts
61
+ */
62
+ registerTrait(definition) {
63
+ const { name, requires, conflicts } = definition;
64
+ if (!this.traitDependencies.has(name)) {
65
+ this.traitDependencies.set(name, /* @__PURE__ */ new Set());
66
+ }
67
+ for (const req of requires) {
68
+ this.traitDependencies.get(name).add(req);
69
+ }
70
+ if (!this.traitConflicts.has(name)) {
71
+ this.traitConflicts.set(name, /* @__PURE__ */ new Set());
72
+ }
73
+ for (const conflict of conflicts) {
74
+ this.traitConflicts.get(name).add(conflict);
75
+ }
76
+ }
77
+ /**
78
+ * Register common VR trait dependencies
79
+ */
80
+ registerBuiltinTraits() {
81
+ this.registerTrait({
82
+ name: "physics",
83
+ requires: [],
84
+ conflicts: ["static"]
85
+ });
86
+ this.registerTrait({
87
+ name: "static",
88
+ requires: [],
89
+ conflicts: ["physics", "kinematic"]
90
+ });
91
+ this.registerTrait({
92
+ name: "kinematic",
93
+ requires: [],
94
+ conflicts: ["static"]
95
+ });
96
+ this.registerTrait({
97
+ name: "collidable",
98
+ requires: [],
99
+ conflicts: []
100
+ });
101
+ this.registerTrait({
102
+ name: "grabbable",
103
+ requires: ["collidable"],
104
+ conflicts: []
105
+ });
106
+ this.registerTrait({
107
+ name: "throwable",
108
+ requires: ["grabbable"],
109
+ conflicts: []
110
+ });
111
+ this.registerTrait({
112
+ name: "draggable",
113
+ requires: ["collidable"],
114
+ conflicts: []
115
+ });
116
+ this.registerTrait({
117
+ name: "visible",
118
+ requires: [],
119
+ conflicts: ["invisible"]
120
+ });
121
+ this.registerTrait({
122
+ name: "invisible",
123
+ requires: [],
124
+ conflicts: ["visible"]
125
+ });
126
+ this.registerTrait({
127
+ name: "audio",
128
+ requires: [],
129
+ conflicts: []
130
+ });
131
+ this.registerTrait({
132
+ name: "spatial_audio",
133
+ requires: ["audio"],
134
+ conflicts: []
135
+ });
136
+ this.registerTrait({
137
+ name: "networked",
138
+ requires: [],
139
+ conflicts: []
140
+ });
141
+ this.registerTrait({
142
+ name: "lobby",
143
+ requires: [],
144
+ conflicts: []
145
+ });
146
+ this.registerTrait({
147
+ name: "crdt-room",
148
+ requires: [],
149
+ conflicts: ["lobby"]
150
+ // crdt-room replaces lobby-based room management
151
+ });
152
+ this.registerTrait({
153
+ name: "crdt-room.entity",
154
+ requires: ["crdt-room"],
155
+ conflicts: []
156
+ });
157
+ this.registerTrait({
158
+ name: "cultural_profile",
159
+ requires: [],
160
+ conflicts: []
161
+ });
162
+ this.registerTrait({
163
+ name: "norm_compliant",
164
+ requires: ["cultural_profile"],
165
+ conflicts: []
166
+ });
167
+ this.registerTrait({
168
+ name: "cultural_memory",
169
+ requires: ["cultural_profile"],
170
+ conflicts: []
171
+ });
172
+ this.registerTrait({
173
+ name: "cultural_trace",
174
+ requires: [],
175
+ conflicts: []
176
+ });
177
+ this.registerV6Traits();
178
+ }
179
+ /**
180
+ * Register v6 universal service/data/pipeline/container/resilience traits
181
+ */
182
+ registerV6Traits() {
183
+ this.registerTrait({ name: "service", requires: [], conflicts: [] });
184
+ this.registerTrait({ name: "endpoint", requires: ["service"], conflicts: [] });
185
+ this.registerTrait({ name: "handler", requires: ["http"], conflicts: [] });
186
+ this.registerTrait({ name: "middleware", requires: ["service"], conflicts: [] });
187
+ this.registerTrait({ name: "http", requires: [], conflicts: [] });
188
+ this.registerTrait({ name: "gateway", requires: [], conflicts: ["proxy"] });
189
+ this.registerTrait({ name: "proxy", requires: [], conflicts: ["gateway"] });
190
+ this.registerTrait({ name: "db", requires: [], conflicts: [] });
191
+ this.registerTrait({ name: "data_model", requires: ["db"], conflicts: [] });
192
+ this.registerTrait({ name: "migration", requires: ["db"], conflicts: [] });
193
+ this.registerTrait({ name: "query", requires: ["db"], conflicts: [] });
194
+ this.registerTrait({ name: "cache", requires: [], conflicts: [] });
195
+ this.registerTrait({ name: "pipeline", requires: [], conflicts: [] });
196
+ this.registerTrait({ name: "stream", requires: ["pipeline"], conflicts: [] });
197
+ this.registerTrait({ name: "queue", requires: [], conflicts: [] });
198
+ this.registerTrait({ name: "worker", requires: ["pipeline"], conflicts: ["scheduler"] });
199
+ this.registerTrait({ name: "scheduler", requires: [], conflicts: ["worker"] });
200
+ this.registerTrait({ name: "container", requires: [], conflicts: ["serverless"] });
201
+ this.registerTrait({ name: "serverless", requires: [], conflicts: ["container"] });
202
+ this.registerTrait({ name: "deployment", requires: [], conflicts: [] });
203
+ this.registerTrait({ name: "metric", requires: [], conflicts: [] });
204
+ this.registerTrait({ name: "trace", requires: ["service"], conflicts: [] });
205
+ this.registerTrait({ name: "health_check", requires: ["service"], conflicts: [] });
206
+ this.registerTrait({ name: "log", requires: [], conflicts: [] });
207
+ this.registerTrait({ name: "circuit_breaker", requires: ["service"], conflicts: [] });
208
+ this.registerTrait({ name: "retry", requires: ["service"], conflicts: [] });
209
+ this.registerTrait({ name: "timeout", requires: ["service"], conflicts: [] });
210
+ this.registerTrait({ name: "fallback", requires: [], conflicts: [] });
211
+ this.registerTrait({ name: "bulkhead", requires: ["service"], conflicts: [] });
212
+ this.registerTrait({ name: "schema", requires: [], conflicts: [] });
213
+ this.registerTrait({ name: "validator", requires: ["schema"], conflicts: [] });
214
+ this.registerTrait({ name: "serializer", requires: ["schema"], conflicts: [] });
215
+ this.registerTrait({ name: "contract", requires: [], conflicts: [] });
216
+ }
217
+ // ===========================================================================
218
+ // IMPORT EDGE TRACKING (@import cross-file dependencies)
219
+ // ===========================================================================
220
+ /**
221
+ * Register a cross-file @import relationship.
222
+ *
223
+ * Call this once per `@import` directive after parsing.
224
+ * Idempotent — registering the same edge twice is safe.
225
+ *
226
+ * @param importingFile Canonical path of the file that contains `@import`
227
+ * @param importedFile Canonical path of the file being imported
228
+ */
229
+ registerImport(importingFile, importedFile) {
230
+ if (!this.importEdges.has(importingFile)) {
231
+ this.importEdges.set(importingFile, /* @__PURE__ */ new Set());
232
+ }
233
+ this.importEdges.get(importingFile).add(importedFile);
234
+ if (!this.reverseImportEdges.has(importedFile)) {
235
+ this.reverseImportEdges.set(importedFile, /* @__PURE__ */ new Set());
236
+ }
237
+ this.reverseImportEdges.get(importedFile).add(importingFile);
238
+ }
239
+ /**
240
+ * Remove all import edges for a file (call before re-registering after a parse).
241
+ * Cleans both the forward edge and the corresponding reverse entries.
242
+ */
243
+ clearImportsForFile(importingFile) {
244
+ const imported = this.importEdges.get(importingFile);
245
+ if (!imported) return;
246
+ for (const dep of imported) {
247
+ this.reverseImportEdges.get(dep)?.delete(importingFile);
248
+ }
249
+ this.importEdges.delete(importingFile);
250
+ }
251
+ /**
252
+ * Return the set of files that `sourceFile` directly imports.
253
+ */
254
+ getImportedFiles(sourceFile) {
255
+ return new Set(this.importEdges.get(sourceFile) ?? []);
256
+ }
257
+ /**
258
+ * Return the set of files that directly import `sourceFile`.
259
+ */
260
+ getFilesThatImport(sourceFile) {
261
+ return new Set(this.reverseImportEdges.get(sourceFile) ?? []);
262
+ }
263
+ /**
264
+ * Walk the reverse-import graph (BFS) to compute the full set of files that
265
+ * need to be recompiled when `changedFiles` are modified.
266
+ *
267
+ * Includes the changed files themselves and all direct/transitive importers.
268
+ *
269
+ * @param changedFiles Canonical paths of the files that changed on disk
270
+ * @returns Set of canonical paths that need recompilation
271
+ */
272
+ getFilesAffectedByChange(changedFiles) {
273
+ const affected = new Set(changedFiles);
274
+ const queue = [...changedFiles];
275
+ while (queue.length > 0) {
276
+ const current = queue.shift();
277
+ const importers = this.reverseImportEdges.get(current);
278
+ if (!importers) continue;
279
+ for (const importer of importers) {
280
+ if (!affected.has(importer)) {
281
+ affected.add(importer);
282
+ queue.push(importer);
283
+ }
284
+ }
285
+ }
286
+ return affected;
287
+ }
288
+ // ===========================================================================
289
+ // OBJECT TRACKING
290
+ // ===========================================================================
291
+ /**
292
+ * Register an object and its trait usage
293
+ */
294
+ registerObject(info) {
295
+ const { objectName, sourceId, traits, template } = info;
296
+ const traitsWithHashes = traits.map((t) => ({
297
+ ...t,
298
+ configHash: t.configHash || hashConfig(t.config)
299
+ }));
300
+ const fullInfo = {
301
+ ...info,
302
+ traits: traitsWithHashes
303
+ };
304
+ this.objectTraits.set(objectName, fullInfo);
305
+ for (const trait of traitsWithHashes) {
306
+ if (!this.traitToObjects.has(trait.name)) {
307
+ this.traitToObjects.set(trait.name, /* @__PURE__ */ new Set());
308
+ }
309
+ this.traitToObjects.get(trait.name).add(objectName);
310
+ }
311
+ if (!this.sourceToObjects.has(sourceId)) {
312
+ this.sourceToObjects.set(sourceId, /* @__PURE__ */ new Set());
313
+ }
314
+ this.sourceToObjects.get(sourceId).add(objectName);
315
+ if (template) {
316
+ if (!this.templateToObjects.has(template)) {
317
+ this.templateToObjects.set(template, /* @__PURE__ */ new Set());
318
+ }
319
+ this.templateToObjects.get(template).add(objectName);
320
+ }
321
+ }
322
+ /**
323
+ * Remove an object from tracking
324
+ */
325
+ unregisterObject(objectName) {
326
+ const info = this.objectTraits.get(objectName);
327
+ if (!info) return;
328
+ for (const trait of info.traits) {
329
+ this.traitToObjects.get(trait.name)?.delete(objectName);
330
+ }
331
+ this.sourceToObjects.get(info.sourceId)?.delete(objectName);
332
+ if (info.template) {
333
+ this.templateToObjects.get(info.template)?.delete(objectName);
334
+ }
335
+ this.objectTraits.delete(objectName);
336
+ }
337
+ // ===========================================================================
338
+ // CHANGE DETECTION
339
+ // ===========================================================================
340
+ /**
341
+ * Save current state for comparison
342
+ */
343
+ saveSnapshot() {
344
+ this.previousObjectTraits = new Map(
345
+ Array.from(this.objectTraits.entries()).map(([k, v]) => [
346
+ k,
347
+ {
348
+ ...v,
349
+ traits: [...v.traits]
350
+ }
351
+ ])
352
+ );
353
+ }
354
+ /**
355
+ * Detect trait changes for an object
356
+ */
357
+ detectTraitChanges(objectName, newTraits) {
358
+ const changes = [];
359
+ const oldInfo = this.previousObjectTraits.get(objectName);
360
+ const newTraitsWithHashes = newTraits.map((t) => ({
361
+ ...t,
362
+ configHash: t.configHash || hashConfig(t.config)
363
+ }));
364
+ const oldTraitMap = /* @__PURE__ */ new Map();
365
+ const newTraitMap = /* @__PURE__ */ new Map();
366
+ if (oldInfo) {
367
+ for (const t of oldInfo.traits) {
368
+ oldTraitMap.set(t.name, t);
369
+ }
370
+ }
371
+ for (const t of newTraitsWithHashes) {
372
+ newTraitMap.set(t.name, t);
373
+ }
374
+ for (const [name, newTrait] of newTraitMap) {
375
+ if (!oldTraitMap.has(name)) {
376
+ changes.push({
377
+ traitName: name,
378
+ changeType: "added",
379
+ newConfigHash: newTrait.configHash
380
+ });
381
+ }
382
+ }
383
+ for (const [name, oldTrait] of oldTraitMap) {
384
+ if (!newTraitMap.has(name)) {
385
+ changes.push({
386
+ traitName: name,
387
+ changeType: "removed",
388
+ oldConfigHash: oldTrait.configHash
389
+ });
390
+ }
391
+ }
392
+ for (const [name, newTrait] of newTraitMap) {
393
+ const oldTrait = oldTraitMap.get(name);
394
+ if (oldTrait && oldTrait.configHash !== newTrait.configHash) {
395
+ changes.push({
396
+ traitName: name,
397
+ changeType: "config_changed",
398
+ oldConfigHash: oldTrait.configHash,
399
+ newConfigHash: newTrait.configHash
400
+ });
401
+ }
402
+ }
403
+ return changes;
404
+ }
405
+ // ===========================================================================
406
+ // AFFECTED SET CALCULATION
407
+ // ===========================================================================
408
+ /**
409
+ * Get all objects using a specific trait
410
+ */
411
+ getObjectsUsingTrait(traitName) {
412
+ return new Set(this.traitToObjects.get(traitName) || []);
413
+ }
414
+ /**
415
+ * Get all traits that depend on a given trait
416
+ */
417
+ getDependentTraits(traitName) {
418
+ const dependents = /* @__PURE__ */ new Set();
419
+ for (const [trait, deps] of this.traitDependencies) {
420
+ if (deps.has(traitName)) {
421
+ dependents.add(trait);
422
+ }
423
+ }
424
+ return dependents;
425
+ }
426
+ /**
427
+ * Calculate the affected set when traits change
428
+ */
429
+ calculateAffectedSet(changes) {
430
+ const objects = /* @__PURE__ */ new Set();
431
+ const sources = /* @__PURE__ */ new Set();
432
+ const reasons = /* @__PURE__ */ new Map();
433
+ for (const change of changes) {
434
+ const { traitName, changeType } = change;
435
+ const directUsers = this.getObjectsUsingTrait(traitName);
436
+ for (const obj of directUsers) {
437
+ objects.add(obj);
438
+ reasons.set(obj, `Uses trait @${traitName} (${changeType})`);
439
+ const info = this.objectTraits.get(obj);
440
+ if (info) {
441
+ sources.add(info.sourceId);
442
+ }
443
+ }
444
+ const dependentTraits = this.getDependentTraits(traitName);
445
+ for (const depTrait of dependentTraits) {
446
+ const depUsers = this.getObjectsUsingTrait(depTrait);
447
+ for (const obj of depUsers) {
448
+ if (!objects.has(obj)) {
449
+ objects.add(obj);
450
+ reasons.set(obj, `Uses trait @${depTrait} which depends on @${traitName}`);
451
+ const info = this.objectTraits.get(obj);
452
+ if (info) {
453
+ sources.add(info.sourceId);
454
+ }
455
+ }
456
+ }
457
+ }
458
+ }
459
+ return { objects, sources, reasons };
460
+ }
461
+ /**
462
+ * Calculate minimal recompilation set for changed objects
463
+ * Considers trait dependencies and template inheritance
464
+ */
465
+ calculateRecompilationSet(changedObjects) {
466
+ const toRecompile = new Set(changedObjects);
467
+ const queue = [...changedObjects];
468
+ while (queue.length > 0) {
469
+ const current = queue.shift();
470
+ const info = this.objectTraits.get(current);
471
+ if (!info) continue;
472
+ const extending = this.templateToObjects.get(current);
473
+ if (extending) {
474
+ for (const obj of extending) {
475
+ if (!toRecompile.has(obj)) {
476
+ toRecompile.add(obj);
477
+ queue.push(obj);
478
+ }
479
+ }
480
+ }
481
+ }
482
+ return toRecompile;
483
+ }
484
+ // ===========================================================================
485
+ // SERIALIZATION (for cache persistence)
486
+ // ===========================================================================
487
+ /**
488
+ * Serialize the graph for persistence
489
+ */
490
+ serialize() {
491
+ const data = {
492
+ version: 2,
493
+ traitDependencies: Array.from(this.traitDependencies.entries()).map(([k, v]) => [
494
+ k,
495
+ Array.from(v)
496
+ ]),
497
+ traitConflicts: Array.from(this.traitConflicts.entries()).map(([k, v]) => [k, Array.from(v)]),
498
+ objectTraits: Array.from(this.objectTraits.entries()),
499
+ importEdges: Array.from(this.importEdges.entries()).map(([k, v]) => [k, Array.from(v)]),
500
+ timestamp: Date.now()
501
+ };
502
+ return JSON.stringify(data);
503
+ }
504
+ /**
505
+ * Deserialize the graph from persisted data
506
+ */
507
+ static deserialize(json) {
508
+ const graph = new _TraitDependencyGraph();
509
+ const data = chunkE7JP3BS3_cjs.readJson(json);
510
+ if (data.version !== 1 && data.version !== 2) {
511
+ throw new Error(`Unsupported trait graph version: ${data.version}`);
512
+ }
513
+ for (const [trait, deps] of data.traitDependencies) {
514
+ graph.traitDependencies.set(trait, new Set(deps));
515
+ }
516
+ for (const [trait, conflicts] of data.traitConflicts) {
517
+ graph.traitConflicts.set(trait, new Set(conflicts));
518
+ }
519
+ for (const [_name, info] of data.objectTraits) {
520
+ graph.registerObject(info);
521
+ }
522
+ if (data.importEdges) {
523
+ for (const [importer, imported] of data.importEdges) {
524
+ for (const dep of imported) {
525
+ graph.registerImport(importer, dep);
526
+ }
527
+ }
528
+ }
529
+ return graph;
530
+ }
531
+ // ===========================================================================
532
+ // STATS & DEBUGGING
533
+ // ===========================================================================
534
+ /**
535
+ * Get graph statistics
536
+ */
537
+ getStats() {
538
+ let dependencyEdges = 0;
539
+ for (const deps of this.traitDependencies.values()) {
540
+ dependencyEdges += deps.size;
541
+ }
542
+ let importEdges = 0;
543
+ for (const deps of this.importEdges.values()) {
544
+ importEdges += deps.size;
545
+ }
546
+ return {
547
+ traitCount: this.traitDependencies.size,
548
+ objectCount: this.objectTraits.size,
549
+ sourceCount: this.sourceToObjects.size,
550
+ dependencyEdges,
551
+ importEdges
552
+ };
553
+ }
554
+ /**
555
+ * Clear all data
556
+ */
557
+ clear() {
558
+ this.traitDependencies.clear();
559
+ this.traitConflicts.clear();
560
+ this.objectTraits.clear();
561
+ this.traitToObjects.clear();
562
+ this.sourceToObjects.clear();
563
+ this.templateToObjects.clear();
564
+ this.previousObjectTraits.clear();
565
+ this.importEdges.clear();
566
+ this.reverseImportEdges.clear();
567
+ }
568
+ };
569
+ var globalTraitGraph = new TraitDependencyGraph();
570
+ globalTraitGraph.registerBuiltinTraits();
571
+
572
+ // src/parser/ImportResolver.ts
573
+ function resolveImportPath(importPath, baseDir) {
574
+ importPath = importPath.replace(/\\/g, "/");
575
+ baseDir = baseDir.replace(/\\/g, "/");
576
+ if (importPath.startsWith("/") || /^[A-Za-z]:/.test(importPath)) {
577
+ return importPath;
578
+ }
579
+ const baseResolved = normalizePath(baseDir);
580
+ const base = baseResolved.replace(/\/$/, "");
581
+ const combined = base + "/" + importPath;
582
+ return normalizePath(combined);
583
+ }
584
+ function normalizePath(p) {
585
+ const isAbsolute = p.startsWith("/");
586
+ const parts = p.split("/");
587
+ const resolved = [];
588
+ for (const part of parts) {
589
+ if (part === "" || part === ".") {
590
+ if (resolved.length === 0 && part === "" && isAbsolute) {
591
+ resolved.push("");
592
+ }
593
+ continue;
594
+ }
595
+ if (part === "..") {
596
+ if (resolved.length > (isAbsolute ? 1 : 0)) {
597
+ resolved.pop();
598
+ }
599
+ } else {
600
+ resolved.push(part);
601
+ }
602
+ }
603
+ let result = resolved.join("/");
604
+ if (isAbsolute && !result.startsWith("/")) result = "/" + result;
605
+ return result || "/";
606
+ }
607
+ var REGISTRY_IMPORT_RE = /^@[a-zA-Z0-9_-]+\/[a-zA-Z0-9_.-]+$/;
608
+ function isRegistryImport(importPath) {
609
+ return REGISTRY_IMPORT_RE.test(importPath);
610
+ }
611
+ function isCrdtImport(importPath) {
612
+ return importPath.startsWith("crdt://");
613
+ }
614
+ function parseRegistryImport(importPath) {
615
+ if (!isRegistryImport(importPath)) return null;
616
+ const parts = importPath.slice(1).split("/");
617
+ return { username: parts[0], name: parts[1] };
618
+ }
619
+ var ImportResolver = class {
620
+ constructor() {
621
+ /** Already-resolved modules keyed by canonical path */
622
+ this.cache = /* @__PURE__ */ new Map();
623
+ /** Paths currently being resolved (DFS cycle detection) */
624
+ this.inProgress = /* @__PURE__ */ new Set();
625
+ }
626
+ /**
627
+ * Resolve all @import directives from a parsed result and return a merged scope.
628
+ *
629
+ * @param result - The top-level parse result (from HoloScriptPlusParser.parse)
630
+ * @param sourceFile - Canonical path of the file that produced `result`
631
+ * @param options - Resolution options
632
+ */
633
+ async resolve(result, sourceFile, options) {
634
+ if (options.disabled) {
635
+ return { scope: /* @__PURE__ */ new Map(), modules: /* @__PURE__ */ new Map(), errors: [] };
636
+ }
637
+ const scope = /* @__PURE__ */ new Map();
638
+ const modules = /* @__PURE__ */ new Map();
639
+ const errors = [];
640
+ const imports = result.ast?.imports ?? [];
641
+ if (imports.length === 0) {
642
+ return { scope, modules, errors };
643
+ }
644
+ const baseDir = options.baseDir.replace(/\\/g, "/");
645
+ for (const imp of imports) {
646
+ const canonicalPath = isRegistryImport(imp.path) || isCrdtImport(imp.path) ? imp.path : resolveImportPath(imp.path, baseDir);
647
+ let mod;
648
+ try {
649
+ mod = await this._resolveModule(canonicalPath, sourceFile, options, 0, errors);
650
+ } catch (err) {
651
+ const msg = err instanceof Error ? err.message : String(err);
652
+ errors.push({
653
+ importPath: imp.path,
654
+ message: msg,
655
+ code: msg.startsWith("Circular") ? "cycle" : msg.startsWith("Max depth") ? "max_depth" : msg.startsWith("Parse error") ? "parse_error" : msg.startsWith("Registry") ? "registry_unavailable" : "not_found",
656
+ ...msg.startsWith("Circular") ? { cycle: [canonicalPath] } : {}
657
+ });
658
+ continue;
659
+ }
660
+ modules.set(canonicalPath, mod);
661
+ if (imp.namedImports && imp.namedImports.length > 0) {
662
+ for (const named of imp.namedImports) {
663
+ const node = mod.exports.get(named);
664
+ if (!node) {
665
+ errors.push({
666
+ importPath: imp.path,
667
+ message: `'${named}' is not exported from '${imp.path}'`,
668
+ code: "named_not_exported"
669
+ });
670
+ } else {
671
+ scope.set(named, node);
672
+ }
673
+ }
674
+ } else if (imp.isWildcard) {
675
+ for (const [exportName, node] of mod.exports) {
676
+ scope.set(`${imp.alias}.${exportName}`, node);
677
+ }
678
+ } else {
679
+ for (const [exportName, node] of mod.exports) {
680
+ scope.set(`${imp.alias}.${exportName}`, node);
681
+ }
682
+ }
683
+ }
684
+ return { scope, modules, errors };
685
+ }
686
+ /**
687
+ * Recursively resolve a single module file.
688
+ * Cycle detection: if `canonicalPath` is already in `inProgress`, throws.
689
+ * Transitive errors (cycles, missing, max depth) are pushed to `errors` array.
690
+ */
691
+ async _resolveModule(canonicalPath, importedBy, options, depth, errors) {
692
+ const maxDepth = options.maxDepth ?? 32;
693
+ if (depth > maxDepth) {
694
+ throw new Error(`Max depth (${maxDepth}) exceeded resolving '${canonicalPath}'`);
695
+ }
696
+ if (this.inProgress.has(canonicalPath)) {
697
+ const chain = [...this.inProgress, canonicalPath];
698
+ throw new Error(`Circular import detected: ${chain.join(" \u2192 ")}`);
699
+ }
700
+ if (this.cache.has(canonicalPath)) {
701
+ return this.cache.get(canonicalPath);
702
+ }
703
+ this.inProgress.add(canonicalPath);
704
+ try {
705
+ let source;
706
+ if (isRegistryImport(canonicalPath) && options.registryBaseUrl) {
707
+ try {
708
+ source = await this._fetchRegistrySource(canonicalPath, options.registryBaseUrl);
709
+ } catch {
710
+ throw new Error(
711
+ `Registry unavailable for '${canonicalPath}' (imported from '${importedBy}')`
712
+ );
713
+ }
714
+ } else if (isCrdtImport(canonicalPath)) {
715
+ try {
716
+ source = await this._fetchCrdtSource(canonicalPath);
717
+ } catch (err) {
718
+ throw new Error(
719
+ `CRDT feed unavailable for '${canonicalPath}' (imported from '${importedBy}'): ${err instanceof Error ? err.message : String(err)}`
720
+ );
721
+ }
722
+ } else {
723
+ try {
724
+ const reader = options.readFile ?? this._defaultReader();
725
+ source = await reader(canonicalPath);
726
+ } catch {
727
+ throw new Error(`File not found: '${canonicalPath}' (imported from '${importedBy}')`);
728
+ }
729
+ }
730
+ const { HoloScriptPlusParser } = await import('./HoloScriptPlusParser-WKHRIH6T.cjs');
731
+ const parser = new HoloScriptPlusParser({ enableTypeScriptImports: true });
732
+ const result = parser.parse(source);
733
+ if (!result.success && result.errors.length > 0) {
734
+ throw new Error(
735
+ `Parse error in '${canonicalPath}': ${result.errors[0]?.message ?? "unknown error"}`
736
+ );
737
+ }
738
+ const exports$1 = this._extractExports(result);
739
+ const transitiveDeps = [];
740
+ const subImports = result.ast?.imports ?? [];
741
+ const baseDir = canonicalPath.replace(/\/[^/]+$/, "");
742
+ for (const subImp of subImports) {
743
+ const subPath = isRegistryImport(subImp.path) || isCrdtImport(subImp.path) ? subImp.path : resolveImportPath(subImp.path, baseDir);
744
+ transitiveDeps.push(subPath);
745
+ if (!this.cache.has(subPath)) {
746
+ try {
747
+ const subMod = await this._resolveModule(
748
+ subPath,
749
+ canonicalPath,
750
+ options,
751
+ depth + 1,
752
+ errors
753
+ );
754
+ for (const [k, v] of subMod.exports) {
755
+ if (!exports$1.has(k)) exports$1.set(k, v);
756
+ }
757
+ } catch (err) {
758
+ const msg = err instanceof Error ? err.message : String(err);
759
+ errors.push({
760
+ importPath: subImp.path,
761
+ message: msg,
762
+ code: msg.startsWith("Circular") ? "cycle" : msg.startsWith("Max depth") ? "max_depth" : msg.startsWith("Parse error") ? "parse_error" : msg.startsWith("Registry") ? "registry_unavailable" : "not_found",
763
+ ...msg.startsWith("Circular") ? { cycle: [subPath] } : {}
764
+ });
765
+ }
766
+ }
767
+ }
768
+ const mod = {
769
+ canonicalPath,
770
+ result,
771
+ exports: exports$1,
772
+ dependencies: transitiveDeps
773
+ };
774
+ this.cache.set(canonicalPath, mod);
775
+ return mod;
776
+ } finally {
777
+ this.inProgress.delete(canonicalPath);
778
+ }
779
+ }
780
+ /**
781
+ * Fetch native string sources from the local LoroText Holographic CRDT.
782
+ * This bridges the compiler directly into the decentralized HoloMesh feed.
783
+ */
784
+ async _fetchCrdtSource(importPath) {
785
+ if (importPath !== "crdt://holomesh/feed") {
786
+ throw new Error(`Unknown CRDT namespace. Only crdt://holomesh/feed is supported.`);
787
+ }
788
+ try {
789
+ const fsModule = "fs/promises";
790
+ const pathModule = "path";
791
+ const fs = await import(
792
+ /* webpackIgnore: true */
793
+ /* @vite-ignore */
794
+ fsModule
795
+ );
796
+ const path = await import(
797
+ /* webpackIgnore: true */
798
+ /* @vite-ignore */
799
+ pathModule
800
+ );
801
+ const pkgName = "@loro/loro";
802
+ const { LoroDoc } = await import(
803
+ /* webpackIgnore: true */
804
+ /* @vite-ignore */
805
+ pkgName
806
+ );
807
+ const crdtPath = path.resolve(process.cwd(), ".holomesh/worldstate.crdt");
808
+ const bytes = await fs.readFile(crdtPath);
809
+ const doc = new LoroDoc();
810
+ doc.import(bytes);
811
+ const feed = doc.getText("feed");
812
+ return feed.toString();
813
+ } catch (e) {
814
+ throw new Error(`CRDT Sync Error: ${e instanceof Error ? e.message : String(e)}`);
815
+ }
816
+ }
817
+ /**
818
+ * Fetch source code from the community registry for @username/name imports.
819
+ * Calls GET {registryBaseUrl}/api/scene/{name} and returns the scene code.
820
+ */
821
+ async _fetchRegistrySource(importPath, registryBaseUrl) {
822
+ const parsed = parseRegistryImport(importPath);
823
+ if (!parsed) {
824
+ throw new Error(`Invalid registry import path: '${importPath}'`);
825
+ }
826
+ const url = `${registryBaseUrl.replace(/\/$/, "")}/api/registry/${encodeURIComponent(parsed.username)}/${encodeURIComponent(parsed.name)}`;
827
+ const response = await fetch(url);
828
+ if (!response.ok) {
829
+ throw new Error(`Registry returned ${response.status} for '${importPath}'`);
830
+ }
831
+ const data = await response.json();
832
+ if (!data.code || typeof data.code !== "string") {
833
+ throw new Error(`Registry returned no code for '${importPath}'`);
834
+ }
835
+ return data.code;
836
+ }
837
+ /**
838
+ * Extract @exported nodes from a parse result.
839
+ *
840
+ * Handles two AST shapes that HoloScriptPlusParser can produce:
841
+ * 1. Single node file: result.ast.root IS the node; its directives contain @export
842
+ * 2. Fragment file: result.ast.root.children[] are nodes, each may have @export directives
843
+ */
844
+ _extractExports(result) {
845
+ const exports$1 = /* @__PURE__ */ new Map();
846
+ const ast = result.ast;
847
+ if (!ast) return exports$1;
848
+ const root = ast.root;
849
+ if (!root) return exports$1;
850
+ const seen = /* @__PURE__ */ new Set();
851
+ const nodesToCheck = [];
852
+ const addNode = (n) => {
853
+ if (!n || typeof n !== "object") return;
854
+ const node = n;
855
+ if (!seen.has(node)) {
856
+ seen.add(node);
857
+ nodesToCheck.push(node);
858
+ }
859
+ };
860
+ addNode(root);
861
+ if (Array.isArray(root.children)) {
862
+ for (const child of root.children) addNode(child);
863
+ }
864
+ if (Array.isArray(ast.body)) {
865
+ for (const n of ast.body) addNode(n);
866
+ }
867
+ if (Array.isArray(ast.children)) {
868
+ for (const n of ast.children) addNode(n);
869
+ }
870
+ for (const node of nodesToCheck) {
871
+ const nodeRec = node;
872
+ const directives = nodeRec.directives ?? [];
873
+ const exportDir = directives.find((d) => d?.type === "export");
874
+ if (exportDir) {
875
+ const exportName = exportDir.exportName ?? nodeRec.id ?? nodeRec.name ?? nodeRec.type;
876
+ exports$1.set(exportName, node);
877
+ }
878
+ }
879
+ return exports$1;
880
+ }
881
+ /**
882
+ * Default Node.js file reader. Only used on server-side / CLI.
883
+ * Throws in environments without the 'fs' module (browser, XR).
884
+ */
885
+ _defaultReader() {
886
+ return async (filePath) => {
887
+ try {
888
+ const fsModule = "fs/promises";
889
+ const fs = await import(
890
+ /* webpackIgnore: true */
891
+ /* @vite-ignore */
892
+ fsModule
893
+ );
894
+ return await fs.readFile(filePath, "utf-8");
895
+ } catch {
896
+ throw new Error(
897
+ `Cannot read '${filePath}': no readFile option provided and fs is unavailable`
898
+ );
899
+ }
900
+ };
901
+ }
902
+ /** Clear the module cache (useful between test runs) */
903
+ clearCache() {
904
+ this.cache.clear();
905
+ this.inProgress.clear();
906
+ }
907
+ /** Return the set of canonical paths currently cached */
908
+ getCachedPaths() {
909
+ return [...this.cache.keys()];
910
+ }
911
+ /** Return a resolved module from cache, or undefined */
912
+ getCached(canonicalPath) {
913
+ return this.cache.get(canonicalPath);
914
+ }
915
+ };
916
+
917
+ // src/compiler/SemanticCache.ts
918
+ chunkE7JP3BS3_cjs.init_safeJsonParse();
919
+ function hashSourceCode(source) {
920
+ return crypto.createHash("sha256").update(source, "utf8").digest("hex");
921
+ }
922
+ function generateCacheKey(contentHash, type, prefix) {
923
+ return `${prefix}:${type}:${contentHash}`;
924
+ }
925
+ function serializeASTNode(node) {
926
+ return JSON.stringify(node, null, 0);
927
+ }
928
+ function hashASTSubtree(node) {
929
+ const serialized = serializeASTNode(node);
930
+ return hashSourceCode(serialized);
931
+ }
932
+ var SemanticCache = class {
933
+ constructor(options = {}) {
934
+ this.redis = null;
935
+ this.memoryCache = /* @__PURE__ */ new Map();
936
+ this.stats = {
937
+ hits: 0,
938
+ misses: 0,
939
+ totalLatencyMs: 0,
940
+ lookupCount: 0
941
+ };
942
+ this.redisConnected = false;
943
+ this.initialized = false;
944
+ this.options = {
945
+ redisUrl: options.redisUrl ?? "redis://localhost:6379",
946
+ keyPrefix: options.keyPrefix ?? "holoscript:semantic",
947
+ ttl: options.ttl ?? 7 * 24 * 60 * 60,
948
+ // 7 days in seconds
949
+ version: options.version ?? "1.0.0",
950
+ debug: options.debug ?? false,
951
+ connectionTimeout: options.connectionTimeout ?? 5e3,
952
+ maxRetries: options.maxRetries ?? 3
953
+ };
954
+ }
955
+ /**
956
+ * Initialize the cache (connect to Redis if available)
957
+ */
958
+ async initialize() {
959
+ if (this.initialized) return;
960
+ try {
961
+ const Redis = await this.loadRedisClient();
962
+ if (Redis) {
963
+ this.redis = new Redis(this.options.redisUrl, {
964
+ connectTimeout: this.options.connectionTimeout,
965
+ maxRetriesPerRequest: this.options.maxRetries,
966
+ lazyConnect: true,
967
+ enableOfflineQueue: false
968
+ });
969
+ this.redis.on("connect", () => {
970
+ this.redisConnected = true;
971
+ this.log("Redis connected");
972
+ });
973
+ this.redis.on("error", (error) => {
974
+ this.log(`Redis error: ${error.message}`);
975
+ this.redisConnected = false;
976
+ });
977
+ this.redis.on("close", () => {
978
+ this.redisConnected = false;
979
+ this.log("Redis disconnected");
980
+ });
981
+ await this.redis.ping();
982
+ this.redisConnected = true;
983
+ this.log("Redis cache initialized");
984
+ }
985
+ } catch (error) {
986
+ this.log(`Redis initialization failed: ${error}. Falling back to in-memory cache.`);
987
+ this.redis = null;
988
+ this.redisConnected = false;
989
+ }
990
+ this.initialized = true;
991
+ this.log(`Semantic cache initialized (backend: ${this.getBackend()})`);
992
+ }
993
+ /**
994
+ * Load Redis client dynamically (optional dependency)
995
+ */
996
+ async loadRedisClient() {
997
+ try {
998
+ const ioredis = await import('ioredis');
999
+ return ioredis.default;
1000
+ } catch (error) {
1001
+ this.log("ioredis not installed, using in-memory cache");
1002
+ return null;
1003
+ }
1004
+ }
1005
+ /**
1006
+ * Get cache entry
1007
+ */
1008
+ async get(contentHash, type) {
1009
+ if (!this.initialized) {
1010
+ await this.initialize();
1011
+ }
1012
+ const startTime = Date.now();
1013
+ const key = generateCacheKey(contentHash, type, this.options.keyPrefix);
1014
+ try {
1015
+ let entry = null;
1016
+ if (this.redis && this.redisConnected) {
1017
+ const raw = await this.redis.get(key);
1018
+ if (raw) {
1019
+ entry = chunkE7JP3BS3_cjs.readJson(raw);
1020
+ }
1021
+ } else {
1022
+ const memEntry = this.memoryCache.get(key);
1023
+ if (memEntry) {
1024
+ entry = memEntry;
1025
+ }
1026
+ }
1027
+ const latencyMs = Date.now() - startTime;
1028
+ this.stats.totalLatencyMs += latencyMs;
1029
+ this.stats.lookupCount++;
1030
+ if (!entry) {
1031
+ this.stats.misses++;
1032
+ return {
1033
+ hit: false,
1034
+ reason: "not_found",
1035
+ latencyMs
1036
+ };
1037
+ }
1038
+ if (entry.version !== this.options.version) {
1039
+ this.stats.misses++;
1040
+ await this.delete(contentHash, type);
1041
+ return {
1042
+ hit: false,
1043
+ reason: "version_mismatch",
1044
+ latencyMs
1045
+ };
1046
+ }
1047
+ if (!this.redis) {
1048
+ const age = Date.now() - entry.createdAt;
1049
+ const ttlMs = this.options.ttl * 1e3;
1050
+ if (age > ttlMs) {
1051
+ this.stats.misses++;
1052
+ this.memoryCache.delete(key);
1053
+ return {
1054
+ hit: false,
1055
+ reason: "expired",
1056
+ latencyMs
1057
+ };
1058
+ }
1059
+ }
1060
+ entry.accessedAt = Date.now();
1061
+ entry.accessCount++;
1062
+ if (this.redis && this.redisConnected) {
1063
+ await this.redis.set(key, JSON.stringify(entry), "EX", this.options.ttl);
1064
+ } else {
1065
+ this.memoryCache.set(key, entry);
1066
+ }
1067
+ this.stats.hits++;
1068
+ this.log(`Cache HIT: ${type} (${contentHash.slice(0, 8)}...) [${latencyMs}ms]`);
1069
+ return {
1070
+ hit: true,
1071
+ entry,
1072
+ latencyMs
1073
+ };
1074
+ } catch (error) {
1075
+ this.stats.misses++;
1076
+ this.log(`Cache lookup error: ${error}`);
1077
+ return {
1078
+ hit: false,
1079
+ reason: "redis_error",
1080
+ latencyMs: Date.now() - startTime
1081
+ };
1082
+ }
1083
+ }
1084
+ /**
1085
+ * Set cache entry
1086
+ */
1087
+ async set(contentHash, type, data, options) {
1088
+ if (!this.initialized) {
1089
+ await this.initialize();
1090
+ }
1091
+ const key = generateCacheKey(contentHash, type, this.options.keyPrefix);
1092
+ const serialized = JSON.stringify(data);
1093
+ const entry = {
1094
+ contentHash,
1095
+ type,
1096
+ data,
1097
+ sourcePath: options?.sourcePath,
1098
+ dependencies: options?.dependencies,
1099
+ createdAt: Date.now(),
1100
+ accessedAt: Date.now(),
1101
+ accessCount: 0,
1102
+ size: serialized.length,
1103
+ version: this.options.version
1104
+ };
1105
+ try {
1106
+ if (this.redis && this.redisConnected) {
1107
+ await this.redis.set(key, JSON.stringify(entry), "EX", this.options.ttl);
1108
+ } else {
1109
+ this.memoryCache.set(key, entry);
1110
+ }
1111
+ this.log(`Cache SET: ${type} (${contentHash.slice(0, 8)}...) [${entry.size} bytes]`);
1112
+ } catch (error) {
1113
+ this.log(`Cache set error: ${error}`);
1114
+ }
1115
+ }
1116
+ /**
1117
+ * Delete cache entry
1118
+ */
1119
+ async delete(contentHash, type) {
1120
+ if (!this.initialized) {
1121
+ await this.initialize();
1122
+ }
1123
+ const key = generateCacheKey(contentHash, type, this.options.keyPrefix);
1124
+ try {
1125
+ if (this.redis && this.redisConnected) {
1126
+ await this.redis.del(key);
1127
+ } else {
1128
+ this.memoryCache.delete(key);
1129
+ }
1130
+ this.log(`Cache DELETE: ${type} (${contentHash.slice(0, 8)}...)`);
1131
+ } catch (error) {
1132
+ this.log(`Cache delete error: ${error}`);
1133
+ }
1134
+ }
1135
+ /**
1136
+ * Invalidate all cache entries for a type
1137
+ */
1138
+ async invalidateType(type) {
1139
+ if (!this.initialized) {
1140
+ await this.initialize();
1141
+ }
1142
+ let count = 0;
1143
+ try {
1144
+ if (this.redis && this.redisConnected) {
1145
+ const pattern = `${this.options.keyPrefix}:${type}:*`;
1146
+ const keys = await this.redis.keys(pattern);
1147
+ for (const key of keys) {
1148
+ await this.redis.del(key);
1149
+ count++;
1150
+ }
1151
+ } else {
1152
+ for (const [key, entry] of this.memoryCache.entries()) {
1153
+ if (entry.type === type) {
1154
+ this.memoryCache.delete(key);
1155
+ count++;
1156
+ }
1157
+ }
1158
+ }
1159
+ this.log(`Invalidated ${count} entries of type: ${type}`);
1160
+ } catch (error) {
1161
+ this.log(`Cache invalidation error: ${error}`);
1162
+ }
1163
+ return count;
1164
+ }
1165
+ /**
1166
+ * Clear all cache entries
1167
+ */
1168
+ async clear() {
1169
+ if (!this.initialized) {
1170
+ await this.initialize();
1171
+ }
1172
+ try {
1173
+ if (this.redis && this.redisConnected) {
1174
+ const pattern = `${this.options.keyPrefix}:*`;
1175
+ const keys = await this.redis.keys(pattern);
1176
+ for (const key of keys) {
1177
+ await this.redis.del(key);
1178
+ }
1179
+ } else {
1180
+ this.memoryCache.clear();
1181
+ }
1182
+ this.stats.hits = 0;
1183
+ this.stats.misses = 0;
1184
+ this.stats.totalLatencyMs = 0;
1185
+ this.stats.lookupCount = 0;
1186
+ this.log("Cache cleared");
1187
+ } catch (error) {
1188
+ this.log(`Cache clear error: ${error}`);
1189
+ }
1190
+ }
1191
+ /**
1192
+ * Get cache statistics
1193
+ */
1194
+ async getStats() {
1195
+ const totalRequests = this.stats.hits + this.stats.misses;
1196
+ const hitRate = totalRequests > 0 ? this.stats.hits / totalRequests : 0;
1197
+ const avgLatencyMs = this.stats.lookupCount > 0 ? this.stats.totalLatencyMs / this.stats.lookupCount : 0;
1198
+ let totalEntries = 0;
1199
+ const entriesByType = {
1200
+ "ast-subtree": 0,
1201
+ "compiled-module": 0,
1202
+ "compiled-object": 0,
1203
+ "trait-composition": 0,
1204
+ "import-resolution": 0
1205
+ };
1206
+ try {
1207
+ if (this.redis && this.redisConnected) {
1208
+ const pattern = `${this.options.keyPrefix}:*`;
1209
+ const keys = await this.redis.keys(pattern);
1210
+ totalEntries = keys.length;
1211
+ for (const key of keys) {
1212
+ const parts = key.split(":");
1213
+ const type = parts[2];
1214
+ if (type in entriesByType) {
1215
+ entriesByType[type]++;
1216
+ }
1217
+ }
1218
+ } else {
1219
+ totalEntries = this.memoryCache.size;
1220
+ for (const entry of this.memoryCache.values()) {
1221
+ entriesByType[entry.type]++;
1222
+ }
1223
+ }
1224
+ } catch (error) {
1225
+ this.log(`Stats error: ${error}`);
1226
+ }
1227
+ return {
1228
+ hits: this.stats.hits,
1229
+ misses: this.stats.misses,
1230
+ hitRate,
1231
+ avgLatencyMs,
1232
+ totalEntries,
1233
+ backend: this.getBackend(),
1234
+ redisConnected: this.redisConnected,
1235
+ entriesByType
1236
+ };
1237
+ }
1238
+ /**
1239
+ * Get cache backend type
1240
+ */
1241
+ getBackend() {
1242
+ return this.redis && this.redisConnected ? "redis" : "memory";
1243
+ }
1244
+ /**
1245
+ * Close Redis connection
1246
+ */
1247
+ async close() {
1248
+ if (this.redis) {
1249
+ try {
1250
+ await this.redis.quit();
1251
+ this.log("Redis connection closed");
1252
+ } catch (error) {
1253
+ this.log(`Error closing Redis: ${error}`);
1254
+ }
1255
+ }
1256
+ }
1257
+ /**
1258
+ * Debug logging
1259
+ */
1260
+ log(message) {
1261
+ if (this.options.debug) {
1262
+ console.log(`[SemanticCache] ${message}`);
1263
+ }
1264
+ }
1265
+ };
1266
+ function createSemanticCache(options) {
1267
+ return new SemanticCache(options);
1268
+ }
1269
+
1270
+ // src/compiler/IncrementalCompiler.ts
1271
+ chunkKKP7JKN4_cjs.init_AgentRBAC();
1272
+ chunkKKP7JKN4_cjs.init_CompilerBase();
1273
+ chunkE7JP3BS3_cjs.init_safeJsonParse();
1274
+ function hashContent(content) {
1275
+ let hash = 0;
1276
+ for (let i = 0; i < content.length; i++) {
1277
+ const char = content.charCodeAt(i);
1278
+ hash = (hash << 5) - hash + char;
1279
+ hash = hash & hash;
1280
+ }
1281
+ return hash.toString(36);
1282
+ }
1283
+ function hashConfig2(config) {
1284
+ const keys = Object.keys(config).sort();
1285
+ const parts = [];
1286
+ for (const key of keys) {
1287
+ const value = config[key];
1288
+ parts.push(`${key}:${JSON.stringify(value)}`);
1289
+ }
1290
+ const str = parts.join("|");
1291
+ let hash = 5381;
1292
+ for (let i = 0; i < str.length; i++) {
1293
+ hash = (hash << 5) + hash ^ str.charCodeAt(i);
1294
+ }
1295
+ return (hash >>> 0).toString(36);
1296
+ }
1297
+ function serializeObject(obj) {
1298
+ return JSON.stringify({
1299
+ name: obj.name,
1300
+ properties: obj.properties,
1301
+ traits: obj.traits,
1302
+ children: obj.children?.map(serializeObject),
1303
+ logic: obj.logic
1304
+ // logic might not be directly on HoloObjectDecl but used in diff
1305
+ });
1306
+ }
1307
+ function serializeProperty(prop) {
1308
+ return JSON.stringify({ key: prop.key, value: prop.value });
1309
+ }
1310
+ var IncrementalCompiler = class _IncrementalCompiler {
1311
+ constructor(traitGraph, options) {
1312
+ this.cache = /* @__PURE__ */ new Map();
1313
+ this.previousAST = null;
1314
+ this.stateSnapshot = null;
1315
+ this.dependencyGraph = /* @__PURE__ */ new Map();
1316
+ this.semanticCache = null;
1317
+ /** Persistent disk cache keyed by provenance content-hash (paper-10). */
1318
+ this.buildCache = null;
1319
+ this.traitGraph = traitGraph || globalTraitGraph;
1320
+ this.buildCache = options?.buildCache ?? null;
1321
+ if (options?.enableSemanticCache) {
1322
+ this.semanticCache = createSemanticCache({
1323
+ redisUrl: options.redisUrl,
1324
+ ttl: options.cacheTTL,
1325
+ debug: false
1326
+ });
1327
+ this.semanticCache.initialize().catch((err) => {
1328
+ console.warn(`Semantic cache initialization failed: ${err}`);
1329
+ this.semanticCache = null;
1330
+ });
1331
+ }
1332
+ }
1333
+ /**
1334
+ * Diff two ASTs and return the changes
1335
+ */
1336
+ diff(oldAST, newAST) {
1337
+ const changes = [];
1338
+ const addedObjects = [];
1339
+ const removedObjects = [];
1340
+ const modifiedObjects = [];
1341
+ const unchangedObjects = [];
1342
+ if (!oldAST) {
1343
+ const allObjects = this.collectObjectNames(newAST);
1344
+ return {
1345
+ hasChanges: true,
1346
+ changes: allObjects.map((name) => ({
1347
+ type: "added",
1348
+ path: [name],
1349
+ nodeName: name,
1350
+ nodeType: "object",
1351
+ newValue: this.findObject(newAST, name)
1352
+ })),
1353
+ addedObjects: allObjects,
1354
+ removedObjects: [],
1355
+ modifiedObjects: [],
1356
+ unchangedObjects: []
1357
+ };
1358
+ }
1359
+ const oldObjects = /* @__PURE__ */ new Map();
1360
+ const newObjects = /* @__PURE__ */ new Map();
1361
+ this.collectObjects(oldAST, oldObjects);
1362
+ this.collectObjects(newAST, newObjects);
1363
+ for (const [name, obj] of newObjects) {
1364
+ if (!oldObjects.has(name)) {
1365
+ addedObjects.push(name);
1366
+ changes.push({
1367
+ type: "added",
1368
+ path: [name],
1369
+ nodeName: name,
1370
+ nodeType: "object",
1371
+ newValue: obj
1372
+ });
1373
+ }
1374
+ }
1375
+ for (const [name, obj] of oldObjects) {
1376
+ if (!newObjects.has(name)) {
1377
+ removedObjects.push(name);
1378
+ changes.push({
1379
+ type: "removed",
1380
+ path: [name],
1381
+ nodeName: name,
1382
+ nodeType: "object",
1383
+ oldValue: obj
1384
+ });
1385
+ }
1386
+ }
1387
+ for (const [name, newObj] of newObjects) {
1388
+ if (oldObjects.has(name)) {
1389
+ const oldObj = oldObjects.get(name);
1390
+ const objectChanges = this.diffObject(oldObj, newObj, [name]);
1391
+ if (objectChanges.length > 0) {
1392
+ modifiedObjects.push(name);
1393
+ changes.push(...objectChanges);
1394
+ } else {
1395
+ unchangedObjects.push(name);
1396
+ }
1397
+ }
1398
+ }
1399
+ return {
1400
+ hasChanges: changes.length > 0,
1401
+ changes,
1402
+ addedObjects,
1403
+ removedObjects,
1404
+ modifiedObjects,
1405
+ unchangedObjects
1406
+ };
1407
+ }
1408
+ /**
1409
+ * Diff two objects and return property-level changes
1410
+ */
1411
+ diffObject(oldObj, newObj, path) {
1412
+ const changes = [];
1413
+ const oldProps = new Map(oldObj.properties?.map((p) => [p.key, p]) || []);
1414
+ const newProps = new Map(newObj.properties?.map((p) => [p.key, p]) || []);
1415
+ for (const [key, newProp] of newProps) {
1416
+ if (!oldProps.has(key)) {
1417
+ changes.push({
1418
+ type: "added",
1419
+ path: [...path, key],
1420
+ nodeName: key,
1421
+ nodeType: "property",
1422
+ newValue: newProp.value
1423
+ });
1424
+ } else {
1425
+ const oldProp = oldProps.get(key);
1426
+ if (serializeProperty(oldProp) !== serializeProperty(newProp)) {
1427
+ changes.push({
1428
+ type: "modified",
1429
+ path: [...path, key],
1430
+ nodeName: key,
1431
+ nodeType: "property",
1432
+ oldValue: oldProp.value,
1433
+ newValue: newProp.value
1434
+ });
1435
+ }
1436
+ }
1437
+ }
1438
+ for (const key of oldProps.keys()) {
1439
+ if (!newProps.has(key)) {
1440
+ changes.push({
1441
+ type: "removed",
1442
+ path: [...path, key],
1443
+ nodeName: key,
1444
+ nodeType: "property",
1445
+ oldValue: oldProps.get(key).value
1446
+ });
1447
+ }
1448
+ }
1449
+ const oldTraitUsages = this.extractTraitUsages(oldObj.traits || []);
1450
+ const newTraitUsages = this.extractTraitUsages(newObj.traits || []);
1451
+ const oldTraitMap = new Map(oldTraitUsages.map((t) => [t.name, t]));
1452
+ const newTraitMap = new Map(newTraitUsages.map((t) => [t.name, t]));
1453
+ for (const [name, newTrait] of newTraitMap) {
1454
+ if (!oldTraitMap.has(name)) {
1455
+ changes.push({
1456
+ type: "added",
1457
+ path: [...path, "@" + name],
1458
+ nodeName: name,
1459
+ nodeType: "trait",
1460
+ newValue: newTrait
1461
+ });
1462
+ }
1463
+ }
1464
+ for (const [name, oldTrait] of oldTraitMap) {
1465
+ if (!newTraitMap.has(name)) {
1466
+ changes.push({
1467
+ type: "removed",
1468
+ path: [...path, "@" + name],
1469
+ nodeName: name,
1470
+ nodeType: "trait",
1471
+ oldValue: oldTrait
1472
+ });
1473
+ }
1474
+ }
1475
+ for (const [name, newTrait] of newTraitMap) {
1476
+ const oldTrait = oldTraitMap.get(name);
1477
+ if (oldTrait && oldTrait.configHash !== newTrait.configHash) {
1478
+ changes.push({
1479
+ type: "modified",
1480
+ path: [...path, "@" + name],
1481
+ nodeName: name,
1482
+ nodeType: "trait",
1483
+ oldValue: oldTrait,
1484
+ newValue: newTrait
1485
+ });
1486
+ }
1487
+ }
1488
+ if (JSON.stringify(oldObj.logic) !== JSON.stringify(newObj.logic)) {
1489
+ changes.push({
1490
+ type: "modified",
1491
+ path: [...path, "logic"],
1492
+ nodeName: "logic",
1493
+ nodeType: "logic",
1494
+ oldValue: oldObj.logic,
1495
+ newValue: newObj.logic
1496
+ });
1497
+ }
1498
+ const oldChildren = new Map((oldObj.children || []).map((c) => [c.name, c]));
1499
+ const newChildren = new Map((newObj.children || []).map((c) => [c.name, c]));
1500
+ for (const [name, newChild] of newChildren) {
1501
+ if (!oldChildren.has(name)) {
1502
+ changes.push({
1503
+ type: "added",
1504
+ path: [...path, name],
1505
+ nodeName: name,
1506
+ nodeType: "object",
1507
+ newValue: newChild
1508
+ });
1509
+ } else {
1510
+ const childChanges = this.diffObject(oldChildren.get(name), newChild, [...path, name]);
1511
+ changes.push(...childChanges);
1512
+ }
1513
+ }
1514
+ for (const name of oldChildren.keys()) {
1515
+ if (!newChildren.has(name)) {
1516
+ changes.push({
1517
+ type: "removed",
1518
+ path: [...path, name],
1519
+ nodeName: name,
1520
+ nodeType: "object",
1521
+ oldValue: oldChildren.get(name)
1522
+ });
1523
+ }
1524
+ }
1525
+ return changes;
1526
+ }
1527
+ /**
1528
+ * Extract trait usages with config hashes from trait array
1529
+ * Handles both string traits and trait objects with config
1530
+ */
1531
+ extractTraitUsages(traits) {
1532
+ return traits.map((t) => {
1533
+ if (typeof t === "string") {
1534
+ return {
1535
+ name: t,
1536
+ config: {},
1537
+ configHash: hashConfig2({})
1538
+ };
1539
+ }
1540
+ if (t && typeof t === "object") {
1541
+ const traitObj = t;
1542
+ if ("name" in traitObj) {
1543
+ const name = String(traitObj.name);
1544
+ const config = {};
1545
+ for (const [key, value] of Object.entries(traitObj)) {
1546
+ if (key !== "name") {
1547
+ config[key] = value;
1548
+ }
1549
+ }
1550
+ return {
1551
+ name,
1552
+ config,
1553
+ configHash: hashConfig2(config)
1554
+ };
1555
+ }
1556
+ const keys = Object.keys(traitObj);
1557
+ if (keys.length === 1) {
1558
+ const name = keys[0];
1559
+ const config = traitObj[name] || {};
1560
+ return {
1561
+ name,
1562
+ config: typeof config === "object" ? config : {},
1563
+ configHash: hashConfig2(typeof config === "object" ? config : {})
1564
+ };
1565
+ }
1566
+ }
1567
+ return {
1568
+ name: String(t),
1569
+ config: {},
1570
+ configHash: hashConfig2({})
1571
+ };
1572
+ });
1573
+ }
1574
+ /**
1575
+ * Collect all object names from a composition
1576
+ */
1577
+ collectObjectNames(composition) {
1578
+ const names = [];
1579
+ const collectFromObject = (obj) => {
1580
+ names.push(obj.name);
1581
+ obj.children?.forEach(collectFromObject);
1582
+ };
1583
+ composition.objects?.forEach(collectFromObject);
1584
+ composition.spatialGroups?.forEach((group) => {
1585
+ names.push(group.name);
1586
+ group.objects?.forEach(collectFromObject);
1587
+ });
1588
+ return names;
1589
+ }
1590
+ /**
1591
+ * Collect all objects into a map
1592
+ */
1593
+ collectObjects(composition, map) {
1594
+ const collectFromObject = (obj) => {
1595
+ map.set(obj.name, obj);
1596
+ obj.children?.forEach(collectFromObject);
1597
+ };
1598
+ composition.objects?.forEach(collectFromObject);
1599
+ composition.spatialGroups?.forEach((group) => {
1600
+ group.objects?.forEach(collectFromObject);
1601
+ });
1602
+ }
1603
+ /**
1604
+ * Find an object by name in a composition
1605
+ */
1606
+ findObject(composition, name) {
1607
+ const searchInObject = (obj) => {
1608
+ if (obj.name === name) return obj;
1609
+ for (const child of obj.children || []) {
1610
+ const found = searchInObject(child);
1611
+ if (found) return found;
1612
+ }
1613
+ return void 0;
1614
+ };
1615
+ for (const obj of composition.objects || []) {
1616
+ const found = searchInObject(obj);
1617
+ if (found) return found;
1618
+ }
1619
+ for (const group of composition.spatialGroups || []) {
1620
+ for (const obj of group.objects || []) {
1621
+ const found = searchInObject(obj);
1622
+ if (found) return found;
1623
+ }
1624
+ }
1625
+ return void 0;
1626
+ }
1627
+ /**
1628
+ * Get cached compilation for an object if still valid
1629
+ */
1630
+ getCached(objectName, currentHash) {
1631
+ const entry = this.cache.get(objectName);
1632
+ if (entry && entry.hash === currentHash) {
1633
+ return entry;
1634
+ }
1635
+ return null;
1636
+ }
1637
+ /**
1638
+ * Store compilation result in cache
1639
+ */
1640
+ setCached(objectName, hash, compiledCode, dependencies) {
1641
+ this.cache.set(objectName, {
1642
+ hash,
1643
+ compiledCode,
1644
+ dependencies,
1645
+ timestamp: Date.now()
1646
+ });
1647
+ }
1648
+ /**
1649
+ * Save current state for hot reload
1650
+ */
1651
+ saveState(states) {
1652
+ this.stateSnapshot = {
1653
+ objectStates: new Map(states),
1654
+ timestamp: Date.now()
1655
+ };
1656
+ }
1657
+ /**
1658
+ * Restore state after hot reload
1659
+ */
1660
+ restoreState() {
1661
+ return this.stateSnapshot;
1662
+ }
1663
+ /**
1664
+ * Clear state snapshot
1665
+ */
1666
+ clearState() {
1667
+ this.stateSnapshot = null;
1668
+ }
1669
+ /**
1670
+ * Update dependency graph
1671
+ */
1672
+ updateDependencies(objectName, dependencies) {
1673
+ this.dependencyGraph.set(objectName, new Set(dependencies));
1674
+ }
1675
+ /**
1676
+ * Get objects that depend on a given object
1677
+ */
1678
+ getDependents(objectName) {
1679
+ const dependents = [];
1680
+ for (const [name, deps] of this.dependencyGraph) {
1681
+ if (deps.has(objectName)) {
1682
+ dependents.push(name);
1683
+ }
1684
+ }
1685
+ return dependents;
1686
+ }
1687
+ /**
1688
+ * Get all objects that need recompilation due to a change
1689
+ * Enhanced with trait-aware dependency tracking
1690
+ */
1691
+ getRecompilationSet(changedObjects) {
1692
+ const toRecompile = new Set(changedObjects);
1693
+ const queue = [...changedObjects];
1694
+ while (queue.length > 0) {
1695
+ const current = queue.shift();
1696
+ const dependents = this.getDependents(current);
1697
+ for (const dep of dependents) {
1698
+ if (!toRecompile.has(dep)) {
1699
+ toRecompile.add(dep);
1700
+ queue.push(dep);
1701
+ }
1702
+ }
1703
+ }
1704
+ const traitRecompileSet = this.traitGraph.calculateRecompilationSet(changedObjects);
1705
+ for (const obj of traitRecompileSet) {
1706
+ toRecompile.add(obj);
1707
+ }
1708
+ return toRecompile;
1709
+ }
1710
+ /**
1711
+ * Get trait changes for specific objects
1712
+ * Used for fine-grained trait config change detection
1713
+ */
1714
+ getTraitChanges(objectName, newTraits) {
1715
+ return this.traitGraph.detectTraitChanges(objectName, newTraits);
1716
+ }
1717
+ /**
1718
+ * Get the trait dependency graph for external access
1719
+ */
1720
+ getTraitGraph() {
1721
+ return this.traitGraph;
1722
+ }
1723
+ // ===========================================================================
1724
+ // IMPORT RESOLUTION (Asset Pipeline)
1725
+ // ===========================================================================
1726
+ /**
1727
+ * Resolve all `@import` directives in a `HSPlusCompileResult`, merge the
1728
+ * imported exports into a scope, and register cross-file edges in the
1729
+ * `TraitDependencyGraph` for incremental recompilation.
1730
+ *
1731
+ * This method is **async** because it may read files from disk (or any
1732
+ * injected async reader).
1733
+ *
1734
+ * ### Typical usage
1735
+ * ```ts
1736
+ * const parser = new HoloScriptPlusParser({ enableTypeScriptImports: true });
1737
+ * const result = parser.parse(source);
1738
+ *
1739
+ * const compiler = new IncrementalCompiler();
1740
+ * const { importScope, importErrors } = await compiler.resolveImports(
1741
+ * result,
1742
+ * { baseDir: '/project', sourceFile: '/project/scene.hs' }
1743
+ * );
1744
+ * ```
1745
+ *
1746
+ * @param result Parse result that may contain `ast.imports`
1747
+ * @param options Must include `baseDir` (and optionally `sourceFile`, `readFile`)
1748
+ * @returns `{ scope, modules, errors }` from `ImportResolver.resolve()`
1749
+ */
1750
+ async resolveImports(result, options) {
1751
+ const baseDir = options.baseDir ?? "/";
1752
+ const sourceFile = options.sourceFile ?? `${baseDir}/unknown.hs`;
1753
+ const resolver = new ImportResolver();
1754
+ const resolution = await resolver.resolve(result, sourceFile, {
1755
+ baseDir,
1756
+ readFile: options.readFile
1757
+ });
1758
+ const imports = result.ast?.imports ?? [];
1759
+ this.traitGraph.clearImportsForFile(sourceFile);
1760
+ for (const imp of imports) {
1761
+ const canonicalPath = resolveImportPath(imp.path, baseDir);
1762
+ this.traitGraph.registerImport(sourceFile, canonicalPath);
1763
+ }
1764
+ return resolution;
1765
+ }
1766
+ // ===========================================================================
1767
+ // RBAC ENFORCEMENT
1768
+ // ===========================================================================
1769
+ /**
1770
+ * Validate agent has permission for incremental compilation.
1771
+ * Skips validation when no token is provided (backwards compatibility / testing).
1772
+ */
1773
+ validateAccess(agentToken) {
1774
+ if (!agentToken) return;
1775
+ const rbac = chunkKKP7JKN4_cjs.getRBAC();
1776
+ const decision = rbac.checkAccess({
1777
+ token: agentToken,
1778
+ resourceType: "ast" /* AST */,
1779
+ operation: "read",
1780
+ expectedWorkflowStep: "generate_assembly" /* GENERATE_ASSEMBLY */
1781
+ });
1782
+ if (!decision.allowed) {
1783
+ throw new UnauthorizedIncrementalCompilerAccessError(decision, "IncrementalCompiler");
1784
+ }
1785
+ }
1786
+ /**
1787
+ * Perform incremental compilation
1788
+ */
1789
+ async compile(newAST, compileObject, options = {}) {
1790
+ const { preserveState = true, forceRecompile = [], skipUnchanged = true, agentToken } = options;
1791
+ this.validateAccess(agentToken);
1792
+ const diffResult = this.diff(this.previousAST, newAST);
1793
+ const changedObjects = [
1794
+ ...diffResult.addedObjects,
1795
+ ...diffResult.modifiedObjects,
1796
+ ...forceRecompile
1797
+ ];
1798
+ const recompileSet = this.getRecompilationSet(changedObjects);
1799
+ for (const removed of diffResult.removedObjects) {
1800
+ const dependents = this.getDependents(removed);
1801
+ for (const dep of dependents) {
1802
+ recompileSet.add(dep);
1803
+ }
1804
+ }
1805
+ const recompiledObjects = [];
1806
+ const cachedObjects = [];
1807
+ const compiledParts = [];
1808
+ const allObjects = /* @__PURE__ */ new Map();
1809
+ this.collectObjects(newAST, allObjects);
1810
+ for (const [name, obj] of allObjects) {
1811
+ const hash = hashContent(serializeObject(obj));
1812
+ const provenanceHash = chunkR75BSDH7_cjs.computeContentHash(serializeObject(obj));
1813
+ const traitUsages = this.extractTraitUsages(obj.traits || []);
1814
+ this.traitGraph.registerObject({
1815
+ objectName: name,
1816
+ sourceId: newAST.name || "default",
1817
+ traits: traitUsages,
1818
+ template: obj.template
1819
+ });
1820
+ if (this.buildCache) {
1821
+ const provResult = await this.buildCache.getByProvenanceHash(
1822
+ provenanceHash,
1823
+ "compiled"
1824
+ );
1825
+ if (provResult.hit) {
1826
+ cachedObjects.push(name);
1827
+ compiledParts.push(provResult.entry.data);
1828
+ continue;
1829
+ }
1830
+ }
1831
+ if (skipUnchanged && !recompileSet.has(name)) {
1832
+ if (this.semanticCache) {
1833
+ const astHash = hashASTSubtree(obj);
1834
+ const semanticResult = await this.semanticCache.get(astHash, "compiled-object");
1835
+ if (semanticResult.hit) {
1836
+ cachedObjects.push(name);
1837
+ compiledParts.push(semanticResult.entry.data);
1838
+ continue;
1839
+ }
1840
+ }
1841
+ const cached = this.getCached(name, hash);
1842
+ if (cached) {
1843
+ cachedObjects.push(name);
1844
+ compiledParts.push(cached.compiledCode);
1845
+ continue;
1846
+ }
1847
+ }
1848
+ const compiled = compileObject(obj);
1849
+ recompiledObjects.push(name);
1850
+ compiledParts.push(compiled);
1851
+ this.setCached(name, hash, compiled, []);
1852
+ if (this.buildCache) {
1853
+ await this.buildCache.setByProvenanceHash(provenanceHash, "compiled", compiled, {
1854
+ tags: ["incremental-compiler", newAST.name || "unknown"]
1855
+ });
1856
+ }
1857
+ if (this.semanticCache) {
1858
+ const astHash = hashASTSubtree(obj);
1859
+ await this.semanticCache.set(astHash, "compiled-object", compiled, {
1860
+ sourcePath: newAST.name,
1861
+ dependencies: []
1862
+ });
1863
+ }
1864
+ }
1865
+ this.previousAST = newAST;
1866
+ return {
1867
+ fullRecompile: cachedObjects.length === 0,
1868
+ recompiledObjects,
1869
+ cachedObjects,
1870
+ statePreserved: preserveState && this.stateSnapshot !== null,
1871
+ compiledCode: compiledParts.join("\n\n"),
1872
+ changes: diffResult
1873
+ };
1874
+ }
1875
+ /**
1876
+ * Reset compiler state
1877
+ */
1878
+ reset() {
1879
+ this.cache.clear();
1880
+ this.previousAST = null;
1881
+ this.stateSnapshot = null;
1882
+ this.dependencyGraph.clear();
1883
+ }
1884
+ /**
1885
+ * Get cache statistics including trait graph info
1886
+ */
1887
+ async getStats() {
1888
+ let dependencyEdges = 0;
1889
+ for (const deps of this.dependencyGraph.values()) {
1890
+ dependencyEdges += deps.size;
1891
+ }
1892
+ const stats = {
1893
+ cacheSize: this.cache.size,
1894
+ objectsCached: Array.from(this.cache.keys()),
1895
+ dependencyEdges,
1896
+ traitGraphStats: this.traitGraph.getStats()
1897
+ };
1898
+ if (this.semanticCache) {
1899
+ const semanticStats = await this.semanticCache.getStats();
1900
+ return {
1901
+ ...stats,
1902
+ semanticCache: semanticStats
1903
+ };
1904
+ }
1905
+ return stats;
1906
+ }
1907
+ /**
1908
+ * Get semantic cache statistics
1909
+ */
1910
+ async getSemanticCacheStats() {
1911
+ if (!this.semanticCache) {
1912
+ return null;
1913
+ }
1914
+ return this.semanticCache.getStats();
1915
+ }
1916
+ /**
1917
+ * Clear semantic cache
1918
+ */
1919
+ async clearSemanticCache() {
1920
+ if (this.semanticCache) {
1921
+ await this.semanticCache.clear();
1922
+ }
1923
+ }
1924
+ /**
1925
+ * Close semantic cache connection
1926
+ */
1927
+ async closeSemanticCache() {
1928
+ if (this.semanticCache) {
1929
+ await this.semanticCache.close();
1930
+ }
1931
+ }
1932
+ /**
1933
+ * Serialize compiler state for persistence
1934
+ * Includes cache, dependency graph, and trait graph
1935
+ */
1936
+ serialize() {
1937
+ const data = {
1938
+ version: 1,
1939
+ entries: Array.from(this.cache.entries()).map(([name, entry]) => ({
1940
+ name,
1941
+ entry
1942
+ })),
1943
+ dependencies: Array.from(this.dependencyGraph.entries()).map(([name, deps]) => ({
1944
+ name,
1945
+ deps: Array.from(deps)
1946
+ })),
1947
+ traitGraph: this.traitGraph.serialize(),
1948
+ timestamp: Date.now()
1949
+ };
1950
+ return JSON.stringify(data);
1951
+ }
1952
+ /**
1953
+ * Restore compiler state from serialized data
1954
+ */
1955
+ static deserialize(json) {
1956
+ const data = chunkE7JP3BS3_cjs.readJson(json);
1957
+ if (data.version !== 1) {
1958
+ throw new Error(`Unsupported cache version: ${data.version}`);
1959
+ }
1960
+ const traitGraph = TraitDependencyGraph.deserialize(data.traitGraph);
1961
+ const compiler = new _IncrementalCompiler(traitGraph);
1962
+ for (const { name, entry } of data.entries) {
1963
+ compiler.cache.set(name, entry);
1964
+ }
1965
+ for (const { name, deps } of data.dependencies) {
1966
+ compiler.dependencyGraph.set(name, new Set(deps));
1967
+ }
1968
+ return compiler;
1969
+ }
1970
+ };
1971
+ function createIncrementalCompiler() {
1972
+ return new IncrementalCompiler();
1973
+ }
1974
+ function serializeCache(compiler) {
1975
+ compiler.getStats();
1976
+ const data = {
1977
+ version: 1,
1978
+ entries: [],
1979
+ dependencies: [],
1980
+ traitGraph: compiler.getTraitGraph().serialize(),
1981
+ timestamp: Date.now()
1982
+ };
1983
+ return JSON.stringify(data);
1984
+ }
1985
+ function deserializeCache(json) {
1986
+ const data = chunkE7JP3BS3_cjs.readJson(json);
1987
+ if (data.version !== 1) {
1988
+ throw new Error(`Unsupported cache version: ${data.version}`);
1989
+ }
1990
+ const traitGraph = TraitDependencyGraph.deserialize(data.traitGraph);
1991
+ const compiler = new IncrementalCompiler(traitGraph);
1992
+ for (const { name, entry } of data.entries) {
1993
+ compiler.setCached(name, entry.hash, entry.compiledCode, entry.dependencies);
1994
+ }
1995
+ for (const { name, deps } of data.dependencies) {
1996
+ compiler.updateDependencies(name, deps);
1997
+ }
1998
+ return compiler;
1999
+ }
2000
+ var UnauthorizedIncrementalCompilerAccessError = class extends chunkKKP7JKN4_cjs.UnauthorizedCompilerAccessError {
2001
+ constructor(decision, compilerName) {
2002
+ super(decision, "incremental compilation", compilerName);
2003
+ this.name = "UnauthorizedIncrementalCompilerAccessError";
2004
+ }
2005
+ };
2006
+
2007
+ exports.IncrementalCompiler = IncrementalCompiler;
2008
+ exports.TraitDependencyGraph = TraitDependencyGraph;
2009
+ exports.UnauthorizedIncrementalCompilerAccessError = UnauthorizedIncrementalCompilerAccessError;
2010
+ exports.createIncrementalCompiler = createIncrementalCompiler;
2011
+ exports.deserializeCache = deserializeCache;
2012
+ exports.globalTraitGraph = globalTraitGraph;
2013
+ exports.serializeCache = serializeCache;
2014
+ //# sourceMappingURL=chunk-4V2E7U7Q.cjs.map
2015
+ //# sourceMappingURL=chunk-4V2E7U7Q.cjs.map