import path from "path"; import type { Dirent } from "fs"; import type { IsomorphicRollupFs } from "../../fs-iface"; export type NodeModulesSymlinkResolver = { /** * Given a real (symlink-resolved) `filePath`, looks up the node_modules * symlink/junction whose real path is a prefix of it and rewrites the * path to go through that symlink, so a subsequent `path.relative` call * produces a clean `node_modules/@pkg/...` name instead of a `../../..` * traversal. * * Returns `undefined` when no symlink matches `filePath`. */ resolve: ( fs: IsomorphicRollupFs, filePath: string, ) => Promise<{ filePath: string; relativeRoot: string } | undefined>; /** Evicts the memoized node_modules scan, forcing a re-scan on next use. */ reset: () => void; }; /** * Creates a resolver that maps a real (symlink-resolved) path back to its * `node_modules`-relative path — needed because pnpm (and other symlink- * based package managers) resolve symlinks before passing the module id to * rollup plugins, so a file path can be the real path under * `packages//dist/` with no `node_modules` ancestor. * * The `node_modules` scan is built lazily on first use and cached until * `reset()` is called, so repeated lookups (e.g. one per extracted * stylesheet in a single build) don't rescan `node_modules` every time. */ export function createNodeModulesSymlinkResolver( rootDir: string, ): NodeModulesSymlinkResolver { let symlinkPrefixMapPromise: | Promise<{ map: Map; relativeRoot: string }> | undefined; const getNodeModulesSymlinkMap = ( fs: IsomorphicRollupFs, ): Promise<{ map: Map; relativeRoot: string }> => { if (!symlinkPrefixMapPromise) { // Built once from the first-provided fs adapter; safe because fs // always resolves to the same adapter instance within a single // build (see `reset` for cross-build invalidation). symlinkPrefixMapPromise = (async () => { const map = new Map(); const addCandidate = (linkPath: string) => { let realTarget: string; try { realTarget = fs.realpathSync(linkPath); } catch { return; } if (realTarget === linkPath) return; // not a symlink/junction // path.sep matches the platform's native separator, which is what // fs.realpathSync returns here. If this is ever fed a path using // a different separator convention, the startsWith check below // simply won't match and falls back to the relative traversal. const prefix = realTarget.endsWith(path.sep) ? realTarget : realTarget + path.sep; map.set(prefix, linkPath); }; // Returns undefined (rather than []) when `dir` doesn't exist, so // callers can distinguish "no node_modules here" from "empty // node_modules" while walking up the directory tree below. const readDirIfExists = async ( dir: string, ): Promise => { try { return ( (await fs.promises?.readdir?.(dir, { withFileTypes: true, })) ?? [] ); } catch (err) { const code = (err as NodeJS.ErrnoException)?.code; if (code !== "ENOENT" && code !== "ENOTDIR") { console.warn( `Could not scan ${dir} for symlinked packages: ${err}`, ); } return undefined; } }; // rootDir is the client source directory (e.g. "src/client"), which // is typically nested below the actual package/app root — walk up // until a node_modules directory is found. let nodeModulesDir = ""; let nodeModulesEntries: Dirent[] | undefined; for ( let dir = rootDir; nodeModulesEntries === undefined; dir = path.dirname(dir) ) { const candidate = path.join(dir, "node_modules"); nodeModulesEntries = await readDirIfExists(candidate); if (nodeModulesEntries !== undefined) { nodeModulesDir = candidate; break; } if (path.dirname(dir) === dir) break; // reached filesystem root } for (const entry of nodeModulesEntries ?? []) { const entryPath = path.join(nodeModulesDir, entry.name); addCandidate(entryPath); // Scoped packages (e.g. @servicenow/foo) live one level deeper — // the scope directory itself is rarely a symlink, but its // members are. if (entry.name.startsWith("@")) { for (const scopedEntry of (await readDirIfExists(entryPath)) ?? []) { addCandidate(path.join(entryPath, scopedEntry.name)); } } } // path.relative should be computed against the directory that // actually contains node_modules, not `rootDir` itself — they // differ whenever node_modules was found by walking up. const relativeRoot = nodeModulesDir ? path.dirname(nodeModulesDir) : rootDir; return { map, relativeRoot }; })(); } return symlinkPrefixMapPromise; }; return { async resolve(fs, filePath) { const { map: symlinkMap, relativeRoot } = await getNodeModulesSymlinkMap(fs); for (const [prefix, linkPath] of symlinkMap) { if (filePath.startsWith(prefix)) { return { filePath: path.join(linkPath, filePath.slice(prefix.length)), relativeRoot, }; } } return undefined; }, reset() { symlinkPrefixMapPromise = undefined; }, }; }