esm: move hook execution to separate thread

PR-URL: https://github.com/nodejs/node/pull/44710
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
Co-authored-by: Antoine du Hamel <duhamelantoine1995@gmail.com>
Co-authored-by: Geoffrey Booth <webadmin@geoffreybooth.com>
Co-authored-by: Michaël Zasso <targos@protonmail.com>
This commit is contained in:
authored and GitHub committed 2023-04-13 09:35:17 +02:00
1 parent 527394783e
commit 4667b07cd2
37 files changed
+995 -455

No files matched your search

+25 -14
View File
@@ -7,6 +7,9 @@
<!-- YAML
added: v8.5.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/44710
description: Loader hooks are executed off the main thread.
- version:
- v18.6.0
- v16.17.0
@@ -325,6 +328,9 @@ added:
- v13.9.0
- v12.16.2
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/44710
description: This API now returns a string synchronously instead of a Promise.
- version:
- v16.2.0
- v14.18.0
@@ -340,29 +346,26 @@ command flag enabled.
* `specifier` {string} The module specifier to resolve relative to `parent`.
* `parent` {string|URL} The absolute parent module URL to resolve from. If none
is specified, the value of `import.meta.url` is used as the default.
* Returns: {Promise}
* Returns: {string}
Provides a module-relative resolution function scoped to each module, returning
the URL string.
the URL string. In alignment with browser behavior, this now returns
synchronously.
<!-- eslint-skip -->
> **Caveat** This can result in synchronous file-system operations, which
> can impact performance similarly to `require.resolve`.
```js
const dependencyAsset = await import.meta.resolve('component-lib/asset.css');
const dependencyAsset = import.meta.resolve('component-lib/asset.css');
```
`import.meta.resolve` also accepts a second argument which is the parent module
from which to resolve from:
<!-- eslint-skip -->
from which to resolve:
```js
await import.meta.resolve('./dep', import.meta.url);
import.meta.resolve('./dep', import.meta.url);
```
This function is asynchronous because the ES module resolver in Node.js is
allowed to be asynchronous.
## Interoperability with CommonJS
### `import` statements
@@ -730,6 +733,11 @@ A hook that returns without calling `next<hookName>()` _and_ without returning
`shortCircuit: true` also triggers an exception. These errors are to help
prevent unintentional breaks in the chain.
Hooks are run in a separate thread, isolated from the main. That means it is a
different [realm](https://tc39.es/ecma262/#realm). The hooks thread may be
terminated by the main thread at any time, so do not depend on asynchronous
operations to (like `console.log`) complete.
#### `resolve(specifier, context, nextResolve)`
<!-- YAML
@@ -762,7 +770,7 @@ changes:
Node.js default `resolve` hook after the last user-supplied `resolve` hook
* `specifier` {string}
* `context` {Object}
* Returns: {Object}
* Returns: {Object|Promise}
* `format` {string|null|undefined} A hint to the load hook (it might be
ignored)
`'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'`
@@ -772,6 +780,9 @@ changes:
terminate the chain of `resolve` hooks. **Default:** `false`
* `url` {string} The absolute URL to which this input resolves
> **Caveat** Despite support for returning promises and async functions, calls
> to `resolve` may block the main thread which can impact performance.
The `resolve` hook chain is responsible for telling Node.js where to find and
how to cache a given `import` statement or expression. It can optionally return
its format (such as `'module'`) as a hint to the `load` hook. If a format is
@@ -797,7 +808,7 @@ Node.js module specifier resolution behavior_ when calling `defaultResolve`, the
`context.conditions` array originally passed into the `resolve` hook.
```js
export async function resolve(specifier, context, nextResolve) {
export function resolve(specifier, context, nextResolve) {
const { parentURL = null } = context;
if (Math.random() > 0.5) { // Some condition.
@@ -1100,7 +1111,7 @@ const baseURL = pathToFileURL(`${cwd()}/`).href;
// CoffeeScript files end in .coffee, .litcoffee, or .coffee.md.
const extensionsRegex = /\.coffee$|\.litcoffee$|\.coffee\.md$/;
export async function resolve(specifier, context, nextResolve) {
export function resolve(specifier, context, nextResolve) {
if (extensionsRegex.test(specifier)) {
const { parentURL = baseURL } = context;
+54 -35
View File
@@ -10,6 +10,7 @@ const {
ObjectDefineProperty,
PromisePrototypeThen,
RegExpPrototypeExec,
SafeWeakMap,
globalThis: {
Atomics,
SharedArrayBuffer,
@@ -89,23 +90,25 @@ port.on('message', (message) => {
const {
argv,
cwdCounter,
filename,
doEval,
workerData,
environmentData,
publicPort,
filename,
hasStdin,
manifestSrc,
manifestURL,
hasStdin,
publicPort,
workerData,
} = message;
if (argv !== undefined) {
ArrayPrototypePushApply(process.argv, argv);
}
if (doEval !== 'internal') {
if (argv !== undefined) {
ArrayPrototypePushApply(process.argv, argv);
}
const publicWorker = require('worker_threads');
publicWorker.parentPort = publicPort;
publicWorker.workerData = workerData;
const publicWorker = require('worker_threads');
publicWorker.parentPort = publicPort;
publicWorker.workerData = workerData;
}
require('internal/worker').assignEnvironmentData(environmentData);
@@ -138,31 +141,47 @@ port.on('message', (message) => {
debug(`[${threadId}] starts worker script ${filename} ` +
`(eval = ${doEval}) at cwd = ${process.cwd()}`);
port.postMessage({ type: UP_AND_RUNNING });
if (doEval === 'classic') {
const { evalScript } = require('internal/process/execution');
const name = '[worker eval]';
// This is necessary for CJS module compilation.
// TODO: pass this with something really internal.
ObjectDefineProperty(process, '_eval', {
__proto__: null,
configurable: true,
enumerable: true,
value: filename,
});
ArrayPrototypeSplice(process.argv, 1, 0, name);
evalScript(name, filename);
} else if (doEval === 'module') {
const { evalModule } = require('internal/process/execution');
PromisePrototypeThen(evalModule(filename), undefined, (e) => {
workerOnGlobalUncaughtException(e, true);
});
} else {
// script filename
// runMain here might be monkey-patched by users in --require.
// XXX: the monkey-patchability here should probably be deprecated.
ArrayPrototypeSplice(process.argv, 1, 0, filename);
const CJSLoader = require('internal/modules/cjs/loader');
CJSLoader.Module.runMain(filename);
switch (doEval) {
case 'internal': {
// Create this WeakMap in js-land because V8 has no C++ API for WeakMap.
internalBinding('module_wrap').callbackMap = new SafeWeakMap();
require(filename)(workerData, publicPort);
break;
}
case 'classic': {
const { evalScript } = require('internal/process/execution');
const name = '[worker eval]';
// This is necessary for CJS module compilation.
// TODO: pass this with something really internal.
ObjectDefineProperty(process, '_eval', {
__proto__: null,
configurable: true,
enumerable: true,
value: filename,
});
ArrayPrototypeSplice(process.argv, 1, 0, name);
evalScript(name, filename);
break;
}
case 'module': {
const { evalModule } = require('internal/process/execution');
PromisePrototypeThen(evalModule(filename), undefined, (e) => {
workerOnGlobalUncaughtException(e, true);
});
break;
}
default: {
// script filename
// runMain here might be monkey-patched by users in --require.
// XXX: the monkey-patchability here should probably be deprecated.
ArrayPrototypeSplice(process.argv, 1, 0, filename);
const CJSLoader = require('internal/modules/cjs/loader');
CJSLoader.Module.runMain(filename);
break;
}
}
} else if (message.type === STDIO_PAYLOAD) {
const { stream, chunks } = message;
+239 -110
View File
@@ -4,9 +4,11 @@ const {
ArrayPrototypeJoin,
ArrayPrototypePush,
FunctionPrototypeCall,
Int32Array,
ObjectAssign,
ObjectDefineProperty,
ObjectSetPrototypeOf,
Promise,
SafeSet,
StringPrototypeSlice,
StringPrototypeToUpperCase,
@@ -14,14 +16,26 @@ const {
} = primordials;
const {
ERR_LOADER_CHAIN_INCOMPLETE,
Atomics: {
load: AtomicsLoad,
wait: AtomicsWait,
waitAsync: AtomicsWaitAsync,
},
SharedArrayBuffer,
} = globalThis;
const {
ERR_INTERNAL_ASSERTION,
ERR_INVALID_ARG_TYPE,
ERR_INVALID_ARG_VALUE,
ERR_INVALID_RETURN_PROPERTY_VALUE,
ERR_INVALID_RETURN_VALUE,
ERR_LOADER_CHAIN_INCOMPLETE,
ERR_WORKER_UNSERIALIZABLE_ERROR,
} = require('internal/errors').codes;
const { isURL, URL } = require('internal/url');
const { exitCodes: { kUnfinishedTopLevelAwait } } = internalBinding('errors');
const { URL } = require('internal/url');
const { receiveMessageOnPort } = require('worker_threads');
const {
isAnyArrayBuffer,
isArrayBufferView,
@@ -33,10 +47,19 @@ const {
const {
defaultResolve,
throwIfInvalidParentURL,
} = require('internal/modules/esm/resolve');
const {
getDefaultConditions,
} = require('internal/modules/esm/utils');
const { deserializeError } = require('internal/error_serdes');
const {
SHARED_MEMORY_BYTE_LENGTH,
WORKER_TO_MAIN_THREAD_NOTIFICATION,
} = require('internal/modules/esm/shared_constants');
let debug = require('internal/util/debuglog').debuglog('esm', (fn) => {
debug = fn;
});
/**
@@ -49,7 +72,7 @@ const {
class Hooks {
#hooks = {
#chains = {
/**
* Prior to ESM loading. These are called once before any modules are started.
* @private
@@ -83,27 +106,20 @@ class Hooks {
],
};
// Enable an optimization in ESMLoader.getModuleJob
hasCustomResolveOrLoadHooks = false;
// Cache URLs we've already validated to avoid repeated validation
#validatedUrls = new SafeSet();
#importMetaInitializer = require('internal/modules/esm/initialize_import_meta').initializeImportMeta;
constructor(userLoaders) {
this.#addCustomLoaders(userLoaders);
this.addCustomLoaders(userLoaders);
}
/**
* Collect custom/user-defined module loader hook(s).
* After all hooks have been collected, the global preload hook(s) must be initialized.
* @param {import('./loader.js).KeyedExports} customLoaders Exports from user-defined loaders
* (as returned by `ESMLoader.import()`).
* (as returned by `ModuleLoader.import()`).
*/
#addCustomLoaders(
customLoaders = [],
) {
addCustomLoaders(customLoaders = []) {
for (let i = 0; i < customLoaders.length; i++) {
const {
exports,
@@ -116,33 +132,13 @@ class Hooks {
} = pluckHooks(exports);
if (globalPreload) {
ArrayPrototypePush(
this.#hooks.globalPreload,
{
fn: globalPreload,
url,
},
);
ArrayPrototypePush(this.#chains.globalPreload, { fn: globalPreload, url });
}
if (resolve) {
this.hasCustomResolveOrLoadHooks = true;
ArrayPrototypePush(
this.#hooks.resolve,
{
fn: resolve,
url,
},
);
ArrayPrototypePush(this.#chains.resolve, { fn: resolve, url });
}
if (load) {
this.hasCustomResolveOrLoadHooks = true;
ArrayPrototypePush(
this.#hooks.load,
{
fn: load,
url,
},
);
ArrayPrototypePush(this.#chains.load, { fn: load, url });
}
}
}
@@ -150,8 +146,9 @@ class Hooks {
/**
* Initialize `globalPreload` hooks.
*/
preload() {
for (let i = this.#hooks.globalPreload.length - 1; i >= 0; i--) {
initializeGlobalPreload() {
const preloadScripts = [];
for (let i = this.#chains.globalPreload.length - 1; i >= 0; i--) {
const { MessageChannel } = require('internal/worker/io');
const channel = new MessageChannel();
const {
@@ -165,7 +162,7 @@ class Hooks {
const {
fn: preload,
url: specifier,
} = this.#hooks.globalPreload[i];
} = this.#chains.globalPreload[i];
const preloaded = preload({
port: insideLoader,
@@ -173,69 +170,20 @@ class Hooks {
if (preloaded == null) { return; }
const hookErrIdentifier = `${specifier} globalPreload`;
if (typeof preloaded !== 'string') { // [2]
throw new ERR_INVALID_RETURN_VALUE(
'a string',
hookErrIdentifier,
`${specifier} globalPreload`,
preload,
);
}
const { compileFunction } = require('vm');
const preloadInit = compileFunction(
preloaded,
['getBuiltin', 'port', 'setImportMetaCallback'],
{
filename: '<preload>',
},
);
const { BuiltinModule } = require('internal/bootstrap/realm');
// We only allow replacing the importMetaInitializer during preload;
// after preload is finished, we disable the ability to replace it.
//
// This exposes accidentally setting the initializer too late by throwing an error.
let finished = false;
let replacedImportMetaInitializer = false;
let next = this.#importMetaInitializer;
try {
// Calls the compiled preload source text gotten from the hook
// Since the parameters are named we use positional parameters
// see compileFunction above to cross reference the names
FunctionPrototypeCall(
preloadInit,
globalThis,
// Param getBuiltin
(builtinName) => {
if (BuiltinModule.canBeRequiredWithoutScheme(builtinName)) {
return require(builtinName);
}
throw new ERR_INVALID_ARG_VALUE('builtinName', builtinName);
},
// Param port
insidePreload,
// Param setImportMetaCallback
(fn) => {
if (finished || typeof fn !== 'function') {
throw new ERR_INVALID_ARG_TYPE('fn', fn);
}
replacedImportMetaInitializer = true;
const parent = next;
next = (meta, context) => {
return fn(meta, context, parent);
};
});
} finally {
finished = true;
if (replacedImportMetaInitializer) {
this.#importMetaInitializer = next;
}
}
}
}
importMetaInitialize(meta, context) {
this.#importMetaInitializer(meta, context);
ArrayPrototypePush(preloadScripts, {
code: preloaded,
port: insidePreload,
});
}
return preloadScripts;
}
/**
@@ -257,20 +205,9 @@ class Hooks {
parentURL,
importAssertions = { __proto__: null },
) {
const isMain = parentURL === undefined;
throwIfInvalidParentURL(parentURL);
if (
!isMain &&
typeof parentURL !== 'string' &&
!isURL(parentURL)
) {
throw new ERR_INVALID_ARG_TYPE(
'parentURL',
['string', 'URL'],
parentURL,
);
}
const chain = this.#hooks.resolve;
const chain = this.#chains.resolve;
const context = {
conditions: getDefaultConditions(),
importAssertions,
@@ -392,7 +329,7 @@ class Hooks {
* @returns {Promise<{ format: ModuleFormat, source: ModuleSource }>}
*/
async load(url, context = {}) {
const chain = this.#hooks.load;
const chain = this.#chains.load;
const meta = {
chainFinished: null,
context,
@@ -515,9 +452,200 @@ class Hooks {
};
}
}
ObjectSetPrototypeOf(Hooks.prototype, null);
/**
* There may be multiple instances of Hooks/HooksProxy, but there is only 1 Internal worker, so
* there is only 1 MessageChannel.
*/
let MessageChannel;
class HooksProxy {
/**
* Shared memory. Always use Atomics method to read or write to it.
* @type {Int32Array}
*/
#lock;
/**
* The InternalWorker instance, which lets us communicate with the loader thread.
*/
#worker;
/**
* The last notification ID received from the worker. This is used to detect
* if the worker has already sent a notification before putting the main
* thread to sleep, to avoid a race condition.
* @type {number}
*/
#workerNotificationLastId = 0;
/**
* Track how many async responses the main thread should expect.
* @type {number}
*/
#numberOfPendingAsyncResponses = 0;
#isReady = false;
constructor() {
const { InternalWorker } = require('internal/worker');
MessageChannel ??= require('internal/worker/io').MessageChannel;
const lock = new SharedArrayBuffer(SHARED_MEMORY_BYTE_LENGTH);
this.#lock = new Int32Array(lock);
this.#worker = new InternalWorker('internal/modules/esm/worker', {
stderr: false,
stdin: false,
stdout: false,
trackUnmanagedFds: false,
workerData: {
lock,
},
});
this.#worker.unref(); // ! Allows the process to eventually exit.
}
#waitForWorker() {
if (!this.#isReady) {
const { kIsOnline } = require('internal/worker');
if (!this.#worker[kIsOnline]) {
debug('wait for signal from worker');
AtomicsWait(this.#lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 0);
const response = this.#worker.receiveMessageSync();
const { preloadScripts } = this.#unwrapMessage(response);
this.#executePreloadScripts(preloadScripts);
}
this.#isReady = true;
}
}
#beforeExitHandler = () => {
debug('beforeExit main thread', this.#lock, this.#numberOfPendingAsyncResponses);
if (this.#numberOfPendingAsyncResponses !== 0) {
// The worker still has some work to do, let's wait for it before terminating the process.
this.#worker.ref();
}
};
async makeAsyncRequest(method, ...args) {
this.#waitForWorker();
MessageChannel ??= require('internal/worker/io').MessageChannel;
const asyncCommChannel = new MessageChannel();
// Pass work to the worker.
debug('post async message to worker', { method, args });
this.#worker.postMessage({ method, args, port: asyncCommChannel.port2 }, [asyncCommChannel.port2]);
if (this.#numberOfPendingAsyncResponses++ === 0) {
// On the next lines, the main thread will await a response from the worker thread that might
// come AFTER the last task in the event loop has run its course and there would be nothing
// left keeping the thread alive (and once the main thread dies, the whole process stops).
// However we want to keep the process alive until the worker thread responds (or until the
// event loop of the worker thread is also empty). So we add the beforeExit handler whose
// mission is to lock the main thread until we hear back from the worker thread. The `if`
// condition is there so we only add the event handler once (if there are already pending
// async responses, the previous calls have added the event listener).
process.on('beforeExit', this.#beforeExitHandler);
}
let response;
do {
debug('wait for async response from worker', { method, args });
await AtomicsWaitAsync(this.#lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, this.#workerNotificationLastId).value;
this.#workerNotificationLastId = AtomicsLoad(this.#lock, WORKER_TO_MAIN_THREAD_NOTIFICATION);
// In case the beforeExit handler was called during the await, we revert its actions.
this.#worker.unref();
response = receiveMessageOnPort(asyncCommChannel.port1);
} while (response == null);
debug('got async response from worker', { method, args }, this.#lock);
if (--this.#numberOfPendingAsyncResponses === 0) {
// We got all the responses from the worker, its job is done (until next time).
process.off('beforeExit', this.#beforeExitHandler);
}
const body = this.#unwrapMessage(response);
asyncCommChannel.port1.close();
return body;
}
makeSyncRequest(method, ...args) {
this.#waitForWorker();
// Pass work to the worker.
debug('post sync message to worker', { method, args });
this.#worker.postMessage({ method, args });
let response;
do {
debug('wait for sync response from worker', { method, args });
// Sleep until worker responds.
AtomicsWait(this.#lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, this.#workerNotificationLastId);
this.#workerNotificationLastId = AtomicsLoad(this.#lock, WORKER_TO_MAIN_THREAD_NOTIFICATION);
response = this.#worker.receiveMessageSync();
} while (response == null);
debug('got sync response from worker', { method, args });
if (response.message.status === 'never-settle') {
process.exit(kUnfinishedTopLevelAwait);
}
return this.#unwrapMessage(response);
}
#unwrapMessage(response) {
if (response.message.status === 'never-settle') {
return new Promise(() => {});
}
if (response.message.status === 'error') {
if (response.message.body == null) throw response.message.body;
if (response.message.body.serializationFailed || response.message.body.serialized == null) {
throw ERR_WORKER_UNSERIALIZABLE_ERROR();
}
// eslint-disable-next-line no-restricted-syntax
throw deserializeError(response.message.body.serialized);
} else {
return response.message.body;
}
}
#executePreloadScripts(preloadScripts) {
for (let i = 0; i < preloadScripts.length; i++) {
const { code, port } = preloadScripts[i];
const { compileFunction } = require('vm');
const preloadInit = compileFunction(
code,
['getBuiltin', 'port'],
{
filename: '<preload>',
},
);
const { BuiltinModule } = require('internal/bootstrap/realm');
// Calls the compiled preload source text gotten from the hook
// Since the parameters are named we use positional parameters
// see compileFunction above to cross reference the names
FunctionPrototypeCall(
preloadInit,
globalThis,
// Param getBuiltin
(builtinName) => {
if (BuiltinModule.canBeRequiredByUsers(builtinName) &&
BuiltinModule.canBeRequiredWithoutScheme(builtinName)) {
return require(builtinName);
}
throw new ERR_INVALID_ARG_VALUE('builtinName', builtinName);
},
// Param port
port,
);
}
}
}
ObjectSetPrototypeOf(HooksProxy.prototype, null);
/**
* A utility function to pluck the hooks from a user-defined loader.
@@ -665,3 +793,4 @@ function nextHookFactory(chain, meta, { validateArgs, validateOutput }) {
exports.Hooks = Hooks;
exports.HooksProxy = HooksProxy;
@@ -1,39 +1,50 @@
'use strict';
const { getOptionValue } = require('internal/options');
const experimentalImportMetaResolve =
getOptionValue('--experimental-import-meta-resolve');
const {
PromisePrototypeThen,
PromiseReject,
} = primordials;
const asyncESM = require('internal/process/esm_loader');
const experimentalImportMetaResolve = getOptionValue('--experimental-import-meta-resolve');
function createImportMetaResolve(defaultParentUrl) {
return async function resolve(specifier, parentUrl = defaultParentUrl) {
return PromisePrototypeThen(
asyncESM.esmLoader.resolve(specifier, parentUrl),
({ url }) => url,
(error) => (
error.code === 'ERR_UNSUPPORTED_DIR_IMPORT' ?
error.url : PromiseReject(error)),
);
/**
* Generate a function to be used as import.meta.resolve for a particular module.
* @param {string} defaultParentUrl The default base to use for resolution
* @param {typeof import('./loader.js').ModuleLoader} loader Reference to the current module loader
* @returns {(specifier: string, parentUrl?: string) => string} Function to assign to import.meta.resolve
*/
function createImportMetaResolve(defaultParentUrl, loader) {
return function resolve(specifier, parentUrl = defaultParentUrl) {
let url;
try {
({ url } = loader.resolve(specifier, parentUrl));
} catch (error) {
if (error?.code === 'ERR_UNSUPPORTED_DIR_IMPORT') {
({ url } = error);
} else {
throw error;
}
}
return url;
};
}
/**
* Create the `import.meta` object for a module.
* @param {object} meta
* @param {{url: string}} context
* @param {typeof import('./loader.js').ModuleLoader} loader Reference to the current module loader
* @returns {{url: string, resolve?: Function}}
*/
function initializeImportMeta(meta, context) {
function initializeImportMeta(meta, context, loader) {
const { url } = context;
// Alphabetical
if (experimentalImportMetaResolve) {
meta.resolve = createImportMetaResolve(url);
if (experimentalImportMetaResolve && loader.loaderType !== 'internal') {
meta.resolve = createImportMetaResolve(url, loader);
}
meta.url = url;
return meta;
}
module.exports = {
+140 -72
View File
@@ -8,6 +8,7 @@ const {
ArrayIsArray,
FunctionPrototypeCall,
ObjectSetPrototypeOf,
PromisePrototypeThen,
SafePromiseAllReturnArrayLike,
SafeWeakMap,
} = primordials;
@@ -18,10 +19,10 @@ const {
const { getOptionValue } = require('internal/options');
const { pathToFileURL } = require('internal/url');
const { emitExperimentalWarning } = require('internal/util');
const {
getDefaultConditions,
} = require('internal/modules/esm/utils');
let defaultResolve, defaultLoad, importMetaInitializer;
function newModuleMap() {
const ModuleMap = require('internal/modules/esm/module_map');
@@ -33,6 +34,14 @@ function getTranslators() {
return translators;
}
/**
* @type {HooksProxy}
* Multiple loader instances exist for various, specific reasons (see code comments at site).
* In order to maintain consistency, we use a single worker (sandbox), which must sit apart of an
* individual loader instance.
*/
let hooksProxy;
/**
* @typedef {object} ExportedHooks
* @property {Function} globalPreload Global preload hook.
@@ -60,17 +69,10 @@ function getTranslators() {
/**
* 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.
* This class covers the default case of an module loader instance where no custom user loaders are used.
* The below CustomizedModuleLoader class extends this one to support custom user loader hooks.
*/
class ESMLoader {
#hooks;
#defaultResolve;
#defaultLoad;
#importMetaInitializer;
class DefaultModuleLoader {
/**
* The conditions for resolving packages if `--conditions` is not used.
*/
@@ -96,24 +98,18 @@ class ESMLoader {
*/
translators = getTranslators();
/**
* Type of loader.
* @type {'default' | 'internal'}
*/
loaderType = 'default';
constructor() {
if (getOptionValue('--experimental-loader').length > 0) {
emitExperimentalWarning('Custom ESM Loaders');
}
if (getOptionValue('--experimental-network-imports')) {
emitExperimentalWarning('Network Imports');
}
}
addCustomLoaders(userLoaders) {
const { Hooks } = require('internal/modules/esm/hooks');
this.#hooks = new Hooks(userLoaders);
}
preload() {
this.#hooks?.preload();
}
async eval(
source,
url = pathToFileURL(`${process.cwd()}/[eval${++this.evalIndex}]`).href,
@@ -153,23 +149,14 @@ class ESMLoader {
* point.
* @param {Record<string, string>} importAssertions Validations for the
* module import.
* @returns {Promise<ModuleJob>} The (possibly pending) module job
* @returns {ModuleJob} The (possibly pending) module job
*/
async getModuleJob(specifier, parentURL, importAssertions) {
let importAssertionsForResolve;
getModuleJob(specifier, parentURL, importAssertions) {
const resolveResult = this.resolve(specifier, parentURL, importAssertions);
return this.getJobFromResolveResult(resolveResult, parentURL, importAssertions);
}
// We can skip cloning if there are no user-provided loaders because
// the Node.js default resolve hook does not use import assertions.
if (this.#hooks?.hasCustomResolveOrLoadHooks) {
// This method of cloning only works so long as import assertions cannot contain objects as values,
// which they currently cannot per spec.
importAssertionsForResolve = {
__proto__: null,
...importAssertions,
};
}
const resolveResult = await this.resolve(specifier, parentURL, importAssertionsForResolve);
getJobFromResolveResult(resolveResult, parentURL, importAssertions) {
const { url, format } = resolveResult;
const resolvedImportAssertions = resolveResult.importAssertions ?? importAssertions;
@@ -273,9 +260,12 @@ class ESMLoader {
const jobs = new Array(count);
for (let i = 0; i < count; i++) {
jobs[i] = this.getModuleJob(specifiers[i], parentURL, importAssertions)
.then((job) => job.run())
.then(({ module }) => module.getNamespace());
jobs[i] = PromisePrototypeThen(
this
.getModuleJob(specifiers[i], parentURL, importAssertions)
.run(),
({ module }) => module.getNamespace(),
);
}
const namespaces = await SafePromiseAllReturnArrayLike(jobs);
@@ -300,24 +290,20 @@ class ESMLoader {
* be resolved.
* @param {string} [parentURL] The URL path of the module's parent.
* @param {ImportAssertions} importAssertions Assertions from the import
* statement or expression.
* @returns {Promise<{ format: string, url: URL['href'] }>}
* statement or expression.
* @returns {{ format: string, url: URL['href'] }}
*/
async resolve(originalSpecifier, parentURL, importAssertions) {
if (this.#hooks) {
return this.#hooks.resolve(originalSpecifier, parentURL, importAssertions);
}
if (!this.#defaultResolve) {
this.#defaultResolve = require('internal/modules/esm/resolve').defaultResolve;
}
resolve(originalSpecifier, parentURL, importAssertions) {
defaultResolve ??= require('internal/modules/esm/resolve').defaultResolve;
const context = {
__proto__: null,
conditions: this.#defaultConditions,
importAssertions,
parentURL,
};
return this.#defaultResolve(originalSpecifier, context);
return defaultResolve(originalSpecifier, context);
}
/**
@@ -328,36 +314,118 @@ class ESMLoader {
* @returns {Promise<{ format: ModuleFormat, source: ModuleSource }>}
*/
async load(url, context) {
let loadResult;
if (this.#hooks) {
loadResult = await this.#hooks.load(url, context);
} else {
if (!this.#defaultLoad) {
this.#defaultLoad = require('internal/modules/esm/load').defaultLoad;
}
loadResult = await this.#defaultLoad(url, context);
}
defaultLoad ??= require('internal/modules/esm/load').defaultLoad;
const { format } = loadResult;
const result = await defaultLoad(url, context);
this.validateLoadResult(url, result?.format);
return result;
}
validateLoadResult(url, format) {
if (format == null) {
require('internal/modules/esm/load').throwUnknownModuleFormat(url, format);
}
return loadResult;
}
importMetaInitialize(meta, context) {
if (this.#hooks) {
this.#hooks.importMetaInitialize(meta, context);
} else {
if (!this.#importMetaInitializer) {
this.#importMetaInitializer = require('internal/modules/esm/initialize_import_meta').initializeImportMeta;
}
this.#importMetaInitializer(meta, context);
importMetaInitializer ??= require('internal/modules/esm/initialize_import_meta').initializeImportMeta;
meta = importMetaInitializer(meta, context, this);
return meta;
}
}
ObjectSetPrototypeOf(DefaultModuleLoader.prototype, null);
class CustomizedModuleLoader extends DefaultModuleLoader {
/**
* Instantiate a module loader that uses user-provided custom loader hooks.
*/
constructor() {
super();
if (hooksProxy) {
// The worker proxy is shared across all instances, so don't recreate it if it already exists.
return;
}
const { HooksProxy } = require('internal/modules/esm/hooks');
hooksProxy = new HooksProxy(); // The user's custom hooks are loaded within the worker as part of its startup.
}
/**
* Resolve the location of the module.
*
* @param {string} originalSpecifier The specified URL path of the module to
* be resolved.
* @param {string} [parentURL] The URL path of the module's parent.
* @param {ImportAssertions} importAssertions Assertions from the import
* statement or expression.
* @returns {{ format: string, url: URL['href'] }}
*/
resolve(originalSpecifier, parentURL, importAssertions) {
return hooksProxy.makeSyncRequest('resolve', originalSpecifier, parentURL, importAssertions);
}
async #getModuleJob(specifier, parentURL, importAssertions) {
const resolveResult = await hooksProxy.makeAsyncRequest('resolve', specifier, parentURL, importAssertions);
return this.getJobFromResolveResult(resolveResult, parentURL, importAssertions);
}
getModuleJob(specifier, parentURL, importAssertions) {
const jobPromise = this.#getModuleJob(specifier, parentURL, importAssertions);
return {
run() {
return PromisePrototypeThen(jobPromise, (job) => job.run());
},
get modulePromise() {
return PromisePrototypeThen(jobPromise, (job) => job.modulePromise);
},
get linked() {
return PromisePrototypeThen(jobPromise, (job) => job.linked);
},
};
}
/**
* Provide source that is understood by one of Node's translators.
*
* @param {URL['href']} url The URL/path of the module to be loaded
* @param {object} [context] Metadata about the module
* @returns {Promise<{ format: ModuleFormat, source: ModuleSource }>}
*/
async load(url, context) {
const result = await hooksProxy.makeAsyncRequest('load', url, context);
this.validateLoadResult(url, result?.format);
return result;
}
}
ObjectSetPrototypeOf(ESMLoader.prototype, null);
exports.ESMLoader = ESMLoader;
let emittedExperimentalWarning = false;
/**
* A loader 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, though separate instances of this
* class might be instantiated as part of bootstrap for other purposes.
* @param {boolean} useCustomLoadersIfPresent If the user has provided loaders via the --loader flag, use them.
* @returns {DefaultModuleLoader | CustomizedModuleLoader}
*/
function createModuleLoader(useCustomLoadersIfPresent = true) {
if (useCustomLoadersIfPresent) {
const userLoaderPaths = getOptionValue('--experimental-loader');
if (userLoaderPaths.length > 0) {
if (!emittedExperimentalWarning) {
emitExperimentalWarning('Custom ESM Loaders');
emittedExperimentalWarning = true;
}
return new CustomizedModuleLoader();
}
}
return new DefaultModuleLoader();
}
module.exports = {
DefaultModuleLoader,
createModuleLoader,
};
+3 -4
View File
@@ -72,10 +72,9 @@ class ModuleJob {
// so that circular dependencies can't cause a deadlock by two of
// these `link` callbacks depending on each other.
const dependencyJobs = [];
const promises = this.module.link(async (specifier, assertions) => {
const jobPromise = this.loader.getModuleJob(specifier, url, assertions);
ArrayPrototypePush(dependencyJobs, jobPromise);
const job = await jobPromise;
const promises = this.module.link((specifier, assertions) => {
const job = this.loader.getModuleJob(specifier, url, assertions);
ArrayPrototypePush(dependencyJobs, job);
return job.modulePromise;
});
+19 -4
View File
@@ -41,9 +41,10 @@ const preserveSymlinksMain = getOptionValue('--preserve-symlinks-main');
const experimentalNetworkImports =
getOptionValue('--experimental-network-imports');
const typeFlag = getOptionValue('--input-type');
const { URL, pathToFileURL, fileURLToPath } = require('internal/url');
const { URL, pathToFileURL, fileURLToPath, isURL } = require('internal/url');
const {
ERR_INPUT_TYPE_NOT_ALLOWED,
ERR_INVALID_ARG_TYPE,
ERR_INVALID_MODULE_SPECIFIER,
ERR_INVALID_PACKAGE_CONFIG,
ERR_INVALID_PACKAGE_TARGET,
@@ -935,6 +936,18 @@ function checkIfDisallowedImport(specifier, parsed, parsedParentURL) {
}
}
/**
* Validate user-input in `context` supplied by a custom loader.
*/
function throwIfInvalidParentURL(parentURL) {
if (parentURL === undefined) {
return; // Main entry point, so no parent
}
if (typeof parentURL !== 'string' && !isURL(parentURL)) {
throw new ERR_INVALID_ARG_TYPE('parentURL', ['string', 'URL'], parentURL);
}
}
function throwIfUnsupportedURLProtocol(url) {
if (url.protocol !== 'file:' && url.protocol !== 'data:' &&
url.protocol !== 'node:') {
@@ -963,8 +976,9 @@ function throwIfUnsupportedURLScheme(parsed, experimentalNetworkImports) {
}
}
async function defaultResolve(specifier, context = {}) {
function defaultResolve(specifier, context = {}) {
let { parentURL, conditions } = context;
throwIfInvalidParentURL(parentURL);
if (parentURL && policy?.manifest) {
const redirects = policy.manifest.getDependencyMapper(parentURL);
if (redirects) {
@@ -1100,6 +1114,7 @@ module.exports = {
getPackageType,
packageExportsResolve,
packageImportsResolve,
throwIfInvalidParentURL,
};
// cycle
@@ -1109,11 +1124,11 @@ const {
if (policy) {
const $defaultResolve = defaultResolve;
module.exports.defaultResolve = async function defaultResolve(
module.exports.defaultResolve = function defaultResolve(
specifier,
context,
) {
const ret = await $defaultResolve(specifier, context);
const ret = $defaultResolve(specifier, context);
// This is a preflight check to avoid data exfiltration by query params etc.
policy.manifest.mightAllow(ret.url, () =>
new ERR_MANIFEST_DEPENDENCY_MISSING(
@@ -0,0 +1,25 @@
// This file contains the definition for the constant values that must be
// available to both the main thread and the loader thread.
'use strict';
/*
The shared memory area is divided in 1 32-bit long section. It has to be 32-bit long as
`Atomics.notify` only works with `Int32Array` objects.
--32-bits--
^
|
|
WORKER_TO_MAIN_THREAD_NOTIFICATION
WORKER_TO_MAIN_THREAD_NOTIFICATION is only used to send notifications, its value is going to
increase every time the worker sends a notification to the main thread.
*/
module.exports = {
WORKER_TO_MAIN_THREAD_NOTIFICATION: 0,
SHARED_MEMORY_BYTE_LENGTH: 1 * 4,
};
+66 -3
View File
@@ -1,6 +1,8 @@
'use strict';
const {
ArrayIsArray,
PromisePrototypeThen,
SafeSet,
SafeWeakMap,
ObjectFreeze,
@@ -10,9 +12,9 @@ const {
ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING,
ERR_INVALID_ARG_VALUE,
} = require('internal/errors').codes;
const { getOptionValue } = require('internal/options');
const { pathToFileURL } = require('internal/url');
const { kEmptyObject } = require('internal/util');
const {
setImportModuleDynamicallyCallback,
setInitializeImportMetaObjectCallback,
@@ -73,7 +75,7 @@ function initializeImportMetaObject(wrap, meta) {
if (callbackMap.has(wrap)) {
const { initializeImportMeta } = callbackMap.get(wrap);
if (initializeImportMeta !== undefined) {
initializeImportMeta(meta, getModuleFromWrap(wrap) || wrap);
meta = initializeImportMeta(meta, getModuleFromWrap(wrap) || wrap);
}
}
}
@@ -97,9 +99,70 @@ function initializeESM() {
setImportModuleDynamicallyCallback(importModuleDynamicallyCallback);
}
async function initializeHooks() {
const customLoaderPaths = getOptionValue('--experimental-loader');
let cwd;
try {
// `process.cwd()` can fail if the parent directory is deleted while the process runs.
cwd = process.cwd() + '/';
} catch {
cwd = '/';
}
const { Hooks } = require('internal/modules/esm/hooks');
const hooks = new Hooks();
const { DefaultModuleLoader } = require('internal/modules/esm/loader');
class ModuleLoader extends DefaultModuleLoader {
loaderType = 'internal';
async #getModuleJob(specifier, parentURL, importAssertions) {
const resolveResult = await hooks.resolve(specifier, parentURL, importAssertions);
return this.getJobFromResolveResult(resolveResult, parentURL, importAssertions);
}
getModuleJob(specifier, parentURL, importAssertions) {
const jobPromise = this.#getModuleJob(specifier, parentURL, importAssertions);
return {
run() {
return PromisePrototypeThen(jobPromise, (job) => job.run());
},
get modulePromise() {
return PromisePrototypeThen(jobPromise, (job) => job.modulePromise);
},
get linked() {
return PromisePrototypeThen(jobPromise, (job) => job.linked);
},
};
}
load(url, context) { return hooks.load(url, context); }
}
const privateModuleLoader = new ModuleLoader();
const parentURL = pathToFileURL(cwd).href;
for (let i = 0; i < customLoaderPaths.length; i++) {
const customLoaderPath = customLoaderPaths[i];
// Importation must be handled by internal loader to avoid polluting user-land
const keyedExportsSublist = await privateModuleLoader.import(
[customLoaderPath], // Import can handle multiple paths, but custom loaders must be sequential
parentURL,
kEmptyObject,
);
hooks.addCustomLoaders(keyedExportsSublist);
}
const preloadScripts = hooks.initializeGlobalPreload();
return { __proto__: null, hooks, preloadScripts };
}
module.exports = {
setCallbackForWrap,
initializeESM,
initializeHooks,
getDefaultConditions,
getConditionsSet,
};
+210
View File
@@ -0,0 +1,210 @@
'use strict';
const {
DataViewPrototypeGetBuffer,
Int32Array,
PromisePrototypeThen,
ReflectApply,
SafeSet,
TypedArrayPrototypeGetBuffer,
globalThis: {
Atomics: {
add: AtomicsAdd,
notify: AtomicsNotify,
},
},
} = primordials;
const assert = require('internal/assert');
const { clearImmediate, setImmediate } = require('timers');
const {
hasUncaughtExceptionCaptureCallback,
} = require('internal/process/execution');
const {
isArrayBuffer,
isDataView,
isTypedArray,
} = require('util/types');
const { receiveMessageOnPort } = require('internal/worker/io');
const {
WORKER_TO_MAIN_THREAD_NOTIFICATION,
} = require('internal/modules/esm/shared_constants');
const { initializeESM, initializeHooks } = require('internal/modules/esm/utils');
function transferArrayBuffer(hasError, source) {
if (hasError || source == null) return;
if (isArrayBuffer(source)) return [source];
if (isTypedArray(source)) return [TypedArrayPrototypeGetBuffer(source)];
if (isDataView(source)) return [DataViewPrototypeGetBuffer(source)];
}
function wrapMessage(status, body) {
if (status === 'success' || body === null || typeof body !== 'object') {
return { status, body };
}
let serialized;
let serializationFailed;
try {
const { serializeError } = require('internal/error_serdes');
serialized = serializeError(body);
} catch {
serializationFailed = true;
}
return {
status,
body: {
serialized,
serializationFailed,
},
};
}
async function customizedModuleWorker(lock, syncCommPort, errorHandler) {
let hooks, preloadScripts, initializationError;
let hasInitializationError = false;
try {
initializeESM();
const initResult = await initializeHooks();
hooks = initResult.hooks;
preloadScripts = initResult.preloadScripts;
} catch (exception) {
// If there was an error while parsing and executing a user loader, for example if because a
// loader contained a syntax error, then we need to send the error to the main thread so it can
// be thrown and printed.
hasInitializationError = true;
initializationError = exception;
}
syncCommPort.on('message', handleMessage);
if (hasInitializationError) {
syncCommPort.postMessage(wrapMessage('error', initializationError));
} else {
syncCommPort.postMessage(wrapMessage('success', { preloadScripts }), preloadScripts.map(({ port }) => port));
}
// We're ready, so unlock the main thread.
AtomicsAdd(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 1);
AtomicsNotify(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION);
let immediate;
function checkForMessages() {
immediate = setImmediate(checkForMessages).unref();
// We need to let the event loop tick a few times to give the main thread a chance to send
// follow-up messages.
const response = receiveMessageOnPort(syncCommPort);
if (response !== undefined) {
PromisePrototypeThen(handleMessage(response.message), undefined, errorHandler);
}
}
const unsettledResponsePorts = new SafeSet();
process.on('beforeExit', () => {
for (const port of unsettledResponsePorts) {
port.postMessage(wrapMessage('never-settle'));
}
unsettledResponsePorts.clear();
AtomicsAdd(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 1);
AtomicsNotify(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION);
// Attach back the event handler.
syncCommPort.on('message', handleMessage);
// Also check synchronously for a message, in case it's already there.
clearImmediate(immediate);
checkForMessages();
// We don't need the sync check after this tick, as we already have added the event handler.
clearImmediate(immediate);
// Add some work for next tick so the worker cannot exit.
setImmediate(() => {});
});
async function handleMessage({ method, args, port }) {
// Each potential exception needs to be caught individually so that the correct error is sent to
// the main thread.
let hasError = false;
let shouldRemoveGlobalErrorHandler = false;
assert(typeof hooks[method] === 'function');
if (port == null && !hasUncaughtExceptionCaptureCallback()) {
// When receiving sync messages, we want to unlock the main thread when there's an exception.
process.on('uncaughtException', errorHandler);
shouldRemoveGlobalErrorHandler = true;
}
// We are about to yield the execution with `await ReflectApply` below. In case the code
// following the `await` never runs, we remove the message handler so the `beforeExit` event
// can be triggered.
syncCommPort.off('message', handleMessage);
// We keep checking for new messages to not miss any.
clearImmediate(immediate);
immediate = setImmediate(checkForMessages).unref();
unsettledResponsePorts.add(port ?? syncCommPort);
let response;
try {
response = await ReflectApply(hooks[method], hooks, args);
} catch (exception) {
hasError = true;
response = exception;
}
unsettledResponsePorts.delete(port ?? syncCommPort);
// Send the method response (or exception) to the main thread.
try {
(port ?? syncCommPort).postMessage(
wrapMessage(hasError ? 'error' : 'success', response),
transferArrayBuffer(hasError, response?.source),
);
} catch (exception) {
// Or send the exception thrown when trying to send the response.
(port ?? syncCommPort).postMessage(wrapMessage('error', exception));
}
AtomicsAdd(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 1);
AtomicsNotify(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION);
if (shouldRemoveGlobalErrorHandler) {
process.off('uncaughtException', errorHandler);
}
syncCommPort.off('message', handleMessage);
// We keep checking for new messages to not miss any.
clearImmediate(immediate);
immediate = setImmediate(checkForMessages).unref();
}
}
/**
* ! Run everything possible within this function so errors get reported.
*/
module.exports = function setupModuleWorker(workerData, syncCommPort) {
const lock = new Int32Array(workerData.lock);
function errorHandler(err, origin = 'unhandledRejection') {
AtomicsAdd(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 1);
AtomicsNotify(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION);
process.off('uncaughtException', errorHandler);
if (hasUncaughtExceptionCaptureCallback()) {
process._fatalException(err);
return;
}
internalBinding('errors').triggerUncaughtException(
err,
origin === 'unhandledRejection',
);
}
return PromisePrototypeThen(
customizedModuleWorker(lock, syncCommPort, errorHandler),
undefined,
errorHandler,
);
};
+37 -94
View File
@@ -1,105 +1,48 @@
'use strict';
const {
ArrayIsArray,
ArrayPrototypePushApply,
} = primordials;
const { ESMLoader } = require('internal/modules/esm/loader');
const { createModuleLoader } = require('internal/modules/esm/loader');
const { getOptionValue } = require('internal/options');
const {
hasUncaughtExceptionCaptureCallback,
} = require('internal/process/execution');
const { pathToFileURL } = require('internal/url');
const { kEmptyObject } = require('internal/util');
const esmLoader = new ESMLoader();
exports.esmLoader = esmLoader;
let esmLoader;
// Module.runMain() causes loadESM() to re-run (which it should do); however, this should NOT cause
// ESM to be re-initialized; doing so causes duplicate custom loaders to be added to the public
// esmLoader.
let isESMInitialized = false;
/**
* Causes side-effects: user-defined loader hooks are added to esmLoader.
* @returns {void}
*/
async function initializeLoader() {
if (isESMInitialized) { return; }
const { getOptionValue } = require('internal/options');
const customLoaders = getOptionValue('--experimental-loader');
const preloadModules = getOptionValue('--import');
let cwd;
try {
cwd = process.cwd() + '/';
} catch {
cwd = '/';
}
const internalEsmLoader = new ESMLoader();
const allLoaders = [];
const parentURL = pathToFileURL(cwd).href;
for (let i = 0; i < customLoaders.length; i++) {
const customLoader = customLoaders[i];
// Importation must be handled by internal loader to avoid polluting user-land
const keyedExportsSublist = await internalEsmLoader.import(
[customLoader],
parentURL,
kEmptyObject,
);
internalEsmLoader.addCustomLoaders(keyedExportsSublist);
ArrayPrototypePushApply(allLoaders, keyedExportsSublist);
}
// Hooks must then be added to external/public loader
// (so they're triggered in userland)
esmLoader.addCustomLoaders(allLoaders);
esmLoader.preload();
// Preload after loaders are added so they can be used
if (preloadModules?.length) {
await loadModulesInIsolation(parentURL, preloadModules, allLoaders);
}
isESMInitialized = true;
}
function loadModulesInIsolation(parentURL, specifiers, loaders = []) {
if (!ArrayIsArray(specifiers) || specifiers.length === 0) { return; }
// 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();
internalEsmLoader.addCustomLoaders(loaders);
internalEsmLoader.preload();
// Importation must be handled by internal loader to avoid polluting userland
return internalEsmLoader.import(
specifiers,
parentURL,
kEmptyObject,
);
}
exports.loadESM = async function loadESM(callback) {
try {
await initializeLoader();
await callback(esmLoader);
} catch (err) {
if (hasUncaughtExceptionCaptureCallback()) {
process._fatalException(err);
return;
module.exports = {
get esmLoader() {
return esmLoader ??= createModuleLoader(true);
},
async loadESM(callback) {
esmLoader ??= createModuleLoader(true);
try {
const userImports = getOptionValue('--import');
if (userImports.length > 0) {
let cwd;
try {
// `process.cwd()` can fail if the parent directory is deleted while the process runs.
cwd = process.cwd() + '/';
} catch {
cwd = '/';
}
const parentURL = pathToFileURL(cwd).href;
await esmLoader.import(
userImports,
parentURL,
kEmptyObject,
);
}
await callback(esmLoader);
} catch (err) {
if (hasUncaughtExceptionCaptureCallback()) {
process._fatalException(err);
return;
}
internalBinding('errors').triggerUncaughtException(
err,
true, /* fromPromise */
);
}
internalBinding('errors').triggerUncaughtException(
err,
true, /* fromPromise */
);
}
},
};
+32 -2
View File
@@ -45,6 +45,7 @@ const { getOptionValue } = require('internal/options');
const workerIo = require('internal/worker/io');
const {
drainMessagePort,
receiveMessageOnPort,
MessageChannel,
messageTypes,
kPort,
@@ -82,6 +83,7 @@ const kOnCouldNotSerializeErr = Symbol('kOnCouldNotSerializeErr');
const kOnErrorMessage = Symbol('kOnErrorMessage');
const kParentSideStdio = Symbol('kParentSideStdio');
const kLoopStartTime = Symbol('kLoopStartTime');
const kIsInternal = Symbol('kIsInternal');
const kIsOnline = Symbol('kIsOnline');
const SHARE_ENV = SymbolFor('nodejs.worker_threads.SHARE_ENV');
@@ -128,7 +130,13 @@ function assignEnvironmentData(data) {
class Worker extends EventEmitter {
constructor(filename, options = kEmptyObject) {
super();
debug(`[${threadId}] create new worker`, filename, options);
const isInternal = arguments[2] === kIsInternal;
debug(
`[${threadId}] create new worker`,
filename,
options,
`isInternal: ${isInternal}`,
);
if (options.execArgv)
validateArray(options.execArgv, 'options.execArgv');
@@ -139,7 +147,10 @@ class Worker extends EventEmitter {
}
let url, doEval;
if (options.eval) {
if (isInternal) {
doEval = 'internal';
url = `node:${filename}`;
} else if (options.eval) {
if (typeof filename !== 'string') {
throw new ERR_INVALID_ARG_VALUE(
'options.eval',
@@ -195,12 +206,14 @@ class Worker extends EventEmitter {
name = StringPrototypeTrim(options.name);
}
debug('instantiating Worker.', `url: ${url}`, `doEval: ${doEval}`);
// Set up the C++ handle for the worker, as well as some internal wiring.
this[kHandle] = new WorkerImpl(url,
env === process.env ? null : env,
options.execArgv,
parseResourceLimits(options.resourceLimits),
!!(options.trackUnmanagedFds ?? true),
isInternal,
name);
if (this[kHandle].invalidExecArgv) {
throw new ERR_WORKER_INVALID_EXEC_ARGV(this[kHandle].invalidExecArgv);
@@ -252,6 +265,7 @@ class Worker extends EventEmitter {
type: messageTypes.LOAD_SCRIPT,
filename,
doEval,
isInternal,
cwdCounter: cwdCounter || workerIo.sharedCwdCounter,
workerData: options.workerData,
environmentData,
@@ -441,6 +455,20 @@ class Worker extends EventEmitter {
}
}
/**
* A worker which has an internal module for entry point (e.g. internal/module/esm/worker).
* Internal workers bypass the permission model.
*/
class InternalWorker extends Worker {
constructor(filename, options) {
super(filename, options, kIsInternal);
}
receiveMessageSync() {
return receiveMessageOnPort(this[kPublicPort]);
}
}
function pipeWithoutWarning(source, dest) {
const sourceMaxListeners = source._maxListeners;
const destMaxListeners = dest._maxListeners;
@@ -505,6 +533,7 @@ function eventLoopUtilization(util1, util2) {
module.exports = {
ownsProcessState,
kIsOnline,
isMainThread,
SHARE_ENV,
resourceLimits:
@@ -513,5 +542,6 @@ module.exports = {
getEnvironmentData,
assignEnvironmentData,
threadId,
InternalWorker,
Worker,
};
+8 -4
View File
@@ -459,8 +459,12 @@ Worker::~Worker() {
void Worker::New(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
THROW_IF_INSUFFICIENT_PERMISSIONS(
env, permission::PermissionScope::kWorkerThreads, "");
auto is_internal = args[5];
CHECK(is_internal->IsBoolean());
if (is_internal->IsFalse()) {
THROW_IF_INSUFFICIENT_PERMISSIONS(
env, permission::PermissionScope::kWorkerThreads, "");
}
Isolate* isolate = args.GetIsolate();
CHECK(args.IsConstructCall());
@@ -484,9 +488,9 @@ void Worker::New(const FunctionCallbackInfo<Value>& args) {
url.append(value.out(), value.length());
}
if (!args[5]->IsNullOrUndefined()) {
if (!args[6]->IsNullOrUndefined()) {
Utf8Value value(
isolate, args[5]->ToString(env->context()).FromMaybe(Local<String>()));
isolate, args[6]->ToString(env->context()).FromMaybe(Local<String>()));
name.append(value.out(), value.length());
}
+26 -30
View File
@@ -1,36 +1,32 @@
// Flags: --experimental-import-meta-resolve
import { mustCall } from '../common/index.mjs';
import '../common/index.mjs';
import assert from 'assert';
const dirname = import.meta.url.slice(0, import.meta.url.lastIndexOf('/') + 1);
const fixtures = dirname.slice(0, dirname.lastIndexOf('/', dirname.length - 2) + 1) + 'fixtures/';
(async () => {
assert.strictEqual(await import.meta.resolve('./test-esm-import-meta.mjs'),
dirname + 'test-esm-import-meta.mjs');
try {
await import.meta.resolve('./notfound.mjs');
assert.fail();
} catch (e) {
assert.strictEqual(e.code, 'ERR_MODULE_NOT_FOUND');
}
assert.strictEqual(
await import.meta.resolve('../fixtures/empty-with-bom.txt'),
fixtures + 'empty-with-bom.txt');
assert.strictEqual(await import.meta.resolve('../fixtures/'), fixtures);
assert.strictEqual(
await import.meta.resolve('../fixtures/', import.meta.url),
fixtures);
assert.strictEqual(
await import.meta.resolve('../fixtures/', new URL(import.meta.url)),
fixtures);
await Promise.all(
[[], {}, Symbol(), 0, 1, 1n, 1.1, () => {}, true, false].map((arg) =>
assert.rejects(import.meta.resolve('../fixtures/', arg), {
code: 'ERR_INVALID_ARG_TYPE',
})
)
);
assert.strictEqual(await import.meta.resolve('baz/', fixtures),
fixtures + 'node_modules/baz/');
})().then(mustCall());
assert.strictEqual(import.meta.resolve('./test-esm-import-meta.mjs'),
dirname + 'test-esm-import-meta.mjs');
try {
import.meta.resolve('./notfound.mjs');
assert.fail();
} catch (e) {
assert.strictEqual(e.code, 'ERR_MODULE_NOT_FOUND');
}
assert.strictEqual(
import.meta.resolve('../fixtures/empty-with-bom.txt'),
fixtures + 'empty-with-bom.txt');
assert.strictEqual(import.meta.resolve('../fixtures/'), fixtures);
assert.strictEqual(
import.meta.resolve('../fixtures/', import.meta.url),
fixtures);
assert.strictEqual(
import.meta.resolve('../fixtures/', new URL(import.meta.url)),
fixtures);
[[], {}, Symbol(), 0, 1, 1n, 1.1, () => {}, true, false].map((arg) =>
assert.throws(() => import.meta.resolve('../fixtures/', arg), {
code: 'ERR_INVALID_ARG_TYPE',
})
);
assert.strictEqual(import.meta.resolve('baz/', fixtures),
fixtures + 'node_modules/baz/');
+2 -2
View File
@@ -4,7 +4,7 @@
require('../common');
const { strictEqual, throws } = require('assert');
const { ESMLoader } = require('internal/modules/esm/loader');
const { createModuleLoader } = require('internal/modules/esm/loader');
const ModuleMap = require('internal/modules/esm/module_map');
const ModuleJob = require('internal/modules/esm/module_job');
const createDynamicModule = require(
@@ -16,7 +16,7 @@ const jsonModuleDataUrl = 'data:application/json,""';
const stubJsModule = createDynamicModule([], ['default'], jsModuleDataUrl);
const stubJsonModule = createDynamicModule([], ['default'], jsonModuleDataUrl);
const loader = new ESMLoader();
const loader = createModuleLoader(false);
const jsModuleJob = new ModuleJob(loader, stubJsModule.module, undefined,
() => new Promise(() => {}));
const jsonModuleJob = new ModuleJob(loader, stubJsonModule.module,
+2 -2
View File
@@ -10,8 +10,8 @@ const {
defaultResolve: resolve
} = require('internal/modules/esm/resolve');
assert.rejects(
resolve('target'),
assert.throws(
() => resolve('target'),
{
code: 'ERR_MODULE_NOT_FOUND',
name: 'Error',
@@ -13,7 +13,7 @@ describe('ESM: loader with syntax error', { concurrency: true }, () => {
path('print-error-message.js'),
]);
match(stderr, /SyntaxError:/);
match(stderr, /SyntaxError \[Error\]:/);
ok(!stderr.includes('Bad command or file name'));
notStrictEqual(code, 0);
});
+10 -10
View File
@@ -37,16 +37,16 @@ try {
* ensure that resolving by full path does not return the format
* with the defaultResolver
*/
await Promise.all([
[
[ '/es-modules/package-type-module/index.js', 'module' ],
[ '/es-modules/package-type-commonjs/index.js', 'commonjs' ],
[ '/es-modules/package-without-type/index.js', 'commonjs' ],
[ '/es-modules/package-without-pjson/index.js', 'commonjs' ],
].map(async ([ testScript, expectedType ]) => {
].forEach(([ testScript, expectedType ]) => {
const resolvedPath = path.resolve(fixtures.path(testScript));
const resolveResult = await resolve(url.pathToFileURL(resolvedPath));
const resolveResult = resolve(url.pathToFileURL(resolvedPath));
assert.strictEqual(resolveResult.format, expectedType);
}));
});
/**
* create a test module and try to resolve it by module name.
@@ -85,7 +85,7 @@ try {
fs.writeFileSync(script,
'export function esm-resolve-tester() {return 42}');
const resolveResult = await resolve(`${moduleName}`);
const resolveResult = resolve(`${moduleName}`);
assert.strictEqual(resolveResult.format, expectedResolvedType);
fs.rmSync(nmDir, { recursive: true, force: true });
@@ -168,14 +168,14 @@ try {
);
// test the resolve
const resolveResult = await resolve(`${moduleName}`);
const resolveResult = resolve(`${moduleName}`);
assert.strictEqual(resolveResult.format, 'module');
assert.ok(resolveResult.url.includes('my-dual-package/es/index.js'));
}
// TestParameters are ModuleName, mainRequireScript, mainImportScript,
// mainPackageType, subdirPkgJsonType, expectedResolvedFormat, mainSuffix
await Promise.all([
[
[ 'mjs-mod-mod', 'index.js', 'index.mjs', 'module', 'module', 'module'],
[ 'mjs-com-com', 'idx.js', 'idx.mjs', 'commonjs', 'commonjs', 'module'],
[ 'mjs-mod-com', 'index.js', 'imp.mjs', 'module', 'commonjs', 'module'],
@@ -186,7 +186,7 @@ try {
[ 'hmod', 'index.js', 'imp.js', 'commonjs', 'module', 'module', '#Key'],
[ 'qhmod', 'index.js', 'imp.js', 'commonjs', 'module', 'module', '?k=v#h'],
[ 'ts-mod-com', 'index.js', 'imp.ts', 'module', 'commonjs', undefined],
].map(async (testVariant) => {
].forEach((testVariant) => {
const [
moduleName,
mainRequireScript,
@@ -234,10 +234,10 @@ try {
);
// test the resolve
const resolveResult = await resolve(`${moduleName}`);
const resolveResult = resolve(`${moduleName}`);
assert.strictEqual(resolveResult.format, expectedResolvedFormat);
assert.ok(resolveResult.url.endsWith(`${moduleName}/subdir/${mainImportScript}${mainSuffix}`));
}));
});
} finally {
process.chdir(previousCwd);
+5 -10
View File
@@ -2,6 +2,7 @@
// node --loader ./test/fixtures/es-module-loaders/hooks-input.mjs ./test/fixtures/es-modules/json-modules.mjs
import assert from 'assert';
import { writeSync } from 'fs';
import { readFile } from 'fs/promises';
import { fileURLToPath } from 'url';
@@ -17,15 +18,12 @@ export async function resolve(specifier, context, next) {
url = new URL(specifier).href;
assert.match(specifier, /json-modules\.mjs$/);
assert.strictEqual(context.parentURL, undefined);
assert.deepStrictEqual(context.importAssertions, {
__proto__: null,
});
assert.deepStrictEqual(context.importAssertions, {});
} else if (resolveCalls === 2) {
url = new URL(specifier, context.parentURL).href;
assert.match(specifier, /experimental\.json$/);
assert.match(context.parentURL, /json-modules\.mjs$/);
assert.deepStrictEqual(context.importAssertions, {
__proto__: null,
type: 'json',
});
}
@@ -45,7 +43,7 @@ export async function resolve(specifier, context, next) {
shortCircuit: true,
}
console.log(JSON.stringify(returnValue)); // For the test to validate when it parses stdout
writeSync(1, JSON.stringify(returnValue) + '\n'); // For the test to validate when it parses stdout
return returnValue;
}
@@ -57,14 +55,11 @@ export async function load(url, context, next) {
if (loadCalls === 1) {
assert.match(url, /json-modules\.mjs$/);
assert.deepStrictEqual(context.importAssertions, {
__proto__: null,
});
assert.deepStrictEqual(context.importAssertions, {});
format = 'module';
} else if (loadCalls === 2) {
assert.match(url, /experimental\.json$/);
assert.deepStrictEqual(context.importAssertions, {
__proto__: null,
type: 'json',
});
format = 'json';
@@ -85,7 +80,7 @@ export async function load(url, context, next) {
shortCircuit: true,
};
console.log(JSON.stringify(returnValue)); // For the test to validate when it parses stdout
writeSync(1, JSON.stringify(returnValue) + '\n'); // For the test to validate when it parses stdout
return returnValue;
}
+2 -4
View File
@@ -1,15 +1,13 @@
import { strictEqual } from "node:assert";
import { isMainThread, workerData, parentPort } from "node:worker_threads";
// TODO(aduh95): switch this to `false` when loader hooks are run on a separate thread.
strictEqual(isMainThread, true);
strictEqual(isMainThread, false);
// We want to make sure that internals are not leaked on the public module:
strictEqual(workerData, null);
strictEqual(parentPort, null);
// TODO(aduh95): switch to `"undefined"` when loader hooks are run on a separate thread.
// We don't want `import.meta.resolve` being available from loaders
// as the sync implementation is not compatible with calling async
// functions on the same thread.
strictEqual(typeof import.meta.resolve, 'function');
strictEqual(typeof import.meta.resolve, 'undefined');
+1 -1
View File
@@ -3,7 +3,7 @@ export async function load(url, context, next) {
// resolution from follow-up loaders. It wouldn't be a problem
// in real life because loaders aren't supposed to break the
// resolution, but the ones used in our tests do, for convenience.
if (url.includes('loader')) {
if (url === 'node:fs' || url.includes('loader')) {
return next(url);
}
+1 -1
View File
@@ -3,7 +3,7 @@ export async function load(url, context, next) {
// resolution from follow-up loaders. It wouldn't be a problem
// in real life because loaders aren't supposed to break the
// resolution, but the ones used in our tests do, for convenience.
if (url.includes('loader')) {
if (url === 'node:fs' || url.includes('loader')) {
return next(url);
}
+5 -2
View File
@@ -1,12 +1,15 @@
import { writeSync } from 'node:fs';
export async function load(url, context, next) {
// This check is needed to make sure that we don't prevent the
// resolution from follow-up loaders. It wouldn't be a problem
// in real life because loaders aren't supposed to break the
// resolution, but the ones used in our tests do, for convenience.
if (url.includes('loader')) {
if (url === 'node:fs' || url.includes('loader')) {
return next(url);
}
console.log('load passthru'); // This log is deliberate
writeSync(1, 'load passthru' + '\n'); // Signal that this specific hook ran
return next(url);
}
@@ -1,4 +1,7 @@
import { writeSync } from 'node:fs';
export async function load(url, context, next) {
console.log(context.foo); // This log is deliberate
writeSync(1, context.foo + '\n'); // Expose actual value the hook was called with
return next(url, context);
}
+9 -6
View File
@@ -1,10 +1,13 @@
import { writeSync } from 'node:fs';
import { inspect } from 'node:util'
export async function resolve(...args) {
console.log(`resolve arg count: ${args.length}`);
console.log({
writeSync(1, `resolve arg count: ${args.length}\n`);
writeSync(1, inspect({
specifier: args[0],
context: args[1],
next: args[2],
});
}) + '\n');
return {
shortCircuit: true,
@@ -13,12 +16,12 @@ export async function resolve(...args) {
}
export async function load(...args) {
console.log(`load arg count: ${args.length}`);
console.log({
writeSync(1, `load arg count: ${args.length}\n`);
writeSync(1, inspect({
url: args[0],
context: args[1],
next: args[2],
});
}) + '\n');
return {
format: 'module',
+6 -3
View File
@@ -1,14 +1,17 @@
import { writeSync } from 'node:fs';
export async function resolve(specifier, context, next) {
// This check is needed to make sure that we don't prevent the
// resolution from follow-up loaders. It wouldn't be a problem
// in real life because loaders aren't supposed to break the
// resolution, but the ones used in our tests do, for convenience.
if (specifier.includes('loader')) {
if (specifier === 'node:fs' || specifier.includes('loader')) {
return next(specifier);
}
console.log('resolve 42'); // This log is deliberate
console.log('next<HookName>:', next.name); // This log is deliberate
writeSync(1, 'resolve 42' + '\n'); // Signal that this specific hook ran
writeSync(1, `next<HookName>: ${next.name}\n`); // Expose actual value the hook was called with
return next('file:///42.mjs');
}
+5 -2
View File
@@ -1,12 +1,15 @@
import { writeSync } from 'node:fs';
export async function resolve(specifier, context, next) {
// This check is needed to make sure that we don't prevent the
// resolution from follow-up loaders. It wouldn't be a problem
// in real life because loaders aren't supposed to break the
// resolution, but the ones used in our tests do, for convenience.
if (specifier.includes('loader')) {
if (specifier === 'node:fs' || specifier.includes('loader')) {
return next(specifier);
}
console.log('resolve foo'); // This log is deliberate
writeSync(1, 'resolve foo' + '\n'); // Signal that this specific hook ran
return next('file:///foo.mjs');
}
@@ -3,7 +3,7 @@ export async function resolve(specifier, context, next) {
// resolution from follow-up loaders. It wouldn't be a problem
// in real life because loaders aren't supposed to break the
// resolution, but the ones used in our tests do, for convenience.
if (specifier.includes('loader')) {
if (specifier === 'node:fs' || specifier.includes('loader')) {
return next(specifier);
}
@@ -3,7 +3,7 @@ export async function resolve(url, context, next) {
// resolution from follow-up loaders. It wouldn't be a problem
// in real life because loaders aren't supposed to break the
// resolution, but the ones used in our tests do, for convenience.
if (url.includes('loader')) {
if (url === 'node:fs' || url.includes('loader')) {
return next(url);
}
@@ -1,12 +1,15 @@
import { writeSync } from 'node:fs';
export async function resolve(specifier, context, next) {
// This check is needed to make sure that we don't prevent the
// resolution from follow-up loaders. It wouldn't be a problem
// in real life because loaders aren't supposed to break the
// resolution, but the ones used in our tests do, for convenience.
if (specifier.includes('loader')) {
if (specifier === 'node:fs' || specifier.includes('loader')) {
return next(specifier);
}
console.log('resolve passthru'); // This log is deliberate
writeSync(1, 'resolve passthru' + '\n'); // Signal that this specific hook ran
return next(specifier);
}
@@ -1,4 +1,7 @@
import { writeSync } from 'node:fs';
export async function resolve(specifier, context, next) {
console.log(context.foo); // This log is deliberate
writeSync(1, context.foo + '\n'); // Expose actual value the hook was called with
return next(specifier, context);
}
@@ -3,7 +3,7 @@ export async function resolve(specifier, context, next) {
// resolution from follow-up loaders. It wouldn't be a problem
// in real life because loaders aren't supposed to break the
// resolution, but the ones used in our tests do, for convenience.
if (specifier.includes('loader')) {
if (specifier === 'node:fs' || specifier.includes('loader')) {
return next(specifier);
}
@@ -1,4 +1,10 @@
import { writeSync } from 'node:fs';
import { inspect } from 'node:util';
export async function resolve(specifier, context, nextResolve) {
console.log(`loader-a`, {specifier});
if (specifier.startsWith('node:')) {
return nextResolve(specifier);
}
writeSync(1, `loader-a ${inspect({specifier})}\n`);
return nextResolve(specifier.replace(/^xxx\//, `./`));
}
@@ -1,4 +1,7 @@
import { writeSync } from 'node:fs';
import { inspect } from 'node:util';
export async function resolve(specifier, context, nextResolve) {
console.log(`loader-b`, {specifier});
writeSync(1, `loader-b ${inspect({specifier})}\n`);
return nextResolve(specifier.replace(/^yyy\//, `./`));
}
@@ -1,5 +1,5 @@
console.log('should be output');
await import.meta.resolve('never-settle-resolve');
import.meta.resolve('never-settle-resolve');
console.log('should not be output');
+2 -8
View File
@@ -1,10 +1,4 @@
import { strictEqual } from 'assert';
(async () => {
const resolved = await import.meta.resolve('pkgexports-sugar');
strictEqual(typeof resolved, 'string');
})()
.catch((e) => {
console.error(e);
process.exit(1);
});
const resolved = import.meta.resolve('pkgexports-sugar');
strictEqual(typeof resolved, 'string');
+2 -2
View File
@@ -1,7 +1,7 @@
import { runMain } from 'node:module';
try { await import.meta.resolve('doesnt-matter.mjs') } catch {}
try { import.meta.resolve('doesnt-matter.mjs') } catch {}
runMain();
try { await import.meta.resolve('doesnt-matter.mjs') } catch {}
try { import.meta.resolve('doesnt-matter.mjs') } catch {}