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

module: add support for nodeEntryPointConfig.loaders in package.json #43973

Closed
wants to merge 2 commits into from
Closed
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
28 changes: 28 additions & 0 deletions doc/api/packages.md
Original file line number Diff line number Diff line change
Expand Up @@ -1315,10 +1315,36 @@ Package imports permit mapping to external packages.

This field defines [subpath imports][] for the current package.

### `nodeEntryPointConfig`

<!-- YAML
added: REPLACEME
-->

* Type: {Object}

Additional configuration on how to start the Node.js processes inside a package
(does not apply if the entry point is using `.mjs` or `.cjs` file extension).

#### `nodeEntryPointConfig.loaders`

<!-- YAML
added: REPLACEME
-->

* Type: {string\[]}

Specify the `module` of a custom experimental [ECMAScript module loader][].
`module` may be any string accepted as an [`import` specifier][] resolved
relative to the `package.json` file.
This field is ignored if the [`--experimental-loader`][] CLI flag is used.


[Babel]: https://babeljs.io/
[CommonJS]: modules.md
[Conditional exports]: #conditional-exports
[Corepack]: corepack.md
[ECMAScript module loader]: esm.md#loaders
[ES module]: esm.md
[ES modules]: esm.md
[Node.js documentation for this section]: https://github.com/nodejs/node/blob/HEAD/doc/api/packages.md#conditions-definitions
Expand All @@ -1329,9 +1355,11 @@ This field defines [subpath imports][] for the current package.
[`"packageManager"`]: #packagemanager
[`"type"`]: #type
[`--conditions` / `-C` flag]: #resolving-user-conditions
[`--experimental-loader`]: cli.md#--experimental-loadermodule
[`--no-addons` flag]: cli.md#--no-addons
[`ERR_PACKAGE_PATH_NOT_EXPORTED`]: errors.md#err_package_path_not_exported
[`esm`]: https://github.com/standard-things/esm#readme
[`import` specifier]: esm.md#import-specifiers
[`package.json`]: #nodejs-packagejson-field-definitions
[entry points]: #package-entry-points
[folders as modules]: modules.md#folders-as-modules
Expand Down
2 changes: 2 additions & 0 deletions lib/internal/modules/cjs/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -314,10 +314,12 @@ function readPackage(requestPath) {
try {
const parsed = JSONParse(json);
const filtered = {
__proto__: null,
JakobJingleheimer marked this conversation as resolved.
Show resolved Hide resolved
name: parsed.name,
main: parsed.main,
exports: parsed.exports,
imports: parsed.imports,
nodeEntryPointConfig: parsed.nodeEntryPointConfig,
type: parsed.type
};
packageJsonCache.set(jsonPath, filtered);
Expand Down
6 changes: 3 additions & 3 deletions lib/internal/modules/esm/resolve.js
Original file line number Diff line number Diff line change
Expand Up @@ -1080,7 +1080,7 @@ function throwIfUnsupportedURLScheme(parsed, experimentalNetworkImports) {
}
}

async function defaultResolve(specifier, context = {}) {
function defaultResolve(specifier, context = {}) {
let { parentURL, conditions } = context;
if (parentURL && policy?.manifest) {
const redirects = policy.manifest.getDependencyMapper(parentURL);
Expand Down Expand Up @@ -1226,11 +1226,11 @@ const {

if (policy) {
const $defaultResolve = defaultResolve;
module.exports.defaultResolve = async function defaultResolve(
module.exports.defaultResolve = function defaultResolve(
specifier,
context
) {
const ret = await $defaultResolve(specifier, context);
const ret = $defaultResolve(specifier, context);
// This is a preflight check to avoid data exfiltration by query params etc.
policy.manifest.mightAllow(ret.url, () =>
new ERR_MANIFEST_DEPENDENCY_MISSING(
Expand Down
19 changes: 19 additions & 0 deletions lib/internal/modules/run_main.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
'use strict';

const {
ArrayPrototypeMap,
ArrayPrototypePushApply,
ObjectCreate,
StringPrototypeEndsWith,
} = primordials;
Expand All @@ -11,6 +13,7 @@ const path = require('path');
const {
handleProcessExit,
} = require('internal/modules/esm/handle_process_exit');
const { validateArray } = require('internal/validators');

function resolveMainPath(main) {
// Note extension resolution for the main entry point can be deprecated in a
Expand Down Expand Up @@ -45,6 +48,22 @@ function shouldUseESMLoader(mainPath) {
if (!mainPath || StringPrototypeEndsWith(mainPath, '.cjs'))
return false;
const pkg = readPackageScope(mainPath);
if (typeof pkg.data?.nodeEntryPointConfig === 'object') {
const { loaders } = pkg.data.nodeEntryPointConfig;
if (loaders != null) {
const { pathToFileURL } = require('internal/url');
const {
defaultResolve,
DEFAULT_CONDITIONS,
} = require('internal/modules/esm/resolve');
validateArray(loaders, 'nodeEntryPointConfig.loaders');
const context = { parentURL: pathToFileURL(pkg.path).href + '/', conditions: DEFAULT_CONDITIONS };
const resolvedLoaders =
ArrayPrototypeMap(loaders, (loaderSpecifier) => defaultResolve(loaderSpecifier, context).url);
ArrayPrototypePushApply(userLoaders, resolvedLoaders);
return true;
}
}
return pkg && pkg.data.type === 'module';
}

Expand Down
24 changes: 24 additions & 0 deletions test/es-module/test-esm-loader-chaining.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -431,3 +431,27 @@ const commonArgs = [
assert.match(stderr, /'load' hook's nextLoad\(\) context/);
assert.strictEqual(status, 1);
}

{
const { status } = spawnSync(
process.execPath,
[
fixtures.path('es-module-loaders', 'package.json-loader-relative-url', 'entryPoint'),
],
{ encoding: 'utf8' },
);

assert.strictEqual(status, 0);
}

{
const { status } = spawnSync(
process.execPath,
[
fixtures.path('es-module-loaders', 'package.json-loader-package-name', 'entryPoint'),
],
{ encoding: 'utf8' },
);

assert.strictEqual(status, 0);
}
4 changes: 2 additions & 2 deletions test/es-module/test-esm-loader-search.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ const {
defaultResolve: resolve
} = require('internal/modules/esm/resolve');

assert.rejects(
resolve('target'),
assert.throws(
() => resolve('target'),
{
code: 'ERR_MODULE_NOT_FOUND',
name: 'Error',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/usr/bin/env node

export {};

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"name": "somePackage",
"nodeEntryPointConfig": {
"loaders": ["extensionless-loader"]
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/usr/bin/env node

export {};
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const extensionlessPath = /\/[^.]+$/;

export async function resolve(specifier, context, next) {
const n = await next(specifier.toString(), context);
if (n.format == null && extensionlessPath.test(n.url)) {
n.format = "module";
}
return n;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"name": "package.json-loader-relative-url",
"nodeEntryPointConfig": {
"loaders": ["./load-extensionless-as-esm.mjs"]
}
}