|
| 1 | +import fs from 'fs'; |
| 2 | +import path from 'path'; |
| 3 | +import {pathToFileURL} from 'url'; |
| 4 | +import {resolve as resolveExports} from '../../../third_party/github.com/lukeed/resolve.exports/index.mjs'; |
| 5 | + |
| 6 | +/* |
| 7 | + Custom module loader (see https://nodejs.org/api/cli.html#--experimental-loadermodule) to support |
| 8 | + loading third-party packages in esm modules when the rules_nodejs linker is disabled. Resolves |
| 9 | + third-party imports from the node_modules folder in the bazel workspace defined by |
| 10 | + process.env.NODE_MODULES_WORKSPACE_NAME, and uses default resolution for all other imports. |
| 11 | +
|
| 12 | + This is required because rules_nodejs only patches requires in cjs modules when the linker |
| 13 | + is disabled, not imports in mjs modules. |
| 14 | +*/ |
| 15 | +export async function resolve(specifier, context, defaultResolve) { |
| 16 | + if (!isNodeOrNpmPackageImport(specifier)) { |
| 17 | + return defaultResolve(specifier, context, defaultResolve); |
| 18 | + } |
| 19 | + |
| 20 | + const nodeModules = path.resolve('external', process.env.NODE_MODULES_WORKSPACE_NAME, 'node_modules'); |
| 21 | + |
| 22 | + const packageImport = parsePackageImport(specifier); |
| 23 | + const pathToNodeModule = path.join(nodeModules, packageImport.packageName); |
| 24 | + |
| 25 | + const isInternalNodePackage = !fs.existsSync(pathToNodeModule); |
| 26 | + if (isInternalNodePackage) { |
| 27 | + return defaultResolve(specifier, context, defaultResolve); |
| 28 | + } |
| 29 | + |
| 30 | + const packageJson = JSON.parse(fs.readFileSync(path.join(pathToNodeModule, 'package.json'), 'utf-8')); |
| 31 | + |
| 32 | + const localPackagePath = resolvePackageLocalFilepath(packageImport, packageJson); |
| 33 | + const resolvedFilePath = path.join(pathToNodeModule, localPackagePath); |
| 34 | + |
| 35 | + return {url: pathToFileURL(resolvedFilePath).href}; |
| 36 | +} |
| 37 | + |
| 38 | +function isNodeOrNpmPackageImport(specifier) { |
| 39 | + return !specifier.startsWith('./') && !specifier.startsWith('../') && !specifier.startsWith('node:') && !specifier.startsWith('file:'); |
| 40 | +} |
| 41 | + |
| 42 | +function parsePackageImport(specifier) { |
| 43 | + const [, packageName, pathInPackage = ''] = /^((?:@[^/]+\/)?[^/]+)(?:\/(.+))?$/.exec(specifier) ?? []; |
| 44 | + if (!packageName) { |
| 45 | + throw new Error(`Could not parse package name import statement '${specifier}'`); |
| 46 | + } |
| 47 | + return {packageName, pathInPackage, specifier}; |
| 48 | +} |
| 49 | + |
| 50 | +function resolvePackageLocalFilepath(packageImport, packageJson) { |
| 51 | + if (packageJson.exports) { |
| 52 | + return resolveExports(packageJson, packageImport.specifier); |
| 53 | + } |
| 54 | + |
| 55 | + return packageImport.pathInPackage || packageJson.module || packageJson.main || 'index.js'; |
| 56 | +} |
0 commit comments