44 ObjectPrototypeHasOwnProperty,
55 PromisePrototypeThen,
66 PromiseResolve,
7+ StringPrototypeCharCodeAt,
78 StringPrototypeSlice,
89} = primordials ;
9- const { basename, extname , relative } = require ( 'path' ) ;
10+ const { basename, relative } = require ( 'path' ) ;
1011const { getOptionValue } = require ( 'internal/options' ) ;
1112const {
1213 extensionFormatMap,
@@ -17,6 +18,7 @@ const experimentalNetworkImports =
1718 getOptionValue ( '--experimental-network-imports' ) ;
1819const { getPackageType, getPackageScopeConfig } = require ( 'internal/modules/esm/resolve' ) ;
1920const { URL , fileURLToPath } = require ( 'internal/url' ) ;
21+ const assert = require ( 'internal/assert' ) ;
2022const { ERR_UNKNOWN_FILE_EXTENSION } = require ( 'internal/errors' ) . codes ;
2123
2224const protocolHandlers = {
@@ -41,15 +43,37 @@ function getDataProtocolModuleFormat(parsed) {
4143 return mimeToFormat ( mime ) ;
4244}
4345
46+ const DOT_CODE = 46 ;
47+ const SLASH_CODE = 47 ;
48+
49+ /**
50+ * Returns the file extension from a file: URL. Should give similar result than
51+ * require('node:path').extname(require('node:url').fileURLToPath(url)).
52+ * @param {URL } url A file: URL.
53+ * @returns {string }
54+ */
55+ function extname ( url ) {
56+ const { pathname } = url ;
57+ for ( let i = pathname . length - 1 ; i > 0 ; i -- ) {
58+ switch ( StringPrototypeCharCodeAt ( pathname , i ) ) {
59+ case SLASH_CODE :
60+ return '' ;
61+
62+ case DOT_CODE :
63+ return StringPrototypeCharCodeAt ( pathname , i - 1 ) === SLASH_CODE ? '' : StringPrototypeSlice ( pathname , i ) ;
64+ }
65+ }
66+ return '' ;
67+ }
68+
4469/**
4570 * @param {URL } url
4671 * @param {{parentURL: string} } context
4772 * @param {boolean } ignoreErrors
4873 * @returns {string }
4974 */
5075function getFileProtocolModuleFormat ( url , context , ignoreErrors ) {
51- const filepath = fileURLToPath ( url ) ;
52- const ext = extname ( filepath ) ;
76+ const ext = extname ( url ) ;
5377 if ( ext === '.js' ) {
5478 return getPackageType ( url ) === 'module' ? 'module' : 'commonjs' ;
5579 }
@@ -59,6 +83,7 @@ function getFileProtocolModuleFormat(url, context, ignoreErrors) {
5983
6084 // Explicit undefined return indicates load hook should rerun format check
6185 if ( ignoreErrors ) { return undefined ; }
86+ const filepath = fileURLToPath ( url ) ;
6287 let suggestion = '' ;
6388 if ( getPackageType ( url ) === 'module' && ext === '' ) {
6489 const config = getPackageScopeConfig ( url ) ;
@@ -119,4 +144,5 @@ module.exports = {
119144 defaultGetFormat,
120145 defaultGetFormatWithoutErrors,
121146 extensionFormatMap,
147+ extname,
122148} ;
0 commit comments