loader: implement package maps

Signed-off-by: Mael Nison <nison.mael@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/62239
Reviewed-By: Aviv Keller <me@aviv.sh>
Reviewed-By: Marco Ippolito <marcoippolito54@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
This commit is contained in:
Maël Nison authored and Antoine du Hamel committed 2026-08-06 15:34:58 +02:00
1 parent 1bde0ef053
commit b3cfb55267
66 files changed
+1811 -34

No files matched your search

+23
View File
@@ -1148,6 +1148,27 @@ added:
Enable experimental support for the network inspection with Chrome DevTools.
### `--experimental-package-map=<path>`
<!-- YAML
added: REPLACEME
-->
> Stability: 1 - Experimental
Enable experimental package map resolution. The `path` argument specifies the
location of a JSON configuration file that defines package resolution mappings.
```bash
node --experimental-package-map=./package-map.json app.js
```
When enabled, bare specifier resolution consults the package map for resolution.
This allows explicit control over which packages can import which dependencies.
See [Package maps][] for details on the configuration file format and
resolution algorithm.
### `--experimental-print-required-tla`
<!-- YAML
@@ -3579,6 +3600,7 @@ one is included in the list below.
* `--experimental-json-modules`
* `--experimental-loader`
* `--experimental-modules`
* `--experimental-package-map`
* `--experimental-print-required-tla`
* `--experimental-quic`
* `--experimental-require-module`
@@ -4170,6 +4192,7 @@ node --stack-trace-limit=12 -p -e "Error.stackTraceLimit" # prints 12
[Navigator API]: globals.md#navigator
[Node.js issue tracker]: https://github.com/nodejs/node/issues
[OSSL_PROVIDER-legacy]: https://www.openssl.org/docs/man3.0/man7/OSSL_PROVIDER-legacy.html
[Package maps]: packages.md#package-maps
[Permission Model]: permissions.md#permission-model
[REPL]: repl.md
[ScriptCoverage]: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#type-ScriptCoverage
+72
View File
@@ -2499,6 +2499,77 @@ A given value is out of the accepted range.
The `package.json` [`"imports"`][] field does not define the given internal
package specifier mapping.
<a id="ERR_PACKAGE_MAP_EXTERNAL_FILE"></a>
### `ERR_PACKAGE_MAP_EXTERNAL_FILE`
<!-- YAML
added: REPLACEME
-->
A module attempted to resolve a bare specifier using the [package map][], but
the importing file is not located within any package defined in the map.
```console
$ node --experimental-package-map=./package-map.json /tmp/script.js
Error [ERR_PACKAGE_MAP_EXTERNAL_FILE]: Cannot resolve "dep-a" from "/tmp/script.js": file is not within any package defined in /path/to/package-map.json
```
To fix this error, ensure the importing file is inside one of the package
directories listed in the package map, or add a new package entry whose `url`
covers the importing file.
<a id="ERR_PACKAGE_MAP_INVALID"></a>
### `ERR_PACKAGE_MAP_INVALID`
<!-- YAML
added: REPLACEME
-->
The [package map][] configuration file is invalid. This can occur when:
* The file does not exist at the specified path.
* The file contains invalid JSON.
* The file is missing the required `packages` object.
* A package entry is missing the required `url` field.
* Two package entries have the same `url` value.
```console
$ node --experimental-package-map=./missing.json app.js
Error [ERR_PACKAGE_MAP_INVALID]: Invalid package map at "./missing.json": file not found
```
<a id="ERR_PACKAGE_MAP_KEY_NOT_FOUND"></a>
### `ERR_PACKAGE_MAP_KEY_NOT_FOUND`
<!-- YAML
added: REPLACEME
-->
A package's `dependencies` object in the [package map][] references a package
key that is not defined in the `packages` object.
```json
{
"packages": {
"app": {
"url": "./app",
"dependencies": {
"foo": "nonexistent"
}
}
}
}
```
In this example, `"nonexistent"` is referenced as a dependency target but not
defined in `packages`, which will throw this error.
To fix this error, ensure all package keys referenced in `dependencies` values
are defined in the `packages` object.
<a id="ERR_PACKAGE_PATH_NOT_EXPORTED"></a>
### `ERR_PACKAGE_PATH_NOT_EXPORTED`
@@ -4531,6 +4602,7 @@ An error occurred trying to allocate memory. This should never happen.
[domains]: domain.md
[event emitter-based]: events.md#class-eventemitter
[file descriptors]: https://en.wikipedia.org/wiki/File_descriptor
[package map]: packages.md#package-maps
[relative URL]: https://url.spec.whatwg.org/#relative-url-string
[self-reference a package using its name]: packages.md#self-referencing-a-package-using-its-name
[special scheme]: https://url.spec.whatwg.org/#special-scheme
+8
View File
@@ -949,6 +949,12 @@ The default loader has the following properties
* Fails on unknown extensions for `file:` loading
(supports only `.cjs`, `.js`, and `.mjs`)
When the [`--experimental-package-map`][] flag is enabled, bare specifier
resolution first consults the package map configuration. If the importing
module is within a mapped package and the specifier matches a declared
dependency, the package map resolution takes precedence. See [Package maps][]
for details.
### Resolution algorithm
The algorithm to load an ES module specifier is given through the
@@ -1312,6 +1318,7 @@ resolution for ESM specifiers is [commonjs-extension-resolution-loader][].
[Loading ECMAScript modules using `require()`]: modules.md#loading-ecmascript-modules-using-require
[Module customization hooks]: module.md#customization-hooks
[Node.js Module Resolution And Loading Algorithm]: #resolution-algorithm-specification
[Package maps]: packages.md#package-maps
[Source Phase Imports]: https://github.com/tc39/proposal-source-phase-imports
[Terminology]: #terminology
[Text modules]: #text-modules
@@ -1319,6 +1326,7 @@ resolution for ESM specifiers is [commonjs-extension-resolution-loader][].
[WebAssembly JS String Builtins Proposal]: https://github.com/WebAssembly/js-string-builtins
[`"exports"`]: packages.md#exports
[`"type"`]: packages.md#type
[`--experimental-package-map`]: cli.md#--experimental-package-mappath
[`--input-type`]: cli.md#--input-typetype
[`data:` URLs]: https://developer.mozilla.org/en-US/docs/Web/URI/Reference/Schemes/data
[`export`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export
+36 -15
View File
@@ -353,8 +353,12 @@ require(X) from module at path Y
4. If X begins with '#'
a. LOAD_PACKAGE_IMPORTS(X, dirname(Y))
5. LOAD_PACKAGE_SELF(X, dirname(Y))
6. LOAD_NODE_MODULES(X, dirname(Y))
7. THROW "not found"
6. If a package map PACKAGE_MAP exists,
a. Find the package ID for the package owning Y
1. Let PARENT_PACKAGE_ID be FIND_PACKAGE_ID(dirname(Y), PACKAGE_MAP)
b. LOAD_PACKAGE_MAP(X, PARENT_PACKAGE_ID, PACKAGE_MAP)
7. LOAD_NODE_MODULES(X, dirname(Y))
8. THROW "not found"
MAYBE_DETECT_AND_LOAD(X)
1. If X parses as a CommonJS module, load X as a CommonJS module. STOP.
@@ -398,9 +402,11 @@ LOAD_AS_DIRECTORY(X)
2. LOAD_INDEX(X)
LOAD_NODE_MODULES(X, START)
1. let DIRS = NODE_MODULES_PATHS(START)
2. for each DIR in DIRS:
a. LOAD_PACKAGE_EXPORTS(X, DIR)
1. Try to interpret X as a combination of NAME and SUBPATH where the name
may have a @scope/ prefix and the subpath begins with a slash (`/`).
2. let DIRS = NODE_MODULES_PATHS(START)
3. for each DIR in DIRS:
a. LOAD_PACKAGE_EXPORTS(SUBPATH, DIR/NAME)
b. LOAD_AS_FILE(DIR/X)
c. LOAD_AS_DIRECTORY(DIR/X)
@@ -415,6 +421,25 @@ NODE_MODULES_PATHS(START)
d. let I = I - 1
5. return DIRS + GLOBAL_FOLDERS
FIND_PACKAGE_ID(PATH, PACKAGE_MAP)
1. Find the PACKAGE_ID for the entry whose "path" is a parent directory of PATH
2. If multiple entries are found, THROW "ambiguous resolution"
3. If no entry was found, THROW "external file".
4. return PACKAGE_ID
LOAD_PACKAGE_MAP(X, PARENT_PACKAGE_ID, PACKAGE_MAP)
1. Try to interpret X as a combination of NAME and SUBPATH where the name
may have a @scope/ prefix and the subpath begins with a slash (`/`).
2. Find the package map entry for key PARENT_PACKAGE_ID
3. Look up NAME in the entry's "dependencies" map.
4. If NAME is not found, THROW "not found".
5. Let TARGET be PACKAGE_MAP.packages[dependencies[name]]
6. Let PACKAGE_PATH be the resolved path of TARGET.
7. LOAD_PACKAGE_EXPORTS(SUBPATH, PACKAGE_PATH)
8. LOAD_AS_FILE(PACKAGE_PATH/SUBPATH)
9. LOAD_AS_DIRECTORY(PACKAGE_PATH/SUBPATH)
10. THROW "not found"
LOAD_PACKAGE_IMPORTS(X, DIR)
1. Find the closest package scope SCOPE to DIR.
2. If no scope was found, return.
@@ -426,19 +451,15 @@ LOAD_PACKAGE_IMPORTS(X, DIR)
CONDITIONS) defined in the ESM resolver.
6. RESOLVE_ESM_MATCH(MATCH).
LOAD_PACKAGE_EXPORTS(X, DIR)
1. Try to interpret X as a combination of NAME and SUBPATH where the name
may have a @scope/ prefix and the subpath begins with a slash (`/`).
2. If X does not match this pattern or DIR/NAME/package.json is not a file,
return.
3. Parse DIR/NAME/package.json, and look for "exports" field.
4. If "exports" is null or undefined, return.
5. If `--no-require-module` is not enabled
LOAD_PACKAGE_EXPORTS(SUBPATH, PACKAGE_DIR)
1. Parse PACKAGE_DIR/package.json, and look for "exports" field.
2. If "exports" is null or undefined, return.
3. If `--no-require-module` is not enabled
a. let CONDITIONS = ["node", "require", "module-sync"]
b. Else, let CONDITIONS = ["node", "require"]
6. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(DIR/NAME), "." + SUBPATH,
4. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(PACKAGE_DIR), "." + SUBPATH,
`package.json` "exports", CONDITIONS) defined in the ESM resolver.
7. RESOLVE_ESM_MATCH(MATCH)
5. RESOLVE_ESM_MATCH(MATCH)
LOAD_PACKAGE_SELF(X, DIR)
1. Find the closest package scope SCOPE to DIR.
+190
View File
@@ -945,6 +945,192 @@ $ node other.js
See [the package examples repository][] for details.
## Package maps
<!-- YAML
added: REPLACEME
-->
> Stability: 1 - Experimental. Enable this API with [`--experimental-package-map`][].
Package maps provide a mechanism to control package resolution without relying
on the `node_modules` folder structure. When enabled via the
[`--experimental-package-map`][] flag, Node.js uses a JSON configuration file
to determine how bare specifiers are resolved.
This feature is useful for:
* **Monorepos**: Define explicit dependency relationships between workspace
packages without symlinks or hoisting complexities.
* **Dependency isolation**: Prevent packages from accessing undeclared
dependencies (phantom dependencies).
* **Low file system coupling**: The package resolution algorithm runs without
inspecting the file system, relying instead on static data tables.
### Configuration file format
The package map configuration file is a JSON file with a `packages` object.
Each key in `packages` is called a package ID and is a unique identifier for a package entry:
```json
{
"packages": {
"app": {
"url": "./packages/app",
"dependencies": {
"@myorg/utils": "utils",
"@myorg/ui-lib": "ui-lib"
}
},
"utils": {
"url": "./packages/utils"
},
"ui-lib": {
"url": "./packages/ui-lib",
"dependencies": {
"@myorg/utils": "utils"
}
}
}
}
```
Each package entry has the following fields:
* `url` {string} **Required.** An absolute or relative URL. This is parsed using
the WHATWG [`URL`][] API, using the configuration file URL as base. Only
`file:` protocol is supported. Multiple packages are allowed to share the
same URL; consumers must key module instances by both module url **and package IDs**
to differentiate them.
* `dependencies` {Object} An object mapping bare specifiers to package keys.
Each key is the import name used in source code, and each value is the
corresponding package key in the `packages` object. Defaults to an empty
object.
### Resolution algorithm
When a bare specifier is encountered:
1. Node.js determines which package performs the resolution request.
* If possible the package ID for the importer file should be provided to the resolution algorithm.
* Failing that, the resolution will check if the file path is within any
package location decoded from its `url`.
2. If no package ID is provided and the importing file is not within any mapped package, an
[`ERR_PACKAGE_MAP_EXTERNAL_FILE`][] error is thrown.
3. Node.js looks up the specifier's package name in the importing package's
`dependencies` object to find the corresponding package key.
4. If found, the resolution algorithm locates the target package location from the
package's `url` field in the package map.
5. If the specifier is not in `dependencies`, a
`MODULE_NOT_FOUND` error is thrown.
6. The package location is forwarded to the regular Node.js resolution algorithm to
finish the resolution (`index.js`, exports field, etc).
More details can be found in the [resolution algorithm pseudo-code][].
### Multiple package versions
Different packages can depend on different versions of the same package.
Because `dependencies` maps bare specifiers to package keys, two packages
can map the same specifier to different targets:
```json
{
"packages": {
"app": {
"url": "./app",
"dependencies": {
"component": "component-v2"
}
},
"legacy": {
"url": "./legacy",
"dependencies": {
"component": "component-v1"
}
},
"component-v1": {
"url": "./vendor/component-1.0.0"
},
"component-v2": {
"url": "./vendor/component-2.0.0"
}
}
}
```
Both `app` and `legacy` can `import 'component'`, but they resolve to
different paths based on their declared dependencies.
### Multiple packages for the same URL
To address complex hoisting situations, multiple packages may share the same
URL, which introduces ambiguity when determining which package an import
originates from:
```json
{
"packages": {
"app-old": {
"url": "./app-old",
"dependencies": {
"lib": "lib-old"
}
},
"app-new": {
"url": "./app-new",
"dependencies": {
"lib": "lib-new"
}
},
"lib-old": {
"url": "./lib",
"dependencies": {
"react": "react-15"
}
},
"lib-new": {
"url": "./lib",
"dependencies": {
"react": "react-18"
}
}
}
}
```
In the example above both `lib-old` and `lib-new` use the same `./lib` folder to
store their sources, the only difference being in which version of `react` they'll
access when performing `require` calls or using `import`.
Because multiple package entries share the same URL, resolving a bare specifier
from a file within that URL is ambiguous unless the originating package ID is
known. If the package ID cannot be determined (for example, because the caller
did not propagate it from a previous resolution), Node.js will throw an error
rather than guess.
To support this pattern, implementers must key module instances by package ID
and propagate it from each resolution result to subsequent resolution requests.
This ensures that when `lib` requires `react`, the runtime knows whether the
request comes from `lib-old` or `lib-new` and can select the correct dependency.
### Interaction with other resolution
Package maps only apply to bare specifiers that are not Node.js builtin
modules. The following cases are not affected by package maps and continue
to use standard resolution:
* Relative paths or URLs (`./` or `../`).
* Absolute paths or URLs.
* Node.js builtin modules (`node:fs`, etc.).
### Limitations
* Package maps must be a single static file; dynamic configuration is not
supported.
* Circular dependency detection is not performed by the package map resolver.
* The package map file is loaded synchronously at startup.
## Node.js `package.json` field definitions
This section describes the fields used by the Node.js runtime. Other tools (such
@@ -1175,9 +1361,12 @@ This field defines [subpath imports][] for the current package.
[`"type"`]: #type
[`--conditions` / `-C` flag]: #resolving-user-conditions
[`--experimental-addon-modules`]: cli.md#--experimental-addon-modules
[`--experimental-package-map`]: cli.md#--experimental-package-mappath
[`--no-addons` flag]: cli.md#--no-addons
[`ERR_PACKAGE_MAP_EXTERNAL_FILE`]: errors.md#err_package_map_external_file
[`ERR_PACKAGE_PATH_NOT_EXPORTED`]: errors.md#err_package_path_not_exported
[`ERR_UNKNOWN_FILE_EXTENSION`]: errors.md#err_unknown_file_extension
[`URL`]: url.md#the-whatwg-url-api
[`package.json`]: #nodejs-packagejson-field-definitions
[customization hooks]: module.md#customization-hooks
[entry points]: #package-entry-points
@@ -1186,6 +1375,7 @@ This field defines [subpath imports][] for the current package.
[load ECMAScript modules from CommonJS modules]: modules.md#loading-ecmascript-modules-using-require
[merve]: https://github.com/anonrig/merve
[packages folder mapping]: https://github.com/WICG/import-maps#packages-via-trailing-slashes
[resolution algorithm pseudo-code]: modules.md#all-together
[self-reference]: #self-referencing-a-package-using-its-name
[subpath exports]: #subpath-exports
[subpath imports]: #subpath-imports
+3
View File
@@ -253,6 +253,9 @@ to use as a custom module loader.
.It Fl -permission
Enable the permission model.
.
.It Fl -experimental-package-map Ns = Ns Ar path
Enable experimental package map resolution using the specified configuration file.
.
.It Fl -experimental-stream-iter
Enable the experimental
.Sy node:stream/iter
+9
View File
@@ -1655,6 +1655,15 @@ E('ERR_PACKAGE_IMPORT_NOT_DEFINED', (specifier, packagePath, base) => {
return `Package import specifier "${specifier}" is not defined${packagePath ?
` in package ${packagePath}package.json` : ''} imported from ${base}`;
}, TypeError);
E('ERR_PACKAGE_MAP_EXTERNAL_FILE', (specifier, parentPath, configPath) => {
return `Cannot resolve "${specifier}" from "${parentPath}": file is not within any package defined in ${configPath}`;
}, Error);
E('ERR_PACKAGE_MAP_INVALID', (configPath, reason) => {
return `Invalid package-map.json at "${configPath}": ${reason}`;
}, SyntaxError);
E('ERR_PACKAGE_MAP_KEY_NOT_FOUND', (key, configPath) => {
return `Package key "${key}" referenced in dependencies but not defined in ${configPath}`;
}, Error);
E('ERR_PACKAGE_PATH_NOT_EXPORTED', (pkgPath, subpath, base = undefined) => {
if (subpath === '.')
return `No "exports" main defined in ${pkgPath}package.json${base ?
+76 -9
View File
@@ -184,6 +184,11 @@ const packageJsonReader = require('internal/modules/package_json_reader');
const { getOptionValue, getEmbedderOptions } = require('internal/options');
const shouldReportRequiredModules = getLazy(() => process.env.WATCH_REPORT_DEPENDENCIES);
const {
hasPackageMap,
packageMapResolve,
} = require('internal/modules/package_map');
const {
vm_dynamic_import_default_internal,
} = internalBinding('symbols');
@@ -667,14 +672,55 @@ function trySelf(parentPath, request, conditions) {
return false;
}
return resolveExpansion(expansion, pkg.path, pkg.data, parentPath, conditions);
}
/**
* Try to resolve using package map (if enabled via --experimental-package-map).
* @param {string} request - The bare specifier
* @param {Module} parent - The parent module
* @param {Set<string>} conditions - Export conditions
* @returns {string|undefined}
*/
function tryPackageMapResolveCJS(request, parent, conditions) {
if (!hasPackageMap()) { return undefined; }
const parentPath = trySelfParentPath(parent);
if (!parentPath) { return undefined; }
const mapped = packageMapResolve(request, parentPath);
if (mapped === undefined) {
const requireStack = getRequireStack(parent);
const message = getRequireStackMessage(request, requireStack);
// eslint-disable-next-line no-restricted-syntax
const err = new Error(message);
setOwnProperty(err, 'code', 'MODULE_NOT_FOUND');
setOwnProperty(err, 'requireStack', requireStack);
throw err;
}
const { packagePath, subpath } = mapped;
const packageJSONPath = path.resolve(packagePath, 'package.json');
const pkg = packageJsonReader.read(packageJSONPath);
if (pkg.exports !== undefined) {
return resolveExpansion(subpath, packageJSONPath, pkg, parentPath, conditions);
}
// No exports - try standard path resolution within the package
return Module._findPath(subpath, [packagePath], false, conditions);
}
function resolveExpansion(expansion, pkgJsonPath, pkgData, parentPath, conditions) {
const pkgPath = path.dirname(pkgJsonPath);
try {
const { packageExportsResolve } = require('internal/modules/esm/resolve');
return finalizeEsmResolution(packageExportsResolve(
pathToFileURL(pkg.path), expansion, pkg.data,
pathToFileURL(parentPath), conditions), parentPath, pkg.path);
pathToFileURL(pkgJsonPath), expansion, pkgData,
pathToFileURL(parentPath), conditions), parentPath, pkgPath);
} catch (e) {
if (e.code === 'ERR_MODULE_NOT_FOUND') {
throw createEsmNotFoundErr(request, pkg.path);
throw createEsmNotFoundErr(expansion, pkgPath);
}
throw e;
}
@@ -1436,6 +1482,14 @@ Module._resolveFilename = function(request, parent, isMain, options) {
}
const conditions = (options?.conditions) || getCjsConditions();
// Try package map resolution for bare specifiers (if --experimental-package-map is set)
if (!isRelative(request) && !path.isAbsolute(request)) {
const resolved = tryPackageMapResolveCJS(request, parent, conditions);
if (resolved !== undefined) {
return resolved;
}
}
let paths;
if (typeof options === 'object' && options !== null) {
@@ -1501,6 +1555,19 @@ Module._resolveFilename = function(request, parent, isMain, options) {
// Look up the filename first, since that's the cache key.
const filename = Module._findPath(request, paths, isMain, conditions);
if (filename) { return filename; }
const requireStack = getRequireStack(parent);
const message = getRequireStackMessage(request, requireStack);
// eslint-disable-next-line no-restricted-syntax
const err = new Error(message);
setOwnProperty(err, 'code', 'MODULE_NOT_FOUND');
setOwnProperty(err, 'requireStack', requireStack);
throw err;
};
function getRequireStack(parent) {
const requireStack = [];
for (let cursor = parent;
cursor;
@@ -1508,17 +1575,17 @@ Module._resolveFilename = function(request, parent, isMain, options) {
cursor = cursor[kFirstModuleParent]) {
ArrayPrototypePush(requireStack, cursor.filename || cursor.id);
}
return requireStack;
}
function getRequireStackMessage(request, requireStack) {
let message = `Cannot find module '${request}'`;
if (requireStack.length > 0) {
message = message + '\nRequire stack:\n- ' +
ArrayPrototypeJoin(requireStack, '\n- ');
}
// eslint-disable-next-line no-restricted-syntax
const err = new Error(message);
err.code = 'MODULE_NOT_FOUND';
err.requireStack = requireStack;
throw err;
};
return message;
}
/**
* Finishes resolving an ES module specifier into an absolute file path.
+24 -10
View File
@@ -28,7 +28,7 @@ const { BuiltinModule } = require('internal/bootstrap/realm');
const fs = require('fs');
const { getOptionValue } = require('internal/options');
// Do not eagerly grab .manifest, it may be in TDZ
const { sep, posix: { relative: relativePosixPath }, resolve } = require('path');
const { sep, posix: { relative: relativePosixPath }, resolve, join } = require('path');
const { URL, pathToFileURL, fileURLToPath, isURL, URLParse } = require('internal/url');
const { getCWDURL, setOwnProperty } = require('internal/util');
const { canParse: URLCanParse } = internalBinding('url');
@@ -55,6 +55,7 @@ const internalFsBinding = internalBinding('fs');
* @typedef {import('internal/modules/esm/package_config.js').PackageConfig} PackageConfig
*/
const { hasPackageMap, packageMapResolve } = require('internal/modules/package_map');
const emittedPackageWarnings = new SafeSet();
@@ -751,7 +752,6 @@ function packageImportsResolve(name, base, conditions) {
throw importNotDefined(name, packageJSONUrl, base);
}
/**
* Resolves a package specifier to a URL.
* @param {string} specifier - The package specifier to resolve.
@@ -765,21 +765,35 @@ function packageResolve(specifier, base, conditions) {
return new URL('node:' + specifier);
}
const { packageJSONUrl, packageJSONPath, packageSubpath } = packageJsonReader.getPackageJSONURL(specifier, base);
let packageJSONUrl, packageJSONPath, packageSubpath;
const packageConfig = packageJsonReader.read(packageJSONPath, { __proto__: null, specifier, base, isESM: true });
if (hasPackageMap()) {
// Package map is enabled - use it exclusively
const parentPath = fileURLToPath(base);
const mapped = packageMapResolve(specifier, parentPath);
if (mapped === undefined) {
throw new ERR_MODULE_NOT_FOUND(specifier, fileURLToPath(base), null);
}
const { packagePath, subpath } = mapped;
packageJSONPath = join(packagePath, 'package.json');
packageJSONUrl = pathToFileURL(packageJSONPath);
packageSubpath = subpath;
} else {
// Standard node_modules resolution
({ packageJSONUrl, packageJSONPath, packageSubpath } =
packageJsonReader.getPackageJSONURL(specifier, base));
}
const packageConfig = packageJsonReader.read(packageJSONPath, {
__proto__: null, specifier, base, isESM: true,
});
// Package match.
if (packageConfig.exports != null) {
return packageExportsResolve(
packageJSONUrl, packageSubpath, packageConfig, base, conditions);
}
if (packageSubpath === '.') {
return legacyMainResolve(
packageJSONUrl,
packageConfig,
base,
);
return legacyMainResolve(packageJSONUrl, packageConfig, base);
}
return new URL(packageSubpath, packageJSONUrl);
+309
View File
@@ -0,0 +1,309 @@
'use strict';
const {
JSONParse,
ObjectEntries,
SafeMap,
StringPrototypeIndexOf,
StringPrototypeSlice,
} = primordials;
const assert = require('internal/assert');
const { emitExperimentalWarning, getLazy, setOwnProperty } = require('internal/util');
const { dirname, resolve: pathResolve } = require('path');
const { fileURLToPath, pathToFileURL, URL } = require('internal/url');
const getPackageMapPath = getLazy(() =>
require('internal/options').getOptionValue('--experimental-package-map'),
);
const fs = require('fs');
const {
ERR_PACKAGE_MAP_EXTERNAL_FILE,
ERR_PACKAGE_MAP_INVALID,
ERR_PACKAGE_MAP_KEY_NOT_FOUND,
} = require('internal/errors').codes;
// Singleton - initialized once on first call
let packageMap;
let packageMapPath;
/**
* @typedef {object} PackageMapEntry
* @property {string} path - Absolute decoded path to package on disk
* @property {Map<string, string>} dependencies - Map from bare specifier to package key
*/
class PackageMap {
/** @type {string} */
#configPath;
/** @type {URL} */
#baseURL;
/** @type {Map<string, PackageMapEntry>} */
#packages;
/** @type {Map<string, string>} */
#pathToKey;
/** @type {Map<string, string|null>} */
#pathToKeyCache;
/**
* @param {string} configPath
* @param {object} data
*/
constructor(configPath, data) {
this.#configPath = configPath;
this.#baseURL = new URL('./', pathToFileURL(configPath));
this.#packages = new SafeMap();
this.#pathToKey = new SafeMap();
this.#pathToKeyCache = new SafeMap();
this.#parse(data);
}
/**
* @param {object} data
*/
#parse(data) {
if (!data.packages || typeof data.packages !== 'object') {
throw new ERR_PACKAGE_MAP_INVALID(this.#configPath, 'missing "packages" object');
}
const entries = ObjectEntries(data.packages);
for (let i = 0; i < entries.length; i++) {
const { 0: key, 1: entry } = entries[i];
const { url } = entry;
switch (typeof url) {
case 'string':
if (url === '') {
throw new ERR_PACKAGE_MAP_INVALID(this.#configPath, `package "${key}" has an empty "url" field`);
}
break;
case 'undefined':
throw new ERR_PACKAGE_MAP_INVALID(this.#configPath, `package "${key}" is missing "url" field`);
default:
throw new ERR_PACKAGE_MAP_INVALID(this.#configPath, `package "${key}" has invalid "url" field: expected string, got ${typeof url}`);
}
let packageURL;
try {
packageURL = new URL(entry.url, this.#baseURL);
} catch (err) {
const error = new ERR_PACKAGE_MAP_INVALID(
this.#configPath,
`package "${key}" has invalid url "${entry.url}"`,
);
setOwnProperty(error, 'cause', err);
throw error;
}
if (packageURL.protocol !== 'file:') {
throw new ERR_PACKAGE_MAP_INVALID(
this.#configPath,
`package "${key}" has unsupported URL scheme in url "${entry.url}"; only file: URLs and relative URLs are currently supported`,
);
}
let absolutePath;
try {
absolutePath = fileURLToPath(packageURL);
} catch (err) {
const error = new ERR_PACKAGE_MAP_INVALID(
this.#configPath,
`package "${key}" has invalid file url "${entry.url}"`,
);
setOwnProperty(error, 'cause', err);
throw error;
}
this.#packages.set(key, {
path: absolutePath,
dependencies: new SafeMap(ObjectEntries(entry.dependencies ?? {})),
});
// TODO(arcanis): Duplicates should be tolerated, but it requires changing module IDs
// to include the package ID whenever a package map is used.
const existingKey = this.#pathToKey.get(absolutePath);
if (existingKey != null) {
throw new ERR_PACKAGE_MAP_INVALID(
this.#configPath,
`packages "${existingKey}" and "${key}" have the same url "${entry.url}"; this will be supported in the future`,
);
}
this.#pathToKey.set(absolutePath, key);
}
}
/**
* Find which package key contains the given file path.
* @param {string} filePath
* @returns {string|null}
*/
#getKeyForPath(filePath) {
const cached = this.#pathToKeyCache.get(filePath);
if (cached !== undefined) { return cached; }
// Walk up to find containing package
let checkPath = filePath;
while (true) {
const key = this.#pathToKey.get(checkPath);
if (key !== undefined) {
this.#pathToKeyCache.set(filePath, key);
return key;
}
const parent = dirname(checkPath);
if (parent === checkPath) { break; }
checkPath = parent;
}
this.#pathToKeyCache.set(filePath, null);
return null;
}
/**
* Main resolution method.
* Returns the package path and subpath for the specifier, or undefined if
* the specifier is not in the parent package's dependencies.
* Throws ERR_PACKAGE_MAP_EXTERNAL_FILE if parentPath is not within any
* mapped package.
* @param {string} specifier
* @param {string} parentPath - File path of the importing module
* @returns {{packagePath: string, subpath: string}|undefined}
*/
resolve(specifier, parentPath) {
const parentKey = this.#getKeyForPath(parentPath);
if (parentKey === null) {
throw new ERR_PACKAGE_MAP_EXTERNAL_FILE(specifier, parentPath, this.#configPath);
}
const { packageName, subpath } = parsePackageName(specifier);
const parentEntry = this.#packages.get(parentKey);
const targetKey = parentEntry.dependencies.get(packageName);
if (targetKey === undefined) {
// Package not in parent's dependencies - let the caller throw the appropriate error
return undefined;
}
const targetEntry = this.#packages.get(targetKey);
if (!targetEntry) {
throw new ERR_PACKAGE_MAP_KEY_NOT_FOUND(targetKey, this.#configPath);
}
return { packagePath: targetEntry.path, subpath };
}
}
/**
* Parse a package specifier into name and subpath.
* @param {string} specifier
* @returns {{packageName: string, subpath: string}}
*/
function parsePackageName(specifier) {
const isScoped = specifier[0] === '@';
let slashIndex = StringPrototypeIndexOf(specifier, '/');
if (isScoped) {
if (slashIndex === -1) {
// Invalid: @scope without package name, treat whole thing as name
return { packageName: specifier, subpath: '.' };
}
slashIndex = StringPrototypeIndexOf(specifier, '/', slashIndex + 1);
}
if (slashIndex === -1) {
return { packageName: specifier, subpath: '.' };
}
return {
packageName: StringPrototypeSlice(specifier, 0, slashIndex),
subpath: '.' + StringPrototypeSlice(specifier, slashIndex),
};
}
/**
* Load and parse the package map from a config path.
* @param {string} configPath
* @returns {PackageMap}
*/
function loadPackageMap(configPath) {
let content;
try {
content = fs.readFileSync(configPath);
} catch (err) {
const error = new ERR_PACKAGE_MAP_INVALID(configPath, 'failed to read');
setOwnProperty(error, 'cause', err);
throw error;
}
// Resolve symlinks so that stored paths match the realpath'd module paths
// that Node.js uses during resolution.
configPath = fs.realpathSync(configPath);
let data;
try {
data = JSONParse(content);
} catch (err) {
const error = new ERR_PACKAGE_MAP_INVALID(configPath, `invalid JSON`);
setOwnProperty(error, 'cause', err);
throw error;
}
return new PackageMap(configPath, data);
}
/**
* Get the singleton package map, initializing on first call.
* @returns {PackageMap|null}
*/
function getPackageMap() {
if (packageMap !== undefined) { return packageMap; }
packageMapPath = getPackageMapPath();
if (!packageMapPath) {
packageMap = null;
return null;
}
emitExperimentalWarning('Package maps');
try {
packageMap = loadPackageMap(pathResolve(packageMapPath));
} catch (err) {
// Fallback to an empty package map to avoid repeatedly trying
// to load the broken package map file. Subsequent resolutions
// will still fail to resolve due to the package map being empty.
packageMap = new PackageMap(packageMapPath, { packages: {} });
throw err;
}
return packageMap;
}
/**
* Check if the package map is enabled.
* @returns {boolean}
*/
function hasPackageMap() {
return !!getPackageMapPath();
}
/**
* Resolve a package specifier using the package map.
* Returns the package path and subpath, or undefined if resolution should
* fall back to standard resolution.
* @param {string} specifier - The bare specifier (e.g., "lodash", "react/jsx-runtime")
* @param {string} parentPath - File path of the importing module
* @returns {{packagePath: string, subpath: string}|undefined}
*/
function packageMapResolve(specifier, parentPath) {
const map = getPackageMap();
assert(map !== null, 'Package map is not enabled');
return map.resolve(specifier, parentPath);
}
module.exports = {
hasPackageMap,
packageMapResolve,
};
+4
View File
@@ -871,6 +871,10 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() {
&EnvironmentOptions::experimental_config_file_path,
kDisallowedInEnvvar);
AddAlias("--experimental-default-config-file", "--experimental-config-file");
AddOption("--experimental-package-map",
"use the specified file for package map resolution",
&EnvironmentOptions::experimental_package_map_path,
kAllowedInEnvvar);
AddOption("--test",
"launch test runner on startup",
&EnvironmentOptions::test_runner,
+1
View File
@@ -277,6 +277,7 @@ class EnvironmentOptions : public Options {
bool report_exclude_env = false;
bool report_exclude_network = false;
std::string experimental_config_file_path;
std::string experimental_package_map_path;
inline DebugOptions* get_debug_options() { return &debug_options_; }
inline const DebugOptions& debug_options() const { return debug_options_; }
@@ -0,0 +1,31 @@
// Test that package maps resolve direct, subpath, and transitive dependencies.
import '../common/index.mjs';
import { spawnSyncAndAssert } from '../common/child_process.js';
import * as fixtures from '../common/fixtures.mjs';
const packageMapPath = fixtures.path('package-map/package-map.json');
const cwd = fixtures.path('package-map/root');
// Resolves a direct dependency.
spawnSyncAndAssert(process.execPath, [
'--no-warnings',
'--experimental-package-map', packageMapPath,
'--input-type=module',
'--eval', `import dep from 'dep-a'; console.log(dep);`,
], { cwd }, { stdout: /dep-a-value/, trim: true });
// Resolves a subpath export.
spawnSyncAndAssert(process.execPath, [
'--no-warnings',
'--experimental-package-map', packageMapPath,
'--input-type=module',
'--eval', `import util from 'dep-a/lib/util'; console.log(util);`,
], { cwd }, { stdout: /dep-a-util/, trim: true });
// Resolves transitive dependency from allowed package.
spawnSyncAndAssert(process.execPath, [
'--no-warnings',
'--experimental-package-map', packageMapPath,
'--input-type=module',
'--eval', `import depB from 'dep-b'; console.log(depB);`,
], { cwd }, { stdout: /dep-b using dep-a-value/, trim: true });
@@ -0,0 +1,30 @@
// Test that package maps fall back for builtins and reject files outside mapped packages.
import '../common/index.mjs';
import { spawnSyncAndAssert, spawnSyncAndExit } from '../common/child_process.js';
import * as fixtures from '../common/fixtures.mjs';
import tmpdir from '../common/tmpdir.js';
tmpdir.refresh();
const packageMapPath = fixtures.path('package-map/package-map.json');
const cwd = fixtures.path('package-map/root');
// Falls back for builtin modules.
spawnSyncAndAssert(process.execPath, [
'--no-warnings',
'--experimental-package-map', packageMapPath,
'--input-type=module',
'--eval', `import fs from 'node:fs'; console.log(typeof fs.readFileSync);`,
], { cwd }, { stdout: /function/, trim: true });
// Throws when parent not in map.
spawnSyncAndExit(process.execPath, [
'--no-warnings',
'--experimental-package-map', packageMapPath,
'--input-type=module',
'--eval', `import dep from 'dep-a'; console.log(dep);`,
], { cwd: tmpdir.path }, {
status: 1,
signal: null,
stderr: /ERR_PACKAGE_MAP_EXTERNAL_FILE/,
});
@@ -0,0 +1,127 @@
// Test package map error handling: invalid JSON, missing fields, bad URLs, duplicates.
import '../common/index.mjs';
import assert from 'node:assert';
import { spawnSyncAndAssert, spawnSyncAndExit } from '../common/child_process.js';
import * as fixtures from '../common/fixtures.mjs';
import tmpdir from '../common/tmpdir.js';
import { writeFileSync } from 'node:fs';
import { pathToFileURL } from 'node:url';
tmpdir.refresh();
const cwd = fixtures.path('package-map/root');
// Throws ERR_PACKAGE_MAP_INVALID for invalid JSON.
spawnSyncAndExit(process.execPath, [
'--no-warnings',
'--experimental-package-map',
fixtures.path('package-map/package-map-invalid-syntax.json'),
'--input-type=module',
'--eval', `import x from 'dep-a';`,
], { cwd }, {
status: 1,
signal: null,
stderr: /ERR_PACKAGE_MAP_INVALID/,
});
// Throws ERR_PACKAGE_MAP_INVALID for missing packages field.
spawnSyncAndExit(process.execPath, [
'--no-warnings',
'--experimental-package-map',
fixtures.path('package-map/package-map-invalid-schema.json'),
'--input-type=module',
'--eval', `import x from 'dep-a';`,
], { cwd }, {
status: 1,
signal: null,
stderr(output) {
assert.match(output, /ERR_PACKAGE_MAP_INVALID/);
assert.match(output, /packages/);
},
});
// Throws ERR_PACKAGE_MAP_KEY_NOT_FOUND for undefined dependency key.
spawnSyncAndExit(process.execPath, [
'--no-warnings',
'--experimental-package-map',
fixtures.path('package-map/package-map-missing-dep.json'),
'--input-type=module',
'--eval', `import x from 'nonexistent';`,
], { cwd }, {
status: 1,
signal: null,
stderr: /ERR_PACKAGE_MAP_KEY_NOT_FOUND/,
});
// Throws for non-existent map file.
spawnSyncAndExit(process.execPath, [
'--no-warnings',
'--experimental-package-map', '/nonexistent/package-map.json',
'--input-type=module',
'--eval', `import x from 'dep-a';`,
], { cwd }, {
status: 1,
signal: null,
stderr(output) {
assert.match(output, /ERR_PACKAGE_MAP_INVALID/);
assert.match(output, /no such file or directory/);
},
});
// Throws ERR_PACKAGE_MAP_INVALID for unsupported URL scheme in url.
spawnSyncAndExit(process.execPath, [
'--no-warnings',
'--experimental-package-map',
fixtures.path('package-map/package-map-https-path.json'),
'--input-type=module',
'--eval', `import x from 'dep-a';`,
], { cwd }, {
status: 1,
signal: null,
stderr(output) {
assert.match(output, /ERR_PACKAGE_MAP_INVALID/);
assert.match(output, /unsupported URL scheme/);
assert.match(output, /https:\/\//);
},
});
// Accepts file:// URLs in url.
{
const fileUrlFixturePath = tmpdir.resolve('package-map-file-url.json');
writeFileSync(fileUrlFixturePath, JSON.stringify({
packages: {
'root': {
url: pathToFileURL(fixtures.path('package-map/root')).href,
dependencies: { 'dep-a': 'dep-a' },
},
'dep-a': {
url: pathToFileURL(fixtures.path('package-map/dep-a')).href,
dependencies: {},
},
},
}));
spawnSyncAndAssert(process.execPath, [
'--no-warnings',
'--experimental-package-map', fileUrlFixturePath,
'--input-type=module',
'--eval', `import dep from 'dep-a'; console.log(dep);`,
], { cwd }, { stdout: /dep-a-value/, trim: true });
}
// Throws ERR_PACKAGE_MAP_INVALID for duplicate package URLs.
spawnSyncAndExit(process.execPath, [
'--no-warnings',
'--experimental-package-map',
fixtures.path('package-map/package-map-duplicate-path.json'),
'--input-type=module',
'--eval', `import x from 'dep-a';`,
], { cwd }, {
status: 1,
signal: null,
stderr(output) {
assert.match(output, /ERR_PACKAGE_MAP_INVALID/);
assert.match(output, /pkg-a/);
assert.match(output, /pkg-b/);
},
});
@@ -0,0 +1,23 @@
// Test that package maps respect package.json conditional and pattern exports.
import '../common/index.mjs';
import { spawnSyncAndAssert } from '../common/child_process.js';
import * as fixtures from '../common/fixtures.mjs';
const packageMapPath = fixtures.path('package-map/package-map.json');
const cwd = fixtures.path('package-map/root');
// Respects conditional exports (import).
spawnSyncAndAssert(process.execPath, [
'--no-warnings',
'--experimental-package-map', packageMapPath,
'--input-type=module',
'--eval', `import { format } from 'dep-a'; console.log(format);`,
], { cwd }, { stdout: /esm/, trim: true });
// Respects pattern exports.
spawnSyncAndAssert(process.execPath, [
'--no-warnings',
'--experimental-package-map', packageMapPath,
'--input-type=module',
'--eval', `import util from 'dep-a/lib/util'; console.log(util);`,
], { cwd }, { stdout: /dep-a-util/, trim: true });
@@ -0,0 +1,26 @@
// Test that the package map flag has no impact when not set and emits a warning when used.
import '../common/index.mjs';
import assert from 'node:assert';
import { spawnSyncAndAssert } from '../common/child_process.js';
import * as fixtures from '../common/fixtures.mjs';
const packageMapPath = fixtures.path('package-map/package-map.json');
// No impact when flag not set.
spawnSyncAndAssert(process.execPath, [
'--no-warnings',
'--input-type=module',
'--eval', `import fs from 'node:fs'; console.log('ok');`,
], { stdout: /ok/, trim: true });
// Emits experimental warning on first use.
spawnSyncAndAssert(process.execPath, [
'--experimental-package-map', packageMapPath,
'--input-type=module',
'--eval', `import dep from 'dep-a';`,
], { cwd: fixtures.path('package-map/root') }, {
stderr(output) {
assert.match(output, /ExperimentalWarning/);
assert.match(output, /Package map/i);
},
});
@@ -0,0 +1,65 @@
// Test package map path handling: containment, external paths, longest-path-wins.
import '../common/index.mjs';
import { spawnSyncAndAssert, spawnSyncAndExit } from '../common/child_process.js';
import * as fixtures from '../common/fixtures.mjs';
// Path containment: does not match pkg-other as being inside pkg.
spawnSyncAndAssert(process.execPath, [
'--no-warnings',
'--experimental-package-map',
fixtures.path('package-map/package-map-path-prefix.json'),
'--input-type=module',
'--eval', `import pkg from 'pkg'; console.log(pkg);`,
], { cwd: fixtures.path('package-map/pkg-other') }, {
stdout: /pkg-value/,
trim: true,
});
// External paths: resolves packages outside the package map directory.
spawnSyncAndAssert(process.execPath, [
'--no-warnings',
'--experimental-package-map',
fixtures.path('package-map/nested-project/package-map-external-deps.json'),
'--input-type=module',
'--eval', `import dep from 'dep-a'; console.log(dep);`,
], { cwd: fixtures.path('package-map/nested-project/src') }, {
stdout: /dep-a-value/,
trim: true,
});
// URL fields are decoded as URLs before being converted to paths.
spawnSyncAndAssert(process.execPath, [
'--no-warnings',
'--experimental-package-map',
fixtures.path('package-map/package-map-url-encoded-spaces.json'),
'--input-type=module',
'--eval', `import dep from 'dep-with-spaces'; console.log(dep);`,
], { cwd: fixtures.path('package-map/root') }, {
stdout: /dep-with-spaces-value/,
trim: true,
});
// Longest path wins: nested package uses its own dependencies, not the parent's.
{
const longestPathMap = fixtures.path('package-map/package-map-longest-path.json');
const cwd = fixtures.path('package-map/root');
spawnSyncAndAssert(process.execPath, [
'--no-warnings',
'--experimental-package-map', longestPathMap,
'--input-type=module',
'--eval', `import inner from 'inner'; console.log(inner);`,
], { cwd }, { stdout: /inner using dep-a-value/, trim: true });
// Root does not list dep-a, so importing it from root should fail.
spawnSyncAndExit(process.execPath, [
'--no-warnings',
'--experimental-package-map', longestPathMap,
'--input-type=module',
'--eval', `import dep from 'dep-a';`,
], { cwd }, {
status: 1,
signal: null,
stderr: /ERR_MODULE_NOT_FOUND/,
});
}
@@ -0,0 +1,26 @@
// Test that package maps resolve correctly through a symlinked ancestor directory.
import { canCreateSymLink } from '../common/index.mjs';
import { spawnSyncAndAssert } from '../common/child_process.js';
import * as fixtures from '../common/fixtures.mjs';
import tmpdir from '../common/tmpdir.js';
import { symlinkSync } from 'node:fs';
import path from 'node:path';
if (!canCreateSymLink()) {
process.exit(0);
}
tmpdir.refresh();
const symlinkDir = tmpdir.resolve('symlinked-package-map-esm');
symlinkSync(fixtures.path('package-map'), symlinkDir, 'dir');
spawnSyncAndAssert(process.execPath, [
'--no-warnings',
'--experimental-package-map', path.join(symlinkDir, 'package-map.json'),
'--input-type=module',
'--eval', `import dep from 'dep-a'; console.log(dep);`,
], { cwd: fixtures.path('package-map/root') }, {
stdout: /dep-a-value/,
trim: true,
});
@@ -0,0 +1,19 @@
// Test that the same bare specifier resolves to different packages depending on the importer.
import '../common/index.mjs';
import assert from 'node:assert';
import { spawnSyncAndAssert } from '../common/child_process.js';
import * as fixtures from '../common/fixtures.mjs';
spawnSyncAndAssert(process.execPath, [
'--no-warnings',
'--experimental-package-map',
fixtures.path('package-map/package-map-version-fork.json'),
'--input-type=module',
'--eval',
`import app18 from 'app-18'; import app19 from 'app-19'; console.log(app18); console.log(app19);`,
], { cwd: fixtures.path('package-map/root') }, {
stdout(output) {
assert.match(output, /app-18 using react 18/);
assert.match(output, /app-19 using react 19/);
},
});
+2
View File
@@ -0,0 +1,2 @@
import react from 'react';
export default `app-18 using react ${react.version}`;
+7
View File
@@ -0,0 +1,7 @@
{
"name": "app-18",
"type": "module",
"exports": {
".": "./index.js"
}
}
+2
View File
@@ -0,0 +1,2 @@
import react from 'react';
export default `app-19 using react ${react.version}`;
+7
View File
@@ -0,0 +1,7 @@
{
"name": "app-19",
"type": "module",
"exports": {
".": "./index.js"
}
}
+3
View File
@@ -0,0 +1,3 @@
import react from 'react';
export const reactVersion = react.version;
export default `component-lib using react ${react.version}`;
+7
View File
@@ -0,0 +1,7 @@
{
"name": "component-lib",
"type": "module",
"exports": {
".": "./index.js"
}
}
+1
View File
@@ -0,0 +1 @@
export default 'dep-with-spaces-value';
@@ -0,0 +1,7 @@
{
"name": "dep-with-spaces",
"type": "module",
"exports": {
".": "./index.js"
}
}
+4
View File
@@ -0,0 +1,4 @@
module.exports = {
default: 'dep-a-value',
format: 'cjs',
};
+2
View File
@@ -0,0 +1,2 @@
export default 'dep-a-value';
export const format = 'esm';
+1
View File
@@ -0,0 +1 @@
export default 'dep-a-util';
+11
View File
@@ -0,0 +1,11 @@
{
"name": "dep-a",
"type": "module",
"exports": {
".": {
"import": "./index.js",
"require": "./index.cjs"
},
"./lib/*": "./lib/*.js"
}
}
+2
View File
@@ -0,0 +1,2 @@
import depA from 'dep-a';
export default `dep-b using ${depA}`;
+7
View File
@@ -0,0 +1,7 @@
{
"name": "dep-b",
"type": "module",
"exports": {
".": "./index.js"
}
}
+1
View File
@@ -0,0 +1 @@
export default 'nameless-package';
@@ -0,0 +1,12 @@
{
"packages": {
"app": {
"url": "./src",
"dependencies": {"dep-a": "dep-a"}
},
"dep-a": {
"url": "../dep-a",
"dependencies": {}
}
}
}
Whitespace-only changes.
+1
View File
@@ -0,0 +1 @@
export default 'not-a-dep-value';
+7
View File
@@ -0,0 +1,7 @@
{
"name": "not-a-dep",
"type": "module",
"exports": {
".": "./index.js"
}
}
@@ -0,0 +1,12 @@
{
"packages": {
"pkg-a": {
"url": "./root",
"dependencies": {}
},
"pkg-b": {
"url": "./root",
"dependencies": {}
}
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"packages": {
"root": {
"url": "./root",
"dependencies": {"dep-a": "dep-a"}
},
"dep-a": {
"url": "https://example.com/dep-a",
"dependencies": {}
}
}
}
@@ -0,0 +1,3 @@
{
"not-packages": {}
}
@@ -0,0 +1 @@
{ invalid json here
+16
View File
@@ -0,0 +1,16 @@
{
"packages": {
"root": {
"url": "./root",
"dependencies": {"inner": "inner"}
},
"inner": {
"url": "./root/node_modules/inner",
"dependencies": {"dep-a": "dep-a"}
},
"dep-a": {
"url": "./dep-a",
"dependencies": {}
}
}
}
@@ -0,0 +1,8 @@
{
"packages": {
"root": {
"url": "./root",
"dependencies": {"nonexistent": "nonexistent-key"}
}
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"packages": {
"pkg": {
"url": "./pkg",
"dependencies": {}
},
"pkg-other": {
"url": "./pkg-other",
"dependencies": {"pkg": "pkg"}
}
}
}
@@ -0,0 +1,12 @@
{
"packages": {
"root": {
"url": "./root",
"dependencies": {"dep-with-spaces": "dep-with-spaces"}
},
"dep-with-spaces": {
"url": "./dep%20with%20spaces",
"dependencies": {}
}
}
}
+22
View File
@@ -0,0 +1,22 @@
{
"packages": {
"root": {
"url": "./root",
"dependencies": {"app-18": "app-18", "app-19": "app-19"}
},
"app-18": {
"url": "./app-18",
"dependencies": {"react": "react@18"}
},
"app-19": {
"url": "./app-19",
"dependencies": {"react": "react@19"}
},
"react@18": {
"url": "./react-18"
},
"react@19": {
"url": "./react-19"
}
}
}
+20
View File
@@ -0,0 +1,20 @@
{
"packages": {
"root": {
"url": "./root",
"dependencies": {"dep-a": "dep-a", "dep-b": "dep-b"}
},
"dep-a": {
"url": "./dep-a",
"dependencies": {}
},
"dep-b": {
"url": "./dep-b",
"dependencies": {"dep-a": "dep-a"}
},
"not-a-dep": {
"url": "./not-a-dep",
"dependencies": {}
}
}
}
+1
View File
@@ -0,0 +1 @@
export default 'pkg-other-value';
+7
View File
@@ -0,0 +1,7 @@
{
"name": "pkg-other",
"type": "module",
"exports": {
".": "./index.js"
}
}
+3
View File
@@ -0,0 +1,3 @@
module.exports = {
default: 'pkg-value',
};
+1
View File
@@ -0,0 +1 @@
export default 'pkg-value';
+10
View File
@@ -0,0 +1,10 @@
{
"name": "pkg",
"type": "module",
"exports": {
".": {
"import": "./index.js",
"require": "./index.cjs"
}
}
}
+2
View File
@@ -0,0 +1,2 @@
export const version = '18';
export default { version: '18' };
+8
View File
@@ -0,0 +1,8 @@
{
"name": "react",
"version": "18.0.0",
"type": "module",
"exports": {
".": "./index.js"
}
}
+2
View File
@@ -0,0 +1,2 @@
export const version = '19';
export default { version: '19' };
+8
View File
@@ -0,0 +1,8 @@
{
"name": "react",
"version": "19.0.0",
"type": "module",
"exports": {
".": "./index.js"
}
}
+1
View File
@@ -0,0 +1 @@
export default 'root-package';
+2
View File
@@ -0,0 +1,2 @@
const depA = require('dep-a');
module.exports = { default: `inner using ${depA.default}` };
+2
View File
@@ -0,0 +1,2 @@
import depA from 'dep-a';
export default `inner using ${depA}`;
+10
View File
@@ -0,0 +1,10 @@
{
"name": "inner",
"type": "module",
"exports": {
".": {
"import": "./index.js",
"require": "./index.cjs"
}
}
}
+7
View File
@@ -0,0 +1,7 @@
{
"name": "root",
"type": "module",
"exports": {
".": "./index.js"
}
}
+1
View File
@@ -104,6 +104,7 @@ expected.beforePreExec = new Set([
'NativeModule internal/modules/package_json_reader',
'Internal Binding module_wrap',
'NativeModule internal/modules/cjs/loader',
'NativeModule internal/modules/package_map',
'NativeModule diagnostics_channel',
'Internal Binding diagnostics_channel',
'Internal Binding wasm_web_api',
+79
View File
@@ -0,0 +1,79 @@
'use strict';
require('../common');
const fixtures = require('../common/fixtures');
const assert = require('node:assert');
const { spawnSync } = require('node:child_process');
const { describe, it } = require('node:test');
const onlyIfNodeOptionsSupport = {
skip: process.config.variables.node_without_node_options,
};
describe('--experimental-package-map CLI behavior', () => {
it('works via NODE_OPTIONS', onlyIfNodeOptionsSupport, () => {
const { status, stdout, stderr } = spawnSync(process.execPath, [
'--no-warnings',
'-e',
`const dep = require('dep-a'); console.log(dep);`,
], {
cwd: fixtures.path('package-map/root'),
encoding: 'utf8',
env: {
...process.env,
NODE_OPTIONS: `--experimental-package-map=${JSON.stringify(fixtures.path('package-map/package-map.json'))}`,
},
});
assert.strictEqual(stderr, '');
assert.match(stdout, /dep-a-value/);
assert.strictEqual(status, 0, stderr);
});
it('emits experimental warning on first use', () => {
const { status, stderr } = spawnSync(process.execPath, [
'--experimental-package-map', fixtures.path('package-map/package-map.json'),
'-e',
`require('dep-a');`,
], {
cwd: fixtures.path('package-map/root'),
encoding: 'utf8',
});
assert.match(stderr, /ExperimentalWarning/);
assert.match(stderr, /[Pp]ackage map/);
assert.strictEqual(status, 0, stderr);
});
it('accepts relative path', () => {
const { status, stdout, stderr } = spawnSync(process.execPath, [
'--no-warnings',
'--experimental-package-map', '../package-map.json',
'-e',
`const dep = require('dep-a'); console.log(dep.default);`,
], {
cwd: fixtures.path('package-map/root'),
encoding: 'utf8',
});
assert.strictEqual(stderr, '');
// Relative path ../package-map.json resolved from cwd (root/)
assert.match(stdout, /dep-a-value/);
assert.strictEqual(status, 0, stderr);
});
it('accepts absolute path', () => {
const { status, stderr } = spawnSync(process.execPath, [
'--no-warnings',
'--experimental-package-map', fixtures.path('package-map/package-map.json'),
'-e',
`console.log('ok');`,
], {
encoding: 'utf8',
});
assert.strictEqual(stderr, '');
assert.strictEqual(status, 0, stderr);
});
});
+363
View File
@@ -0,0 +1,363 @@
'use strict';
const common = require('../common');
const fixtures = require('../common/fixtures');
const assert = require('node:assert');
const { spawnSync } = require('node:child_process');
const { symlinkSync, writeFileSync } = require('node:fs');
const path = require('node:path');
const { describe, it } = require('node:test');
const { pathToFileURL } = require('node:url');
const tmpdir = require('../common/tmpdir');
tmpdir.refresh();
const packageMapPath = fixtures.path('package-map/package-map.json');
// Generated at runtime because file:// URLs must be absolute, making them machine-dependent.
const fileUrlFixturePath = tmpdir.resolve('package-map-file-url.json');
writeFileSync(fileUrlFixturePath, JSON.stringify({
packages: {
'root': {
url: pathToFileURL(fixtures.path('package-map/root')).href,
dependencies: { 'dep-a': 'dep-a' },
},
'dep-a': {
url: pathToFileURL(fixtures.path('package-map/dep-a')).href,
dependencies: {},
},
},
}));
describe('CJS: --experimental-package-map', { concurrency: !process.env.TEST_PARALLEL }, () => {
describe('basic resolution', () => {
it('resolves require() through package map', () => {
const { status, stdout, stderr } = spawnSync(process.execPath, [
'--no-warnings',
'--experimental-package-map', packageMapPath,
'-e',
`const dep = require('dep-a'); console.log(dep.default);`,
], {
cwd: fixtures.path('package-map/root'),
encoding: 'utf8',
});
assert.strictEqual(stderr, '');
assert.match(stdout, /dep-a-value/);
assert.strictEqual(status, 0, stderr);
});
it('resolves subpath require()', () => {
const { status, stdout, stderr } = spawnSync(process.execPath, [
'--no-warnings',
'--experimental-package-map', packageMapPath,
'-e',
`const util = require('dep-a/lib/util'); console.log(util.default);`,
], {
cwd: fixtures.path('package-map/root'),
encoding: 'utf8',
});
assert.strictEqual(stderr, '');
assert.match(stdout, /dep-a-util/);
assert.strictEqual(status, 0, stderr);
});
it('resolves transitive dependencies', () => {
const { status, stdout, stderr } = spawnSync(process.execPath, [
'--no-warnings',
'--experimental-package-map', packageMapPath,
'-e',
`const depB = require('dep-b'); console.log(depB.default);`,
], {
cwd: fixtures.path('package-map/root'),
encoding: 'utf8',
});
assert.strictEqual(stderr, '');
assert.match(stdout, /dep-b using dep-a-value/);
assert.strictEqual(status, 0, stderr);
});
});
describe('resolution boundaries', () => {
it('falls back for builtin modules', () => {
const { status, stdout, stderr } = spawnSync(process.execPath, [
'--no-warnings',
'--experimental-package-map', packageMapPath,
'-e',
`const fs = require('fs'); console.log(typeof fs.readFileSync);`,
], {
cwd: fixtures.path('package-map/root'),
encoding: 'utf8',
});
assert.strictEqual(stderr, '');
assert.match(stdout, /function/);
assert.strictEqual(status, 0, stderr);
});
it('throws when parent not in map', () => {
const { status, stderr } = spawnSync(process.execPath, [
'--no-warnings',
'--experimental-package-map', packageMapPath,
'-e',
`require('dep-a');`,
], {
cwd: tmpdir.path,
encoding: 'utf8',
});
assert.match(stderr, /ERR_PACKAGE_MAP_EXTERNAL_FILE/);
assert.notStrictEqual(status, 0, stderr);
});
});
describe('error handling', () => {
it('throws for invalid JSON', () => {
const { status, stderr } = spawnSync(process.execPath, [
'--no-warnings',
'--experimental-package-map',
fixtures.path('package-map/package-map-invalid-syntax.json'),
'-e',
`require('dep-a');`,
], {
cwd: fixtures.path('package-map/root'),
encoding: 'utf8',
});
assert.match(stderr, /ERR_PACKAGE_MAP_INVALID/);
assert.notStrictEqual(status, 0, stderr);
});
it('throws for missing packages field', () => {
const { status, stderr } = spawnSync(process.execPath, [
'--no-warnings',
'--experimental-package-map',
fixtures.path('package-map/package-map-invalid-schema.json'),
'-e',
`require('dep-a');`,
], {
cwd: fixtures.path('package-map/root'),
encoding: 'utf8',
});
assert.match(stderr, /ERR_PACKAGE_MAP_INVALID/);
assert.notStrictEqual(status, 0, stderr);
});
it('throws for unsupported URL scheme in url', () => {
const { status, stderr } = spawnSync(process.execPath, [
'--experimental-package-map',
fixtures.path('package-map/package-map-https-path.json'),
'-e',
`require('dep-a');`,
], {
cwd: fixtures.path('package-map/root'),
encoding: 'utf8',
});
assert.match(stderr, /ERR_PACKAGE_MAP_INVALID/);
assert.match(stderr, /unsupported URL scheme/);
assert.match(stderr, /https:\/\//);
assert.notStrictEqual(status, 0, stderr);
});
it('accepts file:// URLs in url', () => {
const { status, stdout, stderr } = spawnSync(process.execPath, [
'--no-warnings',
'--experimental-package-map', fileUrlFixturePath,
'-e',
`const dep = require('dep-a'); console.log(dep.default);`,
], {
cwd: fixtures.path('package-map/root'),
encoding: 'utf8',
});
assert.strictEqual(stderr, '');
assert.match(stdout, /dep-a-value/);
assert.strictEqual(status, 0, stderr);
});
it('throws for duplicate package URLs', () => {
const { status, stderr } = spawnSync(process.execPath, [
'--no-warnings',
'--experimental-package-map',
fixtures.path('package-map/package-map-duplicate-path.json'),
'-e',
`require('dep-a');`,
], {
cwd: fixtures.path('package-map/root'),
encoding: 'utf8',
});
assert.match(stderr, /ERR_PACKAGE_MAP_INVALID/);
assert.match(stderr, /pkg-a/);
assert.match(stderr, /pkg-b/);
assert.notStrictEqual(status, 0, stderr);
});
});
describe('conditional exports', () => {
it('respects require condition in exports', () => {
const { status, stdout, stderr } = spawnSync(process.execPath, [
'--no-warnings',
'--experimental-package-map', packageMapPath,
'-e',
`const dep = require('dep-a'); console.log(dep.format);`,
], {
cwd: fixtures.path('package-map/root'),
encoding: 'utf8',
});
assert.strictEqual(stderr, '');
assert.match(stdout, /cjs/); // Should get CJS export
assert.strictEqual(status, 0, stderr);
});
});
describe('disabled by default', () => {
it('has no impact when flag not set', () => {
const { status, stdout, stderr } = spawnSync(process.execPath, [
'--no-warnings',
'-e',
`const fs = require('fs'); console.log('ok');`,
], {
encoding: 'utf8',
});
assert.strictEqual(stderr, '');
assert.match(stdout, /ok/);
assert.strictEqual(status, 0, stderr);
});
});
describe('path containment edge cases', () => {
it('does not match pkg-other as being inside pkg', () => {
// Regression test: pkg-other (at ./pkg-other) should not be
// incorrectly matched as inside pkg (at ./pkg) just because
// the string "./pkg-other" starts with "./pkg"
const { status, stdout, stderr } = spawnSync(process.execPath, [
'--no-warnings',
'--experimental-package-map',
fixtures.path('package-map/package-map-path-prefix.json'),
'-e',
`const pkg = require('pkg'); console.log(pkg.default);`,
], {
cwd: fixtures.path('package-map/pkg-other'),
encoding: 'utf8',
});
assert.strictEqual(stderr, '');
assert.match(stdout, /pkg-value/);
assert.strictEqual(status, 0, stderr);
});
});
describe('external package paths', () => {
it('resolves packages outside the package map directory via relative paths', () => {
const { status, stdout, stderr } = spawnSync(process.execPath, [
'--no-warnings',
'--experimental-package-map',
fixtures.path('package-map/nested-project/package-map-external-deps.json'),
'-e',
`const dep = require('dep-a'); console.log(dep.default);`,
], {
cwd: fixtures.path('package-map/nested-project/src'),
encoding: 'utf8',
});
assert.strictEqual(stderr, '');
assert.match(stdout, /dep-a-value/);
assert.strictEqual(status, 0, stderr);
});
});
describe('same request resolves to different versions', () => {
const versionForkMap = fixtures.path('package-map/package-map-version-fork.json');
it('resolves the same bare specifier to different packages depending on the importer', () => {
// app-18 and app-19 both require 'react', but the package map wires
// them to react@18 and react@19 respectively.
const { status, stdout, stderr } = spawnSync(process.execPath, [
'--no-warnings',
'--experimental-package-map', versionForkMap,
'-e',
`const app18 = require('app-18'); const app19 = require('app-19'); console.log(app18.default); console.log(app19.default);`,
], {
cwd: fixtures.path('package-map/root'),
encoding: 'utf8',
});
assert.strictEqual(stderr, '');
assert.match(stdout, /app-18 using react 18/);
assert.match(stdout, /app-19 using react 19/);
assert.strictEqual(status, 0, stderr);
});
});
describe('longest path wins', () => {
const longestPathMap = fixtures.path('package-map/package-map-longest-path.json');
it('resolves nested package using its own dependencies, not the parent', () => {
// Inner lives at ./root/node_modules/inner which is inside root's
// path (./root). The longest matching path should win, so code in
// inner should resolve dep-a (inner's dep), not be treated as root.
const { status, stdout, stderr } = spawnSync(process.execPath, [
'--no-warnings',
'--experimental-package-map', longestPathMap,
'-e',
`const inner = require('inner'); console.log(inner.default);`,
], {
cwd: fixtures.path('package-map/root'),
encoding: 'utf8',
});
assert.strictEqual(stderr, '');
assert.match(stdout, /inner using dep-a-value/);
assert.strictEqual(status, 0, stderr);
});
it('falls back for undeclared dependency in nested package parent', () => {
// Root does not list dep-a in its dependencies, so requiring it
// from root should fail with MODULE_NOT_FOUND.
const { status, stderr } = spawnSync(process.execPath, [
'--no-warnings',
'--experimental-package-map', longestPathMap,
'-e',
`require('dep-a');`,
], {
cwd: fixtures.path('package-map/root'),
encoding: 'utf8',
});
assert.match(stderr, /Cannot find module/);
assert.notStrictEqual(status, 0);
});
});
describe('symlink in ancestor of package map', {
skip: !common.canCreateSymLink() && 'insufficient privileges for symlinks',
}, () => {
const symlinkDir = tmpdir.resolve('symlinked-package-map-cjs');
symlinkSync(fixtures.path('package-map'), symlinkDir, 'dir');
it('resolves through a symlinked ancestor directory', () => {
const symlinkMapPath = path.join(symlinkDir, 'package-map.json');
const { status, stdout, stderr } = spawnSync(process.execPath, [
'--no-warnings',
'--experimental-package-map', symlinkMapPath,
'-e',
`const dep = require('dep-a'); console.log(dep.default);`,
], {
cwd: fixtures.path('package-map/root'),
encoding: 'utf8',
});
assert.strictEqual(stderr, '');
assert.match(stdout, /dep-a-value/);
assert.strictEqual(status, 0, stderr);
});
});
});