@@ -34,7 +34,7 @@ const { getOptionValue } = require('internal/options');
34
34
const policy = getOptionValue ( '--experimental-policy' ) ?
35
35
require ( 'internal/process/policy' ) :
36
36
null ;
37
- const { sep, relative } = require ( 'path' ) ;
37
+ const { sep, relative, resolve } = require ( 'path' ) ;
38
38
const preserveSymlinks = getOptionValue ( '--preserve-symlinks' ) ;
39
39
const preserveSymlinksMain = getOptionValue ( '--preserve-symlinks-main' ) ;
40
40
const typeFlag = getOptionValue ( '--input-type' ) ;
@@ -204,16 +204,18 @@ function getPackageScopeConfig(resolved) {
204
204
return packageConfig ;
205
205
}
206
206
207
- /*
207
+ /**
208
208
* Legacy CommonJS main resolution:
209
209
* 1. let M = pkg_url + (json main field)
210
210
* 2. TRY(M, M.js, M.json, M.node)
211
211
* 3. TRY(M/index.js, M/index.json, M/index.node)
212
212
* 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node)
213
213
* 5. NOT_FOUND
214
+ * @param {string | URL } url
215
+ * @returns {boolean }
214
216
*/
215
217
function fileExists ( url ) {
216
- return tryStatSync ( fileURLToPath ( url ) ) . isFile ( ) ;
218
+ return statSync ( url , { throwIfNoEntry : false } ) ? .isFile ( ) ?? false ;
217
219
}
218
220
219
221
function legacyMainResolve ( packageJSONUrl , packageConfig , base ) {
@@ -272,7 +274,19 @@ function resolveExtensions(search) {
272
274
return undefined ;
273
275
}
274
276
275
- function resolveIndex ( search ) {
277
+ function resolveDirectoryEntry ( search ) {
278
+ const dirPath = fileURLToPath ( search ) ;
279
+ const pkgJsonPath = resolve ( dirPath , 'package.json' ) ;
280
+ if ( fileExists ( pkgJsonPath ) ) {
281
+ const pkgJson = packageJsonReader . read ( pkgJsonPath ) ;
282
+ if ( pkgJson . containsKeys ) {
283
+ const { main } = JSONParse ( pkgJson . string ) ;
284
+ if ( main != null ) {
285
+ const mainUrl = pathToFileURL ( resolve ( dirPath , main ) ) ;
286
+ return resolveExtensionsWithTryExactName ( mainUrl ) ;
287
+ }
288
+ }
289
+ }
276
290
return resolveExtensions ( new URL ( 'index' , search ) ) ;
277
291
}
278
292
@@ -288,10 +302,10 @@ function finalizeResolution(resolved, base) {
288
302
let file = resolveExtensionsWithTryExactName ( resolved ) ;
289
303
if ( file !== undefined ) return file ;
290
304
if ( ! StringPrototypeEndsWith ( path , '/' ) ) {
291
- file = resolveIndex ( new URL ( `${ resolved } /` ) ) ;
305
+ file = resolveDirectoryEntry ( new URL ( `${ resolved } /` ) ) ;
292
306
if ( file !== undefined ) return file ;
293
307
} else {
294
- return resolveIndex ( resolved ) || resolved ;
308
+ return resolveDirectoryEntry ( resolved ) || resolved ;
295
309
}
296
310
throw new ERR_MODULE_NOT_FOUND (
297
311
resolved . pathname , fileURLToPath ( base ) , 'module' ) ;
0 commit comments