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,
@@ -44,15 +45,38 @@ function getDataProtocolModuleFormat(parsed) {
4445 return mimeToFormat ( mime ) ;
4546}
4647
48+ const DOT_CODE = 46 ;
49+ const SLASH_CODE = 47 ;
50+
51+ /**
52+ * Returns the file extension from a URL. Should give similar result to
53+ * `require('node:path').extname(require('node:url').fileURLToPath(url))`
54+ * when used with a `file:` URL.
55+ * @param {URL } url
56+ * @returns {string }
57+ */
58+ function extname ( url ) {
59+ const { pathname } = url ;
60+ for ( let i = pathname . length - 1 ; i > 0 ; i -- ) {
61+ switch ( StringPrototypeCharCodeAt ( pathname , i ) ) {
62+ case SLASH_CODE :
63+ return '' ;
64+
65+ case DOT_CODE :
66+ return StringPrototypeCharCodeAt ( pathname , i - 1 ) === SLASH_CODE ? '' : StringPrototypeSlice ( pathname , i ) ;
67+ }
68+ }
69+ return '' ;
70+ }
71+
4772/**
4873 * @param {URL } url
4974 * @param {{parentURL: string} } context
5075 * @param {boolean } ignoreErrors
5176 * @returns {string }
5277 */
5378function getFileProtocolModuleFormat ( url , context , ignoreErrors ) {
54- const filepath = fileURLToPath ( url ) ;
55- const ext = extname ( filepath ) ;
79+ const ext = extname ( url ) ;
5680 if ( ext === '.js' ) {
5781 return getPackageType ( url ) === 'module' ? 'module' : 'commonjs' ;
5882 }
@@ -63,6 +87,7 @@ function getFileProtocolModuleFormat(url, context, ignoreErrors) {
6387 if ( experimentalSpecifierResolution !== 'node' ) {
6488 // Explicit undefined return indicates load hook should rerun format check
6589 if ( ignoreErrors ) return undefined ;
90+ const filepath = fileURLToPath ( url ) ;
6691 let suggestion = '' ;
6792 if ( getPackageType ( url ) === 'module' && ext === '' ) {
6893 const config = getPackageScopeConfig ( url ) ;
@@ -128,4 +153,5 @@ module.exports = {
128153 defaultGetFormat,
129154 defaultGetFormatWithoutErrors,
130155 extensionFormatMap,
156+ extname,
131157} ;
0 commit comments