|
| 1 | +import { join } from 'path'; |
| 2 | +import Parser from 'web-tree-sitter'; |
| 3 | +import { DocumentType } from '../document/Document'; |
| 4 | +import { readBufferIfExists } from '../utils/File'; |
| 5 | + |
| 6 | +export interface GrammarConfig { |
| 7 | + yamlGrammarPath?: string; |
| 8 | + jsonGrammarPath?: string; |
| 9 | + maxRetries?: number; |
| 10 | + retryDelay?: number; |
| 11 | + wasmBasePath?: string; |
| 12 | +} |
| 13 | + |
| 14 | +export class GrammarManager { |
| 15 | + private static instance: GrammarManager; |
| 16 | + private initialized = false; |
| 17 | + private readonly grammarCache = new Map<DocumentType, Parser.Language>(); |
| 18 | + private readonly loadingPromises = new Map<DocumentType, Promise<Parser.Language>>(); |
| 19 | + private readonly config: Required<GrammarConfig>; |
| 20 | + |
| 21 | + private constructor(config: GrammarConfig = {}) { |
| 22 | + const basePath = config.wasmBasePath ?? this.getDefaultWasmPath(); |
| 23 | + |
| 24 | + this.config = { |
| 25 | + yamlGrammarPath: config.yamlGrammarPath ?? join(basePath, 'tree-sitter-yaml.wasm'), |
| 26 | + jsonGrammarPath: config.jsonGrammarPath ?? join(basePath, 'tree-sitter-json.wasm'), |
| 27 | + maxRetries: config.maxRetries ?? 3, |
| 28 | + retryDelay: config.retryDelay ?? 100, |
| 29 | + wasmBasePath: basePath, |
| 30 | + }; |
| 31 | + } |
| 32 | + |
| 33 | + private getDefaultWasmPath(): string { |
| 34 | + // In bundled environment, WASM files are in the same directory as the bundle |
| 35 | + if (typeof __dirname !== 'undefined') { |
| 36 | + // __dirname points to the bundle directory, WASM files are in ./wasm/ |
| 37 | + return join(__dirname, 'wasm'); |
| 38 | + } |
| 39 | + // Fallback for different environments |
| 40 | + return './wasm'; |
| 41 | + } |
| 42 | + |
| 43 | + public static getInstance(config?: GrammarConfig): GrammarManager { |
| 44 | + if (!GrammarManager.instance) { |
| 45 | + GrammarManager.instance = new GrammarManager(config); |
| 46 | + } |
| 47 | + return GrammarManager.instance; |
| 48 | + } |
| 49 | + |
| 50 | + private async ensureInitialized(): Promise<void> { |
| 51 | + if (this.initialized) return; |
| 52 | + |
| 53 | + await Parser.init({ |
| 54 | + locateFile: (scriptName: string) => { |
| 55 | + if (scriptName === 'tree-sitter.wasm') { |
| 56 | + return join(this.config.wasmBasePath, '..', 'tree-sitter.wasm'); |
| 57 | + } |
| 58 | + return scriptName; |
| 59 | + }, |
| 60 | + }); |
| 61 | + |
| 62 | + this.initialized = true; |
| 63 | + } |
| 64 | + |
| 65 | + private async loadGrammarWithRetry(type: DocumentType): Promise<Parser.Language> { |
| 66 | + const grammarPath = type === DocumentType.YAML ? this.config.yamlGrammarPath : this.config.jsonGrammarPath; |
| 67 | + |
| 68 | + let lastError: Error | undefined; |
| 69 | + |
| 70 | + for (let attempt = 1; attempt <= this.config.maxRetries; attempt++) { |
| 71 | + try { |
| 72 | + const wasmBuffer = readBufferIfExists(grammarPath); |
| 73 | + return await Parser.Language.load(wasmBuffer); |
| 74 | + } catch (error) { |
| 75 | + lastError = error as Error; |
| 76 | + |
| 77 | + if (attempt < this.config.maxRetries) { |
| 78 | + await new Promise((resolve) => setTimeout(resolve, this.config.retryDelay * attempt)); |
| 79 | + } |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + throw new Error( |
| 84 | + `Failed to load ${type} grammar after ${this.config.maxRetries} attempts: ${lastError?.message}`, |
| 85 | + ); |
| 86 | + } |
| 87 | + |
| 88 | + public async loadGrammar(type: DocumentType): Promise<Parser.Language> { |
| 89 | + // Return cached grammar if available |
| 90 | + const cached = this.grammarCache.get(type); |
| 91 | + if (cached) { |
| 92 | + return cached; |
| 93 | + } |
| 94 | + |
| 95 | + // Return existing loading promise if in progress |
| 96 | + const existingPromise = this.loadingPromises.get(type); |
| 97 | + if (existingPromise) { |
| 98 | + return await existingPromise; |
| 99 | + } |
| 100 | + |
| 101 | + // Start new loading process |
| 102 | + const loadingPromise = this.loadGrammarInternal(type); |
| 103 | + this.loadingPromises.set(type, loadingPromise); |
| 104 | + |
| 105 | + try { |
| 106 | + const grammar = await loadingPromise; |
| 107 | + this.grammarCache.set(type, grammar); |
| 108 | + return grammar; |
| 109 | + } finally { |
| 110 | + this.loadingPromises.delete(type); |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + private async loadGrammarInternal(type: DocumentType): Promise<Parser.Language> { |
| 115 | + await this.ensureInitialized(); |
| 116 | + return await this.loadGrammarWithRetry(type); |
| 117 | + } |
| 118 | + |
| 119 | + public async preloadGrammars(types: DocumentType[] = [DocumentType.YAML, DocumentType.JSON]): Promise<void> { |
| 120 | + const promises = types.map((type) => this.loadGrammar(type)); |
| 121 | + await Promise.all(promises); |
| 122 | + } |
| 123 | + |
| 124 | + public isGrammarLoaded(type: DocumentType): boolean { |
| 125 | + return this.grammarCache.has(type); |
| 126 | + } |
| 127 | + |
| 128 | + public clearCache(): void { |
| 129 | + this.grammarCache.clear(); |
| 130 | + this.loadingPromises.clear(); |
| 131 | + } |
| 132 | + |
| 133 | + public getGrammarPath(type: DocumentType): string { |
| 134 | + return type === DocumentType.YAML ? this.config.yamlGrammarPath : this.config.jsonGrammarPath; |
| 135 | + } |
| 136 | +} |
0 commit comments