Skip to content

Commit 05091d4

Browse files
guybedfordMylesBorins
authored andcommitted
esm: import.meta.resolve with nodejs: builtins
Backport-PR-URL: #32610 PR-URL: #31032 Reviewed-By: Jan Krems <[email protected]> Reviewed-By: Myles Borins <[email protected]>
1 parent c0e6e60 commit 05091d4

15 files changed

+145
-37
lines changed

doc/api/cli.md

+8
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,13 @@ Enable experimental Source Map V3 support for stack traces.
156156
Currently, overriding `Error.prepareStackTrace` is ignored when the
157157
`--enable-source-maps` flag is set.
158158

159+
### `--experimental-import-meta-resolve`
160+
<!-- YAML
161+
added: REPLACEME
162+
-->
163+
164+
Enable experimental `import.meta.resolve()` support.
165+
159166
### `--experimental-json-modules`
160167
<!-- YAML
161168
added: v12.9.0
@@ -1085,6 +1092,7 @@ Node.js options that are allowed are:
10851092
<!-- node-options-node start -->
10861093
* `--enable-fips`
10871094
* `--enable-source-maps`
1095+
* `--experimental-import-meta-resolve`
10881096
* `--experimental-json-modules`
10891097
* `--experimental-loader`
10901098
* `--experimental-modules`

doc/api/esm.md

+42-8
Original file line numberDiff line numberDiff line change
@@ -837,6 +837,32 @@ const __filename = fileURLToPath(import.meta.url);
837837
const __dirname = dirname(__filename);
838838
```
839839

840+
### No `require.resolve`
841+
842+
Former use cases relying on `require.resolve` to determine the resolved path
843+
of a module can be supported via `import.meta.resolve`, which is experimental
844+
and supported via the `--experimental-import-meta-resolve` flag:
845+
846+
```js
847+
(async () => {
848+
const dependencyAsset = await import.meta.resolve('component-lib/asset.css');
849+
})();
850+
```
851+
852+
`import.meta.resolve` also accepts a second argument which is the parent module
853+
from which to resolve from:
854+
855+
```js
856+
(async () => {
857+
// Equivalent to import.meta.resolve('./dep')
858+
await import.meta.resolve('./dep', import.meta.url);
859+
})();
860+
```
861+
862+
This function is asynchronous since the ES module resolver in Node.js is
863+
asynchronous. With the introduction of [Top-Level Await][], these use cases
864+
will be easier as they won't require an async function wrapper.
865+
840866
### No `require.extensions`
841867

842868
`require.extensions` is not used by `import`. The expectation is that loader
@@ -1405,13 +1431,14 @@ The resolver has the following properties:
14051431
14061432
The algorithm to load an ES module specifier is given through the
14071433
**ESM_RESOLVE** method below. It returns the resolved URL for a
1408-
module specifier relative to a parentURL, in addition to the unique module
1409-
format for that resolved URL given by the **ESM_FORMAT** routine.
1434+
module specifier relative to a parentURL.
14101435
1411-
The _"module"_ format is returned for an ECMAScript Module, while the
1412-
_"commonjs"_ format is used to indicate loading through the legacy
1413-
CommonJS loader. Additional formats such as _"addon"_ can be extended in future
1414-
updates.
1436+
The algorithm to determine the module format of a resolved URL is
1437+
provided by **ESM_FORMAT**, which returns the unique module
1438+
format for any file. The _"module"_ format is returned for an ECMAScript
1439+
Module, while the _"commonjs"_ format is used to indicate loading through the
1440+
legacy CommonJS loader. Additional formats such as _"addon"_ can be extended in
1441+
future updates.
14151442
14161443
In the following algorithms, all subroutine errors are propagated as errors
14171444
of these top-level routines unless stated otherwise.
@@ -1440,11 +1467,13 @@ _defaultEnv_ is the conditional environment name priority array,
14401467
> 1. If _resolvedURL_ contains any percent encodings of _"/"_ or _"\\"_ (_"%2f"_
14411468
> and _"%5C"_ respectively), then
14421469
> 1. Throw an _Invalid Specifier_ error.
1443-
> 1. If the file at _resolvedURL_ does not exist, then
1470+
> 1. If _resolvedURL_ does not end with a trailing _"/"_ and the file at
1471+
> _resolvedURL_ does not exist, then
14441472
> 1. Throw a _Module Not Found_ error.
14451473
> 1. Set _resolvedURL_ to the real path of _resolvedURL_.
14461474
> 1. Let _format_ be the result of **ESM_FORMAT**(_resolvedURL_).
14471475
> 1. Load _resolvedURL_ as module format, _format_.
1476+
> 1. Return _resolvedURL_.
14481477
14491478
**PACKAGE_RESOLVE**(_packageSpecifier_, _parentURL_)
14501479
@@ -1472,7 +1501,7 @@ _defaultEnv_ is the conditional environment name priority array,
14721501
> 1. If _selfUrl_ isn't empty, return _selfUrl_.
14731502
> 1. If _packageSubpath_ is _undefined_ and _packageName_ is a Node.js builtin
14741503
> module, then
1475-
> 1. Return the string _"node:"_ concatenated with _packageSpecifier_.
1504+
> 1. Return the string _"nodejs:"_ concatenated with _packageSpecifier_.
14761505
> 1. While _parentURL_ is not the file system root,
14771506
> 1. Let _packageURL_ be the URL resolution of _"node_modules/"_
14781507
> concatenated with _packageSpecifier_, relative to _parentURL_.
@@ -1481,6 +1510,8 @@ _defaultEnv_ is the conditional environment name priority array,
14811510
> 1. Set _parentURL_ to the parent URL path of _parentURL_.
14821511
> 1. Continue the next loop iteration.
14831512
> 1. Let _pjson_ be the result of **READ_PACKAGE_JSON**(_packageURL_).
1513+
> 1. If _packageSubpath_ is equal to _"./"_, then
1514+
> 1. Return _packageURL_ + _"/"_.
14841515
> 1. If _packageSubpath_ is _undefined__, then
14851516
> 1. Return the result of **PACKAGE_MAIN_RESOLVE**(_packageURL_,
14861517
> _pjson_).
@@ -1502,6 +1533,8 @@ _defaultEnv_ is the conditional environment name priority array,
15021533
> 1. If _pjson_ does not include an _"exports"_ property, then
15031534
> 1. Return **undefined**.
15041535
> 1. If _pjson.name_ is equal to _packageName_, then
1536+
> 1. If _packageSubpath_ is equal to _"./"_, then
1537+
> 1. Return _packageURL_ + _"/"_.
15051538
> 1. If _packageSubpath_ is _undefined_, then
15061539
> 1. Return the result of **PACKAGE_MAIN_RESOLVE**(_packageURL_, _pjson_).
15071540
> 1. Otherwise,
@@ -1680,3 +1713,4 @@ success!
16801713
[the official standard format]: https://tc39.github.io/ecma262/#sec-modules
16811714
[transpiler loader example]: #esm_transpiler_loader
16821715
[6.1.7 Array Index]: https://tc39.es/ecma262/#integer-index
1716+
[Top-Level Await]: https://github.com./tc39/proposal-top-level-await

doc/node.1

+3
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,9 @@ Requires Node.js to be built with
113113
.It Fl -enable-source-maps
114114
Enable experimental Source Map V3 support for stack traces.
115115
.
116+
.It Fl -experimental-import-meta-resolve
117+
Enable experimental ES modules support for import.meta.resolve().
118+
.
116119
.It Fl -experimental-json-modules
117120
Enable experimental JSON interop support for the ES Module loader.
118121
.

lib/internal/modules/esm/get_format.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
'use strict';
22

3-
const { NativeModule } = require('internal/bootstrap/loaders');
43
const { extname } = require('path');
54
const { getOptionValue } = require('internal/options');
65

@@ -39,7 +38,7 @@ if (experimentalJsonModules)
3938
extensionFormatMap['.json'] = legacyExtensionFormatMap['.json'] = 'json';
4039

4140
function defaultGetFormat(url, context, defaultGetFormat) {
42-
if (NativeModule.canBeRequiredByUsers(url)) {
41+
if (url.startsWith('nodejs:')) {
4342
return { format: 'builtin' };
4443
}
4544
const parsed = new URL(url);
@@ -73,5 +72,6 @@ function defaultGetFormat(url, context, defaultGetFormat) {
7372
}
7473
return { format: format || null };
7574
}
75+
return { format: null };
7676
}
7777
exports.defaultGetFormat = defaultGetFormat;

lib/internal/modules/esm/loader.js

+7-3
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,10 @@ class Loader {
9494
throw new ERR_INVALID_RETURN_PROPERTY_VALUE(
9595
'string', 'loader resolve', 'url', url);
9696
}
97+
return url;
98+
}
9799

100+
async getFormat(url) {
98101
const getFormatResponse = await this._getFormat(
99102
url, {}, defaultGetFormat);
100103
if (typeof getFormatResponse !== 'object') {
@@ -109,7 +112,7 @@ class Loader {
109112
}
110113

111114
if (format === 'builtin') {
112-
return { url: `node:${url}`, format };
115+
return format;
113116
}
114117

115118
if (this._resolve !== defaultResolve) {
@@ -132,7 +135,7 @@ class Loader {
132135
);
133136
}
134137

135-
return { url, format };
138+
return format;
136139
}
137140

138141
async eval(
@@ -185,7 +188,8 @@ class Loader {
185188
}
186189

187190
async getModuleJob(specifier, parentURL) {
188-
const { url, format } = await this.resolve(specifier, parentURL);
191+
const url = await this.resolve(specifier, parentURL);
192+
const format = await this.getFormat(url);
189193
let job = this.moduleMap.get(url);
190194
// CommonJS will set functions for lazy job evaluation.
191195
if (typeof job === 'function')

lib/internal/modules/esm/resolve.js

+7-3
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ const internalFS = require('internal/fs/utils');
88
const { NativeModule } = require('internal/bootstrap/loaders');
99
const { realpathSync } = require('fs');
1010
const { getOptionValue } = require('internal/options');
11+
const { sep } = require('path');
1112

1213
const preserveSymlinks = getOptionValue('--preserve-symlinks');
1314
const preserveSymlinksMain = getOptionValue('--preserve-symlinks-main');
@@ -29,11 +30,13 @@ function defaultResolve(specifier, { parentURL } = {}, defaultResolve) {
2930
};
3031
}
3132
} catch {}
33+
if (parsed && parsed.protocol === 'nodejs:')
34+
return { url: specifier };
3235
if (parsed && parsed.protocol !== 'file:' && parsed.protocol !== 'data:')
3336
throw new ERR_UNSUPPORTED_ESM_URL_SCHEME();
3437
if (NativeModule.canBeRequiredByUsers(specifier)) {
3538
return {
36-
url: specifier
39+
url: 'nodejs:' + specifier
3740
};
3841
}
3942
if (parentURL && parentURL.startsWith('data:')) {
@@ -58,11 +61,12 @@ function defaultResolve(specifier, { parentURL } = {}, defaultResolve) {
5861
let url = moduleWrapResolve(specifier, parentURL);
5962

6063
if (isMain ? !preserveSymlinksMain : !preserveSymlinks) {
61-
const real = realpathSync(fileURLToPath(url), {
64+
const urlPath = fileURLToPath(url);
65+
const real = realpathSync(urlPath, {
6266
[internalFS.realpathCacheKey]: realpathCache
6367
});
6468
const old = url;
65-
url = pathToFileURL(real);
69+
url = pathToFileURL(real + (urlPath.endsWith(sep) ? '/' : ''));
6670
url.search = old.search;
6771
url.hash = old.hash;
6872
}

lib/internal/modules/esm/translators.js

+24-9
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@ const { ERR_UNKNOWN_BUILTIN_MODULE } = require('internal/errors').codes;
2828
const { maybeCacheSourceMap } = require('internal/source_map/source_map_cache');
2929
const moduleWrap = internalBinding('module_wrap');
3030
const { ModuleWrap } = moduleWrap;
31+
const { getOptionValue } = require('internal/options');
32+
const experimentalImportMetaResolve =
33+
getOptionValue('--experimental-import-meta-resolve');
3134

3235
const debug = debuglog('esm');
3336

@@ -42,16 +45,28 @@ function errPath(url) {
4245
return url;
4346
}
4447

45-
function initializeImportMeta(meta, { url }) {
46-
meta.url = url;
47-
}
48-
4948
let esmLoader;
5049
async function importModuleDynamically(specifier, { url }) {
5150
if (!esmLoader) {
52-
esmLoader = require('internal/process/esm_loader');
51+
esmLoader = require('internal/process/esm_loader').ESMLoader;
5352
}
54-
return esmLoader.ESMLoader.import(specifier, url);
53+
return esmLoader.import(specifier, url);
54+
}
55+
56+
function createImportMetaResolve(defaultParentUrl) {
57+
return async function resolve(specifier, parentUrl = defaultParentUrl) {
58+
if (!esmLoader) {
59+
esmLoader = require('internal/process/esm_loader').ESMLoader;
60+
}
61+
return esmLoader.resolve(specifier, parentUrl);
62+
};
63+
}
64+
65+
function initializeImportMeta(meta, { url }) {
66+
// Alphabetical
67+
if (experimentalImportMetaResolve)
68+
meta.resolve = createImportMetaResolve(url);
69+
meta.url = url;
5570
}
5671

5772
// Strategy for loading a standard JavaScript module
@@ -104,10 +119,10 @@ translators.set('commonjs', function commonjsStrategy(url, isMain) {
104119
// through normal resolution
105120
translators.set('builtin', async function builtinStrategy(url) {
106121
debug(`Translating BuiltinModule ${url}`);
107-
// Slice 'node:' scheme
108-
const id = url.slice(5);
122+
// Slice 'nodejs:' scheme
123+
const id = url.slice(7);
109124
const module = loadNativeModule(id, url, true);
110-
if (!module) {
125+
if (!url.startsWith('nodejs:') || !module) {
111126
throw new ERR_UNKNOWN_BUILTIN_MODULE(id);
112127
}
113128
debug(`Loading BuiltinModule ${url}`);

src/module_wrap.cc

+11-4
Original file line numberDiff line numberDiff line change
@@ -812,6 +812,10 @@ Maybe<URL> FinalizeResolution(Environment* env,
812812
return Nothing<URL>();
813813
}
814814

815+
if (resolved.path().back() == '/') {
816+
return Just(resolved);
817+
}
818+
815819
const std::string& path = resolved.ToFilePath();
816820
if (CheckDescriptorAtPath(path) != FILE) {
817821
std::string msg = "Cannot find module " +
@@ -1197,7 +1201,9 @@ Maybe<URL> ResolveSelf(Environment* env,
11971201
}
11981202
if (!found_pjson || pcfg->name != pkg_name) return Nothing<URL>();
11991203
if (pcfg->exports.IsEmpty()) return Nothing<URL>();
1200-
if (!pkg_subpath.length()) {
1204+
if (pkg_subpath == "./") {
1205+
return Just(URL("./", pjson_url));
1206+
} else if (!pkg_subpath.length()) {
12011207
return PackageMainResolve(env, pjson_url, *pcfg, base);
12021208
} else {
12031209
return PackageExportsResolve(env, pjson_url, pkg_subpath, *pcfg, base);
@@ -1241,8 +1247,7 @@ Maybe<URL> PackageResolve(Environment* env,
12411247
return Nothing<URL>();
12421248
}
12431249
std::string pkg_subpath;
1244-
if ((sep_index == std::string::npos ||
1245-
sep_index == specifier.length() - 1)) {
1250+
if (sep_index == std::string::npos) {
12461251
pkg_subpath = "";
12471252
} else {
12481253
pkg_subpath = "." + specifier.substr(sep_index);
@@ -1273,7 +1278,9 @@ Maybe<URL> PackageResolve(Environment* env,
12731278
Maybe<const PackageConfig*> pcfg = GetPackageConfig(env, pjson_path, base);
12741279
// Invalid package configuration error.
12751280
if (pcfg.IsNothing()) return Nothing<URL>();
1276-
if (!pkg_subpath.length()) {
1281+
if (pkg_subpath == "./") {
1282+
return Just(URL("./", pjson_url));
1283+
} else if (!pkg_subpath.length()) {
12771284
return PackageMainResolve(env, pjson_url, *pcfg.FromJust(), base);
12781285
} else {
12791286
if (!pcfg.FromJust()->exports.IsEmpty()) {

src/node_options.cc

+8
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,10 @@ void PerIsolateOptions::CheckOptions(std::vector<std::string>* errors) {
116116
}
117117

118118
void EnvironmentOptions::CheckOptions(std::vector<std::string>* errors) {
119+
if (experimental_import_meta_resolve && !experimental_modules) {
120+
errors->push_back("--experimental-meta-resolve requires "
121+
"--experimental-modules be enabled");
122+
}
119123
if (!userland_loader.empty() && !experimental_modules) {
120124
errors->push_back("--experimental-loader requires "
121125
"--experimental-modules be enabled");
@@ -360,6 +364,10 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() {
360364
"experimental ES Module support for webassembly modules",
361365
&EnvironmentOptions::experimental_wasm_modules,
362366
kAllowedInEnvironment);
367+
AddOption("--experimental-import-meta-resolve",
368+
"experimental ES Module import.meta.resolve() support",
369+
&EnvironmentOptions::experimental_import_meta_resolve,
370+
kAllowedInEnvironment);
363371
AddOption("--experimental-policy",
364372
"use the specified file as a "
365373
"security policy",

src/node_options.h

+1
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ class EnvironmentOptions : public Options {
106106
std::string experimental_specifier_resolution;
107107
std::string es_module_specifier_resolution;
108108
bool experimental_wasm_modules = false;
109+
bool experimental_import_meta_resolve = false;
109110
std::string module_type;
110111
std::string experimental_policy;
111112
std::string experimental_policy_integrity;

test/es-module/test-esm-dynamic-import.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -54,11 +54,12 @@ function expectFsNamespace(result) {
5454
expectFsNamespace(import('fs'));
5555
expectFsNamespace(eval('import("fs")'));
5656
expectFsNamespace(eval('import("fs")'));
57+
expectFsNamespace(import('nodejs:fs'));
5758

59+
expectModuleError(import('nodejs:unknown'),
60+
'ERR_UNKNOWN_BUILTIN_MODULE');
5861
expectModuleError(import('./not-an-existing-module.mjs'),
5962
'ERR_MODULE_NOT_FOUND');
60-
expectModuleError(import('node:fs'),
61-
'ERR_UNSUPPORTED_ESM_URL_SCHEME');
6263
expectModuleError(import('http://example.com/foo.js'),
6364
'ERR_UNSUPPORTED_ESM_URL_SCHEME');
6465
})();

0 commit comments

Comments
 (0)