33const getEsmExports = require ( './get-esm-exports.js' )
44const { parse : getCjsExports } = require ( 'cjs-module-lexer' )
55const fs = require ( 'fs' )
6- const { fileURLToPath } = require ( 'url' )
6+ const { fileURLToPath, pathToFileURL } = require ( 'url' )
77
88function addDefault ( arr ) {
99 return Array . from ( new Set ( [ 'default' , ...arr ] ) )
1010}
1111
12+ const urlsBeingProcessed = new Set ( ) // Guard against circular imports.
13+
14+ async function getFullCjsExports ( url , context , parentLoad , source ) {
15+ if ( urlsBeingProcessed . has ( url ) ) {
16+ return [ ]
17+ }
18+ urlsBeingProcessed . add ( url )
19+
20+ const ex = getCjsExports ( source )
21+ const full = Array . from ( new Set ( [
22+ ...addDefault ( ex . exports ) ,
23+ ...( await Promise . all ( ex . reexports . map ( re => getExports ( ( {
24+ url : ( / ^ ( ..? ( $ | \/ | \\ ) ) / ) . test ( re )
25+ ? pathToFileURL ( require . resolve ( fileURLToPath ( new URL ( re , url ) ) ) ) . toString ( )
26+ : pathToFileURL ( require . resolve ( re ) ) . toString ( ) ,
27+ context,
28+ parentLoad
29+ } ) ) ) ) ) . flat ( )
30+ ] ) )
31+
32+ urlsBeingProcessed . delete ( url )
33+ return full
34+ }
35+
1236/**
1337 * Inspects a module for its type (commonjs or module), attempts to get the
1438 * source code for said module from the loader API, and parses the result
@@ -56,7 +80,7 @@ async function getExports ({ url, context, parentLoad, defaultAs = 'default' })
5680 return getEsmExports ( { moduleSource : source , defaultAs } )
5781 }
5882 if ( format === 'commonjs' ) {
59- return addDefault ( getCjsExports ( source ) . exports )
83+ return getFullCjsExports ( url , context , parentLoad , source )
6084 }
6185
6286 // At this point our `format` is either undefined or not known by us. Fall
@@ -67,7 +91,7 @@ async function getExports ({ url, context, parentLoad, defaultAs = 'default' })
6791 // isn't set at first and yet we have an ESM module with no exports.
6892 // I couldn't construct an example that would do this, so maybe it's
6993 // impossible?
70- return addDefault ( getCjsExports ( source ) . exports )
94+ return getFullCjsExports ( url , context , parentLoad , source )
7195 }
7296}
7397
0 commit comments