Skip to content

Commit

Permalink
fix(core): resolve .cjs/.cts file in esm pacakge (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
Brooooooklyn authored Jul 13, 2024
1 parent 48ac182 commit 9616417
Show file tree
Hide file tree
Showing 8 changed files with 70 additions and 21 deletions.
2 changes: 1 addition & 1 deletion packages/core/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,5 @@ export interface ResolveFnOutput {
importAttributes?: Record<string, string> | null
}

export declare function transform(path: string, code: string): Output
export declare function transform(path: string, code: string | Uint8Array): Output

3 changes: 3 additions & 0 deletions packages/integrate-ava/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
"nodeArguments": [
"--import",
"@oxc-node/core/register"
],
"files": [
"__tests__/**/*.spec.ts"
]
}
}
2 changes: 2 additions & 0 deletions packages/integrate-ava/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,7 @@
"module": "ESNext",
"moduleResolution": "Bundler"
},
"include": ["__tests__/**/*.ts"],
"exclude": ["__tests__/fixtures/**/*"],
"references": [{ "path": "../core" }]
}
1 change: 1 addition & 0 deletions packages/integrate-module-bundler/src/common.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports.common = 'common'
1 change: 1 addition & 0 deletions packages/integrate-module-bundler/src/common.d.cts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const common: string
5 changes: 5 additions & 0 deletions packages/integrate-module-bundler/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { renderToString } from 'react-dom/server'
import { simpleGit } from 'simple-git'

import { CompiledClass } from './compiled'
import { common } from './common.cjs'
import { foo } from './foo'
import { bar } from './subdirectory/bar'
import { baz } from './subdirectory/index'
Expand Down Expand Up @@ -61,3 +62,7 @@ await test('resolve simple-git', () => {
await test('import default from babel-generated cjs file', () => {
assert.equal(babelGeneratedDoubleDefault.default(), 'default.default')
})

await test('resolve cjs in type module package', () => {
assert.equal(common, 'common')
})
1 change: 1 addition & 0 deletions packages/integrate-module-bundler/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "Bundler",
"allowJs": true,
"composite": true,
"jsx": "react-jsx",
"outDir": "dist",
Expand Down
76 changes: 56 additions & 20 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,16 +160,17 @@ impl Output {
}

#[napi]
pub fn transform(path: String, code: String) -> Result<Output> {
pub fn transform(path: String, code: Either<String, &[u8]>) -> Result<Output> {
let allocator = Allocator::default();
let src_path = Path::new(&path);
let source_type = SourceType::from_path(src_path).unwrap_or_default();
let source_str = code.try_as_str()?;
let ParserReturn {
trivias,
mut program,
errors,
..
} = Parser::new(&allocator, &code, source_type).parse();
} = Parser::new(&allocator, source_str, source_type).parse();
if !errors.is_empty() {
for error in &errors {
eprintln!("{}", error);
Expand All @@ -183,7 +184,7 @@ pub fn transform(path: String, code: String) -> Result<Output> {
&allocator,
src_path,
source_type,
&code,
source_str,
trivias,
Default::default(),
)
Expand Down Expand Up @@ -352,16 +353,27 @@ pub fn resolve(
return Ok(Either::A(ResolveFnOutput {
short_circuit: Some(true),
format: {
let format = if resolution
.package_json()
.and_then(|p| p.r#type.as_ref())
.and_then(|t| t.as_str())
.is_some_and(|t| t == "module")
{
"module".to_owned()
} else {
"commonjs".to_owned()
};
let format = p
.extension()
.and_then(|ext| ext.to_str())
.and_then(|ext| {
if ext == "cjs" || ext == "cts" {
None
} else {
resolution
.package_json()
.and_then(|p| p.r#type.as_ref())
.and_then(|t| t.as_str())
.and_then(|format| {
if format == "module" {
Some("module".to_owned())
} else {
None
}
})
}
})
.unwrap_or_else(|| "commonjs".to_owned());
tracing::debug!(path = ?p, format = ?format);
Either3::A(format)
},
Expand Down Expand Up @@ -437,22 +449,28 @@ fn oxc_transform(url: String, output: LoadFnOutput) -> Result<LoadFnOutput> {
let source = output.source.as_ref().unwrap().try_as_str()?;
let allocator = Allocator::default();
let src_path = Path::new(&url);
let jsx = src_path
.extension()
.and_then(|ext| ext.to_str())
let ext = src_path.extension().and_then(|ext| ext.to_str());
let jsx = ext
.map(|ext| ext == "tsx" || ext == "jsx")
.unwrap_or_default();
tracing::debug!(url = ?url, jsx = ?jsx, src_path = ?src_path, "running oxc transform");
let ts = ext.map(|ext| ext.contains("ts")).unwrap_or_default();
let source_type = match output.format.as_str() {
"commonjs" => SourceType::default().with_script(true).with_jsx(jsx),
"module" => SourceType::default().with_module(true).with_jsx(jsx),
"commonjs" => SourceType::default()
.with_script(true)
.with_typescript(ts)
.with_jsx(jsx),
"module" => SourceType::default()
.with_module(true)
.with_typescript(ts)
.with_jsx(jsx),
_ => {
return Err(Error::new(
Status::InvalidArg,
format!("Unknown module format {}", output.format),
))
}
};
tracing::debug!(url = ?url, jsx = ?jsx, src_path = ?src_path, source_type = ?source_type, "running oxc transform");
let ParserReturn {
trivias,
mut program,
Expand Down Expand Up @@ -504,6 +522,20 @@ trait TryAsStr {
fn try_as_str(&self) -> Result<&str>;
}

impl TryAsStr for Either<String, &[u8]> {
fn try_as_str(&self) -> Result<&str> {
match self {
Either::A(s) => Ok(s),
Either::B(b) => std::str::from_utf8(b).map_err(|err| {
Error::new(
Status::GenericFailure,
format!("Failed to convert &[u8] to &str: {}", err),
)
}),
}
}
}

impl TryAsStr for Either4<String, Uint8Array, Buffer, Null> {
fn try_as_str(&self) -> Result<&str> {
match self {
Expand Down Expand Up @@ -546,7 +578,11 @@ fn init_resolver() -> Resolver {
config_file: tsconfig_full_path,
references: TsconfigReferences::Auto,
}),
condition_names: vec!["node".to_owned(), "import".to_owned()],
condition_names: vec![
"node".to_owned(),
"import".to_owned(),
"node-addons".to_owned(),
],
extension_alias: vec![
(
".js".to_owned(),
Expand Down

0 comments on commit 9616417

Please sign in to comment.