feat: add typings for the node bindings

Fixes #3072
This commit is contained in:
Segev Finer 2024-02-28 21:41:14 +02:00 committed by Amaan Qureshi
parent b43e8ce902
commit 30bb44f48a
3 changed files with 40 additions and 1 deletions

View file

@ -35,6 +35,7 @@ const BUILD_RS_TEMPLATE: &str = include_str!("./templates/build.rs");
const CARGO_TOML_TEMPLATE: &str = include_str!("./templates/cargo.toml");
const INDEX_JS_TEMPLATE: &str = include_str!("./templates/index.js");
const INDEX_D_TS_TEMPLATE: &str = include_str!("./templates/index.d.ts");
const JS_BINDING_CC_TEMPLATE: &str = include_str!("./templates/js-binding.cc");
const BINDING_GYP_TEMPLATE: &str = include_str!("./templates/binding.gyp");
@ -97,16 +98,21 @@ pub fn generate_grammar_files(
let mut package_json = serde_json::from_str::<Map<String, Value>>(&package_json_str)
.with_context(|| "Failed to parse package.json")?;
let package_json_main = package_json.get("main");
let package_json_types = package_json.get("types");
let package_json_needs_update = package_json_main.map_or(true, |v| {
let main_string = v.as_str();
main_string == Some("index.js") || main_string == Some("./index.js")
});
}) || package_json_types.is_none();
if package_json_needs_update {
eprintln!("Updating package.json with new binding path");
package_json.insert(
"main".to_string(),
Value::String("bindings/node".to_string()),
);
package_json.insert(
"types".to_string(),
Value::String("bindings/node".to_string()),
);
let mut package_json_str = serde_json::to_string_pretty(&package_json)?;
package_json_str.push('\n');
write_file(path, package_json_str)?;
@ -193,6 +199,10 @@ pub fn generate_grammar_files(
generate_file(path, INDEX_JS_TEMPLATE, language_name)
})?;
missing_path(path.join("index.d.ts"), |path| {
generate_file(path, INDEX_D_TS_TEMPLATE, language_name)
})?;
missing_path_else(
path.join("binding.cc"),
|path| generate_file(path, JS_BINDING_CC_TEMPLATE, language_name),

28
cli/src/generate/templates/index.d.ts vendored Normal file
View file

@ -0,0 +1,28 @@
type BaseNode = {
type: string;
named: boolean;
};
type ChildNode = {
multiple: boolean;
required: boolean;
types: BaseNode[];
};
type NodeInfo =
| (BaseNode & {
subtypes: BaseNode[];
})
| (BaseNode & {
fields: { [name: string]: ChildNode };
children: ChildNode[];
});
type Language = {
name: string;
language: unknown;
nodeTypeInfo: NodeInfo[];
};
declare const language: Language;
export = language;

View file

@ -4,6 +4,7 @@
"description": "CAMEL_PARSER_NAME grammar for tree-sitter",
"repository": "github:tree-sitter/tree-sitter-PARSER_NAME",
"license": "MIT",
"types": "bindings/node",
"main": "bindings/node",
"files": [
"grammar.js",