|
| 1 | +import { ResolverFactory, CachedInputFileSystem, type ResolveOptions } from 'enhanced-resolve'; |
| 2 | +import fs from 'node:fs'; |
| 3 | +import type { NewResolver } from './types'; |
| 4 | +import { isBuiltin } from 'node:module'; |
| 5 | +import { dirname } from 'node:path'; |
| 6 | + |
| 7 | +interface NodeResolverOptions extends Omit<ResolveOptions, 'useSyncFileSystemCalls'> { |
| 8 | + /** |
| 9 | + * The allowed extensions the resolver will attempt to find when resolving a module |
| 10 | + * @type {string[] | undefined} |
| 11 | + * @default ['.mjs', '.cjs', '.js', '.json', '.node'] |
| 12 | + */ |
| 13 | + extensions?: string[]; |
| 14 | + /** |
| 15 | + * The import conditions the resolver will used when reading the exports map from "package.json" |
| 16 | + * @type {string[] | undefined} |
| 17 | + * @default ['default', 'module', 'import', 'require'] |
| 18 | + */ |
| 19 | + conditionNames?: string[]; |
| 20 | +} |
| 21 | + |
| 22 | +export function createNodeResolver({ |
| 23 | + extensions = ['.mjs', '.cjs', '.js', '.json', '.node'], |
| 24 | + conditionNames = ['default', 'module', 'import', 'require'], |
| 25 | + mainFields = ['main'], |
| 26 | + exportsFields = ['exports'], |
| 27 | + mainFiles = ['index'], |
| 28 | + fileSystem = new CachedInputFileSystem(fs, 4 * 1000), |
| 29 | + ...restOptions |
| 30 | +}: Partial<NodeResolverOptions> = {}): NewResolver { |
| 31 | + const resolver = ResolverFactory.createResolver({ |
| 32 | + extensions, |
| 33 | + fileSystem, |
| 34 | + conditionNames, |
| 35 | + useSyncFileSystemCalls: true, |
| 36 | + ...restOptions, |
| 37 | + }); |
| 38 | + |
| 39 | + // shared context across all resolve calls |
| 40 | + |
| 41 | + return { |
| 42 | + interfaceVersion: 3, |
| 43 | + name: 'eslint-plugin-import-x built-in node resolver', |
| 44 | + resolve: (modulePath, sourceFile) => { |
| 45 | + if (isBuiltin(modulePath)) { |
| 46 | + return { found: true, path: null }; |
| 47 | + } |
| 48 | + |
| 49 | + if (modulePath.startsWith('data:')) { |
| 50 | + return { found: true, path: null }; |
| 51 | + } |
| 52 | + |
| 53 | + try { |
| 54 | + const path = resolver.resolveSync( |
| 55 | + {}, |
| 56 | + dirname(sourceFile), |
| 57 | + modulePath |
| 58 | + ); |
| 59 | + if (path) { |
| 60 | + return { found: true, path }; |
| 61 | + } |
| 62 | + return { found: false }; |
| 63 | + } catch { |
| 64 | + return { found: false }; |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments