From 7fe4745ca151f6ab959d2a41444b1e51451c468d Mon Sep 17 00:00:00 2001 From: Darshan Sen Date: Mon, 8 May 2023 13:47:13 +0530 Subject: [PATCH] module: refactor to use `normalizeRequirableId` in the CJS module loader `BuiltinModule.normalizeRequirableId()` was introduced in https://github.com/nodejs/node/pull/47779 to fix a bug in the require function of SEAs and Snapshots, so that built-in modules with the `node:` scheme could be required correctly. This change makes more use of this API instead of `BuiltinModule.canBeRequiredByUsers()` and `BuiltinModule.canBeRequiredWithoutScheme()` to reduce chances of such bugs. Signed-off-by: Darshan Sen PR-URL: https://github.com/nodejs/node/pull/47896 Reviewed-By: Geoffrey Booth Reviewed-By: Yagiz Nizipli Reviewed-By: Mohammed Keyvanzadeh --- lib/internal/bootstrap/realm.js | 15 +++++++-------- lib/internal/modules/cjs/loader.js | 16 ++-------------- 2 files changed, 9 insertions(+), 22 deletions(-) diff --git a/lib/internal/bootstrap/realm.js b/lib/internal/bootstrap/realm.js index 8e35213234e995..aa4f79fefa02ef 100644 --- a/lib/internal/bootstrap/realm.js +++ b/lib/internal/bootstrap/realm.js @@ -287,17 +287,16 @@ class BuiltinModule { } static normalizeRequirableId(id) { - let normalizedId = id; if (StringPrototypeStartsWith(id, 'node:')) { - normalizedId = StringPrototypeSlice(id, 5); - } - - if (!BuiltinModule.canBeRequiredByUsers(normalizedId) || - (id === normalizedId && !BuiltinModule.canBeRequiredWithoutScheme(normalizedId))) { - return undefined; + const normalizedId = StringPrototypeSlice(id, 5); + if (BuiltinModule.canBeRequiredByUsers(normalizedId)) { + return normalizedId; + } + } else if (BuiltinModule.canBeRequiredWithoutScheme(id)) { + return id; } - return normalizedId; + return undefined; } static isBuiltin(id) { diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js index 3cab6d3ade3f93..60fa7e79d19693 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js @@ -792,12 +792,7 @@ if (isWindows) { } Module._resolveLookupPaths = function(request, parent) { - if (( - StringPrototypeStartsWith(request, 'node:') && - BuiltinModule.canBeRequiredByUsers(StringPrototypeSlice(request, 5)) - ) || ( - BuiltinModule.canBeRequiredWithoutScheme(request) - )) { + if (BuiltinModule.normalizeRequirableId(request)) { debug('looking for %j in []', request); return null; } @@ -989,14 +984,7 @@ Module._load = function(request, parent, isMain) { }; Module._resolveFilename = function(request, parent, isMain, options) { - if ( - ( - StringPrototypeStartsWith(request, 'node:') && - BuiltinModule.canBeRequiredByUsers(StringPrototypeSlice(request, 5)) - ) || ( - BuiltinModule.canBeRequiredWithoutScheme(request) - ) - ) { + if (BuiltinModule.normalizeRequirableId(request)) { return request; }