fix(web): add early version check in Language.load()

Add ABI version compatibility check immediately after loading a WASM
language file in Language.load(). This provides:

1. Earlier failure detection - fails at load time instead of setLanguage()
2. More helpful error message - indicates WASM file may be built with
   incompatible tree-sitter-cli version
3. Better developer experience - clearer guidance on how to fix the issue

This helps users who use pre-built WASM files from third-party packages
(like tree-sitter-wasms) that may be built with older tree-sitter-cli
versions incompatible with newer web-tree-sitter releases.

Relates to #5171
This commit is contained in:
Kyuhwan Lee 2025-12-26 19:54:25 +09:00
parent ba7350c7ee
commit 709555a958

View file

@ -1,7 +1,7 @@
import { C, INTERNAL, Internal, assertInternal, SIZE_OF_INT, SIZE_OF_SHORT } from './constants';
import { LookaheadIterator } from './lookahead_iterator';
import { unmarshalLanguageMetadata } from './marshal';
import { TRANSFER_BUFFER } from './parser';
import { TRANSFER_BUFFER, LANGUAGE_VERSION, MIN_COMPATIBLE_VERSION } from './parser';
const LANGUAGE_FUNCTION_REGEX = /^tree_sitter_\w+$/;
@ -226,6 +226,8 @@ export class Language {
/**
* Load a language from a WebAssembly module.
* The module can be provided as a path to a file or as a buffer.
*
* @throws {Error} If the WASM file was built with an incompatible version of tree-sitter-cli.
*/
static async load(input: string | Uint8Array): Promise<Language> {
let binary: Uint8Array | WebAssembly.Module;
@ -263,6 +265,19 @@ export class Language {
throw new Error('Language.load failed: no language function found in Wasm file');
}
const languageAddress = mod[functionName]();
return new Language(INTERNAL, languageAddress);
const language = new Language(INTERNAL, languageAddress);
// Early version compatibility check
const version = language.abiVersion;
if (version < MIN_COMPATIBLE_VERSION || LANGUAGE_VERSION < version) {
throw new Error(
`Incompatible language version ${version}. ` +
`Compatibility range ${MIN_COMPATIBLE_VERSION} through ${LANGUAGE_VERSION}. ` +
`The WASM file may have been built with an incompatible version of tree-sitter-cli. ` +
`Please regenerate the WASM file using a compatible tree-sitter-cli version.`
);
}
return language;
}
}