"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateArtifacts = updateArtifacts;
const tslib_1 = require("tslib");
const upath_1 = tslib_1.__importDefault(require("upath"));
const logger_1 = require("../../../logger");
const exec_1 = require("../../../util/exec");
const fs_1 = require("../../../util/fs");
const regex_1 = require("../../../util/regex");
const node_version_1 = require("./post-update/node-version");
const utils_1 = require("./post-update/utils");
// eg. 8.15.5+sha256.4b4efa12490e5055d59b9b9fc9438b7d581a6b7af3b5675eb5c5f447cee1a589
const versionWithHashRegString = '^(?<version>.*)\\+(?<hash>.*)';
// Execute 'corepack use' command for npm manager updates
// This step is necessary because Corepack recommends attaching a hash after the version
// The hash is generated only after running 'corepack use' and cannot be fetched from the npm registry
async function updateArtifacts({ packageFileName, config, updatedDeps, newPackageFileContent: existingPackageFileContent, }) {
    logger_1.logger.debug(`npm.updateArtifacts(${packageFileName})`);
    const packageManagerUpdate = updatedDeps.find((dep) => dep.depType === 'packageManager');
    if (!packageManagerUpdate) {
        logger_1.logger.debug('No packageManager updates - returning null');
        return null;
    }
    const { currentValue, depName, newVersion } = packageManagerUpdate;
    // Execute 'corepack use' command only if the currentValue already has hash in it
    if (!currentValue || !(0, regex_1.regEx)(versionWithHashRegString).test(currentValue)) {
        return null;
    }
    // Asumming that corepack only needs to modify the package.json file in the root folder
    // As it should not be regular practice to have different package managers in different workspaces
    const pkgFileDir = upath_1.default.dirname(packageFileName);
    const lazyPkgJson = (0, utils_1.lazyLoadPackageJson)(pkgFileDir);
    const cmd = `corepack use ${depName}@${newVersion}`;
    const nodeConstraints = await (0, node_version_1.getNodeToolConstraint)(config, updatedDeps, pkgFileDir, lazyPkgJson);
    const execOptions = {
        cwdFile: packageFileName,
        toolConstraints: [
            nodeConstraints,
            {
                toolName: 'corepack',
                constraint: config.constraints?.corepack,
            },
        ],
        docker: {},
        userConfiguredEnv: config.env,
    };
    try {
        await (0, exec_1.exec)(cmd, execOptions);
        const newPackageFileContent = await (0, fs_1.readLocalFile)(packageFileName, 'utf8');
        if (!newPackageFileContent ||
            existingPackageFileContent === newPackageFileContent) {
            return null;
        }
        logger_1.logger.debug('Returning updated package.json');
        return [
            {
                file: {
                    type: 'addition',
                    path: packageFileName,
                    contents: newPackageFileContent,
                },
            },
        ];
    }
    catch (err) {
        logger_1.logger.warn({ err }, 'Error updating package.json');
        return [
            {
                artifactError: {
                    fileName: packageFileName,
                    stderr: err.message,
                },
            },
        ];
    }
}
//# sourceMappingURL=artifacts.js.map