All files / src/sass/utils nodeModulesSymlinkResolver.ts

87.23% Statements 41/47
53.84% Branches 14/26
100% Functions 7/7
91.11% Lines 41/45

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 1552x                                                                 2x             4x     15x       5x 5x   5x   2x 2x       2x         2x     2x           5x     7x 7x           2x 2x         2x             5x   5x 5x       5x 5x 5x 5x 5x         5x 2x 2x       2x 2x                 5x     5x     15x     4x     15x 15x 4x 4x           11x     1x        
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/<pkg>/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<string, string>; relativeRoot: string }>
    | undefined;
 
  const getNodeModulesSymlinkMap = (
    fs: IsomorphicRollupFs,
  ): Promise<{ map: Map<string, string>; 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<string, string>();
 
        const addCandidate = (linkPath: string) => {
          let realTarget: string;
          try {
            realTarget = fs.realpathSync(linkPath);
          } catch {
            return;
          }
          Iif (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<Dirent[] | undefined> => {
          try {
            return (
              (await fs.promises?.readdir?.(dir, {
                withFileTypes: true,
              })) ?? []
            );
          } catch (err) {
            const code = (err as NodeJS.ErrnoException)?.code;
            Iif (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);
          Eif (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.
          Eif (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) {
        Eif (filePath.startsWith(prefix)) {
          return {
            filePath: path.join(linkPath, filePath.slice(prefix.length)),
            relativeRoot,
          };
        }
      }
      return undefined;
    },
    reset() {
      symlinkPrefixMapPromise = undefined;
    },
  };
}