diff --git a/benchmark/module/module-require-hooks.js b/benchmark/module/module-require-hooks.js new file mode 100644 index 000000000000..9821168c6cfb --- /dev/null +++ b/benchmark/module/module-require-hooks.js @@ -0,0 +1,56 @@ +'use strict'; + +// Measures require() of files resolved from many parent directories, with and +// without a pass-through resolve hook registered via module.registerHooks(). + +const fs = require('fs'); +const path = require('path'); +const { registerHooks } = require('module'); +const common = require('../common.js'); +const tmpdir = require('../../test/common/tmpdir'); +const benchmarkDirectory = tmpdir.resolve('nodejs-benchmark-module-hooks'); + +const bench = common.createBenchmark(main, { + hooks: ['none', 'resolve'], + packages: [10], + n: [1e3], +}, { + setup(configs) { + tmpdir.refresh(); + const maxN = configs.reduce((max, c) => Math.max(max, c.n), 0); + const maxPackages = configs.reduce((max, c) => Math.max(max, c.packages), 0); + createFiles(maxN, maxPackages); + }, +}); + +function main({ hooks, packages, n }) { + if (hooks === 'resolve') { + registerHooks({ + resolve(specifier, context, nextResolve) { + return nextResolve(specifier, context); + }, + }); + } + bench.start(); + for (let i = 0; i < n; i++) { + require(path.join(benchmarkDirectory, `parent${i}`, `${packages}.js`)); + } + bench.end(n * packages); +} + +function createFiles(n, packages) { + const nodeModules = path.join(benchmarkDirectory, 'node_modules'); + for (let p = 0; p < packages; p++) { + fs.mkdirSync(path.join(nodeModules, `pkg${p}`), { recursive: true }); + fs.writeFileSync(path.join(nodeModules, `pkg${p}`, 'index.js'), 'module.exports = {};'); + } + for (let i = 0; i < n; i++) { + const parent = path.join(benchmarkDirectory, `parent${i}`); + fs.mkdirSync(parent); + let content = ''; + for (let p = 0; p < packages; p++) { + content += `require('pkg${p}');\n`; + fs.writeFileSync(path.join(parent, `${p + 1}.js`), content); + } + } +} diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js index 0ce49516f9c9..a48d8c3b4eef 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js @@ -230,6 +230,11 @@ const { tracingChannel } = require('diagnostics_channel'); const onRequire = getLazy(() => tracingChannel('module.require')); const relativeResolveCache = new SafeMap(); +// Maps filenames returned by the default CommonJS resolver to the URLs passed +// to resolve hooks, and those URLs back to filenames for the loader. Both +// conversions only depend on their input for the filenames kept here. +// See resolveForCJSWithHooks. +const cjsHooksURLCache = new SafeMap(); let requireDepth = 0; let isPreloading = false; @@ -1189,6 +1194,27 @@ function defaultResolveImplForCJSLoading(specifier, parent, isMain, options) { * }} CJSModuleLoadInternalOptions */ +/** + * Returns the cached URL conversions for a filename returned by the default + * CommonJS resolver, or undefined if the conversion is not cached because it + * depends on the current working directory (rooted paths without a drive + * letter on Windows). + * @param {string} filename + * @returns {{url: string, filename: string|undefined}|undefined} + */ +function getCJSHooksURLEntry(filename) { + let entry = cjsHooksURLCache.get(filename); + if (entry === undefined) { + if (isWindows && path.isAbsolute(filename) && + RegExpPrototypeExec(/^(?:[a-zA-Z]:[\\/]|\\\\)/, filename) === null) { + return undefined; + } + entry = { __proto__: null, url: convertCJSFilenameToURL(filename), filename: undefined }; + cjsHooksURLCache.set(filename, entry); + } + return entry; +} + /** * Resolve a module request for CommonJS, invoking hooks from module.registerHooks() * if necessary. @@ -1216,6 +1242,8 @@ function resolveForCJSWithHooks(specifier, parent, isMain, internalOptions) { parentURL = parent[kURL]; } + // The URL conversions of the filename most recently returned by defaultResolve. + let defaultURLEntry; // This is used as the last nextResolve for the resolve hooks. function defaultResolve(specifier, context) { // TODO(joyeecheung): parent and isMain should be part of context, then we @@ -1240,7 +1268,10 @@ function resolveForCJSWithHooks(specifier, parent, isMain, internalOptions) { conditions: conditionSet, }); // If the default resolver does not return a URL, convert it for the public API. - result.url ??= convertCJSFilenameToURL(result.filename); + if (result.url == null) { + defaultURLEntry = getCJSHooksURLEntry(result.filename); + result.url = defaultURLEntry?.url ?? convertCJSFilenameToURL(result.filename); + } // Remove filename because it's not part of the public API. // TODO(joyeecheung): maybe expose it in the public API to avoid re-conversion for users too. @@ -1251,7 +1282,12 @@ function resolveForCJSWithHooks(specifier, parent, isMain, internalOptions) { getCjsConditionsArray(), defaultResolve); const { url, format } = resolveResult; // Convert the URL from the hook chain back to a filename for internal use. - const filename = convertURLToCJSFilename(url); + let filename; + if (defaultURLEntry !== undefined && url === defaultURLEntry.url) { + filename = defaultURLEntry.filename ??= convertURLToCJSFilename(url); + } else { + filename = convertURLToCJSFilename(url); + } const result = new CJSResolveResult(url, format, filename, parentURL); debug('resolveForCJSWithHooks', specifier, parent?.id, isMain, shouldSkipModuleHooks, '->', result); return result; diff --git a/test/module-hooks/test-module-hooks-resolve-require-repeated.js b/test/module-hooks/test-module-hooks-resolve-require-repeated.js new file mode 100644 index 000000000000..1364b4bbc5e5 --- /dev/null +++ b/test/module-hooks/test-module-hooks-resolve-require-repeated.js @@ -0,0 +1,55 @@ +'use strict'; + +// This tests that repeated CommonJS resolutions of the same file through +// resolve hooks registered via module.registerHooks() map the URL returned +// by the hooks back to the right filename, whether the hooks pass the default +// result through or redirect it, including filenames that are percent-encoded +// in their URLs. + +require('../common'); +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); +const { registerHooks } = require('module'); +const tmpdir = require('../common/tmpdir'); +const { pathToFileURL } = require('url'); + +tmpdir.refresh(); +const original = tmpdir.resolve('original 100% #1.js'); +const redirected = tmpdir.resolve('redirected 100% #2.js'); +fs.writeFileSync(original, 'module.exports = "original";'); +fs.writeFileSync(redirected, 'module.exports = "redirected";'); +const originalURL = pathToFileURL(original).href; +const redirectedURL = pathToFileURL(redirected).href; + +let redirect = false; +const urls = []; +const hook = registerHooks({ + resolve(specifier, context, nextResolve) { + const result = nextResolve(specifier, context); + urls.push(result.url); + if (redirect && result.url === originalURL) { + return { url: redirectedURL, shortCircuit: true }; + } + return result; + }, +}); + +assert.strictEqual(require.resolve(original), original); +redirect = true; +assert.strictEqual(require.resolve(original), redirected); +redirect = false; +assert.strictEqual(require.resolve(original), original); +assert.deepStrictEqual(urls, [originalURL, originalURL, originalURL]); + +// Requires from different parent directories each resolve the file again. +for (const name of ['a', 'b', 'c']) { + const dir = tmpdir.resolve(name); + fs.mkdirSync(dir); + const parent = path.join(dir, 'parent.js'); + fs.writeFileSync(parent, `module.exports = require(${JSON.stringify(original)});`); + redirect = name === 'b'; + assert.strictEqual(require(parent), redirect ? 'redirected' : 'original'); +} + +hook.deregister();