@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,4499 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkGVUR45UF_cjs = require('./chunk-GVUR45UF.cjs');
4
- var chunkXG23EUQX_cjs = require('./chunk-XG23EUQX.cjs');
5
- var crypto = require('crypto');
6
-
7
- function _interopNamespace(e) {
8
- if (e && e.__esModule) return e;
9
- var n = Object.create(null);
10
- if (e) {
11
- Object.keys(e).forEach(function (k) {
12
- if (k !== 'default') {
13
- var d = Object.getOwnPropertyDescriptor(e, k);
14
- Object.defineProperty(n, k, d.get ? d : {
15
- enumerable: true,
16
- get: function () { return e[k]; }
17
- });
18
- }
19
- });
20
- }
21
- n.default = e;
22
- return Object.freeze(n);
23
- }
24
-
25
- var crypto__namespace = /*#__PURE__*/_interopNamespace(crypto);
26
-
27
- // src/parser/HybridChunker.ts
28
- function countTokens(text) {
29
- return Math.ceil(text.length / 4);
30
- }
31
- function detectFileType(filePath) {
32
- const ext = filePath.split(".").pop()?.toLowerCase() || "";
33
- if (["ts", "js", "jsx", "tsx", "hs", "hsplus"].includes(ext)) {
34
- return "code";
35
- }
36
- if (["log", "txt", "csv"].includes(ext)) {
37
- return "log";
38
- }
39
- if (["md", "mdx", "markdown"].includes(ext)) {
40
- return "markdown";
41
- }
42
- return "unknown";
43
- }
44
- var StructureBasedChunker = class {
45
- constructor(options) {
46
- this.options = {
47
- maxTokens: options.maxTokens || 1024,
48
- overlapTokens: options.overlapTokens || 100,
49
- semanticThreshold: options.semanticThreshold || 0.85,
50
- debug: options.debug || false
51
- };
52
- }
53
- /**
54
- * Chunk code files by detecting structural boundaries
55
- */
56
- chunk(content, filePath) {
57
- const lines = content.split("\n");
58
- const boundaries = this.detectStructuralBoundaries(lines);
59
- if (boundaries.length === 0) {
60
- return [
61
- {
62
- id: `structure:${filePath}:0`,
63
- type: "code-block",
64
- startLine: 1,
65
- endLine: lines.length,
66
- content,
67
- tokens: countTokens(content),
68
- strategy: "structure"
69
- }
70
- ];
71
- }
72
- const chunks = [];
73
- let currentChunk = [];
74
- let currentStart = 1;
75
- let chunkIndex = 0;
76
- for (let i = 0; i < boundaries.length; i++) {
77
- const boundary = boundaries[i];
78
- const segmentContent = lines.slice(boundary.startLine - 1, boundary.endLine).join("\n");
79
- const segmentTokens = countTokens(segmentContent);
80
- if (currentChunk.length > 0 && countTokens(currentChunk.join("\n") + "\n" + segmentContent) > this.options.maxTokens) {
81
- const chunkContent = currentChunk.join("\n");
82
- chunks.push({
83
- id: `structure:${filePath}:${chunkIndex++}`,
84
- type: "code-block",
85
- startLine: currentStart,
86
- endLine: currentStart + currentChunk.length - 1,
87
- content: chunkContent,
88
- tokens: countTokens(chunkContent),
89
- strategy: "structure"
90
- });
91
- currentChunk = [];
92
- currentStart = boundary.startLine;
93
- }
94
- if (segmentTokens > this.options.maxTokens) {
95
- const subChunks = this.recursiveSplit(
96
- segmentContent,
97
- boundary.startLine,
98
- filePath,
99
- chunkIndex
100
- );
101
- chunks.push(...subChunks);
102
- chunkIndex += subChunks.length;
103
- } else {
104
- currentChunk.push(segmentContent);
105
- }
106
- }
107
- if (currentChunk.length > 0) {
108
- const chunkContent = currentChunk.join("\n");
109
- chunks.push({
110
- id: `structure:${filePath}:${chunkIndex}`,
111
- type: "code-block",
112
- startLine: currentStart,
113
- endLine: currentStart + currentChunk.length - 1,
114
- content: chunkContent,
115
- tokens: countTokens(chunkContent),
116
- strategy: "structure"
117
- });
118
- }
119
- return chunks;
120
- }
121
- /**
122
- * Detect structural boundaries (functions, classes, interfaces)
123
- */
124
- detectStructuralBoundaries(lines) {
125
- const boundaries = [];
126
- let braceDepth = 0;
127
- let currentBlock = null;
128
- for (let i = 0; i < lines.length; i++) {
129
- const line = lines[i];
130
- const trimmed = line.trim();
131
- if (!currentBlock) {
132
- const functionMatch = trimmed.match(
133
- /^(export\s+)?(async\s+)?function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/
134
- );
135
- const classMatch = trimmed.match(
136
- /^(export\s+)?(abstract\s+)?class\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/
137
- );
138
- const interfaceMatch = trimmed.match(/^(export\s+)?interface\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/);
139
- const methodMatch = trimmed.match(
140
- /^(public|private|protected|static)?\s*([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\([^)]*\)\s*[:{]/
141
- );
142
- if (functionMatch) {
143
- currentBlock = {
144
- type: "function",
145
- name: functionMatch[3],
146
- startLine: i + 1
147
- };
148
- } else if (classMatch) {
149
- currentBlock = {
150
- type: "class",
151
- name: classMatch[3],
152
- startLine: i + 1
153
- };
154
- } else if (interfaceMatch) {
155
- currentBlock = {
156
- type: "interface",
157
- name: interfaceMatch[2],
158
- startLine: i + 1
159
- };
160
- } else if (methodMatch) {
161
- currentBlock = {
162
- type: "method",
163
- name: methodMatch[2],
164
- startLine: i + 1
165
- };
166
- }
167
- }
168
- if (currentBlock) {
169
- for (const char of line) {
170
- if (char === "{") braceDepth++;
171
- if (char === "}") braceDepth--;
172
- }
173
- if (braceDepth === 0 && trimmed.includes("}")) {
174
- boundaries.push({
175
- type: currentBlock.type,
176
- name: currentBlock.name,
177
- startLine: currentBlock.startLine,
178
- endLine: i + 1
179
- });
180
- currentBlock = null;
181
- }
182
- }
183
- }
184
- if (currentBlock) {
185
- boundaries.push({
186
- type: currentBlock.type,
187
- name: currentBlock.name,
188
- startLine: currentBlock.startLine,
189
- endLine: lines.length
190
- });
191
- }
192
- return boundaries;
193
- }
194
- /**
195
- * Recursively split large segments
196
- */
197
- recursiveSplit(content, startLine, filePath, baseIndex) {
198
- const lines = content.split("\n");
199
- const chunks = [];
200
- let currentChunk = [];
201
- let currentStart = startLine;
202
- for (let i = 0; i < lines.length; i++) {
203
- currentChunk.push(lines[i]);
204
- if (countTokens(currentChunk.join("\n")) >= this.options.maxTokens) {
205
- const chunkContent = currentChunk.join("\n");
206
- chunks.push({
207
- id: `structure:${filePath}:${baseIndex + chunks.length}`,
208
- type: "code-fragment",
209
- startLine: currentStart,
210
- endLine: currentStart + currentChunk.length - 1,
211
- content: chunkContent,
212
- tokens: countTokens(chunkContent),
213
- strategy: "structure",
214
- metadata: { splitReason: "recursive-oversized" }
215
- });
216
- currentChunk = [];
217
- currentStart = startLine + i + 1;
218
- }
219
- }
220
- if (currentChunk.length > 0) {
221
- const chunkContent = currentChunk.join("\n");
222
- chunks.push({
223
- id: `structure:${filePath}:${baseIndex + chunks.length}`,
224
- type: "code-fragment",
225
- startLine: currentStart,
226
- endLine: currentStart + currentChunk.length - 1,
227
- content: chunkContent,
228
- tokens: countTokens(chunkContent),
229
- strategy: "structure"
230
- });
231
- }
232
- return chunks;
233
- }
234
- };
235
- var FixedSizeChunker = class {
236
- constructor(options) {
237
- this.options = {
238
- maxTokens: options.maxTokens || 1024,
239
- overlapTokens: options.overlapTokens || 100,
240
- semanticThreshold: options.semanticThreshold || 0.85,
241
- debug: options.debug || false
242
- };
243
- }
244
- /**
245
- * Chunk text files into fixed-size segments with overlap
246
- */
247
- chunk(content, filePath) {
248
- const lines = content.split("\n");
249
- const chunks = [];
250
- let currentChunk = [];
251
- let currentStart = 1;
252
- let chunkIndex = 0;
253
- for (let i = 0; i < lines.length; i++) {
254
- currentChunk.push(lines[i]);
255
- const currentTokens = countTokens(currentChunk.join("\n"));
256
- if (currentTokens >= this.options.maxTokens) {
257
- const chunkContent = currentChunk.join("\n");
258
- chunks.push({
259
- id: `fixed:${filePath}:${chunkIndex++}`,
260
- type: "text-block",
261
- startLine: currentStart,
262
- endLine: currentStart + currentChunk.length - 1,
263
- content: chunkContent,
264
- tokens: currentTokens,
265
- strategy: "fixed"
266
- });
267
- const overlapLines = this.calculateOverlapLines(currentChunk);
268
- currentChunk = overlapLines;
269
- currentStart = currentStart + currentChunk.length - overlapLines.length;
270
- }
271
- }
272
- if (currentChunk.length > 0) {
273
- const chunkContent = currentChunk.join("\n");
274
- chunks.push({
275
- id: `fixed:${filePath}:${chunkIndex}`,
276
- type: "text-block",
277
- startLine: currentStart,
278
- endLine: currentStart + currentChunk.length - 1,
279
- content: chunkContent,
280
- tokens: countTokens(chunkContent),
281
- strategy: "fixed"
282
- });
283
- }
284
- return chunks;
285
- }
286
- /**
287
- * Calculate overlap lines based on token count
288
- */
289
- calculateOverlapLines(lines) {
290
- const overlapLines = [];
291
- let overlapTokens = 0;
292
- for (let i = lines.length - 1; i >= 0; i--) {
293
- const lineTokens = countTokens(lines[i]);
294
- if (overlapTokens + lineTokens > this.options.overlapTokens) {
295
- break;
296
- }
297
- overlapLines.unshift(lines[i]);
298
- overlapTokens += lineTokens;
299
- }
300
- return overlapLines;
301
- }
302
- };
303
- var SemanticChunker = class {
304
- constructor(options) {
305
- this.options = {
306
- maxTokens: options.maxTokens || 1024,
307
- overlapTokens: options.overlapTokens || 100,
308
- semanticThreshold: options.semanticThreshold || 0.85,
309
- debug: options.debug || false
310
- };
311
- }
312
- /**
313
- * Chunk markdown/docs by semantic similarity
314
- */
315
- chunk(content, filePath) {
316
- const paragraphs = this.detectParagraphs(content);
317
- if (paragraphs.length === 0) {
318
- return [
319
- {
320
- id: `semantic:${filePath}:0`,
321
- type: "document",
322
- startLine: 1,
323
- endLine: content.split("\n").length,
324
- content,
325
- tokens: countTokens(content),
326
- strategy: "semantic"
327
- }
328
- ];
329
- }
330
- const chunks = [];
331
- let currentGroup = [];
332
- let chunkIndex = 0;
333
- for (let i = 0; i < paragraphs.length; i++) {
334
- const para = paragraphs[i];
335
- if (currentGroup.length === 0) {
336
- currentGroup.push(para);
337
- continue;
338
- }
339
- const lastPara = currentGroup[currentGroup.length - 1];
340
- const similarity2 = this.computeSimilarity(lastPara.content, para.content);
341
- const groupContent = currentGroup.map((p) => p.content).join("\n\n");
342
- const groupTokens = countTokens(groupContent + "\n\n" + para.content);
343
- if (similarity2 >= this.options.semanticThreshold && groupTokens <= this.options.maxTokens) {
344
- currentGroup.push(para);
345
- } else {
346
- const chunkContent = currentGroup.map((p) => p.content).join("\n\n");
347
- chunks.push({
348
- id: `semantic:${filePath}:${chunkIndex++}`,
349
- type: "semantic-group",
350
- startLine: currentGroup[0].startLine,
351
- endLine: currentGroup[currentGroup.length - 1].endLine,
352
- content: chunkContent,
353
- tokens: countTokens(chunkContent),
354
- strategy: "semantic",
355
- metadata: {
356
- paragraphCount: currentGroup.length
357
- }
358
- });
359
- currentGroup = [para];
360
- }
361
- }
362
- if (currentGroup.length > 0) {
363
- const chunkContent = currentGroup.map((p) => p.content).join("\n\n");
364
- chunks.push({
365
- id: `semantic:${filePath}:${chunkIndex}`,
366
- type: "semantic-group",
367
- startLine: currentGroup[0].startLine,
368
- endLine: currentGroup[currentGroup.length - 1].endLine,
369
- content: chunkContent,
370
- tokens: countTokens(chunkContent),
371
- strategy: "semantic",
372
- metadata: {
373
- paragraphCount: currentGroup.length
374
- }
375
- });
376
- }
377
- return chunks;
378
- }
379
- /**
380
- * Detect paragraph boundaries in markdown
381
- */
382
- detectParagraphs(content) {
383
- const lines = content.split("\n");
384
- const paragraphs = [];
385
- let currentPara = [];
386
- let currentStart = 1;
387
- for (let i = 0; i < lines.length; i++) {
388
- const line = lines[i];
389
- const trimmed = line.trim();
390
- if (trimmed === "" || trimmed.startsWith("#") || /^[-*+]\s/.test(trimmed) || /^\d+\.\s/.test(trimmed)) {
391
- if (currentPara.length > 0) {
392
- paragraphs.push({
393
- content: currentPara.join("\n"),
394
- startLine: currentStart,
395
- endLine: i
396
- });
397
- currentPara = [];
398
- }
399
- if (trimmed !== "") {
400
- currentPara.push(line);
401
- currentStart = i + 1;
402
- } else {
403
- currentStart = i + 2;
404
- }
405
- } else {
406
- currentPara.push(line);
407
- }
408
- }
409
- if (currentPara.length > 0) {
410
- paragraphs.push({
411
- content: currentPara.join("\n"),
412
- startLine: currentStart,
413
- endLine: lines.length
414
- });
415
- }
416
- return paragraphs;
417
- }
418
- /**
419
- * Compute similarity between two text segments
420
- *
421
- * Simple heuristic: Jaccard similarity of word sets
422
- * For production: Use sentence-transformers embeddings + cosine similarity
423
- */
424
- computeSimilarity(text1, text2) {
425
- const words1 = new Set(
426
- text1.toLowerCase().split(/\s+/).filter((w) => w.length > 3)
427
- );
428
- const words2 = new Set(
429
- text2.toLowerCase().split(/\s+/).filter((w) => w.length > 3)
430
- );
431
- const intersection = new Set([...words1].filter((w) => words2.has(w)));
432
- const union = /* @__PURE__ */ new Set([...words1, ...words2]);
433
- return union.size > 0 ? intersection.size / union.size : 0;
434
- }
435
- };
436
- var HybridChunker = class {
437
- constructor(options = {}) {
438
- this.options = {
439
- maxTokens: options.maxTokens || 1024,
440
- overlapTokens: options.overlapTokens || 100,
441
- semanticThreshold: options.semanticThreshold || 0.85,
442
- debug: options.debug || false
443
- };
444
- this.structureChunker = new StructureBasedChunker(this.options);
445
- this.fixedChunker = new FixedSizeChunker(this.options);
446
- this.semanticChunker = new SemanticChunker(this.options);
447
- }
448
- /**
449
- * Chunk a file using the optimal strategy
450
- */
451
- chunk(content, filePath) {
452
- const fileType = detectFileType(filePath);
453
- this.log(`Chunking ${filePath} (type: ${fileType})`);
454
- let chunks;
455
- switch (fileType) {
456
- case "code":
457
- chunks = this.structureChunker.chunk(content, filePath);
458
- break;
459
- case "log":
460
- chunks = this.fixedChunker.chunk(content, filePath);
461
- break;
462
- case "markdown":
463
- chunks = this.semanticChunker.chunk(content, filePath);
464
- break;
465
- default:
466
- this.log(`Unknown file type for ${filePath}, using fixed-size chunking`);
467
- chunks = this.fixedChunker.chunk(content, filePath);
468
- }
469
- this.log(
470
- `Generated ${chunks.length} chunks (${chunks.reduce((sum, c) => sum + c.tokens, 0)} total tokens)`
471
- );
472
- return chunks;
473
- }
474
- /**
475
- * Get chunking statistics
476
- */
477
- getStats(chunks) {
478
- const totalTokens = chunks.reduce((sum, c) => sum + c.tokens, 0);
479
- const strategyDistribution = {};
480
- for (const chunk of chunks) {
481
- strategyDistribution[chunk.strategy] = (strategyDistribution[chunk.strategy] || 0) + 1;
482
- }
483
- return {
484
- totalChunks: chunks.length,
485
- totalTokens,
486
- avgTokensPerChunk: chunks.length > 0 ? totalTokens / chunks.length : 0,
487
- strategyDistribution
488
- };
489
- }
490
- /**
491
- * Debug logging
492
- */
493
- log(message) {
494
- if (this.options.debug) {
495
- console.log(`[HybridChunker] ${message}`);
496
- }
497
- }
498
- };
499
- function createHybridChunker(options) {
500
- return new HybridChunker(options);
501
- }
502
-
503
- // src/parser/ChunkDetector.ts
504
- var ChunkDetector = class {
505
- /**
506
- * Detects chunks in the source code based on top-level keywords
507
- *
508
- * @deprecated Use detectHybrid() for better performance with multi-strategy chunking
509
- */
510
- static detect(source) {
511
- const lines = source.split(/\r?\n/);
512
- const chunks = [];
513
- let currentChunk = null;
514
- let braceDepth = 0;
515
- for (let i = 0; i < lines.length; i++) {
516
- const line = lines[i];
517
- const trimmed = line.trim();
518
- if (!currentChunk && (!trimmed || trimmed.startsWith("//"))) {
519
- continue;
520
- }
521
- if (!currentChunk) {
522
- const orbMatch = trimmed.match(/^orb\s+([a-zA-Z0-9_#"]+)/);
523
- const templateMatch = trimmed.match(/^template\s+"([^"]+)"/);
524
- const envMatch = trimmed.startsWith("environment");
525
- const logicMatch = trimmed.startsWith("logic");
526
- const directiveMatch = trimmed.startsWith("@");
527
- if (orbMatch || templateMatch || envMatch || logicMatch || directiveMatch) {
528
- currentChunk = {
529
- startLine: i + 1,
530
- content: line
531
- };
532
- if (orbMatch) {
533
- currentChunk.type = "orb";
534
- currentChunk.name = orbMatch[1].replace(/[#"]/g, "");
535
- currentChunk.id = `orb:${currentChunk.name}`;
536
- } else if (templateMatch) {
537
- currentChunk.type = "template";
538
- currentChunk.name = templateMatch[1];
539
- currentChunk.id = `template:${currentChunk.name}`;
540
- } else if (envMatch) {
541
- currentChunk.type = "environment";
542
- currentChunk.id = `environment:${i + 1}`;
543
- } else if (logicMatch) {
544
- currentChunk.type = "logic";
545
- currentChunk.id = `logic:${i + 1}`;
546
- } else if (directiveMatch) {
547
- currentChunk.type = "directive";
548
- if (!trimmed.includes("{")) {
549
- currentChunk.endLine = i + 1;
550
- currentChunk.id = `directive:${i + 1}`;
551
- chunks.push(currentChunk);
552
- currentChunk = null;
553
- continue;
554
- }
555
- currentChunk.id = `directive:${i + 1}`;
556
- }
557
- }
558
- } else {
559
- currentChunk.content += "\n" + line;
560
- }
561
- if (currentChunk) {
562
- for (const char of line) {
563
- if (char === "{") braceDepth++;
564
- if (char === "}") braceDepth--;
565
- }
566
- if (braceDepth === 0) {
567
- currentChunk.endLine = i + 1;
568
- chunks.push(currentChunk);
569
- currentChunk = null;
570
- }
571
- }
572
- }
573
- if (currentChunk) {
574
- currentChunk.endLine = lines.length;
575
- chunks.push(currentChunk);
576
- }
577
- return chunks;
578
- }
579
- /**
580
- * Detect chunks using HybridChunker (structure-based + semantic + fixed-size)
581
- *
582
- * Routes .hs/.hsplus files to structure-based chunking for better performance.
583
- * This method provides 20-30% better parsing speed by using AST-aware boundaries.
584
- *
585
- * @param source - Source code content
586
- * @param filePath - File path for type detection (defaults to .hsplus)
587
- * @param options - Chunking options
588
- */
589
- static detectHybrid(source, filePath = "file.hsplus", options) {
590
- const hybridChunker = createHybridChunker(options);
591
- const chunks = hybridChunker.chunk(source, filePath);
592
- return chunks.map((chunk) => ({
593
- id: chunk.id,
594
- type: this.mapChunkType(chunk.type),
595
- name: chunk.name,
596
- startLine: chunk.startLine,
597
- endLine: chunk.endLine,
598
- content: chunk.content,
599
- tokens: chunk.tokens,
600
- strategy: chunk.strategy,
601
- metadata: chunk.metadata
602
- }));
603
- }
604
- /**
605
- * Map HybridChunker types to ChunkDetector types
606
- */
607
- static mapChunkType(hybridType) {
608
- if (hybridType.includes("class")) return "template";
609
- if (hybridType.includes("function")) return "logic";
610
- return "unknown";
611
- }
612
- };
613
- var ParseCache = class {
614
- constructor(maxEntries = 500) {
615
- this.cache = /* @__PURE__ */ new Map();
616
- this.evictionCount = 0;
617
- /** Monotonically increasing counter for reliable LRU ordering */
618
- this.clock = 0;
619
- this.maxEntries = maxEntries;
620
- }
621
- /**
622
- * Generates a hash for the chunk content
623
- */
624
- static hash(content) {
625
- return crypto__namespace.createHash("sha256").update(content).digest("hex");
626
- }
627
- /**
628
- * Retrieves a cached node if the hash matches
629
- */
630
- get(id, currentHash) {
631
- const cached = this.cache.get(id);
632
- if (cached && cached.hash === currentHash) {
633
- cached.lastUsed = ++this.clock;
634
- return cached.node;
635
- }
636
- return null;
637
- }
638
- /**
639
- * Stores a node in the cache
640
- */
641
- set(id, hash, node) {
642
- if (this.cache.size >= this.maxEntries) {
643
- this.evictOldest();
644
- }
645
- this.cache.set(id, {
646
- id,
647
- hash,
648
- node,
649
- lastUsed: ++this.clock
650
- });
651
- }
652
- /**
653
- * Clears the entire cache
654
- */
655
- clear() {
656
- this.cache.clear();
657
- }
658
- /**
659
- * Returns cache statistics: current size, total evictions, and capacity.
660
- */
661
- getStats() {
662
- return {
663
- size: this.cache.size,
664
- evictions: this.evictionCount,
665
- maxEntries: this.maxEntries
666
- };
667
- }
668
- evictOldest() {
669
- let oldestId = null;
670
- let oldestTime = Infinity;
671
- for (const [id, entry] of this.cache.entries()) {
672
- if (entry.lastUsed < oldestTime) {
673
- oldestTime = entry.lastUsed;
674
- oldestId = id;
675
- }
676
- }
677
- if (oldestId) {
678
- this.cache.delete(oldestId);
679
- this.evictionCount++;
680
- }
681
- }
682
- };
683
- var globalParseCache = new ParseCache();
684
-
685
- // src/parser/RichErrors.ts
686
- var HSPLUS_ERROR_CODES = {
687
- // Syntax Errors (HSP001-HSP099)
688
- HSP001: "Unexpected token",
689
- HSP002: "Expected identifier",
690
- HSP003: "Expected keyword",
691
- HSP004: "Unclosed brace - missing }",
692
- HSP005: "Unclosed bracket - missing ]",
693
- HSP006: "Unclosed parenthesis - missing )",
694
- HSP007: "Unclosed string literal",
695
- HSP008: "Invalid number format",
696
- HSP009: "Missing colon after property name",
697
- HSP010: "Missing value after colon",
698
- // Structure Errors (HSP100-HSP199)
699
- HSP100: "Invalid composition structure",
700
- HSP101: "Invalid object definition",
701
- HSP102: "Invalid template definition",
702
- HSP103: "Invalid spatial_group definition",
703
- HSP104: "Invalid environment block",
704
- HSP105: "Invalid state block",
705
- HSP106: "Invalid logic block",
706
- HSP107: "Duplicate identifier",
707
- HSP108: "Missing required property",
708
- // Trait Errors (HSP200-HSP299)
709
- HSP200: "Unknown trait",
710
- HSP201: "Invalid trait syntax",
711
- HSP202: "Missing trait argument",
712
- HSP203: "Invalid trait argument type",
713
- HSP204: "Trait not allowed in this context",
714
- HSP205: "Duplicate trait",
715
- // Expression Errors (HSP300-HSP399)
716
- HSP300: "Invalid expression",
717
- HSP301: "Undefined variable",
718
- HSP302: "Invalid operator",
719
- HSP303: "Type mismatch",
720
- HSP304: "Invalid function call",
721
- HSP305: "Missing function argument",
722
- // Import/Module Errors (HSP400-HSP499)
723
- HSP400: "Invalid import statement",
724
- HSP401: "Module not found",
725
- HSP402: "Circular import detected",
726
- // Limit Errors (HSP900-HSP999)
727
- HSP900: "Maximum nesting depth exceeded",
728
- HSP901: "Maximum array length exceeded",
729
- HSP902: "Maximum string length exceeded"
730
- };
731
- function levenshteinDistance(a, b) {
732
- const matrix = [];
733
- for (let i = 0; i <= b.length; i++) {
734
- matrix[i] = [i];
735
- }
736
- for (let j = 0; j <= a.length; j++) {
737
- matrix[0][j] = j;
738
- }
739
- for (let i = 1; i <= b.length; i++) {
740
- for (let j = 1; j <= a.length; j++) {
741
- if (b.charAt(i - 1) === a.charAt(j - 1)) {
742
- matrix[i][j] = matrix[i - 1][j - 1];
743
- } else {
744
- matrix[i][j] = Math.min(
745
- matrix[i - 1][j - 1] + 1,
746
- // substitution
747
- matrix[i][j - 1] + 1,
748
- // insertion
749
- matrix[i - 1][j] + 1
750
- // deletion
751
- );
752
- }
753
- }
754
- }
755
- return matrix[b.length][a.length];
756
- }
757
- function similarity(a, b) {
758
- const aLower = a.toLowerCase();
759
- const bLower = b.toLowerCase();
760
- if (aLower === bLower) return 1;
761
- if (bLower.startsWith(aLower) || aLower.startsWith(bLower)) {
762
- return 0.9;
763
- }
764
- const maxLen = Math.max(a.length, b.length);
765
- if (maxLen === 0) return 1;
766
- const distance = levenshteinDistance(aLower, bLower);
767
- return 1 - distance / maxLen;
768
- }
769
- function findSimilarTrait(input, threshold = 0.5) {
770
- let bestMatch;
771
- let bestScore = threshold;
772
- for (const trait of chunkXG23EUQX_cjs.VR_TRAITS) {
773
- const score = similarity(input, trait);
774
- if (score > bestScore) {
775
- bestScore = score;
776
- bestMatch = trait;
777
- }
778
- }
779
- return bestMatch;
780
- }
781
- function findSimilarKeyword(input, threshold = 0.5) {
782
- const keywords = [
783
- "composition",
784
- "object",
785
- "template",
786
- "spatial_group",
787
- "environment",
788
- "state",
789
- "logic",
790
- "on_click",
791
- "on_hover",
792
- "on_enter",
793
- "on_exit",
794
- "position",
795
- "rotation",
796
- "scale",
797
- "color",
798
- "model",
799
- "geometry",
800
- "visible",
801
- "opacity",
802
- "material",
803
- "physics",
804
- "audio",
805
- "animation",
806
- "true",
807
- "false",
808
- "null",
809
- "if",
810
- "else",
811
- "for",
812
- "while",
813
- "function",
814
- "let",
815
- "const",
816
- "return",
817
- "import",
818
- "from",
819
- "using",
820
- "spawn",
821
- "emit"
822
- ];
823
- let bestMatch;
824
- let bestScore = threshold;
825
- for (const keyword of keywords) {
826
- const score = similarity(input, keyword);
827
- if (score > bestScore) {
828
- bestScore = score;
829
- bestMatch = keyword;
830
- }
831
- }
832
- return bestMatch;
833
- }
834
- function getSourceContext(source, line, column, contextLines = 2) {
835
- const lines = source.split("\n");
836
- const result = [];
837
- const startLine = Math.max(1, line - contextLines);
838
- const endLine = Math.min(lines.length, line + contextLines);
839
- const maxLineNum = endLine;
840
- const padding = String(maxLineNum).length;
841
- for (let i = startLine; i <= endLine; i++) {
842
- const lineContent = lines[i - 1] || "";
843
- const lineNum = String(i).padStart(padding, " ");
844
- const prefix = i === line ? ">" : " ";
845
- result.push(`${prefix} ${lineNum} | ${lineContent}`);
846
- if (i === line) {
847
- const indicator = " ".repeat(padding + 4 + Math.max(0, column - 1)) + "^";
848
- result.push(indicator);
849
- }
850
- }
851
- return result.join("\n");
852
- }
853
- function createRichError(code, message, line, column, options = {}) {
854
- const { source, suggestion, severity = "error", endLine, endColumn } = options;
855
- return {
856
- code,
857
- message: `${code}: ${message}`,
858
- line,
859
- column,
860
- endLine,
861
- endColumn,
862
- context: source ? getSourceContext(source, line, column) : void 0,
863
- suggestion,
864
- severity
865
- };
866
- }
867
- function createTraitError(traitName, line, column, source) {
868
- const similar = findSimilarTrait(traitName);
869
- const suggestion = similar ? `Did you mean '@${similar}'?` : void 0;
870
- return createRichError("HSP200", `Unknown trait '@${traitName}'`, line, column, {
871
- source,
872
- suggestion
873
- });
874
- }
875
- function createKeywordError(found, expected, line, column, source) {
876
- const similar = findSimilarKeyword(found);
877
- const suggestion = similar ? `Did you mean '${similar}'?` : `Expected '${expected}'`;
878
- return createRichError("HSP003", `Expected '${expected}' but found '${found}'`, line, column, {
879
- source,
880
- suggestion
881
- });
882
- }
883
- function formatRichError(error) {
884
- const lines = [];
885
- const icon = error.severity === "error" ? "\u274C" : error.severity === "warning" ? "\u26A0\uFE0F" : "\u2139\uFE0F";
886
- lines.push(`${icon} ${error.message}`);
887
- lines.push(` at line ${error.line}, column ${error.column}`);
888
- if (error.context) {
889
- lines.push("");
890
- lines.push(error.context);
891
- }
892
- if (error.suggestion) {
893
- lines.push("");
894
- lines.push(`\u{1F4A1} ${error.suggestion}`);
895
- }
896
- lines.push("");
897
- lines.push(`\u{1F4D6} See: https://holoscript.net/errors/${error.code}`);
898
- return lines.join("\n");
899
- }
900
- function formatRichErrors(errors) {
901
- if (errors.length === 0) {
902
- return "\u2705 No errors found";
903
- }
904
- const lines = [];
905
- const errorCount = errors.filter((e) => e.severity === "error").length;
906
- const warningCount = errors.filter((e) => e.severity === "warning").length;
907
- lines.push(`Found ${errorCount} error(s) and ${warningCount} warning(s):`);
908
- lines.push("");
909
- const displayErrors = errors.slice(0, 10);
910
- for (let i = 0; i < displayErrors.length; i++) {
911
- lines.push(`[${i + 1}/${errors.length}] \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`);
912
- lines.push(formatRichError(displayErrors[i]));
913
- lines.push("");
914
- }
915
- if (errors.length > 10) {
916
- lines.push(`... and ${errors.length - 10} more errors`);
917
- }
918
- return lines.join("\n");
919
- }
920
- function getErrorCodeDocumentation() {
921
- const docs = [];
922
- for (const [code, description] of Object.entries(HSPLUS_ERROR_CODES)) {
923
- let category = "General";
924
- const num = parseInt(code.replace("HSP", ""), 10);
925
- if (num < 100) category = "Syntax";
926
- else if (num < 200) category = "Structure";
927
- else if (num < 300) category = "Traits";
928
- else if (num < 400) category = "Expressions";
929
- else if (num < 500) category = "Imports";
930
- else if (num >= 900) category = "Limits";
931
- docs.push({ code, description, category });
932
- }
933
- return docs;
934
- }
935
-
936
- // src/parser/HoloScriptPlusParser.ts
937
- var Lexer = class {
938
- constructor(source) {
939
- this.pos = 0;
940
- this.line = 1;
941
- this.column = 1;
942
- this.indentStack = [0];
943
- this.tokens = [];
944
- this.pendingDedents = 0;
945
- this.source = source;
946
- }
947
- tokenize() {
948
- while (this.pos < this.source.length) {
949
- while (this.pendingDedents > 0) {
950
- this.tokens.push(this.createToken("DEDENT", ""));
951
- this.pendingDedents--;
952
- }
953
- const char = this.source[this.pos];
954
- if (char === " " || char === " ") {
955
- if (this.column === 1) {
956
- this.handleIndentation();
957
- } else {
958
- this.advance();
959
- }
960
- continue;
961
- }
962
- if (char === "/" && this.peek(1) === "/") {
963
- this.skipLineComment();
964
- continue;
965
- }
966
- if (char === "\n") {
967
- this.advance();
968
- this.tokens.push(this.createToken("NEWLINE", "\n"));
969
- this.line++;
970
- this.column = 1;
971
- continue;
972
- }
973
- if (char === "\r") {
974
- const startOff = this.pos;
975
- this.advance();
976
- if (this.peek() === "\n") {
977
- this.advance();
978
- }
979
- const token = this.createToken("NEWLINE", "\n");
980
- token.offset = startOff;
981
- this.tokens.push(token);
982
- this.line++;
983
- this.column = 1;
984
- continue;
985
- }
986
- if (char === "{") {
987
- this.advance();
988
- this.tokens.push(this.createToken("LBRACE", "{"));
989
- continue;
990
- }
991
- if (char === "}") {
992
- this.advance();
993
- this.tokens.push(this.createToken("RBRACE", "}"));
994
- continue;
995
- }
996
- if (char === "[") {
997
- this.advance();
998
- this.tokens.push(this.createToken("LBRACKET", "["));
999
- continue;
1000
- }
1001
- if (char === "]") {
1002
- this.advance();
1003
- this.tokens.push(this.createToken("RBRACKET", "]"));
1004
- continue;
1005
- }
1006
- if (char === "(") {
1007
- this.advance();
1008
- this.tokens.push(this.createToken("LPAREN", "("));
1009
- continue;
1010
- }
1011
- if (char === ")") {
1012
- this.advance();
1013
- this.tokens.push(this.createToken("RPAREN", ")"));
1014
- continue;
1015
- }
1016
- if (char === ":") {
1017
- this.advance();
1018
- this.tokens.push(this.createToken("COLON", ":"));
1019
- continue;
1020
- }
1021
- if (char === ",") {
1022
- this.advance();
1023
- this.tokens.push(this.createToken("COMMA", ","));
1024
- continue;
1025
- }
1026
- if (char === "@") {
1027
- this.advance();
1028
- this.tokens.push(this.createToken("AT", "@"));
1029
- continue;
1030
- }
1031
- if (char === "#") {
1032
- this.advance();
1033
- this.tokens.push(this.createToken("HASH", "#"));
1034
- continue;
1035
- }
1036
- if (char === ".") {
1037
- if (this.peek(1) === "." && this.peek(2) === ".") {
1038
- const startCol = this.column;
1039
- this.advance();
1040
- this.advance();
1041
- this.advance();
1042
- this.tokens.push(this.createToken("SPREAD", "..."));
1043
- this.tokens[this.tokens.length - 1].column = startCol;
1044
- continue;
1045
- }
1046
- this.advance();
1047
- this.tokens.push(this.createToken("DOT", "."));
1048
- continue;
1049
- }
1050
- if (char === "+") {
1051
- this.advance();
1052
- this.tokens.push(this.createToken("PLUS", "+"));
1053
- continue;
1054
- }
1055
- if (char === "-") {
1056
- if (this.peek(1) === ">") {
1057
- const startCol = this.column;
1058
- this.advance();
1059
- this.advance();
1060
- this.tokens.push(this.createToken("ARROW", "->"));
1061
- this.tokens[this.tokens.length - 1].column = startCol;
1062
- continue;
1063
- }
1064
- this.advance();
1065
- this.tokens.push(this.createToken("MINUS", "-"));
1066
- continue;
1067
- }
1068
- if (char === "*") {
1069
- this.advance();
1070
- this.tokens.push(this.createToken("ASTERISK", "*"));
1071
- continue;
1072
- }
1073
- if (char === "/") {
1074
- if (this.peek(1) === "*") {
1075
- this.skipBlockComment();
1076
- continue;
1077
- }
1078
- if (this.peek(1) === "/") {
1079
- this.skipLineComment();
1080
- continue;
1081
- }
1082
- this.advance();
1083
- this.tokens.push(this.createToken("SLASH", "/"));
1084
- continue;
1085
- }
1086
- if (char === "%") {
1087
- this.advance();
1088
- this.tokens.push(this.createToken("PERCENT", "%"));
1089
- continue;
1090
- }
1091
- if (char === "!") {
1092
- if (this.peek(1) === "=") {
1093
- const startCol = this.column;
1094
- const startOff = this.pos;
1095
- this.advance();
1096
- this.advance();
1097
- this.tokens.push(this.createToken("NOT_EQUALS", "!="));
1098
- this.tokens[this.tokens.length - 1].column = startCol;
1099
- this.tokens[this.tokens.length - 1].offset = startOff;
1100
- continue;
1101
- }
1102
- this.advance();
1103
- this.tokens.push(this.createToken("EXCLAMATION", "!"));
1104
- continue;
1105
- }
1106
- if (char === "=") {
1107
- if (this.peek(1) === ">") {
1108
- const startCol = this.column;
1109
- const startOff = this.pos;
1110
- this.advance();
1111
- this.advance();
1112
- this.tokens.push(this.createToken("ARROW", "=>"));
1113
- this.tokens[this.tokens.length - 1].column = startCol;
1114
- this.tokens[this.tokens.length - 1].offset = startOff;
1115
- continue;
1116
- }
1117
- if (this.peek(1) === "=") {
1118
- const startCol = this.column;
1119
- const startOff = this.pos;
1120
- this.advance();
1121
- this.advance();
1122
- this.tokens.push(this.createToken("DOUBLE_EQUALS", "=="));
1123
- this.tokens[this.tokens.length - 1].column = startCol;
1124
- this.tokens[this.tokens.length - 1].offset = startOff;
1125
- continue;
1126
- }
1127
- this.advance();
1128
- this.tokens.push(this.createToken("EQUALS", "="));
1129
- continue;
1130
- }
1131
- if (char === "<") {
1132
- if (this.peek(1) === "=") {
1133
- const startCol = this.column;
1134
- const startOff = this.pos;
1135
- this.advance();
1136
- this.advance();
1137
- this.tokens.push(this.createToken("LESS_EQUAL", "<="));
1138
- this.tokens[this.tokens.length - 1].column = startCol;
1139
- this.tokens[this.tokens.length - 1].offset = startOff;
1140
- continue;
1141
- }
1142
- this.advance();
1143
- this.tokens.push(this.createToken("LESS_THAN", "<"));
1144
- continue;
1145
- }
1146
- if (char === ">") {
1147
- if (this.peek(1) === "=") {
1148
- const startCol = this.column;
1149
- const startOff = this.pos;
1150
- this.advance();
1151
- this.advance();
1152
- this.tokens.push(this.createToken("GREATER_EQUAL", ">="));
1153
- this.tokens[this.tokens.length - 1].column = startCol;
1154
- this.tokens[this.tokens.length - 1].offset = startOff;
1155
- continue;
1156
- }
1157
- this.advance();
1158
- this.tokens.push(this.createToken("GREATER_THAN", ">"));
1159
- continue;
1160
- }
1161
- if (char === "-") {
1162
- if (this.peek(1) === ">") {
1163
- const startCol = this.column;
1164
- this.advance();
1165
- this.advance();
1166
- this.tokens.push(this.createToken("ARROW", "->"));
1167
- this.tokens[this.tokens.length - 1].column = startCol;
1168
- continue;
1169
- }
1170
- }
1171
- if (char === "&") {
1172
- if (this.peek(1) === "&") {
1173
- const startCol = this.column;
1174
- const startOff = this.pos;
1175
- this.advance();
1176
- this.advance();
1177
- this.tokens.push(this.createToken("AND", "&&"));
1178
- this.tokens[this.tokens.length - 1].column = startCol;
1179
- this.tokens[this.tokens.length - 1].offset = startOff;
1180
- continue;
1181
- }
1182
- this.advance();
1183
- continue;
1184
- }
1185
- if (char === "|") {
1186
- if (this.peek(1) === "|") {
1187
- const startCol = this.column;
1188
- const startOff = this.pos;
1189
- this.advance();
1190
- this.advance();
1191
- this.tokens.push(this.createToken("OR", "||"));
1192
- this.tokens[this.tokens.length - 1].column = startCol;
1193
- this.tokens[this.tokens.length - 1].offset = startOff;
1194
- continue;
1195
- }
1196
- this.advance();
1197
- this.tokens.push(this.createToken("PIPE", "|"));
1198
- continue;
1199
- }
1200
- if (char === '"' || char === "'") {
1201
- this.tokens.push(this.readString(char));
1202
- continue;
1203
- }
1204
- if (this.isDigit(char) || char === "-" && this.isDigit(this.peek(1))) {
1205
- this.tokens.push(this.readNumber());
1206
- continue;
1207
- }
1208
- if (char === "?") {
1209
- if (this.peek(1) === "?") {
1210
- if (this.peek(2) === "=") {
1211
- const startCol2 = this.column;
1212
- const startOff2 = this.pos;
1213
- this.advance();
1214
- this.advance();
1215
- this.advance();
1216
- this.tokens.push(this.createToken("NULL_COALESCE_ASSIGN", "??="));
1217
- this.tokens[this.tokens.length - 1].column = startCol2;
1218
- this.tokens[this.tokens.length - 1].offset = startOff2;
1219
- continue;
1220
- }
1221
- const startCol = this.column;
1222
- const startOff = this.pos;
1223
- this.advance();
1224
- this.advance();
1225
- this.tokens.push(this.createToken("NULL_COALESCE", "??"));
1226
- this.tokens[this.tokens.length - 1].column = startCol;
1227
- this.tokens[this.tokens.length - 1].offset = startOff;
1228
- continue;
1229
- }
1230
- if (this.peek(1) === ".") {
1231
- const startCol = this.column;
1232
- const startOff = this.pos;
1233
- this.advance();
1234
- this.advance();
1235
- this.tokens.push(this.createToken("OPTIONAL_DOT", "?."));
1236
- this.tokens[this.tokens.length - 1].column = startCol;
1237
- this.tokens[this.tokens.length - 1].offset = startOff;
1238
- continue;
1239
- }
1240
- this.advance();
1241
- this.tokens.push(this.createToken("QUESTION", "?"));
1242
- continue;
1243
- }
1244
- if (char === "`") {
1245
- this.tokens.push(this.readTemplateString());
1246
- continue;
1247
- }
1248
- if (this.isIdentifierStart(char)) {
1249
- this.tokens.push(this.readIdentifier());
1250
- continue;
1251
- }
1252
- this.advance();
1253
- }
1254
- while (this.indentStack.length > 1) {
1255
- this.tokens.push(this.createToken("DEDENT", ""));
1256
- this.indentStack.pop();
1257
- }
1258
- this.tokens.push(this.createToken("EOF", ""));
1259
- return this.tokens;
1260
- }
1261
- advance() {
1262
- const char = this.source[this.pos];
1263
- this.pos++;
1264
- this.column++;
1265
- return char;
1266
- }
1267
- peek(offset = 0) {
1268
- const pos = this.pos + offset;
1269
- return pos < this.source.length ? this.source[pos] : "";
1270
- }
1271
- createToken(type, value) {
1272
- const token = {
1273
- type,
1274
- value,
1275
- line: this.line,
1276
- column: this.column - (value.length || 0),
1277
- offset: this.pos - (value.length || 0)
1278
- };
1279
- return token;
1280
- }
1281
- handleIndentation() {
1282
- let indent = 0;
1283
- while (this.peek() === " " || this.peek() === " ") {
1284
- indent += this.peek() === " " ? 4 : 1;
1285
- this.advance();
1286
- }
1287
- if (this.peek() === "\n" || this.peek() === "\r") {
1288
- return;
1289
- }
1290
- const currentIndent = this.indentStack[this.indentStack.length - 1];
1291
- if (indent > currentIndent) {
1292
- this.indentStack.push(indent);
1293
- this.tokens.push(this.createToken("INDENT", ""));
1294
- } else if (indent < currentIndent) {
1295
- while (this.indentStack.length > 1 && indent < this.indentStack[this.indentStack.length - 1]) {
1296
- this.indentStack.pop();
1297
- this.pendingDedents++;
1298
- }
1299
- }
1300
- }
1301
- skipLineComment() {
1302
- while (this.peek() !== "\n" && this.pos < this.source.length) {
1303
- this.advance();
1304
- }
1305
- }
1306
- skipBlockComment() {
1307
- this.advance();
1308
- this.advance();
1309
- while (this.pos < this.source.length) {
1310
- if (this.peek() === "*" && this.peek(1) === "/") {
1311
- this.advance();
1312
- this.advance();
1313
- break;
1314
- }
1315
- if (this.peek() === "\n") {
1316
- this.line++;
1317
- this.column = 0;
1318
- }
1319
- this.advance();
1320
- }
1321
- }
1322
- readString(quote) {
1323
- const startLine = this.line;
1324
- const startColumn = this.column;
1325
- this.advance();
1326
- let value = "";
1327
- while (this.peek() !== quote && this.pos < this.source.length) {
1328
- if (this.peek() === "\\") {
1329
- this.advance();
1330
- const escaped = this.advance();
1331
- switch (escaped) {
1332
- case "n":
1333
- value += "\n";
1334
- break;
1335
- case "t":
1336
- value += " ";
1337
- break;
1338
- case "r":
1339
- value += "\r";
1340
- break;
1341
- case "\\":
1342
- value += "\\";
1343
- break;
1344
- case '"':
1345
- value += '"';
1346
- break;
1347
- case "'":
1348
- value += "'";
1349
- break;
1350
- default:
1351
- value += escaped;
1352
- }
1353
- } else if (this.peek() === "\n") {
1354
- this.line++;
1355
- this.column = 0;
1356
- value += this.advance();
1357
- } else {
1358
- value += this.advance();
1359
- }
1360
- }
1361
- this.advance();
1362
- const token = {
1363
- type: "STRING",
1364
- value,
1365
- line: startLine,
1366
- column: startColumn,
1367
- offset: this.pos - (value.length + 2)
1368
- // approximation for start of string
1369
- };
1370
- return token;
1371
- }
1372
- readTemplateString() {
1373
- const startLine = this.line;
1374
- const startColumn = this.column;
1375
- const startOff = this.pos;
1376
- this.advance();
1377
- let value = "";
1378
- let braceDepth = 0;
1379
- while (this.pos < this.source.length) {
1380
- const c = this.source[this.pos];
1381
- if (c === "`" && braceDepth === 0) {
1382
- this.advance();
1383
- break;
1384
- }
1385
- if (c === "$" && this.peek(1) === "{") {
1386
- braceDepth++;
1387
- value += "${";
1388
- this.advance();
1389
- this.advance();
1390
- continue;
1391
- }
1392
- if (c === "{" && braceDepth > 0) {
1393
- braceDepth++;
1394
- value += c;
1395
- this.advance();
1396
- continue;
1397
- }
1398
- if (c === "}" && braceDepth > 0) {
1399
- braceDepth--;
1400
- value += c;
1401
- this.advance();
1402
- continue;
1403
- }
1404
- if (c === "\n") {
1405
- this.line++;
1406
- this.column = 0;
1407
- }
1408
- value += c;
1409
- this.advance();
1410
- }
1411
- return {
1412
- type: "TEMPLATE_STRING",
1413
- value,
1414
- line: startLine,
1415
- column: startColumn,
1416
- offset: startOff
1417
- };
1418
- }
1419
- readNumber() {
1420
- const startColumn = this.column;
1421
- let value = "";
1422
- if (this.peek() === "-") {
1423
- value += this.advance();
1424
- }
1425
- while (this.isDigit(this.peek())) {
1426
- value += this.advance();
1427
- }
1428
- if (this.peek() === "." && this.isDigit(this.peek(1))) {
1429
- value += this.advance();
1430
- while (this.isDigit(this.peek())) {
1431
- value += this.advance();
1432
- }
1433
- }
1434
- if (this.peek() === "e" || this.peek() === "E") {
1435
- value += this.advance();
1436
- if (this.peek() === "+" || this.peek() === "-") {
1437
- value += this.advance();
1438
- }
1439
- while (this.isDigit(this.peek())) {
1440
- value += this.advance();
1441
- }
1442
- }
1443
- while (this.isAlpha(this.peek()) || this.peek() === "%") {
1444
- value += this.advance();
1445
- }
1446
- const token = {
1447
- type: "NUMBER",
1448
- value,
1449
- line: this.line,
1450
- column: startColumn,
1451
- offset: this.pos - value.length
1452
- };
1453
- return token;
1454
- }
1455
- readExpression() {
1456
- const startLine = this.line;
1457
- const startColumn = this.column;
1458
- this.advance();
1459
- this.advance();
1460
- let value = "";
1461
- let braceDepth = 1;
1462
- while (braceDepth > 0 && this.pos < this.source.length) {
1463
- if (this.peek() === "{") {
1464
- braceDepth++;
1465
- } else if (this.peek() === "}") {
1466
- braceDepth--;
1467
- if (braceDepth === 0) {
1468
- break;
1469
- }
1470
- }
1471
- if (this.peek() === "\n") {
1472
- this.line++;
1473
- this.column = 0;
1474
- }
1475
- value += this.advance();
1476
- }
1477
- this.advance();
1478
- return {
1479
- type: "EXPRESSION",
1480
- value: value.trim(),
1481
- line: startLine,
1482
- column: startColumn,
1483
- offset: this.pos - (value.length + 3)
1484
- // ${...}
1485
- };
1486
- }
1487
- readIdentifier() {
1488
- const startColumn = this.column;
1489
- let value = "";
1490
- while (this.isIdentifierPart(this.peek())) {
1491
- value += this.advance();
1492
- }
1493
- if (value === "true" || value === "false") {
1494
- return {
1495
- type: "BOOLEAN",
1496
- value,
1497
- line: this.line,
1498
- column: startColumn,
1499
- offset: this.pos - value.length
1500
- };
1501
- }
1502
- if (value === "null" || value === "none") {
1503
- return {
1504
- type: "NULL",
1505
- value,
1506
- line: this.line,
1507
- column: startColumn,
1508
- offset: this.pos - value.length
1509
- };
1510
- }
1511
- const token = {
1512
- type: "IDENTIFIER",
1513
- value,
1514
- line: this.line,
1515
- column: startColumn,
1516
- offset: this.pos - value.length
1517
- };
1518
- switch (value) {
1519
- case "state_machine":
1520
- token.type = "STATE_MACHINE";
1521
- break;
1522
- case "initial":
1523
- token.type = "INITIAL";
1524
- break;
1525
- case "state":
1526
- token.type = "STATE";
1527
- break;
1528
- case "on_entry":
1529
- token.type = "ON_ENTRY";
1530
- break;
1531
- case "on_exit":
1532
- token.type = "ON_EXIT";
1533
- break;
1534
- case "transition":
1535
- token.type = "TRANSITION";
1536
- break;
1537
- case "match":
1538
- token.type = "MATCH";
1539
- break;
1540
- case "on_error":
1541
- token.type = "ON_ERROR";
1542
- break;
1543
- case "assert":
1544
- token.type = "ASSERT";
1545
- break;
1546
- case "_":
1547
- token.type = "UNDERSCORE";
1548
- break;
1549
- }
1550
- return token;
1551
- }
1552
- isDigit(char) {
1553
- return char >= "0" && char <= "9";
1554
- }
1555
- isAlpha(char) {
1556
- return char >= "a" && char <= "z" || char >= "A" && char <= "Z";
1557
- }
1558
- isIdentifierStart(char) {
1559
- return this.isAlpha(char) || char === "_" || char === "$";
1560
- }
1561
- isIdentifierPart(char) {
1562
- return this.isIdentifierStart(char) || this.isDigit(char) || char === "-";
1563
- }
1564
- };
1565
- var HoloScriptPlusParser = class {
1566
- constructor(options = {}) {
1567
- this.tokens = [];
1568
- this.pos = 0;
1569
- this.source = "";
1570
- this.errors = [];
1571
- this.warnings = [];
1572
- this.imports = [];
1573
- this.hasState = false;
1574
- this.hasVRTraits = false;
1575
- this.hasControlFlow = false;
1576
- this.compiledExpressions = /* @__PURE__ */ new Map();
1577
- this.errorRecovery = new chunkGVUR45UF_cjs.ErrorRecovery();
1578
- this.options = {
1579
- enableVRTraits: true,
1580
- enableTypeScriptImports: true,
1581
- strict: false,
1582
- ...options
1583
- };
1584
- }
1585
- /**
1586
- * Get quick fixes for all errors in the last parse
1587
- * Useful for IDE integrations and LSP
1588
- */
1589
- getQuickFixes() {
1590
- const fixes = /* @__PURE__ */ new Map();
1591
- for (const error of this.errors) {
1592
- const errorFixes = chunkGVUR45UF_cjs.generateQuickFixes(
1593
- {
1594
- code: error.code,
1595
- message: error.message,
1596
- line: error.line,
1597
- column: error.column,
1598
- source: this.source
1599
- },
1600
- this.source
1601
- );
1602
- if (errorFixes.length > 0) {
1603
- fixes.set(error.line, errorFixes);
1604
- }
1605
- }
1606
- return fixes;
1607
- }
1608
- /**
1609
- * Get enriched errors with additional suggestions from ErrorRecovery
1610
- */
1611
- getEnrichedErrors() {
1612
- return this.errors.map(
1613
- (error) => chunkGVUR45UF_cjs.enrichErrorWithSuggestions(
1614
- {
1615
- code: error.code,
1616
- message: error.message,
1617
- line: error.line,
1618
- column: error.column,
1619
- source: this.source
1620
- },
1621
- this.source
1622
- )
1623
- );
1624
- }
1625
- parse(source) {
1626
- this.source = source;
1627
- this.errors = [];
1628
- this.warnings = [];
1629
- this.imports = [];
1630
- this.hasState = false;
1631
- this.hasVRTraits = false;
1632
- this.hasControlFlow = false;
1633
- this.compiledExpressions = /* @__PURE__ */ new Map();
1634
- this.pos = 0;
1635
- this.errorRecovery.clear();
1636
- const lexer = new Lexer(source);
1637
- this.tokens = lexer.tokenize();
1638
- const root = this.parseDocument();
1639
- return this.buildResult(root);
1640
- }
1641
- /**
1642
- * Performs an incremental parse using cached nodes for unchanged chunks
1643
- */
1644
- parseIncremental(source, cache = globalParseCache) {
1645
- this.source = source;
1646
- this.errors = [];
1647
- this.warnings = [];
1648
- this.imports = [];
1649
- this.hasState = false;
1650
- this.hasVRTraits = false;
1651
- this.hasControlFlow = false;
1652
- this.compiledExpressions = /* @__PURE__ */ new Map();
1653
- const chunks = ChunkDetector.detect(source);
1654
- const topLevelNodes = [];
1655
- const globalDirectives = [];
1656
- for (const chunk of chunks) {
1657
- const hash = ParseCache.hash(chunk.content);
1658
- const cachedNode = cache.get(chunk.id, hash);
1659
- if (cachedNode) {
1660
- topLevelNodes.push(cachedNode);
1661
- } else {
1662
- const chunkResult = this.parse(chunk.content);
1663
- const chunkAst = chunkResult.ast;
1664
- const chunkFeatures = chunkResult.features;
1665
- if (chunkAst?.root) {
1666
- const node = chunkAst.root;
1667
- this.offsetNodeLoc(node, chunk.startLine - 1);
1668
- topLevelNodes.push(node);
1669
- cache.set(chunk.id, hash, node);
1670
- this.hasState = this.hasState || !!chunkFeatures?.state;
1671
- this.hasVRTraits = this.hasVRTraits || !!chunkFeatures?.vrTraits;
1672
- this.hasControlFlow = this.hasControlFlow || !!chunkFeatures?.loops || !!chunkFeatures?.conditionals;
1673
- this.imports.push(...chunkAst.imports);
1674
- }
1675
- this.errors.push(...chunkResult.errors);
1676
- this.warnings.push(...chunkResult.warnings || []);
1677
- }
1678
- }
1679
- const root = {
1680
- type: "fragment",
1681
- id: "root",
1682
- properties: {},
1683
- directives: globalDirectives,
1684
- children: topLevelNodes,
1685
- traits: /* @__PURE__ */ new Map(),
1686
- loc: {
1687
- start: { line: 1, column: 1 },
1688
- end: { line: chunks.length > 0 ? chunks[chunks.length - 1].endLine : 1, column: 1 }
1689
- },
1690
- body: topLevelNodes
1691
- };
1692
- const result = this.buildResult(root);
1693
- return result;
1694
- }
1695
- buildResult(root) {
1696
- const isFragment = root.type === "fragment";
1697
- const directives = root.directives || [];
1698
- let version;
1699
- const migrations = [];
1700
- for (const d of directives) {
1701
- if (d.type === "version") {
1702
- version = d.version;
1703
- } else if (d.type === "migrate") {
1704
- migrations.push({
1705
- type: "Migration",
1706
- fromVersion: d.fromVersion,
1707
- body: d.body
1708
- });
1709
- }
1710
- }
1711
- if (version === void 0) version = "1.0";
1712
- const ast = {
1713
- type: "Program",
1714
- id: "root",
1715
- properties: isFragment ? root.properties || {} : {},
1716
- directives,
1717
- children: isFragment ? root.children || [] : [root],
1718
- traits: isFragment ? root.traits || /* @__PURE__ */ new Map() : /* @__PURE__ */ new Map(),
1719
- loc: root.loc,
1720
- body: isFragment ? root.children || [] : [root],
1721
- version,
1722
- migrations: migrations.length > 0 ? migrations : void 0,
1723
- root,
1724
- imports: this.imports,
1725
- hasState: this.hasState,
1726
- hasVRTraits: this.hasVRTraits,
1727
- hasControlFlow: this.hasControlFlow
1728
- };
1729
- return {
1730
- success: this.errors.length === 0,
1731
- ast,
1732
- compiledExpressions: this.compiledExpressions,
1733
- requiredCompanions: this.imports.map((i) => i.path),
1734
- features: {
1735
- state: this.hasState,
1736
- vrTraits: this.hasVRTraits,
1737
- loops: this.hasControlFlow,
1738
- conditionals: this.hasControlFlow,
1739
- lifecycleHooks: (root.directives || []).some((d) => d.type === "lifecycle")
1740
- },
1741
- warnings: this.warnings,
1742
- errors: this.errors
1743
- };
1744
- }
1745
- offsetNodeLoc(node, lineOffset) {
1746
- if (node.loc) {
1747
- if (node.loc.start) node.loc.start.line += lineOffset;
1748
- if (node.loc.end) node.loc.end.line += lineOffset;
1749
- }
1750
- if (node.children) {
1751
- node.children.forEach((child) => this.offsetNodeLoc(child, lineOffset));
1752
- }
1753
- if (node.body && Array.isArray(node.body)) {
1754
- node.body.forEach((child) => this.offsetNodeLoc(child, lineOffset));
1755
- }
1756
- }
1757
- parseDocument() {
1758
- this.skipNewlines();
1759
- const topLevelNodes = [];
1760
- const globalDirectives = [];
1761
- while (!this.check("EOF")) {
1762
- const currentDirectives = [];
1763
- try {
1764
- while (this.check("AT")) {
1765
- const directive = this.parseDirective();
1766
- if (directive) {
1767
- const { type } = directive;
1768
- if (type === "version" || type === "migrate" || type === "import" || type === "export") {
1769
- globalDirectives.push(directive);
1770
- if (type === "export") {
1771
- currentDirectives.push(directive);
1772
- }
1773
- } else {
1774
- currentDirectives.push(directive);
1775
- }
1776
- }
1777
- this.skipNewlines();
1778
- }
1779
- const isNodeStart = this.check("IDENTIFIER") || this.check("STATE_MACHINE") || this.check("STATE") || this.check("TRANSITION") || this.check("INITIAL");
1780
- if (isNodeStart) {
1781
- const node = this.parseNode();
1782
- const existingDirectives = node.directives || [];
1783
- node.directives = [...currentDirectives, ...existingDirectives];
1784
- if (node.type === "template") {
1785
- for (const d of currentDirectives) {
1786
- if (d.type === "version") {
1787
- node.version = d.version;
1788
- } else if (d.type === "migrate") {
1789
- if (!node.migrations) node.migrations = [];
1790
- node.migrations.push({
1791
- type: "Migration",
1792
- fromVersion: d.fromVersion,
1793
- body: d.body
1794
- });
1795
- }
1796
- }
1797
- }
1798
- topLevelNodes.push(node);
1799
- } else {
1800
- if (currentDirectives.length > 0) {
1801
- if (this.check("EOF")) {
1802
- globalDirectives.push(...currentDirectives);
1803
- } else {
1804
- this.error(
1805
- `Expected node after directives, got ${this.current().type}. Valid nodes: orb, template, logic, object, composition, scene, group`,
1806
- "HSP003"
1807
- );
1808
- globalDirectives.push(...currentDirectives);
1809
- }
1810
- } else if (!this.check("EOF")) {
1811
- this.error(
1812
- `Unexpected token ${this.current().type} "${this.current().value}" at top level. Expected: composition, object, template, logic, or @directive`,
1813
- "HSP001"
1814
- );
1815
- throw new Error("ParseError");
1816
- }
1817
- }
1818
- if (this.check("IDENTIFIER") && this.current().value === "connect") {
1819
- const connection = this.parseConnectionStatement();
1820
- const node = {
1821
- type: "connection",
1822
- properties: connection,
1823
- directives: [],
1824
- children: [],
1825
- traits: /* @__PURE__ */ new Map(),
1826
- loc: {
1827
- start: { line: this.current().line, column: 0 },
1828
- end: { line: this.current().line, column: 0 }
1829
- }
1830
- };
1831
- topLevelNodes.push(node);
1832
- }
1833
- } catch (e) {
1834
- const errorMessage = e instanceof Error ? e.message : String(e);
1835
- if (errorMessage !== "ParseError" && errorMessage !== "Unexpected token") {
1836
- console.error(e);
1837
- }
1838
- this.synchronize();
1839
- }
1840
- this.skipNewlines();
1841
- }
1842
- if (topLevelNodes.length === 1 && globalDirectives.length === 0) {
1843
- return topLevelNodes[0];
1844
- }
1845
- return {
1846
- type: "fragment",
1847
- id: "root",
1848
- properties: {},
1849
- directives: globalDirectives,
1850
- children: topLevelNodes,
1851
- traits: /* @__PURE__ */ new Map(),
1852
- loc: {
1853
- start: { line: 1, column: 1 },
1854
- end: { line: this.current().line, column: this.current().column }
1855
- },
1856
- body: topLevelNodes
1857
- };
1858
- }
1859
- parseNode() {
1860
- const startToken = this.current();
1861
- const typeToken = this.match([
1862
- "IDENTIFIER",
1863
- "STATE_MACHINE",
1864
- "STATE",
1865
- "TRANSITION",
1866
- "INITIAL",
1867
- "ON_ENTRY",
1868
- "ON_EXIT"
1869
- ]) || this.expect("IDENTIFIER", "Expected element type");
1870
- const type = typeToken.value;
1871
- if (type === "template") {
1872
- const templateName = this.expect("STRING", "Expected template name").value;
1873
- const templateBody = this.parseBlockContent();
1874
- let version;
1875
- const migrations = [];
1876
- const directives2 = [];
1877
- const children2 = [];
1878
- for (const [key, value] of Object.entries(templateBody)) {
1879
- if (key === "@version") {
1880
- const v = value;
1881
- if (v.type === "version") version = v.version;
1882
- delete templateBody[key];
1883
- } else if (key === "@migrate") {
1884
- const m = value;
1885
- if (m.type === "migrate") {
1886
- migrations.push({
1887
- type: "Migration",
1888
- fromVersion: m.fromVersion,
1889
- body: m.body
1890
- });
1891
- }
1892
- delete templateBody[key];
1893
- } else if (key.startsWith("@")) {
1894
- directives2.push(value);
1895
- delete templateBody[key];
1896
- } else if (typeof value === "object" && value && "type" in value) {
1897
- children2.push(value);
1898
- delete templateBody[key];
1899
- }
1900
- }
1901
- return {
1902
- type: "template",
1903
- name: templateName,
1904
- properties: templateBody,
1905
- // Now contains only true properties
1906
- version,
1907
- migrations,
1908
- directives: directives2,
1909
- children: children2,
1910
- traits: /* @__PURE__ */ new Map(),
1911
- loc: {
1912
- start: { line: startToken.line, column: startToken.column },
1913
- end: { line: this.current().line, column: this.current().column }
1914
- }
1915
- };
1916
- }
1917
- if (type === "logic") {
1918
- const logicBody = this.parseLogicBlock();
1919
- return {
1920
- type: "logic",
1921
- name: "logic",
1922
- id: "logic",
1923
- properties: {},
1924
- directives: [],
1925
- children: [],
1926
- traits: /* @__PURE__ */ new Map(),
1927
- body: logicBody,
1928
- loc: {
1929
- start: { line: startToken.line, column: startToken.column },
1930
- end: { line: this.current().line, column: this.current().column }
1931
- }
1932
- };
1933
- }
1934
- if ([
1935
- "module",
1936
- "script",
1937
- "struct",
1938
- "enum",
1939
- "class",
1940
- "interface",
1941
- "action",
1942
- "function",
1943
- "async",
1944
- "on"
1945
- ].includes(type)) {
1946
- let name = "anonymous";
1947
- if (this.check("IDENTIFIER")) {
1948
- name = this.advance().value;
1949
- } else if (this.check("STRING")) {
1950
- name = this.advance().value;
1951
- }
1952
- while (this.check("DOT")) {
1953
- this.advance();
1954
- if (this.check("IDENTIFIER")) this.advance();
1955
- }
1956
- if (this.check("LPAREN")) {
1957
- this.skipParens();
1958
- }
1959
- let bodyContent = "";
1960
- if (this.check("LBRACE")) {
1961
- bodyContent = this.parseRawBlock();
1962
- }
1963
- return {
1964
- type,
1965
- name,
1966
- id: name,
1967
- properties: {},
1968
- directives: [],
1969
- children: [],
1970
- traits: /* @__PURE__ */ new Map(),
1971
- body: bodyContent,
1972
- loc: {
1973
- start: { line: startToken.line, column: startToken.column },
1974
- end: { line: this.current().line, column: this.current().column }
1975
- }
1976
- };
1977
- }
1978
- if (startToken.type === "STATE_MACHINE" || type === "state_machine") {
1979
- return this.parseStateMachine();
1980
- }
1981
- if (type === "on_error" || startToken.type === "ON_ERROR") {
1982
- return this.parseOnErrorNode();
1983
- }
1984
- if (type === "assert" || startToken.type === "ASSERT") {
1985
- return this.parseAssertNode();
1986
- }
1987
- if (type === "environment") {
1988
- const envBody = this.parseEnvironmentBlock();
1989
- return {
1990
- type: "environment",
1991
- properties: envBody.properties,
1992
- directives: envBody.directives,
1993
- children: [],
1994
- traits: /* @__PURE__ */ new Map(),
1995
- loc: {
1996
- start: { line: startToken.line, column: startToken.column },
1997
- end: { line: this.current().line, column: this.current().column }
1998
- }
1999
- };
2000
- }
2001
- if (type === "composition") {
2002
- let id2;
2003
- if (this.check("HASH")) {
2004
- this.advance();
2005
- id2 = this.expect("IDENTIFIER", "Expected ID after #").value;
2006
- }
2007
- if (this.check("STRING")) {
2008
- id2 = this.advance().value;
2009
- }
2010
- if (this.check("IDENTIFIER")) {
2011
- id2 = this.advance().value;
2012
- }
2013
- const compBody = this.parseCompositionBlock();
2014
- return {
2015
- type: "composition",
2016
- name: id2,
2017
- id: id2,
2018
- properties: compBody.properties || {},
2019
- directives: [],
2020
- children: compBody.children,
2021
- traits: /* @__PURE__ */ new Map(),
2022
- body: compBody,
2023
- loc: {
2024
- start: { line: startToken.line, column: startToken.column },
2025
- end: { line: this.current().line, column: this.current().column }
2026
- }
2027
- };
2028
- }
2029
- let id;
2030
- let templateRef;
2031
- if (this.check("HASH")) {
2032
- this.advance();
2033
- id = this.expect("IDENTIFIER", "Expected ID after #").value;
2034
- }
2035
- if (this.check("STRING")) {
2036
- id = this.advance().value;
2037
- }
2038
- if (this.check("IDENTIFIER") && this.current().value !== "using") {
2039
- id = this.advance().value;
2040
- }
2041
- if (this.check("LPAREN")) {
2042
- this.skipParens();
2043
- }
2044
- if (this.check("IDENTIFIER") && this.current().value === "using") {
2045
- this.advance();
2046
- templateRef = this.expect("STRING", "Expected template name after using").value;
2047
- }
2048
- if (this.check("COLON")) {
2049
- this.advance();
2050
- if (this.check("IDENTIFIER")) this.advance();
2051
- if (this.check("LBRACKET")) {
2052
- this.advance();
2053
- if (this.check("RBRACKET")) this.advance();
2054
- }
2055
- }
2056
- const properties = {};
2057
- const children = [];
2058
- const directives = [];
2059
- const traits = /* @__PURE__ */ new Map();
2060
- if (templateRef) {
2061
- properties.__templateRef = templateRef;
2062
- }
2063
- while (!this.check("LBRACE") && !this.check("EOF")) {
2064
- try {
2065
- if (this.check("NEWLINE")) {
2066
- this.skipNewlines();
2067
- if (this.check("LBRACE")) break;
2068
- if (!this.check("AT")) {
2069
- if (this.check("EOF")) break;
2070
- }
2071
- }
2072
- if (this.check("AT")) {
2073
- const directive = this.parseDirective();
2074
- if (directive) {
2075
- if (directive.type === "trait") {
2076
- traits.set(directive.name, directive.config);
2077
- this.hasVRTraits = true;
2078
- directives.push(directive);
2079
- } else {
2080
- directives.push(directive);
2081
- }
2082
- }
2083
- } else if (this.check("SPREAD")) {
2084
- const startToken2 = this.advance();
2085
- const targetExpr = this.parseUnary();
2086
- let target;
2087
- if (typeof targetExpr === "object" && targetExpr && "__ref" in targetExpr) {
2088
- target = targetExpr.__ref;
2089
- } else if (typeof targetExpr === "string") {
2090
- target = targetExpr;
2091
- } else {
2092
- this.error(
2093
- "Expected identifier or member expression after spread operator (...)",
2094
- "HSP002"
2095
- );
2096
- target = "unknown";
2097
- }
2098
- children.push({
2099
- type: "spread",
2100
- target,
2101
- loc: {
2102
- start: { line: startToken2.line, column: startToken2.column },
2103
- end: { line: this.current().line, column: this.current().column }
2104
- }
2105
- });
2106
- } else if (this.check("IDENTIFIER")) {
2107
- const key = this.advance().value;
2108
- let value = true;
2109
- if (this.check("COLON")) {
2110
- this.advance();
2111
- value = this.parseValue();
2112
- }
2113
- properties[key] = value;
2114
- } else {
2115
- if (!this.check("LBRACE")) {
2116
- this.error(
2117
- `Unexpected token in properties: ${this.current().type}. Expected property name, @directive, or spread (...)`,
2118
- "HSP101"
2119
- );
2120
- this.synchronizeProperty();
2121
- }
2122
- }
2123
- } catch (e) {
2124
- const errorMessage = e instanceof Error ? e.message : String(e);
2125
- if (errorMessage !== "ParseError") console.error(e);
2126
- this.synchronizeProperty();
2127
- }
2128
- }
2129
- if (this.check("LBRACE")) {
2130
- this.advance();
2131
- this.skipNewlines();
2132
- while (!this.check("RBRACE") && !this.check("EOF")) {
2133
- try {
2134
- this.skipNewlines();
2135
- if (this.check("RBRACE") || this.check("EOF")) break;
2136
- if (this.check("AT")) {
2137
- const directive = this.parseDirective();
2138
- if (directive) {
2139
- if (directive.type === "trait") {
2140
- traits.set(directive.name, directive.config);
2141
- this.hasVRTraits = true;
2142
- }
2143
- directives.push(directive);
2144
- }
2145
- } else if (this.check("SPREAD")) {
2146
- const startToken2 = this.advance();
2147
- const targetExpr = this.parseUnary();
2148
- let target;
2149
- if (typeof targetExpr === "object" && targetExpr && "__ref" in targetExpr) {
2150
- target = targetExpr.__ref;
2151
- } else if (typeof targetExpr === "string") {
2152
- target = targetExpr;
2153
- } else {
2154
- this.error(
2155
- "Expected identifier or member expression after spread operator (...)",
2156
- "HSP002"
2157
- );
2158
- target = "unknown";
2159
- }
2160
- const spreadNode = {
2161
- type: "spread",
2162
- target,
2163
- loc: {
2164
- start: { line: startToken2.line, column: startToken2.column },
2165
- end: { line: this.current().line, column: this.current().column }
2166
- }
2167
- };
2168
- children.push(spreadNode);
2169
- const key = "__spread_" + target;
2170
- properties[key] = spreadNode;
2171
- } else {
2172
- const token = this.current();
2173
- const isKeyToken = token.type === "IDENTIFIER" || token.type === "STRING" || token.type === "STATE" || token.type === "STATE_MACHINE" || token.type === "INITIAL" || token.type === "ON_ENTRY" || token.type === "ON_EXIT" || token.type === "TRANSITION";
2174
- if (isKeyToken) {
2175
- const saved = this.pos;
2176
- const name = this.advance().value;
2177
- const childNodeKeywords = [
2178
- "logic",
2179
- "template",
2180
- "environment",
2181
- "state",
2182
- "object",
2183
- "composition",
2184
- "system",
2185
- "core_config",
2186
- "narrative",
2187
- "quest",
2188
- "objective",
2189
- "dialogue",
2190
- "choice",
2191
- "visual_metadata",
2192
- "spatial_group",
2193
- "scene",
2194
- "group",
2195
- "module",
2196
- "struct",
2197
- "orb",
2198
- "on_error",
2199
- "assert",
2200
- "transition",
2201
- "on_entry",
2202
- "on_exit"
2203
- ];
2204
- if (name === "transition" && this.check("STRING")) {
2205
- const event = this.advance().value;
2206
- if (this.check("ARROW")) {
2207
- this.advance();
2208
- const targetState = this.expect("STRING", "Expected target state string").value;
2209
- let block = {};
2210
- if (this.check("LBRACE")) {
2211
- block = this.parseBlockContent();
2212
- }
2213
- children.push({
2214
- type: "transition",
2215
- name: `${event}_to_${targetState}`,
2216
- event,
2217
- target: targetState,
2218
- guard: block.guard || "",
2219
- action: block.action || "",
2220
- block
2221
- });
2222
- continue;
2223
- } else {
2224
- this.pos = saved;
2225
- }
2226
- }
2227
- if (name === "on_entry" || name === "on_exit") {
2228
- let block = "";
2229
- if (this.check("LBRACE")) {
2230
- block = this.parseCodeBlock();
2231
- } else {
2232
- while (!this.check("RBRACE") && !this.check("EOF")) this.advance();
2233
- }
2234
- children.push({
2235
- type: "method",
2236
- name,
2237
- params: [],
2238
- returnType: "unknown",
2239
- body: block
2240
- });
2241
- continue;
2242
- }
2243
- if (this.check("LPAREN")) {
2244
- const possibleMethod = saved;
2245
- this.pos = saved;
2246
- const methodName = this.advance().value;
2247
- const params = [];
2248
- this.advance();
2249
- while (!this.check("RPAREN") && !this.check("EOF") && !this.check("LBRACE")) {
2250
- if (this.check("IDENTIFIER")) {
2251
- params.push(this.advance().value);
2252
- } else {
2253
- this.advance();
2254
- }
2255
- }
2256
- if (this.check("RPAREN")) this.advance();
2257
- let returnType = "unknown";
2258
- if (this.check("COLON")) {
2259
- this.advance();
2260
- if (this.check("IDENTIFIER")) {
2261
- returnType = this.advance().value;
2262
- }
2263
- }
2264
- if (this.check("LBRACE")) {
2265
- const body = this.parseCodeBlock();
2266
- children.push({
2267
- type: "method",
2268
- name: methodName,
2269
- params,
2270
- returnType,
2271
- body
2272
- });
2273
- continue;
2274
- } else {
2275
- this.pos = possibleMethod;
2276
- this.advance();
2277
- }
2278
- }
2279
- if (this.check("COLON") || this.check("EQUALS")) {
2280
- this.advance();
2281
- properties[name] = this.parseValue();
2282
- } else if (childNodeKeywords.includes(name) && (this.check("LBRACE") || this.check("STRING"))) {
2283
- this.pos = saved;
2284
- children.push(this.parseNode());
2285
- } else if (this.current().type === "IDENTIFIER") {
2286
- this.pos = saved;
2287
- children.push(this.parseNode());
2288
- } else {
2289
- properties[name] = true;
2290
- while (this.check("LPAREN") || this.check("DOT") || this.check("LBRACE")) {
2291
- if (this.check("LPAREN")) this.skipParens();
2292
- else if (this.check("LBRACE")) this.skipBraces();
2293
- else {
2294
- this.advance();
2295
- if (this.check("IDENTIFIER")) this.advance();
2296
- }
2297
- }
2298
- }
2299
- } else if (this.check("COMMA")) {
2300
- this.advance();
2301
- } else {
2302
- this.error(
2303
- `Unexpected token ${this.current().type} "${this.current().value}" in node body`
2304
- );
2305
- this.synchronizeProperty();
2306
- }
2307
- }
2308
- this.skipNewlines();
2309
- } catch (e) {
2310
- const errorMessage = e instanceof Error ? e.message : String(e);
2311
- if (errorMessage !== "ParseError") console.error(e);
2312
- this.synchronizeProperty();
2313
- }
2314
- }
2315
- this.expect("RBRACE", "Expected }");
2316
- }
2317
- return {
2318
- type,
2319
- name: id,
2320
- // Mapping id to name for runtime compatibility
2321
- id,
2322
- properties,
2323
- directives,
2324
- children,
2325
- traits,
2326
- loc: {
2327
- start: { line: startToken.line, column: startToken.column },
2328
- end: { line: this.current().line, column: this.current().column }
2329
- }
2330
- };
2331
- }
2332
- parseDirective() {
2333
- this.expect("AT", "Expected @");
2334
- const nameToken = this.current();
2335
- const isKeyword = ["STATE_MACHINE", "STATE", "ON_ENTRY", "ON_EXIT", "TRANSITION"].includes(
2336
- nameToken.type
2337
- );
2338
- if (nameToken.type !== "IDENTIFIER" && !isKeyword) {
2339
- this.error(
2340
- `Expected directive name, got ${nameToken.type}. Directives start with @ followed by name (e.g., @grabbable)`,
2341
- "HSP201"
2342
- );
2343
- return null;
2344
- }
2345
- this.advance();
2346
- const name = nameToken.value;
2347
- if (name === "version") {
2348
- this.expect("LPAREN", "Expected ( after @version");
2349
- const versionToken = this.expect("NUMBER", "Expected version number");
2350
- const version = Number(versionToken.value);
2351
- this.expect("RPAREN", "Expected ) after version number");
2352
- return { type: "version", version };
2353
- }
2354
- if (name === "migrate") {
2355
- const fromToken = this.expect("IDENTIFIER", 'Expected "from" after @migrate');
2356
- if (fromToken.value !== "from") {
2357
- this.error('Expected "from" after @migrate');
2358
- }
2359
- this.expect("LPAREN", "Expected ( after from");
2360
- const fromVersionToken = this.expect("NUMBER", "Expected version number");
2361
- const fromVersion = Number(fromVersionToken.value);
2362
- this.expect("RPAREN", "Expected ) after version number");
2363
- const body = this.check("LBRACE") ? this.parseCodeBlock() : "";
2364
- return { type: "migrate", fromVersion, body };
2365
- }
2366
- if (chunkXG23EUQX_cjs.VR_TRAITS.includes(name)) {
2367
- if (!this.options.enableVRTraits) {
2368
- this.warn(`VR trait @${name} is disabled`);
2369
- return null;
2370
- }
2371
- let config2 = {};
2372
- if (this.check("LPAREN")) {
2373
- config2 = this.parseTraitConfig();
2374
- } else if (this.check("LBRACE")) {
2375
- config2 = this.parseBlockContent();
2376
- }
2377
- return { type: "trait", name, config: config2 };
2378
- }
2379
- if (chunkGVUR45UF_cjs.LIFECYCLE_HOOKS.includes(name)) {
2380
- const params = [];
2381
- if (this.check("LPAREN")) {
2382
- this.advance();
2383
- while (!this.check("RPAREN") && !this.check("EOF")) {
2384
- params.push(this.expect("IDENTIFIER", "Expected parameter name").value);
2385
- if (this.check("COLON")) {
2386
- this.advance();
2387
- this.expect("IDENTIFIER", "Expected type");
2388
- }
2389
- if (this.check("COMMA")) this.advance();
2390
- }
2391
- this.expect("RPAREN", "Expected )");
2392
- }
2393
- if (this.check("COLON")) {
2394
- this.advance();
2395
- if (this.check("LPAREN")) this.skipParens();
2396
- if (this.check("ARROW")) this.advance();
2397
- }
2398
- let body = "";
2399
- if (this.check("ARROW")) {
2400
- this.advance();
2401
- body = this.parseInlineExpression();
2402
- } else if (this.check("LBRACE")) {
2403
- body = this.parseCodeBlock();
2404
- }
2405
- return {
2406
- type: "lifecycle",
2407
- hook: name,
2408
- params,
2409
- body
2410
- };
2411
- }
2412
- if (name === "state") {
2413
- this.hasState = true;
2414
- const body = this.parseStateBlock();
2415
- return { type: "state", body };
2416
- }
2417
- if (name === "bindings") {
2418
- const bindings = this.parseBindingsBlock();
2419
- return { type: "bindings", bindings };
2420
- }
2421
- if (name === "for") {
2422
- this.hasControlFlow = true;
2423
- const variable = this.expect("IDENTIFIER", "Expected variable name").value;
2424
- this.expect("IDENTIFIER", 'Expected "in"');
2425
- const iterable = this.parseInlineExpression();
2426
- const body = this.parseControlFlowBody();
2427
- return { type: "for", variable, iterable, body };
2428
- }
2429
- if (name === "forEach") {
2430
- this.hasControlFlow = true;
2431
- const variable = this.expect("IDENTIFIER", "Expected variable name").value;
2432
- this.expect("IDENTIFIER", 'Expected "in"');
2433
- const collection = this.parseInlineExpression();
2434
- const body = this.parseControlFlowBody();
2435
- return { type: "forEach", variable, collection, body };
2436
- }
2437
- if (name === "while") {
2438
- this.hasControlFlow = true;
2439
- const condition = this.parseInlineExpression();
2440
- const body = this.parseControlFlowBody();
2441
- return { type: "while", condition, body };
2442
- }
2443
- if (name === "if") {
2444
- this.hasControlFlow = true;
2445
- const condition = this.parseInlineExpression();
2446
- const body = this.parseControlFlowBody();
2447
- let elseBody;
2448
- this.skipNewlines();
2449
- if (this.check("AT")) {
2450
- const saved = this.pos;
2451
- this.advance();
2452
- if (this.check("IDENTIFIER") && this.current().value === "else") {
2453
- this.advance();
2454
- elseBody = this.parseControlFlowBody();
2455
- } else {
2456
- this.pos = saved;
2457
- }
2458
- }
2459
- return { type: "if", condition, body, else: elseBody };
2460
- }
2461
- if (name === "import") {
2462
- if (!this.options.enableTypeScriptImports) {
2463
- this.warn("@import is disabled");
2464
- return null;
2465
- }
2466
- let namedImports;
2467
- let isWildcard = false;
2468
- if (this.check("LBRACE")) {
2469
- this.advance();
2470
- namedImports = [];
2471
- while (!this.check("RBRACE") && !this.check("EOF")) {
2472
- if (this.check("IDENTIFIER")) {
2473
- namedImports.push(this.advance().value);
2474
- }
2475
- if (this.check("COMMA")) this.advance();
2476
- }
2477
- this.expect("RBRACE", "Expected } in named import list");
2478
- if (this.check("IDENTIFIER") && this.current().value === "from") {
2479
- this.advance();
2480
- } else {
2481
- this.warn("Expected 'from' after named import specifiers");
2482
- }
2483
- }
2484
- if (this.check("ASTERISK") || this.check("IDENTIFIER") && this.current().value === "*") {
2485
- this.advance();
2486
- isWildcard = true;
2487
- if (this.check("IDENTIFIER") && this.current().value === "as") {
2488
- this.advance();
2489
- }
2490
- }
2491
- const path = this.expect("STRING", "Expected import path string").value;
2492
- let alias = path.split("/").pop()?.replace(/\.[^.]+$/, "") || "import";
2493
- if (!namedImports && this.check("IDENTIFIER") && this.current().value === "as") {
2494
- this.advance();
2495
- alias = this.expect("IDENTIFIER", "Expected alias after as").value;
2496
- }
2497
- if (isWildcard && this.check("IDENTIFIER") && this.current().value !== "from") {
2498
- alias = this.advance().value;
2499
- if (this.check("IDENTIFIER") && this.current().value === "from") {
2500
- this.advance();
2501
- }
2502
- }
2503
- this.imports.push({ path, alias, namedImports, isWildcard });
2504
- return {
2505
- type: "import",
2506
- path,
2507
- alias,
2508
- namedImports,
2509
- isWildcard
2510
- };
2511
- }
2512
- if (name === "export") {
2513
- let exportKind = "any";
2514
- if (this.check("IDENTIFIER")) {
2515
- const kindToken = this.current();
2516
- const knownKinds = ["template", "object", "composition", "trait", "group", "scene"];
2517
- if (knownKinds.includes(kindToken.value)) {
2518
- exportKind = this.advance().value;
2519
- }
2520
- }
2521
- let exportName;
2522
- if (this.check("STRING")) {
2523
- exportName = this.advance().value;
2524
- } else if (this.check("IDENTIFIER")) {
2525
- exportName = this.advance().value;
2526
- }
2527
- return {
2528
- type: "export",
2529
- exportKind,
2530
- exportName
2531
- };
2532
- }
2533
- if (name === "manifest") {
2534
- let config2 = {};
2535
- let manifestName = "default";
2536
- if (this.check("LPAREN")) {
2537
- this.advance();
2538
- if (this.check("STRING")) {
2539
- manifestName = this.advance().value;
2540
- }
2541
- while (!this.check("RPAREN") && !this.check("EOF")) this.advance();
2542
- this.expect("RPAREN", "Expected )");
2543
- } else if (this.check("STRING")) {
2544
- manifestName = this.advance().value;
2545
- }
2546
- if (this.check("LBRACE")) {
2547
- const block = this.parseBlockContent();
2548
- config2 = { ...config2, ...block };
2549
- }
2550
- return { type: "manifest", name: manifestName, ...config2 };
2551
- }
2552
- if (name === "asset") {
2553
- if (this.check("LPAREN")) {
2554
- const config2 = this.parseTraitConfig();
2555
- return { ...config2, type: "asset" };
2556
- }
2557
- const assetId = this.expect("STRING", "Expected asset ID").value;
2558
- return { type: "asset", id: assetId };
2559
- }
2560
- if (name === "semantic") {
2561
- const semanticName = this.check("LPAREN") ? this.parseParenString() : this.expect("STRING", "Expected semantic name").value;
2562
- const config2 = this.parseBlockContent();
2563
- return { ...config2, type: "semantic", name: semanticName };
2564
- }
2565
- if (name === "annotate") {
2566
- const annotateName = this.check("LPAREN") ? this.parseParenString() : this.expect("STRING", "Expected annotation type").value;
2567
- let config2 = {};
2568
- if (this.check("COMMA")) {
2569
- this.advance();
2570
- config2 = this.parseValue();
2571
- if (this.check("RPAREN")) this.advance();
2572
- } else if (this.check("RPAREN")) {
2573
- this.advance();
2574
- }
2575
- return { type: "annotate", annotationType: annotateName, config: config2 };
2576
- }
2577
- if (name === "semantic_ref") {
2578
- const refName = this.check("LPAREN") ? this.parseParenString() : this.expect("STRING", "Expected semantic reference").value;
2579
- return { type: "semantic_ref", ref: refName };
2580
- }
2581
- if (name === "bindings") {
2582
- const bindings = this.parseBindingsBlock();
2583
- return { type: "bindings", bindings };
2584
- }
2585
- if (name === "world_metadata") {
2586
- const config2 = this.parseBlockContent();
2587
- return { ...config2, type: "world_metadata" };
2588
- }
2589
- if (name === "world_config") {
2590
- const config2 = this.parseBlockContent();
2591
- return { ...config2, type: "world_config" };
2592
- }
2593
- if (name === "zones") {
2594
- const zones = this.parseNamedBlockList("zone");
2595
- return { type: "zones", zones };
2596
- }
2597
- if (name === "spawn_points") {
2598
- const spawns = this.parseNamedBlockList("spawn");
2599
- return { type: "spawn_points", spawns };
2600
- }
2601
- if (name === "skybox") {
2602
- const config2 = this.parseBlockContent();
2603
- return { ...config2, type: "skybox" };
2604
- }
2605
- if (name === "ambient_light") {
2606
- const config2 = this.parseBlockContent();
2607
- return { ...config2, type: "ambient_light" };
2608
- }
2609
- if (name === "directional_light") {
2610
- let lightName = "default";
2611
- if (this.check("LPAREN")) {
2612
- lightName = this.parseParenString();
2613
- }
2614
- const config2 = this.parseBlockContent();
2615
- return { ...config2, type: "directional_light", name: lightName };
2616
- }
2617
- if (name === "fog") {
2618
- const config2 = this.parseBlockContent();
2619
- return { ...config2, type: "fog" };
2620
- }
2621
- if (name === "artwork_metadata") {
2622
- const config2 = this.parseBlockContent();
2623
- return { ...config2, type: "artwork_metadata" };
2624
- }
2625
- if (name === "npc_behavior") {
2626
- const config2 = this.parseBlockContent();
2627
- return { ...config2, type: "npc_behavior" };
2628
- }
2629
- if (name === "interactive") {
2630
- const config2 = this.parseBlockContent();
2631
- return { ...config2, type: "interactive" };
2632
- }
2633
- if (name === "lod") {
2634
- const config2 = this.parseBlockContent();
2635
- return { ...config2, type: "lod" };
2636
- }
2637
- if (name === "external_api") {
2638
- let externalApiName = "default";
2639
- if (this.check("STRING")) {
2640
- externalApiName = this.advance().value;
2641
- } else if (this.check("IDENTIFIER")) {
2642
- externalApiName = this.advance().value;
2643
- }
2644
- const config2 = this.check("LBRACE") ? this.parseBlockContent() : this.parseTraitConfig();
2645
- return {
2646
- type: "external_api",
2647
- name: externalApiName,
2648
- ...config2
2649
- };
2650
- }
2651
- if (name === "generate") {
2652
- const config2 = this.parseTraitConfig();
2653
- const prompt = config2.prompt || "";
2654
- const context = config2.context || "";
2655
- const target = config2.target || "children";
2656
- return { type: "generate", prompt, context, target };
2657
- }
2658
- if (name === "npc") {
2659
- const npcName = this.expect("STRING", "Expected NPC name").value;
2660
- const props = this.parsePropsBlock();
2661
- return { type: "npc", name: npcName, props };
2662
- }
2663
- if (name === "dialog") {
2664
- const dialogName = this.expect("STRING", "Expected dialog name").value;
2665
- const { props, options } = this.parseDialogBlock();
2666
- return { type: "dialog", name: dialogName, props, options };
2667
- }
2668
- if (name === "hololand") {
2669
- if (this.check("DOT")) {
2670
- this.advance();
2671
- const eventName = this.expect("IDENTIFIER", "Expected event name").value;
2672
- const params = [];
2673
- if (this.check("LPAREN")) {
2674
- this.advance();
2675
- while (!this.check("RPAREN") && !this.check("EOF")) {
2676
- params.push(this.expect("IDENTIFIER", "Expected parameter").value);
2677
- if (this.check("COLON")) {
2678
- this.advance();
2679
- this.expect("IDENTIFIER", "Expected type");
2680
- }
2681
- if (this.check("COMMA")) this.advance();
2682
- }
2683
- this.expect("RPAREN", "Expected )");
2684
- }
2685
- return { type: "hololand_event", event: eventName, params };
2686
- }
2687
- }
2688
- if (chunkGVUR45UF_cjs.STRUCTURAL_DIRECTIVES.includes(name)) {
2689
- let nodeName;
2690
- if (this.check("STRING")) {
2691
- nodeName = this.advance().value;
2692
- }
2693
- const config2 = this.check("LBRACE") ? this.parseBlockContent() : this.parseTraitConfig();
2694
- return { ...config2, type: name, name: nodeName };
2695
- }
2696
- if (this.options.strict) {
2697
- this.traitError(name);
2698
- } else {
2699
- this.warn(`Unknown directive @${name}`);
2700
- }
2701
- let config = {};
2702
- if (this.check("LPAREN")) {
2703
- config = this.parseTraitConfig();
2704
- } else if (this.check("LBRACE")) {
2705
- config = this.parseBlockContent();
2706
- }
2707
- if (this.check("COLON")) {
2708
- this.advance();
2709
- if (this.check("LPAREN")) this.skipParens();
2710
- if (this.check("ARROW")) this.advance();
2711
- if (this.check("LBRACE")) {
2712
- config.body = this.parseCodeBlock();
2713
- }
2714
- }
2715
- return { type: "trait", name, config };
2716
- }
2717
- /**
2718
- * Parse a string inside parentheses: ("name")
2719
- */
2720
- parseParenString() {
2721
- this.expect("LPAREN", "Expected (");
2722
- const value = this.expect("STRING", "Expected string").value;
2723
- this.expect("RPAREN", "Expected )");
2724
- return value;
2725
- }
2726
- parseConnectionStatement() {
2727
- this.expect("IDENTIFIER", "Expected connect");
2728
- const from = this.expect("IDENTIFIER", "Expected from name").value;
2729
- this.expect("IDENTIFIER", "Expected to");
2730
- const to = this.expect("IDENTIFIER", "Expected to name").value;
2731
- return { from, to };
2732
- }
2733
- /**
2734
- * Parse block content: { key: value, ... }
2735
- */
2736
- parseBlockContent() {
2737
- const content = {};
2738
- if (!this.check("LBRACE")) {
2739
- return content;
2740
- }
2741
- this.advance();
2742
- this.skipNewlines();
2743
- while (!this.check("RBRACE") && !this.check("EOF")) {
2744
- this.skipNewlines();
2745
- if (this.check("RBRACE") || this.check("EOF")) break;
2746
- this.skipNewlines();
2747
- if (this.check("RBRACE") || this.check("EOF")) break;
2748
- const token = this.current();
2749
- const isKeyToken = token.type === "IDENTIFIER" || token.type === "STRING" || token.type === "STATE" || token.type === "STATE_MACHINE" || token.type === "INITIAL" || token.type === "ON_ENTRY" || token.type === "ON_EXIT" || token.type === "TRANSITION";
2750
- if (isKeyToken) {
2751
- const next = this.peek(1);
2752
- if (next.type === "COLON" || next.type === "EQUALS") {
2753
- const key = this.advance().value;
2754
- this.advance();
2755
- content[key] = this.parseValue();
2756
- } else if (next.type === "STRING" || next.type === "LBRACE" || next.type === "IDENTIFIER") {
2757
- const node = this.parseNode();
2758
- const type = node.type;
2759
- const name = node.name || `unnamed_${type}_${Object.keys(content).length}`;
2760
- content[name] = node;
2761
- } else {
2762
- const key = this.advance().value;
2763
- content[key] = true;
2764
- }
2765
- } else if (this.check("SPREAD")) {
2766
- this.advance();
2767
- const val = this.parseValue();
2768
- const spreadKey = `__spread_${Object.keys(content).length}`;
2769
- content[spreadKey] = { type: "spread", argument: val };
2770
- } else if (this.check("AT")) {
2771
- const directive = this.parseDirective();
2772
- if (directive) {
2773
- const dirKey = ("name" in directive ? directive.name : void 0) || directive.type;
2774
- content[`@${dirKey}`] = directive;
2775
- }
2776
- } else if (this.check("LBRACE")) {
2777
- let depth = 1;
2778
- this.advance();
2779
- while (depth > 0 && !this.check("EOF")) {
2780
- if (this.check("LBRACE")) depth++;
2781
- if (this.check("RBRACE")) depth--;
2782
- this.advance();
2783
- }
2784
- } else if (this.check("LPAREN")) {
2785
- this.skipParens();
2786
- } else {
2787
- this.advance();
2788
- }
2789
- if (this.check("COMMA")) this.advance();
2790
- this.skipNewlines();
2791
- }
2792
- this.expect("RBRACE", "Expected }");
2793
- return content;
2794
- }
2795
- /**
2796
- * Parse bindings block: { bind(expr) -> target, ... }
2797
- */
2798
- parseBindingsBlock() {
2799
- const bindings = [];
2800
- if (!this.check("LBRACE")) {
2801
- return bindings;
2802
- }
2803
- this.advance();
2804
- this.skipNewlines();
2805
- while (!this.check("RBRACE") && !this.check("EOF")) {
2806
- this.skipNewlines();
2807
- if (this.check("RBRACE") || this.check("EOF")) break;
2808
- if (this.check("IDENTIFIER") && this.current().value === "bind") {
2809
- this.advance();
2810
- if (this.check("LPAREN")) {
2811
- this.advance();
2812
- let source = "";
2813
- let parenDepth = 1;
2814
- while (parenDepth > 0 && !this.check("EOF")) {
2815
- if (this.check("LPAREN")) parenDepth++;
2816
- if (this.check("RPAREN")) {
2817
- parenDepth--;
2818
- if (parenDepth === 0) break;
2819
- }
2820
- source += this.advance().value + " ";
2821
- }
2822
- this.expect("RPAREN", "Expected )");
2823
- source = source.trim();
2824
- if (this.check("ARROW")) {
2825
- this.advance();
2826
- }
2827
- let target = "";
2828
- while (!this.check("NEWLINE") && !this.check("RBRACE") && !this.check("EOF")) {
2829
- target += this.advance().value;
2830
- }
2831
- target = target.trim();
2832
- bindings.push({ source, target });
2833
- }
2834
- } else {
2835
- while (!this.check("NEWLINE") && !this.check("RBRACE") && !this.check("EOF")) {
2836
- this.advance();
2837
- }
2838
- }
2839
- this.skipNewlines();
2840
- }
2841
- this.expect("RBRACE", "Expected }");
2842
- return bindings;
2843
- }
2844
- /**
2845
- * Parse named block list: zone "name" { ... } or spawn "name" { ... }
2846
- */
2847
- parseNamedBlockList(blockType) {
2848
- const blocks = [];
2849
- if (!this.check("LBRACE")) {
2850
- return blocks;
2851
- }
2852
- this.advance();
2853
- this.skipNewlines();
2854
- while (!this.check("RBRACE") && !this.check("EOF")) {
2855
- this.skipNewlines();
2856
- if (this.check("RBRACE") || this.check("EOF")) break;
2857
- if (this.check("IDENTIFIER") && this.current().value === blockType) {
2858
- this.advance();
2859
- const blockName = this.expect("STRING", `Expected ${blockType} name`).value;
2860
- const config = this.parseBlockContent();
2861
- blocks.push({ name: blockName, config });
2862
- } else {
2863
- this.advance();
2864
- }
2865
- this.skipNewlines();
2866
- }
2867
- this.expect("RBRACE", "Expected }");
2868
- return blocks;
2869
- }
2870
- /**
2871
- * Parse composition block: composition "Name" { ... }
2872
- */
2873
- parseCompositionBlock() {
2874
- const result = {
2875
- systems: [],
2876
- configs: [],
2877
- children: [],
2878
- properties: {}
2879
- };
2880
- if (!this.check("LBRACE")) {
2881
- return result;
2882
- }
2883
- this.advance();
2884
- this.skipNewlines();
2885
- const childNodeKeywords = [
2886
- "logic",
2887
- "template",
2888
- "environment",
2889
- "state",
2890
- "object",
2891
- "composition",
2892
- "system",
2893
- "core_config",
2894
- "narrative",
2895
- "quest",
2896
- "objective",
2897
- "dialogue",
2898
- "choice",
2899
- "visual_metadata",
2900
- "spatial_group",
2901
- "scene",
2902
- "group",
2903
- "module",
2904
- "struct",
2905
- "orb",
2906
- "on_error",
2907
- "assert",
2908
- "topic",
2909
- "channel",
2910
- "config",
2911
- "zone",
2912
- "audio",
2913
- "light",
2914
- "npc",
2915
- "camera",
2916
- "timeline"
2917
- ];
2918
- while (!this.check("RBRACE") && !this.check("EOF")) {
2919
- const currentDirectives = [];
2920
- this.skipNewlines();
2921
- if (this.check("RBRACE") || this.check("EOF")) break;
2922
- while (this.check("AT")) {
2923
- const directive = this.parseDirective();
2924
- if (directive) {
2925
- currentDirectives.push(directive);
2926
- }
2927
- this.skipNewlines();
2928
- }
2929
- const isNodeStart = this.check("IDENTIFIER") || this.check("STATE_MACHINE") || this.check("STATE") || this.check("TRANSITION") || this.check("INITIAL");
2930
- if (isNodeStart) {
2931
- const token = this.current();
2932
- const next = this.peek(1);
2933
- if (next.type === "COLON" || next.type === "EQUALS") {
2934
- const key = this.advance().value;
2935
- this.advance();
2936
- result.properties[key] = this.parseValue();
2937
- } else if (childNodeKeywords.includes(token.value) && (next.type === "LBRACE" || next.type === "STRING" || next.type === "IDENTIFIER")) {
2938
- const keyword = this.current().value;
2939
- const node = this.parseNode();
2940
- node.directives = [...currentDirectives, ...node.directives || []];
2941
- if (keyword === "system" || node.type === "system") {
2942
- result.systems.push(node);
2943
- } else if (keyword === "core_config" || node.type === "core_config") {
2944
- result.configs.push(node);
2945
- } else {
2946
- result.children.push(node);
2947
- }
2948
- } else if (!childNodeKeywords.includes(token.value) && (next.type === "STRING" || next.type === "NUMBER" || next.type === "BOOLEAN" || next.type === "NULL")) {
2949
- const key = this.advance().value;
2950
- result.properties[key] = this.parseValue();
2951
- } else if (next.type === "LBRACE" || next.type === "IDENTIFIER" || next.type === "STRING") {
2952
- const keyword = this.current().value;
2953
- const node = this.parseNode();
2954
- node.directives = [...currentDirectives, ...node.directives || []];
2955
- if (keyword === "system" || node.type === "system") {
2956
- result.systems.push(node);
2957
- } else if (keyword === "core_config" || node.type === "core_config") {
2958
- result.configs.push(node);
2959
- } else {
2960
- result.children.push(node);
2961
- }
2962
- } else if (next.type === "LPAREN") {
2963
- const possibleMethod = this.pos;
2964
- const methodName = this.advance().value;
2965
- const params = [];
2966
- this.advance();
2967
- while (!this.check("RPAREN") && !this.check("EOF") && !this.check("LBRACE")) {
2968
- if (this.check("IDENTIFIER")) {
2969
- params.push(this.advance().value);
2970
- } else {
2971
- this.advance();
2972
- }
2973
- }
2974
- if (this.check("RPAREN")) this.advance();
2975
- let returnType = "unknown";
2976
- if (this.check("COLON")) {
2977
- this.advance();
2978
- if (this.check("IDENTIFIER")) {
2979
- returnType = this.advance().value;
2980
- }
2981
- }
2982
- if (this.check("LBRACE")) {
2983
- const body = this.parseCodeBlock();
2984
- result.children.push({
2985
- type: "method",
2986
- name: methodName,
2987
- params,
2988
- returnType,
2989
- body
2990
- });
2991
- } else {
2992
- this.pos = possibleMethod;
2993
- const key = this.advance().value;
2994
- result.properties[key] = true;
2995
- }
2996
- } else {
2997
- const key = this.advance().value;
2998
- result.properties[key] = true;
2999
- }
3000
- } else if (currentDirectives.length > 0) {
3001
- const fragment = {
3002
- type: "fragment",
3003
- directives: currentDirectives,
3004
- children: [],
3005
- traits: /* @__PURE__ */ new Map(),
3006
- properties: {}
3007
- };
3008
- result.children.push(fragment);
3009
- } else if (this.check("COMMA")) {
3010
- this.advance();
3011
- } else if (this.check("LBRACKET")) {
3012
- let depth = 1;
3013
- this.advance();
3014
- while (depth > 0 && !this.check("EOF")) {
3015
- if (this.check("LBRACKET")) depth++;
3016
- else if (this.check("RBRACKET")) depth--;
3017
- this.advance();
3018
- }
3019
- } else if (this.check("LBRACE")) {
3020
- let depth = 1;
3021
- this.advance();
3022
- while (depth > 0 && !this.check("EOF")) {
3023
- if (this.check("LBRACE")) depth++;
3024
- else if (this.check("RBRACE")) depth--;
3025
- this.advance();
3026
- }
3027
- } else {
3028
- if (!this.check("RBRACE") && !this.check("EOF")) {
3029
- this.error(
3030
- `Unexpected token ${this.current().type} "${this.current().value}" in composition body. Expected property name, @directive, or child node`,
3031
- "HSP101"
3032
- );
3033
- this.advance();
3034
- }
3035
- }
3036
- this.skipNewlines();
3037
- }
3038
- this.expect("RBRACE", "Expected }");
3039
- return result;
3040
- }
3041
- /**
3042
- * Parse logic block: logic { function..., on_tick..., on_scene_load... }
3043
- */
3044
- parseLogicBlock() {
3045
- const result = {
3046
- functions: [],
3047
- eventHandlers: [],
3048
- tickHandlers: []
3049
- };
3050
- if (!this.check("LBRACE")) {
3051
- return result;
3052
- }
3053
- this.advance();
3054
- this.skipNewlines();
3055
- while (!this.check("RBRACE") && !this.check("EOF")) {
3056
- this.skipNewlines();
3057
- if (this.check("RBRACE") || this.check("EOF")) break;
3058
- if (this.check("IDENTIFIER")) {
3059
- const keyword = this.current().value;
3060
- if (keyword === "function") {
3061
- this.advance();
3062
- const funcName = this.expect("IDENTIFIER", "Expected function name").value;
3063
- const params = [];
3064
- if (this.check("LPAREN")) {
3065
- this.advance();
3066
- while (!this.check("RPAREN") && !this.check("EOF")) {
3067
- params.push(this.expect("IDENTIFIER", "Expected parameter").value);
3068
- if (this.check("COLON")) {
3069
- this.advance();
3070
- this.expect("IDENTIFIER", "Expected type");
3071
- }
3072
- if (this.check("COMMA")) this.advance();
3073
- }
3074
- this.expect("RPAREN", "Expected )");
3075
- }
3076
- if (this.check("COLON")) {
3077
- this.advance();
3078
- this.expect("IDENTIFIER", "Expected return type");
3079
- }
3080
- const body = this.parseCodeBlock();
3081
- result.functions.push({ name: funcName, params, body });
3082
- } else if (keyword === "on_tick") {
3083
- this.advance();
3084
- let interval = 1;
3085
- if (this.check("LPAREN")) {
3086
- this.advance();
3087
- const intervalToken = this.expect("NUMBER", "Expected interval");
3088
- interval = parseFloat(intervalToken.value);
3089
- this.expect("RPAREN", "Expected )");
3090
- }
3091
- const body = this.parseCodeBlock();
3092
- result.tickHandlers.push({ interval, body });
3093
- } else if (keyword === "on_scene_load") {
3094
- this.advance();
3095
- const body = this.parseCodeBlock();
3096
- result.eventHandlers.push({ event: "scene_load", params: [], body });
3097
- } else if (keyword === "on") {
3098
- this.advance();
3099
- let eventName = "";
3100
- if (this.check("AT")) {
3101
- this.advance();
3102
- eventName = this.expect("IDENTIFIER", "Expected event namespace").value;
3103
- if (this.check("DOT")) {
3104
- this.advance();
3105
- eventName += "." + this.expect("IDENTIFIER", "Expected event name").value;
3106
- }
3107
- } else {
3108
- eventName = this.expect("IDENTIFIER", "Expected event name").value;
3109
- }
3110
- const params = [];
3111
- if (this.check("LPAREN")) {
3112
- this.advance();
3113
- while (!this.check("RPAREN") && !this.check("EOF")) {
3114
- params.push(this.expect("IDENTIFIER", "Expected parameter").value);
3115
- if (this.check("COLON")) {
3116
- this.advance();
3117
- this.expect("IDENTIFIER", "Expected type");
3118
- }
3119
- if (this.check("COMMA")) this.advance();
3120
- }
3121
- this.expect("RPAREN", "Expected )");
3122
- }
3123
- const body = this.parseCodeBlock();
3124
- result.eventHandlers.push({ event: eventName, params, body });
3125
- } else if (keyword === "on_start") {
3126
- this.advance();
3127
- const params = [];
3128
- if (this.check("LPAREN")) {
3129
- this.advance();
3130
- while (!this.check("RPAREN") && !this.check("EOF")) {
3131
- params.push(this.expect("IDENTIFIER", "Expected parameter").value);
3132
- if (this.check("COMMA")) this.advance();
3133
- }
3134
- this.expect("RPAREN", "Expected )");
3135
- }
3136
- const body = this.parseCodeBlock();
3137
- result.eventHandlers.push({ event: "start", params, body });
3138
- } else if (keyword === "on_event") {
3139
- this.advance();
3140
- let eventName = "";
3141
- const params = [];
3142
- if (this.check("LPAREN")) {
3143
- this.advance();
3144
- if (this.check("STRING")) {
3145
- eventName = this.advance().value;
3146
- } else {
3147
- eventName = this.expect("IDENTIFIER", "Expected event name").value;
3148
- }
3149
- if (this.check("COMMA")) {
3150
- this.advance();
3151
- while (!this.check("RPAREN") && !this.check("EOF")) {
3152
- params.push(this.expect("IDENTIFIER", "Expected parameter").value);
3153
- if (this.check("COMMA")) this.advance();
3154
- }
3155
- }
3156
- this.expect("RPAREN", "Expected )");
3157
- }
3158
- const body = this.parseCodeBlock();
3159
- result.eventHandlers.push({ event: eventName, params, body });
3160
- } else {
3161
- this.advance();
3162
- if (this.check("LPAREN")) this.skipParens();
3163
- if (this.check("LBRACE")) this.skipBraces();
3164
- while (!this.check("RBRACE") && !this.check("EOF") && !this.check("NEWLINE")) {
3165
- this.advance();
3166
- }
3167
- }
3168
- } else {
3169
- this.advance();
3170
- }
3171
- this.skipNewlines();
3172
- }
3173
- this.expect("RBRACE", "Expected }");
3174
- return result;
3175
- }
3176
- /**
3177
- * Parse environment block with lighting directives
3178
- */
3179
- parseEnvironmentBlock() {
3180
- const properties = {};
3181
- const directives = [];
3182
- if (!this.check("LBRACE")) {
3183
- return { properties, directives };
3184
- }
3185
- this.advance();
3186
- this.skipNewlines();
3187
- while (!this.check("RBRACE") && !this.check("EOF")) {
3188
- this.skipNewlines();
3189
- if (this.check("RBRACE") || this.check("EOF")) break;
3190
- if (this.check("AT")) {
3191
- const directive = this.parseDirective();
3192
- if (directive) {
3193
- directives.push(directive);
3194
- }
3195
- } else if (this.check("IDENTIFIER")) {
3196
- const key = this.advance().value;
3197
- if (this.check("COLON") || this.check("EQUALS")) {
3198
- this.advance();
3199
- properties[key] = this.parseValue();
3200
- } else {
3201
- properties[key] = true;
3202
- }
3203
- } else {
3204
- this.advance();
3205
- }
3206
- this.skipNewlines();
3207
- }
3208
- this.expect("RBRACE", "Expected }");
3209
- return { properties, directives };
3210
- }
3211
- parsePropsBlock() {
3212
- this.skipNewlines();
3213
- const props = {};
3214
- if (this.check("LBRACE")) {
3215
- this.advance();
3216
- this.skipNewlines();
3217
- while (!this.check("RBRACE") && !this.check("EOF")) {
3218
- if (this.check("SPREAD")) {
3219
- this.advance();
3220
- const val = this.parseValue();
3221
- const spreadKey = `__spread_${Object.keys(props).length}`;
3222
- props[spreadKey] = { type: "spread", argument: val };
3223
- this.skipNewlines();
3224
- if (this.check("COMMA")) this.advance();
3225
- this.skipNewlines();
3226
- continue;
3227
- }
3228
- const key = this.expect("IDENTIFIER", "Expected property name").value;
3229
- if (this.check("COLON") || this.check("EQUALS")) {
3230
- this.advance();
3231
- props[key] = this.parseValue();
3232
- } else {
3233
- props[key] = true;
3234
- }
3235
- this.skipNewlines();
3236
- if (this.check("COMMA")) this.advance();
3237
- this.skipNewlines();
3238
- }
3239
- this.expect("RBRACE", "Expected }");
3240
- }
3241
- return props;
3242
- }
3243
- parseDialogBlock() {
3244
- this.skipNewlines();
3245
- const props = {};
3246
- const options = [];
3247
- if (this.check("LBRACE")) {
3248
- this.advance();
3249
- this.skipNewlines();
3250
- while (!this.check("RBRACE") && !this.check("EOF")) {
3251
- if (this.check("IDENTIFIER") && this.current().value === "option") {
3252
- this.advance();
3253
- const text = this.expect("STRING", "Expected option text").value;
3254
- this.expect("ARROW", "Expected ->");
3255
- let target;
3256
- if (this.check("AT")) {
3257
- const d = this.parseDirective();
3258
- target = { type: "directive", value: d };
3259
- } else {
3260
- target = this.expect("STRING", "Expected target ID").value;
3261
- }
3262
- options.push({ text, target });
3263
- } else {
3264
- const key = this.expect("IDENTIFIER", "Expected property name").value;
3265
- if (this.check("COLON") || this.check("EQUALS")) {
3266
- this.advance();
3267
- props[key] = this.parseValue();
3268
- } else {
3269
- props[key] = true;
3270
- }
3271
- }
3272
- this.skipNewlines();
3273
- }
3274
- this.expect("RBRACE", "Expected }");
3275
- }
3276
- return { props, options };
3277
- }
3278
- parseTraitConfig() {
3279
- const config = {};
3280
- if (this.check("LPAREN")) {
3281
- this.advance();
3282
- this.skipNewlines();
3283
- if (this.check("STRING") && (this.peek(1).type === "RPAREN" || this.peek(1).type === "COMMA")) {
3284
- config["default"] = this.advance().value;
3285
- if (this.check("COMMA")) this.advance();
3286
- this.skipNewlines();
3287
- }
3288
- while (!this.check("RPAREN") && !this.check("EOF")) {
3289
- this.skipNewlines();
3290
- if (this.check("RPAREN") || this.check("EOF")) break;
3291
- if (!this.check("IDENTIFIER")) {
3292
- this.advance();
3293
- continue;
3294
- }
3295
- const key = this.expect("IDENTIFIER", "Expected property name").value;
3296
- if (this.check("COLON") || this.check("EQUALS")) {
3297
- this.advance();
3298
- config[key] = this.parseValue();
3299
- } else {
3300
- config[key] = true;
3301
- }
3302
- if (this.check("COMMA")) this.advance();
3303
- this.skipNewlines();
3304
- }
3305
- this.expect("RPAREN", "Expected )");
3306
- }
3307
- return config;
3308
- }
3309
- parseStateBlock() {
3310
- const state = {};
3311
- if (this.check("LBRACE")) {
3312
- this.advance();
3313
- this.skipNewlines();
3314
- while (!this.check("RBRACE") && !this.check("EOF")) {
3315
- this.skipNewlines();
3316
- if (this.check("RBRACE") || this.check("EOF")) break;
3317
- if (this.check("SPREAD")) {
3318
- this.advance();
3319
- const spreadArg = this.parseValue();
3320
- if (spreadArg === null) {
3321
- this.error("Expected expression after spread operator (...) in state block", "HSP300");
3322
- } else {
3323
- const spreadKey = `__spread_${Object.keys(state).length}`;
3324
- state[spreadKey] = { type: "spread", argument: spreadArg };
3325
- }
3326
- this.skipNewlines();
3327
- continue;
3328
- }
3329
- const key = this.expect("IDENTIFIER", "Expected state variable name").value;
3330
- if (this.check("COLON") || this.check("EQUALS")) {
3331
- this.advance();
3332
- state[key] = this.parseValue();
3333
- } else {
3334
- state[key] = true;
3335
- }
3336
- this.skipNewlines();
3337
- }
3338
- this.expect("RBRACE", "Expected }");
3339
- }
3340
- return state;
3341
- }
3342
- /**
3343
- * Parse spatial state machine (Phase 13)
3344
- */
3345
- parseStateMachine() {
3346
- const startToken = this.current();
3347
- if (startToken.type === "STATE_MACHINE") {
3348
- this.advance();
3349
- }
3350
- const name = this.expect("IDENTIFIER", "Expected state machine name").value;
3351
- const states = [];
3352
- const transitions = [];
3353
- let initialState = "";
3354
- this.expect("LBRACE", "Expected { after state machine name");
3355
- this.skipNewlines();
3356
- while (!this.check("RBRACE") && !this.check("EOF")) {
3357
- this.skipNewlines();
3358
- if (this.check("RBRACE") || this.check("EOF")) break;
3359
- const current = this.current();
3360
- if (current.type === "INITIAL" || current.value === "initial") {
3361
- this.advance();
3362
- this.expect("COLON", "Expected : after initial");
3363
- initialState = this.expect("STRING", "Expected initial state name").value;
3364
- } else if (current.type === "STATE" || current.value === "state") {
3365
- states.push(this.parseStateNode());
3366
- } else if (current.type === "TRANSITION" || current.value === "transitions") {
3367
- transitions.push(...this.parseTransitionsBlock());
3368
- } else {
3369
- this.advance();
3370
- }
3371
- this.skipNewlines();
3372
- }
3373
- this.expect("RBRACE", "Expected } at end of state machine");
3374
- return {
3375
- type: "state-machine",
3376
- name,
3377
- initialState,
3378
- states,
3379
- transitions,
3380
- loc: {
3381
- start: { line: startToken.line, column: startToken.column },
3382
- end: { line: this.current().line, column: this.current().column }
3383
- }
3384
- };
3385
- }
3386
- parseStateNode() {
3387
- this.advance();
3388
- const name = this.expect("IDENTIFIER", "Expected state name").value;
3389
- let onEntry;
3390
- let onExit;
3391
- this.expect("LBRACE", "Expected { after state name");
3392
- this.skipNewlines();
3393
- while (!this.check("RBRACE") && !this.check("EOF")) {
3394
- this.skipNewlines();
3395
- if (this.check("RBRACE") || this.check("EOF")) break;
3396
- const current = this.current();
3397
- if (current.type === "ON_ENTRY" || current.value === "on_entry") {
3398
- this.advance();
3399
- onEntry = this.parseCodeBlock();
3400
- } else if (current.type === "ON_EXIT" || current.value === "on_exit") {
3401
- this.advance();
3402
- onExit = this.parseCodeBlock();
3403
- } else {
3404
- this.advance();
3405
- }
3406
- this.skipNewlines();
3407
- }
3408
- this.expect("RBRACE", "Expected }");
3409
- return { name, onEntry, onExit };
3410
- }
3411
- parseOnErrorNode() {
3412
- const startToken = this.previous();
3413
- const body = this.parseControlFlowBody();
3414
- return {
3415
- type: "on_error",
3416
- body,
3417
- loc: {
3418
- start: { line: startToken.line, column: startToken.column },
3419
- end: { line: this.current().line, column: this.current().column }
3420
- }
3421
- };
3422
- }
3423
- parseAssertNode() {
3424
- const startToken = this.previous();
3425
- this.expect("LPAREN", "Expected (");
3426
- const condition = this.parseExpression();
3427
- let message = "";
3428
- if (this.match(["COMMA"])) {
3429
- message = String(this.parseValue());
3430
- }
3431
- this.expect("RPAREN", "Expected )");
3432
- return {
3433
- type: "assert",
3434
- condition,
3435
- message,
3436
- loc: {
3437
- start: { line: startToken.line, column: startToken.column },
3438
- end: { line: this.current().line, column: this.current().column }
3439
- }
3440
- };
3441
- }
3442
- parseTransitionsBlock() {
3443
- const transitions = [];
3444
- this.advance();
3445
- this.expect("LBRACE", "Expected {");
3446
- this.skipNewlines();
3447
- while (!this.check("RBRACE") && !this.check("EOF")) {
3448
- this.skipNewlines();
3449
- if (this.check("RBRACE") || this.check("EOF")) break;
3450
- const from = this.expect("IDENTIFIER", "Expected source state").value;
3451
- this.expect("ARROW", "Expected ->");
3452
- const to = this.expect("IDENTIFIER", "Expected target state").value;
3453
- this.expect("COLON", "Expected :");
3454
- const event = this.expect("IDENTIFIER", "Expected event name").value;
3455
- transitions.push({ from, to, event });
3456
- this.skipNewlines();
3457
- }
3458
- this.expect("RBRACE", "Expected }");
3459
- return transitions;
3460
- }
3461
- parseControlFlowBody() {
3462
- const nodes = [];
3463
- if (this.check("LBRACE")) {
3464
- this.advance();
3465
- this.skipNewlines();
3466
- while (!this.check("RBRACE") && !this.check("EOF")) {
3467
- this.skipNewlines();
3468
- if (this.check("RBRACE") || this.check("EOF")) break;
3469
- if (this.check("AT")) {
3470
- const directive = this.parseDirective();
3471
- if (directive) {
3472
- if (directive.type === "for" || directive.type === "while" || directive.type === "if" || directive.type === "forEach") {
3473
- nodes.push({
3474
- type: "fragment",
3475
- directives: [directive],
3476
- children: [],
3477
- traits: /* @__PURE__ */ new Map(),
3478
- properties: {}
3479
- });
3480
- } else if (directive.type === "trait") {
3481
- this.warn(`Standalone trait @${directive.name} in block`);
3482
- } else {
3483
- nodes.push({
3484
- type: "fragment",
3485
- directives: [directive],
3486
- children: [],
3487
- traits: /* @__PURE__ */ new Map(),
3488
- properties: {}
3489
- });
3490
- }
3491
- }
3492
- } else if (this.check("IDENTIFIER")) {
3493
- nodes.push(this.parseNode());
3494
- } else {
3495
- this.advance();
3496
- }
3497
- this.skipNewlines();
3498
- }
3499
- this.expect("RBRACE", "Expected }");
3500
- }
3501
- return nodes;
3502
- }
3503
- parseCodeBlock() {
3504
- let code = "";
3505
- let braceDepth = 0;
3506
- if (this.check("LBRACE")) {
3507
- this.advance();
3508
- braceDepth = 1;
3509
- try {
3510
- while (braceDepth > 0 && !this.check("EOF")) {
3511
- const token = this.advance();
3512
- if (token.type === "LBRACE") {
3513
- braceDepth++;
3514
- code += "{";
3515
- } else if (token.type === "RBRACE") {
3516
- braceDepth--;
3517
- if (braceDepth > 0) {
3518
- code += "}";
3519
- }
3520
- } else if (token.type === "STRING") {
3521
- code += `"${token.value}"`;
3522
- code += " ";
3523
- } else {
3524
- code += token.value;
3525
- if (token.type === "NEWLINE") {
3526
- code += "\n";
3527
- } else {
3528
- code += " ";
3529
- }
3530
- }
3531
- }
3532
- } catch (e) {
3533
- const errorMessage = e instanceof Error ? e.message : String(e);
3534
- if (errorMessage !== "ParseError") console.error(e);
3535
- this.synchronize();
3536
- }
3537
- }
3538
- return code.trim();
3539
- }
3540
- parseInlineExpression() {
3541
- let expr = "";
3542
- while (!this.check("NEWLINE") && !this.check("LBRACE") && !this.check("EOF")) {
3543
- const token = this.advance();
3544
- expr += token.value + " ";
3545
- }
3546
- return expr.trim();
3547
- }
3548
- /**
3549
- * Parse any value or expression (Entry Point)
3550
- * Handles operators like ?? and unary operators like ...
3551
- */
3552
- parseValue() {
3553
- return this.parseAssignment();
3554
- }
3555
- /**
3556
- * Parse assignment expressions (??=)
3557
- * Much lower precedence than ternary/null-coalesce
3558
- * Example: x ??= value → x = x ?? value
3559
- */
3560
- parseAssignment() {
3561
- const expr = this.parseExpression();
3562
- if (this.check("NULL_COALESCE_ASSIGN")) {
3563
- const isAssignable = typeof expr === "string" || typeof expr === "object" && expr && "__ref" in expr || // identifier or member expression
3564
- typeof expr === "object" && expr && "type" in expr && expr.type === "member";
3565
- if (isAssignable) {
3566
- this.advance();
3567
- const value = this.parseExpression();
3568
- return {
3569
- type: "nullCoalescingAssignment",
3570
- target: expr,
3571
- value
3572
- };
3573
- } else {
3574
- throw new Error(
3575
- `Cannot use ??= on non-assignable expression at line ${this.current().line}`
3576
- );
3577
- }
3578
- }
3579
- return expr;
3580
- }
3581
- /**
3582
- * Parse expression (Entry Point for operators)
3583
- * Handles Ternary Operators: cond ? true : false
3584
- */
3585
- parseExpression() {
3586
- const condition = this.parseNullCoalesce();
3587
- if (this.check("QUESTION")) {
3588
- this.advance();
3589
- const trueValue = this.parseExpression();
3590
- this.expect("COLON", "Expected : in ternary operator");
3591
- const falseValue = this.parseExpression();
3592
- return { type: "ternary", condition, trueValue, falseValue };
3593
- }
3594
- return condition;
3595
- }
3596
- /**
3597
- * Parse binary expressions: ?? (null coalesce) — lower precedence than logical OR
3598
- */
3599
- parseNullCoalesce() {
3600
- let left = this.parseLogicalOr();
3601
- while (this.check("NULL_COALESCE")) {
3602
- this.advance();
3603
- const right = this.parseLogicalOr();
3604
- left = { type: "binary", operator: "??", left, right };
3605
- }
3606
- return left;
3607
- }
3608
- /** Parse logical OR: a || b */
3609
- parseLogicalOr() {
3610
- let left = this.parseLogicalAnd();
3611
- while (this.check("OR")) {
3612
- this.advance();
3613
- const right = this.parseLogicalAnd();
3614
- left = { type: "binary", operator: "||", left, right };
3615
- }
3616
- return left;
3617
- }
3618
- /** Parse logical AND: a && b */
3619
- parseLogicalAnd() {
3620
- let left = this.parseEquality();
3621
- while (this.check("AND")) {
3622
- this.advance();
3623
- const right = this.parseEquality();
3624
- left = { type: "binary", operator: "&&", left, right };
3625
- }
3626
- return left;
3627
- }
3628
- /** Parse equality: a == b, a != b */
3629
- parseEquality() {
3630
- let left = this.parseComparison();
3631
- while (this.check("DOUBLE_EQUALS") || this.check("NOT_EQUALS")) {
3632
- const operator = this.current().value;
3633
- this.advance();
3634
- const right = this.parseComparison();
3635
- left = { type: "binary", operator, left, right };
3636
- }
3637
- return left;
3638
- }
3639
- /** Parse comparison: a < b, a > b, a <= b, a >= b */
3640
- parseComparison() {
3641
- let left = this.parseAdditive();
3642
- while (this.check("LESS_THAN") || this.check("GREATER_THAN") || this.check("LESS_EQUAL") || this.check("GREATER_EQUAL")) {
3643
- const operator = this.current().value;
3644
- this.advance();
3645
- const right = this.parseAdditive();
3646
- left = { type: "binary", operator, left, right };
3647
- }
3648
- return left;
3649
- }
3650
- /** Parse additive: a + b, a - b */
3651
- parseAdditive() {
3652
- let left = this.parseMultiplicative();
3653
- while (this.check("PLUS") || this.check("MINUS")) {
3654
- const operator = this.current().value;
3655
- this.advance();
3656
- const right = this.parseMultiplicative();
3657
- left = { type: "binary", operator, left, right };
3658
- }
3659
- return left;
3660
- }
3661
- /** Parse multiplicative: a * b, a / b, a % b */
3662
- parseMultiplicative() {
3663
- let left = this.parseUnary();
3664
- while (this.check("ASTERISK") || this.check("SLASH") || this.check("PERCENT")) {
3665
- const operator = this.current().value;
3666
- this.advance();
3667
- const right = this.parseUnary();
3668
- left = { type: "binary", operator, left, right };
3669
- }
3670
- return left;
3671
- }
3672
- /**
3673
- * Parse unary prefix expressions (!, spread, unary minus, unary plus)
3674
- */
3675
- parseUnary() {
3676
- if (this.check("SPREAD")) {
3677
- this.advance();
3678
- const arg = this.parseUnary();
3679
- return { type: "spread", argument: arg };
3680
- }
3681
- if (this.check("EXCLAMATION")) {
3682
- this.advance();
3683
- const arg = this.parseUnary();
3684
- return { type: "unary", operator: "!", argument: arg };
3685
- }
3686
- if (this.check("MINUS") || this.check("PLUS")) {
3687
- const operator = this.current().type === "MINUS" ? "-" : "+";
3688
- this.advance();
3689
- const arg = this.parseUnary();
3690
- if (typeof arg === "number") {
3691
- return operator === "-" ? -arg : arg;
3692
- }
3693
- return { type: "unary", operator, argument: arg };
3694
- }
3695
- return this.parsePrimary();
3696
- }
3697
- /**
3698
- * Parse a primary value (literal, identifier, parenthesis, etc.)
3699
- */
3700
- parsePrimary() {
3701
- const token = this.current();
3702
- if (token.type === "STRING") {
3703
- this.advance();
3704
- return token.value;
3705
- }
3706
- if (token.type === "NUMBER") {
3707
- this.advance();
3708
- const match = token.value.match(/^(-?\d+(?:\.\d+)?(?:e[+-]?\d+)?)(.*)?$/i);
3709
- if (match) {
3710
- const num = parseFloat(match[1]);
3711
- const unit = match[2];
3712
- if (unit) {
3713
- return `${num}${unit}`;
3714
- }
3715
- return num;
3716
- }
3717
- return parseFloat(token.value);
3718
- }
3719
- if (token.type === "BOOLEAN") {
3720
- this.advance();
3721
- return token.value === "true";
3722
- }
3723
- if (token.type === "NULL") {
3724
- this.advance();
3725
- return null;
3726
- }
3727
- if (token.type === "EXPRESSION") {
3728
- this.advance();
3729
- const exprId = `expr_${this.compiledExpressions.size}`;
3730
- this.compiledExpressions.set(exprId, token.value);
3731
- return { __expr: exprId, __raw: token.value };
3732
- }
3733
- if (token.type === "TEMPLATE_STRING") {
3734
- this.advance();
3735
- return { type: "templateLiteral", value: token.value };
3736
- }
3737
- if (token.type === "LBRACKET") {
3738
- return this.parseArray();
3739
- }
3740
- if (token.type === "LBRACE") {
3741
- return this.parseBlockContent();
3742
- }
3743
- if (token.type === "HASH") {
3744
- this.advance();
3745
- const nextToken = this.current();
3746
- if (nextToken.type === "IDENTIFIER" || nextToken.type === "NUMBER") {
3747
- const hexValue = this.advance().value;
3748
- return `#${hexValue}`;
3749
- }
3750
- return `#`;
3751
- }
3752
- if (token.type === "THIS") {
3753
- this.advance();
3754
- let ref = "this";
3755
- while (this.check("DOT")) {
3756
- this.advance();
3757
- const part = this.expect("IDENTIFIER", "Expected property name").value;
3758
- ref += "." + part;
3759
- }
3760
- return { __ref: ref };
3761
- }
3762
- if (token.type === "LPAREN") {
3763
- let isArrow = false;
3764
- let i = 1;
3765
- let parenDepth = 1;
3766
- while (this.peek(i).type !== "EOF") {
3767
- const t = this.peek(i);
3768
- if (t.type === "LPAREN") parenDepth++;
3769
- if (t.type === "RPAREN") {
3770
- parenDepth--;
3771
- if (parenDepth === 0) {
3772
- const next = this.peek(i + 1);
3773
- if (next.type === "ARROW") isArrow = true;
3774
- if (next.type === "COLON") {
3775
- let j = i + 2;
3776
- while (this.peek(j).type === "IDENTIFIER" || this.peek(j).type === "LBRACKET" || this.peek(j).type === "RBRACKET")
3777
- j++;
3778
- if (this.peek(j).type === "ARROW") isArrow = true;
3779
- }
3780
- break;
3781
- }
3782
- }
3783
- i++;
3784
- }
3785
- if (isArrow) {
3786
- return this.parseArrowFunction();
3787
- }
3788
- return this.parseParenExpression();
3789
- }
3790
- if (token.type === "MATCH") {
3791
- return this.parseMatchExpression();
3792
- }
3793
- const isIdentifierLike = token.type === "IDENTIFIER" || token.type === "STATE" || token.type === "INITIAL" || token.type === "STATE_MACHINE" || token.type === "TRANSITION" || token.type === "ON_ENTRY" || token.type === "ON_EXIT";
3794
- if (isIdentifierLike) {
3795
- if (this.peek(1).type === "ARROW") {
3796
- return this.parseArrowFunction();
3797
- }
3798
- this.advance();
3799
- let ref = token.value;
3800
- while (this.check("DOT") || this.check("OPTIONAL_DOT") || this.check("LBRACKET")) {
3801
- if (this.check("OPTIONAL_DOT")) {
3802
- this.advance();
3803
- const nextToken = this.current();
3804
- const isPropertyName = nextToken.type === "IDENTIFIER" || nextToken.type === "STATE" || nextToken.type === "INITIAL" || nextToken.type === "STATE_MACHINE" || nextToken.type === "TRANSITION" || nextToken.type === "ON_ENTRY" || nextToken.type === "ON_EXIT";
3805
- if (isPropertyName) {
3806
- ref += "?." + this.advance().value;
3807
- } else {
3808
- this.error("Expected property name after optional chaining (?.)", "HSP002");
3809
- }
3810
- } else if (this.check("LBRACKET")) {
3811
- this.advance();
3812
- const indexExpr = this.parseValue();
3813
- this.expect("RBRACKET", "Expected ]");
3814
- const base = ref;
3815
- return { type: "computedMember", object: { __ref: base }, property: indexExpr };
3816
- } else {
3817
- this.advance();
3818
- const nextToken = this.current();
3819
- const isPropertyName = nextToken.type === "IDENTIFIER" || nextToken.type === "STATE" || nextToken.type === "INITIAL" || nextToken.type === "STATE_MACHINE" || nextToken.type === "TRANSITION" || nextToken.type === "ON_ENTRY" || nextToken.type === "ON_EXIT";
3820
- if (isPropertyName) {
3821
- ref += "." + this.advance().value;
3822
- } else {
3823
- this.error("Expected property name after dot (.)", "HSP002");
3824
- }
3825
- }
3826
- }
3827
- if (this.check("LPAREN")) {
3828
- const args = this.parseParenExpression();
3829
- return { type: "call", callee: ref, args };
3830
- }
3831
- return { __ref: ref };
3832
- }
3833
- if (this.check("AT")) {
3834
- const dir = this.parseDirective();
3835
- return dir;
3836
- }
3837
- this.error(
3838
- `Unexpected token in expression: ${token.type} "${token.value}". Expected value, identifier, or expression`,
3839
- "HSP300"
3840
- );
3841
- const err = new Error("ParseError");
3842
- err.message = "ParseError";
3843
- throw err;
3844
- }
3845
- parseParenExpression() {
3846
- this.expect("LPAREN", "Expected (");
3847
- const items = [];
3848
- while (!this.check("RPAREN") && !this.check("EOF")) {
3849
- items.push(this.parseValue());
3850
- if (this.check("COMMA")) this.advance();
3851
- }
3852
- this.expect("RPAREN", "Expected )");
3853
- return items.length === 1 ? items[0] : items;
3854
- }
3855
- parseArrowFunction() {
3856
- const params = [];
3857
- if (this.check("LPAREN")) {
3858
- this.advance();
3859
- while (!this.check("RPAREN") && !this.check("EOF")) {
3860
- if (this.check("SPREAD")) {
3861
- this.advance();
3862
- const name2 = this.expect("IDENTIFIER", "Expected parameter name after ...").value;
3863
- let type2 = null;
3864
- if (this.check("COLON")) {
3865
- this.advance();
3866
- type2 = this.expect("IDENTIFIER", "Expected type").value;
3867
- }
3868
- params.push({ name: name2, type: type2, rest: true });
3869
- if (this.check("COMMA")) this.advance();
3870
- break;
3871
- }
3872
- const name = this.expect("IDENTIFIER", "Expected parameter name").value;
3873
- let type = null;
3874
- if (this.check("COLON")) {
3875
- this.advance();
3876
- type = this.expect("IDENTIFIER", "Expected type").value;
3877
- }
3878
- params.push({ name, type });
3879
- if (this.check("COMMA")) this.advance();
3880
- }
3881
- this.expect("RPAREN", "Expected )");
3882
- } else {
3883
- if (this.check("SPREAD")) {
3884
- this.advance();
3885
- const name = this.expect("IDENTIFIER", "Expected parameter name after ...").value;
3886
- params.push({ name, type: null, rest: true });
3887
- } else {
3888
- const name = this.expect("IDENTIFIER", "Expected parameter name").value;
3889
- params.push({ name, type: null });
3890
- }
3891
- }
3892
- let returnType = null;
3893
- if (this.check("COLON")) {
3894
- this.advance();
3895
- returnType = this.expect("IDENTIFIER", "Expected return type").value;
3896
- }
3897
- this.expect("ARROW", "Expected =>");
3898
- let body;
3899
- if (this.check("LBRACE")) {
3900
- body = this.parseCodeBlock();
3901
- } else {
3902
- body = this.parseInlineExpression();
3903
- }
3904
- return { type: "arrow_function", params, returnType, body };
3905
- }
3906
- parseArray() {
3907
- const arr = [];
3908
- this.expect("LBRACKET", "Expected [");
3909
- this.skipNewlines();
3910
- while (!this.check("RBRACKET") && !this.check("EOF")) {
3911
- const beforePos = this.pos;
3912
- this.skipNewlines();
3913
- if (this.check("RBRACKET") || this.check("EOF")) break;
3914
- if (this.check("SPREAD")) {
3915
- this.advance();
3916
- const spreadArg = this.parseValue();
3917
- if (spreadArg === null) {
3918
- this.error(
3919
- "Expected expression after spread operator (...) in array. Example: [...items]",
3920
- "HSP300"
3921
- );
3922
- } else {
3923
- arr.push({ type: "spread", argument: spreadArg });
3924
- }
3925
- } else {
3926
- const value = this.parseValue();
3927
- if (value !== null) {
3928
- arr.push(value);
3929
- } else if (this.pos === beforePos) {
3930
- this.advance();
3931
- }
3932
- }
3933
- if (this.check("COMMA")) this.advance();
3934
- this.skipNewlines();
3935
- }
3936
- this.expect("RBRACKET", "Expected ]");
3937
- return arr;
3938
- }
3939
- parseObject() {
3940
- const obj = {};
3941
- this.expect("LBRACE", "Expected {");
3942
- this.skipNewlines();
3943
- while (!this.check("RBRACE") && !this.check("EOF")) {
3944
- this.skipNewlines();
3945
- if (this.check("RBRACE") || this.check("EOF")) break;
3946
- if (this.check("SPREAD")) {
3947
- this.advance();
3948
- const spreadArg = this.parseValue();
3949
- if (spreadArg === null) {
3950
- this.error(
3951
- "Expected expression after spread operator (...) in object. Example: {...template}",
3952
- "HSP300"
3953
- );
3954
- } else {
3955
- const spreadKey = `__spread_${Object.keys(obj).length}`;
3956
- obj[spreadKey] = { type: "spread", argument: spreadArg };
3957
- }
3958
- } else if (this.check("IDENTIFIER")) {
3959
- const key = this.advance().value;
3960
- if (this.check("COLON") || this.check("EQUALS")) {
3961
- this.advance();
3962
- obj[key] = this.parseValue();
3963
- } else {
3964
- obj[key] = true;
3965
- }
3966
- } else {
3967
- this.advance();
3968
- continue;
3969
- }
3970
- if (this.check("COMMA")) this.advance();
3971
- this.skipNewlines();
3972
- }
3973
- this.expect("RBRACE", "Expected }");
3974
- return obj;
3975
- }
3976
- /**
3977
- * Parse a match expression: match subject { pattern => body, ... }
3978
- * Supports:
3979
- * - Literal patterns: "idle", 42, true
3980
- * - Wildcard pattern: _
3981
- * - Binding patterns: x (captures value)
3982
- * - Guard clauses: pattern if condition => body
3983
- */
3984
- parseMatchExpression() {
3985
- const startToken = this.current();
3986
- this.expect("MATCH", "Expected match keyword");
3987
- const subject = this.parseValue();
3988
- if (subject === null) {
3989
- this.error("Expected expression after match keyword", "HSP300");
3990
- return null;
3991
- }
3992
- this.expect("LBRACE", "Expected { after match subject");
3993
- this.skipNewlines();
3994
- const cases = [];
3995
- let hasWildcard = false;
3996
- while (!this.check("RBRACE") && !this.check("EOF")) {
3997
- this.skipNewlines();
3998
- if (this.check("RBRACE")) break;
3999
- const caseNode = this.parseMatchCase();
4000
- if (caseNode) {
4001
- cases.push(caseNode);
4002
- if (caseNode.pattern && caseNode.pattern.type === "wildcard-pattern") {
4003
- hasWildcard = true;
4004
- }
4005
- }
4006
- if (this.check("COMMA")) this.advance();
4007
- this.skipNewlines();
4008
- }
4009
- this.expect("RBRACE", "Expected } to close match expression");
4010
- return {
4011
- type: "match",
4012
- subject,
4013
- cases,
4014
- hasWildcard,
4015
- sourceLocation: {
4016
- line: startToken.line,
4017
- column: startToken.column
4018
- }
4019
- };
4020
- }
4021
- /**
4022
- * Parse a single match case: pattern [if guard] => body
4023
- */
4024
- parseMatchCase() {
4025
- const pattern = this.parseMatchPattern();
4026
- if (!pattern) {
4027
- return null;
4028
- }
4029
- let guard;
4030
- if (this.check("IDENTIFIER") && this.current().value === "if") {
4031
- this.advance();
4032
- let guardExpr = "";
4033
- while (!this.check("ARROW") && !this.check("EOF") && !this.check("RBRACE")) {
4034
- guardExpr += this.current().value + " ";
4035
- this.advance();
4036
- }
4037
- guard = guardExpr.trim();
4038
- }
4039
- this.expect("ARROW", "Expected => after match pattern");
4040
- let body;
4041
- if (this.check("LBRACE")) {
4042
- body = this.parseBlockContent();
4043
- } else {
4044
- body = this.parseValue();
4045
- }
4046
- return {
4047
- type: "match-case",
4048
- pattern,
4049
- body,
4050
- guard
4051
- };
4052
- }
4053
- /**
4054
- * Parse a match pattern:
4055
- * - Literal: "string", 42, true
4056
- * - Wildcard: _
4057
- * - Binding: identifier
4058
- */
4059
- parseMatchPattern() {
4060
- const token = this.current();
4061
- if (token.type === "UNDERSCORE" || token.type === "IDENTIFIER" && token.value === "_") {
4062
- this.advance();
4063
- return {
4064
- type: "wildcard-pattern",
4065
- symbol: "_"
4066
- };
4067
- }
4068
- if (token.type === "STRING") {
4069
- this.advance();
4070
- return {
4071
- type: "literal-pattern",
4072
- value: token.value
4073
- };
4074
- }
4075
- if (token.type === "NUMBER") {
4076
- this.advance();
4077
- return {
4078
- type: "literal-pattern",
4079
- value: parseFloat(token.value)
4080
- };
4081
- }
4082
- if (token.type === "BOOLEAN") {
4083
- this.advance();
4084
- return {
4085
- type: "literal-pattern",
4086
- value: token.value === "true"
4087
- };
4088
- }
4089
- if (token.type === "IDENTIFIER") {
4090
- this.advance();
4091
- return {
4092
- type: "binding-pattern",
4093
- name: token.value
4094
- };
4095
- }
4096
- if (token.type === "NULL") {
4097
- this.advance();
4098
- return {
4099
- type: "literal-pattern",
4100
- value: null
4101
- };
4102
- }
4103
- this.error(`Expected match pattern (literal, identifier, or _), got ${token.type}`, "HSP300");
4104
- return null;
4105
- }
4106
- current() {
4107
- return this.tokens[this.pos] || { type: "EOF", value: "", line: 0, column: 0 };
4108
- }
4109
- peek(offset = 0) {
4110
- return this.tokens[this.pos + offset] || { type: "EOF", value: "", line: 0, column: 0 };
4111
- }
4112
- check(type) {
4113
- return this.current().type === type;
4114
- }
4115
- advance() {
4116
- const token = this.current();
4117
- if (this.pos < this.tokens.length) {
4118
- this.pos++;
4119
- }
4120
- return token;
4121
- }
4122
- previous() {
4123
- return this.tokens[this.pos - 1] || this.current();
4124
- }
4125
- match(types) {
4126
- for (const type of types) {
4127
- if (this.check(type)) {
4128
- return this.advance();
4129
- }
4130
- }
4131
- return null;
4132
- }
4133
- expect(type, message) {
4134
- if (!this.check(type)) {
4135
- const current = this.current();
4136
- const fullMessage = `${message}. Got ${current.type} "${current.value}"`;
4137
- let errorCode = "HSP001";
4138
- let suggestion;
4139
- switch (type) {
4140
- case "RBRACE":
4141
- errorCode = "HSP004";
4142
- suggestion = "Check for matching opening brace { and ensure all blocks are properly closed";
4143
- break;
4144
- case "RBRACKET":
4145
- errorCode = "HSP005";
4146
- suggestion = "Check for matching opening bracket [ and ensure all arrays are properly closed";
4147
- break;
4148
- case "RPAREN":
4149
- errorCode = "HSP006";
4150
- suggestion = "Check for matching opening parenthesis ( and ensure all expressions are properly closed";
4151
- break;
4152
- case "COLON":
4153
- errorCode = "HSP009";
4154
- suggestion = "Properties use colon syntax: propertyName: value";
4155
- break;
4156
- case "IDENTIFIER":
4157
- errorCode = "HSP002";
4158
- if (current.type === "IDENTIFIER") {
4159
- const similar = findSimilarKeyword(current.value);
4160
- if (similar) {
4161
- suggestion = `Did you mean '${similar}'?`;
4162
- }
4163
- }
4164
- break;
4165
- case "LBRACE":
4166
- errorCode = "HSP100";
4167
- suggestion = "Expected opening brace { to start block";
4168
- break;
4169
- default:
4170
- errorCode = "HSP001";
4171
- }
4172
- if (suggestion) {
4173
- this.errorWithSuggestion(fullMessage, suggestion, errorCode);
4174
- } else {
4175
- this.error(fullMessage, errorCode);
4176
- }
4177
- if (type === "RBRACE" || type === "LBRACE" || type === "IDENTIFIER") {
4178
- this.synchronize();
4179
- }
4180
- return current;
4181
- }
4182
- return this.advance();
4183
- }
4184
- skipNewlines() {
4185
- while (this.check("NEWLINE") || this.check("INDENT") || this.check("DEDENT")) {
4186
- this.advance();
4187
- }
4188
- }
4189
- /** Skip a balanced parenthesised list ( ... ) including nested parens */
4190
- skipParens() {
4191
- if (!this.check("LPAREN")) return;
4192
- this.advance();
4193
- let depth = 1;
4194
- while (depth > 0 && !this.check("EOF")) {
4195
- if (this.check("LPAREN")) depth++;
4196
- if (this.check("RPAREN")) depth--;
4197
- this.advance();
4198
- }
4199
- }
4200
- skipBraces() {
4201
- if (!this.check("LBRACE")) return;
4202
- this.advance();
4203
- let depth = 1;
4204
- while (depth > 0 && !this.check("EOF")) {
4205
- if (this.check("LBRACE")) depth++;
4206
- if (this.check("RBRACE")) depth--;
4207
- this.advance();
4208
- }
4209
- }
4210
- error(message, code = "HSP001") {
4211
- const token = this.current();
4212
- const line = token.line;
4213
- const column = token.column;
4214
- let suggestion;
4215
- if (token.type === "IDENTIFIER") {
4216
- const similar = findSimilarKeyword(token.value);
4217
- if (similar) {
4218
- suggestion = `Did you mean '${similar}'?`;
4219
- }
4220
- }
4221
- this.errors.push(
4222
- createRichError(code, message, line, column, {
4223
- source: this.source,
4224
- suggestion,
4225
- severity: "error"
4226
- })
4227
- );
4228
- }
4229
- errorWithSuggestion(message, suggestion, code = "HSP001") {
4230
- const token = this.current();
4231
- this.errors.push(
4232
- createRichError(code, message, token.line, token.column, {
4233
- source: this.source,
4234
- suggestion,
4235
- severity: "error"
4236
- })
4237
- );
4238
- }
4239
- traitError(traitName) {
4240
- const token = this.current();
4241
- this.errors.push(createTraitError(traitName, token.line, token.column, this.source));
4242
- }
4243
- warn(message, code = "HSP001") {
4244
- const token = this.current();
4245
- this.warnings.push(
4246
- createRichError(code, message, token.line, token.column, {
4247
- source: this.source,
4248
- severity: "warning"
4249
- })
4250
- );
4251
- }
4252
- /**
4253
- * Detect common mistakes and provide context-aware error messages
4254
- */
4255
- detectCommonMistake() {
4256
- const current = this.current();
4257
- const prev = this.pos > 0 ? this.tokens[this.pos - 1] : null;
4258
- const next = this.pos + 1 < this.tokens.length ? this.tokens[this.pos + 1] : null;
4259
- if (current.type === "EQUALS" && prev?.type === "IDENTIFIER") {
4260
- return {
4261
- message: `Unexpected '=' after property name '${prev.value}'`,
4262
- suggestion: "Use ':' instead of '=' for property assignment. Example: propertyName: value",
4263
- code: "HSP009"
4264
- };
4265
- }
4266
- if (current.value === ";") {
4267
- return {
4268
- message: "Unexpected semicolon",
4269
- suggestion: "HoloScript does not require semicolons. Remove the semicolon to continue.",
4270
- code: "HSP001"
4271
- };
4272
- }
4273
- if (current.type === "IDENTIFIER" && chunkXG23EUQX_cjs.VR_TRAITS.includes(current.value)) {
4274
- if (prev?.type !== "AT") {
4275
- return {
4276
- message: `'${current.value}' is a trait and requires '@' prefix`,
4277
- suggestion: `Use '@${current.value}' to apply this trait`,
4278
- code: "HSP200"
4279
- };
4280
- }
4281
- }
4282
- if (current.type === "STRING" && next?.type === "COLON") {
4283
- return {
4284
- message: "Property names should not be quoted in HoloScript",
4285
- suggestion: `Remove quotes: use ${current.value.replace(/['"]/g, "")}: instead of "${current.value}":`,
4286
- code: "HSP101"
4287
- };
4288
- }
4289
- if (current.value === "function" && prev?.type === "COLON") {
4290
- return {
4291
- message: "Unexpected 'function' keyword",
4292
- suggestion: "Use arrow function syntax: handler: (args) => { ... }",
4293
- code: "HSP300"
4294
- };
4295
- }
4296
- if (current.type === "SPREAD" && next && (next.type === "RBRACE" || next.type === "RBRACKET" || next.type === "COMMA" || next.type === "NEWLINE")) {
4297
- return {
4298
- message: "Spread operator (...) requires a target expression",
4299
- suggestion: "Provide an expression to spread: ...targetObject or ...targetArray",
4300
- code: "HSP002"
4301
- };
4302
- }
4303
- return null;
4304
- }
4305
- /**
4306
- * Enhanced error reporting with common mistake detection
4307
- */
4308
- errorWithContext(message, code = "HSP001") {
4309
- const commonMistake = this.detectCommonMistake();
4310
- if (commonMistake) {
4311
- this.errorWithSuggestion(commonMistake.message, commonMistake.suggestion, commonMistake.code);
4312
- return;
4313
- }
4314
- this.error(message, code);
4315
- }
4316
- /**
4317
- * Synchronize parser state after an error
4318
- * Skips tokens until a potential recovery point (newline followed by keyword/directive)
4319
- */
4320
- synchronize() {
4321
- this.advance();
4322
- while (!this.check("EOF")) {
4323
- if (this.check("RBRACE")) {
4324
- return;
4325
- }
4326
- if (this.check("IDENTIFIER") && ["orb", "template", "logic", "object", "composition", "scene", "group"].includes(
4327
- this.current().value
4328
- )) {
4329
- return;
4330
- }
4331
- if (this.check("AT")) {
4332
- return;
4333
- }
4334
- this.advance();
4335
- }
4336
- }
4337
- /**
4338
- * Mini-sync for property lists: skips until next line or comma
4339
- */
4340
- synchronizeProperty() {
4341
- this.advance();
4342
- while (!this.check("EOF")) {
4343
- if (this.check("RBRACE") || this.check("LBRACE")) {
4344
- return;
4345
- }
4346
- if (this.check("IDENTIFIER") || this.check("STRING") || this.check("SPREAD") || this.check("AT")) {
4347
- return;
4348
- }
4349
- if (this.check("NEWLINE")) {
4350
- this.advance();
4351
- this.skipNewlines();
4352
- if (this.check("IDENTIFIER") || this.check("STRING") || this.check("SPREAD") || this.check("AT")) {
4353
- return;
4354
- }
4355
- }
4356
- if (this.check("COMMA")) {
4357
- this.advance();
4358
- return;
4359
- }
4360
- this.advance();
4361
- }
4362
- }
4363
- /**
4364
- * Synchronize for array context: skip to next valid array element or closing bracket
4365
- */
4366
- synchronizeArray() {
4367
- while (!this.check("EOF")) {
4368
- if (this.check("RBRACKET")) {
4369
- return;
4370
- }
4371
- if (this.check("COMMA")) {
4372
- this.advance();
4373
- this.skipNewlines();
4374
- return;
4375
- }
4376
- if (this.check("NEWLINE")) {
4377
- this.advance();
4378
- this.skipNewlines();
4379
- if (this.check("RBRACKET") || this.isLikelyValue(this.current()) || this.check("SPREAD")) {
4380
- return;
4381
- }
4382
- }
4383
- this.advance();
4384
- }
4385
- }
4386
- /**
4387
- * Synchronize for expression context: skip to end of expression
4388
- */
4389
- synchronizeExpression() {
4390
- let parenDepth = 0;
4391
- let braceDepth = 0;
4392
- let bracketDepth = 0;
4393
- while (!this.check("EOF")) {
4394
- const token = this.current();
4395
- if (token.type === "LPAREN") parenDepth++;
4396
- else if (token.type === "RPAREN") {
4397
- if (parenDepth === 0) return;
4398
- parenDepth--;
4399
- } else if (token.type === "LBRACE") braceDepth++;
4400
- else if (token.type === "RBRACE") {
4401
- if (braceDepth === 0) return;
4402
- braceDepth--;
4403
- } else if (token.type === "LBRACKET") bracketDepth++;
4404
- else if (token.type === "RBRACKET") {
4405
- if (bracketDepth === 0) return;
4406
- bracketDepth--;
4407
- }
4408
- if (parenDepth === 0 && braceDepth === 0 && bracketDepth === 0) {
4409
- if (this.check("NEWLINE") || this.check("COMMA")) {
4410
- return;
4411
- }
4412
- }
4413
- this.advance();
4414
- }
4415
- }
4416
- /**
4417
- * Attempt to recover from missing colon by looking ahead
4418
- * Returns true if recovery was successful
4419
- */
4420
- tryRecoverMissingColon() {
4421
- if (this.check("IDENTIFIER")) {
4422
- const nextPos = this.pos + 1;
4423
- if (nextPos < this.tokens.length) {
4424
- const nextToken = this.tokens[nextPos];
4425
- if (this.isLikelyValue(nextToken) || nextToken.type === "IDENTIFIER") {
4426
- this.warn(
4427
- `Missing colon after property "${this.current().value}". Consider adding ':' between property name and value`,
4428
- "HSP009"
4429
- );
4430
- return true;
4431
- }
4432
- }
4433
- }
4434
- return false;
4435
- }
4436
- /**
4437
- * Helper to check if current token is a natural boundary after a value
4438
- */
4439
- isValueBoundary() {
4440
- return this.check("NEWLINE") || this.check("RBRACE") || this.check("COMMA") || this.check("IDENTIFIER") || this.check("SPREAD") || this.check("AT") || this.check("EOF");
4441
- }
4442
- /**
4443
- * Helper to check if a token is likely the start of a value
4444
- */
4445
- isLikelyValue(token) {
4446
- return token.type === "STRING" || token.type === "NUMBER" || token.type === "LBRACKET" || token.type === "LBRACE" || token.type === "BOOLEAN" || token.type === "NULL" || token.type === "TEMPLATE_STRING";
4447
- }
4448
- /**
4449
- * Parse a block of raw code (balanced braces)
4450
- */
4451
- parseRawBlock() {
4452
- const startToken = this.expect("LBRACE", "Expected {");
4453
- const startOffset = startToken.offset + 1;
4454
- let braceDepth = 1;
4455
- let endOffset = startOffset;
4456
- while (braceDepth > 0 && this.pos < this.tokens.length) {
4457
- const token = this.current();
4458
- if (token.type === "EOF") break;
4459
- if (token.type === "LBRACE") {
4460
- braceDepth++;
4461
- } else if (token.type === "RBRACE") {
4462
- braceDepth--;
4463
- if (braceDepth === 0) {
4464
- endOffset = token.offset;
4465
- break;
4466
- }
4467
- }
4468
- this.advance();
4469
- }
4470
- this.expect("RBRACE", "Expected }");
4471
- return this.source.substring(startOffset, endOffset).trim();
4472
- }
4473
- };
4474
- function createParser(options) {
4475
- return new HoloScriptPlusParser(options);
4476
- }
4477
- function parse(source, options) {
4478
- const parser = createParser(options);
4479
- return parser.parse(source);
4480
- }
4481
-
4482
- exports.ChunkDetector = ChunkDetector;
4483
- exports.HSPLUS_ERROR_CODES = HSPLUS_ERROR_CODES;
4484
- exports.HoloScriptPlusParser = HoloScriptPlusParser;
4485
- exports.ParseCache = ParseCache;
4486
- exports.createKeywordError = createKeywordError;
4487
- exports.createParser = createParser;
4488
- exports.createRichError = createRichError;
4489
- exports.createTraitError = createTraitError;
4490
- exports.findSimilarKeyword = findSimilarKeyword;
4491
- exports.findSimilarTrait = findSimilarTrait;
4492
- exports.formatRichError = formatRichError;
4493
- exports.formatRichErrors = formatRichErrors;
4494
- exports.getErrorCodeDocumentation = getErrorCodeDocumentation;
4495
- exports.getSourceContext = getSourceContext;
4496
- exports.globalParseCache = globalParseCache;
4497
- exports.parse = parse;
4498
- //# sourceMappingURL=chunk-LZ266PCM.cjs.map
4499
- //# sourceMappingURL=chunk-LZ266PCM.cjs.map