diff --git a/lib/internal/modules/esm/hooks.js b/lib/internal/modules/esm/hooks.js index 7df6672582c50d..cde399d97f974f 100644 --- a/lib/internal/modules/esm/hooks.js +++ b/lib/internal/modules/esm/hooks.js @@ -35,6 +35,7 @@ const { } = require('internal/errors').codes; const { exitCodes: { kUnfinishedTopLevelAwait } } = internalBinding('errors'); const { URL } = require('internal/url'); +const { canParse: urlCanParse } = internalBinding('url'); const { receiveMessageOnPort } = require('worker_threads'); const { isAnyArrayBuffer, @@ -272,10 +273,8 @@ class Hooks { // Avoid expensive URL instantiation for known-good URLs if (!this.#validatedUrls.has(url)) { - try { - new URL(url); - this.#validatedUrls.add(url); - } catch { + // No need to convert to string, since the type is already validated + if (!urlCanParse(url)) { throw new ERR_INVALID_RETURN_PROPERTY_VALUE( 'a URL string', hookErrIdentifier, @@ -283,6 +282,8 @@ class Hooks { url, ); } + + this.#validatedUrls.add(url); } if ( @@ -352,16 +353,16 @@ class Hooks { // Avoid expensive URL instantiation for known-good URLs if (!this.#validatedUrls.has(nextUrl)) { - try { - new URL(nextUrl); - this.#validatedUrls.add(nextUrl); - } catch { + // No need to convert to string, since the type is already validated + if (!urlCanParse(nextUrl)) { throw new ERR_INVALID_ARG_VALUE( `${hookErrIdentifier} url`, nextUrl, 'should be a URL string', ); } + + this.#validatedUrls.add(nextUrl); } if (ctx) { validateObject(ctx, `${hookErrIdentifier} context`); } diff --git a/lib/internal/modules/esm/resolve.js b/lib/internal/modules/esm/resolve.js index 0dc7a9ae1d6690..2ee5b0e23e0ba6 100644 --- a/lib/internal/modules/esm/resolve.js +++ b/lib/internal/modules/esm/resolve.js @@ -42,6 +42,7 @@ const experimentalNetworkImports = getOptionValue('--experimental-network-imports'); const typeFlag = getOptionValue('--input-type'); const { URL, pathToFileURL, fileURLToPath, isURL } = require('internal/url'); +const { canParse: canParseURL } = internalBinding('url'); const { ERR_INPUT_TYPE_NOT_ALLOWED, ERR_INVALID_ARG_TYPE, @@ -333,14 +334,8 @@ function resolvePackageTargetString( if (!StringPrototypeStartsWith(target, './')) { if (internal && !StringPrototypeStartsWith(target, '../') && !StringPrototypeStartsWith(target, '/')) { - let isURL = false; - try { - new URL(target); - isURL = true; - } catch { - // Continue regardless of error. - } - if (!isURL) { + // No need to convert target to string, since it's already presumed to be + if (!canParseURL(target)) { const exportTarget = pattern ? RegExpPrototypeSymbolReplace(patternRegEx, target, () => subpath) : target + subpath;