From 07b486340e0d1804f20082bd5c7fa4d61b7c557f Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Thu, 23 Apr 2020 09:05:18 +0200 Subject: [PATCH] fix: pass custom cached realpath function to `resolve` --- CHANGELOG.md | 1 + packages/jest-resolve/src/defaultResolver.ts | 20 +++++++++++++++++--- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f1165f46273..1b51d48e0c9e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ ### Fixes +- `[jest-resolve]` Pass custom cached `realpath` function to `resolve` ([#9873](https://github.com/facebook/jest/pull/9873)) - `[jest-runtime]` Support importing CJS from ESM using `import` statements ([#9850](https://github.com/facebook/jest/pull/9850)) - `[jest-runtime]` Support importing parallel dynamic `import`s ([#9858](https://github.com/facebook/jest/pull/9858)) diff --git a/packages/jest-resolve/src/defaultResolver.ts b/packages/jest-resolve/src/defaultResolver.ts index 2481a8c606c4..0e20699364ba 100644 --- a/packages/jest-resolve/src/defaultResolver.ts +++ b/packages/jest-resolve/src/defaultResolver.ts @@ -52,6 +52,7 @@ export default function defaultResolver( export function clearDefaultResolverCache(): void { checkedPaths.clear(); + checkedRealpathPaths.clear(); } enum IPathType { @@ -89,8 +90,14 @@ function statSyncCached(path: string): IPathType { return IPathType.OTHER; } -function tolerantRealpath(path: Config.Path): Config.Path { - let result: Config.Path | undefined = undefined; +const checkedRealpathPaths = new Map(); +function realpathCached(path: Config.Path): Config.Path { + let result = checkedRealpathPaths.get(path); + + if (result !== undefined) { + return result; + } + try { result = realpath(path); } catch (error) { @@ -103,6 +110,13 @@ function tolerantRealpath(path: Config.Path): Config.Path { result = path; } + checkedRealpathPaths.set(path, result); + + if (path !== result) { + // also cache the result in case it's ever referenced directly - no reason to `realpath` that as well + checkedRealpathPaths.set(result, result); + } + return result; } @@ -118,5 +132,5 @@ function isDirectory(dir: Config.Path): boolean { } function realpathSync(file: Config.Path): Config.Path { - return tolerantRealpath(file); + return realpathCached(file); }