app-builder-lib 26.16.0 → 26.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/out/codeSign/macCodeSign.js +5 -3
  2. package/out/codeSign/macCodeSign.js.map +1 -1
  3. package/out/codeSign/windowsCodeSign.js +0 -3
  4. package/out/codeSign/windowsCodeSign.js.map +1 -1
  5. package/out/codeSign/windowsSignToolManager.js +4 -1
  6. package/out/codeSign/windowsSignToolManager.js.map +1 -1
  7. package/out/electron/ElectronFramework.d.ts +2 -1
  8. package/out/electron/ElectronFramework.js +13 -5
  9. package/out/electron/ElectronFramework.js.map +1 -1
  10. package/out/electron/electronMac.js +1 -5
  11. package/out/electron/electronMac.js.map +1 -1
  12. package/out/node-module-collector/index.js +48 -15
  13. package/out/node-module-collector/index.js.map +1 -1
  14. package/out/node-module-collector/moduleManager.d.ts +7 -1
  15. package/out/node-module-collector/moduleManager.js +2 -2
  16. package/out/node-module-collector/moduleManager.js.map +1 -1
  17. package/out/node-module-collector/nodeModulesCollector.d.ts +7 -3
  18. package/out/node-module-collector/nodeModulesCollector.js +26 -8
  19. package/out/node-module-collector/nodeModulesCollector.js.map +1 -1
  20. package/out/node-module-collector/pnpmNodeModulesCollector.d.ts +42 -0
  21. package/out/node-module-collector/pnpmNodeModulesCollector.js +146 -0
  22. package/out/node-module-collector/pnpmNodeModulesCollector.js.map +1 -1
  23. package/out/packager.d.ts +2 -0
  24. package/out/packager.js +15 -0
  25. package/out/packager.js.map +1 -1
  26. package/out/platformPackager.d.ts +1 -0
  27. package/out/platformPackager.js +3 -0
  28. package/out/platformPackager.js.map +1 -1
  29. package/out/targets/FlatpakTarget.js +6 -1
  30. package/out/targets/FlatpakTarget.js.map +1 -1
  31. package/out/targets/archive.d.ts +12 -0
  32. package/out/targets/archive.js +45 -1
  33. package/out/targets/archive.js.map +1 -1
  34. package/out/targets/nsis/NsisTarget.d.ts +2 -2
  35. package/out/targets/nsis/NsisTarget.js +13 -1
  36. package/out/targets/nsis/NsisTarget.js.map +1 -1
  37. package/out/targets/nsis/nsisOptions.d.ts +15 -2
  38. package/out/targets/nsis/nsisOptions.js.map +1 -1
  39. package/out/targets/nsis/nsisUtil.d.ts +5 -2
  40. package/out/targets/nsis/nsisUtil.js +48 -24
  41. package/out/targets/nsis/nsisUtil.js.map +1 -1
  42. package/out/targets/pkg.d.ts +16 -0
  43. package/out/targets/pkg.js +27 -0
  44. package/out/targets/pkg.js.map +1 -1
  45. package/out/util/appFileCopier.d.ts +5 -0
  46. package/out/util/appFileCopier.js +19 -1
  47. package/out/util/appFileCopier.js.map +1 -1
  48. package/out/version.d.ts +1 -1
  49. package/out/version.js +1 -1
  50. package/out/version.js.map +1 -1
  51. package/package.json +7 -7
  52. package/scheme.json +16 -4
@@ -1 +1 @@
1
- {"version":3,"file":"nodeModulesCollector.js","sourceRoot":"","sources":["../../src/node-module-collector/nodeModulesCollector.ts"],"names":[],"mappings":";;;AAseA,gEAMC;AA5eD,+CAAgF;AAChF,8CAA6C;AAC7C,+BAA8B;AAC9B,uCAA4C;AAC5C,uCAA+B;AAC/B,6BAA4B;AAC5B,mCAAqE;AACrE,mDAAgE;AAChE,qDAA+D;AAG/D,MAAsB,oBAAoB;IAsBxC,YACqB,OAAe,EACjB,cAAsB;QADpB,YAAO,GAAP,OAAO,CAAQ;QACjB,mBAAc,GAAd,cAAc,CAAQ;QAvBxB,gBAAW,GAAqB,EAAE,CAAA;QAChC,oBAAe,GAA6B,IAAI,GAAG,EAAE,CAAA;QACrD,oBAAe,GAAoB,EAAE,CAAA;QACrC,UAAK,GAAkB,IAAI,6BAAa,EAAE,CAAA;QAEnD,cAAS,GAAG,IAAI,eAAI,CAAU,KAAK,IAAI,EAAE;YACjD,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC,cAAc,CAAA;YACvC,MAAM,OAAO,GAAG,IAAA,yCAAwB,EAAC,OAAO,CAAC,CAAA;YACjD,MAAM,M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G;AACH,SAAgB,0BAA0B,CAAC,OAAe,EAAE,IAAc;IACxE,MAAM,OAAO,GAAG,CAAC,KAAa,EAAE,EAAE,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAA;IACnE,MAAM,UAAU,GAAG,CAAC,GAAG,EAAE,OAAO,CAAC,OAAO,CAAC,EAAE,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;IAC1E,MAAM,MAAM,GAAG,sEAAsE,UAAU,sBAAsB,CAAA;IACrH,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAA;IACjE,OAAO,CAAC,YAAY,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,OAAO,CAAC,CAAA;AACtE,CAAC","sourcesContent":["import { exists, log, retry, stripSensitiveEnvVars, TmpDir } from \"builder-util\"\nimport * as childProcess from \"child_process\"\nimport * as fs from \"fs-extra\"\nimport { createWriteStream } from \"fs-extra\"\nimport { Lazy } from \"lazy-val\"\nimport * as path from \"path\"\nimport { hoist, type HoisterResult, type HoisterTree } from \"./hoist\"\nimport { LogMessageByKey, ModuleManager } from \"./moduleManager\"\nimport { getPackageManagerCommand, PM } from \"./packageManager\"\nimport type { Dependency, DependencyGraph, NodeModuleInfo, PackageJson } from \"./types\"\n\nexport abstract class NodeModulesCollector<ProdDepType extends Dependency<ProdDepType, OptionalDepType>, OptionalDepType> {\n private readonly nodeModules: NodeModuleInfo[] = []\n protected readonly allDependencies: Map<string, ProdDepType> = new Map()\n protected readonly productionGraph: DependencyGraph = {}\n protected readonly cache: ModuleManager = new ModuleManager()\n\n protected isHoisted = new Lazy<boolean>(async () => {\n const { manager } = this.installOptions\n const command = getPackageManagerCommand(manager)\n const config = (await this.asyncExec(command, [\"config\", \"list\"])).stdout\n if (config == null) {\n log.debug({ manager }, \"unable to determine node-linker setting; assuming non-hoisted (virtual store) layout\")\n return false\n }\n const lines = Object.fromEntries(config.split(\"\\n\").map(line => line.split(\"=\").map(s => s.trim())))\n if (lines[\"node-linker\"] === \"hoisted\") {\n log.debug({ manager }, \"node_modules are hoisted\")\n return true\n }\n return false\n })\n\n constructor(\n protected readonly rootDir: string,\n private readonly tempDirManager: TmpDir\n ) {}\n\n /**\n * Retrieves and collects all Node.js modules for a given package.\n *\n * This method orchestrates the entire module collection process by:\n * 1. Fetching the dependency tree from the package manager\n * 2. Collecting all dependencies recursively\n * 3. Extracting workspace references if applicable\n * 4. Building a production dependency graph\n * 5. Hoisting the dependencies to their final locations\n * 6. Resolving and returning module information\n */\n public async getNodeModules({ packageName }: { packageName: string }): Promise<{\n nodeModules: NodeModuleInfo[]\n logSummary: ModuleManager[\"logSummary\"]\n }> {\n const tree: ProdDepType = await this.getDependenciesTree(this.installOptions.manager)\n\n await this.collectAllDependencies(tree, packageName)\n const realTree: ProdDepType = this.getTreeFromWorkspaces(tree, packageName)\n await this.extractProductionDependencyGraph(realTree, packageName)\n\n const hoisterResult: HoisterResult = hoist(this.transformToHoisterTree(this.productionGraph, packageName), {\n check: log.isDebugEnabled,\n })\n\n await this._getNodeModules(hoisterResult.dependencies, this.nodeModules)\n\n log.debug({ packageName, depCount: this.nodeModules.length }, \"node modules collection complete\")\n\n return { nodeModules: this.nodeModules, logSummary: this.cache.logSummary }\n }\n\n public abstract readonly installOptions: {\n manager: PM\n lockfile: string\n }\n\n protected abstract getArgs(): string[]\n protected abstract extractProductionDependencyGraph(tree: Dependency<ProdDepType, OptionalDepType>, dependencyId: string): Promise<void>\n protected abstract collectAllDependencies(tree: Dependency<ProdDepType, OptionalDepType>, appPackageName: string): Promise<void>\n\n /**\n * Retrieves the dependency tree from the package manager.\n *\n * Executes the appropriate package manager command to fetch the dependency tree and writes\n * the output to a temporary file. Includes retry logic to handle transient failures such as\n * incomplete JSON output or missing files. Will retry up to 1 time with exponential backoff.\n */\n protected async getDependenciesTree(pm: PM): Promise<ProdDepType> {\n const command = getPackageManagerCommand(pm)\n const args = this.getArgs()\n\n const tempOutputFile = await this.tempDirManager.getTempFile({\n prefix: path.basename(command, path.extname(command)),\n suffix: \"output.json\",\n })\n\n return retry(\n async () => {\n await this.streamCollectorCommandToFile(command, args, this.rootDir, tempOutputFile)\n const shellOutput = await fs.readFile(tempOutputFile, { encoding: \"utf8\" })\n const result = await Promise.resolve(this.parseDependenciesTree(shellOutput))\n return result\n },\n {\n retries: 1,\n interval: 2000,\n backoff: 2000,\n shouldRetry: async (error: any) => {\n const fields: Record<string, string> = { error: error.message, tempOutputFile, cwd: this.rootDir, packageManager: pm }\n\n if (!(await exists(tempOutputFile))) {\n log.debug(fields, \"dependency tree output file missing, retrying\")\n return true\n }\n\n const fileContent = await fs.readFile(tempOutputFile, { encoding: \"utf8\" })\n fields.fileContentLength = fileContent.length.toString()\n\n if (fileContent.trim().length === 0) {\n log.debug(fields, \"dependency tree output file empty, retrying\")\n return true\n }\n\n // extract small start/end sample for debugging purposes (e.g. polluted console output)\n const lines = fileContent.split(\"\\n\")\n const lineSampleSize = Math.min(5, lines.length / 2)\n if (2 * lineSampleSize > 5) {\n fields.sampleStart = lines.slice(0, lineSampleSize).join(\"\\n\")\n fields.sampleEnd = lines.slice(-lineSampleSize).join(\"\\n\")\n } else {\n fields.content = fileContent\n }\n\n // Both indicate truncated/polluted PM output (a transient that re-running the command clears).\n if (error.message?.includes(\"Unexpected end of JSON input\") || error.message?.includes(\"No JSON content found in output\")) {\n log.debug(fields, \"JSON parse error in dependency tree, retrying\")\n return true\n }\n\n log.error(fields, \"error parsing dependencies tree\")\n return false\n },\n }\n )\n }\n\n /**\n * Parses the dependencies tree from shell command output.\n *\n **/\n protected parseDependenciesTree(shellOutput: string): ProdDepType | Promise<ProdDepType> {\n return this.extractJsonFromPollutedOutput<ProdDepType>(shellOutput)\n }\n\n protected extractJsonFromPollutedOutput<T>(shellOutput: string): T {\n const consoleOutput = shellOutput.trim()\n try {\n // Please for the love of all that is holy, this should cover 99% of cases where npm/pnpm/yarn output is clean JSON\n return JSON.parse(consoleOutput)\n } catch {\n // ignore\n }\n\n // DEDICATED FALLBACK FOR POLLUTED OUTPUT, non-trivial to implement correctly, not needed in most cases, and highly inefficient\n\n // Find the first index that starts with { or [\n const bracketOpen = Math.max(consoleOutput.indexOf(\"{\"), 0)\n const bracketOpenSquare = Math.max(consoleOutput.indexOf(\"[\"), 0)\n const start = Math.min(bracketOpen, bracketOpenSquare) // always non-negative due to Math.max above\n\n for (let i = start; i < consoleOutput.length; i++) {\n const slice = consoleOutput.slice(start, i + 1)\n try {\n return JSON.parse(slice)\n } catch {\n // ignore, try next\n }\n }\n throw new Error(\"No JSON content found in output\")\n }\n\n protected cacheKey(pkg: Pick<ProdDepType, \"name\" | \"version\" | \"path\">): string {\n const rel = path.relative(this.rootDir, pkg.path)\n return `${pkg.name}::${pkg.version}::${rel ?? \".\"}`\n }\n\n // We use the key (alias name) instead of value.name for npm aliased packages\n // e.g., { \"foo\": { name: \"@scope/bar\", ... } } should be stored as \"foo@version\"\n protected normalizePackageVersion(key: string, pkg: ProdDepType) {\n return { id: `${key}@${pkg.version}`, pkgOverride: { ...pkg, name: key } }\n }\n\n /**\n * Determines if a given dependency is a production dependency of a package.\n *\n * Checks both the dependencies and optionalDependencies of a package to see if\n * the specified dependency name is listed.\n *\n * @param depName - The name of the dependency to check\n * @param pkg - The package to search for the dependency in\n * @returns True if the dependency is found in either dependencies or optionalDependencies, false otherwise\n */\n protected isProdDependency(depName: string, pkg: ProdDepType): boolean {\n const prodDeps = { ...pkg.dependencies, ...pkg.optionalDependencies }\n return prodDeps[depName] != null\n }\n\n protected async locatePackageWithVersion(depTree: Pick<ProdDepType, \"name\" | \"version\" | \"path\">): Promise<{ packageDir: string; packageJson: PackageJson } | null> {\n const result = await this.cache.locatePackageVersion({\n parentDir: depTree.path,\n pkgName: depTree.name,\n requiredRange: depTree.version,\n })\n return result\n }\n /**\n * Parses a dependency identifier string into name and version components.\n *\n * Handles both scoped packages (e.g., \"@scope/pkg@1.2.3\") and regular packages (e.g., \"pkg@1.2.3\").\n * If the identifier is malformed or cannot be parsed, defaults to treating the entire string as\n * the package name with an \"unknown\" version.\n */\n protected parseNameVersion(identifier: string): { name: string; version: string } {\n let at: number\n if (identifier.startsWith(\"@\")) {\n // Scoped package: find the version separator after the scope (e.g. \"@scope/pkg@1.2.3\")\n const slashIndex = identifier.indexOf(\"/\")\n if (slashIndex === -1) {\n return { name: identifier, version: \"unknown\" }\n }\n at = identifier.indexOf(\"@\", slashIndex + 1)\n } else {\n at = identifier.indexOf(\"@\")\n }\n if (at <= 0) {\n return { name: identifier, version: \"unknown\" }\n }\n return { name: identifier.slice(0, at), version: identifier.slice(at + 1) }\n }\n\n /**\n * Retrieves the dependency tree and handles workspace package self-references.\n *\n * If the project is a workspace project, this method removes the root package's self-reference\n * from the dependency tree to avoid circular dependencies. It promotes the root package's\n * direct dependencies to the top level of the tree.\n *\n * @param tree - The original dependency tree\n * @param packageName - The name of the package to check for and remove from the tree\n * @returns The extracted dependency subtree\n */\n protected getTreeFromWorkspaces(tree: ProdDepType, packageName: string): ProdDepType {\n if (tree.workspaces && tree.dependencies) {\n for (const [key, value] of Object.entries(tree.dependencies)) {\n if (key === packageName) {\n return value\n }\n }\n }\n\n return tree\n }\n\n private transformToHoisterTree(obj: DependencyGraph, key: string, nodes: Map<string, HoisterTree> = new Map()): HoisterTree {\n let node = nodes.get(key)\n const { name, version } = this.parseNameVersion(key)\n\n if (!node) {\n node = {\n name,\n identName: name,\n reference: version,\n dependencies: new Set<HoisterTree>(),\n peerNames: new Set<string>(),\n }\n\n nodes.set(key, node)\n\n const deps = (obj[key] || {}).dependencies || []\n for (const dep of deps) {\n const child = this.transformToHoisterTree(obj, dep, nodes)\n node.dependencies.add(child)\n }\n }\n\n return node\n }\n\n private async _getNodeModules(dependencies: Set<HoisterResult>, result: NodeModuleInfo[]) {\n if (dependencies.size === 0) {\n return\n }\n\n for (const d of dependencies.values()) {\n const reference = [...d.references][0]\n const key = `${d.name}@${reference}`\n // Normalize the path to handle mixed separators from pnpm JSON output on Windows\n const rawPath = this.allDependencies.get(key)?.path\n const p = rawPath != null ? path.normalize(rawPath) : undefined\n if (p === undefined) {\n this.cache.logSummary[LogMessageByKey.PKG_NOT_FOUND].push(key)\n continue\n }\n\n // fix npm list issue\n // https://github.com/npm/cli/issues/8535\n if (!(await this.cache.exists[p])) {\n this.logMissingDependency(key)\n continue\n }\n\n const node: NodeModuleInfo = {\n name: d.name,\n version: reference,\n dir: await this.cache.realPath[p],\n }\n result.push(node)\n if (d.dependencies.size > 0) {\n node.dependencies = []\n await this._getNodeModules(d.dependencies, node.dependencies)\n }\n }\n result.sort((a, b) => a.name.localeCompare(b.name))\n }\n\n /**\n * Records a dependency that could not be resolved on disk in the log summary.\n *\n * A platform-specific package name (e.g. `sass-embedded-linux-x64`) is always classified as a\n * platform-specific optional dependency. Otherwise, `isDeclaredOptional` decides the bucket: a\n * caller that *knows* the dependency was declared in `optionalDependencies` (e.g. the pnpm\n * collector's optional-dependency check) reports a missing *optional* dependency — an expected\n * condition — rather than the `PKG_NOT_ON_DISK` warning reserved for genuinely missing\n * production dependencies.\n */\n protected logMissingDependency(pkgName: string, isDeclaredOptional = false) {\n const PLATFORM_PACKAGE_RE = /(linux|win32|darwin|freebsd|android)[-_](x64|arm64|ia32|arm|ppc64|s390x|loong64|riscv64|universal)/\n const diskLogKey = PLATFORM_PACKAGE_RE.test(pkgName)\n ? LogMessageByKey.PKG_OPTIONAL_PLATFORM_NOT_INSTALLED\n : isDeclaredOptional\n ? LogMessageByKey.PKG_OPTIONAL_NOT_INSTALLED\n : LogMessageByKey.PKG_NOT_ON_DISK\n this.cache.logSummary[diskLogKey].push(pkgName)\n }\n\n protected async asyncExec(command: string, args: string[], cwd: string = this.rootDir): Promise<{ stdout: string | undefined; stderr: string | undefined }> {\n const file = await this.tempDirManager.getTempFile({ prefix: \"exec-\", suffix: \".txt\" })\n try {\n await this.streamCollectorCommandToFile(command, args, cwd, file)\n const result = await fs.readFile(file, { encoding: \"utf8\" })\n return { stdout: result?.trim(), stderr: undefined }\n } catch (error: any) {\n log.debug({ error: error.message }, \"failed to execute command\")\n return { stdout: undefined, stderr: error.message }\n }\n }\n\n /**\n * Executes a command and streams its output to a file.\n *\n * Spawns a child process to execute the specified command with arguments, capturing stdout\n * to a file. On Windows, wraps the invocation in `powershell.exe -EncodedCommand` (UTF-16LE\n * base64) to avoid spawning `.cmd` shims directly and to eliminate shell-injection surface area.\n * Enables corepack strict mode by default but allows process.env overrides.\n *\n * Special handling for `npm list` exit code 1, which is expected in certain scenarios.\n *\n * @param command - The command to execute\n * @param args - Array of command-line arguments\n * @param cwd - The working directory to execute the command in\n * @param tempOutputFile - The path to the temporary file where stdout will be written\n * @returns Promise that resolves when the command completes successfully or rejects if it fails\n * @throws {Error} If the child process spawn fails or exits with a non-zero code\n */\n protected async streamCollectorCommandToFile(command: string, args: string[], cwd: string, tempOutputFile: string) {\n // Derive execName from the original command so the npm-list shouldIgnore check below keys off the\n // real invocation (e.g. \"npm\"), not the \"powershell\" wrapper we spawn on Windows.\n const execName = path.basename(command, path.extname(command))\n\n // On Windows the package-manager command is typically a `.cmd` shim (npm.cmd/pnpm.cmd/yarn.cmd),\n // which Node can no longer spawn directly (CVE-2024-27980). Rather than spawn with `shell: true` —\n // which emits the DEP0190 \"args with shell\" deprecation warning and forces manual metacharacter\n // escaping — wrap the invocation in a single PowerShell `-EncodedCommand`. The base64 (UTF-16LE)\n // payload sidesteps every shell-quoting layer, and `powershell.exe` is a real executable we spawn\n // directly with no shell. See buildPowerShellEncodedArgs for the UTF-8 / exit-code handling.\n const [spawnCommand, spawnArgs] = process.platform === \"win32\" ? ([\"powershell.exe\", buildPowerShellEncodedArgs(command, args)] as const) : ([command, args] as const)\n\n await new Promise<void>((resolve, reject) => {\n const outStream = createWriteStream(tempOutputFile)\n\n const child = childProcess.spawn(spawnCommand, spawnArgs, {\n cwd,\n // Package manager invocations do not need signing/publishing credentials.\n env: { COREPACK_ENABLE_STRICT: \"0\", ...stripSensitiveEnvVars(process.env) },\n })\n\n let stderr = \"\"\n // The process can close before all piped stdout has been flushed to disk. Resolving on the\n // child's \"close\" alone races the write stream and lets the caller read a TRUNCATED file\n // (manifesting as \"No JSON content found in output\"). Gate the settle on BOTH the child exit\n // (for the code/stderr) and the write stream's \"finish\" (all bytes flushed).\n let exitCode: number | null = null\n let childClosed = false\n let streamFinished = false\n let settled = false\n\n // `pipe` ends `outStream` when stdout EOFs, which triggers its \"finish\" once flushed.\n child.stdout.pipe(outStream)\n child.stderr.on(\"data\", chunk => {\n stderr += chunk.toString()\n })\n\n const fail = (err: Error) => {\n if (settled) {\n return\n }\n settled = true\n // Best-effort cleanup: stop the child and close the stream so we don't\n // waste CPU writing to a broken fd after rejection.\n try {\n child.kill()\n } catch {\n // ignore\n }\n try {\n outStream.destroy()\n } catch {\n // ignore\n }\n reject(err)\n }\n\n const settle = () => {\n if (settled || !childClosed || !streamFinished) {\n return\n }\n const code = exitCode\n // https://github.com/npm/npm/issues/17624\n const shouldIgnore = code === 1 && \"npm\" === execName.toLowerCase() && args.includes(\"list\")\n if (shouldIgnore) {\n log.debug(null, \"`npm list` returned non-zero exit code, but it MIGHT be expected (https://github.com/npm/npm/issues/17624). Check stderr for details.\")\n }\n if (stderr.length > 0) {\n log.debug({ stderr }, \"note: there was node module collector output on stderr\")\n // Only surface stderr as a user-visible warning when the exit code itself is unexpected.\n // When shouldIgnore is true (npm list exit code 1) the stderr is an anticipated side\n // effect of package-manager features like yarn resolutions or npm overrides that cause\n // npm to report ELSPROBLEMS for aliased packages it considers \"invalid\".\n if (!shouldIgnore) {\n this.cache.logSummary[LogMessageByKey.PKG_COLLECTOR_OUTPUT].push(stderr)\n }\n }\n settled = true\n const shouldResolve = code === 0 || shouldIgnore\n return shouldResolve ? resolve() : reject(new Error(`Node module collector process exited with code ${code}:\\n${stderr}`))\n }\n\n outStream.on(\"error\", err => fail(new Error(`Node module collector failed writing output (${command}): ${err.message}`)))\n outStream.on(\"finish\", () => {\n streamFinished = true\n settle()\n })\n child.on(\"error\", err => {\n fail(new Error(`Node module collector spawn (${command} ${JSON.stringify(args)}) failed: ${err.message}`))\n })\n child.on(\"close\", code => {\n exitCode = code\n childClosed = true\n settle()\n })\n })\n }\n}\n\n/**\n * Build the argv for invoking a Windows command through `powershell.exe -EncodedCommand`.\n *\n * Each token is wrapped in a PowerShell single-quoted string (with embedded single quotes doubled),\n * so no character is interpreted by a shell. The script:\n * - pins `[Console]::OutputEncoding` to UTF-8 *without* a BOM so the JSON dependency tree is not\n * corrupted by the console's OEM code page (and no BOM is prepended to break `JSON.parse`),\n * - invokes the command via the call operator `&`,\n * - re-emits the command's own exit code via `exit $LASTEXITCODE` (e.g. `npm list` returns 1 in\n * expected scenarios, which the caller's shouldIgnore logic relies on).\n *\n * The whole script is base64-encoded as UTF-16LE per PowerShell's `-EncodedCommand` contract.\n */\nexport function buildPowerShellEncodedArgs(command: string, args: string[]): string[] {\n const psQuote = (value: string) => `'${value.replace(/'/g, \"''\")}'`\n const invocation = [\"&\", psQuote(command), ...args.map(psQuote)].join(\" \")\n const script = `[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new($false); ${invocation}; exit $LASTEXITCODE`\n const encoded = Buffer.from(script, \"utf16le\").toString(\"base64\")\n return [\"-NoProfile\", \"-NonInteractive\", \"-EncodedCommand\", encoded]\n}\n"]}
1
+ {"version":3,"file":"nodeModulesCollector.js","sourceRoot":"","sources":["../../src/node-module-collector/nodeModulesCollector.ts"],"names":[],"mappings":";;;AA0fA,gEAMC;AAhgBD,+CAAgF;AAChF,8CAA6C;AAC7C,+BAA8B;AAC9B,uCAA4C;AAC5C,uCAA+B;AAC/B,6BAA4B;AAC5B,mCAAqE;AACrE,mDAAgE;AAChE,qDAA+D;AAG/D,MAAsB,oBAAoB;IAsBxC,YACqB,OAAe,EACjB,cAAs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AC,CAAC,CAAA;IACJ,CAAC;CACF;AAheD,oDAgeC;AAED;;;;;;;;;;;;GAYG;AACH,SAAgB,0BAA0B,CAAC,OAAe,EAAE,IAAc;IACxE,MAAM,OAAO,GAAG,CAAC,KAAa,EAAE,EAAE,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAA;IACnE,MAAM,UAAU,GAAG,CAAC,GAAG,EAAE,OAAO,CAAC,OAAO,CAAC,EAAE,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;IAC1E,MAAM,MAAM,GAAG,sEAAsE,UAAU,sBAAsB,CAAA;IACrH,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAA;IACjE,OAAO,CAAC,YAAY,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,OAAO,CAAC,CAAA;AACtE,CAAC","sourcesContent":["import { exists, log, retry, stripSensitiveEnvVars, TmpDir } from \"builder-util\"\nimport * as childProcess from \"child_process\"\nimport * as fs from \"fs-extra\"\nimport { createWriteStream } from \"fs-extra\"\nimport { Lazy } from \"lazy-val\"\nimport * as path from \"path\"\nimport { hoist, type HoisterResult, type HoisterTree } from \"./hoist\"\nimport { LogMessageByKey, ModuleManager } from \"./moduleManager\"\nimport { getPackageManagerCommand, PM } from \"./packageManager\"\nimport type { Dependency, DependencyGraph, NodeModuleInfo, PackageJson } from \"./types\"\n\nexport abstract class NodeModulesCollector<ProdDepType extends Dependency<ProdDepType, OptionalDepType>, OptionalDepType> {\n private readonly nodeModules: NodeModuleInfo[] = []\n protected readonly allDependencies: Map<string, ProdDepType> = new Map()\n protected readonly productionGraph: DependencyGraph = {}\n protected readonly cache: ModuleManager = new ModuleManager()\n\n protected isHoisted = new Lazy<boolean>(async () => {\n const { manager } = this.installOptions\n const command = getPackageManagerCommand(manager)\n const config = (await this.asyncExec(command, [\"config\", \"list\"])).stdout\n if (config == null) {\n log.debug({ manager }, \"unable to determine node-linker setting; assuming non-hoisted (virtual store) layout\")\n return false\n }\n const lines = Object.fromEntries(config.split(\"\\n\").map(line => line.split(\"=\").map(s => s.trim())))\n if (lines[\"node-linker\"] === \"hoisted\") {\n log.debug({ manager }, \"node_modules are hoisted\")\n return true\n }\n return false\n })\n\n constructor(\n protected readonly rootDir: string,\n private readonly tempDirManager: TmpDir\n ) {}\n\n /**\n * Retrieves and collects all Node.js modules for a given package.\n *\n * This method orchestrates the entire module collection process by:\n * 1. Fetching the dependency tree from the package manager\n * 2. Collecting all dependencies recursively\n * 3. Extracting workspace references if applicable\n * 4. Building a production dependency graph\n * 5. Hoisting the dependencies to their final locations\n * 6. Resolving and returning module information\n */\n public async getNodeModules({ packageName }: { packageName: string }): Promise<{\n nodeModules: NodeModuleInfo[]\n logSummary: ModuleManager[\"logSummary\"]\n }> {\n const tree: ProdDepType = await this.getDependenciesTree(this.installOptions.manager)\n\n await this.collectAllDependencies(tree, packageName)\n const realTree: ProdDepType = this.getTreeFromWorkspaces(tree, packageName)\n await this.extractProductionDependencyGraph(realTree, packageName)\n\n const hoisterResult: HoisterResult = hoist(this.transformToHoisterTree(this.productionGraph, packageName), {\n check: log.isDebugEnabled,\n })\n\n await this._getNodeModules(hoisterResult.dependencies, this.nodeModules)\n\n log.debug({ packageName, depCount: this.nodeModules.length }, \"node modules collection complete\")\n\n return { nodeModules: this.nodeModules, logSummary: this.cache.logSummary }\n }\n\n public abstract readonly installOptions: {\n manager: PM\n lockfile: string\n }\n\n protected abstract getArgs(): string[]\n protected abstract extractProductionDependencyGraph(tree: Dependency<ProdDepType, OptionalDepType>, dependencyId: string): Promise<void>\n protected abstract collectAllDependencies(tree: Dependency<ProdDepType, OptionalDepType>, appPackageName: string): Promise<void>\n\n /**\n * Retrieves the dependency tree from the package manager.\n *\n * Executes the appropriate package manager command to fetch the dependency tree and writes\n * the output to a temporary file. Includes retry logic to handle transient failures such as\n * incomplete JSON output or missing files. Will retry up to 1 time with exponential backoff.\n */\n protected async getDependenciesTree(pm: PM): Promise<ProdDepType> {\n const command = getPackageManagerCommand(pm)\n const args = this.getArgs()\n\n const tempOutputFile = await this.tempDirManager.getTempFile({\n prefix: path.basename(command, path.extname(command)),\n suffix: \"output.json\",\n })\n\n return retry(\n async () => {\n const { code, stderr } = await this.streamCollectorCommandToFile(command, args, this.rootDir, tempOutputFile)\n const shellOutput = await fs.readFile(tempOutputFile, { encoding: \"utf8\" })\n if (shellOutput.trim().length === 0) {\n // Parsing an empty string would only yield a misleading \"No JSON content found in output\" (#10208).\n // With npm this usually means npm itself threw while writing its buffered JSON tree at exit: npm's exit\n // handler swallows that exception and exits 1 with nothing on stdout and only `verbose exit 1` in its log.\n throw new Error(\n `\\`${[path.basename(command), ...args].join(\" \")}\\` (cwd: ${this.rootDir}) exited with code ${code} and produced no output on stdout; ` +\n `with npm this usually means npm itself failed while writing its JSON dependency tree. stderr: ${stderr.trim().length > 0 ? stderr.trim() : \"(empty)\"}`\n )\n }\n const result = await Promise.resolve(this.parseDependenciesTree(shellOutput))\n return result\n },\n {\n retries: 1,\n interval: 2000,\n backoff: 2000,\n shouldRetry: async (error: any) => {\n const fields: Record<string, string> = { error: error.message, tempOutputFile, cwd: this.rootDir, packageManager: pm }\n\n if (!(await exists(tempOutputFile))) {\n log.debug(fields, \"dependency tree output file missing, retrying\")\n return true\n }\n\n const fileContent = await fs.readFile(tempOutputFile, { encoding: \"utf8\" })\n fields.fileContentLength = fileContent.length.toString()\n\n if (fileContent.trim().length === 0) {\n log.debug(fields, \"dependency tree output file empty, retrying\")\n return true\n }\n\n // extract small start/end sample for debugging purposes (e.g. polluted console output)\n const lines = fileContent.split(\"\\n\")\n const lineSampleSize = Math.min(5, lines.length / 2)\n if (2 * lineSampleSize > 5) {\n fields.sampleStart = lines.slice(0, lineSampleSize).join(\"\\n\")\n fields.sampleEnd = lines.slice(-lineSampleSize).join(\"\\n\")\n } else {\n fields.content = fileContent\n }\n\n // Both indicate truncated/polluted PM output (a transient that re-running the command clears).\n if (error.message?.includes(\"Unexpected end of JSON input\") || error.message?.includes(\"No JSON content found in output\")) {\n log.debug(fields, \"JSON parse error in dependency tree, retrying\")\n return true\n }\n\n log.error(fields, \"error parsing dependencies tree\")\n return false\n },\n }\n )\n }\n\n /**\n * Parses the dependencies tree from shell command output.\n *\n **/\n protected parseDependenciesTree(shellOutput: string): ProdDepType | Promise<ProdDepType> {\n return this.extractJsonFromPollutedOutput<ProdDepType>(shellOutput)\n }\n\n protected extractJsonFromPollutedOutput<T>(shellOutput: string): T {\n const consoleOutput = shellOutput.trim()\n try {\n // Please for the love of all that is holy, this should cover 99% of cases where npm/pnpm/yarn output is clean JSON\n return JSON.parse(consoleOutput)\n } catch {\n // ignore\n }\n\n // DEDICATED FALLBACK FOR POLLUTED OUTPUT, non-trivial to implement correctly, not needed in most cases, and highly inefficient\n\n // Find the first index that starts with { or [\n const bracketOpen = Math.max(consoleOutput.indexOf(\"{\"), 0)\n const bracketOpenSquare = Math.max(consoleOutput.indexOf(\"[\"), 0)\n const start = Math.min(bracketOpen, bracketOpenSquare) // always non-negative due to Math.max above\n\n for (let i = start; i < consoleOutput.length; i++) {\n const slice = consoleOutput.slice(start, i + 1)\n try {\n return JSON.parse(slice)\n } catch {\n // ignore, try next\n }\n }\n throw new Error(\"No JSON content found in output\")\n }\n\n protected cacheKey(pkg: Pick<ProdDepType, \"name\" | \"version\" | \"path\">): string {\n const rel = path.relative(this.rootDir, pkg.path)\n return `${pkg.name}::${pkg.version}::${rel ?? \".\"}`\n }\n\n // We use the key (alias name) instead of value.name for npm aliased packages\n // e.g., { \"foo\": { name: \"@scope/bar\", ... } } should be stored as \"foo@version\"\n protected normalizePackageVersion(key: string, pkg: ProdDepType) {\n return { id: `${key}@${pkg.version}`, pkgOverride: { ...pkg, name: key } }\n }\n\n /**\n * Determines if a given dependency is a production dependency of a package.\n *\n * Checks both the dependencies and optionalDependencies of a package to see if\n * the specified dependency name is listed.\n *\n * @param depName - The name of the dependency to check\n * @param pkg - The package to search for the dependency in\n * @returns True if the dependency is found in either dependencies or optionalDependencies, false otherwise\n */\n protected isProdDependency(depName: string, pkg: ProdDepType): boolean {\n const prodDeps = { ...pkg.dependencies, ...pkg.optionalDependencies }\n return prodDeps[depName] != null\n }\n\n protected async locatePackageWithVersion(depTree: Pick<ProdDepType, \"name\" | \"version\" | \"path\">): Promise<{ packageDir: string; packageJson: PackageJson } | null> {\n const result = await this.cache.locatePackageVersion({\n parentDir: depTree.path,\n pkgName: depTree.name,\n requiredRange: depTree.version,\n })\n return result\n }\n /**\n * Parses a dependency identifier string into name and version components.\n *\n * Handles both scoped packages (e.g., \"@scope/pkg@1.2.3\") and regular packages (e.g., \"pkg@1.2.3\").\n * If the identifier is malformed or cannot be parsed, defaults to treating the entire string as\n * the package name with an \"unknown\" version.\n */\n protected parseNameVersion(identifier: string): { name: string; version: string } {\n let at: number\n if (identifier.startsWith(\"@\")) {\n // Scoped package: find the version separator after the scope (e.g. \"@scope/pkg@1.2.3\")\n const slashIndex = identifier.indexOf(\"/\")\n if (slashIndex === -1) {\n return { name: identifier, version: \"unknown\" }\n }\n at = identifier.indexOf(\"@\", slashIndex + 1)\n } else {\n at = identifier.indexOf(\"@\")\n }\n if (at <= 0) {\n return { name: identifier, version: \"unknown\" }\n }\n return { name: identifier.slice(0, at), version: identifier.slice(at + 1) }\n }\n\n /**\n * Retrieves the dependency tree and handles workspace package self-references.\n *\n * If the project is a workspace project, this method removes the root package's self-reference\n * from the dependency tree to avoid circular dependencies. It promotes the root package's\n * direct dependencies to the top level of the tree.\n *\n * @param tree - The original dependency tree\n * @param packageName - The name of the package to check for and remove from the tree\n * @returns The extracted dependency subtree\n */\n protected getTreeFromWorkspaces(tree: ProdDepType, packageName: string): ProdDepType {\n if (tree.workspaces && tree.dependencies) {\n for (const [key, value] of Object.entries(tree.dependencies)) {\n if (key === packageName) {\n return value\n }\n }\n }\n\n return tree\n }\n\n private transformToHoisterTree(obj: DependencyGraph, key: string, nodes: Map<string, HoisterTree> = new Map()): HoisterTree {\n let node = nodes.get(key)\n const { name, version } = this.parseNameVersion(key)\n\n if (!node) {\n node = {\n name,\n identName: name,\n reference: version,\n dependencies: new Set<HoisterTree>(),\n peerNames: new Set<string>(),\n }\n\n nodes.set(key, node)\n\n const deps = (obj[key] || {}).dependencies || []\n for (const dep of deps) {\n const child = this.transformToHoisterTree(obj, dep, nodes)\n // a package that declares itself as a dependency (e.g. libsql) must not produce a self-edge\n if (child !== node) {\n node.dependencies.add(child)\n }\n }\n }\n\n return node\n }\n\n private async _getNodeModules(dependencies: Set<HoisterResult>, result: NodeModuleInfo[], ancestors: Set<HoisterResult> = new Set()) {\n if (dependencies.size === 0) {\n return\n }\n\n for (const d of dependencies.values()) {\n // dependency cycles (including self-references) must not recurse\n if (ancestors.has(d)) {\n continue\n }\n const reference = [...d.references][0]\n const key = `${d.name}@${reference}`\n // Normalize the path to handle mixed separators from pnpm JSON output on Windows\n const rawPath = this.allDependencies.get(key)?.path\n const p = rawPath != null ? path.normalize(rawPath) : undefined\n if (p === undefined) {\n this.cache.logSummary[LogMessageByKey.PKG_NOT_FOUND].push(key)\n continue\n }\n\n // fix npm list issue\n // https://github.com/npm/cli/issues/8535\n if (!(await this.cache.exists[p])) {\n this.logMissingDependency(key)\n continue\n }\n\n const node: NodeModuleInfo = {\n name: d.name,\n version: reference,\n dir: await this.cache.realPath[p],\n }\n result.push(node)\n if (d.dependencies.size > 0) {\n node.dependencies = []\n ancestors.add(d)\n await this._getNodeModules(d.dependencies, node.dependencies, ancestors)\n ancestors.delete(d)\n }\n }\n result.sort((a, b) => a.name.localeCompare(b.name))\n }\n\n /**\n * Records a dependency that could not be resolved on disk in the log summary.\n *\n * A platform-specific package name (e.g. `sass-embedded-linux-x64`) is always classified as a\n * platform-specific optional dependency. Otherwise, `isDeclaredOptional` decides the bucket: a\n * caller that *knows* the dependency was declared in `optionalDependencies` (e.g. the pnpm\n * collector's optional-dependency check) reports a missing *optional* dependency — an expected\n * condition — rather than the `PKG_NOT_ON_DISK` warning reserved for genuinely missing\n * production dependencies.\n */\n protected logMissingDependency(pkgName: string, isDeclaredOptional = false) {\n const PLATFORM_PACKAGE_RE = /(linux|win32|darwin|freebsd|android)[-_](x64|arm64|ia32|arm|ppc64|s390x|loong64|riscv64|universal)/\n const diskLogKey = PLATFORM_PACKAGE_RE.test(pkgName)\n ? LogMessageByKey.PKG_OPTIONAL_PLATFORM_NOT_INSTALLED\n : isDeclaredOptional\n ? LogMessageByKey.PKG_OPTIONAL_NOT_INSTALLED\n : LogMessageByKey.PKG_NOT_ON_DISK\n this.cache.logSummary[diskLogKey].push(pkgName)\n }\n\n protected async asyncExec(command: string, args: string[], cwd: string = this.rootDir): Promise<{ stdout: string | undefined; stderr: string | undefined }> {\n const file = await this.tempDirManager.getTempFile({ prefix: \"exec-\", suffix: \".txt\" })\n try {\n await this.streamCollectorCommandToFile(command, args, cwd, file)\n const result = await fs.readFile(file, { encoding: \"utf8\" })\n return { stdout: result?.trim(), stderr: undefined }\n } catch (error: any) {\n log.debug({ error: error.message }, \"failed to execute command\")\n return { stdout: undefined, stderr: error.message }\n }\n }\n\n /**\n * Executes a command and streams its output to a file.\n *\n * Spawns a child process to execute the specified command with arguments, capturing stdout\n * to a file. On Windows, wraps the invocation in `powershell.exe -EncodedCommand` (UTF-16LE\n * base64) to avoid spawning `.cmd` shims directly and to eliminate shell-injection surface area.\n * Enables corepack strict mode by default but allows process.env overrides.\n *\n * Special handling for `npm list` exit code 1, which is expected in certain scenarios.\n *\n * @param command - The command to execute\n * @param args - Array of command-line arguments\n * @param cwd - The working directory to execute the command in\n * @param tempOutputFile - The path to the temporary file where stdout will be written\n * @returns Promise that resolves with the exit code and captured stderr when the command completes\n * successfully (or with a tolerated exit code), or rejects if it fails\n * @throws {Error} If the child process spawn fails or exits with a non-zero, unexpected code\n */\n protected async streamCollectorCommandToFile(command: string, args: string[], cwd: string, tempOutputFile: string): Promise<{ code: number; stderr: string }> {\n // Derive execName from the original command so the npm-list shouldIgnore check below keys off the\n // real invocation (e.g. \"npm\"), not the \"powershell\" wrapper we spawn on Windows.\n const execName = path.basename(command, path.extname(command))\n\n // On Windows the package-manager command is typically a `.cmd` shim (npm.cmd/pnpm.cmd/yarn.cmd),\n // which Node can no longer spawn directly (CVE-2024-27980). Rather than spawn with `shell: true` —\n // which emits the DEP0190 \"args with shell\" deprecation warning and forces manual metacharacter\n // escaping — wrap the invocation in a single PowerShell `-EncodedCommand`. The base64 (UTF-16LE)\n // payload sidesteps every shell-quoting layer, and `powershell.exe` is a real executable we spawn\n // directly with no shell. See buildPowerShellEncodedArgs for the UTF-8 / exit-code handling.\n const [spawnCommand, spawnArgs] = process.platform === \"win32\" ? ([\"powershell.exe\", buildPowerShellEncodedArgs(command, args)] as const) : ([command, args] as const)\n\n return await new Promise<{ code: number; stderr: string }>((resolve, reject) => {\n const outStream = createWriteStream(tempOutputFile)\n\n const child = childProcess.spawn(spawnCommand, spawnArgs, {\n cwd,\n // Package manager invocations do not need signing/publishing credentials.\n env: { COREPACK_ENABLE_STRICT: \"0\", ...stripSensitiveEnvVars(process.env) },\n })\n\n let stderr = \"\"\n // The process can close before all piped stdout has been flushed to disk. Resolving on the\n // child's \"close\" alone races the write stream and lets the caller read a TRUNCATED file\n // (manifesting as \"No JSON content found in output\"). Gate the settle on BOTH the child exit\n // (for the code/stderr) and the write stream's \"finish\" (all bytes flushed).\n let exitCode: number | null = null\n let childClosed = false\n let streamFinished = false\n let settled = false\n\n // `pipe` ends `outStream` when stdout EOFs, which triggers its \"finish\" once flushed.\n child.stdout.pipe(outStream)\n child.stderr.on(\"data\", chunk => {\n stderr += chunk.toString()\n })\n\n const fail = (err: Error) => {\n if (settled) {\n return\n }\n settled = true\n // Best-effort cleanup: stop the child and close the stream so we don't\n // waste CPU writing to a broken fd after rejection.\n try {\n child.kill()\n } catch {\n // ignore\n }\n try {\n outStream.destroy()\n } catch {\n // ignore\n }\n reject(err)\n }\n\n const settle = () => {\n if (settled || !childClosed || !streamFinished) {\n return\n }\n const code = exitCode\n // https://github.com/npm/npm/issues/17624\n const shouldIgnore = code === 1 && \"npm\" === execName.toLowerCase() && args.includes(\"list\")\n if (shouldIgnore) {\n log.debug(null, \"`npm list` returned non-zero exit code, but it MIGHT be expected (https://github.com/npm/npm/issues/17624). Check stderr for details.\")\n }\n if (stderr.length > 0) {\n log.debug({ stderr }, \"note: there was node module collector output on stderr\")\n // Only surface stderr as a user-visible warning when the exit code itself is unexpected.\n // When shouldIgnore is true (npm list exit code 1) the stderr is an anticipated side\n // effect of package-manager features like yarn resolutions or npm overrides that cause\n // npm to report ELSPROBLEMS for aliased packages it considers \"invalid\".\n if (!shouldIgnore) {\n this.cache.logSummary[LogMessageByKey.PKG_COLLECTOR_OUTPUT].push(stderr)\n }\n }\n settled = true\n const shouldResolve = code === 0 || shouldIgnore\n // `code` is 0 or the tolerated `npm list` 1 whenever we resolve, so it is never null here.\n return shouldResolve ? resolve({ code: code as number, stderr }) : reject(new Error(`Node module collector process exited with code ${code}:\\n${stderr}`))\n }\n\n outStream.on(\"error\", err => fail(new Error(`Node module collector failed writing output (${command}): ${err.message}`)))\n outStream.on(\"finish\", () => {\n streamFinished = true\n settle()\n })\n child.on(\"error\", err => {\n fail(new Error(`Node module collector spawn (${command} ${JSON.stringify(args)}) failed: ${err.message}`))\n })\n child.on(\"close\", code => {\n exitCode = code\n childClosed = true\n settle()\n })\n })\n }\n}\n\n/**\n * Build the argv for invoking a Windows command through `powershell.exe -EncodedCommand`.\n *\n * Each token is wrapped in a PowerShell single-quoted string (with embedded single quotes doubled),\n * so no character is interpreted by a shell. The script:\n * - pins `[Console]::OutputEncoding` to UTF-8 *without* a BOM so the JSON dependency tree is not\n * corrupted by the console's OEM code page (and no BOM is prepended to break `JSON.parse`),\n * - invokes the command via the call operator `&`,\n * - re-emits the command's own exit code via `exit $LASTEXITCODE` (e.g. `npm list` returns 1 in\n * expected scenarios, which the caller's shouldIgnore logic relies on).\n *\n * The whole script is base64-encoded as UTF-16LE per PowerShell's `-EncodedCommand` contract.\n */\nexport function buildPowerShellEncodedArgs(command: string, args: string[]): string[] {\n const psQuote = (value: string) => `'${value.replace(/'/g, \"''\")}'`\n const invocation = [\"&\", psQuote(command), ...args.map(psQuote)].join(\" \")\n const script = `[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new($false); ${invocation}; exit $LASTEXITCODE`\n const encoded = Buffer.from(script, \"utf16le\").toString(\"base64\")\n return [\"-NoProfile\", \"-NonInteractive\", \"-EncodedCommand\", encoded]\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import { Lazy } from "lazy-val";
1
2
  import { NodeModulesCollector } from "./nodeModulesCollector";
2
3
  import { PM } from "./packageManager";
3
4
  import { PnpmDependency } from "./types";
@@ -9,6 +10,30 @@ export declare class PnpmNodeModulesCollector extends NodeModulesCollector<PnpmD
9
10
  private _allWorkspacePackages;
10
11
  private _pnpmMajorVersion;
11
12
  private readonly pnpmVersion;
13
+ /**
14
+ * Detect pnpm's installed layout from the on-disk structure rather than `pnpm config list`.
15
+ * pnpm 11 no longer echoes `node-linker` (from `.npmrc`) in `config list`, so the base-class
16
+ * config-parsing detection silently reports "not hoisted" for a hoisted install, which would
17
+ * disable the downward search needed to find version-conflicted nested deps.
18
+ *
19
+ * In the default isolated store every regular top-level package resolves — through a symlink
20
+ * on POSIX, a junction on Windows — into `node_modules/.pnpm/<name>@<ver>/node_modules/<name>`.
21
+ * In a hoisted layout the same package is a real directory directly under `node_modules`.
22
+ * `realpath` transparently follows both symlinks and junctions, so a layout is isolated iff
23
+ * *any* top-level package's real path routes through `.pnpm`. We scan rather than sample the
24
+ * first entry because `link:` packages resolve to their source (never under `.pnpm`) and could
25
+ * otherwise mask an isolated store.
26
+ */
27
+ protected isHoisted: Lazy<boolean>;
28
+ /**
29
+ * The pnpm workspace root containing `rootDir` (nearest ancestor with `pnpm-workspace.yaml`, as pnpm
30
+ * itself resolves it), or null outside a workspace or when `rootDir` is the workspace root.
31
+ */
32
+ private readonly workspaceRoot;
33
+ /** `rootDir`, then the workspace root when `rootDir` is a workspace package. */
34
+ private readonly layoutRoots;
35
+ /** Returns true if `nmDir` is an isolated (`.pnpm`) store, false if hoisted, null if it holds no packages. */
36
+ private scanNodeModulesLayout;
12
37
  /**
13
38
  * Memo for `locateFromDepOrRoot`, keyed by `name@version`. pnpm's content-addressed virtual
14
39
  * store guarantees that any given `name@version` resolves to a single location on disk, so
@@ -22,6 +47,9 @@ export declare class PnpmNodeModulesCollector extends NodeModulesCollector<PnpmD
22
47
  * every shared subtree of the pnpm list output, exploding work in deep workspaces.
23
48
  */
24
49
  private readonly collectedDeps;
50
+ /** Reverse index of `allDependencies` keyed by package name (without version). Built once on
51
+ * first access inside `extractProductionDependencyGraph`, after `allDependencies` is settled. */
52
+ private _allDepsByName;
25
53
  /**
26
54
  * Returns the workspace packages to iterate over, gated by detected pnpm version:
27
55
  * - pnpm v11+: multi-entry workspace output → return the full parsed array
@@ -29,6 +57,7 @@ export declare class PnpmNodeModulesCollector extends NodeModulesCollector<PnpmD
29
57
  */
30
58
  private get allWorkspacePackages();
31
59
  protected getArgs(): string[];
60
+ private getAllDepsByName;
32
61
  /**
33
62
  * Locate a package version, preferring the dep's own reported path before falling back to rootDir.
34
63
  * This is critical for pnpm non-hoisted (virtual store) setups where each package has its own
@@ -37,6 +66,19 @@ export declare class PnpmNodeModulesCollector extends NodeModulesCollector<PnpmD
37
66
  */
38
67
  private locateFromDepOrRoot;
39
68
  protected extractProductionDependencyGraph(tree: PnpmDependency, dependencyId: string): Promise<void>;
69
+ /**
70
+ * Resolve a dependency that `pnpm list` left out of a package's tree to its `allDependencies` entry.
71
+ * The lookup goes through the copy node itself would load from `parentPath` (the package's real store
72
+ * directory), filtered by the declared range, and falls back to a name-only match only when nothing on
73
+ * disk resolves to a collected entry (a `link:` dep, whose entry is keyed by its `link:` version).
74
+ *
75
+ * A name-only lookup returns whichever version was collected first, which is wrong as soon as two
76
+ * versions of the package are installed: with the app pinning es5-ext@0.10.53 while its transitive
77
+ * d@1.0.2 needs es5-ext ^0.10.64, `d` was wired to 0.10.53 and the nested 0.10.64 copy (with its own
78
+ * esniff / event-emitter / next-tick@1.1.0 closure) vanished from the asar (#8493). pnpm 10.29.3+
79
+ * made this common, because its deduped output routes every repeated package through this recovery.
80
+ */
81
+ private resolveOmittedDependency;
40
82
  protected collectAllDependencies(_tree: PnpmDependency, _appPackageName: string): Promise<void>;
41
83
  private collectDepsRecursively;
42
84
  protected getTreeFromWorkspaces(tree: PnpmDependency, packageName: string): PnpmDependency;
@@ -1,10 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PnpmNodeModulesCollector = void 0;
4
+ const fs = require("fs-extra");
4
5
  const lazy_val_1 = require("lazy-val");
6
+ const path = require("path");
5
7
  const moduleManager_1 = require("./moduleManager");
6
8
  const nodeModulesCollector_1 = require("./nodeModulesCollector");
7
9
  const packageManager_1 = require("./packageManager");
10
+ const builder_util_1 = require("builder-util");
8
11
  class PnpmNodeModulesCollector extends nodeModulesCollector_1.NodeModulesCollector {
9
12
  constructor() {
10
13
  super(...arguments);
@@ -23,6 +26,58 @@ class PnpmNodeModulesCollector extends nodeModulesCollector_1.NodeModulesCollect
23
26
  const major = parseInt(((_a = result.stdout) !== null && _a !== void 0 ? _a : "0").split(".")[0], 10);
24
27
  return isNaN(major) ? 0 : major;
25
28
  });
29
+ /**
30
+ * Detect pnpm's installed layout from the on-disk structure rather than `pnpm config list`.
31
+ * pnpm 11 no longer echoes `node-linker` (from `.npmrc`) in `config list`, so the base-class
32
+ * config-parsing detection silently reports "not hoisted" for a hoisted install, which would
33
+ * disable the downward search needed to find version-conflicted nested deps.
34
+ *
35
+ * In the default isolated store every regular top-level package resolves — through a symlink
36
+ * on POSIX, a junction on Windows — into `node_modules/.pnpm/<name>@<ver>/node_modules/<name>`.
37
+ * In a hoisted layout the same package is a real directory directly under `node_modules`.
38
+ * `realpath` transparently follows both symlinks and junctions, so a layout is isolated iff
39
+ * *any* top-level package's real path routes through `.pnpm`. We scan rather than sample the
40
+ * first entry because `link:` packages resolve to their source (never under `.pnpm`) and could
41
+ * otherwise mask an isolated store.
42
+ */
43
+ this.isHoisted = new lazy_val_1.Lazy(async () => {
44
+ // A workspace package's own `node_modules` is often absent (or holds only its version
45
+ // conflicts) in a hoisted workspace, so fall back to the workspace root's `node_modules`.
46
+ let sawPackage = false;
47
+ for (const dir of await this.layoutRoots.value) {
48
+ const isolated = await this.scanNodeModulesLayout(path.join(dir, "node_modules"));
49
+ if (isolated != null) {
50
+ if (isolated) {
51
+ return false;
52
+ }
53
+ sawPackage = true;
54
+ }
55
+ }
56
+ // Packages exist and none route through `.pnpm` → hoisted. No packages → flat default.
57
+ return sawPackage;
58
+ });
59
+ /**
60
+ * The pnpm workspace root containing `rootDir` (nearest ancestor with `pnpm-workspace.yaml`, as pnpm
61
+ * itself resolves it), or null outside a workspace or when `rootDir` is the workspace root.
62
+ */
63
+ this.workspaceRoot = new lazy_val_1.Lazy(async () => {
64
+ let current = path.resolve(this.rootDir);
65
+ while (true) {
66
+ if (await (0, builder_util_1.exists)(path.join(current, "pnpm-workspace.yaml"))) {
67
+ return current === path.resolve(this.rootDir) ? null : current;
68
+ }
69
+ const parent = path.dirname(current);
70
+ if (parent === current) {
71
+ return null;
72
+ }
73
+ current = parent;
74
+ }
75
+ });
76
+ /** `rootDir`, then the workspace root when `rootDir` is a workspace package. */
77
+ this.layoutRoots = new lazy_val_1.Lazy(async () => {
78
+ const workspaceRoot = await this.workspaceRoot.value;
79
+ return workspaceRoot == null ? [this.rootDir] : [this.rootDir, workspaceRoot];
80
+ });
26
81
  /**
27
82
  * Memo for `locateFromDepOrRoot`, keyed by `name@version`. pnpm's content-addressed virtual
28
83
  * store guarantees that any given `name@version` resolves to a single location on disk, so
@@ -36,6 +91,33 @@ class PnpmNodeModulesCollector extends nodeModulesCollector_1.NodeModulesCollect
36
91
  * every shared subtree of the pnpm list output, exploding work in deep workspaces.
37
92
  */
38
93
  this.collectedDeps = new Set();
94
+ /** Reverse index of `allDependencies` keyed by package name (without version). Built once on
95
+ * first access inside `extractProductionDependencyGraph`, after `allDependencies` is settled. */
96
+ this._allDepsByName = null;
97
+ }
98
+ /** Returns true if `nmDir` is an isolated (`.pnpm`) store, false if hoisted, null if it holds no packages. */
99
+ async scanNodeModulesLayout(nmDir) {
100
+ const entries = await fs.readdir(nmDir).catch(() => []);
101
+ let sawPackage = false;
102
+ for (const name of entries) {
103
+ if (name.startsWith(".")) {
104
+ continue; // .pnpm, .bin, .modules.yaml
105
+ }
106
+ const entryPath = path.join(nmDir, name);
107
+ // A scoped dir (@scope) is not a package itself; descend to its packages.
108
+ const candidates = name.startsWith("@") ? (await fs.readdir(entryPath).catch(() => [])).map(s => path.join(entryPath, s)) : [entryPath];
109
+ for (const candidate of candidates) {
110
+ const real = await fs.realpath(candidate).catch(() => null);
111
+ if (real == null) {
112
+ continue;
113
+ }
114
+ sawPackage = true;
115
+ if (real.split(path.sep).includes(".pnpm")) {
116
+ return true; // isolated store: a package routes through the virtual store
117
+ }
118
+ }
119
+ }
120
+ return sawPackage ? false : null;
39
121
  }
40
122
  /**
41
123
  * Returns the workspace packages to iterate over, gated by detected pnpm version:
@@ -51,6 +133,18 @@ class PnpmNodeModulesCollector extends nodeModulesCollector_1.NodeModulesCollect
51
133
  getArgs() {
52
134
  return ["list", "--prod", "--json", "--depth", "Infinity", "--silent", "--loglevel=error"];
53
135
  }
136
+ getAllDepsByName() {
137
+ if (!this._allDepsByName) {
138
+ this._allDepsByName = new Map();
139
+ for (const [id, dep] of this.allDependencies.entries()) {
140
+ const { name } = this.parseNameVersion(id);
141
+ if (!this._allDepsByName.has(name)) {
142
+ this._allDepsByName.set(name, dep);
143
+ }
144
+ }
145
+ }
146
+ return this._allDepsByName;
147
+ }
54
148
  /**
55
149
  * Locate a package version, preferring the dep's own reported path before falling back to rootDir.
56
150
  * This is critical for pnpm non-hoisted (virtual store) setups where each package has its own
@@ -76,6 +170,27 @@ class PnpmNodeModulesCollector extends nodeModulesCollector_1.NodeModulesCollect
76
170
  // land at `<root>/node_modules/A/node_modules/B` — downward BFS is needed to find them.
77
171
  const skipDownwardSearch = !(await this.isHoisted.value);
78
172
  const promise = (async () => {
173
+ // Phase 1: find a version that SATISFIES requiredRange, trying the dep's own location
174
+ // first, then the workspace root. Crucially, neither pass accepts an out-of-range override
175
+ // here — so a wrong-version copy reachable via upward search from `parentPath` (e.g. a
176
+ // hoisted top-level dep) can't shadow the correct nested copy under root. With
177
+ // `nodeLinker: hoisted`, pnpm still reports virtual-store `path`s that don't exist on disk;
178
+ // an upward walk from one meets the root copy, which previously got accepted as an
179
+ // "override" before the root search (whose downward BFS finds the nested copy) ever ran.
180
+ //
181
+ // When `rootDir` is a workspace package, a hoisted install keeps the tree — including the
182
+ // nested `<workspaceRoot>/node_modules/A/node_modules/B` copies — under the workspace root,
183
+ // which the downward BFS from `rootDir` never reaches (its `node_modules` is often absent),
184
+ // so search the workspace root last.
185
+ let satisfying = parentPath ? await this.cache.locatePackageVersion({ pkgName, parentDir: parentPath, requiredRange, skipDownwardSearch, skipOverrideFallback: true }) : null;
186
+ for (const dir of await this.layoutRoots.value) {
187
+ satisfying !== null && satisfying !== void 0 ? satisfying : (satisfying = await this.cache.locatePackageVersion({ pkgName, parentDir: dir, requiredRange, skipDownwardSearch, skipOverrideFallback: true }));
188
+ }
189
+ if (satisfying) {
190
+ return satisfying;
191
+ }
192
+ // Phase 2: no version satisfies requiredRange (package-manager override, or no range
193
+ // given). Fall back to the original dep-then-root order, now allowing override versions.
79
194
  const fromDep = parentPath ? await this.cache.locatePackageVersion({ pkgName, parentDir: parentPath, requiredRange, skipDownwardSearch }) : null;
80
195
  if (fromDep) {
81
196
  return fromDep;
@@ -113,6 +228,19 @@ class PnpmNodeModulesCollector extends nodeModulesCollector_1.NodeModulesCollect
113
228
  const all = packageJson ? { ...packageJson.dependencies, ...packageJson.optionalDependencies } : { ...tree.dependencies, ...tree.optionalDependencies };
114
229
  const optional = packageJson ? { ...packageJson.optionalDependencies } : {};
115
230
  const deps = { ...(tree.dependencies || {}), ...(tree.optionalDependencies || {}) };
231
+ // pnpm --prod omits sub-deps for link: packages (and synthetic entries derived from them), and pnpm
232
+ // 10.29.3+ prints a repeated subtree only once, so every later occurrence is a childless `deduped`
233
+ // stub (which is what `tree` is when the stub was the first occurrence collected). For any dep
234
+ // declared in the package.json (all) that pnpm left out of the tree, recover the resolved entry
235
+ // from allDependencies so it lands in the production graph.
236
+ for (const [depName, declaredRange] of Object.entries(all)) {
237
+ if (!deps[depName]) {
238
+ const dep = await this.resolveOmittedDependency(depName, declaredRange, tree.path);
239
+ if (dep && (0, builder_util_1.isValidKey)(depName)) {
240
+ deps[depName] = dep;
241
+ }
242
+ }
243
+ }
116
244
  this.productionGraph[dependencyId] = { dependencies: [] };
117
245
  const depPromises = Object.entries(deps).map(async ([packageName, dependency]) => {
118
246
  // First check if it's in production dependencies
@@ -142,6 +270,24 @@ class PnpmNodeModulesCollector extends nodeModulesCollector_1.NodeModulesCollect
142
270
  }
143
271
  this.productionGraph[dependencyId] = { dependencies: collectedDependencies };
144
272
  }
273
+ /**
274
+ * Resolve a dependency that `pnpm list` left out of a package's tree to its `allDependencies` entry.
275
+ * The lookup goes through the copy node itself would load from `parentPath` (the package's real store
276
+ * directory), filtered by the declared range, and falls back to a name-only match only when nothing on
277
+ * disk resolves to a collected entry (a `link:` dep, whose entry is keyed by its `link:` version).
278
+ *
279
+ * A name-only lookup returns whichever version was collected first, which is wrong as soon as two
280
+ * versions of the package are installed: with the app pinning es5-ext@0.10.53 while its transitive
281
+ * d@1.0.2 needs es5-ext ^0.10.64, `d` was wired to 0.10.53 and the nested 0.10.64 copy (with its own
282
+ * esniff / event-emitter / next-tick@1.1.0 closure) vanished from the asar (#8493). pnpm 10.29.3+
283
+ * made this common, because its deduped output routes every repeated package through this recovery.
284
+ */
285
+ async resolveOmittedDependency(depName, declaredRange, parentPath) {
286
+ const range = typeof declaredRange === "string" ? declaredRange : undefined;
287
+ const located = await this.locateFromDepOrRoot(depName, parentPath, range);
288
+ const exact = located ? this.allDependencies.get(`${depName}@${located.packageJson.version}`) : undefined;
289
+ return exact !== null && exact !== void 0 ? exact : this.getAllDepsByName().get(depName);
290
+ }
145
291
  async collectAllDependencies(_tree, _appPackageName) {
146
292
  for (const root of this.allWorkspacePackages) {
147
293
  await this.collectDepsRecursively(root);
@@ -1 +1 @@
1
- {"version":3,"file":"pnpmNodeModulesCollector.js","sourceRoot":"","sources":["../../src/node-module-collector/pnpmNodeModulesCollector.ts"],"names":[],"mappings":";;;AAAA,uCAA+B;AAC/B,mDAA+D;AAC/D,iEAA6D;AAC7D,qDAA+D;AAG/D,MAAa,wBAAyB,SAAQ,2CAAoD;IAAlG;;QACkB,mBAAc,GAAG;YAC/B,OAAO,EAAE,mBAAE,CAAC,IAAI;YAChB,QAAQ,EAAE,gBAAgB;SAC3B,CAAA;QAED,0DAA0D;QAClD,0BAAqB,GAAqB,EAAE,CAAA;QACpD,4FAA4F;QACpF,sBAAiB,GAAG,CAAC,CAAA;QAC7B,iEAAiE;QAChD,gBAAW,GAAG,IAAI,eAAI,CAAS,KAAK,IAAI,EAAE;;YACzD,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,IAAA,yCAAwB,EAAC,mBAAE,CAAC,IAAI,CAAC,EAAE,CAAC,WAAW,CAAC,CAAC,CAAA;YACrF,MAAM,KAAK,GAAG,QAAQ,CAAC,CAAC,MAAA,MAAM,CAAC,MAAM,mCAAI,GAAG,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAA;YAChE,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAA;QACjC,CA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QAChF,oFAAoF;QACpF,MAAM,MAAM,GAAG,KAAK,CAAC,qBAAqB,CAAC,IAAI,EAAE,WAAW,CAAC,CAAA;QAC7D,IAAI,MAAM,KAAK,IAAI,EAAE,CAAC;YACpB,OAAO,MAAM,CAAA;QACf,CAAC;QACD,kFAAkF;QAClF,4FAA4F;QAC5F,MAAM,KAAK,GAAG,IAAI,CAAC,oBAAoB,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,KAAK,WAAW,IAAI,GAAG,CAAC,IAAI,KAAK,WAAW,CAAC,CAAA;QACzG,OAAO,KAAK,aAAL,KAAK,cAAL,KAAK,GAAI,IAAI,CAAA;IACtB,CAAC;IAES,KAAK,CAAC,qBAAqB,CAAC,QAAgB;QACpD,MAAM,cAAc,GAAG,IAAI,CAAC,6BAA6B,CAAmB,QAAQ,CAAC,CAAA;QACrF,IAAI,CAAC,qBAAqB,GAAG,cAAc,CAAA;QAC3C,IAAI,CAAC,iBAAiB,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,KAAK,CAAA;QACrD,OAAO,cAAc,CAAC,CAAC,CAAC,CAAA;IAC1B,CAAC;CACF;AApMD,4DAoMC","sourcesContent":["import { Lazy } from \"lazy-val\"\nimport { LogMessageByKey, type Package } from \"./moduleManager\"\nimport { NodeModulesCollector } from \"./nodeModulesCollector\"\nimport { getPackageManagerCommand, PM } from \"./packageManager\"\nimport { PnpmDependency } from \"./types\"\n\nexport class PnpmNodeModulesCollector extends NodeModulesCollector<PnpmDependency, PnpmDependency> {\n public readonly installOptions = {\n manager: PM.PNPM,\n lockfile: \"pnpm-lock.yaml\",\n }\n\n // Raw backing field — all entries from `pnpm list --json`\n private _allWorkspacePackages: PnpmDependency[] = []\n // Cached after parseDependenciesTree resolves the Lazy; 0 = safe default (treated as < v11)\n private _pnpmMajorVersion = 0\n // Runs `pnpm --version` once and caches the major version number\n private readonly pnpmVersion = new Lazy<number>(async () => {\n const result = await this.asyncExec(getPackageManagerCommand(PM.PNPM), [\"--version\"])\n const major = parseInt((result.stdout ?? \"0\").split(\".\")[0], 10)\n return isNaN(major) ? 0 : major\n })\n\n /**\n * Memo for `locateFromDepOrRoot`, keyed by `name@version`. pnpm's content-addressed virtual\n * store guarantees that any given `name@version` resolves to a single location on disk, so\n * once we've resolved a package we can short-circuit every subsequent lookup. This is the\n * dominant speedup for large workspaces where the `pnpm list --json` tree contains the same\n * `name@version` thousands of times (one entry per dependent).\n */\n private readonly locateMemo: Map<string, Promise<Package | null>> = new Map()\n\n /**\n * Visited set for `collectDepsRecursively`, keyed by `name@version`. Without this we re-walk\n * every shared subtree of the pnpm list output, exploding work in deep workspaces.\n */\n private readonly collectedDeps: Set<string> = new Set()\n\n /**\n * Returns the workspace packages to iterate over, gated by detected pnpm version:\n * - pnpm v11+: multi-entry workspace output → return the full parsed array\n * - pnpm < v11 / non-workspace / detection failure: single-tree behavior → return only [0]\n */\n private get allWorkspacePackages(): PnpmDependency[] {\n if (this._pnpmMajorVersion >= 11) {\n return this._allWorkspacePackages\n }\n return this._allWorkspacePackages.slice(0, 1)\n }\n\n protected getArgs(): string[] {\n return [\"list\", \"--prod\", \"--json\", \"--depth\", \"Infinity\", \"--silent\", \"--loglevel=error\"]\n }\n\n /**\n * Locate a package version, preferring the dep's own reported path before falling back to rootDir.\n * This is critical for pnpm non-hoisted (virtual store) setups where each package has its own\n * nested node_modules. Searching only from rootDir can resolve the wrong version when multiple\n * versions of a dep exist in the workspace.\n */\n private async locateFromDepOrRoot(pkgName: string, parentPath: string | undefined, requiredRange?: string) {\n // pnpm's virtual store is content-addressed: every `name@version` lookup is deterministic,\n // so memoize on the exact version. `requiredRange` is normally an exact version coming from\n // the pnpm list output (e.g. `value.version`), which makes this cache hit on duplicates.\n // Only memoize when we have a concrete version — semver ranges could resolve differently\n // depending on what's installed at `parentPath` vs root, so skip the cache for those.\n const memoKey = requiredRange && /^\\d/.test(requiredRange) ? `${pkgName}@${requiredRange}` : null\n if (memoKey != null) {\n const cached = this.locateMemo.get(memoKey)\n if (cached != null) {\n return cached\n }\n }\n\n // pnpm's default `.pnpm` virtual store is flat, so `downwardSearch` would burn thousands\n // of `readdir`/`lstat` calls finding nothing. With `nodeLinker: hoisted`, however, the\n // layout is a traditional nested `node_modules` tree where version-conflicted packages\n // land at `<root>/node_modules/A/node_modules/B` — downward BFS is needed to find them.\n const skipDownwardSearch = !(await this.isHoisted.value)\n const promise = (async (): Promise<Package | null> => {\n const fromDep = parentPath ? await this.cache.locatePackageVersion({ pkgName, parentDir: parentPath, requiredRange, skipDownwardSearch }) : null\n if (fromDep) {\n return fromDep\n }\n return this.cache.locatePackageVersion({ pkgName, parentDir: this.rootDir, requiredRange, skipDownwardSearch })\n })()\n\n if (memoKey != null) {\n this.locateMemo.set(memoKey, promise)\n }\n return promise\n }\n\n // pnpm 10+ does not automatically preserve transitive optional platform-specific\n // packages (e.g. sass-embedded-linux-x64) across lock file regeneration. Users\n // must list them as direct optionalDependencies. Missing ones are emitted as\n // PKG_OPTIONAL_PLATFORM_NOT_INSTALLED warnings in the log summary.\n protected async extractProductionDependencyGraph(tree: PnpmDependency, dependencyId: string) {\n if (this.productionGraph[dependencyId]) {\n return\n }\n this.productionGraph[dependencyId] = { dependencies: [] }\n\n if ((tree.dedupedDependenciesCount ?? 0) > 0) {\n const realDep = this.allDependencies.get(dependencyId)\n if (realDep) {\n this.cache.logSummary[LogMessageByKey.PKG_DUPLICATE_REF].push(dependencyId)\n tree = realDep\n } else {\n this.cache.logSummary[LogMessageByKey.PKG_DUPLICATE_REF_UNRESOLVED].push(dependencyId)\n return\n }\n }\n\n const packageName = tree.name || tree.from\n const { packageJson } = (await this.locateFromDepOrRoot(packageName, tree.path, tree.version)) || {}\n\n const all = packageJson ? { ...packageJson.dependencies, ...packageJson.optionalDependencies } : { ...tree.dependencies, ...tree.optionalDependencies }\n const optional = packageJson ? { ...packageJson.optionalDependencies } : {}\n\n const deps = { ...(tree.dependencies || {}), ...(tree.optionalDependencies || {}) }\n this.productionGraph[dependencyId] = { dependencies: [] }\n const depPromises = Object.entries(deps).map(async ([packageName, dependency]) => {\n // First check if it's in production dependencies\n if (!all[packageName]) {\n return undefined\n }\n\n // Then check if optional dependency path exists (using actual resolved path)\n if (optional[packageName]) {\n const pkg = await this.locateFromDepOrRoot(packageName, tree.path, dependency.version)\n if (!pkg) {\n // Declared in `optionalDependencies`, so a miss is an expected condition (e.g. fsevents\n // on Linux/Windows) — classify it as a missing optional dependency, not PKG_NOT_ON_DISK.\n this.logMissingDependency(`${packageName}@${dependency.version}`, true)\n return undefined\n }\n }\n const { id: childDependencyId, pkgOverride } = this.normalizePackageVersion(packageName, dependency)\n await this.extractProductionDependencyGraph(pkgOverride, childDependencyId)\n return childDependencyId\n })\n\n const collectedDependencies: string[] = []\n for (const dep of depPromises) {\n const result = await dep\n if (result !== undefined) {\n collectedDependencies.push(result)\n }\n }\n this.productionGraph[dependencyId] = { dependencies: collectedDependencies }\n }\n\n protected async collectAllDependencies(_tree: PnpmDependency, _appPackageName: string): Promise<void> {\n for (const root of this.allWorkspacePackages) {\n await this.collectDepsRecursively(root)\n }\n }\n\n private async collectDepsRecursively(tree: PnpmDependency): Promise<void> {\n const visit = async (key: string, value: PnpmDependency) => {\n if ((value?.dedupedDependenciesCount ?? 0) > 0) {\n return\n }\n const id = `${key}@${value.version}`\n // The pnpm list output can include the same `name@version` thousands of times across a\n // deep workspace; without this guard we re-resolve and re-recurse each occurrence.\n if (this.collectedDeps.has(id)) {\n return\n }\n this.collectedDeps.add(id)\n const pkg = await this.locateFromDepOrRoot(key, value.path, value.version)\n this.allDependencies.set(id, { ...value, path: pkg?.packageDir ?? value.path })\n await this.collectDepsRecursively(value)\n }\n\n for (const [key, value] of Object.entries(tree.dependencies || {})) {\n await visit(key, value)\n }\n for (const [key, value] of Object.entries(tree.optionalDependencies || {})) {\n await visit(key, value)\n }\n }\n\n protected override getTreeFromWorkspaces(tree: PnpmDependency, packageName: string): PnpmDependency {\n // pnpm v10 workspace: app is nested as a dependency of root — handled by base class\n const result = super.getTreeFromWorkspaces(tree, packageName)\n if (result !== tree) {\n return result\n }\n // pnpm v11 workspace: each workspace package is a separate top-level array entry;\n // non-workspace (single-tree): find returns the one entry or undefined → falls back to tree\n const match = this.allWorkspacePackages.find(pkg => pkg.name === packageName || pkg.from === packageName)\n return match ?? tree\n }\n\n protected async parseDependenciesTree(jsonBlob: string): Promise<PnpmDependency> {\n const dependencyTree = this.extractJsonFromPollutedOutput<PnpmDependency[]>(jsonBlob)\n this._allWorkspacePackages = dependencyTree\n this._pnpmMajorVersion = await this.pnpmVersion.value\n return dependencyTree[0]\n }\n}\n"]}
1
+ {"version":3,"file":"pnpmNodeModulesCollector.js","sourceRoot":"","sources":["../../src/node-module-collector/pnpmNodeModulesCollector.ts"],"names":[],"mappings":";;;AAAA,+BAA8B;AAC9B,uCAA+B;AAC/B,6BAA4B;AAC5B,mDAA+D;AAC/D,iEAA6D;AAC7D,qDAA+D;AAE/D,+CAAiD;AAEjD,MAAa,wBAAyB,SAAQ,2CAAoD;IAAlG;;QACkB,mBAAc,GAAG;YAC/B,OAAO,EAAE,mBAAE,CAAC,IAAI;YAChB,QAAQ,EAAE,gBAAgB;SAC3B,CAAA;QAED,0DAA0D;QAClD,0BAAqB,GAAqB,EAAE,CAAA;QACpD,4FAA4F;QACpF,sBAAiB,GAAG,CAAC,CAAA;QAC7B,iEAAiE;QAChD,gBAAW,GAAG,IAAI,eAAI,CAAS,KAAK,IAAI,EAAE;;YACzD,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,IAAA,yCAAwB,EAAC,mBAAE,CAAC,IAAI,CAAC,EAAE,CAAC,WAAW,CAAC,CAAC,CAAA;YACrF,MAAM,KAAK,GAAG,QAAQ,CAAC,CAAC,MAAA,MAAM,CAAC,MAAM,mCAAI,GAAG,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAA;YAChE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\"fs-extra\"\nimport { Lazy } from \"lazy-val\"\nimport * as path from \"path\"\nimport { LogMessageByKey, type Package } from \"./moduleManager\"\nimport { NodeModulesCollector } from \"./nodeModulesCollector\"\nimport { getPackageManagerCommand, PM } from \"./packageManager\"\nimport { PnpmDependency } from \"./types\"\nimport { exists, isValidKey } from \"builder-util\"\n\nexport class PnpmNodeModulesCollector extends NodeModulesCollector<PnpmDependency, PnpmDependency> {\n public readonly installOptions = {\n manager: PM.PNPM,\n lockfile: \"pnpm-lock.yaml\",\n }\n\n // Raw backing field — all entries from `pnpm list --json`\n private _allWorkspacePackages: PnpmDependency[] = []\n // Cached after parseDependenciesTree resolves the Lazy; 0 = safe default (treated as < v11)\n private _pnpmMajorVersion = 0\n // Runs `pnpm --version` once and caches the major version number\n private readonly pnpmVersion = new Lazy<number>(async () => {\n const result = await this.asyncExec(getPackageManagerCommand(PM.PNPM), [\"--version\"])\n const major = parseInt((result.stdout ?? \"0\").split(\".\")[0], 10)\n return isNaN(major) ? 0 : major\n })\n\n /**\n * Detect pnpm's installed layout from the on-disk structure rather than `pnpm config list`.\n * pnpm 11 no longer echoes `node-linker` (from `.npmrc`) in `config list`, so the base-class\n * config-parsing detection silently reports \"not hoisted\" for a hoisted install, which would\n * disable the downward search needed to find version-conflicted nested deps.\n *\n * In the default isolated store every regular top-level package resolves — through a symlink\n * on POSIX, a junction on Windows — into `node_modules/.pnpm/<name>@<ver>/node_modules/<name>`.\n * In a hoisted layout the same package is a real directory directly under `node_modules`.\n * `realpath` transparently follows both symlinks and junctions, so a layout is isolated iff\n * *any* top-level package's real path routes through `.pnpm`. We scan rather than sample the\n * first entry because `link:` packages resolve to their source (never under `.pnpm`) and could\n * otherwise mask an isolated store.\n */\n protected override isHoisted = new Lazy<boolean>(async () => {\n // A workspace package's own `node_modules` is often absent (or holds only its version\n // conflicts) in a hoisted workspace, so fall back to the workspace root's `node_modules`.\n let sawPackage = false\n for (const dir of await this.layoutRoots.value) {\n const isolated = await this.scanNodeModulesLayout(path.join(dir, \"node_modules\"))\n if (isolated != null) {\n if (isolated) {\n return false\n }\n sawPackage = true\n }\n }\n // Packages exist and none route through `.pnpm` → hoisted. No packages → flat default.\n return sawPackage\n })\n\n /**\n * The pnpm workspace root containing `rootDir` (nearest ancestor with `pnpm-workspace.yaml`, as pnpm\n * itself resolves it), or null outside a workspace or when `rootDir` is the workspace root.\n */\n private readonly workspaceRoot = new Lazy<string | null>(async () => {\n let current = path.resolve(this.rootDir)\n while (true) {\n if (await exists(path.join(current, \"pnpm-workspace.yaml\"))) {\n return current === path.resolve(this.rootDir) ? null : current\n }\n const parent = path.dirname(current)\n if (parent === current) {\n return null\n }\n current = parent\n }\n })\n\n /** `rootDir`, then the workspace root when `rootDir` is a workspace package. */\n private readonly layoutRoots = new Lazy<string[]>(async () => {\n const workspaceRoot = await this.workspaceRoot.value\n return workspaceRoot == null ? [this.rootDir] : [this.rootDir, workspaceRoot]\n })\n\n /** Returns true if `nmDir` is an isolated (`.pnpm`) store, false if hoisted, null if it holds no packages. */\n private async scanNodeModulesLayout(nmDir: string): Promise<boolean | null> {\n const entries = await fs.readdir(nmDir).catch(() => [] as string[])\n let sawPackage = false\n for (const name of entries) {\n if (name.startsWith(\".\")) {\n continue // .pnpm, .bin, .modules.yaml\n }\n const entryPath = path.join(nmDir, name)\n // A scoped dir (@scope) is not a package itself; descend to its packages.\n const candidates = name.startsWith(\"@\") ? (await fs.readdir(entryPath).catch(() => [] as string[])).map(s => path.join(entryPath, s)) : [entryPath]\n for (const candidate of candidates) {\n const real = await fs.realpath(candidate).catch(() => null)\n if (real == null) {\n continue\n }\n sawPackage = true\n if (real.split(path.sep).includes(\".pnpm\")) {\n return true // isolated store: a package routes through the virtual store\n }\n }\n }\n return sawPackage ? false : null\n }\n\n /**\n * Memo for `locateFromDepOrRoot`, keyed by `name@version`. pnpm's content-addressed virtual\n * store guarantees that any given `name@version` resolves to a single location on disk, so\n * once we've resolved a package we can short-circuit every subsequent lookup. This is the\n * dominant speedup for large workspaces where the `pnpm list --json` tree contains the same\n * `name@version` thousands of times (one entry per dependent).\n */\n private readonly locateMemo: Map<string, Promise<Package | null>> = new Map()\n\n /**\n * Visited set for `collectDepsRecursively`, keyed by `name@version`. Without this we re-walk\n * every shared subtree of the pnpm list output, exploding work in deep workspaces.\n */\n private readonly collectedDeps: Set<string> = new Set()\n\n /** Reverse index of `allDependencies` keyed by package name (without version). Built once on\n * first access inside `extractProductionDependencyGraph`, after `allDependencies` is settled. */\n private _allDepsByName: Map<string, PnpmDependency> | null = null\n\n /**\n * Returns the workspace packages to iterate over, gated by detected pnpm version:\n * - pnpm v11+: multi-entry workspace output → return the full parsed array\n * - pnpm < v11 / non-workspace / detection failure: single-tree behavior → return only [0]\n */\n private get allWorkspacePackages(): PnpmDependency[] {\n if (this._pnpmMajorVersion >= 11) {\n return this._allWorkspacePackages\n }\n return this._allWorkspacePackages.slice(0, 1)\n }\n\n protected getArgs(): string[] {\n return [\"list\", \"--prod\", \"--json\", \"--depth\", \"Infinity\", \"--silent\", \"--loglevel=error\"]\n }\n\n private getAllDepsByName(): Map<string, PnpmDependency> {\n if (!this._allDepsByName) {\n this._allDepsByName = new Map()\n for (const [id, dep] of this.allDependencies.entries()) {\n const { name } = this.parseNameVersion(id)\n if (!this._allDepsByName.has(name)) {\n this._allDepsByName.set(name, dep)\n }\n }\n }\n return this._allDepsByName\n }\n\n /**\n * Locate a package version, preferring the dep's own reported path before falling back to rootDir.\n * This is critical for pnpm non-hoisted (virtual store) setups where each package has its own\n * nested node_modules. Searching only from rootDir can resolve the wrong version when multiple\n * versions of a dep exist in the workspace.\n */\n private async locateFromDepOrRoot(pkgName: string, parentPath: string | undefined, requiredRange?: string) {\n // pnpm's virtual store is content-addressed: every `name@version` lookup is deterministic,\n // so memoize on the exact version. `requiredRange` is normally an exact version coming from\n // the pnpm list output (e.g. `value.version`), which makes this cache hit on duplicates.\n // Only memoize when we have a concrete version — semver ranges could resolve differently\n // depending on what's installed at `parentPath` vs root, so skip the cache for those.\n const memoKey = requiredRange && /^\\d/.test(requiredRange) ? `${pkgName}@${requiredRange}` : null\n if (memoKey != null) {\n const cached = this.locateMemo.get(memoKey)\n if (cached != null) {\n return cached\n }\n }\n\n // pnpm's default `.pnpm` virtual store is flat, so `downwardSearch` would burn thousands\n // of `readdir`/`lstat` calls finding nothing. With `nodeLinker: hoisted`, however, the\n // layout is a traditional nested `node_modules` tree where version-conflicted packages\n // land at `<root>/node_modules/A/node_modules/B` — downward BFS is needed to find them.\n const skipDownwardSearch = !(await this.isHoisted.value)\n const promise = (async (): Promise<Package | null> => {\n // Phase 1: find a version that SATISFIES requiredRange, trying the dep's own location\n // first, then the workspace root. Crucially, neither pass accepts an out-of-range override\n // here — so a wrong-version copy reachable via upward search from `parentPath` (e.g. a\n // hoisted top-level dep) can't shadow the correct nested copy under root. With\n // `nodeLinker: hoisted`, pnpm still reports virtual-store `path`s that don't exist on disk;\n // an upward walk from one meets the root copy, which previously got accepted as an\n // \"override\" before the root search (whose downward BFS finds the nested copy) ever ran.\n //\n // When `rootDir` is a workspace package, a hoisted install keeps the tree — including the\n // nested `<workspaceRoot>/node_modules/A/node_modules/B` copies — under the workspace root,\n // which the downward BFS from `rootDir` never reaches (its `node_modules` is often absent),\n // so search the workspace root last.\n let satisfying = parentPath ? await this.cache.locatePackageVersion({ pkgName, parentDir: parentPath, requiredRange, skipDownwardSearch, skipOverrideFallback: true }) : null\n for (const dir of await this.layoutRoots.value) {\n satisfying ??= await this.cache.locatePackageVersion({ pkgName, parentDir: dir, requiredRange, skipDownwardSearch, skipOverrideFallback: true })\n }\n if (satisfying) {\n return satisfying\n }\n // Phase 2: no version satisfies requiredRange (package-manager override, or no range\n // given). Fall back to the original dep-then-root order, now allowing override versions.\n const fromDep = parentPath ? await this.cache.locatePackageVersion({ pkgName, parentDir: parentPath, requiredRange, skipDownwardSearch }) : null\n if (fromDep) {\n return fromDep\n }\n return this.cache.locatePackageVersion({ pkgName, parentDir: this.rootDir, requiredRange, skipDownwardSearch })\n })()\n\n if (memoKey != null) {\n this.locateMemo.set(memoKey, promise)\n }\n return promise\n }\n\n // pnpm 10+ does not automatically preserve transitive optional platform-specific\n // packages (e.g. sass-embedded-linux-x64) across lock file regeneration. Users\n // must list them as direct optionalDependencies. Missing ones are emitted as\n // PKG_OPTIONAL_PLATFORM_NOT_INSTALLED warnings in the log summary.\n protected async extractProductionDependencyGraph(tree: PnpmDependency, dependencyId: string) {\n if (this.productionGraph[dependencyId]) {\n return\n }\n this.productionGraph[dependencyId] = { dependencies: [] }\n\n if ((tree.dedupedDependenciesCount ?? 0) > 0) {\n const realDep = this.allDependencies.get(dependencyId)\n if (realDep) {\n this.cache.logSummary[LogMessageByKey.PKG_DUPLICATE_REF].push(dependencyId)\n tree = realDep\n } else {\n this.cache.logSummary[LogMessageByKey.PKG_DUPLICATE_REF_UNRESOLVED].push(dependencyId)\n return\n }\n }\n\n const packageName = tree.name || tree.from\n const { packageJson } = (await this.locateFromDepOrRoot(packageName, tree.path, tree.version)) || {}\n\n const all = packageJson ? { ...packageJson.dependencies, ...packageJson.optionalDependencies } : { ...tree.dependencies, ...tree.optionalDependencies }\n const optional = packageJson ? { ...packageJson.optionalDependencies } : {}\n\n const deps: Record<string, PnpmDependency> = { ...(tree.dependencies || {}), ...(tree.optionalDependencies || {}) }\n\n // pnpm --prod omits sub-deps for link: packages (and synthetic entries derived from them), and pnpm\n // 10.29.3+ prints a repeated subtree only once, so every later occurrence is a childless `deduped`\n // stub (which is what `tree` is when the stub was the first occurrence collected). For any dep\n // declared in the package.json (all) that pnpm left out of the tree, recover the resolved entry\n // from allDependencies so it lands in the production graph.\n for (const [depName, declaredRange] of Object.entries(all)) {\n if (!deps[depName]) {\n const dep = await this.resolveOmittedDependency(depName, declaredRange, tree.path)\n if (dep && isValidKey(depName)) {\n deps[depName] = dep\n }\n }\n }\n\n this.productionGraph[dependencyId] = { dependencies: [] }\n const depPromises = Object.entries(deps).map(async ([packageName, dependency]) => {\n // First check if it's in production dependencies\n if (!all[packageName]) {\n return undefined\n }\n\n // Then check if optional dependency path exists (using actual resolved path)\n if (optional[packageName]) {\n const pkg = await this.locateFromDepOrRoot(packageName, tree.path, dependency.version)\n if (!pkg) {\n // Declared in `optionalDependencies`, so a miss is an expected condition (e.g. fsevents\n // on Linux/Windows) — classify it as a missing optional dependency, not PKG_NOT_ON_DISK.\n this.logMissingDependency(`${packageName}@${dependency.version}`, true)\n return undefined\n }\n }\n const { id: childDependencyId, pkgOverride } = this.normalizePackageVersion(packageName, dependency)\n await this.extractProductionDependencyGraph(pkgOverride, childDependencyId)\n return childDependencyId\n })\n\n const collectedDependencies: string[] = []\n for (const dep of depPromises) {\n const result = await dep\n if (result !== undefined) {\n collectedDependencies.push(result)\n }\n }\n this.productionGraph[dependencyId] = { dependencies: collectedDependencies }\n }\n\n /**\n * Resolve a dependency that `pnpm list` left out of a package's tree to its `allDependencies` entry.\n * The lookup goes through the copy node itself would load from `parentPath` (the package's real store\n * directory), filtered by the declared range, and falls back to a name-only match only when nothing on\n * disk resolves to a collected entry (a `link:` dep, whose entry is keyed by its `link:` version).\n *\n * A name-only lookup returns whichever version was collected first, which is wrong as soon as two\n * versions of the package are installed: with the app pinning es5-ext@0.10.53 while its transitive\n * d@1.0.2 needs es5-ext ^0.10.64, `d` was wired to 0.10.53 and the nested 0.10.64 copy (with its own\n * esniff / event-emitter / next-tick@1.1.0 closure) vanished from the asar (#8493). pnpm 10.29.3+\n * made this common, because its deduped output routes every repeated package through this recovery.\n */\n private async resolveOmittedDependency(depName: string, declaredRange: unknown, parentPath: string | undefined): Promise<PnpmDependency | undefined> {\n const range = typeof declaredRange === \"string\" ? declaredRange : undefined\n const located = await this.locateFromDepOrRoot(depName, parentPath, range)\n const exact = located ? this.allDependencies.get(`${depName}@${located.packageJson.version}`) : undefined\n return exact ?? this.getAllDepsByName().get(depName)\n }\n\n protected async collectAllDependencies(_tree: PnpmDependency, _appPackageName: string): Promise<void> {\n for (const root of this.allWorkspacePackages) {\n await this.collectDepsRecursively(root)\n }\n }\n\n private async collectDepsRecursively(tree: PnpmDependency): Promise<void> {\n const visit = async (key: string, value: PnpmDependency) => {\n if ((value?.dedupedDependenciesCount ?? 0) > 0) {\n return\n }\n const id = `${key}@${value.version}`\n // The pnpm list output can include the same `name@version` thousands of times across a\n // deep workspace; without this guard we re-resolve and re-recurse each occurrence.\n if (this.collectedDeps.has(id)) {\n return\n }\n this.collectedDeps.add(id)\n const pkg = await this.locateFromDepOrRoot(key, value.path, value.version)\n this.allDependencies.set(id, { ...value, path: pkg?.packageDir ?? value.path })\n await this.collectDepsRecursively(value)\n }\n\n for (const [key, value] of Object.entries(tree.dependencies || {})) {\n await visit(key, value)\n }\n for (const [key, value] of Object.entries(tree.optionalDependencies || {})) {\n await visit(key, value)\n }\n }\n\n protected override getTreeFromWorkspaces(tree: PnpmDependency, packageName: string): PnpmDependency {\n // pnpm v10 workspace: app is nested as a dependency of root — handled by base class\n const result = super.getTreeFromWorkspaces(tree, packageName)\n if (result !== tree) {\n return result\n }\n // pnpm v11 workspace: each workspace package is a separate top-level array entry;\n // non-workspace (single-tree): find returns the one entry or undefined → falls back to tree\n const match = this.allWorkspacePackages.find(pkg => pkg.name === packageName || pkg.from === packageName)\n return match ?? tree\n }\n\n protected async parseDependenciesTree(jsonBlob: string): Promise<PnpmDependency> {\n const dependencyTree = this.extractJsonFromPollutedOutput<PnpmDependency[]>(jsonBlob)\n this._allWorkspacePackages = dependencyTree\n this._pnpmMajorVersion = await this.pnpmVersion.value\n return dependencyTree[0]\n }\n}\n"]}
package/out/packager.d.ts CHANGED
@@ -49,6 +49,8 @@ export declare class Packager {
49
49
  _appInfo: AppInfo | null;
50
50
  get appInfo(): AppInfo;
51
51
  readonly tempDirManager: TmpDir;
52
+ private readonly buildFinalizeTasks;
53
+ addBuildFinalizeTask(task: () => Promise<void>): void;
52
54
  private _repositoryInfo;
53
55
  readonly options: PackagerOptions;
54
56
  readonly debugLogger: DebugLogger;
package/out/packager.js CHANGED
@@ -83,6 +83,9 @@ class Packager {
83
83
  get appInfo() {
84
84
  return this._appInfo;
85
85
  }
86
+ addBuildFinalizeTask(task) {
87
+ this.buildFinalizeTasks.push(task);
88
+ }
86
89
  get repositoryInfo() {
87
90
  return this._repositoryInfo.value;
88
91
  }
@@ -118,6 +121,10 @@ class Packager {
118
121
  this.eventEmitter = new asyncEventEmitter_1.AsyncEventEmitter();
119
122
  this._appInfo = null;
120
123
  this.tempDirManager = new builder_util_1.TmpDir("packager");
124
+ // Tasks that must run after EVERY target has finished building — the only point at which the
125
+ // shared appOutDir can be mutated without racing a concurrent target that reads it. Used by NSIS
126
+ // to write elevate.exe into win-unpacked without it leaking into Squirrel/zip/etc. (see #9852).
127
+ this.buildFinalizeTasks = [];
121
128
  this._repositoryInfo = new lazy_val_1.Lazy(() => (0, repositoryInfo_1.getRepositoryInfo)(this.projectDir, this.metadata, this.devMetadata));
122
129
  this.debugLogger = new builder_util_1.DebugLogger(builder_util_1.log.isDebugEnabled);
123
130
  this.runtimeEnvironmentVariables = {};
@@ -421,6 +428,14 @@ class Packager {
421
428
  }
422
429
  await target.finishBuild();
423
430
  }
431
+ // Every target has now finished reading the shared appOutDir(s), so finalize tasks may safely
432
+ // mutate them (e.g. NSIS copying elevate.exe into win-unpacked — see #9852).
433
+ for (const task of this.buildFinalizeTasks) {
434
+ if (this.cancellationToken.cancelled) {
435
+ break;
436
+ }
437
+ await task();
438
+ }
424
439
  return platformToTarget;
425
440
  }
426
441
  async createHelper(platform) {