"use strict";
exports.id = "RushInstallManager";
exports.ids = ["RushInstallManager"];
exports.modules = {

/***/ 512177
/*!*********************************************************!*\
  !*** ./lib-intermediate-esm/logic/TempProjectHelper.js ***!
  \*********************************************************/
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   TempProjectHelper: () => (/* binding */ TempProjectHelper)
/* harmony export */ });
/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! node:path */ 176760);
/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(node_path__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var tar__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! tar */ 126819);
/* harmony import */ var tar__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(tar__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @rushstack/node-core-library */ 277275);
/* harmony import */ var _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _RushConstants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./RushConstants */ 370253);
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.




// The PosixModeBits are intended to be used with bitwise operations.
/* eslint-disable no-bitwise */
class TempProjectHelper {
    constructor(rushConfiguration, subspace) {
        this._rushConfiguration = rushConfiguration;
        this._subspace = subspace;
    }
    /**
     * Deletes the existing tarball and creates a tarball for the given rush project
     */
    createTempProjectTarball(rushProject) {
        _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_2__.FileSystem.ensureFolder(node_path__WEBPACK_IMPORTED_MODULE_0__.resolve(this._subspace.getSubspaceTempFolderPath(), 'projects'));
        const tarballFile = this.getTarballFilePath(rushProject);
        const tempProjectFolder = this.getTempProjectFolder(rushProject);
        _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_2__.FileSystem.deleteFile(tarballFile);
        // NPM expects the root of the tarball to have a directory called 'package'
        const npmPackageFolder = 'package';
        const tarOptions = {
            gzip: true,
            file: tarballFile,
            cwd: tempProjectFolder,
            portable: true,
            noMtime: true,
            noPax: true,
            sync: true,
            prefix: npmPackageFolder,
            filter: (tarPath, stat) => {
                if (!this._rushConfiguration.experimentsConfiguration.configuration.noChmodFieldInTarHeaderNormalization) {
                    stat.mode =
                        (stat.mode & ~0x1ff) | _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_2__.PosixModeBits.AllRead | _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_2__.PosixModeBits.UserWrite | _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_2__.PosixModeBits.AllExecute;
                }
                return true;
            }
        };
        // create the new tarball
        tar__WEBPACK_IMPORTED_MODULE_1__.create(tarOptions, [_rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_2__.FileConstants.PackageJson]);
    }
    /**
     * Gets the path to the tarball
     * Example: "C:\MyRepo\common\temp\projects\my-project-2.tgz"
     */
    getTarballFilePath(project) {
        return node_path__WEBPACK_IMPORTED_MODULE_0__.join(this._subspace.getSubspaceTempFolderPath(), _RushConstants__WEBPACK_IMPORTED_MODULE_3__.RushConstants.rushTempProjectsFolderName, `${project.unscopedTempProjectName}.tgz`);
    }
    getTempProjectFolder(rushProject) {
        const unscopedTempProjectName = rushProject.unscopedTempProjectName;
        return node_path__WEBPACK_IMPORTED_MODULE_0__.join(this._subspace.getSubspaceTempFolderPath(), _RushConstants__WEBPACK_IMPORTED_MODULE_3__.RushConstants.rushTempProjectsFolderName, unscopedTempProjectName);
    }
}
//# sourceMappingURL=TempProjectHelper.js.map

/***/ },

/***/ 229605
/*!*************************************************************************!*\
  !*** ./lib-intermediate-esm/logic/installManager/RushInstallManager.js ***!
  \*************************************************************************/
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   RushInstallManager: () => (/* binding */ RushInstallManager)
/* harmony export */ });
/* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! node:fs */ 973024);
/* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(node_fs__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! node:path */ 176760);
/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(node_path__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! semver */ 338064);
/* harmony import */ var semver__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(semver__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var ssri__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ssri */ 483887);
/* harmony import */ var ssri__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(ssri__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @rushstack/node-core-library */ 277275);
/* harmony import */ var _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _rushstack_terminal__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @rushstack/terminal */ 367587);
/* harmony import */ var _rushstack_terminal__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_rushstack_terminal__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _base_BaseInstallManager__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../base/BaseInstallManager */ 187991);
/* harmony import */ var _RushConstants__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../RushConstants */ 370253);
/* harmony import */ var _utilities_Stopwatch__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../utilities/Stopwatch */ 736071);
/* harmony import */ var _utilities_Utilities__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../utilities/Utilities */ 591564);
/* harmony import */ var _api_PackageJsonEditor__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../api/PackageJsonEditor */ 519511);
/* harmony import */ var _DependencySpecifier__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../DependencySpecifier */ 508969);
/* harmony import */ var _InstallHelpers__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./InstallHelpers */ 766517);
/* harmony import */ var _TempProjectHelper__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../TempProjectHelper */ 512177);
/* harmony import */ var _LinkManagerFactory__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../LinkManagerFactory */ 766691);
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.















/**
 * This class implements common logic between "rush install" and "rush update".
 */
class RushInstallManager extends _base_BaseInstallManager__WEBPACK_IMPORTED_MODULE_6__.BaseInstallManager {
    constructor(rushConfiguration, rushGlobalFolder, purgeManager, options) {
        super(rushConfiguration, rushGlobalFolder, purgeManager, options);
        this._tempProjectHelper = new _TempProjectHelper__WEBPACK_IMPORTED_MODULE_13__.TempProjectHelper(this.rushConfiguration, rushConfiguration.defaultSubspace);
    }
    /**
     * Regenerates the common/package.json and all temp_modules projects.
     * If shrinkwrapFile is provided, this function also validates whether it contains
     * everything we need to install and returns true if so; in all other cases,
     * the return value is false.
     *
     * @override
     */
    async prepareCommonTempAsync(subspace, shrinkwrapFile) {
        const stopwatch = _utilities_Stopwatch__WEBPACK_IMPORTED_MODULE_8__.Stopwatch.start();
        const { fullUpgrade, variant } = this.options;
        // Example: "C:\MyRepo\common\temp\projects"
        const tempProjectsFolder = node_path__WEBPACK_IMPORTED_MODULE_1__.join(this.rushConfiguration.commonTempFolder, _RushConstants__WEBPACK_IMPORTED_MODULE_7__.RushConstants.rushTempProjectsFolderName);
        // eslint-disable-next-line no-console
        console.log('\n' + _rushstack_terminal__WEBPACK_IMPORTED_MODULE_5__.Colorize.bold('Updating temp projects in ' + tempProjectsFolder));
        _utilities_Utilities__WEBPACK_IMPORTED_MODULE_9__.Utilities.createFolderWithRetry(tempProjectsFolder);
        const shrinkwrapWarnings = [];
        // We will start with the assumption that it's valid, and then set it to false if
        // any of the checks fail
        let shrinkwrapIsUpToDate = true;
        if (!shrinkwrapFile) {
            shrinkwrapIsUpToDate = false;
        }
        else if (shrinkwrapFile.isWorkspaceCompatible && !fullUpgrade) {
            // eslint-disable-next-line no-console
            console.log();
            // eslint-disable-next-line no-console
            console.log(_rushstack_terminal__WEBPACK_IMPORTED_MODULE_5__.Colorize.red('The shrinkwrap file had previously been updated to support workspaces. Run "rush update --full" ' +
                'to update the shrinkwrap file.'));
            throw new _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__.AlreadyReportedError();
        }
        // dependency name --> version specifier
        const allExplicitPreferredVersions = this.rushConfiguration.defaultSubspace
            .getCommonVersions(variant)
            .getAllPreferredVersions();
        if (shrinkwrapFile) {
            // Check any (explicitly) preferred dependencies first
            allExplicitPreferredVersions.forEach((version, dependency) => {
                const dependencySpecifier = _DependencySpecifier__WEBPACK_IMPORTED_MODULE_11__.DependencySpecifier.parseWithCache(dependency, version);
                if (!shrinkwrapFile.hasCompatibleTopLevelDependency(dependencySpecifier)) {
                    shrinkwrapWarnings.push(`Missing dependency "${dependency}" (${version}) required by the preferred versions from ` +
                        _RushConstants__WEBPACK_IMPORTED_MODULE_7__.RushConstants.commonVersionsFilename);
                    shrinkwrapIsUpToDate = false;
                }
            });
            if (this._findMissingTempProjects(shrinkwrapFile)) {
                // If any Rush project's tarball is missing from the shrinkwrap file, then we need to update
                // the shrinkwrap file.
                shrinkwrapIsUpToDate = false;
            }
            // If there are orphaned projects, we need to update
            const orphanedProjects = shrinkwrapFile.findOrphanedProjects(this.rushConfiguration, this.rushConfiguration.defaultSubspace);
            if (orphanedProjects.length > 0) {
                for (const orphanedProject of orphanedProjects) {
                    shrinkwrapWarnings.push(`Your ${this.rushConfiguration.shrinkwrapFilePhrase} references "${orphanedProject}" ` +
                        `which was not found in ${_RushConstants__WEBPACK_IMPORTED_MODULE_7__.RushConstants.rushJsonFilename}`);
                }
                shrinkwrapIsUpToDate = false;
            }
        }
        // dependency name --> version specifier
        const commonDependencies = new Map([
            ...allExplicitPreferredVersions,
            ...this.rushConfiguration.getImplicitlyPreferredVersions(subspace, variant)
        ]);
        // To make the common/package.json file more readable, sort alphabetically
        // according to rushProject.tempProjectName instead of packageName.
        const sortedRushProjects = this.rushConfiguration.projects.slice(0);
        _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__.Sort.sortBy(sortedRushProjects, (x) => x.tempProjectName);
        for (const rushProject of sortedRushProjects) {
            const packageJson = rushProject.packageJsonEditor;
            // Example: "C:\MyRepo\common\temp\projects\my-project-2.tgz"
            const tarballFile = this._tempProjectHelper.getTarballFilePath(rushProject);
            // Example: dependencies["@rush-temp/my-project-2"] = "file:./projects/my-project-2.tgz"
            commonDependencies.set(rushProject.tempProjectName, `file:./${_RushConstants__WEBPACK_IMPORTED_MODULE_7__.RushConstants.rushTempProjectsFolderName}/${rushProject.unscopedTempProjectName}.tgz`);
            const tempPackageJson = {
                name: rushProject.tempProjectName,
                version: '0.0.0',
                private: true,
                dependencies: {}
            };
            // Collect pairs of (packageName, packageVersion) to be added as dependencies of the @rush-temp package.json
            const tempDependencies = new Map();
            // These can be regular, optional, or peer dependencies (but NOT dev dependencies).
            // (A given packageName will never appear more than once in this list.)
            for (const dependency of packageJson.dependencyList) {
                if (this.options.fullUpgrade && this._revertWorkspaceNotation(dependency)) {
                    shrinkwrapIsUpToDate = false;
                }
                // If there are any optional dependencies, copy directly into the optionalDependencies field.
                if (dependency.dependencyType === _api_PackageJsonEditor__WEBPACK_IMPORTED_MODULE_10__.DependencyType.Optional) {
                    if (!tempPackageJson.optionalDependencies) {
                        tempPackageJson.optionalDependencies = {};
                    }
                    tempPackageJson.optionalDependencies[dependency.name] = dependency.version;
                }
                else {
                    tempDependencies.set(dependency.name, dependency.version);
                }
            }
            for (const dependency of packageJson.devDependencyList) {
                if (this.options.fullUpgrade && this._revertWorkspaceNotation(dependency)) {
                    shrinkwrapIsUpToDate = false;
                }
                // If there are devDependencies, we need to merge them with the regular dependencies.  If the same
                // library appears in both places, then the dev dependency wins (because presumably it's saying what you
                // want right now for development, not the range that you support for consumers).
                tempDependencies.set(dependency.name, dependency.version);
            }
            _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__.Sort.sortMapKeys(tempDependencies);
            for (const [packageName, packageVersion] of tempDependencies.entries()) {
                const dependencySpecifier = _DependencySpecifier__WEBPACK_IMPORTED_MODULE_11__.DependencySpecifier.parseWithCache(packageName, packageVersion);
                // Is there a locally built Rush project that could satisfy this dependency?
                // If so, then we will symlink to the project folder rather than to common/temp/node_modules.
                // In this case, we don't want "npm install" to process this package, but we do need
                // to record this decision for linking later, so we add it to a special 'rushDependencies' field.
                const localProject = this.rushConfiguration.getProjectByName(packageName);
                if (localProject) {
                    // Don't locally link if it's listed in the decoupledLocalDependencies
                    if (!rushProject.decoupledLocalDependencies.has(packageName)) {
                        // Also, don't locally link if the SemVer doesn't match
                        const localProjectVersion = localProject.packageJsonEditor.version;
                        if (semver__WEBPACK_IMPORTED_MODULE_2__.satisfies(localProjectVersion, packageVersion)) {
                            // We will locally link this package, so instead add it to our special "rushDependencies"
                            // field in the package.json file.
                            if (!tempPackageJson.rushDependencies) {
                                tempPackageJson.rushDependencies = {};
                            }
                            tempPackageJson.rushDependencies[packageName] = packageVersion;
                            continue;
                        }
                    }
                }
                // We will NOT locally link this package; add it as a regular dependency.
                tempPackageJson.dependencies[packageName] = packageVersion;
                if (shrinkwrapFile &&
                    !shrinkwrapFile.tryEnsureCompatibleDependency(dependencySpecifier, rushProject.tempProjectName)) {
                    shrinkwrapWarnings.push(`Missing dependency "${packageName}" (${packageVersion}) required by "${rushProject.packageName}"`);
                    shrinkwrapIsUpToDate = false;
                }
            }
            if (this.rushConfiguration.packageManager === 'yarn') {
                // This feature is only implemented by the Yarn package manager
                if (packageJson.resolutionsList.length > 0) {
                    tempPackageJson.resolutions = packageJson.saveToObject().resolutions;
                }
            }
            // Example: "C:\MyRepo\common\temp\projects\my-project-2"
            const tempProjectFolder = this._tempProjectHelper.getTempProjectFolder(rushProject);
            // Example: "C:\MyRepo\common\temp\projects\my-project-2\package.json"
            const tempPackageJsonFilename = node_path__WEBPACK_IMPORTED_MODULE_1__.join(tempProjectFolder, _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__.FileConstants.PackageJson);
            // we only want to overwrite the package if the existing tarball's package.json is different from tempPackageJson
            let shouldOverwrite = true;
            try {
                // if the tarball and the temp file still exist, then compare the contents
                if (_rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__.FileSystem.exists(tarballFile) && _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__.FileSystem.exists(tempPackageJsonFilename)) {
                    // compare the extracted package.json with the one we are about to write
                    const oldBuffer = _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__.FileSystem.readFileToBuffer(tempPackageJsonFilename);
                    const newBuffer = Buffer.from(_rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__.JsonFile.stringify(tempPackageJson));
                    if (Buffer.compare(oldBuffer, newBuffer) === 0) {
                        shouldOverwrite = false;
                    }
                }
            }
            catch (error) {
                // ignore the error, we will go ahead and create a new tarball
            }
            if (shouldOverwrite) {
                try {
                    // ensure the folder we are about to zip exists
                    _utilities_Utilities__WEBPACK_IMPORTED_MODULE_9__.Utilities.createFolderWithRetry(tempProjectFolder);
                    // remove the old tarball & old temp package json, this is for any cases where new tarball creation
                    // fails, and the shouldOverwrite logic is messed up because the my-project-2\package.json
                    // exists and is updated, but the tarball is not accurate
                    _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__.FileSystem.deleteFile(tarballFile);
                    _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__.FileSystem.deleteFile(tempPackageJsonFilename);
                    // write the expected package.json file into the zip staging folder
                    _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__.JsonFile.save(tempPackageJson, tempPackageJsonFilename);
                    // Delete the existing tarball and create a new one
                    this._tempProjectHelper.createTempProjectTarball(rushProject);
                    // eslint-disable-next-line no-console
                    console.log(`Updating ${tarballFile}`);
                }
                catch (error) {
                    // eslint-disable-next-line no-console
                    console.log(_rushstack_terminal__WEBPACK_IMPORTED_MODULE_5__.Colorize.yellow(error));
                    // delete everything in case of any error
                    _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__.FileSystem.deleteFile(tarballFile);
                    _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__.FileSystem.deleteFile(tempPackageJsonFilename);
                }
            }
            // When using frozen shrinkwrap, we need to validate that the tarball integrities are up-to-date
            // with the shrinkwrap file, since these will cause install to fail.
            if (shrinkwrapFile &&
                this.rushConfiguration.isPnpm &&
                this.rushConfiguration.experimentsConfiguration.configuration.usePnpmFrozenLockfileForRushInstall) {
                const pnpmShrinkwrapFile = shrinkwrapFile;
                const tarballIntegrityValid = await this._validateRushProjectTarballIntegrityAsync(pnpmShrinkwrapFile, rushProject);
                if (!tarballIntegrityValid) {
                    shrinkwrapIsUpToDate = false;
                    shrinkwrapWarnings.push(`Invalid or missing tarball integrity hash in shrinkwrap for "${rushProject.packageName}"`);
                }
            }
            // Save the package.json if we modified the version references and warn that the package.json was modified
            const modified = await packageJson.saveIfModifiedAsync();
            if (modified) {
                // eslint-disable-next-line no-console
                console.log(_rushstack_terminal__WEBPACK_IMPORTED_MODULE_5__.Colorize.yellow(`"${rushProject.packageName}" depends on one or more local packages which used "workspace:" ` +
                    'notation. The package.json has been modified and must be committed to source control.'));
            }
        }
        // Remove the workspace file if it exists
        if (this.rushConfiguration.isPnpm) {
            const workspaceFilePath = node_path__WEBPACK_IMPORTED_MODULE_1__.join(this.rushConfiguration.commonTempFolder, 'pnpm-workspace.yaml');
            try {
                await _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__.FileSystem.deleteFileAsync(workspaceFilePath);
            }
            catch (e) {
                if (!_rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__.FileSystem.isNotExistError(e)) {
                    throw e;
                }
            }
        }
        // Write the common package.json
        _InstallHelpers__WEBPACK_IMPORTED_MODULE_12__.InstallHelpers.generateCommonPackageJson(this.rushConfiguration, this.rushConfiguration.defaultSubspace, commonDependencies, this._terminal);
        stopwatch.stop();
        // eslint-disable-next-line no-console
        console.log(`Finished creating temporary modules (${stopwatch.toString()})`);
        return { shrinkwrapIsUpToDate, shrinkwrapWarnings };
    }
    _revertWorkspaceNotation(dependency) {
        const specifier = _DependencySpecifier__WEBPACK_IMPORTED_MODULE_11__.DependencySpecifier.parseWithCache(dependency.name, dependency.version);
        if (specifier.specifierType !== _DependencySpecifier__WEBPACK_IMPORTED_MODULE_11__.DependencySpecifierType.Workspace) {
            return false;
        }
        // Replace workspace notation with the supplied version range
        if (specifier.versionSpecifier === '*') {
            // When converting to workspaces, exact package versions are replaced with a '*', so undo this
            const localProject = this.rushConfiguration.getProjectByName(specifier.packageName);
            if (!localProject) {
                throw new _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__.InternalError(`Could not find local project with package name ${specifier.packageName}`);
            }
            dependency.setVersion(localProject.packageJson.version);
        }
        else {
            dependency.setVersion(specifier.versionSpecifier);
        }
        return true;
    }
    async _validateRushProjectTarballIntegrityAsync(shrinkwrapFile, rushProject) {
        if (shrinkwrapFile) {
            const tempProjectDependencyKey = shrinkwrapFile.getTempProjectDependencyKey(rushProject.tempProjectName);
            if (!tempProjectDependencyKey) {
                return false;
            }
            const parentShrinkwrapEntry = shrinkwrapFile.getShrinkwrapEntryFromTempProjectDependencyKey(tempProjectDependencyKey);
            const newIntegrity = (await ssri__WEBPACK_IMPORTED_MODULE_3__.fromStream(node_fs__WEBPACK_IMPORTED_MODULE_0__.createReadStream(this._tempProjectHelper.getTarballFilePath(rushProject)))).toString();
            if (!parentShrinkwrapEntry.resolution || parentShrinkwrapEntry.resolution.integrity !== newIntegrity) {
                return false;
            }
        }
        return true;
    }
    /**
     * Check whether or not the install is already valid, and therefore can be skipped.
     *
     * @override
     */
    async canSkipInstallAsync(lastModifiedDate, subspace, variant) {
        if (!(await super.canSkipInstallAsync(lastModifiedDate, subspace, variant))) {
            return false;
        }
        const potentiallyChangedFiles = [];
        // Also consider timestamps for all the temp tarballs. (createTempModulesAndCheckShrinkwrap() will
        // carefully preserve these timestamps unless something has changed.)
        // Example: "C:\MyRepo\common\temp\projects\my-project-2.tgz"
        potentiallyChangedFiles.push(...this.rushConfiguration.projects.map((x) => {
            return this._tempProjectHelper.getTarballFilePath(x);
        }));
        return _utilities_Utilities__WEBPACK_IMPORTED_MODULE_9__.Utilities.isFileTimestampCurrentAsync(lastModifiedDate, potentiallyChangedFiles);
    }
    /**
     * Runs "npm/pnpm/yarn install" in the "common/temp" folder.
     *
     * @override
     */
    async installAsync(cleanInstall, subspace) {
        // Since we are actually running npm/pnpm/yarn install, recreate all the temp project tarballs.
        // This ensures that any existing tarballs with older header bits will be regenerated.
        // It is safe to assume that temp project pacakge.jsons already exist.
        for (const rushProject of this.rushConfiguration.projects) {
            this._tempProjectHelper.createTempProjectTarball(rushProject);
        }
        // NOTE: The PNPM store is supposed to be transactionally safe, so we don't delete it automatically.
        // The user must request that via the command line.
        if (cleanInstall) {
            if (this.rushConfiguration.packageManager === 'npm') {
                // eslint-disable-next-line no-console
                console.log(`Deleting the "npm-cache" folder`);
                // This is faster and more thorough than "npm cache clean"
                this.installRecycler.moveFolder(this.rushConfiguration.npmCacheFolder);
                // eslint-disable-next-line no-console
                console.log(`Deleting the "npm-tmp" folder`);
                this.installRecycler.moveFolder(this.rushConfiguration.npmTmpFolder);
            }
        }
        // Example: "C:\MyRepo\common\temp\npm-local\node_modules\.bin\npm"
        const packageManagerFilename = this.rushConfiguration.packageManagerToolFilename;
        const packageManagerEnv = _InstallHelpers__WEBPACK_IMPORTED_MODULE_12__.InstallHelpers.getPackageManagerEnvironment(this.rushConfiguration, this.options);
        const commonNodeModulesFolder = node_path__WEBPACK_IMPORTED_MODULE_1__.join(this.rushConfiguration.commonTempFolder, _RushConstants__WEBPACK_IMPORTED_MODULE_7__.RushConstants.nodeModulesFolderName);
        // Is there an existing "node_modules" folder to consider?
        if (_rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__.FileSystem.exists(commonNodeModulesFolder)) {
            // Should we delete the entire "node_modules" folder?
            if (cleanInstall) {
                // YES: Delete "node_modules"
                // Explain to the user why we are hosing their node_modules folder
                // eslint-disable-next-line no-console
                console.log('Deleting files from ' + commonNodeModulesFolder);
                this.installRecycler.moveFolder(commonNodeModulesFolder);
                _utilities_Utilities__WEBPACK_IMPORTED_MODULE_9__.Utilities.createFolderWithRetry(commonNodeModulesFolder);
            }
            else {
                // NO: Prepare to do an incremental install in the "node_modules" folder
                // note: it is not necessary to run "prune" with pnpm
                if (this.rushConfiguration.packageManager === 'npm') {
                    // eslint-disable-next-line no-console
                    console.log(`Running "${this.rushConfiguration.packageManager} prune"` +
                        ` in ${this.rushConfiguration.commonTempFolder}`);
                    const args = ['prune'];
                    this.pushConfigurationArgs(args, this.options, subspace);
                    await _utilities_Utilities__WEBPACK_IMPORTED_MODULE_9__.Utilities.executeCommandWithRetryAsync({
                        command: packageManagerFilename,
                        args,
                        workingDirectory: this.rushConfiguration.commonTempFolder,
                        environment: packageManagerEnv
                    }, this.options.maxInstallAttempts);
                    // Delete the (installed image of) the temp projects, since "npm install" does not
                    // detect changes for "file:./" references.
                    // We recognize the temp projects by their names, which always start with "rush-".
                    // Example: "C:\MyRepo\common\temp\node_modules\@rush-temp"
                    const pathToDeleteWithoutStar = node_path__WEBPACK_IMPORTED_MODULE_1__.join(commonNodeModulesFolder, _RushConstants__WEBPACK_IMPORTED_MODULE_7__.RushConstants.rushTempNpmScope);
                    // eslint-disable-next-line no-console
                    console.log(`Deleting ${pathToDeleteWithoutStar}\\*`);
                    // Glob can't handle Windows paths
                    const normalizedPathToDeleteWithoutStar = _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__.Text.replaceAll(pathToDeleteWithoutStar, '\\', '/');
                    const { default: glob } = await Promise.resolve(/*! import() */).then(__webpack_require__.t.bind(__webpack_require__, /*! fast-glob */ 743715, 23));
                    const tempModulePaths = await glob(glob.escapePath(normalizedPathToDeleteWithoutStar) + '/*');
                    // Example: "C:/MyRepo/common/temp/node_modules/@rush-temp/*"
                    for (const tempModulePath of tempModulePaths) {
                        // We could potentially use AsyncRecycler here, but in practice these folders tend
                        // to be very small
                        _utilities_Utilities__WEBPACK_IMPORTED_MODULE_9__.Utilities.dangerouslyDeletePath(tempModulePath);
                    }
                }
            }
        }
        if (this.rushConfiguration.packageManager === 'yarn') {
            // Yarn does not correctly detect changes to a tarball, so we need to forcibly clear its cache
            const yarnRushTempCacheFolder = node_path__WEBPACK_IMPORTED_MODULE_1__.join(this.rushConfiguration.yarnCacheFolder, 'v2', 'npm-@rush-temp');
            if (_rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__.FileSystem.exists(yarnRushTempCacheFolder)) {
                // eslint-disable-next-line no-console
                console.log('Deleting ' + yarnRushTempCacheFolder);
                _utilities_Utilities__WEBPACK_IMPORTED_MODULE_9__.Utilities.dangerouslyDeletePath(yarnRushTempCacheFolder);
            }
        }
        // Run "npm install" in the common folder
        const installArgs = ['install'];
        this.pushConfigurationArgs(installArgs, this.options, subspace);
        // eslint-disable-next-line no-console
        console.log('\n' +
            _rushstack_terminal__WEBPACK_IMPORTED_MODULE_5__.Colorize.bold(`Running "${this.rushConfiguration.packageManager} install" in` +
                ` ${this.rushConfiguration.commonTempFolder}`) +
            '\n');
        // If any diagnostic options were specified, then show the full command-line
        if (this.options.debug || this.options.collectLogFile || this.options.networkConcurrency) {
            // eslint-disable-next-line no-console
            console.log('\n' +
                _rushstack_terminal__WEBPACK_IMPORTED_MODULE_5__.Colorize.green('Invoking package manager: ') +
                _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__.FileSystem.getRealPath(packageManagerFilename) +
                ' ' +
                installArgs.join(' ') +
                '\n');
        }
        await _utilities_Utilities__WEBPACK_IMPORTED_MODULE_9__.Utilities.executeCommandWithRetryAsync({
            command: packageManagerFilename,
            args: installArgs,
            workingDirectory: this.rushConfiguration.commonTempFolder,
            environment: packageManagerEnv,
            suppressOutput: false
        }, this.options.maxInstallAttempts, () => {
            if (this.rushConfiguration.isPnpm) {
                // eslint-disable-next-line no-console
                console.log(_rushstack_terminal__WEBPACK_IMPORTED_MODULE_5__.Colorize.yellow(`Deleting the "node_modules" folder`));
                this.installRecycler.moveFolder(commonNodeModulesFolder);
                // Leave the pnpm-store as is for the retry. This ensures that packages that have already
                // been downloaded need not be downloaded again, thereby potentially increasing the chances
                // of a subsequent successful install.
                _utilities_Utilities__WEBPACK_IMPORTED_MODULE_9__.Utilities.createFolderWithRetry(commonNodeModulesFolder);
            }
        });
        if (this.rushConfiguration.packageManager === 'npm') {
            // eslint-disable-next-line no-console
            console.log('\n' + _rushstack_terminal__WEBPACK_IMPORTED_MODULE_5__.Colorize.bold('Running "npm shrinkwrap"...'));
            const npmArgs = ['shrinkwrap'];
            this.pushConfigurationArgs(npmArgs, this.options, subspace);
            await _utilities_Utilities__WEBPACK_IMPORTED_MODULE_9__.Utilities.executeCommandAsync({
                command: this.rushConfiguration.packageManagerToolFilename,
                args: npmArgs,
                workingDirectory: this.rushConfiguration.commonTempFolder
            });
            // eslint-disable-next-line no-console
            console.log('"npm shrinkwrap" completed\n');
            await this._fixupNpm5RegressionAsync();
        }
    }
    async postInstallAsync(subspace) {
        if (!this.options.noLink) {
            const linkManager = _LinkManagerFactory__WEBPACK_IMPORTED_MODULE_14__.LinkManagerFactory.getLinkManager(this.rushConfiguration);
            await linkManager.createSymlinksForProjectsAsync(false);
        }
        else {
            // eslint-disable-next-line no-console
            console.log('\n' + _rushstack_terminal__WEBPACK_IMPORTED_MODULE_5__.Colorize.yellow('Since "--no-link" was specified, you will need to run "rush link" manually.'));
        }
    }
    /**
     * This is a workaround for a bug introduced in NPM 5 (and still unfixed as of NPM 5.5.1):
     * https://github.com/npm/npm/issues/19006
     *
     * The regression is that "npm install" sets the package.json "version" field for the
     * @rush-temp projects to a value like "file:projects/example.tgz", when it should be "0.0.0".
     * This causes linking to fail later, when read-package-tree tries to parse the bad version.
     * The error looks like this:
     *
     * ERROR: Failed to parse package.json for foo: Invalid version: "file:projects/example.tgz"
     *
     * Our workaround is to rewrite the package.json files for each of the @rush-temp projects
     * in the node_modules folder, after "npm install" completes.
     */
    async _fixupNpm5RegressionAsync() {
        const pathToDeleteWithoutStar = node_path__WEBPACK_IMPORTED_MODULE_1__.join(this.rushConfiguration.commonTempFolder, 'node_modules', _RushConstants__WEBPACK_IMPORTED_MODULE_7__.RushConstants.rushTempNpmScope);
        // Glob can't handle Windows paths
        const normalizedPathToDeleteWithoutStar = _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__.Text.replaceAll(pathToDeleteWithoutStar, '\\', '/');
        let anyChanges = false;
        const { default: glob } = await Promise.resolve(/*! import() */).then(__webpack_require__.t.bind(__webpack_require__, /*! fast-glob */ 743715, 23));
        const packageJsonPaths = await glob(glob.escapePath(normalizedPathToDeleteWithoutStar) + '/*/package.json');
        // Example: "C:/MyRepo/common/temp/node_modules/@rush-temp/*/package.json"
        for (const packageJsonPath of packageJsonPaths) {
            // Example: "C:/MyRepo/common/temp/node_modules/@rush-temp/example/package.json"
            const packageJsonObject = _rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__.JsonFile.load(packageJsonPath);
            // The temp projects always use "0.0.0" as their version
            packageJsonObject.version = '0.0.0';
            if (_rushstack_node_core_library__WEBPACK_IMPORTED_MODULE_4__.JsonFile.save(packageJsonObject, packageJsonPath, { onlyIfChanged: true })) {
                anyChanges = true;
            }
        }
        if (anyChanges) {
            // eslint-disable-next-line no-console
            console.log('\n' + _rushstack_terminal__WEBPACK_IMPORTED_MODULE_5__.Colorize.yellow(_rushstack_terminal__WEBPACK_IMPORTED_MODULE_5__.PrintUtilities.wrapWords(`Applied workaround for NPM 5 bug`)) + '\n');
        }
    }
    /**
     * Checks for temp projects that exist in the shrinkwrap file, but don't exist
     * in rush.json.  This might occur, e.g. if a project was recently deleted or renamed.
     *
     * @returns true if orphans were found, or false if everything is okay
     */
    _findMissingTempProjects(shrinkwrapFile) {
        const tempProjectNames = new Set(shrinkwrapFile.getTempProjectNames());
        for (const rushProject of this.rushConfiguration.projects) {
            if (!tempProjectNames.has(rushProject.tempProjectName)) {
                // eslint-disable-next-line no-console
                console.log('\n' +
                    _rushstack_terminal__WEBPACK_IMPORTED_MODULE_5__.Colorize.yellow(_rushstack_terminal__WEBPACK_IMPORTED_MODULE_5__.PrintUtilities.wrapWords(`Your ${this.rushConfiguration.shrinkwrapFilePhrase} is missing the project "${rushProject.packageName}".`)) +
                    '\n');
                return true; // found one
            }
        }
        return false; // none found
    }
}
//# sourceMappingURL=RushInstallManager.js.map

/***/ }

};
;
//# sourceMappingURL=RushInstallManager.js.map