|
| 1 | +import { builtinModules } from 'node:module'; |
| 2 | +import { dirname } from 'path'; |
| 3 | +import { cwd } from 'process'; |
| 4 | +import { fileURLToPath, pathToFileURL } from 'url'; |
| 5 | +import { promisify } from 'util'; |
| 6 | + |
| 7 | +import resolveCallback from 'resolve/async.js'; |
| 8 | + |
| 9 | +const resolveAsync = promisify(resolveCallback); |
| 10 | + |
| 11 | +const baseURL = pathToFileURL(cwd() + '/').href; |
| 12 | + |
| 13 | +export async function resolve(specifier, context, next) { |
| 14 | + const { parentURL = baseURL } = context; |
| 15 | + |
| 16 | + if (specifier.startsWith('node:') || builtinModules.includes(specifier)) { |
| 17 | + return next(specifier, context); |
| 18 | + } |
| 19 | + |
| 20 | + // `resolveAsync` works with paths, not URLs |
| 21 | + if (specifier.startsWith('file://')) { |
| 22 | + specifier = fileURLToPath(specifier); |
| 23 | + } |
| 24 | + const parentPath = fileURLToPath(parentURL); |
| 25 | + |
| 26 | + let url; |
| 27 | + try { |
| 28 | + const resolution = await resolveAsync(specifier, { |
| 29 | + basedir: dirname(parentPath), |
| 30 | + // For whatever reason, --experimental-specifier-resolution=node doesn't search for .mjs extensions |
| 31 | + // but it does search for index.mjs files within directories |
| 32 | + extensions: ['.js', '.json', '.node', '.mjs'], |
| 33 | + }); |
| 34 | + url = pathToFileURL(resolution).href; |
| 35 | + } catch (error) { |
| 36 | + if (error.code === 'MODULE_NOT_FOUND') { |
| 37 | + // Match Node's error code |
| 38 | + error.code = 'ERR_MODULE_NOT_FOUND'; |
| 39 | + } |
| 40 | + throw error; |
| 41 | + } |
| 42 | + |
| 43 | + return next(url, context); |
| 44 | +} |
0 commit comments