4
4
ObjectPrototypeHasOwnProperty,
5
5
PromisePrototypeThen,
6
6
PromiseResolve,
7
+ StringPrototypeCharCodeAt,
7
8
StringPrototypeSlice,
8
9
} = primordials ;
9
- const { basename, extname , relative } = require ( 'path' ) ;
10
+ const { basename, relative } = require ( 'path' ) ;
10
11
const { getOptionValue } = require ( 'internal/options' ) ;
11
12
const {
12
13
extensionFormatMap,
@@ -41,15 +42,38 @@ function getDataProtocolModuleFormat(parsed) {
41
42
return mimeToFormat ( mime ) ;
42
43
}
43
44
45
+ const DOT_CODE = 46 ;
46
+ const SLASH_CODE = 47 ;
47
+
48
+ /**
49
+ * Returns the file extension from a URL. Should give similar result to
50
+ * `require('node:path').extname(require('node:url').fileURLToPath(url))`
51
+ * when used with a `file:` URL.
52
+ * @param {URL } 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
+
44
69
/**
45
70
* @param {URL } url
46
71
* @param {{parentURL: string} } context
47
72
* @param {boolean } ignoreErrors
48
73
* @returns {string }
49
74
*/
50
75
function getFileProtocolModuleFormat ( url , context , ignoreErrors ) {
51
- const filepath = fileURLToPath ( url ) ;
52
- const ext = extname ( filepath ) ;
76
+ const ext = extname ( url ) ;
53
77
if ( ext === '.js' ) {
54
78
return getPackageType ( url ) === 'module' ? 'module' : 'commonjs' ;
55
79
}
@@ -59,6 +83,7 @@ function getFileProtocolModuleFormat(url, context, ignoreErrors) {
59
83
60
84
// Explicit undefined return indicates load hook should rerun format check
61
85
if ( ignoreErrors ) { return undefined ; }
86
+ const filepath = fileURLToPath ( url ) ;
62
87
let suggestion = '' ;
63
88
if ( getPackageType ( url ) === 'module' && ext === '' ) {
64
89
const config = getPackageScopeConfig ( url ) ;
@@ -119,4 +144,5 @@ module.exports = {
119
144
defaultGetFormat,
120
145
defaultGetFormatWithoutErrors,
121
146
extensionFormatMap,
147
+ extname,
122
148
} ;
0 commit comments