fix(bindings): fix ESM errors in Node bindings

1. The module tries to call the native binary as a function.

Only `node-gyp-build` returns a function, so the call is moved there.

2. `node-types.json` is imported with outdated syntax.

Use import attributes which require Node 18.

3. The test does not properly catch import errors.

This is solved by moving the import inside the assertion.
This commit is contained in:
ObserverOfTime 2025-09-16 19:35:45 +03:00 committed by Amaan Qureshi
parent d29132512b
commit f222db57ce
3 changed files with 11 additions and 12 deletions

View file

@ -309,11 +309,10 @@ pub fn generate_grammar_files(
if !contents.contains("module") {
eprintln!("Updating package.json");
contents = contents.replace(
indoc! {r#"
"repository": {"#},
r#""repository":"#,
indoc! {r#"
"type": "module",
"repository": {"#},
"repository":"#},
);
}
write_file(path, contents)?;

View file

@ -1,9 +1,11 @@
import assert from "node:assert";
import { test } from "node:test";
import Parser from "tree-sitter";
import language from "./index.js";
test("can load grammar", () => {
const parser = new Parser();
assert.doesNotThrow(() => parser.setLanguage(language));
assert.doesNotReject(async () => {
const { default: language } = await import("./index.js");
parser.setLanguage(language);
});
});

View file

@ -2,14 +2,12 @@ const root = new URL("../..", import.meta.url).pathname;
const binding = typeof process.versions.bun === "string"
// Support `bun build --compile` by being statically analyzable enough to find the .node file at build-time
? await import(`../../prebuilds/${process.platform}-${process.arch}/tree-sitter-KEBAB_PARSER_NAME.node`)
: await import("node-gyp-build");
const result = binding.default ? binding.default(root) : binding(root);
? await import(`${root}/prebuilds/${process.platform}-${process.arch}/tree-sitter-KEBAB_PARSER_NAME.node`)
: (await import("node-gyp-build")).default(root);
try {
const nodeTypeInfo = await import("../../src/node-types.json", {assert: {type: "json"}});
result.nodeTypeInfo = nodeTypeInfo.default;
const nodeTypes = await import(`${root}/src/node-types.json`, {with: {type: "json"}});
binding.nodeTypeInfo = nodeTypes.default;
} catch (_) {}
export default result;
export default binding;