@holoscript/core 6.0.3 → 7.0.0

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