runtime-dependency-closure.mjs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. import { existsSync, readFileSync } from "node:fs";
  2. import { dirname, parse, resolve } from "node:path";
  3. import { createRequire } from "node:module";
  4. const NODE_MODULES_DIR = "node_modules";
  5. /**
  6. * 读取 package.json 的 name 字段。
  7. *
  8. * 修复点:`long` 这类包的 main 指向子目录(`umd/index.js`),而该子目录下另有一个
  9. * 只声明 `{"type":"commonjs"}` 的标记型 package.json(没有 name)。
  10. * 旧的 findPackageRoot 遇到第一个 package.json 就返回,会把 `long/umd` 当成包根,
  11. * 注入到 app.asar 后 `require("long")` 直接解析失败。这里要求候选包根必须声明 name。
  12. */
  13. function readPackageName(packageJsonPath) {
  14. try {
  15. const parsed = JSON.parse(readFileSync(packageJsonPath, "utf8"));
  16. return typeof parsed.name === "string" && parsed.name.length > 0 ? parsed.name : null;
  17. } catch {
  18. return null;
  19. }
  20. }
  21. function findPackageRoot(entryPath) {
  22. let currentDir = dirname(entryPath);
  23. const root = parse(currentDir).root;
  24. while (currentDir !== root) {
  25. const packageJsonPath = resolve(currentDir, "package.json");
  26. if (existsSync(packageJsonPath) && readPackageName(packageJsonPath)) {
  27. return currentDir;
  28. }
  29. currentDir = dirname(currentDir);
  30. }
  31. return null;
  32. }
  33. function readRuntimePackage(moduleLookupRoots, moduleName, parentPackagePath = null) {
  34. if (parentPackagePath) {
  35. try {
  36. const requireFromParent = createRequire(parentPackagePath);
  37. // 优先直接解析 `<module>/package.json`:这是 Node 定位包根的官方方式,
  38. // 不受 main/exports 指向子目录的影响(见上面 long 的说明)。
  39. // 少数包用 exports 屏蔽了 `./package.json`,这时再退回按入口文件向上找。
  40. let packageJsonPath = null;
  41. try {
  42. packageJsonPath = requireFromParent.resolve(`${moduleName}/package.json`);
  43. } catch {
  44. packageJsonPath = null;
  45. }
  46. if (!packageJsonPath) {
  47. const packageRoot = findPackageRoot(requireFromParent.resolve(moduleName));
  48. if (packageRoot) {
  49. packageJsonPath = resolve(packageRoot, "package.json");
  50. }
  51. }
  52. if (packageJsonPath && existsSync(packageJsonPath)) {
  53. return {
  54. packageJson: JSON.parse(readFileSync(packageJsonPath, "utf8")),
  55. packageJsonPath,
  56. packageRoot: dirname(packageJsonPath),
  57. };
  58. }
  59. } catch {
  60. // 父包相对解析失败时,继续走 workspace lookup roots 兜底。
  61. }
  62. }
  63. for (const lookupRoot of moduleLookupRoots) {
  64. const packageJsonPath = resolve(lookupRoot, "node_modules", moduleName, "package.json");
  65. if (!existsSync(packageJsonPath)) {
  66. continue;
  67. }
  68. return {
  69. packageJson: JSON.parse(readFileSync(packageJsonPath, "utf8")),
  70. packageJsonPath,
  71. packageRoot: dirname(packageJsonPath),
  72. };
  73. }
  74. return null;
  75. }
  76. function listDependencyEntries(packageJson) {
  77. const dependencies = packageJson.dependencies ?? {};
  78. const optionalDependencies = packageJson.optionalDependencies ?? {};
  79. return [
  80. ...Object.keys(dependencies).map((dependencyName) => [dependencyName, false]),
  81. ...Object.keys(optionalDependencies).map((dependencyName) => [dependencyName, true]),
  82. ].sort(([left], [right]) => left.localeCompare(right));
  83. }
  84. /** 路径里 `node_modules` 段的个数越多,说明这份副本嵌套得越深。 */
  85. function nestingDepth(packageRoot) {
  86. return packageRoot.split(/[\\/]/).filter((segment) => segment === NODE_MODULES_DIR).length;
  87. }
  88. /**
  89. * 收集运行时依赖闭包,并给出每一项在 app.asar 内应该落到的相对路径。
  90. *
  91. * 返回的每一项形如:
  92. * { moduleName, sourceModulePath, packageJsonPath, installRelativePath }
  93. * 其中 installRelativePath 以 `node_modules/` 开头、使用正斜杠、相对 app.asar 根。
  94. *
  95. * 修复点(产物启动即 Cannot find module 的根因):
  96. * 1. 去重键从「模块名」改成「解析出的包根」。旧实现用 visited.has(moduleName),
  97. * 会把同名不同版本压成一条:yazl 需要 buffer-crc32@^1.0.0、yauzl 需要 ~0.2.3,
  98. * 结果只保留先访问到的那个版本,另一个永远不会被注入。
  99. * 2. 注入时不能把每个包都拍平到 node_modules/<name>。多版本必须按依赖它的父包
  100. * 就近落成 node_modules/<parent>/node_modules/<name>,否则后者会覆盖前者,
  101. * Node 解析链仍然拿不到正确版本。
  102. */
  103. export function collectRuntimeModuleClosureEntries(moduleNames, moduleLookupRoots) {
  104. const nodes = new Map(); // packageRoot -> { moduleName, sourceModulePath, packageJsonPath }
  105. const childByParent = new Map(); // parentPackageRoot -> Map<childPackageRoot, dependencyName>
  106. const rootsOfName = new Map(); // moduleName -> Set<packageRoot>
  107. const unresolvedEntries = [];
  108. const registerName = (moduleName, packageRoot) => {
  109. if (!rootsOfName.has(moduleName)) {
  110. rootsOfName.set(moduleName, new Set());
  111. }
  112. rootsOfName.get(moduleName).add(packageRoot);
  113. };
  114. const queue = moduleNames.map((moduleName) => ({
  115. moduleName,
  116. parentPackagePath: null,
  117. parentPackageRoot: null,
  118. optional: false,
  119. }));
  120. while (queue.length > 0) {
  121. const { moduleName, parentPackagePath, parentPackageRoot, optional } = queue.shift();
  122. const runtimePackage = readRuntimePackage(moduleLookupRoots, moduleName, parentPackagePath);
  123. if (!runtimePackage) {
  124. if (!optional) {
  125. // 保持旧行为:不可解析的非可选依赖仍产出一条 sourceModulePath=null 的记录,
  126. // 交给调用方告警并跳过,而不是在这里中断整个平台的出包。
  127. unresolvedEntries.push({
  128. moduleName,
  129. sourceModulePath: null,
  130. packageJsonPath: null,
  131. installRelativePath: `${NODE_MODULES_DIR}/${moduleName}`,
  132. });
  133. }
  134. continue;
  135. }
  136. const packageRoot = runtimePackage.packageRoot;
  137. registerName(moduleName, packageRoot);
  138. if (parentPackageRoot !== null) {
  139. if (!childByParent.has(parentPackageRoot)) {
  140. childByParent.set(parentPackageRoot, new Map());
  141. }
  142. childByParent.get(parentPackageRoot).set(packageRoot, moduleName);
  143. }
  144. if (nodes.has(packageRoot)) {
  145. // 同一个物理包只展开一次依赖,避免环状依赖无限递归。
  146. continue;
  147. }
  148. nodes.set(packageRoot, {
  149. moduleName,
  150. sourceModulePath: packageRoot,
  151. packageJsonPath: runtimePackage.packageJsonPath,
  152. });
  153. for (const [dependencyName, isOptional] of listDependencyEntries(runtimePackage.packageJson)) {
  154. queue.push({
  155. moduleName: dependencyName,
  156. parentPackagePath: runtimePackage.packageJsonPath,
  157. parentPackageRoot: packageRoot,
  158. optional: isOptional,
  159. });
  160. }
  161. }
  162. // 决定哪些包「提升」到 node_modules/<name>:
  163. // - 同名只解析出一个物理版本 → 提升(与旧行为一致,落位不变)。
  164. // - 同名解析出多个版本 → 只提升嵌套最浅的那个,其余版本按父包就近嵌套。
  165. const placements = new Map(); // packageRoot -> Set<installRelativePath>
  166. const hoistedRoots = new Set();
  167. const addPlacement = (packageRoot, installRelativePath) => {
  168. if (!placements.has(packageRoot)) {
  169. placements.set(packageRoot, new Set());
  170. }
  171. placements.get(packageRoot).add(installRelativePath);
  172. };
  173. for (const [moduleName, packageRoots] of rootsOfName) {
  174. const sorted = [...packageRoots].sort(
  175. (left, right) => nestingDepth(left) - nestingDepth(right) || left.localeCompare(right),
  176. );
  177. const hoistedRoot = sorted[0];
  178. hoistedRoots.add(hoistedRoot);
  179. addPlacement(hoistedRoot, `${NODE_MODULES_DIR}/${moduleName}`);
  180. }
  181. // 从提升节点出发,沿依赖边给未提升的包推导嵌套落位。
  182. const pending = [...hoistedRoots].map((packageRoot) => ({
  183. packageRoot,
  184. installRelativePath: [...placements.get(packageRoot)][0],
  185. }));
  186. const visitedPlacements = new Set();
  187. while (pending.length > 0) {
  188. const { packageRoot, installRelativePath } = pending.shift();
  189. const visitKey = `${packageRoot}\u0000${installRelativePath}`;
  190. if (visitedPlacements.has(visitKey)) {
  191. continue;
  192. }
  193. visitedPlacements.add(visitKey);
  194. const children = childByParent.get(packageRoot);
  195. if (!children) {
  196. continue;
  197. }
  198. for (const [childPackageRoot, dependencyName] of children) {
  199. const childNestedPath = `${installRelativePath}/${NODE_MODULES_DIR}/${dependencyName}`;
  200. const childInstallPath = hoistedRoots.has(childPackageRoot)
  201. ? [...placements.get(childPackageRoot)][0]
  202. : childNestedPath;
  203. if (!hoistedRoots.has(childPackageRoot)) {
  204. addPlacement(childPackageRoot, childNestedPath);
  205. }
  206. pending.push({ packageRoot: childPackageRoot, installRelativePath: childInstallPath });
  207. }
  208. }
  209. const entries = [];
  210. for (const [packageRoot, node] of nodes) {
  211. const packagePlacements = placements.get(packageRoot);
  212. if (!packagePlacements || packagePlacements.size === 0) {
  213. // 兜底:理论上不该发生(每个节点都能沿父链回溯到某个提升节点),
  214. // 真遇到就退回旧的拍平落位,保证不会静默漏包。
  215. entries.push({ ...node, installRelativePath: `${NODE_MODULES_DIR}/${node.moduleName}` });
  216. continue;
  217. }
  218. for (const installRelativePath of packagePlacements) {
  219. entries.push({ ...node, installRelativePath });
  220. }
  221. }
  222. entries.sort(
  223. (left, right) =>
  224. left.moduleName.localeCompare(right.moduleName) ||
  225. left.installRelativePath.localeCompare(right.installRelativePath),
  226. );
  227. return [...entries, ...unresolvedEntries];
  228. }
  229. export function collectRuntimeModuleClosure(moduleNames, moduleLookupRoots) {
  230. const seen = new Set();
  231. const names = [];
  232. for (const entry of collectRuntimeModuleClosureEntries(moduleNames, moduleLookupRoots)) {
  233. if (seen.has(entry.moduleName)) {
  234. continue;
  235. }
  236. seen.add(entry.moduleName);
  237. names.push(entry.moduleName);
  238. }
  239. return names;
  240. }