Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion lib/internal/modules/esm/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,15 @@ class ModuleLoader {
return this.#getOrCreateModuleJobAfterResolve(parentURL, resolveResult, request, requestType);
}

#canUseImportCache(specifier, parentURL, phase, isEntryPoint) {
return phase === kEvaluationPhase &&
!isEntryPoint &&
!onImport.hasSubscribers &&
typeof specifier === 'string' &&
typeof parentURL === 'string' &&
syncResolveHooks.length === 0;
}

/**
* This method is usually called indirectly as part of the loading processes.
* Use directly with caution.
Expand All @@ -520,6 +529,16 @@ class ModuleLoader {
* @returns {Promise<ModuleExports>}
*/
async import(specifier, parentURL, importAttributes, phase = kEvaluationPhase, isEntryPoint = false) {
if (this.#canUseImportCache(specifier, parentURL, phase, isEntryPoint)) {
const requestKey = this.#resolveCache.serializeKey(specifier, importAttributes);
const resolved = this.#resolveCache.get(requestKey, parentURL);
if (resolved !== undefined) {
const job = this.loadCache.get(resolved.url, importAttributes.type);
if (job?.namespace !== undefined) {
return job.namespace;
}
}
}
// tracePromise() ignores the context when there are no subscribers, so only
// create it when there are: a `{ __proto__: null }` literal is created in
// dictionary mode, and import() can be called on a hot path.
Expand All @@ -537,7 +556,12 @@ class ModuleLoader {
return module.getModuleSourceObject();
}
const { module } = await moduleJob.run(isEntryPoint);
return module.getNamespace();
const namespace = module.getNamespace();
// Skip async graphs to avoid caching in-flight TLA modules before they settle.
if (!module.hasAsyncGraph) {
moduleJob.namespace = namespace;
}
return namespace;
}, traceContext);
}

Expand Down
1 change: 1 addition & 0 deletions lib/internal/modules/esm/module_job.js
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,7 @@ class ModuleJobBase {
this.inspectBrk = inspectBrk;

this.url = url;
this.namespace = undefined;
}

/**
Expand Down
4 changes: 4 additions & 0 deletions lib/internal/modules/esm/module_map.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ let debug = require('internal/util/debuglog').debuglog('esm', (fn) => {
debug = fn;
});
const { ERR_INVALID_ARG_TYPE } = require('internal/errors').codes;
const { kEmptyObject } = require('internal/util');
const { validateString } = require('internal/validators');

/**
Expand All @@ -34,6 +35,9 @@ class ResolveCache extends SafeMap {
* @returns {string}
*/
serializeKey(specifier, importAttributes) {
if (importAttributes === kEmptyObject) {
return specifier + '::';
}
// To serialize the ModuleRequest (specifier + list of import attributes),
// we need to sort the attributes by key, then stringifying,
// so that different import statements with the same attributes are always treated
Expand Down
32 changes: 24 additions & 8 deletions lib/internal/modules/esm/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
const {
ArrayIsArray,
ObjectFreeze,
SafeMap,
SafeSet,
SafeWeakMap,
Symbol,
Expand Down Expand Up @@ -40,6 +41,7 @@ const {
const { getOptionValue } = require('internal/options');
const {
emitExperimentalWarning,
getLazy,
kEmptyObject,
} = require('internal/util');
const assert = require('internal/assert');
Expand Down Expand Up @@ -203,6 +205,22 @@ function initializeImportMetaObject(symbol, meta, wrap) {
}
}

const getCascadedLoader = getLazy(
() => require('internal/modules/esm/loader').getOrInitializeCascadedLoader(),
);
const scriptReferrerURLCache = new SafeMap();

function getCachedScriptParentURL(referrerName) {
let parentURL = scriptReferrerURLCache.get(referrerName);
if (parentURL === undefined) {
parentURL = normalizeReferrerURL(referrerName);
if (typeof parentURL === 'string') {
scriptReferrerURLCache.set(referrerName, parentURL);
}
}
return parentURL;
}

/**
* Proxy the dynamic import handling to the default loader for source text modules.
* @param {string} specifier - The module specifier string.
Expand All @@ -212,8 +230,7 @@ function initializeImportMetaObject(symbol, meta, wrap) {
* @returns {Promise<import('internal/modules/esm/loader.js').ModuleExports>} - The imported module object.
*/
function defaultImportModuleDynamicallyForModule(specifier, phase, attributes, referrerName) {
const cascadedLoader = require('internal/modules/esm/loader').getOrInitializeCascadedLoader();
return cascadedLoader.import(specifier, referrerName, attributes, phase);
return getCascadedLoader().import(specifier, referrerName, attributes, phase);
}

/**
Expand All @@ -225,9 +242,8 @@ function defaultImportModuleDynamicallyForModule(specifier, phase, attributes, r
* @returns {Promise<import('internal/modules/esm/loader.js').ModuleExports>} - The imported module object.
*/
function defaultImportModuleDynamicallyForScript(specifier, phase, attributes, referrerName) {
const parentURL = normalizeReferrerURL(referrerName);
const cascadedLoader = require('internal/modules/esm/loader').getOrInitializeCascadedLoader();
return cascadedLoader.import(specifier, parentURL, attributes, phase);
const parentURL = getCachedScriptParentURL(referrerName);
return getCascadedLoader().import(specifier, parentURL, attributes, phase);
}

/**
Expand Down Expand Up @@ -257,13 +273,13 @@ function importModuleDynamicallyForEmbedder(specifier, phase, attributes, referr
* @param {symbol} referrerSymbol - Referrer symbol of the registered script, function, module, or contextified object.
* @param {string} specifier - The module specifier string.
* @param {number} phase - The module import phase.
* @param {Record<string, string>} attributes - The import attributes object.
* @param {Record<string, string>|undefined} attributes - The import attributes object, or undefined if empty.
* @param {string|null|undefined} referrerName - name of the referrer.
* @returns {Promise<import('internal/modules/esm/loader.js').ModuleExports>} - The imported module object.
* @throws {ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING} - If the callback function is missing.
*/
async function importModuleDynamicallyCallback(referrerSymbol, specifier, phase, attributes,
referrerName) {
async function importModuleDynamicallyCallback(referrerSymbol, specifier, phase,
attributes = kEmptyObject, referrerName) {
// For user-provided vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER, emit the warning
// and fall back to the default loader.
if (referrerSymbol === vm_dynamic_import_main_context_default) {
Expand Down
8 changes: 6 additions & 2 deletions src/module_wrap.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1171,8 +1171,12 @@ static MaybeLocal<Promise> ImportModuleDynamicallyWithPhase(
return MaybeLocal<Promise>();
}

Local<Object> attributes =
createImportAttributesContainer(realm, isolate, import_attributes, 2);
Local<Value> attributes =
import_attributes->Length() == 0
? Undefined(isolate).As<Value>()
: createImportAttributesContainer(
realm, isolate, import_attributes, 2)
.As<Value>();

Local<Value> import_args[] = {
id,
Expand Down
80 changes: 80 additions & 0 deletions test/es-module/test-esm-dynamic-import-cache.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import '../common/index.mjs';
import tmpdir from '../common/tmpdir.js';

import assert from 'node:assert';
import dc from 'node:diagnostics_channel';
import fs from 'node:fs';
import { createRequire, registerHooks } from 'node:module';
import util from 'node:util';

tmpdir.refresh();

fs.writeFileSync(tmpdir.resolve('a.mjs'), 'export const id = "a";\n');
fs.writeFileSync(tmpdir.resolve('b.mjs'), 'export const id = "b";\n');
fs.writeFileSync(tmpdir.resolve('caller.cjs'), 'module.exports = () => import("./a.mjs");\n');
fs.writeFileSync(tmpdir.resolve('tla-fail.mjs'),
'await new Promise((r) => setTimeout(r, 20)); throw new Error("tla-boom");\n');
fs.writeFileSync(tmpdir.resolve('tla-entry.mjs'), 'import "./tla-fail.mjs";\n');

const urlA = tmpdir.fileURL('a.mjs').href;
const urlB = tmpdir.fileURL('b.mjs').href;
const urlTlaFail = tmpdir.fileURL('tla-fail.mjs').href;
const urlTlaEntry = tmpdir.fileURL('tla-entry.mjs').href;

// 1. Cached dynamic import() returns a pending Promise resolving to the same namespace.
{
const first = await import(urlA);
const promise = import(urlA);
assert.strictEqual(util.inspect(promise), 'Promise { <pending> }');
assert.strictEqual(await promise, first);
assert.strictEqual(await Promise.race([import(urlA), Promise.resolve('sync')]), 'sync');
}

// 2. Resolve hooks registered after caching still intercept import().
{
const hook = registerHooks({
resolve(specifier, context, nextResolve) {
return specifier === urlA ? { url: urlB, shortCircuit: true } : nextResolve(specifier, context);
},
});
try {
assert.strictEqual((await import(urlA)).id, 'b');
} finally {
hook.deregister();
}
assert.strictEqual((await import(urlA)).id, 'a');
}

// 3. diagnostics_channel('module.import') subscribed after caching still fires for ESM & CJS.
{
const loadA = createRequire(import.meta.url)(tmpdir.resolve('caller.cjs'));
const cachedA = await loadA();
const channel = dc.tracingChannel('module.import');
const events = [];
const sub = {
start(ctx) { events.push(['start', ctx.parentURL, ctx.url]); },
asyncEnd(ctx) { events.push(['asyncEnd', ctx.parentURL, ctx.url, ctx.result]); },
};
channel.subscribe(sub);
try {
assert.strictEqual(await import(urlA), cachedA);
assert.strictEqual(await loadA(), cachedA);
} finally {
channel.unsubscribe(sub);
}
const cjsParent = tmpdir.fileURL('caller.cjs').href;
assert.deepStrictEqual(events, [
['start', import.meta.url, urlA],
['asyncEnd', import.meta.url, urlA, cachedA],
['start', cjsParent, './a.mjs'],
['asyncEnd', cjsParent, './a.mjs', cachedA],
]);
}

// 4. In-flight TLA dependencies are not cached before settling.
{
const entry = import(urlTlaEntry);
await import(urlTlaFail);
await assert.rejects(entry, { message: 'tla-boom' });
await assert.rejects(import(urlTlaFail), { message: 'tla-boom' });
}
5 changes: 5 additions & 0 deletions test/parallel/test-vfs-scoped-cache-purge.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,9 @@ const vfsImport = (path) => pathToFileURL(path).href;
assert.strictEqual(ns, nsAgain);

v.unmount();

// Unmounting must also invalidate cached dynamic import() results.
await assert.rejects(import(vfsImport(`${mountPoint}/m.mjs`)), {
code: /^(ENOENT|ENOTDIR|ERR_MODULE_NOT_FOUND)$/,
});
})().then(common.mustCall());
Loading