// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. import * as path from 'node:path'; import { AlreadyReportedError, EnvironmentMap, FileConstants, FileSystem, JsonFile, type JsonObject, Objects } from '@rushstack/node-core-library'; import { Colorize, ConsoleTerminalProvider, type ITerminal, type ITerminalProvider, Terminal, PrintUtilities } from '@rushstack/terminal'; import { RushConfiguration } from '../api/RushConfiguration'; import { NodeJsCompatibility } from '../logic/NodeJsCompatibility'; import { RushConstants } from '../logic/RushConstants'; import { RushGlobalFolder } from '../api/RushGlobalFolder'; import { PurgeManager } from '../logic/PurgeManager'; import type { IBuiltInPluginConfiguration } from '../pluginFramework/PluginLoader/BuiltInPluginLoader'; import type { BaseInstallManager } from '../logic/base/BaseInstallManager'; import type { IInstallManagerOptions } from '../logic/base/BaseInstallManagerTypes'; import { Utilities } from '../utilities/Utilities'; import { getNpmrcEnvironmentVariables } from '../utilities/npmrcUtilities'; import { InstallHelpers } from '../logic/installManager/InstallHelpers'; import type { Subspace } from '../api/Subspace'; import type { PnpmOptionsConfiguration } from '../logic/pnpm/PnpmOptionsConfiguration'; import { getEffectivePnpmOptions, getOtherSubspacesSharingPnpmConfig, mergePnpmCatalogs, type PnpmCatalogs } from '../logic/pnpm/EffectivePnpmOptions'; import { PnpmWorkspaceFile } from '../logic/pnpm/PnpmWorkspaceFile'; import { EnvironmentVariableNames } from '../api/EnvironmentConfiguration'; import { initializeDotEnv } from '../logic/dotenv'; const RUSH_SKIP_CHECKS_PARAMETER: string = '--rush-skip-checks'; const RUSH_PNPM_RECURSIVE_DEFAULT_COMMANDS: Set = new Set(['outdated', 'why']); function _hasRecursiveFlag(pnpmArgs: string[]): boolean { return pnpmArgs.some((arg) => arg === '-r' || arg === '--recursive' || arg.startsWith('--recursive=')); } function _hasGlobalFlag(pnpmArgs: string[]): boolean { return pnpmArgs.some((arg) => arg === '-g' || arg === '--global' || arg.startsWith('--global=')); } function _addDefaultRecursiveFlagIfNeeded(commandName: string, pnpmArgs: string[]): void { if ( RUSH_PNPM_RECURSIVE_DEFAULT_COMMANDS.has(commandName) && !_hasRecursiveFlag(pnpmArgs) && !_hasGlobalFlag(pnpmArgs) ) { pnpmArgs.splice(1, 0, '--recursive'); } } /** * Options for RushPnpmCommandLineParser */ export interface IRushPnpmCommandLineParserOptions { alreadyReportedNodeTooNewError?: boolean; builtInPluginConfigurations?: IBuiltInPluginConfiguration[]; terminalProvider?: ITerminalProvider; } /** * Controlled dependencies for exercising execution and synchronization in unit tests. * @internal */ export interface IRushPnpmCommandLineParserTestOptions { commandName: string; doRushUpdateAsync: () => Promise; rushConfiguration: RushConfiguration; subspace: Subspace; terminal: ITerminal; } function _reportErrorAndSetExitCode(error: Error, terminal: ITerminal, debugEnabled: boolean): never { if (!(error instanceof AlreadyReportedError)) { const prefix: string = 'ERROR: '; terminal.writeErrorLine('\n' + PrintUtilities.wrapWords(prefix + error.message)); } if (debugEnabled) { // If catchSyncErrors() called this, then show a call stack similar to what Node.js // would show for an uncaught error terminal.writeErrorLine('\n' + error.stack); } process.exit(process.exitCode ?? 1); } export class RushPnpmCommandLineParser { readonly #terminal: ITerminal; readonly #rushConfiguration: RushConfiguration; readonly #pnpmArgs: string[]; #commandName: string | undefined; readonly #debugEnabled: boolean; #subspace: Subspace; readonly #doRushUpdateAsyncOverride: (() => Promise) | undefined; private constructor( options: IRushPnpmCommandLineParserOptions, terminal: ITerminal, debugEnabled: boolean, testOptions?: IRushPnpmCommandLineParserTestOptions ) { this.#debugEnabled = debugEnabled; this.#terminal = terminal; this.#doRushUpdateAsyncOverride = testOptions?.doRushUpdateAsync; if (testOptions) { this.#rushConfiguration = testOptions.rushConfiguration; this.#pnpmArgs = []; this.#commandName = testOptions.commandName; this.#subspace = testOptions.subspace; return; } // Are we in a Rush repo? const rushJsonFilePath: string | undefined = RushConfiguration.tryFindRushJsonLocation({ // showVerbose is false because the logging message may break JSON output showVerbose: false }); initializeDotEnv(terminal, rushJsonFilePath); const rushConfiguration: RushConfiguration | undefined = rushJsonFilePath ? RushConfiguration.loadFromConfigurationFile(rushJsonFilePath) : undefined; NodeJsCompatibility.warnAboutCompatibilityIssues({ isRushLib: true, alreadyReportedNodeTooNewError: !!options.alreadyReportedNodeTooNewError, rushConfiguration }); if (!rushConfiguration) { throw new Error( 'The "rush-pnpm" command must be executed in a folder that is under a Rush workspace folder' ); } this.#rushConfiguration = rushConfiguration; if (rushConfiguration.packageManager !== 'pnpm') { throw new Error( `The "rush-pnpm" command requires your ${RushConstants.rushJsonFilename} to be configured to use the PNPM package manager` ); } if (!rushConfiguration.pnpmOptions.useWorkspaces) { const pnpmConfigFilename: string = rushConfiguration.pnpmOptions.jsonFilename || RushConstants.rushJsonFilename; throw new Error( `The "rush-pnpm" command requires the "useWorkspaces" setting to be enabled in ${pnpmConfigFilename}` ); } let pnpmArgs: string[] = []; let subspaceName: string = 'default'; if (process.argv.indexOf('--subspace') >= 0) { if (process.argv[2] !== '--subspace') { throw new Error( 'If you want to specify a subspace, you should place "--subspace " immediately after the "rush-pnpm" command' ); } subspaceName = process.argv[3]; // 0 = node.exe // 1 = rush-pnpm // 2 = --subspace // 3 = pnpmArgs = process.argv.slice(4); } else { // 0 = node.exe // 1 = rush-pnpm pnpmArgs = process.argv.slice(2); } this.#pnpmArgs = pnpmArgs; const subspace: Subspace = rushConfiguration.getSubspace(subspaceName); this.#subspace = subspace; const workspaceFolder: string = subspace.getSubspaceTempFolderPath(); const workspaceFilePath: string = `${workspaceFolder}/${RushConstants.pnpmWorkspaceFileName}`; if (!FileSystem.exists(workspaceFilePath)) { this.#terminal.writeErrorLine('Error: The PNPM workspace file has not been generated:'); this.#terminal.writeErrorLine(` ${workspaceFilePath}\n`); this.#terminal.writeLine(Colorize.cyan(`Do you need to run "rush install" or "rush update"?`)); throw new AlreadyReportedError(); } if (!FileSystem.exists(rushConfiguration.packageManagerToolFilename)) { this.#terminal.writeErrorLine('Error: The PNPM local binary has not been installed yet.'); this.#terminal.writeLine('\n' + Colorize.cyan(`Do you need to run "rush install" or "rush update"?`)); throw new AlreadyReportedError(); } } public static async initializeAsync( options: IRushPnpmCommandLineParserOptions ): Promise { const debugEnabled: boolean = process.argv.indexOf('--debug') >= 0; const verboseEnabled: boolean = process.argv.indexOf('--verbose') >= 0; const localTerminalProvider: ITerminalProvider = options.terminalProvider ?? new ConsoleTerminalProvider({ debugEnabled, verboseEnabled }); const terminal: ITerminal = new Terminal(localTerminalProvider); try { const rushPnpmCommandLineParser: RushPnpmCommandLineParser = new RushPnpmCommandLineParser( options, terminal, debugEnabled ); await rushPnpmCommandLineParser.#validatePnpmUsageAsync(rushPnpmCommandLineParser.#pnpmArgs); return rushPnpmCommandLineParser; } catch (error) { _reportErrorAndSetExitCode(error as Error, terminal, debugEnabled); } } /** * Exercises argument validation without invoking the side-effectful constructor. * @internal */ public static async _validatePnpmUsageForTestingAsync(pnpmArgs: string[]): Promise { const terminal: Terminal = new Terminal(new ConsoleTerminalProvider()); const rushConfiguration: RushConfiguration = Object.create(RushConfiguration.prototype); const subspace: Subspace = Object.create(null); const parser: RushPnpmCommandLineParser = new RushPnpmCommandLineParser({}, terminal, false, { commandName: '', doRushUpdateAsync: async () => {}, rushConfiguration, subspace, terminal }); await parser.#validatePnpmUsageAsync(pnpmArgs); } /** * Exercises post-execution synchronization with controlled dependencies. * @internal */ public static async _postExecuteForTestingAsync( testOptions: IRushPnpmCommandLineParserTestOptions ): Promise { const parser: RushPnpmCommandLineParser = new RushPnpmCommandLineParser( {}, testOptions.terminal, false, testOptions ); await parser.#postExecuteAsync(); } /** * Exercises package-manager execution with controlled dependencies. * @internal */ public static async _executeForTestingAsync( testOptions: IRushPnpmCommandLineParserTestOptions ): Promise { const parser: RushPnpmCommandLineParser = new RushPnpmCommandLineParser( {}, testOptions.terminal, false, testOptions ); await parser.#executeAsync(); } public async executeAsync(): Promise { // Node.js can sometimes accidentally terminate with a zero exit code (e.g. for an uncaught // promise exception), so we start with the assumption that the exit code is 1 // and set it to 0 only on success. process.exitCode = 1; await this.#executeAsync(); if (process.exitCode === 0) { await this.#postExecuteAsync(); } } async #validatePnpmUsageAsync(pnpmArgs: string[]): Promise { if (pnpmArgs[0] === RUSH_SKIP_CHECKS_PARAMETER) { pnpmArgs.shift(); // Ignore other checks return; } if (pnpmArgs.length === 0) { return; } const firstArg: string = pnpmArgs[0]; // Detect common safe invocations if (pnpmArgs.includes('-h') || pnpmArgs.includes('--help') || pnpmArgs.includes('-?')) { return; } if (pnpmArgs.length === 1) { if (firstArg === '-v' || firstArg === '--version') { return; } } const BYPASS_NOTICE: string = `To bypass this check, add "${RUSH_SKIP_CHECKS_PARAMETER}" as the very first command line option.`; if (!/^[a-z]+([a-z0-9\-])*$/.test(firstArg)) { // We can't parse this CLI syntax this.#terminal.writeErrorLine( `Warning: The "rush-pnpm" wrapper expects a command verb before "${firstArg}"\n` ); this.#terminal.writeLine(Colorize.cyan(BYPASS_NOTICE)); throw new AlreadyReportedError(); } else { const commandName: string = firstArg; // Also accept SKIP_RUSH_CHECKS_PARAMETER immediately after the command verb if (pnpmArgs[1] === RUSH_SKIP_CHECKS_PARAMETER) { pnpmArgs.splice(1, 1); return; } if (pnpmArgs.indexOf(RUSH_SKIP_CHECKS_PARAMETER) >= 0) { // We do not attempt to parse PNPM's complete CLI syntax, so we cannot be sure how to interpret // strings that appear outside of the specific patterns that this parser recognizes this.#terminal.writeErrorLine( PrintUtilities.wrapWords( `Error: The "${RUSH_SKIP_CHECKS_PARAMETER}" option must be the first parameter for the "rush-pnpm" command.` ) ); throw new AlreadyReportedError(); } this.#commandName = commandName; _addDefaultRecursiveFlagIfNeeded(commandName, pnpmArgs); // Warn about commands known not to work /* eslint-disable no-fallthrough */ switch (commandName) { // Blocked case 'import': { this.#terminal.writeErrorLine( PrintUtilities.wrapWords( `Error: The "pnpm ${commandName}" command is known to be incompatible with Rush's environment.` ) + '\n' ); this.#terminal.writeLine(Colorize.cyan(BYPASS_NOTICE)); throw new AlreadyReportedError(); } // Show warning for install commands case 'add': case 'install': /* synonym */ case 'i': case 'install-test': /* synonym */ case 'it': { this.#terminal.writeErrorLine( PrintUtilities.wrapWords( `Error: The "pnpm ${commandName}" command is incompatible with Rush's environment.` + ` Use the "rush install" or "rush update" commands instead.` ) + '\n' ); this.#terminal.writeLine(Colorize.cyan(BYPASS_NOTICE)); throw new AlreadyReportedError(); } // Show warning case 'link': /* synonym */ case 'ln': case 'remove': /* synonym */ case 'rm': case 'unlink': case 'update': /* synonym */ case 'up': { this.#terminal.writeWarningLine( PrintUtilities.wrapWords( `Warning: The "pnpm ${commandName}" command makes changes that may invalidate Rush's workspace state.` ) + '\n' ); this.#terminal.writeWarningLine( `==> Consider running "rush install" or "rush update" afterwards.\n` ); break; } // Know safe after validation case 'patch': { const semver: typeof import('semver') = await import('semver'); /** * If you were to accidentally attempt to use rush-pnpm patch with a pnpmVersion < 7.4.0, pnpm patch may fallback to the system patch command. * For instance, /usr/bin/patch which may just hangs forever * So, erroring out the command if the pnpm version is < 7.4.0 */ if (semver.lt(this.#rushConfiguration.packageManagerToolVersion, '7.4.0')) { this.#terminal.writeErrorLine( PrintUtilities.wrapWords( `Error: The "pnpm patch" command is added after pnpm@7.4.0.` + ` Please update "pnpmVersion" >= 7.4.0 in ${RushConstants.rushJsonFilename} file and run "rush update" to use this command.` ) + '\n' ); throw new AlreadyReportedError(); } break; } case 'patch-commit': { const pnpmOptionsJsonFilename: string = path.join( this.#rushConfiguration.commonRushConfigFolder, RushConstants.pnpmConfigFilename ); if (this.#rushConfiguration.rushConfigurationJson.pnpmOptions) { this.#terminal.writeErrorLine( PrintUtilities.wrapWords( `Error: The "pnpm patch-commit" command is incompatible with specifying "pnpmOptions" in ${RushConstants.rushJsonFilename} file.` + ` Please move the content of "pnpmOptions" in ${RushConstants.rushJsonFilename} file to ${pnpmOptionsJsonFilename}` ) + '\n' ); throw new AlreadyReportedError(); } break; } case 'patch-remove': { const semver: typeof import('semver') = await import('semver'); /** * The "patch-remove" command was introduced in pnpm version 8.5.0 */ if (semver.lt(this.#rushConfiguration.packageManagerToolVersion, '8.5.0')) { this.#terminal.writeErrorLine( PrintUtilities.wrapWords( `Error: The "pnpm patch-remove" command is added after pnpm@8.5.0.` + ` Please update "pnpmVersion" >= 8.5.0 in ${RushConstants.rushJsonFilename} file and run "rush update" to use this command.` ) + '\n' ); throw new AlreadyReportedError(); } break; } case 'approve-builds': { const semver: typeof import('semver') = await import('semver'); /** * The "approve-builds" command was introduced in PNPM version 10.1.0 * to approve packages for running build scripts when onlyBuiltDependencies is used. * In PNPM 11.0.0, it was updated to use allowBuilds in pnpm-workspace.yaml. */ if (semver.lt(this.#rushConfiguration.packageManagerToolVersion, '10.1.0')) { this.#terminal.writeErrorLine( PrintUtilities.wrapWords( `Error: The "pnpm approve-builds" command is added after pnpm@10.1.0.` + ` Please update "pnpmVersion" >= 10.1.0 in ${RushConstants.rushJsonFilename} file and run "rush update" to use this command.` ) + '\n' ); throw new AlreadyReportedError(); } const pnpmOptionsJsonFilename: string = path.join( this.#rushConfiguration.commonRushConfigFolder, RushConstants.pnpmConfigFilename ); if (this.#rushConfiguration.rushConfigurationJson.pnpmOptions) { this.#terminal.writeErrorLine( PrintUtilities.wrapWords( `Error: The "pnpm approve-builds" command is incompatible with specifying "pnpmOptions" in ${RushConstants.rushJsonFilename} file.` + ` Please move the content of "pnpmOptions" in ${RushConstants.rushJsonFilename} file to ${pnpmOptionsJsonFilename}` ) + '\n' ); throw new AlreadyReportedError(); } break; } // Known safe case 'audit': case 'exec': case 'list': /* synonym */ case 'ls': case 'outdated': case 'pack': case 'prune': case 'publish': case 'rebuild': /* synonym */ case 'rb': case 'root': case 'run': case 'start': case 'store': case 'test': /* synonym */ case 't': case 'why': { break; } // Unknown default: { this.#terminal.writeErrorLine( PrintUtilities.wrapWords( `Error: The "pnpm ${commandName}" command has not been tested with Rush's environment. It may be incompatible.` ) + '\n' ); this.#terminal.writeLine(Colorize.cyan(BYPASS_NOTICE)); } } /* eslint-enable no-fallthrough */ } } async #executeAsync(): Promise { const rushConfiguration: RushConfiguration = this.#rushConfiguration; const workspaceFolder: string = this.#subspace.getSubspaceTempFolderPath(); const pnpmEnvironmentMap: EnvironmentMap = new EnvironmentMap(process.env); pnpmEnvironmentMap.set('NPM_CONFIG_WORKSPACE_DIR', workspaceFolder); if (rushConfiguration.pnpmOptions.pnpmStorePath) { const pnpmConfigPrefix: string = parseInt(rushConfiguration.packageManagerToolVersion, 10) >= 12 ? 'PNPM_CONFIG_' : 'NPM_CONFIG_'; pnpmEnvironmentMap.set(`${pnpmConfigPrefix}STORE_DIR`, rushConfiguration.pnpmOptions.pnpmStorePath); pnpmEnvironmentMap.set(`${pnpmConfigPrefix}CACHE_DIR`, rushConfiguration.pnpmOptions.pnpmStorePath); pnpmEnvironmentMap.set(`${pnpmConfigPrefix}STATE_DIR`, rushConfiguration.pnpmOptions.pnpmStorePath); } if (rushConfiguration.pnpmOptions.environmentVariables) { for (const [envKey, { value: envValue, override }] of Object.entries( rushConfiguration.pnpmOptions.environmentVariables )) { if (override) { pnpmEnvironmentMap.set(envKey, envValue); } else { if (undefined === pnpmEnvironmentMap.get(envKey)) { pnpmEnvironmentMap.set(envKey, envValue); } } } } // Provide any credentials that "rush install" moved out of the generated .npmrc file. // See the "provideNpmrcCredentialsViaEnvironment" experiment. if (InstallHelpers.shouldProvideNpmrcCredentialsViaEnvironment(rushConfiguration)) { const npmrcEnvironmentVariables: Record | undefined = getNpmrcEnvironmentVariables({ npmrcFolder: workspaceFolder, supportEnvVarFallbackSyntax: rushConfiguration.isPnpm }); for (const [envKey, envValue] of Object.entries(npmrcEnvironmentVariables ?? {})) { pnpmEnvironmentMap.set(envKey, envValue); } } let onStdoutStreamChunk: ((chunk: string) => string | void) | undefined; switch (this.#commandName) { case 'patch': { // Replace `pnpm patch-commit` with `rush-pnpm patch-commit` when running // `pnpm patch` to avoid the `pnpm patch` command being suggested in the output onStdoutStreamChunk = (stdoutChunk: string) => { return stdoutChunk.replace( /pnpm patch-commit/g, `rush-pnpm --subspace ${this.#subspace.subspaceName} patch-commit` ); }; break; } } try { const { exitCode } = await Utilities.executeCommandAsync({ command: rushConfiguration.packageManagerToolFilename, args: this.#pnpmArgs, workingDirectory: process.cwd(), environment: pnpmEnvironmentMap.toObject(), keepEnvironment: true, useShell: !InstallHelpers.shouldProvideNpmrcCredentialsViaEnvironment(rushConfiguration), onStdoutStreamChunk, captureExitCodeAndSignal: true }); if (typeof exitCode === 'number') { process.exitCode = exitCode; } else { // If the exit code is not a number, the process was terminated by a signal process.exitCode = 1; } } catch (e) { this.#terminal.writeDebugLine(`Error: ${e}`); } } async #postExecuteAsync(): Promise { const commandName: string | undefined = this.#commandName; if (!commandName) { return; } const subspaceTempFolder: string = this.#subspace.getSubspaceTempFolderPath(); switch (commandName) { case 'patch-remove': case 'patch-commit': { // why need to throw error when pnpm-config.json not exists? // 1. pnpm-config.json is required for `rush-pnpm patch-commit`. Rush writes the patched dependency to the pnpm-config.json when finishes. // 2. we can not fallback to use Monorepo config folder (common/config/rush) due to that this command is intended to apply to input subspace only. // It will produce unexpected behavior if we use the fallback. if (this.#subspace.getPnpmOptions() === undefined) { const subspaceConfigFolder: string = this.#subspace.getSubspaceConfigFolderPath(); this.#terminal.writeErrorLine( `The "rush-pnpm patch-commit" command cannot proceed without a pnpm-config.json file.` + ` Create one in this folder: ${subspaceConfigFolder}` ); break; } const pnpmOptions: PnpmOptionsConfiguration | undefined = this.#subspace.getPnpmOptions(); const pnpmVersion: string = this.#rushConfiguration.packageManagerToolVersion; const semver: typeof import('semver') = await import('semver'); let newGlobalPatchedDependencies: Record | undefined; if (semver.gte(pnpmVersion, '11.0.0')) { // PNPM 11+ stores patchedDependencies in pnpm-workspace.yaml instead of the package.json "pnpm" field const workspaceFile: PnpmWorkspaceFile | undefined = await PnpmWorkspaceFile.tryLoadAsync( `${subspaceTempFolder}/${RushConstants.pnpmWorkspaceFileName}` ); newGlobalPatchedDependencies = workspaceFile?.patchedDependencies; } else { // PNPM 10.x and earlier store patchedDependencies in the package.json "pnpm" field // Example: "C:\MyRepo\common\temp\package.json" const commonPackageJsonFilename: string = `${subspaceTempFolder}/${FileConstants.PackageJson}`; const commonPackageJson: JsonObject = JsonFile.load(commonPackageJsonFilename); newGlobalPatchedDependencies = commonPackageJson?.pnpm?.patchedDependencies; } const currentGlobalPatchedDependencies: Record | undefined = pnpmOptions?.globalPatchedDependencies; if (!Objects.areDeepEqual(currentGlobalPatchedDependencies, newGlobalPatchedDependencies)) { const commonTempPnpmPatchesFolder: string = `${subspaceTempFolder}/${RushConstants.pnpmPatchesFolderName}`; const rushPnpmPatchesFolder: string = this.#subspace.getSubspacePnpmPatchesFolderPath(); // Copy (or delete) common\temp\subspace\patches\ --> common\config\pnpm-patches\ OR common\config\rush\pnpm-patches\ if (FileSystem.exists(commonTempPnpmPatchesFolder)) { FileSystem.ensureEmptyFolder(rushPnpmPatchesFolder); // eslint-disable-next-line no-console console.log(`Copying ${commonTempPnpmPatchesFolder}`); // eslint-disable-next-line no-console console.log(` --> ${rushPnpmPatchesFolder}`); FileSystem.copyFiles({ sourcePath: commonTempPnpmPatchesFolder, destinationPath: rushPnpmPatchesFolder }); } else { if (FileSystem.exists(rushPnpmPatchesFolder)) { // eslint-disable-next-line no-console console.log(`Deleting ${rushPnpmPatchesFolder}`); FileSystem.deleteFolder(rushPnpmPatchesFolder); } } // Update patchedDependencies to pnpm configuration file pnpmOptions?.updateGlobalPatchedDependencies(newGlobalPatchedDependencies); // Rerun installation to update await this.#doRushUpdateAsync(); this.#terminal.writeWarningLine( `Rush refreshed the ${RushConstants.pnpmConfigFilename}, shrinkwrap file and patch files under the ` + `"${commonTempPnpmPatchesFolder}" folder.\n` + ' Please commit this change to Git.' ); } break; } case 'approve-builds': { if (this.#subspace.getPnpmOptions() === undefined) { const subspaceConfigFolder: string = this.#subspace.getSubspaceConfigFolderPath(); this.#terminal.writeErrorLine( `The "rush-pnpm approve-builds" command cannot proceed without a pnpm-config.json file.` + ` Create one in this folder: ${subspaceConfigFolder}` ); break; } const pnpmOptions: PnpmOptionsConfiguration | undefined = this.#subspace.getPnpmOptions(); const pnpmVersion: string = this.#rushConfiguration.packageManagerToolVersion; const semver: typeof import('semver') = await import('semver'); if (semver.gte(pnpmVersion, '11.0.0')) { // PNPM 11+ uses allowBuilds in pnpm-workspace.yaml instead of onlyBuiltDependencies in package.json const workspaceFile: PnpmWorkspaceFile | undefined = await PnpmWorkspaceFile.tryLoadAsync( `${subspaceTempFolder}/${RushConstants.pnpmWorkspaceFileName}` ); const newGlobalAllowBuilds: Record | undefined = workspaceFile?.allowBuilds; const currentGlobalAllowBuilds: Record | undefined = pnpmOptions?.globalAllowBuilds; if (!Objects.areDeepEqual(currentGlobalAllowBuilds, newGlobalAllowBuilds)) { // Update allowBuilds to pnpm configuration file pnpmOptions?.updateGlobalAllowBuilds(newGlobalAllowBuilds); // Rerun installation to update await this.#doRushUpdateAsync(); this.#terminal.writeWarningLine( `Rush refreshed the ${RushConstants.pnpmConfigFilename} and shrinkwrap file.\n` + ' Please commit this change to Git.' ); } } else { // PNPM 10.x uses onlyBuiltDependencies in package.json // Example: "C:\MyRepo\common\temp\package.json" const commonPackageJsonFilename: string = `${subspaceTempFolder}/${FileConstants.PackageJson}`; const commonPackageJson: JsonObject = await JsonFile.loadAsync(commonPackageJsonFilename); const newGlobalOnlyBuiltDependencies: string[] | undefined = commonPackageJson?.pnpm?.onlyBuiltDependencies; const currentGlobalOnlyBuiltDependencies: string[] | undefined = pnpmOptions?.globalOnlyBuiltDependencies; if (!Objects.areDeepEqual(currentGlobalOnlyBuiltDependencies, newGlobalOnlyBuiltDependencies)) { // Update onlyBuiltDependencies to pnpm configuration file await pnpmOptions?.updateGlobalOnlyBuiltDependenciesAsync(newGlobalOnlyBuiltDependencies); // Rerun installation to update await this.#doRushUpdateAsync(); this.#terminal.writeWarningLine( `Rush refreshed the ${RushConstants.pnpmConfigFilename} and shrinkwrap file.\n` + ' Please commit this change to Git.' ); } } break; } case 'update': case 'up': { // When "pnpm up" / "pnpm update" runs, PNPM writes any updated catalog versions to the // generated "catalogs" section of common/temp//pnpm-workspace.yaml. That file is // regenerated on every install, so the updated versions must be synced back to the // "globalCatalogs" field of pnpm-config.json for the change to be persisted. const { pnpmOptions, pnpmConfigFilePath } = getEffectivePnpmOptions( this.#subspace, this.#rushConfiguration ); if (pnpmOptions.jsonFilename === undefined) { // The legacy "pnpmOptions" field in rush.json does not support catalogs break; } const workspaceYamlFilename: string = `${subspaceTempFolder}/pnpm-workspace.yaml`; const yamlModule: typeof import('js-yaml') = await import('js-yaml'); const workspaceYamlContent: string = await FileSystem.readFileAsync(workspaceYamlFilename); const workspaceYaml: IPnpmWorkspaceYamlCatalogs = (yamlModule.load(workspaceYamlContent) ?? {}) as IPnpmWorkspaceYamlCatalogs; const currentGlobalCatalogs: PnpmCatalogs | undefined = pnpmOptions.globalCatalogs; let newGlobalCatalogs: PnpmCatalogs | undefined = getCatalogsFromWorkspaceYaml(workspaceYaml); // This subspace's workspace can't show which entries other subspaces sharing the file use, // so never remove any const subspacesSharingPnpmConfig: Subspace[] = getOtherSubspacesSharingPnpmConfig( this.#subspace, this.#rushConfiguration ); if (subspacesSharingPnpmConfig.length > 0) { newGlobalCatalogs = mergePnpmCatalogs(currentGlobalCatalogs, newGlobalCatalogs); } if (!Objects.areDeepEqual(currentGlobalCatalogs, newGlobalCatalogs)) { await pnpmOptions.updateGlobalCatalogsAsync(newGlobalCatalogs); await this.#doRushUpdateAsync(); this.#terminal.writeWarningLine( `Rush refreshed the ${RushConstants.pnpmConfigFilename} and shrinkwrap file.\n` + ' Please commit this change to Git.' ); if (subspacesSharingPnpmConfig.length > 0) { // Their lockfiles still have the old catalogs, so their next "rush install" would fail const updateCommands: string[] = subspacesSharingPnpmConfig.map( (subspace: Subspace) => ` rush update --subspace ${subspace.subspaceName}` ); this.#terminal.writeWarningLine( `The catalogs were updated in ${pnpmConfigFilePath}, which is also used by other subspaces.\n` + ' Run these commands to update their shrinkwrap files, then commit those changes to Git:\n' + updateCommands.join('\n') ); } } break; } } } async #doRushUpdateAsync(): Promise { if (this.#doRushUpdateAsyncOverride) { await this.#doRushUpdateAsyncOverride(); return; } this.#terminal.writeLine(); this.#terminal.writeLine(Colorize.green('Running "rush update"')); this.#terminal.writeLine(); const rushGlobalFolder: RushGlobalFolder = new RushGlobalFolder(); const purgeManager: PurgeManager = new PurgeManager(this.#rushConfiguration, rushGlobalFolder); const installManagerOptions: IInstallManagerOptions = { debug: this.#debugEnabled, allowShrinkwrapUpdates: true, bypassPolicy: false, noLink: false, fullUpgrade: false, recheckShrinkwrap: true, networkConcurrency: undefined, offline: false, collectLogFile: false, variant: process.env[EnvironmentVariableNames.RUSH_VARIANT], // For `rush-pnpm`, only use the env var maxInstallAttempts: RushConstants.defaultMaxInstallAttempts, pnpmFilterArgumentValues: [], selectedProjects: new Set(this.#rushConfiguration.projects), checkOnly: false, subspace: this.#subspace, terminal: this.#terminal }; const installManagerFactoryModule: typeof import('../logic/InstallManagerFactory') = await import( /* webpackChunkName: 'InstallManagerFactory' */ '../logic/InstallManagerFactory' ); const installManager: BaseInstallManager = await installManagerFactoryModule.InstallManagerFactory.getInstallManagerAsync( this.#rushConfiguration, rushGlobalFolder, purgeManager, installManagerOptions ); try { await installManager.doInstallAsync(); } finally { await purgeManager.startDeleteAllAsync(); } } } interface IPnpmWorkspaceYamlCatalogs { catalog?: Record; catalogs?: PnpmCatalogs; } /** * Rush writes "catalogs", but PNPM may add default catalog entries to the top-level "catalog" field. */ function getCatalogsFromWorkspaceYaml(workspaceYaml: IPnpmWorkspaceYamlCatalogs): PnpmCatalogs | undefined { const { catalog, catalogs } = workspaceYaml; if (!catalog) { return catalogs; } return { ...catalogs, default: { ...catalogs?.default, ...catalog } }; }