From 1416713cb3af8a952b1ae9952091706e2540341c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Wed, 16 Nov 2022 20:41:27 +0100 Subject: fix(npm): using types for packages with subpath (#16656) For CommonJS packages we were not trying different extensions for files specified as subpath of the package ([package_name]/[subpath]). This commit fixes that. --- ext/node/lib.rs | 1 + ext/node/resolution.rs | 39 ++++++++++++++++++++++++++++++++++++--- 2 files changed, 37 insertions(+), 3 deletions(-) (limited to 'ext') diff --git a/ext/node/lib.rs b/ext/node/lib.rs index b0d5485b4..d69d3b6fe 100644 --- a/ext/node/lib.rs +++ b/ext/node/lib.rs @@ -27,6 +27,7 @@ pub use resolution::legacy_main_resolve; pub use resolution::package_exports_resolve; pub use resolution::package_imports_resolve; pub use resolution::package_resolve; +pub use resolution::path_to_declaration_path; pub use resolution::NodeModuleKind; pub use resolution::DEFAULT_CONDITIONS; pub use resolution::TYPES_CONDITIONS; diff --git a/ext/node/resolution.rs b/ext/node/resolution.rs index de8f6e87b..9a6bc3aeb 100644 --- a/ext/node/resolution.rs +++ b/ext/node/resolution.rs @@ -27,6 +27,34 @@ pub enum NodeModuleKind { Cjs, } +/// Checks if the resolved file has a corresponding declaration file. +pub fn path_to_declaration_path( + path: PathBuf, + referrer_kind: NodeModuleKind, +) -> PathBuf { + let lowercase_path = path.to_string_lossy().to_lowercase(); + if lowercase_path.ends_with(".d.ts") + || lowercase_path.ends_with(".d.cts") + || lowercase_path.ends_with(".d.ts") + { + return path; + } + let specific_dts_path = match referrer_kind { + NodeModuleKind::Cjs => path.with_extension("d.cts"), + NodeModuleKind::Esm => path.with_extension("d.mts"), + }; + if specific_dts_path.exists() { + specific_dts_path + } else { + let dts_path = path.with_extension("d.ts"); + if dts_path.exists() { + dts_path + } else { + path + } + } +} + fn to_specifier_display_string(url: &ModuleSpecifier) -> String { if let Ok(path) = url.to_file_path() { path.display().to_string() @@ -659,9 +687,14 @@ pub fn package_resolve( return legacy_main_resolve(&package_json, referrer_kind, conditions); } - Ok(Some( - package_json.path.parent().unwrap().join(&package_subpath), - )) + let file_path = package_json.path.parent().unwrap().join(&package_subpath); + + if conditions == TYPES_CONDITIONS { + let declaration_path = path_to_declaration_path(file_path, referrer_kind); + Ok(Some(declaration_path)) + } else { + Ok(Some(file_path)) + } } pub fn get_package_scope_config( -- cgit v1.2.3