Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add imports_fields option #138

Merged
merged 2 commits into from
Apr 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions napi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,10 @@ impl ResolverFactory {
.exports_fields
.map(|o| o.into_iter().map(|x| StrOrStrList(x).into()).collect::<Vec<_>>())
.unwrap_or(default.exports_fields),
imports_fields: op
.imports_fields
.map(|o| o.into_iter().map(|x| StrOrStrList(x).into()).collect::<Vec<_>>())
.unwrap_or(default.imports_fields),
extension_alias: op
.extension_alias
.map(|extension_alias| extension_alias.into_iter().collect::<Vec<_>>())
Expand Down
9 changes: 9 additions & 0 deletions napi/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,15 @@ pub struct NapiResolveOptions {
#[napi(ts_type = "(string | string[])[]")]
pub exports_fields: Option<Vec<StrOrStrListType>>,

/// Fields from `package.json` which are used to provide the internal requests of a package
/// (requests starting with # are considered internal).
///
/// Can be a path to a JSON object such as `["path", "to", "imports"]`.
///
/// Default `[["imports"]]`.
#[napi(ts_type = "(string | string[])[]")]
pub imports_fields: Option<Vec<StrOrStrListType>>,

/// An object which maps extension to extension aliases.
///
/// Default `{}`
Expand Down
49 changes: 29 additions & 20 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -474,15 +474,12 @@
return Ok(None);
};
// 3. If the SCOPE/package.json "imports" is null or undefined, return.
if package_json.imports.is_none()
|| package_json.imports.as_ref().is_some_and(|imports| imports.is_empty())
{
return Ok(None);
}
// 4. let MATCH = PACKAGE_IMPORTS_RESOLVE(X, pathToFileURL(SCOPE), ["node", "require"]) defined in the ESM resolver.
let path = self.package_imports_resolve(specifier, &package_json, ctx)?;
// 5. RESOLVE_ESM_MATCH(MATCH).
self.resolve_esm_match(specifier, &path, &package_json, ctx)
if let Some(path) = self.package_imports_resolve(specifier, &package_json, ctx)? {
// 5. RESOLVE_ESM_MATCH(MATCH).
return self.resolve_esm_match(specifier, &path, &package_json, ctx);
}
Ok(None)
}

fn load_as_file(&self, cached_path: &CachedPath, ctx: &mut Ctx) -> ResolveResult {
Expand Down Expand Up @@ -1286,25 +1283,30 @@
specifier: &str,
package_json: &PackageJson,
ctx: &mut Ctx,
) -> Result<CachedPath, ResolveError> {
) -> Result<Option<CachedPath>, ResolveError> {
// 1. Assert: specifier begins with "#".
debug_assert!(specifier.starts_with('#'), "{specifier}");
// 2. If specifier is exactly equal to "#" or starts with "#/", then
if specifier == "#" || specifier.starts_with("#/") {
// 1. Throw an Invalid Module Specifier error.
return Err(ResolveError::InvalidModuleSpecifier(
specifier.to_string(),
package_json.path.clone(),
));
}
// 2. If specifier is exactly equal to "#" or starts with "#/", then
// 1. Throw an Invalid Module Specifier error.
// 3. Let packageURL be the result of LOOKUP_PACKAGE_SCOPE(parentURL).
// 4. If packageURL is not null, then

// 1. Let pjson be the result of READ_PACKAGE_JSON(packageURL).
// 2. If pjson.imports is a non-null Object, then

// 1. Let resolved be the result of PACKAGE_IMPORTS_EXPORTS_RESOLVE( specifier, pjson.imports, packageURL, true, conditions).
if let Some(imports) = &package_json.imports {
let mut has_imports = false;
for imports in package_json.imports_fields(&self.options.imports_fields) {
if !has_imports {
has_imports = true;
// TODO: fill in test case for this case
if specifier == "#" || specifier.starts_with("#/") {
return Err(ResolveError::InvalidModuleSpecifier(
specifier.to_string(),
package_json.path.clone(),
));

Check warning on line 1307 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L1304-L1307

Added lines #L1304 - L1307 were not covered by tests
}
}

Check warning on line 1309 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L1309

Added line #L1309 was not covered by tests
if let Some(path) = self.package_imports_exports_resolve(
specifier,
imports,
Expand All @@ -1314,12 +1316,19 @@
ctx,
)? {
// 2. If resolved is not null or undefined, return resolved.
return Ok(path);
return Ok(Some(path));
}
}

// 5. Throw a Package Import Not Defined error.
Err(ResolveError::PackageImportNotDefined(specifier.to_string(), package_json.path.clone()))
if has_imports {
Err(ResolveError::PackageImportNotDefined(
specifier.to_string(),
package_json.path.clone(),
))
} else {
Ok(None)
}
}

/// PACKAGE_IMPORTS_EXPORTS_RESOLVE(matchKey, matchObj, packageURL, isImports, conditions)
Expand Down
15 changes: 14 additions & 1 deletion src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,14 @@
/// Default `[["exports"]]`.
pub exports_fields: Vec<Vec<String>>,

/// Fields from `package.json` which are used to provide the internal requests of a package
/// (requests starting with # are considered internal).
///
/// Can be a path to a JSON object such as `["path", "to", "imports"]`.
///
/// Default `[["imports"]]`.
pub imports_fields: Vec<Vec<String>>,

/// An object which maps extension to extension aliases.
///
/// Default `{}`
Expand Down Expand Up @@ -446,6 +454,7 @@
enforce_extension: EnforceExtension::Auto,
extension_alias: vec![],
exports_fields: vec![vec!["exports".into()]],
imports_fields: vec![vec!["imports".into()]],
extensions: vec![".js".into(), ".json".into(), ".node".into()],
fallback: vec![],
fully_specified: false,
Expand Down Expand Up @@ -484,6 +493,9 @@
if !self.exports_fields.is_empty() {
write!(f, "exports_fields:{:?},", self.exports_fields)?;
}
if !self.imports_fields.is_empty() {
write!(f, "imports_fields:{:?},", self.imports_fields)?;
}

Check warning on line 498 in src/options.rs

View check run for this annotation

Codecov / codecov/patch

src/options.rs#L498

Added line #L498 was not covered by tests
if !self.extension_alias.is_empty() {
write!(f, "extension_alias:{:?},", self.extension_alias)?;
}
Expand Down Expand Up @@ -566,6 +578,7 @@
enforce_extension: EnforceExtension::Enabled,
extension_alias: vec![(".js".into(), vec![".ts".into()])],
exports_fields: vec![vec!["exports".into()]],
imports_fields: vec![vec!["imports".into()]],
fallback: vec![("fallback".into(), vec![AliasValue::Ignore])],
fully_specified: true,
resolve_to_context: true,
Expand All @@ -577,7 +590,7 @@
..ResolveOptions::default()
};

let expected = r#"tsconfig:TsconfigOptions { config_file: "tsconfig.json", references: Auto },alias:[("a", [Ignore])],alias_fields:[["browser"]],condition_names:["require"],enforce_extension:Enabled,exports_fields:[["exports"]],extension_alias:[(".js", [".ts"])],extensions:[".js", ".json", ".node"],fallback:[("fallback", [Ignore])],fully_specified:true,main_fields:["main"],main_files:["index"],modules:["node_modules"],resolve_to_context:true,prefer_relative:true,prefer_absolute:true,restrictions:[Path("restrictions")],roots:["roots"],symlinks:true,builtin_modules:true,"#;
let expected = r#"tsconfig:TsconfigOptions { config_file: "tsconfig.json", references: Auto },alias:[("a", [Ignore])],alias_fields:[["browser"]],condition_names:["require"],enforce_extension:Enabled,exports_fields:[["exports"]],imports_fields:[["imports"]],extension_alias:[(".js", [".ts"])],extensions:[".js", ".json", ".node"],fallback:[("fallback", [Ignore])],fully_specified:true,main_fields:["main"],main_files:["index"],modules:["node_modules"],resolve_to_context:true,prefer_relative:true,prefer_absolute:true,restrictions:[Path("restrictions")],roots:["roots"],symlinks:true,builtin_modules:true,"#;
assert_eq!(format!("{options}"), expected);
}
}
24 changes: 15 additions & 9 deletions src/package_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,6 @@ pub struct PackageJson {
/// <https://nodejs.org/api/packages.html#name>
pub name: Option<String>,

/// In addition to the "exports" field, there is a package "imports" field to create private mappings that only apply to import specifiers from within the package itself.
///
/// <https://nodejs.org/api/packages.html#subpath-imports>
pub imports: Option<Box<ImportExportMap>>,

/// The "browser" field is provided by a module author as a hint to javascript bundlers or component tools when packaging modules for client side use.
/// Multiple values are configured by [ResolveOptions::alias_fields].
///
Expand Down Expand Up @@ -71,10 +66,6 @@ impl PackageJson {
package_json.name =
json_object.get("name").and_then(|field| field.as_str()).map(ToString::to_string);

// Add imports.
package_json.imports =
json_object.get("imports").and_then(|v| v.as_object()).cloned().map(Box::new);

// Dynamically create `browser_fields`.
let dir = path.parent().unwrap();
for object_path in &options.alias_fields {
Expand Down Expand Up @@ -183,6 +174,21 @@ impl PackageJson {
})
}

/// In addition to the "exports" field, there is a package "imports" field to create private mappings that only apply to import specifiers from within the package itself.
///
/// <https://nodejs.org/api/packages.html#subpath-imports>
pub(crate) fn imports_fields<'a>(
&'a self,
imports_fields: &'a [Vec<String>],
) -> impl Iterator<Item = &'a ImportExportMap> + '_ {
imports_fields.iter().filter_map(|object_path| {
self.raw_json
.as_object()
.and_then(|json_object| Self::get_value_by_path(json_object, object_path))
.and_then(|value| value.as_object())
})
}

/// Resolve the request string for this package.json by looking at the `browser` field.
///
/// # Errors
Expand Down
26 changes: 26 additions & 0 deletions src/tests/imports_field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,32 @@ fn test_simple() {
}
}

#[test]
fn shared_resolvers() {
let f = super::fixture().join("imports-field");

// field name #1
let resolver1 = Resolver::new(ResolveOptions {
extensions: vec![".js".into()],
main_files: vec!["index.js".into()],
imports_fields: vec![vec!["imports".into()]],
condition_names: vec!["webpack".into()],
..ResolveOptions::default()
});

let resolved_path = resolver1.resolve(&f, "#imports-field").map(|r| r.full_path());
assert_eq!(resolved_path, Ok(f.join("b.js")));

// field name #2
let resolver2 = resolver1.clone_with_options(ResolveOptions {
imports_fields: vec![vec!["other".into(), "imports".into()]],
..ResolveOptions::default()
});

let resolved_path = resolver2.resolve(&f, "#b").map(|r| r.full_path());
assert_eq!(resolved_path, Ok(f.join("a.js")));
}

// Small script for generating the test cases from enhanced_resolve
// for (c of testCases) {
// console.log("TestCase {")
Expand Down