| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272 |
- 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) && readPackageName(packageJsonPath)) {
- return currentDir;
- }
- currentDir = dirname(currentDir);
- }
- return null;
- }
- function readRuntimePackage(moduleLookupRoots, moduleName, parentPackagePath = null) {
- if (parentPackagePath) {
- try {
- const requireFromParent = createRequire(parentPackagePath);
- // 优先直接解析 `<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: dirname(packageJsonPath),
- };
- }
- } catch {
- // 父包相对解析失败时,继续走 workspace lookup roots 兜底。
- }
- }
- for (const lookupRoot of moduleLookupRoots) {
- const packageJsonPath = resolve(lookupRoot, "node_modules", moduleName, "package.json");
- if (!existsSync(packageJsonPath)) {
- continue;
- }
- return {
- packageJson: JSON.parse(readFileSync(packageJsonPath, "utf8")),
- packageJsonPath,
- packageRoot: dirname(packageJsonPath),
- };
- }
- return null;
- }
- 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 nodes = new Map(); // packageRoot -> { moduleName, sourceModulePath, packageJsonPath }
- const childByParent = new Map(); // parentPackageRoot -> Map<childPackageRoot, dependencyName>
- const rootsOfName = new Map(); // moduleName -> Set<packageRoot>
- const unresolvedEntries = [];
- 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) {
- if (!optional) {
- // 保持旧行为:不可解析的非可选依赖仍产出一条 sourceModulePath=null 的记录,
- // 交给调用方告警并跳过,而不是在这里中断整个平台的出包。
- unresolvedEntries.push({
- moduleName,
- sourceModulePath: null,
- packageJsonPath: null,
- installRelativePath: `${NODE_MODULES_DIR}/${moduleName}`,
- });
- }
- continue;
- }
- 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: packageRoot,
- packageJsonPath: runtimePackage.packageJsonPath,
- });
- 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 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}`);
- }
- // 从提升节点出发,沿依赖边给未提升的包推导嵌套落位。
- 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 });
- }
- }
- 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;
- }
|