@holoscript/core 6.0.4 → 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 (236) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -1
  3. package/dist/compiler/index.d.ts +82 -0
  4. package/dist/constants.d.ts +3 -2
  5. package/dist/coordinators/index.d.ts +189 -0
  6. package/dist/index.d.ts +501 -19
  7. package/dist/paper-0c-spike/index.d.ts +29 -0
  8. package/dist/reconstruction/index.d.ts +78 -0
  9. package/dist/tools/index.d.ts +22 -1
  10. package/dist/traitDocs/traitDocs.d.ts +69 -0
  11. package/dist/traits/index.d.ts +61 -0
  12. package/package.json +105 -57
  13. package/dist/GLTFPipeline-DEN36VNK.js +0 -12
  14. package/dist/GLTFPipeline-YPCAK236.cjs +0 -33
  15. package/dist/HoloScriptPlusParser-BN6KVRCM.js +0 -692
  16. package/dist/HoloScriptPlusParser-NC5FE6AL.cjs +0 -697
  17. package/dist/USDZExporter-NTMBNTDB.js +0 -707
  18. package/dist/USDZExporter-UWGWNMMD.cjs +0 -709
  19. package/dist/chunk-27LWW5FU.cjs +0 -410
  20. package/dist/chunk-2CWOLHTE.js +0 -69
  21. package/dist/chunk-33LSUQDD.cjs +0 -835
  22. package/dist/chunk-3FJCK5XA.js +0 -2232
  23. package/dist/chunk-3FXV5S25.cjs +0 -633
  24. package/dist/chunk-3FYZOR7S.cjs +0 -69
  25. package/dist/chunk-3SAK5KFL.cjs +0 -83
  26. package/dist/chunk-4XSNJCLC.cjs +0 -1859
  27. package/dist/chunk-54FHG2MX.js +0 -655
  28. package/dist/chunk-56IF4NTA.js +0 -56
  29. package/dist/chunk-5BGSECRJ.cjs +0 -2237
  30. package/dist/chunk-5GLCTO44.js +0 -161
  31. package/dist/chunk-5O6TQC6M.cjs +0 -1871
  32. package/dist/chunk-5OEOHAAW.cjs +0 -682
  33. package/dist/chunk-5TOFIR6L.js +0 -407
  34. package/dist/chunk-5WUNN6ZN.cjs +0 -428
  35. package/dist/chunk-6TZPZCOJ.cjs +0 -1404
  36. package/dist/chunk-6UEHYZ7V.cjs +0 -773
  37. package/dist/chunk-6XSERL6L.js +0 -5678
  38. package/dist/chunk-72EQECGT.cjs +0 -908
  39. package/dist/chunk-7AGYRWKW.cjs +0 -507
  40. package/dist/chunk-7LCYLPW2.cjs +0 -663
  41. package/dist/chunk-A7PIMZGU.js +0 -263
  42. package/dist/chunk-ATSKSYVE.cjs +0 -51683
  43. package/dist/chunk-B5TCIAPQ.cjs +0 -117
  44. package/dist/chunk-BF2235SI.cjs +0 -5714
  45. package/dist/chunk-BKIGPPVM.js +0 -629
  46. package/dist/chunk-BND3ST2K.cjs +0 -662
  47. package/dist/chunk-BU7VWW2K.js +0 -2522
  48. package/dist/chunk-BWFJEM5A.js +0 -5419
  49. package/dist/chunk-CAUCGUEA.cjs +0 -130
  50. package/dist/chunk-CBJSLA2E.cjs +0 -5423
  51. package/dist/chunk-CDPGV4DN.js +0 -114
  52. package/dist/chunk-CLYEIWA5.cjs +0 -408
  53. package/dist/chunk-CS2EMTGF.js +0 -1966
  54. package/dist/chunk-DMG7C4H2.js +0 -975
  55. package/dist/chunk-DXJQDCFL.js +0 -468
  56. package/dist/chunk-E3FWRT3Z.js +0 -608
  57. package/dist/chunk-E3UALNFA.js +0 -421
  58. package/dist/chunk-EONILVMF.js +0 -762
  59. package/dist/chunk-EQV4R3EV.cjs +0 -769
  60. package/dist/chunk-F3HH56EB.cjs +0 -5538
  61. package/dist/chunk-F4IULT7N.js +0 -1488
  62. package/dist/chunk-FF3Q7ADR.js +0 -380
  63. package/dist/chunk-FFKU7BTK.cjs +0 -1046
  64. package/dist/chunk-FHQVYCH2.js +0 -70
  65. package/dist/chunk-FSF7EQVA.cjs +0 -1974
  66. package/dist/chunk-G4VZTCIB.js +0 -659
  67. package/dist/chunk-G7CT3EMP.cjs +0 -1002
  68. package/dist/chunk-GGHSW2NN.js +0 -51334
  69. package/dist/chunk-GVUR45UF.cjs +0 -777
  70. package/dist/chunk-H5Z7NASB.js +0 -9662
  71. package/dist/chunk-HE7ULERA.cjs +0 -697
  72. package/dist/chunk-HJJLD366.js +0 -1169
  73. package/dist/chunk-HPS76H7Q.js +0 -309
  74. package/dist/chunk-HQUEA5R6.cjs +0 -424
  75. package/dist/chunk-HYNTS5CP.js +0 -422
  76. package/dist/chunk-I6XZ5DZF.cjs +0 -488
  77. package/dist/chunk-IBDG74G2.cjs +0 -1219
  78. package/dist/chunk-IFNQFCTM.js +0 -3098
  79. package/dist/chunk-IHOUYQIA.js +0 -406
  80. package/dist/chunk-ILRBGFVD.cjs +0 -72
  81. package/dist/chunk-IWI6J7FX.js +0 -421
  82. package/dist/chunk-K3JDKWGI.cjs +0 -270
  83. package/dist/chunk-K6EKD26I.js +0 -630
  84. package/dist/chunk-KCQ5NDYC.cjs +0 -3172
  85. package/dist/chunk-KED34ILP.js +0 -832
  86. package/dist/chunk-KSGXLT74.cjs +0 -457
  87. package/dist/chunk-L4G4RLXX.js +0 -767
  88. package/dist/chunk-LDP5OK6G.js +0 -1216
  89. package/dist/chunk-LGGRPKTV.cjs +0 -735
  90. package/dist/chunk-LK5IAVH6.cjs +0 -1173
  91. package/dist/chunk-LSW7P7ML.js +0 -3675
  92. package/dist/chunk-LXJ4667L.cjs +0 -3874
  93. package/dist/chunk-LZ266PCM.cjs +0 -4499
  94. package/dist/chunk-MD6KDHVE.cjs +0 -237
  95. package/dist/chunk-MEASWI2Y.js +0 -126
  96. package/dist/chunk-MPXBVFHQ.js +0 -768
  97. package/dist/chunk-N5FTS757.cjs +0 -415
  98. package/dist/chunk-NCUKG4SK.cjs +0 -3075
  99. package/dist/chunk-NDQNIJEH.js +0 -1715
  100. package/dist/chunk-NOZZ46QU.js +0 -168
  101. package/dist/chunk-OFKWH2IP.js +0 -449
  102. package/dist/chunk-PHENW4MQ.js +0 -65
  103. package/dist/chunk-PMGODDJA.cjs +0 -319
  104. package/dist/chunk-Q4QX3AET.cjs +0 -1505
  105. package/dist/chunk-Q56TT7IL.js +0 -483
  106. package/dist/chunk-Q5JT3YML.cjs +0 -129
  107. package/dist/chunk-Q5SJOGHQ.cjs +0 -4256
  108. package/dist/chunk-QGKNANZ3.js +0 -3071
  109. package/dist/chunk-QLEAOI3Q.cjs +0 -424
  110. package/dist/chunk-R7MA7QWV.js +0 -732
  111. package/dist/chunk-RVYPEYPX.js +0 -678
  112. package/dist/chunk-S2N5TNMA.js +0 -1855
  113. package/dist/chunk-S565K7NK.js +0 -752
  114. package/dist/chunk-SDAMZIRE.js +0 -765
  115. package/dist/chunk-T36DDXSF.js +0 -4250
  116. package/dist/chunk-T4NKMBDL.js +0 -5474
  117. package/dist/chunk-T7LEXZUZ.cjs +0 -2526
  118. package/dist/chunk-TEWCN33Y.js +0 -694
  119. package/dist/chunk-TQSZUOW5.cjs +0 -793
  120. package/dist/chunk-TSH3MSQU.cjs +0 -129
  121. package/dist/chunk-UERJ3YJV.js +0 -504
  122. package/dist/chunk-UPJBDCVF.js +0 -1395
  123. package/dist/chunk-V3NN3HPP.js +0 -4462
  124. package/dist/chunk-VJ3L7CHT.cjs +0 -169
  125. package/dist/chunk-WB4Z63GG.js +0 -229
  126. package/dist/chunk-WDW67DZB.cjs +0 -9728
  127. package/dist/chunk-WGMEAYBG.js +0 -126
  128. package/dist/chunk-X4ZF6CNE.cjs +0 -473
  129. package/dist/chunk-X6SEAXAX.cjs +0 -3681
  130. package/dist/chunk-XCWFGZAA.js +0 -1043
  131. package/dist/chunk-XD6IYDUX.js +0 -903
  132. package/dist/chunk-XG23EUQX.cjs +0 -1717
  133. package/dist/chunk-XRKWN5PL.cjs +0 -173
  134. package/dist/chunk-XUILI4KB.cjs +0 -430
  135. package/dist/chunk-XUTX5CBW.js +0 -126
  136. package/dist/chunk-XWPNTWDN.cjs +0 -755
  137. package/dist/chunk-XXINBTZK.cjs +0 -633
  138. package/dist/chunk-YCXFCXDS.js +0 -1868
  139. package/dist/chunk-YQK5JNFK.js +0 -3725
  140. package/dist/chunk-YYXH45E2.js +0 -426
  141. package/dist/chunk-Z34RLXRA.cjs +0 -612
  142. package/dist/chunk-ZP4D3CSX.cjs +0 -72
  143. package/dist/cli/holoscript-runner.cjs +0 -2259
  144. package/dist/cli/holoscript-runner.js +0 -2234
  145. package/dist/codebase/index.cjs +0 -336
  146. package/dist/codebase/index.js +0 -331
  147. package/dist/compiler/agent-inference.cjs +0 -28
  148. package/dist/compiler/agent-inference.js +0 -5
  149. package/dist/compiler/android-xr.cjs +0 -19
  150. package/dist/compiler/android-xr.js +0 -9
  151. package/dist/compiler/android.cjs +0 -20
  152. package/dist/compiler/android.js +0 -10
  153. package/dist/compiler/ar.cjs +0 -20
  154. package/dist/compiler/ar.js +0 -8
  155. package/dist/compiler/babylon.cjs +0 -17
  156. package/dist/compiler/babylon.js +0 -11
  157. package/dist/compiler/coco.cjs +0 -27
  158. package/dist/compiler/coco.js +0 -4
  159. package/dist/compiler/domain-block-utils.cjs +0 -602
  160. package/dist/compiler/domain-block-utils.js +0 -8
  161. package/dist/compiler/dtdl.cjs +0 -24
  162. package/dist/compiler/dtdl.js +0 -8
  163. package/dist/compiler/gltf-pipeline.cjs +0 -39
  164. package/dist/compiler/gltf-pipeline.js +0 -4
  165. package/dist/compiler/godot.cjs +0 -15
  166. package/dist/compiler/godot.js +0 -9
  167. package/dist/compiler/incremental.cjs +0 -29
  168. package/dist/compiler/incremental.js +0 -4
  169. package/dist/compiler/index.cjs +0 -2578
  170. package/dist/compiler/index.js +0 -2383
  171. package/dist/compiler/ios.cjs +0 -20
  172. package/dist/compiler/ios.js +0 -10
  173. package/dist/compiler/multi-layer.cjs +0 -20
  174. package/dist/compiler/multi-layer.js +0 -11
  175. package/dist/compiler/nodetoy.cjs +0 -23
  176. package/dist/compiler/nodetoy.js +0 -4
  177. package/dist/compiler/openxr.cjs +0 -15
  178. package/dist/compiler/openxr.js +0 -9
  179. package/dist/compiler/playcanvas.cjs +0 -16
  180. package/dist/compiler/playcanvas.js +0 -10
  181. package/dist/compiler/r3f.cjs +0 -34
  182. package/dist/compiler/r3f.js +0 -12
  183. package/dist/compiler/remotion.cjs +0 -23
  184. package/dist/compiler/remotion.js +0 -4
  185. package/dist/compiler/reproducibility.cjs +0 -39
  186. package/dist/compiler/reproducibility.js +0 -4
  187. package/dist/compiler/sdf.cjs +0 -21
  188. package/dist/compiler/sdf.js +0 -9
  189. package/dist/compiler/semantic-scene.cjs +0 -31
  190. package/dist/compiler/semantic-scene.js +0 -4
  191. package/dist/compiler/state.cjs +0 -17
  192. package/dist/compiler/state.js +0 -7
  193. package/dist/compiler/trait-composition.cjs +0 -26
  194. package/dist/compiler/trait-composition.js +0 -5
  195. package/dist/compiler/unity.cjs +0 -15
  196. package/dist/compiler/unity.js +0 -9
  197. package/dist/compiler/unreal.cjs +0 -19
  198. package/dist/compiler/unreal.js +0 -9
  199. package/dist/compiler/urdf.cjs +0 -45
  200. package/dist/compiler/urdf.js +0 -9
  201. package/dist/compiler/usd-physics.cjs +0 -23
  202. package/dist/compiler/usd-physics.js +0 -6
  203. package/dist/compiler/visionos.cjs +0 -15
  204. package/dist/compiler/visionos.js +0 -9
  205. package/dist/compiler/vrchat.cjs +0 -19
  206. package/dist/compiler/vrchat.js +0 -9
  207. package/dist/compiler/vrr.cjs +0 -21
  208. package/dist/compiler/vrr.js +0 -9
  209. package/dist/compiler/wasm.cjs +0 -33
  210. package/dist/compiler/wasm.js +0 -9
  211. package/dist/compiler/webgpu.cjs +0 -15
  212. package/dist/compiler/webgpu.js +0 -9
  213. package/dist/debugger.cjs +0 -21
  214. package/dist/debugger.js +0 -8
  215. package/dist/entries/interop.cjs +0 -62
  216. package/dist/entries/interop.js +0 -5
  217. package/dist/entries/scripting.cjs +0 -68
  218. package/dist/entries/scripting.js +0 -11
  219. package/dist/index.cjs +0 -40921
  220. package/dist/index.js +0 -37763
  221. package/dist/math/vec3.cjs +0 -57
  222. package/dist/math/vec3.js +0 -4
  223. package/dist/ml-dsa-PHCWUBPX.cjs +0 -1178
  224. package/dist/ml-dsa-WYLJHJO6.js +0 -1178
  225. package/dist/parser.cjs +0 -27
  226. package/dist/parser.js +0 -10
  227. package/dist/playwright-5OSAPTNH.js +0 -98660
  228. package/dist/playwright-RL6GY4F7.cjs +0 -98673
  229. package/dist/runtime.cjs +0 -16
  230. package/dist/runtime.js +0 -7
  231. package/dist/storage/index.cjs +0 -37
  232. package/dist/storage/index.js +0 -4
  233. package/dist/traits/index.cjs +0 -14649
  234. package/dist/traits/index.js +0 -12243
  235. package/dist/type-checker.cjs +0 -18
  236. package/dist/type-checker.js +0 -5
@@ -1,1966 +0,0 @@
1
- import { createHash } from 'crypto';
2
- import { getRBAC, WorkflowStep, ResourceType } from '@holoscript/platform';
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 pkgName = "@loro/loro";
787
- const { LoroDoc } = await import(
788
- /* @vite-ignore */
789
- pkgName
790
- );
791
- const crdtPath = path.resolve(process.cwd(), ".holomesh/worldstate.crdt");
792
- const bytes = await fs.readFile(crdtPath);
793
- const doc = new LoroDoc();
794
- doc.import(bytes);
795
- const feed = doc.getText("feed");
796
- return feed.toString();
797
- } catch (e) {
798
- throw new Error(`CRDT Sync Error: ${e instanceof Error ? e.message : String(e)}`);
799
- }
800
- }
801
- /**
802
- * Fetch source code from the community registry for @username/name imports.
803
- * Calls GET {registryBaseUrl}/api/scene/{name} and returns the scene code.
804
- */
805
- async _fetchRegistrySource(importPath, registryBaseUrl) {
806
- const parsed = parseRegistryImport(importPath);
807
- if (!parsed) {
808
- throw new Error(`Invalid registry import path: '${importPath}'`);
809
- }
810
- const url = `${registryBaseUrl.replace(/\/$/, "")}/api/registry/${encodeURIComponent(parsed.username)}/${encodeURIComponent(parsed.name)}`;
811
- const response = await fetch(url);
812
- if (!response.ok) {
813
- throw new Error(`Registry returned ${response.status} for '${importPath}'`);
814
- }
815
- const data = await response.json();
816
- if (!data.code || typeof data.code !== "string") {
817
- throw new Error(`Registry returned no code for '${importPath}'`);
818
- }
819
- return data.code;
820
- }
821
- /**
822
- * Extract @exported nodes from a parse result.
823
- *
824
- * Handles two AST shapes that HoloScriptPlusParser can produce:
825
- * 1. Single node file: result.ast.root IS the node; its directives contain @export
826
- * 2. Fragment file: result.ast.root.children[] are nodes, each may have @export directives
827
- */
828
- _extractExports(result) {
829
- const exports$1 = /* @__PURE__ */ new Map();
830
- const ast = result.ast;
831
- if (!ast) return exports$1;
832
- const root = ast.root;
833
- if (!root) return exports$1;
834
- const seen = /* @__PURE__ */ new Set();
835
- const nodesToCheck = [];
836
- const addNode = (n) => {
837
- if (!n || typeof n !== "object") return;
838
- const node = n;
839
- if (!seen.has(node)) {
840
- seen.add(node);
841
- nodesToCheck.push(node);
842
- }
843
- };
844
- addNode(root);
845
- if (Array.isArray(root.children)) {
846
- for (const child of root.children) addNode(child);
847
- }
848
- if (Array.isArray(ast.body)) {
849
- for (const n of ast.body) addNode(n);
850
- }
851
- if (Array.isArray(ast.children)) {
852
- for (const n of ast.children) addNode(n);
853
- }
854
- for (const node of nodesToCheck) {
855
- const nodeRec = node;
856
- const directives = nodeRec.directives ?? [];
857
- const exportDir = directives.find((d) => d?.type === "export");
858
- if (exportDir) {
859
- const exportName = exportDir.exportName ?? nodeRec.id ?? nodeRec.name ?? nodeRec.type;
860
- exports$1.set(exportName, node);
861
- }
862
- }
863
- return exports$1;
864
- }
865
- /**
866
- * Default Node.js file reader. Only used on server-side / CLI.
867
- * Throws in environments without the 'fs' module (browser, XR).
868
- */
869
- _defaultReader() {
870
- return async (filePath) => {
871
- try {
872
- const fs = await import('fs/promises');
873
- return await fs.readFile(filePath, "utf-8");
874
- } catch {
875
- throw new Error(
876
- `Cannot read '${filePath}': no readFile option provided and fs is unavailable`
877
- );
878
- }
879
- };
880
- }
881
- /** Clear the module cache (useful between test runs) */
882
- clearCache() {
883
- this.cache.clear();
884
- this.inProgress.clear();
885
- }
886
- /** Return the set of canonical paths currently cached */
887
- getCachedPaths() {
888
- return [...this.cache.keys()];
889
- }
890
- /** Return a resolved module from cache, or undefined */
891
- getCached(canonicalPath) {
892
- return this.cache.get(canonicalPath);
893
- }
894
- };
895
- function hashSourceCode(source) {
896
- return createHash("sha256").update(source, "utf8").digest("hex");
897
- }
898
- function generateCacheKey(contentHash, type, prefix) {
899
- return `${prefix}:${type}:${contentHash}`;
900
- }
901
- function serializeASTNode(node) {
902
- return JSON.stringify(node, null, 0);
903
- }
904
- function hashASTSubtree(node) {
905
- const serialized = serializeASTNode(node);
906
- return hashSourceCode(serialized);
907
- }
908
- var SemanticCache = class {
909
- constructor(options = {}) {
910
- this.redis = null;
911
- this.memoryCache = /* @__PURE__ */ new Map();
912
- this.stats = {
913
- hits: 0,
914
- misses: 0,
915
- totalLatencyMs: 0,
916
- lookupCount: 0
917
- };
918
- this.redisConnected = false;
919
- this.initialized = false;
920
- this.options = {
921
- redisUrl: options.redisUrl ?? "redis://localhost:6379",
922
- keyPrefix: options.keyPrefix ?? "holoscript:semantic",
923
- ttl: options.ttl ?? 7 * 24 * 60 * 60,
924
- // 7 days in seconds
925
- version: options.version ?? "1.0.0",
926
- debug: options.debug ?? false,
927
- connectionTimeout: options.connectionTimeout ?? 5e3,
928
- maxRetries: options.maxRetries ?? 3
929
- };
930
- }
931
- /**
932
- * Initialize the cache (connect to Redis if available)
933
- */
934
- async initialize() {
935
- if (this.initialized) return;
936
- try {
937
- const Redis = await this.loadRedisClient();
938
- if (Redis) {
939
- this.redis = new Redis(this.options.redisUrl, {
940
- connectTimeout: this.options.connectionTimeout,
941
- maxRetriesPerRequest: this.options.maxRetries,
942
- lazyConnect: true,
943
- enableOfflineQueue: false
944
- });
945
- this.redis.on("connect", () => {
946
- this.redisConnected = true;
947
- this.log("Redis connected");
948
- });
949
- this.redis.on("error", (error) => {
950
- this.log(`Redis error: ${error.message}`);
951
- this.redisConnected = false;
952
- });
953
- this.redis.on("close", () => {
954
- this.redisConnected = false;
955
- this.log("Redis disconnected");
956
- });
957
- await this.redis.ping();
958
- this.redisConnected = true;
959
- this.log("Redis cache initialized");
960
- }
961
- } catch (error) {
962
- this.log(`Redis initialization failed: ${error}. Falling back to in-memory cache.`);
963
- this.redis = null;
964
- this.redisConnected = false;
965
- }
966
- this.initialized = true;
967
- this.log(`Semantic cache initialized (backend: ${this.getBackend()})`);
968
- }
969
- /**
970
- * Load Redis client dynamically (optional dependency)
971
- */
972
- async loadRedisClient() {
973
- try {
974
- const ioredis = await import('ioredis');
975
- return ioredis.default;
976
- } catch (error) {
977
- this.log("ioredis not installed, using in-memory cache");
978
- return null;
979
- }
980
- }
981
- /**
982
- * Get cache entry
983
- */
984
- async get(contentHash, type) {
985
- if (!this.initialized) {
986
- await this.initialize();
987
- }
988
- const startTime = Date.now();
989
- const key = generateCacheKey(contentHash, type, this.options.keyPrefix);
990
- try {
991
- let entry = null;
992
- if (this.redis && this.redisConnected) {
993
- const raw = await this.redis.get(key);
994
- if (raw) {
995
- entry = JSON.parse(raw);
996
- }
997
- } else {
998
- const memEntry = this.memoryCache.get(key);
999
- if (memEntry) {
1000
- entry = memEntry;
1001
- }
1002
- }
1003
- const latencyMs = Date.now() - startTime;
1004
- this.stats.totalLatencyMs += latencyMs;
1005
- this.stats.lookupCount++;
1006
- if (!entry) {
1007
- this.stats.misses++;
1008
- return {
1009
- hit: false,
1010
- reason: "not_found",
1011
- latencyMs
1012
- };
1013
- }
1014
- if (entry.version !== this.options.version) {
1015
- this.stats.misses++;
1016
- await this.delete(contentHash, type);
1017
- return {
1018
- hit: false,
1019
- reason: "version_mismatch",
1020
- latencyMs
1021
- };
1022
- }
1023
- if (!this.redis) {
1024
- const age = Date.now() - entry.createdAt;
1025
- const ttlMs = this.options.ttl * 1e3;
1026
- if (age > ttlMs) {
1027
- this.stats.misses++;
1028
- this.memoryCache.delete(key);
1029
- return {
1030
- hit: false,
1031
- reason: "expired",
1032
- latencyMs
1033
- };
1034
- }
1035
- }
1036
- entry.accessedAt = Date.now();
1037
- entry.accessCount++;
1038
- if (this.redis && this.redisConnected) {
1039
- await this.redis.set(key, JSON.stringify(entry), "EX", this.options.ttl);
1040
- } else {
1041
- this.memoryCache.set(key, entry);
1042
- }
1043
- this.stats.hits++;
1044
- this.log(`Cache HIT: ${type} (${contentHash.slice(0, 8)}...) [${latencyMs}ms]`);
1045
- return {
1046
- hit: true,
1047
- entry,
1048
- latencyMs
1049
- };
1050
- } catch (error) {
1051
- this.stats.misses++;
1052
- this.log(`Cache lookup error: ${error}`);
1053
- return {
1054
- hit: false,
1055
- reason: "redis_error",
1056
- latencyMs: Date.now() - startTime
1057
- };
1058
- }
1059
- }
1060
- /**
1061
- * Set cache entry
1062
- */
1063
- async set(contentHash, type, data, options) {
1064
- if (!this.initialized) {
1065
- await this.initialize();
1066
- }
1067
- const key = generateCacheKey(contentHash, type, this.options.keyPrefix);
1068
- const serialized = JSON.stringify(data);
1069
- const entry = {
1070
- contentHash,
1071
- type,
1072
- data,
1073
- sourcePath: options?.sourcePath,
1074
- dependencies: options?.dependencies,
1075
- createdAt: Date.now(),
1076
- accessedAt: Date.now(),
1077
- accessCount: 0,
1078
- size: serialized.length,
1079
- version: this.options.version
1080
- };
1081
- try {
1082
- if (this.redis && this.redisConnected) {
1083
- await this.redis.set(key, JSON.stringify(entry), "EX", this.options.ttl);
1084
- } else {
1085
- this.memoryCache.set(key, entry);
1086
- }
1087
- this.log(`Cache SET: ${type} (${contentHash.slice(0, 8)}...) [${entry.size} bytes]`);
1088
- } catch (error) {
1089
- this.log(`Cache set error: ${error}`);
1090
- }
1091
- }
1092
- /**
1093
- * Delete cache entry
1094
- */
1095
- async delete(contentHash, type) {
1096
- if (!this.initialized) {
1097
- await this.initialize();
1098
- }
1099
- const key = generateCacheKey(contentHash, type, this.options.keyPrefix);
1100
- try {
1101
- if (this.redis && this.redisConnected) {
1102
- await this.redis.del(key);
1103
- } else {
1104
- this.memoryCache.delete(key);
1105
- }
1106
- this.log(`Cache DELETE: ${type} (${contentHash.slice(0, 8)}...)`);
1107
- } catch (error) {
1108
- this.log(`Cache delete error: ${error}`);
1109
- }
1110
- }
1111
- /**
1112
- * Invalidate all cache entries for a type
1113
- */
1114
- async invalidateType(type) {
1115
- if (!this.initialized) {
1116
- await this.initialize();
1117
- }
1118
- let count = 0;
1119
- try {
1120
- if (this.redis && this.redisConnected) {
1121
- const pattern = `${this.options.keyPrefix}:${type}:*`;
1122
- const keys = await this.redis.keys(pattern);
1123
- for (const key of keys) {
1124
- await this.redis.del(key);
1125
- count++;
1126
- }
1127
- } else {
1128
- for (const [key, entry] of this.memoryCache.entries()) {
1129
- if (entry.type === type) {
1130
- this.memoryCache.delete(key);
1131
- count++;
1132
- }
1133
- }
1134
- }
1135
- this.log(`Invalidated ${count} entries of type: ${type}`);
1136
- } catch (error) {
1137
- this.log(`Cache invalidation error: ${error}`);
1138
- }
1139
- return count;
1140
- }
1141
- /**
1142
- * Clear all cache entries
1143
- */
1144
- async clear() {
1145
- if (!this.initialized) {
1146
- await this.initialize();
1147
- }
1148
- try {
1149
- if (this.redis && this.redisConnected) {
1150
- const pattern = `${this.options.keyPrefix}:*`;
1151
- const keys = await this.redis.keys(pattern);
1152
- for (const key of keys) {
1153
- await this.redis.del(key);
1154
- }
1155
- } else {
1156
- this.memoryCache.clear();
1157
- }
1158
- this.stats.hits = 0;
1159
- this.stats.misses = 0;
1160
- this.stats.totalLatencyMs = 0;
1161
- this.stats.lookupCount = 0;
1162
- this.log("Cache cleared");
1163
- } catch (error) {
1164
- this.log(`Cache clear error: ${error}`);
1165
- }
1166
- }
1167
- /**
1168
- * Get cache statistics
1169
- */
1170
- async getStats() {
1171
- const totalRequests = this.stats.hits + this.stats.misses;
1172
- const hitRate = totalRequests > 0 ? this.stats.hits / totalRequests : 0;
1173
- const avgLatencyMs = this.stats.lookupCount > 0 ? this.stats.totalLatencyMs / this.stats.lookupCount : 0;
1174
- let totalEntries = 0;
1175
- const entriesByType = {
1176
- "ast-subtree": 0,
1177
- "compiled-module": 0,
1178
- "compiled-object": 0,
1179
- "trait-composition": 0,
1180
- "import-resolution": 0
1181
- };
1182
- try {
1183
- if (this.redis && this.redisConnected) {
1184
- const pattern = `${this.options.keyPrefix}:*`;
1185
- const keys = await this.redis.keys(pattern);
1186
- totalEntries = keys.length;
1187
- for (const key of keys) {
1188
- const parts = key.split(":");
1189
- const type = parts[2];
1190
- if (type in entriesByType) {
1191
- entriesByType[type]++;
1192
- }
1193
- }
1194
- } else {
1195
- totalEntries = this.memoryCache.size;
1196
- for (const entry of this.memoryCache.values()) {
1197
- entriesByType[entry.type]++;
1198
- }
1199
- }
1200
- } catch (error) {
1201
- this.log(`Stats error: ${error}`);
1202
- }
1203
- return {
1204
- hits: this.stats.hits,
1205
- misses: this.stats.misses,
1206
- hitRate,
1207
- avgLatencyMs,
1208
- totalEntries,
1209
- backend: this.getBackend(),
1210
- redisConnected: this.redisConnected,
1211
- entriesByType
1212
- };
1213
- }
1214
- /**
1215
- * Get cache backend type
1216
- */
1217
- getBackend() {
1218
- return this.redis && this.redisConnected ? "redis" : "memory";
1219
- }
1220
- /**
1221
- * Close Redis connection
1222
- */
1223
- async close() {
1224
- if (this.redis) {
1225
- try {
1226
- await this.redis.quit();
1227
- this.log("Redis connection closed");
1228
- } catch (error) {
1229
- this.log(`Error closing Redis: ${error}`);
1230
- }
1231
- }
1232
- }
1233
- /**
1234
- * Debug logging
1235
- */
1236
- log(message) {
1237
- if (this.options.debug) {
1238
- console.log(`[SemanticCache] ${message}`);
1239
- }
1240
- }
1241
- };
1242
- function createSemanticCache(options) {
1243
- return new SemanticCache(options);
1244
- }
1245
- function hashContent(content) {
1246
- let hash = 0;
1247
- for (let i = 0; i < content.length; i++) {
1248
- const char = content.charCodeAt(i);
1249
- hash = (hash << 5) - hash + char;
1250
- hash = hash & hash;
1251
- }
1252
- return hash.toString(36);
1253
- }
1254
- function hashConfig2(config) {
1255
- const keys = Object.keys(config).sort();
1256
- const parts = [];
1257
- for (const key of keys) {
1258
- const value = config[key];
1259
- parts.push(`${key}:${JSON.stringify(value)}`);
1260
- }
1261
- const str = parts.join("|");
1262
- let hash = 5381;
1263
- for (let i = 0; i < str.length; i++) {
1264
- hash = (hash << 5) + hash ^ str.charCodeAt(i);
1265
- }
1266
- return (hash >>> 0).toString(36);
1267
- }
1268
- function serializeObject(obj) {
1269
- return JSON.stringify({
1270
- name: obj.name,
1271
- properties: obj.properties,
1272
- traits: obj.traits,
1273
- children: obj.children?.map(serializeObject),
1274
- logic: obj.logic
1275
- // logic might not be directly on HoloObjectDecl but used in diff
1276
- });
1277
- }
1278
- function serializeProperty(prop) {
1279
- return JSON.stringify({ key: prop.key, value: prop.value });
1280
- }
1281
- var IncrementalCompiler = class _IncrementalCompiler {
1282
- constructor(traitGraph, options) {
1283
- this.cache = /* @__PURE__ */ new Map();
1284
- this.previousAST = null;
1285
- this.stateSnapshot = null;
1286
- this.dependencyGraph = /* @__PURE__ */ new Map();
1287
- this.semanticCache = null;
1288
- this.traitGraph = traitGraph || globalTraitGraph;
1289
- if (options?.enableSemanticCache) {
1290
- this.semanticCache = createSemanticCache({
1291
- redisUrl: options.redisUrl,
1292
- ttl: options.cacheTTL,
1293
- debug: false
1294
- });
1295
- this.semanticCache.initialize().catch((err) => {
1296
- console.warn(`Semantic cache initialization failed: ${err}`);
1297
- this.semanticCache = null;
1298
- });
1299
- }
1300
- }
1301
- /**
1302
- * Diff two ASTs and return the changes
1303
- */
1304
- diff(oldAST, newAST) {
1305
- const changes = [];
1306
- const addedObjects = [];
1307
- const removedObjects = [];
1308
- const modifiedObjects = [];
1309
- const unchangedObjects = [];
1310
- if (!oldAST) {
1311
- const allObjects = this.collectObjectNames(newAST);
1312
- return {
1313
- hasChanges: true,
1314
- changes: allObjects.map((name) => ({
1315
- type: "added",
1316
- path: [name],
1317
- nodeName: name,
1318
- nodeType: "object",
1319
- newValue: this.findObject(newAST, name)
1320
- })),
1321
- addedObjects: allObjects,
1322
- removedObjects: [],
1323
- modifiedObjects: [],
1324
- unchangedObjects: []
1325
- };
1326
- }
1327
- const oldObjects = /* @__PURE__ */ new Map();
1328
- const newObjects = /* @__PURE__ */ new Map();
1329
- this.collectObjects(oldAST, oldObjects);
1330
- this.collectObjects(newAST, newObjects);
1331
- for (const [name, obj] of newObjects) {
1332
- if (!oldObjects.has(name)) {
1333
- addedObjects.push(name);
1334
- changes.push({
1335
- type: "added",
1336
- path: [name],
1337
- nodeName: name,
1338
- nodeType: "object",
1339
- newValue: obj
1340
- });
1341
- }
1342
- }
1343
- for (const [name, obj] of oldObjects) {
1344
- if (!newObjects.has(name)) {
1345
- removedObjects.push(name);
1346
- changes.push({
1347
- type: "removed",
1348
- path: [name],
1349
- nodeName: name,
1350
- nodeType: "object",
1351
- oldValue: obj
1352
- });
1353
- }
1354
- }
1355
- for (const [name, newObj] of newObjects) {
1356
- if (oldObjects.has(name)) {
1357
- const oldObj = oldObjects.get(name);
1358
- const objectChanges = this.diffObject(oldObj, newObj, [name]);
1359
- if (objectChanges.length > 0) {
1360
- modifiedObjects.push(name);
1361
- changes.push(...objectChanges);
1362
- } else {
1363
- unchangedObjects.push(name);
1364
- }
1365
- }
1366
- }
1367
- return {
1368
- hasChanges: changes.length > 0,
1369
- changes,
1370
- addedObjects,
1371
- removedObjects,
1372
- modifiedObjects,
1373
- unchangedObjects
1374
- };
1375
- }
1376
- /**
1377
- * Diff two objects and return property-level changes
1378
- */
1379
- diffObject(oldObj, newObj, path) {
1380
- const changes = [];
1381
- const oldProps = new Map(oldObj.properties?.map((p) => [p.key, p]) || []);
1382
- const newProps = new Map(newObj.properties?.map((p) => [p.key, p]) || []);
1383
- for (const [key, newProp] of newProps) {
1384
- if (!oldProps.has(key)) {
1385
- changes.push({
1386
- type: "added",
1387
- path: [...path, key],
1388
- nodeName: key,
1389
- nodeType: "property",
1390
- newValue: newProp.value
1391
- });
1392
- } else {
1393
- const oldProp = oldProps.get(key);
1394
- if (serializeProperty(oldProp) !== serializeProperty(newProp)) {
1395
- changes.push({
1396
- type: "modified",
1397
- path: [...path, key],
1398
- nodeName: key,
1399
- nodeType: "property",
1400
- oldValue: oldProp.value,
1401
- newValue: newProp.value
1402
- });
1403
- }
1404
- }
1405
- }
1406
- for (const key of oldProps.keys()) {
1407
- if (!newProps.has(key)) {
1408
- changes.push({
1409
- type: "removed",
1410
- path: [...path, key],
1411
- nodeName: key,
1412
- nodeType: "property",
1413
- oldValue: oldProps.get(key).value
1414
- });
1415
- }
1416
- }
1417
- const oldTraitUsages = this.extractTraitUsages(oldObj.traits || []);
1418
- const newTraitUsages = this.extractTraitUsages(newObj.traits || []);
1419
- const oldTraitMap = new Map(oldTraitUsages.map((t) => [t.name, t]));
1420
- const newTraitMap = new Map(newTraitUsages.map((t) => [t.name, t]));
1421
- for (const [name, newTrait] of newTraitMap) {
1422
- if (!oldTraitMap.has(name)) {
1423
- changes.push({
1424
- type: "added",
1425
- path: [...path, "@" + name],
1426
- nodeName: name,
1427
- nodeType: "trait",
1428
- newValue: newTrait
1429
- });
1430
- }
1431
- }
1432
- for (const [name, oldTrait] of oldTraitMap) {
1433
- if (!newTraitMap.has(name)) {
1434
- changes.push({
1435
- type: "removed",
1436
- path: [...path, "@" + name],
1437
- nodeName: name,
1438
- nodeType: "trait",
1439
- oldValue: oldTrait
1440
- });
1441
- }
1442
- }
1443
- for (const [name, newTrait] of newTraitMap) {
1444
- const oldTrait = oldTraitMap.get(name);
1445
- if (oldTrait && oldTrait.configHash !== newTrait.configHash) {
1446
- changes.push({
1447
- type: "modified",
1448
- path: [...path, "@" + name],
1449
- nodeName: name,
1450
- nodeType: "trait",
1451
- oldValue: oldTrait,
1452
- newValue: newTrait
1453
- });
1454
- }
1455
- }
1456
- if (JSON.stringify(oldObj.logic) !== JSON.stringify(newObj.logic)) {
1457
- changes.push({
1458
- type: "modified",
1459
- path: [...path, "logic"],
1460
- nodeName: "logic",
1461
- nodeType: "logic",
1462
- oldValue: oldObj.logic,
1463
- newValue: newObj.logic
1464
- });
1465
- }
1466
- const oldChildren = new Map((oldObj.children || []).map((c) => [c.name, c]));
1467
- const newChildren = new Map((newObj.children || []).map((c) => [c.name, c]));
1468
- for (const [name, newChild] of newChildren) {
1469
- if (!oldChildren.has(name)) {
1470
- changes.push({
1471
- type: "added",
1472
- path: [...path, name],
1473
- nodeName: name,
1474
- nodeType: "object",
1475
- newValue: newChild
1476
- });
1477
- } else {
1478
- const childChanges = this.diffObject(oldChildren.get(name), newChild, [...path, name]);
1479
- changes.push(...childChanges);
1480
- }
1481
- }
1482
- for (const name of oldChildren.keys()) {
1483
- if (!newChildren.has(name)) {
1484
- changes.push({
1485
- type: "removed",
1486
- path: [...path, name],
1487
- nodeName: name,
1488
- nodeType: "object",
1489
- oldValue: oldChildren.get(name)
1490
- });
1491
- }
1492
- }
1493
- return changes;
1494
- }
1495
- /**
1496
- * Extract trait usages with config hashes from trait array
1497
- * Handles both string traits and trait objects with config
1498
- */
1499
- extractTraitUsages(traits) {
1500
- return traits.map((t) => {
1501
- if (typeof t === "string") {
1502
- return {
1503
- name: t,
1504
- config: {},
1505
- configHash: hashConfig2({})
1506
- };
1507
- }
1508
- if (t && typeof t === "object") {
1509
- const traitObj = t;
1510
- if ("name" in traitObj) {
1511
- const name = String(traitObj.name);
1512
- const config = {};
1513
- for (const [key, value] of Object.entries(traitObj)) {
1514
- if (key !== "name") {
1515
- config[key] = value;
1516
- }
1517
- }
1518
- return {
1519
- name,
1520
- config,
1521
- configHash: hashConfig2(config)
1522
- };
1523
- }
1524
- const keys = Object.keys(traitObj);
1525
- if (keys.length === 1) {
1526
- const name = keys[0];
1527
- const config = traitObj[name] || {};
1528
- return {
1529
- name,
1530
- config: typeof config === "object" ? config : {},
1531
- configHash: hashConfig2(typeof config === "object" ? config : {})
1532
- };
1533
- }
1534
- }
1535
- return {
1536
- name: String(t),
1537
- config: {},
1538
- configHash: hashConfig2({})
1539
- };
1540
- });
1541
- }
1542
- /**
1543
- * Collect all object names from a composition
1544
- */
1545
- collectObjectNames(composition) {
1546
- const names = [];
1547
- const collectFromObject = (obj) => {
1548
- names.push(obj.name);
1549
- obj.children?.forEach(collectFromObject);
1550
- };
1551
- composition.objects?.forEach(collectFromObject);
1552
- composition.spatialGroups?.forEach((group) => {
1553
- names.push(group.name);
1554
- group.objects?.forEach(collectFromObject);
1555
- });
1556
- return names;
1557
- }
1558
- /**
1559
- * Collect all objects into a map
1560
- */
1561
- collectObjects(composition, map) {
1562
- const collectFromObject = (obj) => {
1563
- map.set(obj.name, obj);
1564
- obj.children?.forEach(collectFromObject);
1565
- };
1566
- composition.objects?.forEach(collectFromObject);
1567
- composition.spatialGroups?.forEach((group) => {
1568
- group.objects?.forEach(collectFromObject);
1569
- });
1570
- }
1571
- /**
1572
- * Find an object by name in a composition
1573
- */
1574
- findObject(composition, name) {
1575
- const searchInObject = (obj) => {
1576
- if (obj.name === name) return obj;
1577
- for (const child of obj.children || []) {
1578
- const found = searchInObject(child);
1579
- if (found) return found;
1580
- }
1581
- return void 0;
1582
- };
1583
- for (const obj of composition.objects || []) {
1584
- const found = searchInObject(obj);
1585
- if (found) return found;
1586
- }
1587
- for (const group of composition.spatialGroups || []) {
1588
- for (const obj of group.objects || []) {
1589
- const found = searchInObject(obj);
1590
- if (found) return found;
1591
- }
1592
- }
1593
- return void 0;
1594
- }
1595
- /**
1596
- * Get cached compilation for an object if still valid
1597
- */
1598
- getCached(objectName, currentHash) {
1599
- const entry = this.cache.get(objectName);
1600
- if (entry && entry.hash === currentHash) {
1601
- return entry;
1602
- }
1603
- return null;
1604
- }
1605
- /**
1606
- * Store compilation result in cache
1607
- */
1608
- setCached(objectName, hash, compiledCode, dependencies) {
1609
- this.cache.set(objectName, {
1610
- hash,
1611
- compiledCode,
1612
- dependencies,
1613
- timestamp: Date.now()
1614
- });
1615
- }
1616
- /**
1617
- * Save current state for hot reload
1618
- */
1619
- saveState(states) {
1620
- this.stateSnapshot = {
1621
- objectStates: new Map(states),
1622
- timestamp: Date.now()
1623
- };
1624
- }
1625
- /**
1626
- * Restore state after hot reload
1627
- */
1628
- restoreState() {
1629
- return this.stateSnapshot;
1630
- }
1631
- /**
1632
- * Clear state snapshot
1633
- */
1634
- clearState() {
1635
- this.stateSnapshot = null;
1636
- }
1637
- /**
1638
- * Update dependency graph
1639
- */
1640
- updateDependencies(objectName, dependencies) {
1641
- this.dependencyGraph.set(objectName, new Set(dependencies));
1642
- }
1643
- /**
1644
- * Get objects that depend on a given object
1645
- */
1646
- getDependents(objectName) {
1647
- const dependents = [];
1648
- for (const [name, deps] of this.dependencyGraph) {
1649
- if (deps.has(objectName)) {
1650
- dependents.push(name);
1651
- }
1652
- }
1653
- return dependents;
1654
- }
1655
- /**
1656
- * Get all objects that need recompilation due to a change
1657
- * Enhanced with trait-aware dependency tracking
1658
- */
1659
- getRecompilationSet(changedObjects) {
1660
- const toRecompile = new Set(changedObjects);
1661
- const queue = [...changedObjects];
1662
- while (queue.length > 0) {
1663
- const current = queue.shift();
1664
- const dependents = this.getDependents(current);
1665
- for (const dep of dependents) {
1666
- if (!toRecompile.has(dep)) {
1667
- toRecompile.add(dep);
1668
- queue.push(dep);
1669
- }
1670
- }
1671
- }
1672
- const traitRecompileSet = this.traitGraph.calculateRecompilationSet(changedObjects);
1673
- for (const obj of traitRecompileSet) {
1674
- toRecompile.add(obj);
1675
- }
1676
- return toRecompile;
1677
- }
1678
- /**
1679
- * Get trait changes for specific objects
1680
- * Used for fine-grained trait config change detection
1681
- */
1682
- getTraitChanges(objectName, newTraits) {
1683
- return this.traitGraph.detectTraitChanges(objectName, newTraits);
1684
- }
1685
- /**
1686
- * Get the trait dependency graph for external access
1687
- */
1688
- getTraitGraph() {
1689
- return this.traitGraph;
1690
- }
1691
- // ===========================================================================
1692
- // IMPORT RESOLUTION (Asset Pipeline)
1693
- // ===========================================================================
1694
- /**
1695
- * Resolve all `@import` directives in a `HSPlusCompileResult`, merge the
1696
- * imported exports into a scope, and register cross-file edges in the
1697
- * `TraitDependencyGraph` for incremental recompilation.
1698
- *
1699
- * This method is **async** because it may read files from disk (or any
1700
- * injected async reader).
1701
- *
1702
- * ### Typical usage
1703
- * ```ts
1704
- * const parser = new HoloScriptPlusParser({ enableTypeScriptImports: true });
1705
- * const result = parser.parse(source);
1706
- *
1707
- * const compiler = new IncrementalCompiler();
1708
- * const { importScope, importErrors } = await compiler.resolveImports(
1709
- * result,
1710
- * { baseDir: '/project', sourceFile: '/project/scene.hs' }
1711
- * );
1712
- * ```
1713
- *
1714
- * @param result Parse result that may contain `ast.imports`
1715
- * @param options Must include `baseDir` (and optionally `sourceFile`, `readFile`)
1716
- * @returns `{ scope, modules, errors }` from `ImportResolver.resolve()`
1717
- */
1718
- async resolveImports(result, options) {
1719
- const baseDir = options.baseDir ?? "/";
1720
- const sourceFile = options.sourceFile ?? `${baseDir}/unknown.hs`;
1721
- const resolver = new ImportResolver();
1722
- const resolution = await resolver.resolve(result, sourceFile, {
1723
- baseDir,
1724
- readFile: options.readFile
1725
- });
1726
- const imports = result.ast?.imports ?? [];
1727
- this.traitGraph.clearImportsForFile(sourceFile);
1728
- for (const imp of imports) {
1729
- const canonicalPath = resolveImportPath(imp.path, baseDir);
1730
- this.traitGraph.registerImport(sourceFile, canonicalPath);
1731
- }
1732
- return resolution;
1733
- }
1734
- // ===========================================================================
1735
- // RBAC ENFORCEMENT
1736
- // ===========================================================================
1737
- /**
1738
- * Validate agent has permission for incremental compilation.
1739
- * Skips validation when no token is provided (backwards compatibility / testing).
1740
- */
1741
- validateAccess(agentToken) {
1742
- if (!agentToken) return;
1743
- const rbac = getRBAC();
1744
- const decision = rbac.checkAccess({
1745
- token: agentToken,
1746
- resourceType: ResourceType.AST,
1747
- operation: "read",
1748
- expectedWorkflowStep: WorkflowStep.GENERATE_ASSEMBLY
1749
- });
1750
- if (!decision.allowed) {
1751
- throw new UnauthorizedIncrementalCompilerAccessError(decision, "IncrementalCompiler");
1752
- }
1753
- }
1754
- /**
1755
- * Perform incremental compilation
1756
- */
1757
- async compile(newAST, compileObject, options = {}) {
1758
- const { preserveState = true, forceRecompile = [], skipUnchanged = true, agentToken } = options;
1759
- this.validateAccess(agentToken);
1760
- const diffResult = this.diff(this.previousAST, newAST);
1761
- const changedObjects = [
1762
- ...diffResult.addedObjects,
1763
- ...diffResult.modifiedObjects,
1764
- ...forceRecompile
1765
- ];
1766
- const recompileSet = this.getRecompilationSet(changedObjects);
1767
- for (const removed of diffResult.removedObjects) {
1768
- const dependents = this.getDependents(removed);
1769
- for (const dep of dependents) {
1770
- recompileSet.add(dep);
1771
- }
1772
- }
1773
- const recompiledObjects = [];
1774
- const cachedObjects = [];
1775
- const compiledParts = [];
1776
- const allObjects = /* @__PURE__ */ new Map();
1777
- this.collectObjects(newAST, allObjects);
1778
- for (const [name, obj] of allObjects) {
1779
- const hash = hashContent(serializeObject(obj));
1780
- const traitUsages = this.extractTraitUsages(obj.traits || []);
1781
- this.traitGraph.registerObject({
1782
- objectName: name,
1783
- sourceId: newAST.name || "default",
1784
- traits: traitUsages,
1785
- template: obj.template
1786
- });
1787
- if (skipUnchanged && !recompileSet.has(name)) {
1788
- if (this.semanticCache) {
1789
- const astHash = hashASTSubtree(obj);
1790
- const semanticResult = await this.semanticCache.get(astHash, "compiled-object");
1791
- if (semanticResult.hit) {
1792
- cachedObjects.push(name);
1793
- compiledParts.push(semanticResult.entry.data);
1794
- continue;
1795
- }
1796
- }
1797
- const cached = this.getCached(name, hash);
1798
- if (cached) {
1799
- cachedObjects.push(name);
1800
- compiledParts.push(cached.compiledCode);
1801
- continue;
1802
- }
1803
- }
1804
- const compiled = compileObject(obj);
1805
- recompiledObjects.push(name);
1806
- compiledParts.push(compiled);
1807
- this.setCached(name, hash, compiled, []);
1808
- if (this.semanticCache) {
1809
- const astHash = hashASTSubtree(obj);
1810
- await this.semanticCache.set(astHash, "compiled-object", compiled, {
1811
- sourcePath: newAST.name,
1812
- dependencies: []
1813
- });
1814
- }
1815
- }
1816
- this.previousAST = newAST;
1817
- return {
1818
- fullRecompile: cachedObjects.length === 0,
1819
- recompiledObjects,
1820
- cachedObjects,
1821
- statePreserved: preserveState && this.stateSnapshot !== null,
1822
- compiledCode: compiledParts.join("\n\n"),
1823
- changes: diffResult
1824
- };
1825
- }
1826
- /**
1827
- * Reset compiler state
1828
- */
1829
- reset() {
1830
- this.cache.clear();
1831
- this.previousAST = null;
1832
- this.stateSnapshot = null;
1833
- this.dependencyGraph.clear();
1834
- }
1835
- /**
1836
- * Get cache statistics including trait graph info
1837
- */
1838
- async getStats() {
1839
- let dependencyEdges = 0;
1840
- for (const deps of this.dependencyGraph.values()) {
1841
- dependencyEdges += deps.size;
1842
- }
1843
- const stats = {
1844
- cacheSize: this.cache.size,
1845
- objectsCached: Array.from(this.cache.keys()),
1846
- dependencyEdges,
1847
- traitGraphStats: this.traitGraph.getStats()
1848
- };
1849
- if (this.semanticCache) {
1850
- const semanticStats = await this.semanticCache.getStats();
1851
- return {
1852
- ...stats,
1853
- semanticCache: semanticStats
1854
- };
1855
- }
1856
- return stats;
1857
- }
1858
- /**
1859
- * Get semantic cache statistics
1860
- */
1861
- async getSemanticCacheStats() {
1862
- if (!this.semanticCache) {
1863
- return null;
1864
- }
1865
- return this.semanticCache.getStats();
1866
- }
1867
- /**
1868
- * Clear semantic cache
1869
- */
1870
- async clearSemanticCache() {
1871
- if (this.semanticCache) {
1872
- await this.semanticCache.clear();
1873
- }
1874
- }
1875
- /**
1876
- * Close semantic cache connection
1877
- */
1878
- async closeSemanticCache() {
1879
- if (this.semanticCache) {
1880
- await this.semanticCache.close();
1881
- }
1882
- }
1883
- /**
1884
- * Serialize compiler state for persistence
1885
- * Includes cache, dependency graph, and trait graph
1886
- */
1887
- serialize() {
1888
- const data = {
1889
- version: 1,
1890
- entries: Array.from(this.cache.entries()).map(([name, entry]) => ({
1891
- name,
1892
- entry
1893
- })),
1894
- dependencies: Array.from(this.dependencyGraph.entries()).map(([name, deps]) => ({
1895
- name,
1896
- deps: Array.from(deps)
1897
- })),
1898
- traitGraph: this.traitGraph.serialize(),
1899
- timestamp: Date.now()
1900
- };
1901
- return JSON.stringify(data);
1902
- }
1903
- /**
1904
- * Restore compiler state from serialized data
1905
- */
1906
- static deserialize(json) {
1907
- const data = JSON.parse(json);
1908
- if (data.version !== 1) {
1909
- throw new Error(`Unsupported cache version: ${data.version}`);
1910
- }
1911
- const traitGraph = TraitDependencyGraph.deserialize(data.traitGraph);
1912
- const compiler = new _IncrementalCompiler(traitGraph);
1913
- for (const { name, entry } of data.entries) {
1914
- compiler.cache.set(name, entry);
1915
- }
1916
- for (const { name, deps } of data.dependencies) {
1917
- compiler.dependencyGraph.set(name, new Set(deps));
1918
- }
1919
- return compiler;
1920
- }
1921
- };
1922
- function createIncrementalCompiler() {
1923
- return new IncrementalCompiler();
1924
- }
1925
- function serializeCache(compiler) {
1926
- compiler.getStats();
1927
- const data = {
1928
- version: 1,
1929
- entries: [],
1930
- dependencies: [],
1931
- traitGraph: compiler.getTraitGraph().serialize(),
1932
- timestamp: Date.now()
1933
- };
1934
- return JSON.stringify(data);
1935
- }
1936
- function deserializeCache(json) {
1937
- const data = JSON.parse(json);
1938
- if (data.version !== 1) {
1939
- throw new Error(`Unsupported cache version: ${data.version}`);
1940
- }
1941
- const traitGraph = TraitDependencyGraph.deserialize(data.traitGraph);
1942
- const compiler = new IncrementalCompiler(traitGraph);
1943
- for (const { name, entry } of data.entries) {
1944
- compiler.setCached(name, entry.hash, entry.compiledCode, entry.dependencies);
1945
- }
1946
- for (const { name, deps } of data.dependencies) {
1947
- compiler.updateDependencies(name, deps);
1948
- }
1949
- return compiler;
1950
- }
1951
- var UnauthorizedIncrementalCompilerAccessError = class extends Error {
1952
- constructor(decision, compilerName) {
1953
- super(
1954
- `[${compilerName}] Unauthorized access: ${decision.reason || "Access denied"}
1955
- Agent Role: ${decision.agentRole || "unknown"}
1956
- Required Permission: ${decision.requiredPermission || "unknown"}`
1957
- );
1958
- this.decision = decision;
1959
- this.compilerName = compilerName;
1960
- this.name = "UnauthorizedIncrementalCompilerAccessError";
1961
- }
1962
- };
1963
-
1964
- export { IncrementalCompiler, TraitDependencyGraph, UnauthorizedIncrementalCompilerAccessError, createIncrementalCompiler, deserializeCache, globalTraitGraph, serializeCache };
1965
- //# sourceMappingURL=chunk-CS2EMTGF.js.map
1966
- //# sourceMappingURL=chunk-CS2EMTGF.js.map