@jitl/opentui-core 0.1.97-next.c8a3f05

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 (180) hide show
  1. package/3d/SpriteResourceManager.d.ts +74 -0
  2. package/3d/SpriteUtils.d.ts +13 -0
  3. package/3d/TextureUtils.d.ts +24 -0
  4. package/3d/ThreeRenderable.d.ts +40 -0
  5. package/3d/WGPURenderer.d.ts +61 -0
  6. package/3d/animation/ExplodingSpriteEffect.d.ts +71 -0
  7. package/3d/animation/PhysicsExplodingSpriteEffect.d.ts +76 -0
  8. package/3d/animation/SpriteAnimator.d.ts +124 -0
  9. package/3d/animation/SpriteParticleGenerator.d.ts +62 -0
  10. package/3d/canvas.d.ts +44 -0
  11. package/3d/index.d.ts +12 -0
  12. package/3d/physics/PlanckPhysicsAdapter.d.ts +19 -0
  13. package/3d/physics/RapierPhysicsAdapter.d.ts +19 -0
  14. package/3d/physics/physics-interface.d.ts +27 -0
  15. package/3d.d.ts +2 -0
  16. package/3d.js +33843 -0
  17. package/3d.js.map +155 -0
  18. package/LICENSE +21 -0
  19. package/NativeSpanFeed.d.ts +41 -0
  20. package/README.md +65 -0
  21. package/Renderable.d.ts +334 -0
  22. package/Worker-vajwjk0s.js +94 -0
  23. package/Worker-vajwjk0s.js.map +10 -0
  24. package/animation/Timeline.d.ts +126 -0
  25. package/ansi.d.ts +13 -0
  26. package/assets/javascript/highlights.scm +205 -0
  27. package/assets/javascript/tree-sitter-javascript.wasm +0 -0
  28. package/assets/markdown/highlights.scm +150 -0
  29. package/assets/markdown/injections.scm +27 -0
  30. package/assets/markdown/tree-sitter-markdown.wasm +0 -0
  31. package/assets/markdown_inline/highlights.scm +115 -0
  32. package/assets/markdown_inline/tree-sitter-markdown_inline.wasm +0 -0
  33. package/assets/typescript/highlights.scm +604 -0
  34. package/assets/typescript/tree-sitter-typescript.wasm +0 -0
  35. package/assets/zig/highlights.scm +284 -0
  36. package/assets/zig/tree-sitter-zig.wasm +0 -0
  37. package/buffer.d.ts +111 -0
  38. package/compat/FFIType.d.ts +304 -0
  39. package/compat/Worker.d.ts +1 -0
  40. package/compat/bun-ffi-structs.d.ts +2 -0
  41. package/compat/ffi.d.ts +86 -0
  42. package/compat/nodejs/Worker.d.ts +16 -0
  43. package/compat/nodejs/bun-ffi-structs/index.d.ts +46 -0
  44. package/compat/nodejs/ffi.d.ts +21 -0
  45. package/compat/nodejs/registerBun.d.ts +1 -0
  46. package/compat/nodejs/registerResolveJs.d.ts +1 -0
  47. package/compat/nodejs/runtime.d.ts +7 -0
  48. package/compat/nodejs/test.d.ts +4 -0
  49. package/compat/nodejs/trampoline.worker.d.ts +1 -0
  50. package/compat/runtime.d.ts +8 -0
  51. package/compat/test.d.ts +1 -0
  52. package/compat/testHelpers.d.ts +18 -0
  53. package/console.d.ts +144 -0
  54. package/edit-buffer.d.ts +98 -0
  55. package/editor-view.d.ts +73 -0
  56. package/ffi-x3zvcksd.js +25 -0
  57. package/ffi-x3zvcksd.js.map +9 -0
  58. package/index-5yqvbmcz.js +220 -0
  59. package/index-5yqvbmcz.js.map +10 -0
  60. package/index-bnfz2g63.js +654 -0
  61. package/index-bnfz2g63.js.map +10 -0
  62. package/index-cbvybypy.js +43 -0
  63. package/index-cbvybypy.js.map +10 -0
  64. package/index-hjna9d1h.js +12074 -0
  65. package/index-hjna9d1h.js.map +42 -0
  66. package/index-jjp8mmgk.js +19991 -0
  67. package/index-jjp8mmgk.js.map +70 -0
  68. package/index-re3ntm60.js +51 -0
  69. package/index-re3ntm60.js.map +9 -0
  70. package/index-t16hn6zn.js +411 -0
  71. package/index-t16hn6zn.js.map +10 -0
  72. package/index-tkk6cmr2.js +650 -0
  73. package/index-tkk6cmr2.js.map +10 -0
  74. package/index.d.ts +23 -0
  75. package/index.js +480 -0
  76. package/index.js.map +9 -0
  77. package/lib/KeyHandler.d.ts +61 -0
  78. package/lib/RGBA.d.ts +26 -0
  79. package/lib/ascii.font.d.ts +508 -0
  80. package/lib/border.d.ts +51 -0
  81. package/lib/bunfs.d.ts +7 -0
  82. package/lib/clipboard.d.ts +17 -0
  83. package/lib/clock.d.ts +15 -0
  84. package/lib/data-paths.d.ts +26 -0
  85. package/lib/debounce.d.ts +42 -0
  86. package/lib/detect-links.d.ts +6 -0
  87. package/lib/env.d.ts +42 -0
  88. package/lib/extmarks-history.d.ts +17 -0
  89. package/lib/extmarks.d.ts +89 -0
  90. package/lib/hast-styled-text.d.ts +17 -0
  91. package/lib/index.d.ts +21 -0
  92. package/lib/keymapping.d.ts +25 -0
  93. package/lib/objects-in-viewport.d.ts +24 -0
  94. package/lib/output.capture.d.ts +24 -0
  95. package/lib/parse.keypress-kitty.d.ts +2 -0
  96. package/lib/parse.keypress.d.ts +26 -0
  97. package/lib/parse.mouse.d.ts +30 -0
  98. package/lib/paste.d.ts +7 -0
  99. package/lib/queue.d.ts +15 -0
  100. package/lib/renderable.validations.d.ts +12 -0
  101. package/lib/scroll-acceleration.d.ts +43 -0
  102. package/lib/selection.d.ts +64 -0
  103. package/lib/singleton.d.ts +7 -0
  104. package/lib/stdin-parser.d.ts +87 -0
  105. package/lib/styled-text.d.ts +63 -0
  106. package/lib/terminal-capability-detection.d.ts +30 -0
  107. package/lib/terminal-palette.d.ts +50 -0
  108. package/lib/tree-sitter/assets/update.d.ts +11 -0
  109. package/lib/tree-sitter/client.d.ts +47 -0
  110. package/lib/tree-sitter/default-parsers.d.ts +2 -0
  111. package/lib/tree-sitter/download-utils.d.ts +21 -0
  112. package/lib/tree-sitter/index.d.ts +8 -0
  113. package/lib/tree-sitter/parser.worker.d.ts +1 -0
  114. package/lib/tree-sitter/parsers-config.d.ts +53 -0
  115. package/lib/tree-sitter/resolve-ft.d.ts +5 -0
  116. package/lib/tree-sitter/types.d.ts +82 -0
  117. package/lib/tree-sitter-styled-text.d.ts +14 -0
  118. package/lib/validate-dir-name.d.ts +1 -0
  119. package/lib/yoga.options.d.ts +32 -0
  120. package/package.json +80 -0
  121. package/parser.worker.js +888 -0
  122. package/parser.worker.js.map +12 -0
  123. package/plugins/core-slot.d.ts +72 -0
  124. package/plugins/registry.d.ts +42 -0
  125. package/plugins/types.d.ts +34 -0
  126. package/post/effects.d.ts +147 -0
  127. package/post/filters.d.ts +65 -0
  128. package/post/matrices.d.ts +20 -0
  129. package/renderables/ASCIIFont.d.ts +52 -0
  130. package/renderables/Box.d.ts +81 -0
  131. package/renderables/Code.d.ts +78 -0
  132. package/renderables/Diff.d.ts +142 -0
  133. package/renderables/EditBufferRenderable.d.ts +237 -0
  134. package/renderables/FrameBuffer.d.ts +16 -0
  135. package/renderables/Input.d.ts +67 -0
  136. package/renderables/LineNumberRenderable.d.ts +78 -0
  137. package/renderables/Markdown.d.ts +181 -0
  138. package/renderables/ScrollBar.d.ts +77 -0
  139. package/renderables/ScrollBox.d.ts +124 -0
  140. package/renderables/Select.d.ts +115 -0
  141. package/renderables/Slider.d.ts +47 -0
  142. package/renderables/TabSelect.d.ts +96 -0
  143. package/renderables/Text.d.ts +36 -0
  144. package/renderables/TextBufferRenderable.d.ts +105 -0
  145. package/renderables/TextNode.d.ts +91 -0
  146. package/renderables/TextTable.d.ts +140 -0
  147. package/renderables/Textarea.d.ts +63 -0
  148. package/renderables/TimeToFirstDraw.d.ts +24 -0
  149. package/renderables/__tests__/renderable-test-utils.d.ts +12 -0
  150. package/renderables/composition/VRenderable.d.ts +16 -0
  151. package/renderables/composition/constructs.d.ts +35 -0
  152. package/renderables/composition/vnode.d.ts +46 -0
  153. package/renderables/index.d.ts +23 -0
  154. package/renderables/markdown-parser.d.ts +10 -0
  155. package/renderer.d.ts +419 -0
  156. package/runtime-hdpkc6qf.js +220 -0
  157. package/runtime-hdpkc6qf.js.map +17 -0
  158. package/runtime-plugin-support.d.ts +3 -0
  159. package/runtime-plugin-support.js +31 -0
  160. package/runtime-plugin-support.js.map +10 -0
  161. package/runtime-plugin.d.ts +19 -0
  162. package/runtime-plugin.js +18 -0
  163. package/runtime-plugin.js.map +9 -0
  164. package/syntax-style.d.ts +54 -0
  165. package/testing/manual-clock.d.ts +17 -0
  166. package/testing/mock-keys.d.ts +81 -0
  167. package/testing/mock-mouse.d.ts +38 -0
  168. package/testing/mock-tree-sitter-client.d.ts +23 -0
  169. package/testing/spy.d.ts +7 -0
  170. package/testing/test-recorder.d.ts +61 -0
  171. package/testing/test-renderer.d.ts +23 -0
  172. package/testing.d.ts +6 -0
  173. package/testing.js +699 -0
  174. package/testing.js.map +15 -0
  175. package/text-buffer-view.d.ts +42 -0
  176. package/text-buffer.d.ts +67 -0
  177. package/types.d.ts +139 -0
  178. package/utils.d.ts +14 -0
  179. package/zig-structs.d.ts +155 -0
  180. package/zig.d.ts +353 -0
@@ -0,0 +1,888 @@
1
+ // @bun
2
+ var __require = import.meta.require;
3
+
4
+ // src/lib/tree-sitter/parser.worker.ts
5
+ import { mkdir as mkdir2 } from "fs/promises";
6
+ import * as path2 from "path";
7
+ import { fileURLToPath } from "url";
8
+ import { Language, Parser, Query } from "web-tree-sitter";
9
+ import { isMainThread } from "worker_threads";
10
+
11
+ // src/lib/bunfs.ts
12
+ import { basename, join } from "path";
13
+ function isBunfsPath(path) {
14
+ return path.includes("$bunfs") || /^B:[\\/]~BUN/i.test(path);
15
+ }
16
+ function getBunfsRootPath() {
17
+ return process.platform === "win32" ? "B:\\~BUN\\root" : "/$bunfs/root";
18
+ }
19
+ function normalizeBunfsPath(fileName) {
20
+ return join(getBunfsRootPath(), basename(fileName));
21
+ }
22
+
23
+ // src/lib/tree-sitter/download-utils.ts
24
+ import { mkdir, readFile, writeFile } from "fs/promises";
25
+ import * as path from "path";
26
+
27
+ class DownloadUtils {
28
+ static hashUrl(url) {
29
+ let hash = 0;
30
+ for (let i = 0;i < url.length; i++) {
31
+ const char = url.charCodeAt(i);
32
+ hash = (hash << 5) - hash + char;
33
+ hash = hash & hash;
34
+ }
35
+ return Math.abs(hash).toString(16);
36
+ }
37
+ static async downloadOrLoad(source, cacheDir, cacheSubdir, fileExtension, useHashForCache = true, filetype) {
38
+ const isUrl = source.startsWith("http://") || source.startsWith("https://");
39
+ if (isUrl) {
40
+ let cacheFileName;
41
+ if (useHashForCache) {
42
+ const hash = this.hashUrl(source);
43
+ cacheFileName = filetype ? `${filetype}-${hash}${fileExtension}` : `${hash}${fileExtension}`;
44
+ } else {
45
+ cacheFileName = path.basename(source);
46
+ }
47
+ const cacheFile = path.join(cacheDir, cacheSubdir, cacheFileName);
48
+ await mkdir(path.dirname(cacheFile), { recursive: true });
49
+ try {
50
+ const cachedContent = await readFile(cacheFile);
51
+ if (cachedContent.byteLength > 0) {
52
+ console.log(`Loaded from cache: ${cacheFile} (${source})`);
53
+ return { content: cachedContent, filePath: cacheFile };
54
+ }
55
+ } catch (error) {}
56
+ try {
57
+ console.log(`Downloading from URL: ${source}`);
58
+ const response = await fetch(source);
59
+ if (!response.ok) {
60
+ return { error: `Failed to fetch from ${source}: ${response.statusText}` };
61
+ }
62
+ const content = Buffer.from(await response.arrayBuffer());
63
+ try {
64
+ await writeFile(cacheFile, Buffer.from(content));
65
+ console.log(`Cached: ${source}`);
66
+ } catch (cacheError) {
67
+ console.warn(`Failed to cache: ${cacheError}`);
68
+ }
69
+ return { content, filePath: cacheFile };
70
+ } catch (error) {
71
+ return { error: `Error downloading from ${source}: ${error}` };
72
+ }
73
+ } else {
74
+ try {
75
+ console.log(`Loading from local path: ${source}`);
76
+ const content = await readFile(source);
77
+ return { content, filePath: source };
78
+ } catch (error) {
79
+ return { error: `Error loading from local path ${source}: ${error}` };
80
+ }
81
+ }
82
+ }
83
+ static async downloadToPath(source, targetPath) {
84
+ const isUrl = source.startsWith("http://") || source.startsWith("https://");
85
+ await mkdir(path.dirname(targetPath), { recursive: true });
86
+ if (isUrl) {
87
+ try {
88
+ console.log(`Downloading from URL: ${source}`);
89
+ const response = await fetch(source);
90
+ if (!response.ok) {
91
+ return { error: `Failed to fetch from ${source}: ${response.statusText}` };
92
+ }
93
+ const content = Buffer.from(await response.arrayBuffer());
94
+ await writeFile(targetPath, Buffer.from(content));
95
+ console.log(`Downloaded: ${source} -> ${targetPath}`);
96
+ return { content, filePath: targetPath };
97
+ } catch (error) {
98
+ return { error: `Error downloading from ${source}: ${error}` };
99
+ }
100
+ } else {
101
+ try {
102
+ console.log(`Copying from local path: ${source}`);
103
+ const content = await readFile(source);
104
+ await writeFile(targetPath, Buffer.from(content));
105
+ return { content, filePath: targetPath };
106
+ } catch (error) {
107
+ return { error: `Error copying from local path ${source}: ${error}` };
108
+ }
109
+ }
110
+ }
111
+ static async fetchHighlightQueries(sources, cacheDir, filetype) {
112
+ const queryPromises = sources.map((source) => this.fetchHighlightQuery(source, cacheDir, filetype));
113
+ const queryResults = await Promise.all(queryPromises);
114
+ const validQueries = queryResults.filter((query) => query.trim().length > 0);
115
+ return validQueries.join(`
116
+ `);
117
+ }
118
+ static async fetchHighlightQuery(source, cacheDir, filetype) {
119
+ const result = await this.downloadOrLoad(source, cacheDir, "queries", ".scm", true, filetype);
120
+ if (result.error) {
121
+ console.error(`Error fetching highlight query from ${source}:`, result.error);
122
+ return "";
123
+ }
124
+ if (result.content) {
125
+ return new TextDecoder().decode(result.content);
126
+ }
127
+ return "";
128
+ }
129
+ }
130
+
131
+ // src/lib/tree-sitter/parser.worker.ts
132
+ var self = globalThis;
133
+
134
+ class ParserWorker {
135
+ bufferParsers = new Map;
136
+ filetypeParserOptions = new Map;
137
+ filetypeAliases = new Map;
138
+ filetypeParsers = new Map;
139
+ filetypeParserPromises = new Map;
140
+ reusableParsers = new Map;
141
+ reusableParserPromises = new Map;
142
+ initializePromise;
143
+ performance;
144
+ dataPath;
145
+ tsDataPath;
146
+ initialized = false;
147
+ constructor() {
148
+ this.performance = {
149
+ averageParseTime: 0,
150
+ parseTimes: [],
151
+ averageQueryTime: 0,
152
+ queryTimes: []
153
+ };
154
+ }
155
+ async fetchQueries(sources, filetype) {
156
+ if (!this.tsDataPath) {
157
+ return "";
158
+ }
159
+ return DownloadUtils.fetchHighlightQueries(sources, this.tsDataPath, filetype);
160
+ }
161
+ async initialize({ dataPath }) {
162
+ if (this.initializePromise) {
163
+ return this.initializePromise;
164
+ }
165
+ this.initializePromise = (async () => {
166
+ this.dataPath = dataPath;
167
+ this.tsDataPath = path2.join(dataPath, "tree-sitter");
168
+ await mkdir2(path2.join(this.tsDataPath, "languages"), { recursive: true });
169
+ await mkdir2(path2.join(this.tsDataPath, "queries"), { recursive: true });
170
+ let treeWasm = fileURLToPath(new URL(import.meta.resolve("web-tree-sitter/tree-sitter.wasm")));
171
+ if (isBunfsPath(treeWasm)) {
172
+ treeWasm = normalizeBunfsPath(path2.parse(treeWasm).base);
173
+ }
174
+ await Parser.init({
175
+ locateFile() {
176
+ return treeWasm;
177
+ }
178
+ });
179
+ this.initialized = true;
180
+ })();
181
+ return this.initializePromise;
182
+ }
183
+ addFiletypeParser(filetypeParser) {
184
+ const previousAliases = this.filetypeParserOptions.get(filetypeParser.filetype)?.aliases ?? [];
185
+ for (const alias of previousAliases) {
186
+ if (this.filetypeAliases.get(alias) === filetypeParser.filetype) {
187
+ this.filetypeAliases.delete(alias);
188
+ }
189
+ }
190
+ const aliases = [...new Set((filetypeParser.aliases ?? []).filter((alias) => alias !== filetypeParser.filetype))];
191
+ this.filetypeAliases.delete(filetypeParser.filetype);
192
+ this.filetypeParserOptions.set(filetypeParser.filetype, {
193
+ ...filetypeParser,
194
+ aliases
195
+ });
196
+ for (const alias of aliases) {
197
+ this.filetypeAliases.set(alias, filetypeParser.filetype);
198
+ }
199
+ this.invalidateParserCaches(filetypeParser.filetype);
200
+ }
201
+ resolveCanonicalFiletype(filetype) {
202
+ if (this.filetypeParserOptions.has(filetype)) {
203
+ return filetype;
204
+ }
205
+ return this.filetypeAliases.get(filetype) ?? filetype;
206
+ }
207
+ invalidateParserCaches(filetype) {
208
+ this.filetypeParsers.delete(filetype);
209
+ this.filetypeParserPromises.delete(filetype);
210
+ const reusableParser = this.reusableParsers.get(filetype);
211
+ if (reusableParser) {
212
+ reusableParser.parser.delete();
213
+ this.reusableParsers.delete(filetype);
214
+ }
215
+ this.reusableParserPromises.delete(filetype);
216
+ }
217
+ async createQueries(filetypeParser, language) {
218
+ try {
219
+ const highlightQueryContent = await this.fetchQueries(filetypeParser.queries.highlights, filetypeParser.filetype);
220
+ if (!highlightQueryContent) {
221
+ console.error("Failed to fetch highlight queries for:", filetypeParser.filetype);
222
+ return;
223
+ }
224
+ const highlightsQuery = new Query(language, highlightQueryContent);
225
+ const result = {
226
+ highlights: highlightsQuery
227
+ };
228
+ if (filetypeParser.queries.injections && filetypeParser.queries.injections.length > 0) {
229
+ const injectionQueryContent = await this.fetchQueries(filetypeParser.queries.injections, filetypeParser.filetype);
230
+ if (injectionQueryContent) {
231
+ result.injections = new Query(language, injectionQueryContent);
232
+ }
233
+ }
234
+ return result;
235
+ } catch (error) {
236
+ console.error("Error creating queries for", filetypeParser.filetype, filetypeParser.queries);
237
+ console.error(error);
238
+ return;
239
+ }
240
+ }
241
+ async loadLanguage(languageSource) {
242
+ if (!this.initialized || !this.tsDataPath) {
243
+ return;
244
+ }
245
+ const result = await DownloadUtils.downloadOrLoad(languageSource, this.tsDataPath, "languages", ".wasm", false);
246
+ if (result.error) {
247
+ console.error(`Error loading language ${languageSource}:`, result.error);
248
+ return;
249
+ }
250
+ if (!result.filePath) {
251
+ return;
252
+ }
253
+ const normalizedPath = result.filePath.replaceAll("\\", "/");
254
+ try {
255
+ const language = await Language.load(normalizedPath);
256
+ return language;
257
+ } catch (error) {
258
+ console.error(`Error loading language from ${normalizedPath}:`, error);
259
+ return;
260
+ }
261
+ }
262
+ async resolveFiletypeParser(filetype) {
263
+ const canonicalFiletype = this.resolveCanonicalFiletype(filetype);
264
+ if (this.filetypeParsers.has(canonicalFiletype)) {
265
+ return this.filetypeParsers.get(canonicalFiletype);
266
+ }
267
+ if (this.filetypeParserPromises.has(canonicalFiletype)) {
268
+ return this.filetypeParserPromises.get(canonicalFiletype);
269
+ }
270
+ const loadingPromise = this.loadFiletypeParser(canonicalFiletype);
271
+ this.filetypeParserPromises.set(canonicalFiletype, loadingPromise);
272
+ try {
273
+ const result = await loadingPromise;
274
+ if (result) {
275
+ this.filetypeParsers.set(canonicalFiletype, result);
276
+ }
277
+ return result;
278
+ } finally {
279
+ this.filetypeParserPromises.delete(canonicalFiletype);
280
+ }
281
+ }
282
+ async loadFiletypeParser(filetype) {
283
+ const filetypeParserOptions = this.filetypeParserOptions.get(filetype);
284
+ if (!filetypeParserOptions) {
285
+ return;
286
+ }
287
+ const language = await this.loadLanguage(filetypeParserOptions.wasm);
288
+ if (!language) {
289
+ return;
290
+ }
291
+ const queries = await this.createQueries(filetypeParserOptions, language);
292
+ if (!queries) {
293
+ console.error("Failed to create queries for:", filetype);
294
+ return;
295
+ }
296
+ const filetypeParser = {
297
+ ...filetypeParserOptions,
298
+ queries,
299
+ language
300
+ };
301
+ return filetypeParser;
302
+ }
303
+ async preloadParser(filetype) {
304
+ return this.resolveFiletypeParser(filetype);
305
+ }
306
+ async getReusableParser(filetype) {
307
+ const canonicalFiletype = this.resolveCanonicalFiletype(filetype);
308
+ if (this.reusableParsers.has(canonicalFiletype)) {
309
+ return this.reusableParsers.get(canonicalFiletype);
310
+ }
311
+ if (this.reusableParserPromises.has(canonicalFiletype)) {
312
+ return this.reusableParserPromises.get(canonicalFiletype);
313
+ }
314
+ const creationPromise = this.createReusableParser(canonicalFiletype);
315
+ this.reusableParserPromises.set(canonicalFiletype, creationPromise);
316
+ try {
317
+ const result = await creationPromise;
318
+ if (result) {
319
+ this.reusableParsers.set(canonicalFiletype, result);
320
+ }
321
+ return result;
322
+ } finally {
323
+ this.reusableParserPromises.delete(canonicalFiletype);
324
+ }
325
+ }
326
+ async createReusableParser(filetype) {
327
+ const filetypeParser = await this.resolveFiletypeParser(filetype);
328
+ if (!filetypeParser) {
329
+ return;
330
+ }
331
+ const parser = new Parser;
332
+ parser.setLanguage(filetypeParser.language);
333
+ const reusableState = {
334
+ parser,
335
+ filetypeParser,
336
+ queries: filetypeParser.queries
337
+ };
338
+ return reusableState;
339
+ }
340
+ async handleInitializeParser(bufferId, version, content, filetype, messageId) {
341
+ const filetypeParser = await this.resolveFiletypeParser(filetype);
342
+ if (!filetypeParser) {
343
+ self.postMessage({
344
+ type: "PARSER_INIT_RESPONSE",
345
+ bufferId,
346
+ messageId,
347
+ hasParser: false,
348
+ warning: `No parser available for filetype ${filetype}`
349
+ });
350
+ return;
351
+ }
352
+ const parser = new Parser;
353
+ parser.setLanguage(filetypeParser.language);
354
+ const tree = parser.parse(content);
355
+ if (!tree) {
356
+ self.postMessage({
357
+ type: "PARSER_INIT_RESPONSE",
358
+ bufferId,
359
+ messageId,
360
+ hasParser: false,
361
+ error: "Failed to parse buffer"
362
+ });
363
+ return;
364
+ }
365
+ const parserState = {
366
+ parser,
367
+ tree,
368
+ queries: filetypeParser.queries,
369
+ filetype,
370
+ content,
371
+ injectionMapping: filetypeParser.injectionMapping
372
+ };
373
+ this.bufferParsers.set(bufferId, parserState);
374
+ self.postMessage({
375
+ type: "PARSER_INIT_RESPONSE",
376
+ bufferId,
377
+ messageId,
378
+ hasParser: true
379
+ });
380
+ const highlights = await this.initialQuery(parserState);
381
+ self.postMessage({
382
+ type: "HIGHLIGHT_RESPONSE",
383
+ bufferId,
384
+ version,
385
+ ...highlights
386
+ });
387
+ }
388
+ async initialQuery(parserState) {
389
+ const query = parserState.queries.highlights;
390
+ const matches = query.captures(parserState.tree.rootNode);
391
+ let injectionRanges = new Map;
392
+ if (parserState.queries.injections) {
393
+ const injectionResult = await this.processInjections(parserState);
394
+ matches.push(...injectionResult.captures);
395
+ injectionRanges = injectionResult.injectionRanges;
396
+ }
397
+ return this.getHighlights(parserState, matches, injectionRanges);
398
+ }
399
+ getNodeText(node, content) {
400
+ return content.substring(node.startIndex, node.endIndex);
401
+ }
402
+ async processInjections(parserState) {
403
+ const injectionMatches = [];
404
+ const injectionRanges = new Map;
405
+ if (!parserState.queries.injections) {
406
+ return { captures: injectionMatches, injectionRanges };
407
+ }
408
+ const content = parserState.content;
409
+ const injectionCaptures = parserState.queries.injections.captures(parserState.tree.rootNode);
410
+ const languageGroups = new Map;
411
+ const injectionMapping = parserState.injectionMapping;
412
+ for (const capture of injectionCaptures) {
413
+ const captureName = capture.name;
414
+ if (captureName === "injection.content" || captureName.includes("injection")) {
415
+ const nodeType = capture.node.type;
416
+ let targetLanguage;
417
+ if (injectionMapping?.nodeTypes && injectionMapping.nodeTypes[nodeType]) {
418
+ targetLanguage = injectionMapping.nodeTypes[nodeType];
419
+ } else if (nodeType === "code_fence_content") {
420
+ const parent = capture.node.parent;
421
+ if (parent) {
422
+ const infoString = parent.children.find((child) => child.type === "info_string");
423
+ if (infoString) {
424
+ const languageNode = infoString.children.find((child) => child.type === "language");
425
+ if (languageNode) {
426
+ const languageName = this.getNodeText(languageNode, content);
427
+ if (injectionMapping?.infoStringMap && injectionMapping.infoStringMap[languageName]) {
428
+ targetLanguage = injectionMapping.infoStringMap[languageName];
429
+ } else {
430
+ targetLanguage = languageName;
431
+ }
432
+ }
433
+ }
434
+ }
435
+ }
436
+ if (targetLanguage) {
437
+ if (!languageGroups.has(targetLanguage)) {
438
+ languageGroups.set(targetLanguage, []);
439
+ }
440
+ languageGroups.get(targetLanguage).push({ node: capture.node, name: capture.name });
441
+ }
442
+ }
443
+ }
444
+ for (const [language, captures] of languageGroups.entries()) {
445
+ const injectedParser = await this.getReusableParser(language);
446
+ if (!injectedParser) {
447
+ console.warn(`No parser found for injection language: ${language}`);
448
+ continue;
449
+ }
450
+ if (!injectionRanges.has(language)) {
451
+ injectionRanges.set(language, []);
452
+ }
453
+ const parser = injectedParser.parser;
454
+ for (const { node: injectionNode } of captures) {
455
+ try {
456
+ injectionRanges.get(language).push({
457
+ start: injectionNode.startIndex,
458
+ end: injectionNode.endIndex
459
+ });
460
+ const injectionContent = this.getNodeText(injectionNode, content);
461
+ const tree = parser.parse(injectionContent);
462
+ if (tree) {
463
+ const matches = injectedParser.queries.highlights.captures(tree.rootNode);
464
+ for (const match of matches) {
465
+ const offsetCapture = {
466
+ name: match.name,
467
+ patternIndex: match.patternIndex,
468
+ _injectedQuery: injectedParser.queries.highlights,
469
+ node: {
470
+ ...match.node,
471
+ startPosition: {
472
+ row: match.node.startPosition.row + injectionNode.startPosition.row,
473
+ column: match.node.startPosition.row === 0 ? match.node.startPosition.column + injectionNode.startPosition.column : match.node.startPosition.column
474
+ },
475
+ endPosition: {
476
+ row: match.node.endPosition.row + injectionNode.startPosition.row,
477
+ column: match.node.endPosition.row === 0 ? match.node.endPosition.column + injectionNode.startPosition.column : match.node.endPosition.column
478
+ },
479
+ startIndex: match.node.startIndex + injectionNode.startIndex,
480
+ endIndex: match.node.endIndex + injectionNode.startIndex
481
+ }
482
+ };
483
+ injectionMatches.push(offsetCapture);
484
+ }
485
+ tree.delete();
486
+ }
487
+ } catch (error) {
488
+ console.error(`Error processing injection for language ${language}:`, error);
489
+ }
490
+ }
491
+ }
492
+ return { captures: injectionMatches, injectionRanges };
493
+ }
494
+ editToRange(edit) {
495
+ return {
496
+ startPosition: {
497
+ column: edit.startPosition.column,
498
+ row: edit.startPosition.row
499
+ },
500
+ endPosition: {
501
+ column: edit.newEndPosition.column,
502
+ row: edit.newEndPosition.row
503
+ },
504
+ startIndex: edit.startIndex,
505
+ endIndex: edit.newEndIndex
506
+ };
507
+ }
508
+ async handleEdits(bufferId, content, edits) {
509
+ const parserState = this.bufferParsers.get(bufferId);
510
+ if (!parserState) {
511
+ return { warning: "No parser state found for buffer" };
512
+ }
513
+ parserState.content = content;
514
+ for (const edit of edits) {
515
+ parserState.tree.edit(edit);
516
+ }
517
+ const startParse = performance.now();
518
+ const newTree = parserState.parser.parse(content, parserState.tree);
519
+ const endParse = performance.now();
520
+ const parseTime = endParse - startParse;
521
+ this.performance.parseTimes.push(parseTime);
522
+ if (this.performance.parseTimes.length > 10) {
523
+ this.performance.parseTimes.shift();
524
+ }
525
+ this.performance.averageParseTime = this.performance.parseTimes.reduce((acc, time) => acc + time, 0) / this.performance.parseTimes.length;
526
+ if (!newTree) {
527
+ return { error: "Failed to parse buffer" };
528
+ }
529
+ const changedRanges = parserState.tree.getChangedRanges(newTree);
530
+ parserState.tree = newTree;
531
+ const startQuery = performance.now();
532
+ const matches = [];
533
+ if (changedRanges.length === 0) {
534
+ edits.forEach((edit) => {
535
+ const range = this.editToRange(edit);
536
+ changedRanges.push(range);
537
+ });
538
+ }
539
+ for (const range of changedRanges) {
540
+ let node = parserState.tree.rootNode.descendantForPosition(range.startPosition, range.endPosition);
541
+ if (!node) {
542
+ continue;
543
+ }
544
+ if (node.equals(parserState.tree.rootNode)) {
545
+ const rangeCaptures = parserState.queries.highlights.captures(node, {
546
+ startIndex: range.startIndex - 100,
547
+ endIndex: range.endIndex + 1000
548
+ });
549
+ matches.push(...rangeCaptures);
550
+ continue;
551
+ }
552
+ while (node && !this.nodeContainsRange(node, range)) {
553
+ node = node.parent;
554
+ }
555
+ if (!node) {
556
+ node = parserState.tree.rootNode;
557
+ }
558
+ const nodeCaptures = parserState.queries.highlights.captures(node);
559
+ matches.push(...nodeCaptures);
560
+ }
561
+ let injectionRanges = new Map;
562
+ if (parserState.queries.injections) {
563
+ const injectionResult = await this.processInjections(parserState);
564
+ matches.push(...injectionResult.captures);
565
+ injectionRanges = injectionResult.injectionRanges;
566
+ }
567
+ const endQuery = performance.now();
568
+ const queryTime = endQuery - startQuery;
569
+ this.performance.queryTimes.push(queryTime);
570
+ if (this.performance.queryTimes.length > 10) {
571
+ this.performance.queryTimes.shift();
572
+ }
573
+ this.performance.averageQueryTime = this.performance.queryTimes.reduce((acc, time) => acc + time, 0) / this.performance.queryTimes.length;
574
+ return this.getHighlights(parserState, matches, injectionRanges);
575
+ }
576
+ nodeContainsRange(node, range) {
577
+ return node.startPosition.row <= range.startPosition.row && node.endPosition.row >= range.endPosition.row && (node.startPosition.row < range.startPosition.row || node.startPosition.column <= range.startPosition.column) && (node.endPosition.row > range.endPosition.row || node.endPosition.column >= range.endPosition.column);
578
+ }
579
+ getHighlights(parserState, matches, injectionRanges) {
580
+ const lineHighlights = new Map;
581
+ const droppedHighlights = new Map;
582
+ for (const match of matches) {
583
+ const node = match.node;
584
+ const startLine = node.startPosition.row;
585
+ const endLine = node.endPosition.row;
586
+ const highlight = {
587
+ startCol: node.startPosition.column,
588
+ endCol: node.endPosition.column,
589
+ group: match.name
590
+ };
591
+ if (!lineHighlights.has(startLine)) {
592
+ lineHighlights.set(startLine, new Map);
593
+ droppedHighlights.set(startLine, new Map);
594
+ }
595
+ if (lineHighlights.get(startLine)?.has(node.id)) {
596
+ droppedHighlights.get(startLine)?.set(node.id, lineHighlights.get(startLine)?.get(node.id));
597
+ }
598
+ lineHighlights.get(startLine)?.set(node.id, highlight);
599
+ if (startLine !== endLine) {
600
+ for (let line = startLine + 1;line <= endLine; line++) {
601
+ if (!lineHighlights.has(line)) {
602
+ lineHighlights.set(line, new Map);
603
+ }
604
+ const hl = {
605
+ startCol: 0,
606
+ endCol: node.endPosition.column,
607
+ group: match.name
608
+ };
609
+ lineHighlights.get(line)?.set(node.id, hl);
610
+ }
611
+ }
612
+ }
613
+ return {
614
+ highlights: Array.from(lineHighlights.entries()).map(([line, lineHighlights2]) => ({
615
+ line,
616
+ highlights: Array.from(lineHighlights2.values()),
617
+ droppedHighlights: droppedHighlights.get(line) ? Array.from(droppedHighlights.get(line).values()) : []
618
+ }))
619
+ };
620
+ }
621
+ getSimpleHighlights(matches, injectionRanges) {
622
+ const highlights = [];
623
+ const flatInjectionRanges = [];
624
+ for (const [lang, ranges] of injectionRanges.entries()) {
625
+ for (const range of ranges) {
626
+ flatInjectionRanges.push({ ...range, lang });
627
+ }
628
+ }
629
+ for (const match of matches) {
630
+ const node = match.node;
631
+ let isInjection = false;
632
+ let injectionLang;
633
+ let containsInjection = false;
634
+ for (const injRange of flatInjectionRanges) {
635
+ if (node.startIndex >= injRange.start && node.endIndex <= injRange.end) {
636
+ isInjection = true;
637
+ injectionLang = injRange.lang;
638
+ break;
639
+ } else if (node.startIndex <= injRange.start && node.endIndex >= injRange.end) {
640
+ containsInjection = true;
641
+ break;
642
+ }
643
+ }
644
+ const matchQuery = match._injectedQuery;
645
+ const patternProperties = matchQuery?.setProperties?.[match.patternIndex];
646
+ const concealValue = patternProperties?.conceal ?? match.setProperties?.conceal;
647
+ const concealLines = patternProperties?.conceal_lines ?? match.setProperties?.conceal_lines;
648
+ const meta = {};
649
+ if (isInjection && injectionLang) {
650
+ meta.isInjection = true;
651
+ meta.injectionLang = injectionLang;
652
+ }
653
+ if (containsInjection) {
654
+ meta.containsInjection = true;
655
+ }
656
+ if (concealValue !== undefined) {
657
+ meta.conceal = concealValue;
658
+ }
659
+ if (concealLines !== undefined) {
660
+ meta.concealLines = concealLines;
661
+ }
662
+ if (Object.keys(meta).length > 0) {
663
+ highlights.push([node.startIndex, node.endIndex, match.name, meta]);
664
+ } else {
665
+ highlights.push([node.startIndex, node.endIndex, match.name]);
666
+ }
667
+ }
668
+ highlights.sort((a, b) => a[0] - b[0]);
669
+ return highlights;
670
+ }
671
+ async handleResetBuffer(bufferId, version, content) {
672
+ const parserState = this.bufferParsers.get(bufferId);
673
+ if (!parserState) {
674
+ return { warning: "No parser state found for buffer" };
675
+ }
676
+ parserState.content = content;
677
+ const newTree = parserState.parser.parse(content);
678
+ if (!newTree) {
679
+ return { error: "Failed to parse buffer during reset" };
680
+ }
681
+ parserState.tree = newTree;
682
+ const matches = parserState.queries.highlights.captures(parserState.tree.rootNode);
683
+ let injectionRanges = new Map;
684
+ if (parserState.queries.injections) {
685
+ const injectionResult = await this.processInjections(parserState);
686
+ matches.push(...injectionResult.captures);
687
+ injectionRanges = injectionResult.injectionRanges;
688
+ }
689
+ return this.getHighlights(parserState, matches, injectionRanges);
690
+ }
691
+ disposeBuffer(bufferId) {
692
+ const parserState = this.bufferParsers.get(bufferId);
693
+ if (!parserState) {
694
+ return;
695
+ }
696
+ parserState.tree.delete();
697
+ parserState.parser.delete();
698
+ this.bufferParsers.delete(bufferId);
699
+ }
700
+ async handleOneShotHighlight(content, filetype, messageId) {
701
+ const reusableState = await this.getReusableParser(filetype);
702
+ if (!reusableState) {
703
+ self.postMessage({
704
+ type: "ONESHOT_HIGHLIGHT_RESPONSE",
705
+ messageId,
706
+ hasParser: false,
707
+ warning: `No parser available for filetype ${filetype}`
708
+ });
709
+ return;
710
+ }
711
+ const parseContent = filetype === "markdown" && content.endsWith("```") ? content + `
712
+ ` : content;
713
+ const tree = reusableState.parser.parse(parseContent);
714
+ if (!tree) {
715
+ self.postMessage({
716
+ type: "ONESHOT_HIGHLIGHT_RESPONSE",
717
+ messageId,
718
+ hasParser: false,
719
+ error: "Failed to parse content"
720
+ });
721
+ return;
722
+ }
723
+ try {
724
+ const matches = reusableState.filetypeParser.queries.highlights.captures(tree.rootNode);
725
+ let injectionRanges = new Map;
726
+ if (reusableState.filetypeParser.queries.injections) {
727
+ const parserState = {
728
+ parser: reusableState.parser,
729
+ tree,
730
+ queries: reusableState.filetypeParser.queries,
731
+ filetype,
732
+ content,
733
+ injectionMapping: reusableState.filetypeParser.injectionMapping
734
+ };
735
+ const injectionResult = await this.processInjections(parserState);
736
+ matches.push(...injectionResult.captures);
737
+ injectionRanges = injectionResult.injectionRanges;
738
+ }
739
+ const highlights = this.getSimpleHighlights(matches, injectionRanges);
740
+ self.postMessage({
741
+ type: "ONESHOT_HIGHLIGHT_RESPONSE",
742
+ messageId,
743
+ hasParser: true,
744
+ highlights
745
+ });
746
+ } finally {
747
+ tree.delete();
748
+ }
749
+ }
750
+ async updateDataPath(dataPath) {
751
+ this.dataPath = dataPath;
752
+ this.tsDataPath = path2.join(dataPath, "tree-sitter");
753
+ try {
754
+ await mkdir2(path2.join(this.tsDataPath, "languages"), { recursive: true });
755
+ await mkdir2(path2.join(this.tsDataPath, "queries"), { recursive: true });
756
+ } catch (error) {
757
+ throw new Error(`Failed to update data path: ${error}`);
758
+ }
759
+ }
760
+ async clearCache() {
761
+ if (!this.dataPath || !this.tsDataPath) {
762
+ throw new Error("No data path configured");
763
+ }
764
+ const { rm } = await import("fs/promises");
765
+ try {
766
+ const treeSitterPath = path2.join(this.dataPath, "tree-sitter");
767
+ await rm(treeSitterPath, { recursive: true, force: true });
768
+ await mkdir2(path2.join(treeSitterPath, "languages"), { recursive: true });
769
+ await mkdir2(path2.join(treeSitterPath, "queries"), { recursive: true });
770
+ this.filetypeParsers.clear();
771
+ this.filetypeParserPromises.clear();
772
+ this.reusableParsers.clear();
773
+ this.reusableParserPromises.clear();
774
+ } catch (error) {
775
+ throw new Error(`Failed to clear cache: ${error}`);
776
+ }
777
+ }
778
+ }
779
+ if (!isMainThread) {
780
+ let logMessage = function(type, ...args) {
781
+ self.postMessage({
782
+ type: "WORKER_LOG",
783
+ logType: type,
784
+ data: args
785
+ });
786
+ };
787
+ const worker = new ParserWorker;
788
+ console.log = (...args) => logMessage("log", ...args);
789
+ console.error = (...args) => logMessage("error", ...args);
790
+ console.warn = (...args) => logMessage("warn", ...args);
791
+ self.onmessage = async (e) => {
792
+ const { type, bufferId, version, content, filetype, edits, filetypeParser, messageId, dataPath } = e.data;
793
+ try {
794
+ switch (type) {
795
+ case "INIT":
796
+ try {
797
+ await worker.initialize({ dataPath });
798
+ self.postMessage({ type: "INIT_RESPONSE" });
799
+ } catch (error) {
800
+ self.postMessage({
801
+ type: "INIT_RESPONSE",
802
+ error: error instanceof Error ? error.stack || error.message : String(error)
803
+ });
804
+ }
805
+ break;
806
+ case "ADD_FILETYPE_PARSER":
807
+ worker.addFiletypeParser(filetypeParser);
808
+ break;
809
+ case "PRELOAD_PARSER":
810
+ const maybeParser = await worker.preloadParser(filetype);
811
+ self.postMessage({ type: "PRELOAD_PARSER_RESPONSE", messageId, hasParser: !!maybeParser });
812
+ break;
813
+ case "INITIALIZE_PARSER":
814
+ await worker.handleInitializeParser(bufferId, version, content, filetype, messageId);
815
+ break;
816
+ case "HANDLE_EDITS":
817
+ const response = await worker.handleEdits(bufferId, content, edits);
818
+ if (response.highlights && response.highlights.length > 0) {
819
+ self.postMessage({ type: "HIGHLIGHT_RESPONSE", bufferId, version, ...response });
820
+ } else if (response.warning) {
821
+ self.postMessage({ type: "WARNING", bufferId, warning: response.warning });
822
+ } else if (response.error) {
823
+ self.postMessage({ type: "ERROR", bufferId, error: response.error });
824
+ }
825
+ break;
826
+ case "GET_PERFORMANCE":
827
+ self.postMessage({ type: "PERFORMANCE_RESPONSE", performance: worker.performance, messageId });
828
+ break;
829
+ case "RESET_BUFFER":
830
+ const resetResponse = await worker.handleResetBuffer(bufferId, version, content);
831
+ if (resetResponse.highlights && resetResponse.highlights.length > 0) {
832
+ self.postMessage({ type: "HIGHLIGHT_RESPONSE", bufferId, version, ...resetResponse });
833
+ } else if (resetResponse.warning) {
834
+ self.postMessage({ type: "WARNING", bufferId, warning: resetResponse.warning });
835
+ } else if (resetResponse.error) {
836
+ self.postMessage({ type: "ERROR", bufferId, error: resetResponse.error });
837
+ }
838
+ break;
839
+ case "DISPOSE_BUFFER":
840
+ worker.disposeBuffer(bufferId);
841
+ self.postMessage({ type: "BUFFER_DISPOSED", bufferId });
842
+ break;
843
+ case "ONESHOT_HIGHLIGHT":
844
+ await worker.handleOneShotHighlight(content, filetype, messageId);
845
+ break;
846
+ case "UPDATE_DATA_PATH":
847
+ try {
848
+ await worker.updateDataPath(dataPath);
849
+ self.postMessage({ type: "UPDATE_DATA_PATH_RESPONSE", messageId });
850
+ } catch (error) {
851
+ self.postMessage({
852
+ type: "UPDATE_DATA_PATH_RESPONSE",
853
+ messageId,
854
+ error: error instanceof Error ? error.message : String(error)
855
+ });
856
+ }
857
+ break;
858
+ case "CLEAR_CACHE":
859
+ try {
860
+ await worker.clearCache();
861
+ self.postMessage({ type: "CLEAR_CACHE_RESPONSE", messageId });
862
+ } catch (error) {
863
+ self.postMessage({
864
+ type: "CLEAR_CACHE_RESPONSE",
865
+ messageId,
866
+ error: error instanceof Error ? error.message : String(error)
867
+ });
868
+ }
869
+ break;
870
+ default:
871
+ self.postMessage({
872
+ type: "ERROR",
873
+ bufferId,
874
+ error: `Unknown message type: ${type}`
875
+ });
876
+ }
877
+ } catch (error) {
878
+ self.postMessage({
879
+ type: "ERROR",
880
+ bufferId,
881
+ error: error instanceof Error ? error.stack || error.message : String(error)
882
+ });
883
+ }
884
+ };
885
+ }
886
+
887
+ //# debugId=18F772B13516D5D764756E2164756E21
888
+ //# sourceMappingURL=parser.worker.js.map