Просмотр исходного кода

fix(desktop): 修复 app.asar 运行时依赖闭包漏包与错误落位

打包产物启动即崩溃:Cannot find module 'buffer-crc32'
(require stack: app.asar/node_modules/yazl/index.js)。

根因是运行时依赖闭包的三处缺陷:

1. collectRuntimeModuleClosureEntries 用 visited.has(moduleName) 去重,
   把同名不同版本压成一条。yazl 需要 buffer-crc32@^1.0.0、yauzl 需要
   ~0.2.3,旧实现只保留先访问到的那个版本,另一个永远不会被注入。
   改为按「解析出的包根」建节点,并输出 installRelativePath:同名多版本
   时只提升嵌套最浅的那份,其余按父包就近落成
   node_modules/<父包>/node_modules/<name>,避免复制阶段互相覆盖。

2. findPackageRoot 取第一个遇到的 package.json 当包根,会把 long/umd
   (只含 {"type":"commonjs"}、没有 name)误判成包根,注入后
   require("long") 直接失败。改为优先解析 <module>/package.json,
   退回向上查找时也要求候选包根必须声明 name。

3. afterPack 用 asar pack 重写 app.asar 时,--unpack-dir 是单值选项
   (commander 只保留最后一次),且本版 @electron/asar 下 ** glob 不生效。
   旧实现固定只传 node-pty/prebuilds/<key>,重写一次就丢一层
   electron-builder 原本的 unpack 布局;sourcemap 清理那次连
   targetPlatformKey 都没传,会退化成 prebuilds/undefined(macOS 上不带
   扩展名的 spawn-helper 会被 pack 回 archive)。改为重写前从 archive
   读出真实 unpack 布局,用 brace glob 一次传全,并在 sourcemap 清理的
   二次重写中同样保留。

bundle.mjs 的产物机械校验同步改为按 installRelativePath 逐项检查,报错时
列出期望落位,否则新逻辑下的嵌套版本会被误判为齐全而漏报。

验证:
- pnpm lint(oxlint,2556 文件)0 error;pnpm typecheck 0 error
- 闭包单测:buffer-crc32 两版各自落位正确;long 源不再是 long/umd
- 用修复后源码重跑 afterPack 注入全流程(先按原始产物的条目集重建缺陷):
  41 条落位、缺失 0、242 个 unpacked 条目与原始产物一致
- 重新产出的 win-unpacked 启动正常,主进程无 Cannot find module
wubinggen 2 месяцев назад
Родитель
Сommit
8730138bea

+ 40 - 13
packages/desktop/electron-builder.config.js

@@ -62,7 +62,10 @@ import {
   createDesktopNativePackagePrunePatterns,
   parseAsarListWithPackState,
 } from "./scripts/desktop-native-package-policy.mjs";
-import { replaceAppAsarFromStaging } from "./scripts/app-asar-repack.mjs";
+import {
+  replaceAppAsarFromStaging,
+  resolveUnpackPackageDirsFromAsarList,
+} from "./scripts/app-asar-repack.mjs";
 import {
   patchNsisInstallSectionFile,
   restoreNsisInstallSectionFileSync,
@@ -324,13 +327,15 @@ function resolveMissingRuntimeModules(appAsarPath) {
     return true;
   });
   return resolvableRuntimeModules.filter((entry) => {
-    const { moduleName } = entry;
-    const moduleRoot = `/node_modules/${moduleName}`;
+    // 落位路径由依赖闭包给出:同名多版本时,非提升版本会落到
+    // `node_modules/<父包>/node_modules/<name>`。这里必须按落位路径判断,
+    // 否则嵌套版本会被「同名包已存在」误判为齐全而漏注入。
+    const moduleRoot = `/${entry.installRelativePath}`;
     if (asarEntrySet.has(moduleRoot)) {
       return false;
     }
-    for (const entry of asarEntrySet) {
-      if (entry.startsWith(`${moduleRoot}/`)) {
+    for (const asarEntry of asarEntrySet) {
+      if (asarEntry.startsWith(`${moduleRoot}/`)) {
         return false;
       }
     }
@@ -338,6 +343,22 @@ function resolveMissingRuntimeModules(appAsarPath) {
   });
 }
 
+/**
+ * 读出当前 archive 的 unpack 布局,供重写时原样保留。
+ * `--unpack-dir` 只能接收一个表达式,重写前先取快照、重写时一次传全,
+ * 避免 afterPack 每重写一次就丢一层 electron-builder 原本的 unpack 结果。
+ */
+function resolveCurrentUnpackDirs(appAsarPath) {
+  if (!existsSync(appAsarPath)) {
+    return [];
+  }
+  return runTimedSync("afterPack:scan-unpack-layout", () =>
+    resolveUnpackPackageDirsFromAsarList(
+      runAsarCommandAndReadStdout(["list", "--is-pack", appAsarPath]),
+    ),
+  );
+}
+
 async function injectHoistedRuntimeModulesIntoAsar(context) {
   const appAsarPath = resolveAppAsarPath(context);
   if (!existsSync(appAsarPath)) {
@@ -355,6 +376,9 @@ async function injectHoistedRuntimeModulesIntoAsar(context) {
   }
   console.log(`[afterPack] missing runtime modules count=${missingRuntimeModules.length}`);
 
+  // 重写前先快照当前 archive 的 unpack 布局,重写时原样保留。
+  const preservedUnpackDirs = resolveCurrentUnpackDirs(appAsarPath);
+
   // CI 会把 TMPDIR 指到项目内 .tmp,GitLab get_sources/clean 可能在脚本启动前清掉该目录。
   // afterPack 里重写 app.asar 同样依赖 mkdtempSync,必须自己兜底创建父目录,避免后续签名阶段只看到 .app 消失。
   mkdirSync(tmpdir(), { recursive: true });
@@ -364,13 +388,13 @@ async function injectHoistedRuntimeModulesIntoAsar(context) {
       runAsarCommand(["extract", appAsarPath, stagingDir]),
     );
 
-    const stagingNodeModulesDir = resolve(stagingDir, "node_modules");
-    mkdirSync(stagingNodeModulesDir, { recursive: true });
-
     runTimedSync("afterPack:copy-runtime-modules", () => {
       for (const runtimeModule of missingRuntimeModules) {
-        const { moduleName, sourceModulePath } = runtimeModule;
-        const targetModulePath = resolve(stagingNodeModulesDir, moduleName);
+        const { moduleName, sourceModulePath, installRelativePath } = runtimeModule;
+        // 按闭包给出的落位路径复制,而不是统一拍平到 node_modules/<name>。
+        // 同名多版本(如 yazl 要 buffer-crc32@1.x、yauzl 要 ~0.2.x)必须各自就位,
+        // 否则后复制的会覆盖先复制的,Node 解析链仍会拿到错误版本。
+        const targetModulePath = resolve(stagingDir, ...installRelativePath.split("/"));
 
         if (!sourceModulePath) {
           throw new Error(
@@ -397,7 +421,7 @@ async function injectHoistedRuntimeModulesIntoAsar(context) {
       replaceAppAsarFromStaging({
         sourceDir: stagingDir,
         appAsarPath,
-        targetPlatformKey: targetPlatform.key,
+        unpackDirs: preservedUnpackDirs,
         runAsarCommand,
       }),
     );
@@ -416,11 +440,14 @@ async function stripPackagedSourcemapReferences(context) {
     runAsarCommand,
     runTimedSync,
     runTimedAsync,
-    replaceAppAsarFromStaging: ({ sourceDir, appAsarPath }) =>
+    // 这次重写同样会替换 app.asar,必须先快照 unpack 布局再原样带过去,
+    // 否则 sourcemap 清理会把注入阶段刚恢复的 unpack 结果又抹掉一次。
+    resolveUnpackDirs: resolveCurrentUnpackDirs,
+    replaceAppAsarFromStaging: ({ sourceDir, appAsarPath, unpackDirs }) =>
       replaceAppAsarFromStaging({
         sourceDir,
         appAsarPath,
-        targetPlatformKey: targetPlatform.key,
+        unpackDirs,
         runAsarCommand,
       }),
   });

+ 57 - 12
packages/desktop/scripts/app-asar-repack.mjs

@@ -11,22 +11,67 @@ async function pathExists(path) {
   }
 }
 
-export function createAppAsarPackArgs({ sourceDir, destinationPath, targetPlatformKey }) {
-  return [
-    "pack",
-    sourceDir,
-    destinationPath,
-    "--unpack",
-    ASAR_UNPACK_NATIVE_GLOB,
-    "--unpack-dir",
-    `node_modules/node-pty/prebuilds/${targetPlatformKey}`,
-  ];
+function normalizeAsarEntryPath(entry) {
+  const normalized = entry.trim().replaceAll("\\", "/");
+  return normalized.startsWith("/") ? normalized.slice(1) : normalized;
+}
+
+/**
+ * 从 `asar list --is-pack` 的输出里取出「存在 unpack 文件」的包目录。
+ *
+ * 修复点:afterPack 会用 `asar pack` 重写 app.asar,而 `--unpack-dir` 是单值选项
+ * (commander 只保留最后一次),并且本版 @electron/asar 下 `**` 形式的 glob 完全
+ * 不生效(`*` 已能跨目录匹配)。
+ *
+ * 旧实现固定只传 `node_modules/node-pty/prebuilds/<targetPlatformKey>`,于是重写后:
+ *  - electron-builder 原本整包 unpack 的依赖(如 ssh2)被重新塞回 archive;
+ *  - 走 sourcemap 清理那次重写时连 targetPlatformKey 都没有,会退化成
+ *    `node-pty/prebuilds/undefined`,macOS 上不带扩展名的 `spawn-helper` 因此被 pack。
+ *
+ * 这里改为先把当前 archive 的 unpack 布局读出来,重写时原样保留,避免「重写一次
+ * 就静默丢一次布局」。返回的是包级目录(如 `node_modules/jszip`),整体 unpack
+ * 比逐文件 unpack 更稳,代价只是 sidecar 稍大。
+ */
+export function resolveUnpackPackageDirsFromAsarList(asarListOutput) {
+  const packageDirs = new Set();
+
+  for (const line of asarListOutput.split("\n")) {
+    const match = /^unpack\s*:\s*(.+)$/.exec(line.trim());
+    if (!match) {
+      continue;
+    }
+
+    const segments = normalizeAsarEntryPath(match[1]).split("/");
+    if (segments[0] !== "node_modules" || !segments[1]) {
+      continue;
+    }
+
+    // 作用域包占两段:node_modules/@scope/name
+    const packageLength = segments[1].startsWith("@") ? 3 : 2;
+    if (segments.length < packageLength) {
+      continue;
+    }
+    packageDirs.add(segments.slice(0, packageLength).join("/"));
+  }
+
+  return [...packageDirs].sort();
+}
+
+export function createAppAsarPackArgs({ sourceDir, destinationPath, unpackDirs = [] }) {
+  const args = ["pack", sourceDir, destinationPath, "--unpack", ASAR_UNPACK_NATIVE_GLOB];
+
+  if (unpackDirs.length > 0) {
+    // `--unpack-dir` 只能接收一个表达式,用 brace glob 一次覆盖多个目录。
+    args.push("--unpack-dir", `{${unpackDirs.join(",")}}`);
+  }
+
+  return args;
 }
 
 export async function replaceAppAsarFromStaging({
   sourceDir,
   appAsarPath,
-  targetPlatformKey,
+  unpackDirs = [],
   runAsarCommand,
 }) {
   const candidateAsarPath = `${appAsarPath}.next`;
@@ -43,7 +88,7 @@ export async function replaceAppAsarFromStaging({
       createAppAsarPackArgs({
         sourceDir,
         destinationPath: candidateAsarPath,
-        targetPlatformKey,
+        unpackDirs,
       }),
     );
 

+ 17 - 5
packages/desktop/scripts/bundle.mjs

@@ -682,20 +682,32 @@ function verifyPackagedRuntimeDependencies(os, arch) {
     return true;
   });
 
-  for (const { moduleName } of resolvableRuntimeModules) {
-    const moduleRoot = `/node_modules/${moduleName}`;
+  const missingRuntimeModules = [];
+  for (const runtimeModule of resolvableRuntimeModules) {
+    // 落位路径由依赖闭包给出:同名多版本时,非提升版本会落到
+    // `node_modules/<父包>/node_modules/<name>`。旧实现按模块名做扁平匹配,
+    // 既判断不出「版本不对」,也判断不出「嵌套版本缺失」。
+    const moduleRoot = `/${runtimeModule.installRelativePath}`;
     // @electron/asar 在 Windows 下列目录时会通过 path.join 产出反斜杠路径,
     // 之前这里按 POSIX 路径做精确匹配,导致模块其实已经打进 app.asar,校验却仍然误报缺失。
     // 先统一归一化成正斜杠,避免 Windows 打包机被这道机械校验误伤。
     const hasModule = asarEntries.some(
-      (entry) => entry === moduleRoot || entry.startsWith(`${moduleRoot}/`),
+      (asarEntry) => asarEntry === moduleRoot || asarEntry.startsWith(`${moduleRoot}/`),
     );
 
     if (!hasModule) {
-      // 校验也按依赖闭包展开,确保 afterPack 注入逻辑遗漏子依赖时能在 bundle 阶段直接失败。
-      throw new Error(`打包产物缺少运行时依赖 ${moduleName}: ${appAsarPath}`);
+      missingRuntimeModules.push(runtimeModule);
     }
   }
+
+  if (missingRuntimeModules.length > 0) {
+    // 校验也按依赖闭包展开,确保 afterPack 注入逻辑遗漏子依赖时能在 bundle 阶段直接失败。
+    throw new Error(
+      `打包产物缺少运行时依赖:\n- ${missingRuntimeModules
+        .map((runtimeModule) => `${runtimeModule.moduleName} (期望落位 /${runtimeModule.installRelativePath})`)
+        .join("\n- ")}\n${appAsarPath}`,
+    );
+  }
 }
 
 async function main() {

+ 8 - 1
packages/desktop/scripts/packaged-sourcemap-cleanup.mjs

@@ -82,6 +82,7 @@ export async function cleanupPackagedSourcemaps({
   runAsarCommand,
   runTimedSync,
   runTimedAsync,
+  resolveUnpackDirs,
   replaceAppAsarFromStaging,
   logger = console,
 }) {
@@ -99,7 +100,13 @@ export async function cleanupPackagedSourcemaps({
           `[afterPack] stripped sourceMappingURL references=${stripSummary.referencesRemoved} files=${stripSummary.filesChanged} maps=${mapSummary.filesRemoved}`,
         );
         await runTimedAsync("afterPack:sourcemap-cleanup:asar-pack", () =>
-          replaceAppAsarFromStaging({ sourceDir: stagingDir, appAsarPath }),
+          replaceAppAsarFromStaging({
+            sourceDir: stagingDir,
+            appAsarPath,
+            // 重写前取 unpack 布局快照,避免这次重写丢掉 electron-builder 或
+            // afterPack 注入阶段已经确定的 unpack 结果。
+            unpackDirs: resolveUnpackDirs ? resolveUnpackDirs(appAsarPath) : [],
+          }),
         );
       } else {
         logger.log("[afterPack] app.asar sourcemap cleanup found no references");

+ 207 - 43
packages/desktop/scripts/runtime-dependency-closure.mjs

@@ -2,12 +2,31 @@ import { existsSync, readFileSync } from "node:fs";
 import { dirname, parse, resolve } from "node:path";
 import { createRequire } from "node:module";
 
+const NODE_MODULES_DIR = "node_modules";
+
+/**
+ * 读取 package.json 的 name 字段。
+ *
+ * 修复点:`long` 这类包的 main 指向子目录(`umd/index.js`),而该子目录下另有一个
+ * 只声明 `{"type":"commonjs"}` 的标记型 package.json(没有 name)。
+ * 旧的 findPackageRoot 遇到第一个 package.json 就返回,会把 `long/umd` 当成包根,
+ * 注入到 app.asar 后 `require("long")` 直接解析失败。这里要求候选包根必须声明 name。
+ */
+function readPackageName(packageJsonPath) {
+  try {
+    const parsed = JSON.parse(readFileSync(packageJsonPath, "utf8"));
+    return typeof parsed.name === "string" && parsed.name.length > 0 ? parsed.name : null;
+  } catch {
+    return null;
+  }
+}
+
 function findPackageRoot(entryPath) {
   let currentDir = dirname(entryPath);
   const root = parse(currentDir).root;
   while (currentDir !== root) {
     const packageJsonPath = resolve(currentDir, "package.json");
-    if (existsSync(packageJsonPath)) {
+    if (existsSync(packageJsonPath) && readPackageName(packageJsonPath)) {
       return currentDir;
     }
     currentDir = dirname(currentDir);
@@ -19,14 +38,28 @@ function readRuntimePackage(moduleLookupRoots, moduleName, parentPackagePath = n
   if (parentPackagePath) {
     try {
       const requireFromParent = createRequire(parentPackagePath);
-      const entryPath = requireFromParent.resolve(moduleName);
-      const packageRoot = findPackageRoot(entryPath);
-      if (packageRoot) {
-        const packageJsonPath = resolve(packageRoot, "package.json");
+
+      // 优先直接解析 `<module>/package.json`:这是 Node 定位包根的官方方式,
+      // 不受 main/exports 指向子目录的影响(见上面 long 的说明)。
+      // 少数包用 exports 屏蔽了 `./package.json`,这时再退回按入口文件向上找。
+      let packageJsonPath = null;
+      try {
+        packageJsonPath = requireFromParent.resolve(`${moduleName}/package.json`);
+      } catch {
+        packageJsonPath = null;
+      }
+      if (!packageJsonPath) {
+        const packageRoot = findPackageRoot(requireFromParent.resolve(moduleName));
+        if (packageRoot) {
+          packageJsonPath = resolve(packageRoot, "package.json");
+        }
+      }
+
+      if (packageJsonPath && existsSync(packageJsonPath)) {
         return {
           packageJson: JSON.parse(readFileSync(packageJsonPath, "utf8")),
           packageJsonPath,
-          packageRoot,
+          packageRoot: dirname(packageJsonPath),
         };
       }
     } catch {
@@ -49,60 +82,191 @@ function readRuntimePackage(moduleLookupRoots, moduleName, parentPackagePath = n
   return null;
 }
 
-export function collectRuntimeModuleClosure(moduleNames, moduleLookupRoots) {
-  return collectRuntimeModuleClosureEntries(moduleNames, moduleLookupRoots).map(
-    (entry) => entry.moduleName,
-  );
+function listDependencyEntries(packageJson) {
+  const dependencies = packageJson.dependencies ?? {};
+  const optionalDependencies = packageJson.optionalDependencies ?? {};
+
+  return [
+    ...Object.keys(dependencies).map((dependencyName) => [dependencyName, false]),
+    ...Object.keys(optionalDependencies).map((dependencyName) => [dependencyName, true]),
+  ].sort(([left], [right]) => left.localeCompare(right));
+}
+
+/** 路径里 `node_modules` 段的个数越多,说明这份副本嵌套得越深。 */
+function nestingDepth(packageRoot) {
+  return packageRoot.split(/[\\/]/).filter((segment) => segment === NODE_MODULES_DIR).length;
 }
 
+/**
+ * 收集运行时依赖闭包,并给出每一项在 app.asar 内应该落到的相对路径。
+ *
+ * 返回的每一项形如:
+ *   { moduleName, sourceModulePath, packageJsonPath, installRelativePath }
+ * 其中 installRelativePath 以 `node_modules/` 开头、使用正斜杠、相对 app.asar 根。
+ *
+ * 修复点(产物启动即 Cannot find module 的根因):
+ *  1. 去重键从「模块名」改成「解析出的包根」。旧实现用 visited.has(moduleName),
+ *     会把同名不同版本压成一条:yazl 需要 buffer-crc32@^1.0.0、yauzl 需要 ~0.2.3,
+ *     结果只保留先访问到的那个版本,另一个永远不会被注入。
+ *  2. 注入时不能把每个包都拍平到 node_modules/<name>。多版本必须按依赖它的父包
+ *     就近落成 node_modules/<parent>/node_modules/<name>,否则后者会覆盖前者,
+ *     Node 解析链仍然拿不到正确版本。
+ */
 export function collectRuntimeModuleClosureEntries(moduleNames, moduleLookupRoots) {
-  const collected = [];
-  const visited = new Set();
+  const nodes = new Map(); // packageRoot -> { moduleName, sourceModulePath, packageJsonPath }
+  const childByParent = new Map(); // parentPackageRoot -> Map<childPackageRoot, dependencyName>
+  const rootsOfName = new Map(); // moduleName -> Set<packageRoot>
+  const unresolvedEntries = [];
 
-  function visit(moduleName, optional = false, parentPackagePath = null) {
-    if (visited.has(moduleName)) {
-      return;
+  const registerName = (moduleName, packageRoot) => {
+    if (!rootsOfName.has(moduleName)) {
+      rootsOfName.set(moduleName, new Set());
     }
+    rootsOfName.get(moduleName).add(packageRoot);
+  };
 
+  const queue = moduleNames.map((moduleName) => ({
+    moduleName,
+    parentPackagePath: null,
+    parentPackageRoot: null,
+    optional: false,
+  }));
+
+  while (queue.length > 0) {
+    const { moduleName, parentPackagePath, parentPackageRoot, optional } = queue.shift();
     const runtimePackage = readRuntimePackage(moduleLookupRoots, moduleName, parentPackagePath);
-    if (!runtimePackage && optional) {
-      return;
+
+    if (!runtimePackage) {
+      if (!optional) {
+        // 保持旧行为:不可解析的非可选依赖仍产出一条 sourceModulePath=null 的记录,
+        // 交给调用方告警并跳过,而不是在这里中断整个平台的出包。
+        unresolvedEntries.push({
+          moduleName,
+          sourceModulePath: null,
+          packageJsonPath: null,
+          installRelativePath: `${NODE_MODULES_DIR}/${moduleName}`,
+        });
+      }
+      continue;
     }
 
-    visited.add(moduleName);
-    collected.push({
+    const packageRoot = runtimePackage.packageRoot;
+    registerName(moduleName, packageRoot);
+
+    if (parentPackageRoot !== null) {
+      if (!childByParent.has(parentPackageRoot)) {
+        childByParent.set(parentPackageRoot, new Map());
+      }
+      childByParent.get(parentPackageRoot).set(packageRoot, moduleName);
+    }
+
+    if (nodes.has(packageRoot)) {
+      // 同一个物理包只展开一次依赖,避免环状依赖无限递归。
+      continue;
+    }
+
+    nodes.set(packageRoot, {
       moduleName,
-      sourceModulePath: runtimePackage?.packageRoot ?? null,
-      packageJsonPath: runtimePackage?.packageJsonPath ?? null,
+      sourceModulePath: packageRoot,
+      packageJsonPath: runtimePackage.packageJsonPath,
     });
 
-    if (!runtimePackage) {
-      return;
+    for (const [dependencyName, isOptional] of listDependencyEntries(runtimePackage.packageJson)) {
+      queue.push({
+        moduleName: dependencyName,
+        parentPackagePath: runtimePackage.packageJsonPath,
+        parentPackageRoot: packageRoot,
+        optional: isOptional,
+      });
     }
+  }
+
+  // 决定哪些包「提升」到 node_modules/<name>:
+  //  - 同名只解析出一个物理版本 → 提升(与旧行为一致,落位不变)。
+  //  - 同名解析出多个版本 → 只提升嵌套最浅的那个,其余版本按父包就近嵌套。
+  const placements = new Map(); // packageRoot -> Set<installRelativePath>
+  const hoistedRoots = new Set();
 
-    const { packageJson, packageJsonPath } = runtimePackage;
-    const dependencies = packageJson.dependencies ?? {};
-    const optionalDependencies = packageJson.optionalDependencies ?? {};
-    const dependencyEntries = [
-      ...Object.keys(dependencies).map((dependencyName) => [dependencyName, false]),
-      ...Object.keys(optionalDependencies).map((dependencyName) => [dependencyName, true]),
-    ];
-
-    for (const [dependencyName, isOptional] of dependencyEntries.sort(([left], [right]) =>
-      left.localeCompare(right),
-    )) {
-      // 运行时外置包进了 app.asar 时,它的 hoisted 子依赖不会自动跟着进包。
-      // 递归收集 dependencies,让打包注入和产物校验覆盖完整运行时解析链。
-      // pnpm 多版本同名依赖下,不能每层都从固定 lookup roots 取第一个目录。
-      // 例如 yazl 需要 buffer-crc32@1.x,而 desktop 测试依赖里还有 0.2.x;
-      // 必须从父包 package.json 相对解析,才能复制到真实运行时会加载的版本。
-      visit(dependencyName, isOptional, packageJsonPath);
+  const addPlacement = (packageRoot, installRelativePath) => {
+    if (!placements.has(packageRoot)) {
+      placements.set(packageRoot, new Set());
     }
+    placements.get(packageRoot).add(installRelativePath);
+  };
+
+  for (const [moduleName, packageRoots] of rootsOfName) {
+    const sorted = [...packageRoots].sort(
+      (left, right) => nestingDepth(left) - nestingDepth(right) || left.localeCompare(right),
+    );
+    const hoistedRoot = sorted[0];
+    hoistedRoots.add(hoistedRoot);
+    addPlacement(hoistedRoot, `${NODE_MODULES_DIR}/${moduleName}`);
   }
 
-  for (const moduleName of moduleNames) {
-    visit(moduleName);
+  // 从提升节点出发,沿依赖边给未提升的包推导嵌套落位。
+  const pending = [...hoistedRoots].map((packageRoot) => ({
+    packageRoot,
+    installRelativePath: [...placements.get(packageRoot)][0],
+  }));
+  const visitedPlacements = new Set();
+
+  while (pending.length > 0) {
+    const { packageRoot, installRelativePath } = pending.shift();
+    const visitKey = `${packageRoot}\u0000${installRelativePath}`;
+    if (visitedPlacements.has(visitKey)) {
+      continue;
+    }
+    visitedPlacements.add(visitKey);
+
+    const children = childByParent.get(packageRoot);
+    if (!children) {
+      continue;
+    }
+
+    for (const [childPackageRoot, dependencyName] of children) {
+      const childNestedPath = `${installRelativePath}/${NODE_MODULES_DIR}/${dependencyName}`;
+      const childInstallPath = hoistedRoots.has(childPackageRoot)
+        ? [...placements.get(childPackageRoot)][0]
+        : childNestedPath;
+      if (!hoistedRoots.has(childPackageRoot)) {
+        addPlacement(childPackageRoot, childNestedPath);
+      }
+      pending.push({ packageRoot: childPackageRoot, installRelativePath: childInstallPath });
+    }
   }
 
-  return collected;
+  const entries = [];
+  for (const [packageRoot, node] of nodes) {
+    const packagePlacements = placements.get(packageRoot);
+    if (!packagePlacements || packagePlacements.size === 0) {
+      // 兜底:理论上不该发生(每个节点都能沿父链回溯到某个提升节点),
+      // 真遇到就退回旧的拍平落位,保证不会静默漏包。
+      entries.push({ ...node, installRelativePath: `${NODE_MODULES_DIR}/${node.moduleName}` });
+      continue;
+    }
+    for (const installRelativePath of packagePlacements) {
+      entries.push({ ...node, installRelativePath });
+    }
+  }
+
+  entries.sort(
+    (left, right) =>
+      left.moduleName.localeCompare(right.moduleName) ||
+      left.installRelativePath.localeCompare(right.installRelativePath),
+  );
+
+  return [...entries, ...unresolvedEntries];
+}
+
+export function collectRuntimeModuleClosure(moduleNames, moduleLookupRoots) {
+  const seen = new Set();
+  const names = [];
+  for (const entry of collectRuntimeModuleClosureEntries(moduleNames, moduleLookupRoots)) {
+    if (seen.has(entry.moduleName)) {
+      continue;
+    }
+    seen.add(entry.moduleName);
+    names.push(entry.moduleName);
+  }
+  return names;
 }