11'use strict'
22
3- const getEsmExports = require ( './get-esm-exports.js' )
4- const { parse : parseCjs } = require ( 'cjs-module-lexer' )
5- const { readFileSync, existsSync } = require ( 'fs' )
6- const { builtinModules } = require ( 'module' )
7- const { fileURLToPath, pathToFileURL } = require ( 'url' )
8- const { dirname, join } = require ( 'path' )
3+ import getEsmExports from './get-esm-exports.mjs'
4+ import { parse as parseCjs , init as parserInit } from 'cjs-module-lexer'
5+ import { readFileSync , existsSync } from 'fs'
6+ import { builtinModules , createRequire } from 'module'
7+ import { fileURLToPath , pathToFileURL } from 'url'
8+ import { dirname , join } from 'path'
9+
10+ let parserInitialized = false
911
1012function addDefault ( arr ) {
1113 return new Set ( [ 'default' , ...arr ] )
@@ -14,9 +16,15 @@ function addDefault (arr) {
1416// Cached exports for Node built-in modules
1517const BUILT_INS = new Map ( )
1618
19+ let require
20+
1721function getExportsForNodeBuiltIn ( name ) {
1822 let exports = BUILT_INS . get ( )
1923
24+ if ( ! require ) {
25+ require = createRequire ( import . meta. url )
26+ }
27+
2028 if ( ! exports ) {
2129 exports = new Set ( addDefault ( Object . keys ( require ( name ) ) ) )
2230 BUILT_INS . set ( name , exports )
@@ -90,6 +98,10 @@ async function getCjsExports (url, context, parentLoad, source) {
9098 urlsBeingProcessed . add ( url )
9199
92100 try {
101+ if ( ! parserInitialized ) {
102+ await parserInit ( )
103+ parserInitialized = true
104+ }
93105 const result = parseCjs ( source )
94106 const full = addDefault ( result . exports )
95107
@@ -110,6 +122,10 @@ async function getCjsExports (url, context, parentLoad, source) {
110122 [ url , re ] = resolved
111123 }
112124
125+ // Resolve the re-exported module relative to the current module.
126+ if ( ! require ) {
127+ require = createRequire ( import . meta. url )
128+ }
113129 const newUrl = pathToFileURL ( require . resolve ( re , { paths : [ dirname ( fileURLToPath ( url ) ) ] } ) ) . href
114130
115131 if ( newUrl . endsWith ( '.node' ) || newUrl . endsWith ( '.json' ) ) {
@@ -144,7 +160,7 @@ async function getCjsExports (url, context, parentLoad, source) {
144160 * Please see {@link getEsmExports} for caveats on special identifiers that may
145161 * be included in the result set.
146162 */
147- async function getExports ( url , context , parentLoad ) {
163+ export async function getExports ( url , context , parentLoad ) {
148164 // `parentLoad` gives us the possibility of getting the source
149165 // from an upstream loader. This doesn't always work though,
150166 // so later on we fall back to reading it from disk.
@@ -188,5 +204,3 @@ async function getExports (url, context, parentLoad) {
188204 throw err
189205 }
190206}
191-
192- module . exports = getExports
0 commit comments