Skip to content

Commit 974db43

Browse files
luoqingmingclaude
andcommitted
fix(dep-versions): 直接读取 node_modules/<dep>/package.json,不再依赖 require.resolve
CI(bun 1.4.0)上 detectHermesEnabled 的 RN 版本用例失败:带 paths 的 require.resolve 结果被按 specifier 缓存,第二个临时项目解析到了第一个项目 的 react-native。改为从 cwd 向上查找 node_modules/<dep>/package.json 直接读取, 不受解析器缓存影响;同时对 exports 映射未导出 package.json 的依赖也能取到版本 (require.resolve 在这种包上会抛错而被静默跳过)。 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Tusm6iL2itjJZDiemujAeL
1 parent b848104 commit 974db43

1 file changed

Lines changed: 24 additions & 8 deletions

File tree

src/utils/dep-versions.ts

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -35,15 +35,31 @@ function directDependencyNames(pkg: ProjectPackageJson): string[] {
3535
];
3636
}
3737

38-
/** version of the installed copy of `dep`, resolved from `cwd` */
38+
/**
39+
* Version of the installed copy of `dep`: the nearest
40+
* `node_modules/<dep>/package.json` from `cwd` upwards, read directly. Not
41+
* `require.resolve`: a package whose `exports` map omits package.json makes
42+
* it throw, and bun caches its answer per specifier, ignoring `paths`.
43+
*/
3944
function readInstalledVersion(dep: string, cwd: string): string | undefined {
40-
try {
41-
const packageJsonPath = require.resolve(`${dep}/package.json`, {
42-
paths: [cwd],
43-
});
44-
return require(packageJsonPath).version;
45-
} catch {
46-
return undefined;
45+
let dir = path.resolve(cwd);
46+
for (;;) {
47+
try {
48+
const pkg = JSON.parse(
49+
fs.readFileSync(
50+
path.join(dir, 'node_modules', dep, 'package.json'),
51+
'utf8',
52+
),
53+
) as { version?: unknown };
54+
return typeof pkg.version === 'string' ? pkg.version : undefined;
55+
} catch {
56+
// not installed at this level
57+
}
58+
const parent = path.dirname(dir);
59+
if (parent === dir) {
60+
return undefined;
61+
}
62+
dir = parent;
4763
}
4864
}
4965

0 commit comments

Comments
 (0)