bootstrap-patched-dependencies.mjs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import { access, readFile, rm } from "node:fs/promises";
  2. import { join } from "node:path";
  3. export function resolvePatchedDependencyPackageName(key) {
  4. const value = key.trim();
  5. const match = value.startsWith("@")
  6. ? value.match(/^(@[^/]+\/[^@]+)@/u)
  7. : value.match(/^([^@]+)@/u);
  8. if (!match?.[1]) {
  9. throw new Error(`Invalid patched dependency key: ${key}`);
  10. }
  11. return match[1];
  12. }
  13. async function pathExists(path) {
  14. return await access(path).then(
  15. () => true,
  16. () => false,
  17. );
  18. }
  19. export async function clearHoistedPatchedDependencyTargets({ rootDir, packageJsonPath }) {
  20. const packageJson = JSON.parse(await readFile(packageJsonPath, "utf8"));
  21. const patchedDependencies = packageJson.pnpm?.patchedDependencies ?? {};
  22. const packageNames = Object.keys(patchedDependencies).map(resolvePatchedDependencyPackageName);
  23. const removed = [];
  24. for (const packageName of packageNames) {
  25. const target = join(rootDir, "node_modules", ...packageName.split("/"));
  26. if (!(await pathExists(target))) continue;
  27. // Bug 原因:pnpm 10 + node-linker=hoisted 会把 patch 直接应用到目标目录;下一次
  28. // install 再对已 patch 内容应用同一 diff 并稳定失败。这里只清理可重建的依赖目标,
  29. // 不碰 store 或用户文件,让 pnpm 从原包重新应用一次 patch。
  30. await rm(target, { recursive: true, force: true });
  31. removed.push(packageName);
  32. }
  33. return removed;
  34. }