fix(napi/transform): display error with spanned messages

This commit is contained in:
Boshen 2024-07-05 23:41:39 +08:00
parent 74aae108da
commit 150f4d90fc
No known key found for this signature in database
GPG key ID: 67715A371E534061
4 changed files with 13 additions and 3 deletions

1
Cargo.lock generated
View file

@ -1783,6 +1783,7 @@ dependencies = [
"napi-derive",
"oxc_allocator",
"oxc_codegen",
"oxc_diagnostics",
"oxc_isolated_declarations",
"oxc_parser",
"oxc_span",

View file

@ -27,6 +27,7 @@ oxc_span = { workspace = true }
oxc_codegen = { workspace = true }
oxc_isolated_declarations = { workspace = true }
oxc_transformer = { workspace = true }
oxc_diagnostics = { workspace = true }
napi = { workspace = true }
napi-derive = { workspace = true }

View file

@ -1,9 +1,12 @@
pub mod transformer;
use std::sync::Arc;
use napi_derive::napi;
use oxc_allocator::Allocator;
use oxc_codegen::CodeGenerator;
use oxc_diagnostics::{Error, NamedSource};
use oxc_isolated_declarations::IsolatedDeclarations;
use oxc_parser::Parser;
use oxc_span::SourceType;
@ -18,7 +21,7 @@ pub struct IsolatedDeclarationsResult {
#[allow(clippy::needless_pass_by_value)]
#[napi]
pub fn isolated_declaration(filename: String, source_text: String) -> IsolatedDeclarationsResult {
let source_type = SourceType::from_path(filename).unwrap_or_default().with_typescript(true);
let source_type = SourceType::from_path(&filename).unwrap_or_default().with_typescript(true);
let allocator = Allocator::default();
let parser_ret = Parser::new(&allocator, &source_text, source_type).parse();
let transformed_ret = IsolatedDeclarations::new(&allocator).build(&parser_ret.program);
@ -26,12 +29,14 @@ pub fn isolated_declaration(filename: String, source_text: String) -> IsolatedDe
let mut errors = vec![];
if !parser_ret.errors.is_empty() || !transformed_ret.errors.is_empty() {
let source = Arc::new(NamedSource::new(filename, source_text.to_string()));
errors.extend(
parser_ret
.errors
.into_iter()
.chain(transformed_ret.errors)
.map(|error| error.message.to_string()),
.map(|diagnostic| Error::from(diagnostic).with_source_code(Arc::clone(&source)))
.map(|error| format!("{error:?}")),
);
}

View file

@ -6,7 +6,10 @@ console.log(`Testing on ${process.platform}-${process.arch}`)
test(oxc.isolatedDeclaration("test.ts", "class A {}"), "declare class A {}\n");
function test(ret, expected) {
console.log(ret);
console.log(ret.sourceText);
for (const error of ret.errors) {
console.log(error)
}
assert.equal(ret.sourceText, expected);
assert(ret.errors.length == 0);
}