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