Skip to content

Commit

Permalink
module: refactor to use normalizeRequirableId in the CJS module loader
Browse files Browse the repository at this point in the history
`BuiltinModule.normalizeRequirableId()` was introduced in
nodejs#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 <[email protected]>
  • Loading branch information
RaisinTen committed May 6, 2023
1 parent 2de10f5 commit 1b0d145
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 22 deletions.
15 changes: 7 additions & 8 deletions lib/internal/bootstrap/realm.js
Original file line number Diff line number Diff line change
Expand Up @@ -286,17 +286,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) {
Expand Down
16 changes: 2 additions & 14 deletions lib/internal/modules/cjs/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}

Expand Down

0 comments on commit 1b0d145

Please sign in to comment.