mirror of
https://github.com/nodejs/node.git
synced 2026-11-25 23:01:06 -05:00
esm: consolidate ESM loader hooks
doc: update ESM hook examples esm: fix unsafe primordial doc: fix ESM example linting esm: allow source of type ArrayBuffer doc: update ESM hook changelog to include resolve format esm: allow all ArrayBuffers and TypedArrays for load hook source doc: tidy code & API docs doc: convert ESM source table header from Title Case to Sentence case doc: add detailed explanation for getPackageType esm: add caveat that ESMLoader::import() must NOT be renamed esm: tidy code declaration of getFormat protocolHandlers doc: correct ESM doc link (bad conflict resolution) doc: update ESM hook limitation for CJS esm: tweak preload description doc: update ESM getPackageType() example explanation PR-URL: https://github.com/nodejs/node/pull/37468 Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com> Reviewed-By: Guy Bedford <guybedford@gmail.com> Reviewed-By: Bradley Farias <bradley.meck@gmail.com> Reviewed-By: Geoffrey Booth <webmaster@geoffreybooth.com>
This commit is contained in:
1 parent
1ef2cf8413
commit
3743406b0a
46 files changed
+977
-551
No files matched your search
+164
-150
@@ -7,6 +7,14 @@
|
||||
<!-- YAML
|
||||
added: v8.5.0
|
||||
changes:
|
||||
- version:
|
||||
- REPLACEME
|
||||
pr-url: https://github.com/nodejs/node/pull/37468
|
||||
description:
|
||||
Consolidate loader hooks, removed `getFormat`, `getSource`,
|
||||
`transformSource`, and `getGlobalPreloadCode` hooks
|
||||
added `load` and `globalPreload` hooks
|
||||
allowed returning `format` from either `resolve` or `load` hooks.
|
||||
- version:
|
||||
- v15.3.0
|
||||
- v12.22.0
|
||||
@@ -604,20 +612,29 @@ CommonJS modules loaded.
|
||||
* `specifier` {string}
|
||||
* `context` {Object}
|
||||
* `conditions` {string[]}
|
||||
* `parentURL` {string}
|
||||
* `defaultResolve` {Function}
|
||||
* `parentURL` {string|undefined}
|
||||
* `defaultResolve` {Function} The Node.js default resolver.
|
||||
* Returns: {Object}
|
||||
* `url` {string}
|
||||
* `format` {string|null|undefined}
|
||||
`'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'`
|
||||
* `url` {string} The absolute url to the import target (such as `file://…`)
|
||||
|
||||
The `resolve` hook returns the resolved file URL for a given module specifier
|
||||
and parent URL. The module specifier is the string in an `import` statement or
|
||||
and parent URL, and optionally its format (such as `'module'`) as a hint to the
|
||||
`load` hook. If a format is specified, the `load` hook is ultimately responsible
|
||||
for providing the final `format` value (and it is free to ignore the hint
|
||||
provided by `resolve`); if `resolve` provides a `format`, a custom `load`
|
||||
hook is required even if only to pass the value to the Node.js default `load`
|
||||
hook.
|
||||
|
||||
The module specifier is the string in an `import` statement or
|
||||
`import()` expression, and the parent URL is the URL of the module that imported
|
||||
this one, or `undefined` if this is the main entry point for the application.
|
||||
|
||||
The `conditions` property on the `context` is an array of conditions for
|
||||
[Conditional exports][] that apply to this resolution request. They can be used
|
||||
for looking up conditional mappings elsewhere or to modify the list when calling
|
||||
the default resolution logic.
|
||||
The `conditions` property in `context` is an array of conditions for
|
||||
[package exports conditions][Conditional Exports] that apply to this resolution
|
||||
request. They can be used for looking up conditional mappings elsewhere or to
|
||||
modify the list when calling the default resolution logic.
|
||||
|
||||
The current [package exports conditions][Conditional Exports] are always in
|
||||
the `context.conditions` array passed into the hook. To guarantee _default
|
||||
@@ -659,23 +676,29 @@ export async function resolve(specifier, context, defaultResolve) {
|
||||
}
|
||||
```
|
||||
|
||||
#### `getFormat(url, context, defaultGetFormat)`
|
||||
#### `load(url, context, defaultLoad)`
|
||||
|
||||
> Note: The loaders API is being redesigned. This hook may disappear or its
|
||||
> signature may change. Do not rely on the API described below.
|
||||
|
||||
> Note: In a previous version of this API, this was split across 3 separate, now
|
||||
> deprecated, hooks (`getFormat`, `getSource`, and `transformSource`).
|
||||
|
||||
* `url` {string}
|
||||
* `context` {Object}
|
||||
* `defaultGetFormat` {Function}
|
||||
* `format` {string|null|undefined} The format optionally supplied by the
|
||||
`resolve` hook.
|
||||
* `defaultLoad` {Function}
|
||||
* Returns: {Object}
|
||||
* `format` {string}
|
||||
* `source` {string|ArrayBuffer|TypedArray}
|
||||
|
||||
The `getFormat` hook provides a way to define a custom method of determining how
|
||||
a URL should be interpreted. The `format` returned also affects what the
|
||||
acceptable forms of source values are for a module when parsing. This can be one
|
||||
of the following:
|
||||
The `load` hook provides a way to define a custom method of determining how
|
||||
a URL should be interpreted, retrieved, and parsed.
|
||||
|
||||
| `format` | Description | Acceptable Types For `source` Returned by `getSource` or `transformSource` |
|
||||
The final value of `format` must be one of the following:
|
||||
|
||||
| `format` | Description | Acceptable types For `source` returned by `resolve` or `load` |
|
||||
| ------------ | ------------------------------ | -------------------------------------------------------------------------- |
|
||||
| `'builtin'` | Load a Node.js builtin module | Not applicable |
|
||||
| `'commonjs'` | Load a Node.js CommonJS module | Not applicable |
|
||||
@@ -683,126 +706,78 @@ of the following:
|
||||
| `'module'` | Load an ES module | { [`string`][], [`ArrayBuffer`][], [`TypedArray`][] } |
|
||||
| `'wasm'` | Load a WebAssembly module | { [`ArrayBuffer`][], [`TypedArray`][] } |
|
||||
|
||||
Note: These types all correspond to classes defined in ECMAScript.
|
||||
The value of `source` is ignored for type `'builtin'` because currently it is
|
||||
not possible to replace the value of a Node.js builtin (core) module. The value
|
||||
of `source` is ignored for type `'commonjs'` because the CommonJS module loader
|
||||
does not provide a mechanism for the ES module loader to override the
|
||||
[CommonJS module return value](#commonjs-namespaces). This limitation might be
|
||||
overcome in the future.
|
||||
|
||||
> **Caveat**: The ESM `load` hook and namespaced exports from CommonJS modules
|
||||
> are incompatible. Attempting to use them together will result in an empty
|
||||
> object from the import. This may be addressed in the future.
|
||||
|
||||
> Note: These types all correspond to classes defined in ECMAScript.
|
||||
|
||||
* The specific [`ArrayBuffer`][] object is a [`SharedArrayBuffer`][].
|
||||
* The specific [`TypedArray`][] object is a [`Uint8Array`][].
|
||||
|
||||
Note: If the source value of a text-based format (i.e., `'json'`, `'module'`) is
|
||||
not a string, it is converted to a string using [`util.TextDecoder`][].
|
||||
If the source value of a text-based format (i.e., `'json'`, `'module'`)
|
||||
is not a string, it is converted to a string using [`util.TextDecoder`][].
|
||||
|
||||
The `load` hook provides a way to define a custom method for retrieving the
|
||||
source code of an ES module specifier. This would allow a loader to potentially
|
||||
avoid reading files from disk. It could also be used to map an unrecognized
|
||||
format to a supported one, for example `yaml` to `module`.
|
||||
|
||||
```js
|
||||
/**
|
||||
* @param {string} url
|
||||
* @param {Object} context (currently empty)
|
||||
* @param {Function} defaultGetFormat
|
||||
* @returns {Promise<{ format: string }>}
|
||||
* @param {{
|
||||
format: string,
|
||||
}} context If resolve settled with a `format`, that value is included here.
|
||||
* @param {Function} defaultLoad
|
||||
* @returns {Promise<{
|
||||
format: !string,
|
||||
source: !(string | ArrayBuffer | SharedArrayBuffer | Uint8Array),
|
||||
}>}
|
||||
*/
|
||||
export async function getFormat(url, context, defaultGetFormat) {
|
||||
if (Math.random() > 0.5) { // Some condition.
|
||||
// For some or all URLs, do some custom logic for determining format.
|
||||
// Always return an object of the form {format: <string>}, where the
|
||||
// format is one of the strings in the preceding table.
|
||||
return {
|
||||
format: 'module',
|
||||
};
|
||||
}
|
||||
// Defer to Node.js for all other URLs.
|
||||
return defaultGetFormat(url, context, defaultGetFormat);
|
||||
}
|
||||
```
|
||||
|
||||
#### `getSource(url, context, defaultGetSource)`
|
||||
|
||||
> Note: The loaders API is being redesigned. This hook may disappear or its
|
||||
> signature may change. Do not rely on the API described below.
|
||||
|
||||
* `url` {string}
|
||||
* `context` {Object}
|
||||
* `format` {string}
|
||||
* `defaultGetSource` {Function}
|
||||
* Returns: {Object}
|
||||
* `source` {string|SharedArrayBuffer|Uint8Array}
|
||||
|
||||
The `getSource` hook provides a way to define a custom method for retrieving
|
||||
the source code of an ES module specifier. This would allow a loader to
|
||||
potentially avoid reading files from disk.
|
||||
|
||||
```js
|
||||
/**
|
||||
* @param {string} url
|
||||
* @param {{ format: string }} context
|
||||
* @param {Function} defaultGetSource
|
||||
* @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) }>}
|
||||
*/
|
||||
export async function getSource(url, context, defaultGetSource) {
|
||||
export async function load(url, context, defaultLoad) {
|
||||
const { format } = context;
|
||||
if (Math.random() > 0.5) { // Some condition.
|
||||
// For some or all URLs, do some custom logic for retrieving the source.
|
||||
// Always return an object of the form {source: <string|buffer>}.
|
||||
/*
|
||||
For some or all URLs, do some custom logic for retrieving the source.
|
||||
Always return an object of the form {
|
||||
format: <string>,
|
||||
source: <string|buffer>,
|
||||
}.
|
||||
*/
|
||||
return {
|
||||
format,
|
||||
source: '...',
|
||||
};
|
||||
}
|
||||
// Defer to Node.js for all other URLs.
|
||||
return defaultGetSource(url, context, defaultGetSource);
|
||||
return defaultLoad(url, context, defaultLoad);
|
||||
}
|
||||
```
|
||||
|
||||
#### `transformSource(source, context, defaultTransformSource)`
|
||||
In a more advanced scenario, this can also be used to transform an unsupported
|
||||
source to a supported one (see [Examples](#examples) below).
|
||||
|
||||
#### `globalPreload()`
|
||||
|
||||
> Note: The loaders API is being redesigned. This hook may disappear or its
|
||||
> signature may change. Do not rely on the API described below.
|
||||
|
||||
* `source` {string|SharedArrayBuffer|Uint8Array}
|
||||
* `context` {Object}
|
||||
* `format` {string}
|
||||
* `url` {string}
|
||||
* Returns: {Object}
|
||||
* `source` {string|SharedArrayBuffer|Uint8Array}
|
||||
|
||||
The `transformSource` hook provides a way to modify the source code of a loaded
|
||||
ES module file after the source string has been loaded but before Node.js has
|
||||
done anything with it.
|
||||
|
||||
If this hook is used to convert unknown-to-Node.js file types into executable
|
||||
JavaScript, a resolve hook is also necessary in order to register any
|
||||
unknown-to-Node.js file extensions. See the [transpiler loader example][] below.
|
||||
|
||||
```js
|
||||
/**
|
||||
* @param {!(string | SharedArrayBuffer | Uint8Array)} source
|
||||
* @param {{
|
||||
* format: string,
|
||||
* url: string,
|
||||
* }} context
|
||||
* @param {Function} defaultTransformSource
|
||||
* @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) }>}
|
||||
*/
|
||||
export async function transformSource(source, context, defaultTransformSource) {
|
||||
const { url, format } = context;
|
||||
if (Math.random() > 0.5) { // Some condition.
|
||||
// For some or all URLs, do some custom logic for modifying the source.
|
||||
// Always return an object of the form {source: <string|buffer>}.
|
||||
return {
|
||||
source: '...',
|
||||
};
|
||||
}
|
||||
// Defer to Node.js for all other sources.
|
||||
return defaultTransformSource(source, context, defaultTransformSource);
|
||||
}
|
||||
```
|
||||
|
||||
#### `getGlobalPreloadCode()`
|
||||
|
||||
> Note: The loaders API is being redesigned. This hook may disappear or its
|
||||
> signature may change. Do not rely on the API described below.
|
||||
> Note: In a previous version of this API, this hook was named
|
||||
> `getGlobalPreloadCode`.
|
||||
|
||||
* Returns: {string}
|
||||
|
||||
Sometimes it might be necessary to run some code inside of the same global scope
|
||||
that the application runs in. This hook allows the return of a string that is
|
||||
run as sloppy-mode script on startup.
|
||||
Sometimes it might be necessary to run some code inside of the same global
|
||||
scope that the application runs in. This hook allows the return of a string
|
||||
that is run as a sloppy-mode script on startup.
|
||||
|
||||
Similar to how CommonJS wrappers work, the code runs in an implicit function
|
||||
scope. The only argument is a `require`-like function that can be used to load
|
||||
@@ -815,7 +790,7 @@ its own `require` using `module.createRequire()`.
|
||||
/**
|
||||
* @returns {string} Code to run before application startup
|
||||
*/
|
||||
export function getGlobalPreloadCode() {
|
||||
export function globalPreload() {
|
||||
return `\
|
||||
globalThis.someInjectedProperty = 42;
|
||||
console.log('I just set some globals!');
|
||||
@@ -867,19 +842,7 @@ export function resolve(specifier, context, defaultResolve) {
|
||||
return defaultResolve(specifier, context, defaultResolve);
|
||||
}
|
||||
|
||||
export function getFormat(url, context, defaultGetFormat) {
|
||||
// This loader assumes all network-provided JavaScript is ES module code.
|
||||
if (url.startsWith('https://')) {
|
||||
return {
|
||||
format: 'module'
|
||||
};
|
||||
}
|
||||
|
||||
// Let Node.js handle all other URLs.
|
||||
return defaultGetFormat(url, context, defaultGetFormat);
|
||||
}
|
||||
|
||||
export function getSource(url, context, defaultGetSource) {
|
||||
export function load(url, context, defaultLoad) {
|
||||
// For JavaScript to be loaded over the network, we need to fetch and
|
||||
// return it.
|
||||
if (url.startsWith('https://')) {
|
||||
@@ -887,13 +850,18 @@ export function getSource(url, context, defaultGetSource) {
|
||||
get(url, (res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk) => data += chunk);
|
||||
res.on('end', () => resolve({ source: data }));
|
||||
res.on('end', () => resolve({
|
||||
// This example assumes all network-provided JavaScript is ES module
|
||||
// code.
|
||||
format: 'module',
|
||||
source: data,
|
||||
}));
|
||||
}).on('error', (err) => reject(err));
|
||||
});
|
||||
}
|
||||
|
||||
// Let Node.js handle all other URLs.
|
||||
return defaultGetSource(url, context, defaultGetSource);
|
||||
return defaultLoad(url, context, defaultLoad);
|
||||
}
|
||||
```
|
||||
|
||||
@@ -912,9 +880,9 @@ prints the current version of CoffeeScript per the module at the URL in
|
||||
#### Transpiler loader
|
||||
|
||||
Sources that are in formats Node.js doesn’t understand can be converted into
|
||||
JavaScript using the [`transformSource` hook][]. Before that hook gets called,
|
||||
however, other hooks need to tell Node.js not to throw an error on unknown file
|
||||
types; and to tell Node.js how to load this new file type.
|
||||
JavaScript using the [`load` hook][load hook]. Before that hook gets called,
|
||||
however, a [`resolve` hook][resolve hook] hook needs to tell Node.js not to
|
||||
throw an error on unknown file types.
|
||||
|
||||
This is less performant than transpiling source files before running
|
||||
Node.js; a transpiler loader should only be used for development and testing
|
||||
@@ -922,16 +890,21 @@ purposes.
|
||||
|
||||
```js
|
||||
// coffeescript-loader.mjs
|
||||
import { URL, pathToFileURL } from 'url';
|
||||
import CoffeeScript from 'coffeescript';
|
||||
import { readFile } from 'fs/promises';
|
||||
import { readFileSync } from 'fs';
|
||||
import { createRequire } from 'module';
|
||||
import { dirname, extname, resolve as resolvePath } from 'path';
|
||||
import { cwd } from 'process';
|
||||
import { fileURLToPath, pathToFileURL } from 'url';
|
||||
|
||||
const baseURL = pathToFileURL(`${cwd()}/`).href;
|
||||
import CoffeeScript from 'coffeescript';
|
||||
|
||||
const baseURL = pathToFileURL(`${cwd}/`).href;
|
||||
|
||||
// CoffeeScript files end in .coffee, .litcoffee or .coffee.md.
|
||||
const extensionsRegex = /\.coffee$|\.litcoffee$|\.coffee\.md$/;
|
||||
|
||||
export function resolve(specifier, context, defaultResolve) {
|
||||
export async function resolve(specifier, context, defaultResolve) {
|
||||
const { parentURL = baseURL } = context;
|
||||
|
||||
// Node.js normally errors on unknown file extensions, so return a URL for
|
||||
@@ -946,31 +919,72 @@ export function resolve(specifier, context, defaultResolve) {
|
||||
return defaultResolve(specifier, context, defaultResolve);
|
||||
}
|
||||
|
||||
export function getFormat(url, context, defaultGetFormat) {
|
||||
export async function load(url, context, defaultLoad) {
|
||||
// Now that we patched resolve to let CoffeeScript URLs through, we need to
|
||||
// tell Node.js what format such URLs should be interpreted as. For the
|
||||
// purposes of this loader, all CoffeeScript URLs are ES modules.
|
||||
// tell Node.js what format such URLs should be interpreted as. Because
|
||||
// CoffeeScript transpiles into JavaScript, it should be one of the two
|
||||
// JavaScript formats: 'commonjs' or 'module'.
|
||||
if (extensionsRegex.test(url)) {
|
||||
// CoffeeScript files can be either CommonJS or ES modules, so we want any
|
||||
// CoffeeScript file to be treated by Node.js the same as a .js file at the
|
||||
// same location. To determine how Node.js would interpret an arbitrary .js
|
||||
// file, search up the file system for the nearest parent package.json file
|
||||
// and read its "type" field.
|
||||
const format = await getPackageType(url);
|
||||
// When a hook returns a format of 'commonjs', `source` is be ignored.
|
||||
// To handle CommonJS files, a handler needs to be registered with
|
||||
// `require.extensions` in order to process the files with the CommonJS
|
||||
// loader. Avoiding the need for a separate CommonJS handler is a future
|
||||
// enhancement planned for ES module loaders.
|
||||
if (format === 'commonjs') {
|
||||
return { format };
|
||||
}
|
||||
|
||||
const { source: rawSource } = await defaultLoad(url, { format });
|
||||
// This hook converts CoffeeScript source code into JavaScript source code
|
||||
// for all imported CoffeeScript files.
|
||||
const transformedSource = CoffeeScript.compile(rawSource.toString(), {
|
||||
bare: true,
|
||||
filename: url,
|
||||
});
|
||||
|
||||
return {
|
||||
format: 'module'
|
||||
format,
|
||||
source: transformedSource,
|
||||
};
|
||||
}
|
||||
|
||||
// Let Node.js handle all other URLs.
|
||||
return defaultGetFormat(url, context, defaultGetFormat);
|
||||
return defaultLoad(url, context, defaultLoad);
|
||||
}
|
||||
|
||||
export function transformSource(source, context, defaultTransformSource) {
|
||||
const { url, format } = context;
|
||||
|
||||
if (extensionsRegex.test(url)) {
|
||||
return {
|
||||
source: CoffeeScript.compile(source, { bare: true })
|
||||
};
|
||||
}
|
||||
|
||||
// Let Node.js handle all other sources.
|
||||
return defaultTransformSource(source, context, defaultTransformSource);
|
||||
async function getPackageType(url) {
|
||||
// `url` is only a file path during the first iteration when passed the
|
||||
// resolved url from the load() hook
|
||||
// an actual file path from load() will contain a file extension as it's
|
||||
// required by the spec
|
||||
// this simple truthy check for whether `url` contains a file extension will
|
||||
// work for most projects but does not cover some edge-cases (such as
|
||||
// extension-less files or a url ending in a trailing space)
|
||||
const isFilePath = !!extname(url);
|
||||
// If it is a file path, get the directory it's in
|
||||
const dir = isFilePath ?
|
||||
dirname(fileURLToPath(url)) :
|
||||
url;
|
||||
// Compose a file path to a package.json in the same directory,
|
||||
// which may or may not exist
|
||||
const packagePath = resolvePath(dir, 'package.json');
|
||||
// Try to read the possibly non-existant package.json
|
||||
const type = await readFile(packagePath, { encoding: 'utf8' })
|
||||
.then((filestring) => JSON.parse(filestring).type)
|
||||
.catch((err) => {
|
||||
if (err?.code !== 'ENOENT') console.error(err);
|
||||
});
|
||||
// Ff package.json existed and contained a `type` field with a value, voila
|
||||
if (type) return type;
|
||||
// Otherwise, (if not at the root) continue checking the next directory up
|
||||
// If at the root, stop and return false
|
||||
return dir.length > 1 && getPackageType(resolvePath(dir, '..'));
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1377,11 +1391,11 @@ success!
|
||||
[`package.json`]: packages.md#nodejs-packagejson-field-definitions
|
||||
[`process.dlopen`]: process.md#processdlopenmodule-filename-flags
|
||||
[`string`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
|
||||
[`transformSource` hook]: #transformsourcesource-context-defaulttransformsource
|
||||
[`util.TextDecoder`]: util.md#class-utiltextdecoder
|
||||
[cjs-module-lexer]: https://github.com/guybedford/cjs-module-lexer/tree/1.2.2
|
||||
[custom https loader]: #https-loader
|
||||
[load hook]: #loadurl-context-defaultload
|
||||
[resolve hook]: #resolvespecifier-context-defaultresolve
|
||||
[special scheme]: https://url.spec.whatwg.org/#special-scheme
|
||||
[the official standard format]: https://tc39.github.io/ecma262/#sec-modules
|
||||
[transpiler loader example]: #transpiler-loader
|
||||
[url.pathToFileURL]: url.md#urlpathtofileurlpath
|
||||
@@ -981,14 +981,14 @@ Module.prototype.load = function(filename) {
|
||||
Module._extensions[extension](this, filename);
|
||||
this.loaded = true;
|
||||
|
||||
const ESMLoader = asyncESM.ESMLoader;
|
||||
const esmLoader = asyncESM.esmLoader;
|
||||
// Create module entry at load time to snapshot exports correctly
|
||||
const exports = this.exports;
|
||||
// Preemptively cache
|
||||
if ((module?.module === undefined ||
|
||||
module.module.getStatus() < kEvaluated) &&
|
||||
!ESMLoader.cjsCache.has(this))
|
||||
ESMLoader.cjsCache.set(this, exports);
|
||||
!esmLoader.cjsCache.has(this))
|
||||
esmLoader.cjsCache.set(this, exports);
|
||||
};
|
||||
|
||||
|
||||
@@ -1022,7 +1022,7 @@ function wrapSafe(filename, content, cjsModuleInstance) {
|
||||
lineOffset: 0,
|
||||
displayErrors: true,
|
||||
importModuleDynamically: async (specifier) => {
|
||||
const loader = asyncESM.ESMLoader;
|
||||
const loader = asyncESM.esmLoader;
|
||||
return loader.import(specifier, normalizeReferrerURL(filename));
|
||||
},
|
||||
});
|
||||
@@ -1037,7 +1037,7 @@ function wrapSafe(filename, content, cjsModuleInstance) {
|
||||
], {
|
||||
filename,
|
||||
importModuleDynamically(specifier) {
|
||||
const loader = asyncESM.ESMLoader;
|
||||
const loader = asyncESM.esmLoader;
|
||||
return loader.import(specifier, normalizeReferrerURL(filename));
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
'use strict';
|
||||
const {
|
||||
ObjectAssign,
|
||||
ObjectCreate,
|
||||
ObjectPrototypeHasOwnProperty,
|
||||
RegExpPrototypeExec,
|
||||
StringPrototypeStartsWith,
|
||||
} = primordials;
|
||||
const { extname } = require('path');
|
||||
const { getOptionValue } = require('internal/options');
|
||||
@@ -36,26 +38,25 @@ if (experimentalWasmModules)
|
||||
if (experimentalJsonModules)
|
||||
extensionFormatMap['.json'] = legacyExtensionFormatMap['.json'] = 'json';
|
||||
|
||||
function defaultGetFormat(url, context, defaultGetFormatUnused) {
|
||||
if (StringPrototypeStartsWith(url, 'node:')) {
|
||||
return { format: 'builtin' };
|
||||
}
|
||||
const parsed = new URL(url);
|
||||
if (parsed.protocol === 'data:') {
|
||||
const protocolHandlers = ObjectAssign(ObjectCreate(null), {
|
||||
'data:'(parsed) {
|
||||
const { 1: mime } = RegExpPrototypeExec(
|
||||
/^([^/]+\/[^;,]+)(?:[^,]*?)(;base64)?,/,
|
||||
parsed.pathname,
|
||||
) || [ , null ];
|
||||
) || [, null];
|
||||
const format = ({
|
||||
'__proto__': null,
|
||||
'text/javascript': 'module',
|
||||
'application/json': experimentalJsonModules ? 'json' : null,
|
||||
'application/wasm': experimentalWasmModules ? 'wasm' : null
|
||||
})[mime] || null;
|
||||
return { format };
|
||||
} else if (parsed.protocol === 'file:') {
|
||||
|
||||
return format;
|
||||
},
|
||||
'file:'(parsed, url) {
|
||||
const ext = extname(parsed.pathname);
|
||||
let format;
|
||||
|
||||
if (ext === '.js') {
|
||||
format = getPackageType(parsed.href) === 'module' ? 'module' : 'commonjs';
|
||||
} else {
|
||||
@@ -71,9 +72,18 @@ function defaultGetFormat(url, context, defaultGetFormatUnused) {
|
||||
throw new ERR_UNKNOWN_FILE_EXTENSION(ext, fileURLToPath(url));
|
||||
}
|
||||
}
|
||||
return { format: format || null };
|
||||
}
|
||||
return { format: null };
|
||||
|
||||
return format || null;
|
||||
},
|
||||
'node:'() { return 'builtin'; },
|
||||
});
|
||||
|
||||
function defaultGetFormat(url, context) {
|
||||
const parsed = new URL(url);
|
||||
|
||||
return ObjectPrototypeHasOwnProperty(protocolHandlers, parsed.protocol) ?
|
||||
protocolHandlers[parsed.protocol](parsed, url) :
|
||||
null;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
|
||||
@@ -40,6 +40,6 @@ async function defaultGetSource(url, { format } = {}, defaultGetSource) {
|
||||
if (policy?.manifest) {
|
||||
policy.manifest.assertIntegrity(parsed, source);
|
||||
}
|
||||
return { source };
|
||||
return source;
|
||||
}
|
||||
exports.defaultGetSource = defaultGetSource;
|
||||
@@ -0,0 +1,32 @@
|
||||
'use strict';
|
||||
|
||||
const { defaultGetFormat } = require('internal/modules/esm/get_format');
|
||||
const { defaultGetSource } = require('internal/modules/esm/get_source');
|
||||
const { translators } = require('internal/modules/esm/translators');
|
||||
|
||||
async function defaultLoad(url, context) {
|
||||
let {
|
||||
format,
|
||||
source,
|
||||
} = context;
|
||||
|
||||
if (!translators.has(format)) format = defaultGetFormat(url);
|
||||
|
||||
if (
|
||||
format === 'builtin' ||
|
||||
format === 'commonjs'
|
||||
) {
|
||||
source = null;
|
||||
} else if (source == null) {
|
||||
source = await defaultGetSource(url, { format });
|
||||
}
|
||||
|
||||
return {
|
||||
format,
|
||||
source,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
defaultLoad,
|
||||
};
|
||||
+383
-180
@@ -4,11 +4,18 @@
|
||||
require('internal/modules/cjs/loader');
|
||||
|
||||
const {
|
||||
Array,
|
||||
ArrayIsArray,
|
||||
ArrayPrototypeJoin,
|
||||
ArrayPrototypePush,
|
||||
FunctionPrototypeBind,
|
||||
FunctionPrototypeCall,
|
||||
ObjectCreate,
|
||||
ObjectSetPrototypeOf,
|
||||
PromiseAll,
|
||||
RegExpPrototypeExec,
|
||||
SafeArrayIterator,
|
||||
SafeWeakMap,
|
||||
StringPrototypeStartsWith,
|
||||
globalThis,
|
||||
} = primordials;
|
||||
|
||||
@@ -16,12 +23,15 @@ const {
|
||||
ERR_INVALID_ARG_TYPE,
|
||||
ERR_INVALID_ARG_VALUE,
|
||||
ERR_INVALID_MODULE_SPECIFIER,
|
||||
ERR_INVALID_RETURN_PROPERTY,
|
||||
ERR_INVALID_RETURN_PROPERTY_VALUE,
|
||||
ERR_INVALID_RETURN_VALUE,
|
||||
ERR_UNKNOWN_MODULE_FORMAT
|
||||
} = require('internal/errors').codes;
|
||||
const { URL, pathToFileURL, isURLInstance } = require('internal/url');
|
||||
const { pathToFileURL, isURLInstance } = require('internal/url');
|
||||
const {
|
||||
isAnyArrayBuffer,
|
||||
isArrayBufferView,
|
||||
} = require('internal/util/types');
|
||||
const ModuleMap = require('internal/modules/esm/module_map');
|
||||
const ModuleJob = require('internal/modules/esm/module_job');
|
||||
|
||||
@@ -29,125 +39,159 @@ const {
|
||||
defaultResolve,
|
||||
DEFAULT_CONDITIONS,
|
||||
} = require('internal/modules/esm/resolve');
|
||||
const { defaultGetFormat } = require('internal/modules/esm/get_format');
|
||||
const { defaultGetSource } = require(
|
||||
'internal/modules/esm/get_source');
|
||||
const { defaultTransformSource } = require(
|
||||
'internal/modules/esm/transform_source');
|
||||
const { defaultLoad } = require('internal/modules/esm/load');
|
||||
const { translators } = require(
|
||||
'internal/modules/esm/translators');
|
||||
const { getOptionValue } = require('internal/options');
|
||||
|
||||
/* A Loader instance is used as the main entry point for loading ES modules.
|
||||
/**
|
||||
* An ESMLoader instance is used as the main entry point for loading ES modules.
|
||||
* Currently, this is a singleton -- there is only one used for loading
|
||||
* the main module and everything in its dependency graph. */
|
||||
class Loader {
|
||||
constructor() {
|
||||
// Methods which translate input code or other information
|
||||
// into es modules
|
||||
this.translators = translators;
|
||||
* the main module and everything in its dependency graph.
|
||||
*/
|
||||
class ESMLoader {
|
||||
/**
|
||||
* Prior to ESM loading. These are called once before any modules are started.
|
||||
* @private
|
||||
* @property {function[]} globalPreloaders First-in-first-out list of
|
||||
* preload hooks.
|
||||
*/
|
||||
#globalPreloaders = [];
|
||||
|
||||
// Registry of loaded modules, akin to `require.cache`
|
||||
this.moduleMap = new ModuleMap();
|
||||
/**
|
||||
* Phase 2 of 2 in ESM loading.
|
||||
* @private
|
||||
* @property {function[]} loaders First-in-first-out list of loader hooks.
|
||||
*/
|
||||
#loaders = [
|
||||
defaultLoad,
|
||||
];
|
||||
|
||||
// Map of already-loaded CJS modules to use
|
||||
this.cjsCache = new SafeWeakMap();
|
||||
/**
|
||||
* Phase 1 of 2 in ESM loading.
|
||||
* @private
|
||||
* @property {function[]} resolvers First-in-first-out list of resolver hooks
|
||||
*/
|
||||
#resolvers = [
|
||||
defaultResolve,
|
||||
];
|
||||
|
||||
// This hook is called before the first root module is imported. It's a
|
||||
// function that returns a piece of code that runs as a sloppy-mode script.
|
||||
// The script may evaluate to a function that can be called with a
|
||||
// `getBuiltin` helper that can be used to retrieve builtins.
|
||||
// If the hook returns `null` instead of a source string, it opts out of
|
||||
// running any preload code.
|
||||
// The preload code runs as soon as the hook module has finished evaluating.
|
||||
this._getGlobalPreloadCode = null;
|
||||
// The resolver has the signature
|
||||
// (specifier : string, parentURL : string, defaultResolve)
|
||||
// -> Promise<{ url : string }>
|
||||
// where defaultResolve is ModuleRequest.resolve (having the same
|
||||
// signature itself).
|
||||
this._resolve = defaultResolve;
|
||||
// This hook is called after the module is resolved but before a translator
|
||||
// is chosen to load it; the format returned by this function is the name
|
||||
// of a translator.
|
||||
this._getFormat = defaultGetFormat;
|
||||
// This hook is called just before the source code of an ES module file
|
||||
// is loaded.
|
||||
this._getSource = defaultGetSource;
|
||||
// This hook is called just after the source code of an ES module file
|
||||
// is loaded, but before anything is done with the string.
|
||||
this._transformSource = defaultTransformSource;
|
||||
// The index for assigning unique URLs to anonymous module evaluation
|
||||
this.evalIndex = 0;
|
||||
}
|
||||
/**
|
||||
* Map of already-loaded CJS modules to use
|
||||
*/
|
||||
cjsCache = new SafeWeakMap();
|
||||
|
||||
async resolve(specifier, parentURL) {
|
||||
const isMain = parentURL === undefined;
|
||||
if (!isMain && typeof parentURL !== 'string' && !isURLInstance(parentURL))
|
||||
throw new ERR_INVALID_ARG_TYPE('parentURL', ['string', 'URL'], parentURL);
|
||||
/**
|
||||
* The index for assigning unique URLs to anonymous module evaluation
|
||||
*/
|
||||
evalIndex = 0;
|
||||
|
||||
const resolveResponse = await this._resolve(
|
||||
specifier, { parentURL, conditions: DEFAULT_CONDITIONS }, defaultResolve);
|
||||
if (typeof resolveResponse !== 'object') {
|
||||
throw new ERR_INVALID_RETURN_VALUE(
|
||||
'object', 'loader resolve', resolveResponse);
|
||||
}
|
||||
/**
|
||||
* Registry of loaded modules, akin to `require.cache`
|
||||
*/
|
||||
moduleMap = new ModuleMap();
|
||||
|
||||
const { url } = resolveResponse;
|
||||
if (typeof url !== 'string') {
|
||||
throw new ERR_INVALID_RETURN_PROPERTY_VALUE(
|
||||
'string', 'loader resolve', 'url', url);
|
||||
}
|
||||
return url;
|
||||
}
|
||||
/**
|
||||
* Methods which translate input code or other information into ES modules
|
||||
*/
|
||||
translators = translators;
|
||||
|
||||
async getFormat(url) {
|
||||
const getFormatResponse = await this._getFormat(
|
||||
url, {}, defaultGetFormat);
|
||||
if (typeof getFormatResponse !== 'object') {
|
||||
throw new ERR_INVALID_RETURN_VALUE(
|
||||
'object', 'loader getFormat', getFormatResponse);
|
||||
}
|
||||
static pluckHooks({
|
||||
globalPreload,
|
||||
resolve,
|
||||
load,
|
||||
// obsolete hooks:
|
||||
dynamicInstantiate,
|
||||
getFormat,
|
||||
getGlobalPreloadCode,
|
||||
getSource,
|
||||
transformSource,
|
||||
}) {
|
||||
const obsoleteHooks = [];
|
||||
const acceptedHooks = ObjectCreate(null);
|
||||
|
||||
const { format } = getFormatResponse;
|
||||
if (format === null) {
|
||||
const dataUrl = RegExpPrototypeExec(
|
||||
/^data:([^/]+\/[^;,]+)(?:[^,]*?)(;base64)?,/,
|
||||
url,
|
||||
if (getGlobalPreloadCode) {
|
||||
globalPreload ??= getGlobalPreloadCode;
|
||||
|
||||
process.emitWarning(
|
||||
'Loader hook "getGlobalPreloadCode" has been renamed to "globalPreload"'
|
||||
);
|
||||
throw new ERR_INVALID_MODULE_SPECIFIER(
|
||||
url,
|
||||
dataUrl ? `has an unsupported MIME type "${dataUrl[1]}"` : '');
|
||||
}
|
||||
if (typeof format !== 'string') {
|
||||
throw new ERR_INVALID_RETURN_PROPERTY_VALUE(
|
||||
'string', 'loader getFormat', 'format', format);
|
||||
if (dynamicInstantiate) ArrayPrototypePush(
|
||||
obsoleteHooks,
|
||||
'dynamicInstantiate'
|
||||
);
|
||||
if (getFormat) ArrayPrototypePush(
|
||||
obsoleteHooks,
|
||||
'getFormat',
|
||||
);
|
||||
if (getSource) ArrayPrototypePush(
|
||||
obsoleteHooks,
|
||||
'getSource',
|
||||
);
|
||||
if (transformSource) ArrayPrototypePush(
|
||||
obsoleteHooks,
|
||||
'transformSource',
|
||||
);
|
||||
|
||||
if (obsoleteHooks.length) process.emitWarning(
|
||||
`Obsolete loader hook(s) supplied and will be ignored: ${
|
||||
ArrayPrototypeJoin(obsoleteHooks, ', ')
|
||||
}`,
|
||||
'DeprecationWarning',
|
||||
);
|
||||
|
||||
// Use .bind() to avoid giving access to the Loader instance when called.
|
||||
if (globalPreload) {
|
||||
acceptedHooks.globalPreloader =
|
||||
FunctionPrototypeBind(globalPreload, null);
|
||||
}
|
||||
if (resolve) {
|
||||
acceptedHooks.resolver = FunctionPrototypeBind(resolve, null);
|
||||
}
|
||||
if (load) {
|
||||
acceptedHooks.loader = FunctionPrototypeBind(load, null);
|
||||
}
|
||||
|
||||
if (format === 'builtin') {
|
||||
return format;
|
||||
}
|
||||
return acceptedHooks;
|
||||
}
|
||||
|
||||
if (this._resolve !== defaultResolve) {
|
||||
try {
|
||||
new URL(url);
|
||||
} catch {
|
||||
throw new ERR_INVALID_RETURN_PROPERTY(
|
||||
'url', 'loader resolve', 'url', url
|
||||
);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Collect custom/user-defined hook(s). After all hooks have been collected,
|
||||
* calls global preload hook(s).
|
||||
* @param {object | object[]} customLoaders A list of exports from
|
||||
* user-defined loaders (as returned by ESMLoader.import()).
|
||||
*/
|
||||
async addCustomLoaders(
|
||||
customLoaders = [],
|
||||
) {
|
||||
if (!ArrayIsArray(customLoaders)) customLoaders = [customLoaders];
|
||||
|
||||
if (this._resolve === defaultResolve &&
|
||||
!StringPrototypeStartsWith(url, 'file:') &&
|
||||
!StringPrototypeStartsWith(url, 'data:')
|
||||
) {
|
||||
throw new ERR_INVALID_RETURN_PROPERTY(
|
||||
'file: or data: url', 'loader resolve', 'url', url
|
||||
for (let i = 0; i < customLoaders.length; i++) {
|
||||
const exports = customLoaders[i];
|
||||
const {
|
||||
globalPreloader,
|
||||
resolver,
|
||||
loader,
|
||||
} = ESMLoader.pluckHooks(exports);
|
||||
|
||||
if (globalPreloader) ArrayPrototypePush(
|
||||
this.#globalPreloaders,
|
||||
FunctionPrototypeBind(globalPreloader, null), // [1]
|
||||
);
|
||||
if (resolver) ArrayPrototypePush(
|
||||
this.#resolvers,
|
||||
FunctionPrototypeBind(resolver, null), // [1]
|
||||
);
|
||||
if (loader) ArrayPrototypePush(
|
||||
this.#loaders,
|
||||
FunctionPrototypeBind(loader, null), // [1]
|
||||
);
|
||||
}
|
||||
|
||||
return format;
|
||||
// [1] ensure hook function is not bound to ESMLoader instance
|
||||
|
||||
this.preload();
|
||||
}
|
||||
|
||||
async eval(
|
||||
@@ -168,100 +212,259 @@ class Loader {
|
||||
const job = new ModuleJob(this, url, evalInstance, false, false);
|
||||
this.moduleMap.set(url, job);
|
||||
const { module } = await job.run();
|
||||
|
||||
return {
|
||||
namespace: module.getNamespace(),
|
||||
};
|
||||
}
|
||||
|
||||
async import(specifier, parent) {
|
||||
const job = await this.getModuleJob(specifier, parent);
|
||||
const { module } = await job.run();
|
||||
return module.getNamespace();
|
||||
}
|
||||
|
||||
hook(hooks) {
|
||||
const {
|
||||
resolve,
|
||||
dynamicInstantiate,
|
||||
getFormat,
|
||||
getSource,
|
||||
transformSource,
|
||||
getGlobalPreloadCode,
|
||||
} = hooks;
|
||||
|
||||
// Use .bind() to avoid giving access to the Loader instance when called.
|
||||
if (resolve !== undefined)
|
||||
this._resolve = FunctionPrototypeBind(resolve, null);
|
||||
if (dynamicInstantiate !== undefined) {
|
||||
process.emitWarning(
|
||||
'The dynamicInstantiate loader hook has been removed.');
|
||||
}
|
||||
if (getFormat !== undefined) {
|
||||
this._getFormat = FunctionPrototypeBind(getFormat, null);
|
||||
}
|
||||
if (getSource !== undefined) {
|
||||
this._getSource = FunctionPrototypeBind(getSource, null);
|
||||
}
|
||||
if (transformSource !== undefined) {
|
||||
this._transformSource = FunctionPrototypeBind(transformSource, null);
|
||||
}
|
||||
if (getGlobalPreloadCode !== undefined) {
|
||||
this._getGlobalPreloadCode =
|
||||
FunctionPrototypeBind(getGlobalPreloadCode, null);
|
||||
}
|
||||
}
|
||||
|
||||
runGlobalPreloadCode() {
|
||||
if (!this._getGlobalPreloadCode) {
|
||||
return;
|
||||
}
|
||||
const preloadCode = this._getGlobalPreloadCode();
|
||||
if (preloadCode === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof preloadCode !== 'string') {
|
||||
throw new ERR_INVALID_RETURN_VALUE(
|
||||
'string', 'loader getGlobalPreloadCode', preloadCode);
|
||||
}
|
||||
const { compileFunction } = require('vm');
|
||||
const preloadInit = compileFunction(preloadCode, ['getBuiltin'], {
|
||||
filename: '<preload>',
|
||||
});
|
||||
const { NativeModule } = require('internal/bootstrap/loaders');
|
||||
|
||||
preloadInit.call(globalThis, (builtinName) => {
|
||||
if (NativeModule.canBeRequiredByUsers(builtinName)) {
|
||||
return require(builtinName);
|
||||
}
|
||||
throw new ERR_INVALID_ARG_VALUE('builtinName', builtinName);
|
||||
});
|
||||
}
|
||||
|
||||
async getModuleJob(specifier, parentURL) {
|
||||
const url = await this.resolve(specifier, parentURL);
|
||||
const format = await this.getFormat(url);
|
||||
const { format, url } = await this.resolve(specifier, parentURL);
|
||||
let job = this.moduleMap.get(url);
|
||||
// CommonJS will set functions for lazy job evaluation.
|
||||
if (typeof job === 'function')
|
||||
this.moduleMap.set(url, job = job());
|
||||
if (job !== undefined)
|
||||
return job;
|
||||
if (typeof job === 'function') this.moduleMap.set(url, job = job());
|
||||
|
||||
if (!translators.has(format))
|
||||
throw new ERR_UNKNOWN_MODULE_FORMAT(format);
|
||||
if (job !== undefined) return job;
|
||||
|
||||
const loaderInstance = translators.get(format);
|
||||
const moduleProvider = async (url, isMain) => {
|
||||
const { format: finalFormat, source } = await this.load(url, { format });
|
||||
|
||||
const translator = translators.get(finalFormat);
|
||||
|
||||
if (!translator) throw new ERR_UNKNOWN_MODULE_FORMAT(finalFormat);
|
||||
|
||||
return FunctionPrototypeCall(translator, this, url, source, isMain);
|
||||
};
|
||||
|
||||
const inspectBrk = (
|
||||
parentURL === undefined &&
|
||||
getOptionValue('--inspect-brk')
|
||||
);
|
||||
|
||||
job = new ModuleJob(
|
||||
this,
|
||||
url,
|
||||
moduleProvider,
|
||||
parentURL === undefined,
|
||||
inspectBrk
|
||||
);
|
||||
|
||||
const inspectBrk = parentURL === undefined &&
|
||||
format === 'module' && getOptionValue('--inspect-brk');
|
||||
job = new ModuleJob(this, url, loaderInstance, parentURL === undefined,
|
||||
inspectBrk);
|
||||
this.moduleMap.set(url, job);
|
||||
|
||||
return job;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is usually called indirectly as part of the loading processes.
|
||||
* Internally, it is used directly to add loaders. Use directly with caution.
|
||||
*
|
||||
* This method must NOT be renamed: it functions as a dynamic import on a
|
||||
* loader module.
|
||||
*
|
||||
* @param {string | string[]} specifiers Path(s) to the module
|
||||
* @param {string} [parentURL] Path of the parent importing the module
|
||||
* @returns {object | object[]} A list of module export(s)
|
||||
*/
|
||||
async import(specifiers, parentURL) {
|
||||
const wasArr = ArrayIsArray(specifiers);
|
||||
if (!wasArr) specifiers = [specifiers];
|
||||
|
||||
const count = specifiers.length;
|
||||
const jobs = new Array(count);
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
jobs[i] = this.getModuleJob(specifiers[i], parentURL)
|
||||
.then((job) => job.run())
|
||||
.then(({ module }) => module.getNamespace());
|
||||
}
|
||||
|
||||
const namespaces = await PromiseAll(new SafeArrayIterator(jobs));
|
||||
|
||||
return wasArr ?
|
||||
namespaces :
|
||||
namespaces[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide source that is understood by one of Node's translators.
|
||||
*
|
||||
* The internals of this WILL change when chaining is implemented,
|
||||
* depending on the resolution/consensus from #36954
|
||||
* @param {string} url The URL/path of the module to be loaded
|
||||
* @param {Object} context Metadata about the module
|
||||
* @returns {Object}
|
||||
*/
|
||||
async load(url, context = {}) {
|
||||
const defaultLoader = this.#loaders[0];
|
||||
|
||||
const loader = this.#loaders.length === 1 ?
|
||||
defaultLoader :
|
||||
this.#loaders[1];
|
||||
const loaded = await loader(url, context, defaultLoader);
|
||||
|
||||
if (typeof loaded !== 'object') {
|
||||
throw new ERR_INVALID_RETURN_VALUE(
|
||||
'object',
|
||||
'loader load',
|
||||
loaded,
|
||||
);
|
||||
}
|
||||
|
||||
const {
|
||||
format,
|
||||
source,
|
||||
} = loaded;
|
||||
|
||||
if (format == null) {
|
||||
const dataUrl = RegExpPrototypeExec(
|
||||
/^data:([^/]+\/[^;,]+)(?:[^,]*?)(;base64)?,/,
|
||||
url,
|
||||
);
|
||||
|
||||
throw new ERR_INVALID_MODULE_SPECIFIER(
|
||||
url,
|
||||
dataUrl ? `has an unsupported MIME type "${dataUrl[1]}"` : ''
|
||||
);
|
||||
}
|
||||
|
||||
if (typeof format !== 'string') {
|
||||
throw new ERR_INVALID_RETURN_PROPERTY_VALUE(
|
||||
'string',
|
||||
'loader resolve',
|
||||
'format',
|
||||
format,
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
source != null &&
|
||||
typeof source !== 'string' &&
|
||||
!isAnyArrayBuffer(source) &&
|
||||
!isArrayBufferView(source)
|
||||
) throw ERR_INVALID_RETURN_PROPERTY_VALUE(
|
||||
'string, an ArrayBuffer, or a TypedArray',
|
||||
'loader load',
|
||||
'source',
|
||||
source
|
||||
);
|
||||
|
||||
return {
|
||||
format,
|
||||
source,
|
||||
};
|
||||
}
|
||||
|
||||
preload() {
|
||||
const count = this.#globalPreloaders.length;
|
||||
if (!count) return;
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
const preload = this.#globalPreloaders[i]();
|
||||
|
||||
if (preload == null) return;
|
||||
|
||||
if (typeof preload !== 'string') {
|
||||
throw new ERR_INVALID_RETURN_VALUE(
|
||||
'string',
|
||||
'loader globalPreloadCode',
|
||||
preload,
|
||||
);
|
||||
}
|
||||
const { compileFunction } = require('vm');
|
||||
const preloadInit = compileFunction(
|
||||
preload,
|
||||
['getBuiltin'],
|
||||
{
|
||||
filename: '<preload>',
|
||||
}
|
||||
);
|
||||
const { NativeModule } = require('internal/bootstrap/loaders');
|
||||
|
||||
FunctionPrototypeCall(preloadInit, globalThis, (builtinName) => {
|
||||
if (NativeModule.canBeRequiredByUsers(builtinName)) {
|
||||
return require(builtinName);
|
||||
}
|
||||
throw new ERR_INVALID_ARG_VALUE('builtinName', builtinName);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the location of the module.
|
||||
*
|
||||
* The internals of this WILL change when chaining is implemented,
|
||||
* depending on the resolution/consensus from #36954
|
||||
* @param {string} originalSpecifier The specified URL path of the module to
|
||||
* be resolved
|
||||
* @param {String} parentURL The URL path of the module's parent
|
||||
* @returns {{ url: String }}
|
||||
*/
|
||||
async resolve(originalSpecifier, parentURL) {
|
||||
const isMain = parentURL === undefined;
|
||||
|
||||
if (
|
||||
!isMain &&
|
||||
typeof parentURL !== 'string' &&
|
||||
!isURLInstance(parentURL)
|
||||
) throw new ERR_INVALID_ARG_TYPE(
|
||||
'parentURL',
|
||||
['string', 'URL'],
|
||||
parentURL,
|
||||
);
|
||||
|
||||
const conditions = DEFAULT_CONDITIONS;
|
||||
|
||||
const defaultResolver = this.#resolvers[0];
|
||||
|
||||
const resolver = this.#resolvers.length === 1 ?
|
||||
defaultResolver :
|
||||
this.#resolvers[1];
|
||||
const resolution = await resolver(
|
||||
originalSpecifier,
|
||||
{
|
||||
conditions,
|
||||
parentURL,
|
||||
},
|
||||
defaultResolver,
|
||||
);
|
||||
|
||||
if (typeof resolution !== 'object') {
|
||||
throw new ERR_INVALID_RETURN_VALUE(
|
||||
'object',
|
||||
'loader resolve',
|
||||
resolution,
|
||||
);
|
||||
}
|
||||
|
||||
const { format, url } = resolution;
|
||||
|
||||
if (
|
||||
format != null &&
|
||||
typeof format !== 'string'
|
||||
) {
|
||||
throw new ERR_INVALID_RETURN_PROPERTY_VALUE(
|
||||
'string',
|
||||
'loader resolve',
|
||||
'format',
|
||||
format,
|
||||
);
|
||||
}
|
||||
if (typeof url !== 'string') {
|
||||
throw new ERR_INVALID_RETURN_PROPERTY_VALUE(
|
||||
'string',
|
||||
'loader resolve',
|
||||
'url',
|
||||
url,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
format,
|
||||
url,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
ObjectSetPrototypeOf(Loader.prototype, null);
|
||||
ObjectSetPrototypeOf(ESMLoader.prototype, null);
|
||||
|
||||
exports.Loader = Loader;
|
||||
exports.ESMLoader = ESMLoader;
|
||||
@@ -141,9 +141,11 @@ class ModuleJob {
|
||||
const { 1: childSpecifier, 2: name } = StringPrototypeMatch(
|
||||
e.message,
|
||||
/module '(.*)' does not provide an export named '(.+)'/);
|
||||
const childFileURL =
|
||||
await this.loader.resolve(childSpecifier, parentFileUrl);
|
||||
const format = await this.loader.getFormat(childFileURL);
|
||||
const { url: childFileURL } = await this.loader.resolve(
|
||||
childSpecifier, parentFileUrl,
|
||||
);
|
||||
const { format } = await this.loader.load(childFileURL);
|
||||
|
||||
if (format === 'commonjs') {
|
||||
const importStatement = splitStack[1];
|
||||
// TODO(@ctavan): The original error stack only provides the single
|
||||
@@ -152,7 +154,7 @@ class ModuleJob {
|
||||
// just parsing the error stack.
|
||||
const oneLineNamedImports = StringPrototypeMatch(importStatement, /{.*}/);
|
||||
const destructuringAssignment = oneLineNamedImports &&
|
||||
StringPrototypeReplace(oneLineNamedImports, /\s+as\s+/g, ': ');
|
||||
StringPrototypeReplace(oneLineNamedImports, /\s+as\s+/g, ': ');
|
||||
e.message = `Named export '${name}' not found. The requested module` +
|
||||
` '${childSpecifier}' is a CommonJS module, which may not support` +
|
||||
' all module.exports as named exports.\nCommonJS modules can ' +
|
||||
|
||||
@@ -130,7 +130,7 @@ function emitTrailingSlashPatternDeprecation(match, pjsonUrl, isExports, base) {
|
||||
* @returns
|
||||
*/
|
||||
function emitLegacyIndexDeprecation(url, packageJSONUrl, base, main) {
|
||||
const { format } = defaultGetFormat(url);
|
||||
const format = defaultGetFormat(url);
|
||||
if (format !== 'module')
|
||||
return;
|
||||
const path = fileURLToPath(url);
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
function defaultTransformSource(source, { url, format } = {},
|
||||
defaultTransformSource) {
|
||||
return { source };
|
||||
}
|
||||
exports.defaultTransformSource = defaultTransformSource;
|
||||
@@ -8,7 +8,7 @@ const {
|
||||
ObjectGetPrototypeOf,
|
||||
ObjectPrototypeHasOwnProperty,
|
||||
ObjectKeys,
|
||||
PromisePrototypeCatch,
|
||||
PromisePrototypeThen,
|
||||
PromiseReject,
|
||||
SafeArrayIterator,
|
||||
SafeMap,
|
||||
@@ -38,10 +38,6 @@ const {
|
||||
cjsParseCache
|
||||
} = require('internal/modules/cjs/loader');
|
||||
const internalURLModule = require('internal/url');
|
||||
const { defaultGetSource } = require(
|
||||
'internal/modules/esm/get_source');
|
||||
const { defaultTransformSource } = require(
|
||||
'internal/modules/esm/transform_source');
|
||||
const createDynamicModule = require(
|
||||
'internal/modules/esm/create_dynamic_module');
|
||||
const { fileURLToPath, URL } = require('url');
|
||||
@@ -112,13 +108,14 @@ function errPath(url) {
|
||||
}
|
||||
|
||||
async function importModuleDynamically(specifier, { url }) {
|
||||
return asyncESM.ESMLoader.import(specifier, url);
|
||||
return asyncESM.esmLoader.import(specifier, url);
|
||||
}
|
||||
|
||||
function createImportMetaResolve(defaultParentUrl) {
|
||||
return async function resolve(specifier, parentUrl = defaultParentUrl) {
|
||||
return PromisePrototypeCatch(
|
||||
asyncESM.ESMLoader.resolve(specifier, parentUrl),
|
||||
return PromisePrototypeThen(
|
||||
asyncESM.esmLoader.resolve(specifier, parentUrl),
|
||||
({ url }) => url,
|
||||
(error) => (
|
||||
error.code === 'ERR_UNSUPPORTED_DIR_IMPORT' ?
|
||||
error.url : PromiseReject(error))
|
||||
@@ -134,12 +131,8 @@ function initializeImportMeta(meta, { url }) {
|
||||
}
|
||||
|
||||
// Strategy for loading a standard JavaScript module.
|
||||
translators.set('module', async function moduleStrategy(url) {
|
||||
let { source } = await this._getSource(
|
||||
url, { format: 'module' }, defaultGetSource);
|
||||
assertBufferSource(source, true, 'getSource');
|
||||
({ source } = await this._transformSource(
|
||||
source, { url, format: 'module' }, defaultTransformSource));
|
||||
translators.set('module', async function moduleStrategy(url, source, isMain) {
|
||||
assertBufferSource(source, true, 'load');
|
||||
source = stringify(source);
|
||||
maybeCacheSourceMap(url, source);
|
||||
debug(`Translating StandardModule ${url}`);
|
||||
@@ -172,7 +165,8 @@ function enrichCJSError(err, content, filename) {
|
||||
// Strategy for loading a node-style CommonJS module
|
||||
const isWindows = process.platform === 'win32';
|
||||
const winSepRegEx = /\//g;
|
||||
translators.set('commonjs', async function commonjsStrategy(url, isMain) {
|
||||
translators.set('commonjs', async function commonjsStrategy(url, source,
|
||||
isMain) {
|
||||
debug(`Translating CJSModule ${url}`);
|
||||
|
||||
let filename = internalURLModule.fileURLToPath(new URL(url));
|
||||
@@ -188,9 +182,9 @@ translators.set('commonjs', async function commonjsStrategy(url, isMain) {
|
||||
debug(`Loading CJSModule ${url}`);
|
||||
|
||||
let exports;
|
||||
if (asyncESM.ESMLoader.cjsCache.has(module)) {
|
||||
exports = asyncESM.ESMLoader.cjsCache.get(module);
|
||||
asyncESM.ESMLoader.cjsCache.delete(module);
|
||||
if (asyncESM.esmLoader.cjsCache.has(module)) {
|
||||
exports = asyncESM.esmLoader.cjsCache.get(module);
|
||||
asyncESM.esmLoader.cjsCache.delete(module);
|
||||
} else {
|
||||
try {
|
||||
exports = CJSModule._load(filename, undefined, isMain);
|
||||
@@ -286,9 +280,9 @@ translators.set('builtin', async function builtinStrategy(url) {
|
||||
});
|
||||
|
||||
// Strategy for loading a JSON file
|
||||
translators.set('json', async function jsonStrategy(url) {
|
||||
translators.set('json', async function jsonStrategy(url, source) {
|
||||
emitExperimentalWarning('Importing JSON modules');
|
||||
debug(`Translating JSONModule ${url}`);
|
||||
assertBufferSource(source, true, 'load');
|
||||
debug(`Loading JSONModule ${url}`);
|
||||
const pathname = StringPrototypeStartsWith(url, 'file:') ?
|
||||
fileURLToPath(url) : null;
|
||||
@@ -305,11 +299,6 @@ translators.set('json', async function jsonStrategy(url) {
|
||||
});
|
||||
}
|
||||
}
|
||||
let { source } = await this._getSource(
|
||||
url, { format: 'json' }, defaultGetSource);
|
||||
assertBufferSource(source, true, 'getSource');
|
||||
({ source } = await this._transformSource(
|
||||
source, { url, format: 'json' }, defaultTransformSource));
|
||||
source = stringify(source);
|
||||
if (pathname) {
|
||||
// A require call could have been called on the same file during loading and
|
||||
@@ -347,15 +336,13 @@ translators.set('json', async function jsonStrategy(url) {
|
||||
});
|
||||
|
||||
// Strategy for loading a wasm module
|
||||
translators.set('wasm', async function(url) {
|
||||
translators.set('wasm', async function(url, source) {
|
||||
emitExperimentalWarning('Importing Web Assembly modules');
|
||||
let { source } = await this._getSource(
|
||||
url, { format: 'wasm' }, defaultGetSource);
|
||||
assertBufferSource(source, false, 'getSource');
|
||||
({ source } = await this._transformSource(
|
||||
source, { url, format: 'wasm' }, defaultTransformSource));
|
||||
assertBufferSource(source, false, 'transformSource');
|
||||
|
||||
assertBufferSource(source, false, 'load');
|
||||
|
||||
debug(`Translating WASMModule ${url}`);
|
||||
|
||||
let compiled;
|
||||
try {
|
||||
compiled = await WebAssembly.compile(source);
|
||||
|
||||
@@ -41,12 +41,14 @@ function shouldUseESMLoader(mainPath) {
|
||||
}
|
||||
|
||||
function runMainESM(mainPath) {
|
||||
const esmLoader = require('internal/process/esm_loader');
|
||||
const { loadESM } = require('internal/process/esm_loader');
|
||||
const { pathToFileURL } = require('internal/url');
|
||||
handleMainPromise(esmLoader.loadESM((ESMLoader) => {
|
||||
|
||||
handleMainPromise(loadESM((esmLoader) => {
|
||||
const main = path.isAbsolute(mainPath) ?
|
||||
pathToFileURL(mainPath).href : mainPath;
|
||||
return ESMLoader.import(main);
|
||||
pathToFileURL(mainPath).href :
|
||||
mainPath;
|
||||
return esmLoader.import(main);
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
const {
|
||||
ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING,
|
||||
} = require('internal/errors').codes;
|
||||
const { Loader } = require('internal/modules/esm/loader');
|
||||
const { ESMLoader } = require('internal/modules/esm/loader');
|
||||
const {
|
||||
hasUncaughtExceptionCaptureCallback,
|
||||
} = require('internal/process/execution');
|
||||
@@ -34,38 +34,52 @@ exports.importModuleDynamicallyCallback = async function(wrap, specifier) {
|
||||
throw new ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING();
|
||||
};
|
||||
|
||||
let ESMLoader = new Loader();
|
||||
exports.ESMLoader = ESMLoader;
|
||||
const esmLoader = new ESMLoader();
|
||||
|
||||
exports.esmLoader = esmLoader;
|
||||
|
||||
/**
|
||||
* Causes side-effects: user-defined loader hooks are added to esmLoader.
|
||||
* @returns {void}
|
||||
*/
|
||||
async function initializeLoader() {
|
||||
const { getOptionValue } = require('internal/options');
|
||||
const userLoader = getOptionValue('--experimental-loader');
|
||||
if (!userLoader)
|
||||
return;
|
||||
// customLoaders CURRENTLY can be only 1 (a string)
|
||||
// Once chaining is implemented, it will be string[]
|
||||
const customLoaders = getOptionValue('--experimental-loader');
|
||||
|
||||
if (!customLoaders.length) return;
|
||||
|
||||
const { emitExperimentalWarning } = require('internal/util');
|
||||
emitExperimentalWarning('--experimental-loader');
|
||||
|
||||
let cwd;
|
||||
try {
|
||||
cwd = process.cwd() + '/';
|
||||
} catch {
|
||||
cwd = 'file:///';
|
||||
}
|
||||
// If --experimental-loader is specified, create a loader with user hooks.
|
||||
// Otherwise create the default loader.
|
||||
const { emitExperimentalWarning } = require('internal/util');
|
||||
emitExperimentalWarning('--experimental-loader');
|
||||
return (async () => {
|
||||
const hooks =
|
||||
await ESMLoader.import(userLoader, pathToFileURL(cwd).href);
|
||||
ESMLoader = new Loader();
|
||||
ESMLoader.hook(hooks);
|
||||
ESMLoader.runGlobalPreloadCode();
|
||||
return exports.ESMLoader = ESMLoader;
|
||||
})();
|
||||
|
||||
// A separate loader instance is necessary to avoid cross-contamination
|
||||
// between internal Node.js and userland. For example, a module with internal
|
||||
// state (such as a counter) should be independent.
|
||||
const internalEsmLoader = new ESMLoader();
|
||||
|
||||
// Importation must be handled by internal loader to avoid poluting userland
|
||||
const exports = await internalEsmLoader.import(
|
||||
customLoaders,
|
||||
pathToFileURL(cwd).href,
|
||||
);
|
||||
|
||||
// Hooks must then be added to external/public loader
|
||||
// (so they're triggered in userland)
|
||||
await esmLoader.addCustomLoaders(exports);
|
||||
}
|
||||
|
||||
exports.loadESM = async function loadESM(callback) {
|
||||
try {
|
||||
await initializeLoader();
|
||||
await callback(ESMLoader);
|
||||
await callback(esmLoader);
|
||||
} catch (err) {
|
||||
if (hasUncaughtExceptionCaptureCallback()) {
|
||||
process._fatalException(err);
|
||||
|
||||
@@ -83,7 +83,7 @@ function evalScript(name, body, breakFirstLine, print) {
|
||||
displayErrors: true,
|
||||
[kVmBreakFirstLineSymbol]: !!breakFirstLine,
|
||||
async importModuleDynamically(specifier) {
|
||||
const loader = await asyncESM.ESMLoader;
|
||||
const loader = await asyncESM.esmLoader;
|
||||
return loader.import(specifier, baseUrl);
|
||||
}
|
||||
}));
|
||||
|
||||
+2
-2
@@ -455,7 +455,7 @@ function REPLServer(prompt,
|
||||
filename: file,
|
||||
displayErrors: true,
|
||||
importModuleDynamically: async (specifier) => {
|
||||
return asyncESM.ESMLoader.import(specifier, parentURL);
|
||||
return asyncESM.esmLoader.import(specifier, parentURL);
|
||||
}
|
||||
});
|
||||
} catch (fallbackError) {
|
||||
@@ -497,7 +497,7 @@ function REPLServer(prompt,
|
||||
filename: file,
|
||||
displayErrors: true,
|
||||
importModuleDynamically: async (specifier) => {
|
||||
return asyncESM.ESMLoader.import(specifier, parentURL);
|
||||
return asyncESM.esmLoader.import(specifier, parentURL);
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
|
||||
@@ -99,7 +99,7 @@ function createBase64URL(mime, body) {
|
||||
await import(plainESMURL);
|
||||
common.mustNotCall()();
|
||||
} catch (e) {
|
||||
assert.strictEqual(e.code, 'ERR_INVALID_MODULE_SPECIFIER');
|
||||
assert.strictEqual(e.code, 'ERR_INVALID_URL');
|
||||
}
|
||||
}
|
||||
{
|
||||
|
||||
File renamed without changes.
@@ -1,6 +0,0 @@
|
||||
// Flags: --experimental-loader ./test/fixtures/es-module-loaders/get-source.mjs
|
||||
/* eslint-disable node-core/require-common-first, node-core/required-modules */
|
||||
import assert from 'assert';
|
||||
import { message } from '../fixtures/es-modules/message.mjs';
|
||||
|
||||
assert.strictEqual(message, 'WOOHOO!');
|
||||
@@ -1,12 +0,0 @@
|
||||
// Flags: --experimental-loader ./test/fixtures/es-module-loaders/loader-get-format.mjs
|
||||
import { mustCall, mustNotCall } from '../common/index.mjs';
|
||||
import assert from 'assert';
|
||||
|
||||
import('../fixtures/es-modules/package-type-module/extension.unknown')
|
||||
.then(
|
||||
mustCall((ns) => {
|
||||
assert.strictEqual(ns.default, 'unknown');
|
||||
}),
|
||||
// Do not use .catch; want exclusive or
|
||||
mustNotCall(() => {})
|
||||
);
|
||||
@@ -7,7 +7,7 @@
|
||||
require('../common');
|
||||
|
||||
const assert = require('assert');
|
||||
const { Loader } = require('internal/modules/esm/loader');
|
||||
const { ESMLoader } = require('internal/modules/esm/loader');
|
||||
const ModuleMap = require('internal/modules/esm/module_map');
|
||||
const ModuleJob = require('internal/modules/esm/module_job');
|
||||
const createDynamicModule = require(
|
||||
@@ -15,7 +15,7 @@ const createDynamicModule = require(
|
||||
|
||||
const stubModuleUrl = new URL('file://tmp/test');
|
||||
const stubModule = createDynamicModule(['default'], stubModuleUrl);
|
||||
const loader = new Loader();
|
||||
const loader = new ESMLoader();
|
||||
const moduleMap = new ModuleMap();
|
||||
const moduleJob = new ModuleJob(loader, stubModule.module,
|
||||
() => new Promise(() => {}));
|
||||
|
||||
@@ -12,6 +12,34 @@ import('test:ArrayBuffer').then(
|
||||
mustCall(),
|
||||
mustNotCall('Should accept ArrayBuffers'),
|
||||
);
|
||||
import('test:BigInt64Array').then(
|
||||
mustCall(),
|
||||
mustNotCall('Should accept BigInt64Array'),
|
||||
);
|
||||
import('test:BigUint64Array').then(
|
||||
mustCall(),
|
||||
mustNotCall('Should accept BigUint64Array'),
|
||||
);
|
||||
import('test:Float32Array').then(
|
||||
mustCall(),
|
||||
mustNotCall('Should accept Float32Array'),
|
||||
);
|
||||
import('test:Float64Array').then(
|
||||
mustCall(),
|
||||
mustNotCall('Should accept Float64Array'),
|
||||
);
|
||||
import('test:Int8Array').then(
|
||||
mustCall(),
|
||||
mustNotCall('Should accept Int8Array'),
|
||||
);
|
||||
import('test:Int16Array').then(
|
||||
mustCall(),
|
||||
mustNotCall('Should accept Int16Array'),
|
||||
);
|
||||
import('test:Int32Array').then(
|
||||
mustCall(),
|
||||
mustNotCall('Should accept Int32Array'),
|
||||
);
|
||||
import('test:null').then(
|
||||
mustNotCall('Should not accept null'),
|
||||
mustCall((e) => {
|
||||
@@ -38,6 +66,18 @@ import('test:String').then(
|
||||
assert.strictEqual(e.code, 'ERR_INVALID_RETURN_PROPERTY_VALUE');
|
||||
})
|
||||
);
|
||||
import('test:Uint8ClampedArray').then(
|
||||
mustCall(),
|
||||
mustNotCall('Should accept Uint8ClampedArray'),
|
||||
);
|
||||
import('test:Uint16Array').then(
|
||||
mustCall(),
|
||||
mustNotCall('Should accept Uint16Array'),
|
||||
);
|
||||
import('test:Uint32Array').then(
|
||||
mustCall(),
|
||||
mustNotCall('Should accept Uint32Array'),
|
||||
);
|
||||
import('test:Uint8Array').then(
|
||||
mustCall(),
|
||||
mustNotCall('Should accept Uint8Arrays'),
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
// Flags: --experimental-loader ./test/fixtures/es-module-loaders/hooks-custom.mjs
|
||||
import '../common/index.mjs';
|
||||
import assert from 'assert';
|
||||
|
||||
|
||||
await assert.rejects(
|
||||
import('nonexistent/file.mjs'),
|
||||
{ code: 'ERR_MODULE_NOT_FOUND' },
|
||||
);
|
||||
|
||||
await assert.rejects(
|
||||
import('../fixtures/es-modules/file.unknown'),
|
||||
{ code: 'ERR_UNKNOWN_FILE_EXTENSION' },
|
||||
);
|
||||
|
||||
await assert.rejects(
|
||||
import('esmHook/badReturnVal.mjs'),
|
||||
{ code: 'ERR_INVALID_RETURN_VALUE' },
|
||||
);
|
||||
|
||||
// Nullish values are allowed; booleans are not
|
||||
await assert.rejects(
|
||||
import('esmHook/format.false'),
|
||||
{ code: 'ERR_INVALID_RETURN_PROPERTY_VALUE' },
|
||||
);
|
||||
await assert.rejects(
|
||||
import('esmHook/format.true'),
|
||||
{ code: 'ERR_INVALID_RETURN_PROPERTY_VALUE' },
|
||||
);
|
||||
|
||||
await assert.rejects(
|
||||
import('esmHook/badReturnFormatVal.mjs'),
|
||||
{ code: 'ERR_INVALID_RETURN_PROPERTY_VALUE' },
|
||||
);
|
||||
|
||||
await assert.rejects(
|
||||
import('esmHook/unsupportedReturnFormatVal.mjs'),
|
||||
{ code: 'ERR_UNKNOWN_MODULE_FORMAT' },
|
||||
);
|
||||
|
||||
await assert.rejects(
|
||||
import('esmHook/badReturnSourceVal.mjs'),
|
||||
{ code: 'ERR_INVALID_RETURN_PROPERTY_VALUE' },
|
||||
);
|
||||
|
||||
await import('../fixtures/es-module-loaders/js-as-esm.js')
|
||||
.then((parsedModule) => {
|
||||
assert.strictEqual(typeof parsedModule, 'object');
|
||||
assert.strictEqual(parsedModule.namedExport, 'named-export');
|
||||
});
|
||||
|
||||
// The custom loader tells node .ext files are MJS
|
||||
await import('../fixtures/es-modules/file.ext')
|
||||
.then((parsedModule) => {
|
||||
assert.strictEqual(typeof parsedModule, 'object');
|
||||
const { default: defaultExport } = parsedModule;
|
||||
assert.strictEqual(typeof defaultExport, 'function');
|
||||
assert.strictEqual(defaultExport.name, 'iAmReal');
|
||||
assert.strictEqual(defaultExport(), true);
|
||||
});
|
||||
|
||||
// The custom loader's resolve hook predetermines the format
|
||||
await import('esmHook/preknownFormat.pre')
|
||||
.then((parsedModule) => {
|
||||
assert.strictEqual(typeof parsedModule, 'object');
|
||||
assert.strictEqual(parsedModule.default, 'hello world');
|
||||
});
|
||||
|
||||
// The custom loader provides source even though file does not actually exist
|
||||
await import('esmHook/virtual.mjs')
|
||||
.then((parsedModule) => {
|
||||
assert.strictEqual(typeof parsedModule, 'object');
|
||||
assert.strictEqual(typeof parsedModule.default, 'undefined');
|
||||
assert.strictEqual(parsedModule.message, 'WOOHOO!');
|
||||
});
|
||||
|
||||
// Ensure custom loaders have separate context from userland
|
||||
// hooks-custom.mjs also increments count (which starts at 0)
|
||||
// if both share context, count here would be 2
|
||||
await import('../fixtures/es-modules/stateful.mjs')
|
||||
.then(({ default: count }) => {
|
||||
assert.strictEqual(count(), 1);
|
||||
});
|
||||
@@ -1,8 +0,0 @@
|
||||
// Flags: --experimental-loader ./test/fixtures/es-module-loaders/js-loader.mjs
|
||||
/* eslint-disable node-core/require-common-first, node-core/required-modules */
|
||||
import { namedExport } from '../fixtures/es-module-loaders/js-as-esm.js';
|
||||
import assert from 'assert';
|
||||
import ok from '../fixtures/es-modules/test-esm-ok.mjs';
|
||||
|
||||
assert(ok);
|
||||
assert(namedExport);
|
||||
@@ -1,6 +0,0 @@
|
||||
// Flags: --experimental-loader ./test/fixtures/es-module-loaders/transform-source.mjs
|
||||
/* eslint-disable node-core/require-common-first, node-core/required-modules */
|
||||
import assert from 'assert';
|
||||
import { message } from '../fixtures/es-modules/message.mjs';
|
||||
|
||||
assert.strictEqual(message, 'A MESSAGE');
|
||||
@@ -2,7 +2,7 @@ import module from 'module';
|
||||
|
||||
const GET_BUILTIN = `$__get_builtin_hole_${Date.now()}`;
|
||||
|
||||
export function getGlobalPreloadCode() {
|
||||
export function globalPreload() {
|
||||
return `Object.defineProperty(globalThis, ${JSON.stringify(GET_BUILTIN)}, {
|
||||
value: (builtinName) => {
|
||||
return getBuiltin(builtinName);
|
||||
@@ -13,8 +13,9 @@ export function getGlobalPreloadCode() {
|
||||
`;
|
||||
}
|
||||
|
||||
export function resolve(specifier, context, defaultResolve) {
|
||||
const def = defaultResolve(specifier, context);
|
||||
export function resolve(specifier, context, next) {
|
||||
const def = next(specifier, context);
|
||||
|
||||
if (def.url.startsWith('node:')) {
|
||||
return {
|
||||
url: `custom-${def.url}`,
|
||||
@@ -23,7 +24,7 @@ export function resolve(specifier, context, defaultResolve) {
|
||||
return def;
|
||||
}
|
||||
|
||||
export function getSource(url, context, defaultGetSource) {
|
||||
export function load(url, context, next) {
|
||||
if (url.startsWith('custom-node:')) {
|
||||
const urlObj = new URL(url);
|
||||
return {
|
||||
@@ -31,14 +32,7 @@ export function getSource(url, context, defaultGetSource) {
|
||||
format: 'module',
|
||||
};
|
||||
}
|
||||
return defaultGetSource(url, context);
|
||||
}
|
||||
|
||||
export function getFormat(url, context, defaultGetFormat) {
|
||||
if (url.startsWith('custom-node:')) {
|
||||
return { format: 'module' };
|
||||
}
|
||||
return defaultGetFormat(url, context, defaultGetFormat);
|
||||
return next(url, context);
|
||||
}
|
||||
|
||||
function generateBuiltinModule(builtinName) {
|
||||
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
export async function getSource(url, { format }, defaultGetSource) {
|
||||
if (url.endsWith('fixtures/es-modules/message.mjs')) {
|
||||
// Oh, I’ve got that one in my cache!
|
||||
return {
|
||||
source: `export const message = 'Woohoo!'.toUpperCase();`
|
||||
}
|
||||
} else {
|
||||
return defaultGetSource(url, {format}, defaultGetSource);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import count from '../es-modules/stateful.mjs';
|
||||
|
||||
|
||||
// Arbitrary instance of manipulating a module's internal state
|
||||
// used to assert node-land and user-land have different contexts
|
||||
count();
|
||||
|
||||
/**
|
||||
* @param {string} url A fully resolved file url.
|
||||
* @param {object} context Additional info.
|
||||
* @param {function} next for now, next is defaultLoad a wrapper for
|
||||
* defaultGetFormat + defaultGetSource
|
||||
* @returns {{ format: string, source: (string|SharedArrayBuffer|Uint8Array) }}
|
||||
*/
|
||||
export function load(url, context, next) {
|
||||
// Load all .js files as ESM, regardless of package scope
|
||||
if (url.endsWith('.js')) return next(url, {
|
||||
...context,
|
||||
format: 'module',
|
||||
});
|
||||
|
||||
if (url.endsWith('.ext')) return next(url, {
|
||||
...context,
|
||||
format: 'module',
|
||||
});
|
||||
|
||||
if (url === 'esmHook/badReturnVal.mjs') return 'export function returnShouldBeObject() {}';
|
||||
|
||||
if (url === 'esmHook/badReturnFormatVal.mjs') return {
|
||||
format: Array(0),
|
||||
source: '',
|
||||
}
|
||||
if (url === 'esmHook/unsupportedReturnFormatVal.mjs') return {
|
||||
format: 'foo', // Not one of the allowable inputs: no translator named 'foo'
|
||||
source: '',
|
||||
}
|
||||
|
||||
if (url === 'esmHook/badReturnSourceVal.mjs') return {
|
||||
format: 'module',
|
||||
source: Array(0),
|
||||
}
|
||||
|
||||
if (url === 'esmHook/preknownFormat.pre') return {
|
||||
format: context.format,
|
||||
source: `const msg = 'hello world'; export default msg;`
|
||||
};
|
||||
|
||||
if (url === 'esmHook/virtual.mjs') return {
|
||||
format: 'module',
|
||||
source: `export const message = 'Woohoo!'.toUpperCase();`,
|
||||
};
|
||||
|
||||
return next(url, context, next);
|
||||
}
|
||||
|
||||
export function resolve(specifier, context, next) {
|
||||
let format = '';
|
||||
|
||||
if (specifier === 'esmHook/format.false') format = false;
|
||||
if (specifier === 'esmHook/format.true') format = true;
|
||||
if (specifier === 'esmHook/preknownFormat.pre') format = 'module';
|
||||
|
||||
if (specifier.startsWith('esmHook')) return {
|
||||
format,
|
||||
url: specifier,
|
||||
};
|
||||
|
||||
return next(specifier, context, next);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
export function dynamicInstantiate() {}
|
||||
export function getFormat() {}
|
||||
export function getSource() {}
|
||||
export function transformSource() {}
|
||||
|
||||
|
||||
export function load(url, context, next) {
|
||||
if (url === 'whatever') return {
|
||||
format: 'module',
|
||||
source: '',
|
||||
};
|
||||
|
||||
return next(url, context, next);
|
||||
}
|
||||
|
||||
export function resolve(specifier, context, next) {
|
||||
if (specifier === 'whatever') return {
|
||||
url: specifier,
|
||||
};
|
||||
|
||||
return next(specifier, context, next);
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
export function getFormat(url, context, defaultGetFormat) {
|
||||
// Load all .js files as ESM, regardless of package scope
|
||||
if (url.endsWith('.js')) {
|
||||
return {
|
||||
format: 'module'
|
||||
}
|
||||
}
|
||||
return defaultGetFormat(url, context, defaultGetFormat);
|
||||
}
|
||||
@@ -7,11 +7,12 @@ export async function resolve(specifier, { parentURL }, defaultResolve) {
|
||||
return defaultResolve(specifier, {parentURL}, defaultResolve);
|
||||
}
|
||||
|
||||
export function getFormat(url, context, defaultGetFormat) {
|
||||
export async function load(url, context, next) {
|
||||
if (url === 'file:///asdf') {
|
||||
return {
|
||||
format: 'esm'
|
||||
format: 'esm',
|
||||
source: '',
|
||||
}
|
||||
}
|
||||
return defaultGetFormat(url, context, defaultGetFormat);
|
||||
return next(url, context, next);
|
||||
}
|
||||
@@ -1,17 +1,7 @@
|
||||
export async function resolve(specifier, { parentURL }, defaultResolve) {
|
||||
if (specifier === 'unknown-builtin-module') {
|
||||
return {
|
||||
url: 'node:unknown-builtin-module'
|
||||
};
|
||||
}
|
||||
return defaultResolve(specifier, {parentURL}, defaultResolve);
|
||||
}
|
||||
export function resolve(specifier, context, next) {
|
||||
if (specifier === 'unknown-builtin-module') return {
|
||||
url: 'node:unknown-builtin-module'
|
||||
};
|
||||
|
||||
export async function getFormat(url, context, defaultGetFormat) {
|
||||
if (url === 'node:unknown-builtin-module') {
|
||||
return {
|
||||
format: 'builtin'
|
||||
};
|
||||
}
|
||||
return defaultGetFormat(url, context, defaultGetFormat);
|
||||
return next(specifier, context, next);
|
||||
}
|
||||
+19
-11
@@ -2,29 +2,37 @@ const SOURCES = {
|
||||
__proto__: null,
|
||||
'test:Array': ['1', '2'], // both `1,2` and `12` are valid ESM
|
||||
'test:ArrayBuffer': new ArrayBuffer(0),
|
||||
'test:BigInt64Array': new BigInt64Array(0),
|
||||
'test:BigUint64Array': new BigUint64Array(0),
|
||||
'test:Float32Array': new Float32Array(0),
|
||||
'test:Float64Array': new Float64Array(0),
|
||||
'test:Int8Array': new Int8Array(0),
|
||||
'test:Int16Array': new Int16Array(0),
|
||||
'test:Int32Array': new Int32Array(0),
|
||||
'test:null': null,
|
||||
'test:Object': {},
|
||||
'test:SharedArrayBuffer': new SharedArrayBuffer(0),
|
||||
'test:string': '',
|
||||
'test:String': new String(''),
|
||||
'test:Uint8Array': new Uint8Array(0),
|
||||
'test:Uint8ClampedArray': new Uint8ClampedArray(0),
|
||||
'test:Uint16Array': new Uint16Array(0),
|
||||
'test:Uint32Array': new Uint32Array(0),
|
||||
'test:undefined': undefined,
|
||||
}
|
||||
export function resolve(specifier, context, defaultFn) {
|
||||
export function resolve(specifier, context, next) {
|
||||
if (specifier.startsWith('test:')) {
|
||||
return { url: specifier };
|
||||
}
|
||||
return defaultFn(specifier, context);
|
||||
return next(specifier, context);
|
||||
}
|
||||
export function getFormat(href, context, defaultFn) {
|
||||
|
||||
export function load(href, context, next) {
|
||||
if (href.startsWith('test:')) {
|
||||
return { format: 'module' };
|
||||
return {
|
||||
format: 'module',
|
||||
source: SOURCES[href],
|
||||
};
|
||||
}
|
||||
return defaultFn(href, context);
|
||||
}
|
||||
export function getSource(href, context, defaultFn) {
|
||||
if (href.startsWith('test:')) {
|
||||
return { source: SOURCES[href] };
|
||||
}
|
||||
return defaultFn(href, context);
|
||||
return next(href, context);
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
export async function transformSource(
|
||||
source, { url, format }, defaultTransformSource) {
|
||||
if (format === 'module') {
|
||||
if (typeof source !== 'string') {
|
||||
source = new TextDecoder().decode(source);
|
||||
}
|
||||
return {
|
||||
source: source.replace(`'A message';`, `'A message'.toUpperCase();`)
|
||||
};
|
||||
} else { // source could be a buffer, e.g. for WASM
|
||||
return defaultTransformSource(
|
||||
source, {url, format}, defaultTransformSource);
|
||||
}
|
||||
}
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
// fixtures/es-module-loader.mjs tells node to treat this file like ESM
|
||||
|
||||
export default function iAmReal() { return true };
|
||||
Whitespace-only changes.
+5
@@ -0,0 +1,5 @@
|
||||
let counter = 0;
|
||||
|
||||
export default function count() {
|
||||
return ++counter;
|
||||
}
|
||||
@@ -3,5 +3,6 @@ await async () => 0;
|
||||
^^^^^
|
||||
|
||||
SyntaxError: Unexpected reserved word
|
||||
at Loader.moduleStrategy (node:internal/modules/esm/translators:*:*)
|
||||
at ESMLoader.moduleStrategy (node:internal/modules/esm/translators:*:*)
|
||||
at ESMLoader.moduleProvider (node:internal/modules/esm/loader:*:*)
|
||||
at async link (node:internal/modules/esm/module_job:*:*)
|
||||
@@ -4,6 +4,7 @@ file:///*/test/message/esm_display_syntax_error_import.mjs:5
|
||||
SyntaxError: The requested module '../fixtures/es-module-loaders/module-named-exports.mjs' does not provide an export named 'notfound'
|
||||
at ModuleJob._instantiate (node:internal/modules/esm/module_job:*:*)
|
||||
at async ModuleJob.run (node:internal/modules/esm/module_job:*:*)
|
||||
at async Loader.import (node:internal/modules/esm/loader:*:*)
|
||||
at async Object.loadESM (node:internal/process/esm_loader:*:*)
|
||||
at async Promise.all (index 0)
|
||||
at async ESMLoader.import (node:internal/modules/esm/loader:*:*)
|
||||
at async loadESM (node:internal/process/esm_loader:*:*)
|
||||
at async handleMainPromise (node:internal/modules/run_main:*:*)
|
||||
@@ -4,6 +4,7 @@ import { foo, notfound } from './module-named-exports.mjs';
|
||||
SyntaxError: The requested module './module-named-exports.mjs' does not provide an export named 'notfound'
|
||||
at ModuleJob._instantiate (node:internal/modules/esm/module_job:*:*)
|
||||
at async ModuleJob.run (node:internal/modules/esm/module_job:*:*)
|
||||
at async Loader.import (node:internal/modules/esm/loader:*:*)
|
||||
at async Object.loadESM (node:internal/process/esm_loader:*:*)
|
||||
at async Promise.all (index 0)
|
||||
at async ESMLoader.import (node:internal/modules/esm/loader:*:*)
|
||||
at async loadESM (node:internal/process/esm_loader:*:*)
|
||||
at async handleMainPromise (node:internal/modules/run_main:*:*)
|
||||
@@ -3,4 +3,5 @@ await async () => 0;
|
||||
^^^^^^^^^^^^^
|
||||
|
||||
SyntaxError: Malformed arrow function parameter list
|
||||
at Loader.moduleStrategy (node:internal/modules/esm/translators:*:*)
|
||||
at ESMLoader.moduleStrategy (node:internal/modules/esm/translators:*:*)
|
||||
at ESMLoader.moduleProvider (node:internal/modules/esm/loader:*:*)
|
||||
@@ -7,12 +7,12 @@ Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'i-dont-exist' imported from *
|
||||
at new NodeError (node:internal/errors:*:*)
|
||||
at packageResolve (node:internal/modules/esm/resolve:*:*)
|
||||
at moduleResolve (node:internal/modules/esm/resolve:*:*)
|
||||
at Loader.defaultResolve [as _resolve] (node:internal/modules/esm/resolve:*:*)
|
||||
at Loader.resolve (node:internal/modules/esm/loader:*:*)
|
||||
at Loader.getModuleJob (node:internal/modules/esm/loader:*:*)
|
||||
at Loader.import (node:internal/modules/esm/loader:*:*)
|
||||
at node:internal/process/esm_loader:*:*
|
||||
at defaultResolve (node:internal/modules/esm/resolve:*:*)
|
||||
at ESMLoader.resolve (node:internal/modules/esm/loader:*:*)
|
||||
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:*:*)
|
||||
at ESMLoader.import (node:internal/modules/esm/loader:*:*)
|
||||
at initializeLoader (node:internal/process/esm_loader:*:*)
|
||||
at Object.loadESM (node:internal/process/esm_loader:*:*) {
|
||||
at loadESM (node:internal/process/esm_loader:*:*)
|
||||
at runMainESM (node:internal/modules/run_main:*:*) {
|
||||
code: 'ERR_MODULE_NOT_FOUND'
|
||||
}
|
||||
@@ -7,9 +7,9 @@ Did you mean to import some_module/obj.js?
|
||||
at new NodeError (node:internal/errors:*:*)
|
||||
at finalizeResolution (node:internal/modules/esm/resolve:*:*)
|
||||
at moduleResolve (node:internal/modules/esm/resolve:*:*)
|
||||
at Loader.defaultResolve [as _resolve] (node:internal/modules/esm/resolve:*:*)
|
||||
at Loader.resolve (node:internal/modules/esm/loader:*:*)
|
||||
at Loader.getModuleJob (node:internal/modules/esm/loader:*:*)
|
||||
at defaultResolve (node:internal/modules/esm/resolve:*:*)
|
||||
at ESMLoader.resolve (node:internal/modules/esm/loader:*:*)
|
||||
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:*:*)
|
||||
at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:*:*)
|
||||
at link (node:internal/modules/esm/module_job:*:*) {
|
||||
code: 'ERR_MODULE_NOT_FOUND'
|
||||
|
||||
@@ -9,12 +9,12 @@ Did you mean to import ./test/common/fixtures.js?
|
||||
at new NodeError (node:internal/errors:*:*)
|
||||
at finalizeResolution (node:internal/modules/esm/resolve:*:*)
|
||||
at moduleResolve (node:internal/modules/esm/resolve:*:*)
|
||||
at Loader.defaultResolve [as _resolve] (node:internal/modules/esm/resolve:*:*)
|
||||
at Loader.resolve (node:internal/modules/esm/loader:*:*)
|
||||
at Loader.getModuleJob (node:internal/modules/esm/loader:*:*)
|
||||
at Loader.import (node:internal/modules/esm/loader:*:*)
|
||||
at node:internal/process/esm_loader:*:*
|
||||
at defaultResolve (node:internal/modules/esm/resolve:*:*)
|
||||
at ESMLoader.resolve (node:internal/modules/esm/loader:*:*)
|
||||
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:*:*)
|
||||
at ESMLoader.import (node:internal/modules/esm/loader:*:*)
|
||||
at initializeLoader (node:internal/process/esm_loader:*:*)
|
||||
at Object.loadESM (node:internal/process/esm_loader:*:*) {
|
||||
at loadESM (node:internal/process/esm_loader:*:*)
|
||||
at runMainESM (node:internal/modules/run_main:*:*) {
|
||||
code: 'ERR_MODULE_NOT_FOUND'
|
||||
}
|
||||
@@ -5,5 +5,6 @@ await async () => 0;
|
||||
^^^^^^^^^^^^^
|
||||
|
||||
SyntaxError: Malformed arrow function parameter list
|
||||
at Loader.moduleStrategy (node:internal/modules/esm/translators:*:*)
|
||||
at ESMLoader.moduleStrategy (node:internal/modules/esm/translators:*:*)
|
||||
at ESMLoader.moduleProvider (node:internal/modules/esm/loader:*:*)
|
||||
at async link (node:internal/modules/esm/module_job:*:*)
|
||||
@@ -0,0 +1,4 @@
|
||||
// Flags: --no-warnings --throw-deprecation --experimental-loader ./test/fixtures/es-module-loaders/hooks-obsolete.mjs
|
||||
/* eslint-disable node-core/require-common-first, node-core/required-modules */
|
||||
|
||||
await import('whatever');
|
||||
@@ -0,0 +1,10 @@
|
||||
node:internal/process/warning:*
|
||||
throw warning;
|
||||
^
|
||||
|
||||
DeprecationWarning: Obsolete loader hook(s) supplied and will be ignored: dynamicInstantiate, getFormat, getSource, transformSource
|
||||
at Function.pluckHooks (node:internal/modules/esm/loader:*:*)
|
||||
at ESMLoader.addCustomLoaders (node:internal/modules/esm/loader:*:*)
|
||||
at initializeLoader (node:internal/process/esm_loader:*:*)
|
||||
at async loadESM (node:internal/process/esm_loader:*:*)
|
||||
at async handleMainPromise (node:internal/modules/run_main:*:*)
|
||||
@@ -72,10 +72,10 @@ const expectedModules = new Set([
|
||||
'NativeModule internal/modules/esm/get_format',
|
||||
'NativeModule internal/modules/esm/get_source',
|
||||
'NativeModule internal/modules/esm/loader',
|
||||
'NativeModule internal/modules/esm/load',
|
||||
'NativeModule internal/modules/esm/module_job',
|
||||
'NativeModule internal/modules/esm/module_map',
|
||||
'NativeModule internal/modules/esm/resolve',
|
||||
'NativeModule internal/modules/esm/transform_source',
|
||||
'NativeModule internal/modules/esm/translators',
|
||||
'NativeModule internal/process/esm_loader',
|
||||
'NativeModule internal/options',
|
||||
|
||||
Reference in new issue
Block a user