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,
@@ -17,6 +18,7 @@ const experimentalNetworkImports =
17
18
getOptionValue ( '--experimental-network-imports' ) ;
18
19
const { getPackageType, getPackageScopeConfig } = require ( 'internal/modules/esm/resolve' ) ;
19
20
const { URL , fileURLToPath } = require ( 'internal/url' ) ;
21
+ const assert = require ( 'internal/assert' ) ;
20
22
const { ERR_UNKNOWN_FILE_EXTENSION } = require ( 'internal/errors' ) . codes ;
21
23
22
24
const protocolHandlers = {
@@ -41,15 +43,37 @@ function getDataProtocolModuleFormat(parsed) {
41
43
return mimeToFormat ( mime ) ;
42
44
}
43
45
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
+
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