"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.RUSH_JSON_FILENAME = void 0;
exports.getNpmPath = getNpmPath;
exports.findRushJsonFolder = findRushJsonFolder;
exports.installAndRun = installAndRun;
exports.runWithErrorAndStatusCode = runWithErrorAndStatusCode;
/* eslint-disable no-console */
const childProcess = __importStar(require("node:child_process"));
const fs = __importStar(require("node:fs"));
const os = __importStar(require("node:os"));
const path = __importStar(require("node:path"));
const npmrcUtilities_1 = require("../utilities/npmrcUtilities");
const executionUtilities_1 = require("../utilities/executionUtilities");
exports.RUSH_JSON_FILENAME = 'rush.json';
const RUSH_TEMP_FOLDER_ENV_VARIABLE_NAME = 'RUSH_TEMP_FOLDER';
const INSTALL_RUN_LOCKFILE_PATH_VARIABLE = 'INSTALL_RUN_LOCKFILE_PATH';
const INSTALLED_FLAG_FILENAME = 'installed.flag';
const NODE_MODULES_FOLDER_NAME = 'node_modules';
const PACKAGE_JSON_FILENAME = 'package.json';
/**
 * Parse a package specifier (in the form of name\@version) into name and version parts.
 */
function _parsePackageSpecifier(rawPackageSpecifier) {
    rawPackageSpecifier = (rawPackageSpecifier || '').trim();
    const separatorIndex = rawPackageSpecifier.lastIndexOf('@');
    let name;
    let version = undefined;
    if (separatorIndex === 0) {
        // The specifier starts with a scope and doesn't have a version specified
        name = rawPackageSpecifier;
    }
    else if (separatorIndex === -1) {
        // The specifier doesn't have a version
        name = rawPackageSpecifier;
    }
    else {
        name = rawPackageSpecifier.substring(0, separatorIndex);
        version = rawPackageSpecifier.substring(separatorIndex + 1);
    }
    if (!name) {
        throw new Error(`Invalid package specifier: ${rawPackageSpecifier}`);
    }
    return { name, version };
}
let _npmPath = undefined;
/**
 * Get the absolute path to the npm executable
 */
function getNpmPath() {
    if (!_npmPath) {
        try {
            if (executionUtilities_1.IS_WINDOWS) {
                // We're on Windows
                const whereOutput = childProcess.execSync('where npm', { stdio: [] }).toString();
                const lines = whereOutput.split(os.EOL).filter((line) => !!line);
                // take the last result, we are looking for a .cmd command
                // see https://github.com/microsoft/rushstack/issues/759
                _npmPath = lines[lines.length - 1];
            }
            else {
                // We aren't on Windows - assume we're on *NIX or Darwin
                _npmPath = childProcess.execSync('command -v npm', { stdio: [] }).toString();
            }
        }
        catch (e) {
            throw new Error(`Unable to determine the path to the NPM tool: ${e}`);
        }
        _npmPath = _npmPath.trim();
        if (!fs.existsSync(_npmPath)) {
            throw new Error('The NPM executable does not exist');
        }
    }
    return _npmPath;
}
function _ensureFolder(folderPath) {
    if (!fs.existsSync(folderPath)) {
        const parentDir = path.dirname(folderPath);
        _ensureFolder(parentDir);
        fs.mkdirSync(folderPath);
    }
}
/**
 * Create missing directories under the specified base directory, and return the resolved directory.
 *
 * Does not support "." or ".." path segments.
 * Assumes the baseFolder exists.
 */
function _ensureAndJoinPath(baseFolder, ...pathSegments) {
    let joinedPath = baseFolder;
    try {
        for (let pathSegment of pathSegments) {
            pathSegment = pathSegment.replace(/[\\\/]/g, '+');
            joinedPath = path.join(joinedPath, pathSegment);
            if (!fs.existsSync(joinedPath)) {
                fs.mkdirSync(joinedPath);
            }
        }
    }
    catch (e) {
        throw new Error(`Error building local installation folder (${path.join(baseFolder, ...pathSegments)}): ${e}`);
    }
    return joinedPath;
}
function _getRushTempFolder(rushCommonFolder) {
    const rushTempFolder = process.env[RUSH_TEMP_FOLDER_ENV_VARIABLE_NAME];
    if (rushTempFolder !== undefined) {
        _ensureFolder(rushTempFolder);
        return rushTempFolder;
    }
    else {
        return _ensureAndJoinPath(rushCommonFolder, 'temp');
    }
}
/**
 * Compare version strings according to semantic versioning.
 * Returns a positive integer if "a" is a later version than "b",
 * a negative integer if "b" is later than "a",
 * and 0 otherwise.
 */
function _compareVersionStrings(a, b) {
    const aParts = a.split(/[.-]/);
    const bParts = b.split(/[.-]/);
    const numberOfParts = Math.max(aParts.length, bParts.length);
    for (let i = 0; i < numberOfParts; i++) {
        if (aParts[i] !== bParts[i]) {
            return (Number(aParts[i]) || 0) - (Number(bParts[i]) || 0);
        }
    }
    return 0;
}
/**
 * Resolve a package specifier to a static version
 */
function _resolvePackageVersion(logger, rushCommonFolder, { name, version }) {
    if (!version) {
        version = '*'; // If no version is specified, use the latest version
    }
    if (version.match(/^[a-zA-Z0-9\-\+\.]+$/)) {
        // If the version contains only characters that we recognize to be used in static version specifiers,
        // pass the version through
        return version;
    }
    else {
        // version resolves to
        try {
            const rushTempFolder = _getRushTempFolder(rushCommonFolder);
            const sourceNpmrcFolder = path.join(rushCommonFolder, 'config', 'rush');
            (0, npmrcUtilities_1.syncNpmrc)({
                sourceNpmrcFolder,
                targetNpmrcFolder: rushTempFolder,
                logger,
                supportEnvVarFallbackSyntax: false,
                // Always filter npm-incompatible properties in install-run scripts.
                // Any warnings will be shown when running Rush commands directly.
                filterNpmIncompatibleProperties: true
            });
            // This returns something that looks like:
            // ```
            // [
            //   "3.0.0",
            //   "3.0.1",
            //   ...
            //   "3.0.20"
            // ]
            // ```
            //
            // if multiple versions match the selector, or
            //
            // ```
            // "3.0.0"
            // ```
            //
            // if only a single version matches.
            const npmVersionSpawnResult = _runNpmConfirmSuccess(['view', `${name}@${version}`, 'version', '--no-update-notifier', '--json'], {
                cwd: rushTempFolder,
                stdio: [],
                env: process.env
            }, 'npm view');
            const npmViewVersionOutput = npmVersionSpawnResult.stdout.toString();
            const parsedVersionOutput = JSON.parse(npmViewVersionOutput);
            const versions = Array.isArray(parsedVersionOutput)
                ? parsedVersionOutput
                : [parsedVersionOutput];
            let latestVersion = versions[0];
            for (let i = 1; i < versions.length; i++) {
                const latestVersionCandidate = versions[i];
                if (_compareVersionStrings(latestVersionCandidate, latestVersion) > 0) {
                    latestVersion = latestVersionCandidate;
                }
            }
            if (!latestVersion) {
                throw new Error('No versions found for the specified version range.');
            }
            return latestVersion;
        }
        catch (e) {
            throw new Error(`Unable to resolve version ${version} of package ${name}: ${e}`);
        }
    }
}
let _rushJsonFolder;
/**
 * Find the absolute path to the folder containing rush.json
 */
function findRushJsonFolder() {
    if (!_rushJsonFolder) {
        let basePath = __dirname;
        let tempPath = __dirname;
        do {
            const testRushJsonPath = path.join(basePath, exports.RUSH_JSON_FILENAME);
            if (fs.existsSync(testRushJsonPath)) {
                _rushJsonFolder = basePath;
                break;
            }
            else {
                basePath = tempPath;
            }
        } while (basePath !== (tempPath = path.dirname(basePath))); // Exit the loop when we hit the disk root
        if (!_rushJsonFolder) {
            throw new Error(`Unable to find ${exports.RUSH_JSON_FILENAME}.`);
        }
    }
    return _rushJsonFolder;
}
/**
 * Detects if the package in the specified directory is installed
 */
function _isPackageAlreadyInstalled(packageInstallFolder) {
    try {
        const flagFilePath = path.join(packageInstallFolder, INSTALLED_FLAG_FILENAME);
        if (!fs.existsSync(flagFilePath)) {
            return false;
        }
        const fileContents = fs.readFileSync(flagFilePath).toString();
        return fileContents.trim() === process.version;
    }
    catch (e) {
        return false;
    }
}
/**
 * Delete a file. Fail silently if it does not exist.
 */
function _deleteFile(file) {
    try {
        fs.unlinkSync(file);
    }
    catch (err) {
        if (err.code !== 'ENOENT' && err.code !== 'ENOTDIR') {
            throw err;
        }
    }
}
/**
 * Removes the following files and directories under the specified folder path:
 *  - installed.flag
 *  -
 *  - node_modules
 */
function _cleanInstallFolder(rushTempFolder, packageInstallFolder, lockFilePath) {
    try {
        const flagFile = path.resolve(packageInstallFolder, INSTALLED_FLAG_FILENAME);
        _deleteFile(flagFile);
        const packageLockFile = path.resolve(packageInstallFolder, 'package-lock.json');
        if (lockFilePath) {
            fs.copyFileSync(lockFilePath, packageLockFile);
        }
        else {
            // Not running `npm ci`, so need to cleanup
            _deleteFile(packageLockFile);
            const nodeModulesFolder = path.resolve(packageInstallFolder, NODE_MODULES_FOLDER_NAME);
            if (fs.existsSync(nodeModulesFolder)) {
                const rushRecyclerFolder = _ensureAndJoinPath(rushTempFolder, 'rush-recycler');
                fs.renameSync(nodeModulesFolder, path.join(rushRecyclerFolder, `install-run-${Date.now().toString()}`));
            }
        }
    }
    catch (e) {
        throw new Error(`Error cleaning the package install folder (${packageInstallFolder}): ${e}`);
    }
}
function _createPackageJson(packageInstallFolder, name, version) {
    try {
        const packageJsonContents = {
            name: 'ci-rush',
            version: '0.0.0',
            dependencies: {
                [name]: version
            },
            description: "DON'T WARN",
            repository: "DON'T WARN",
            license: 'MIT'
        };
        const packageJsonPath = path.join(packageInstallFolder, PACKAGE_JSON_FILENAME);
        fs.writeFileSync(packageJsonPath, JSON.stringify(packageJsonContents, undefined, 2));
    }
    catch (e) {
        throw new Error(`Unable to create package.json: ${e}`);
    }
}
/**
 * Run "npm install" in the package install folder.
 */
function _installPackage(logger, packageInstallFolder, name, version, npmCommand) {
    try {
        logger.info(`Installing ${name}...`);
        _runNpmConfirmSuccess([npmCommand], {
            stdio: 'inherit',
            cwd: packageInstallFolder,
            env: process.env
        }, `npm ${npmCommand}`);
        logger.info(`Successfully installed ${name}@${version}`);
    }
    catch (e) {
        throw new Error(`Unable to install package: ${e}`);
    }
}
/**
 * Get the ".bin" path for the package.
 */
function _getBinPath(packageInstallFolder, binName) {
    const binFolderPath = path.resolve(packageInstallFolder, NODE_MODULES_FOLDER_NAME, '.bin');
    const resolvedBinName = executionUtilities_1.IS_WINDOWS ? `${binName}.cmd` : binName;
    return path.resolve(binFolderPath, resolvedBinName);
}
function _buildShellCommand(command, args) {
    const escapedCommand = (0, executionUtilities_1.escapeArgumentIfNeeded)(command);
    const escapedArgs = args.map((arg) => (0, executionUtilities_1.escapeArgumentIfNeeded)(arg));
    return [escapedCommand, ...escapedArgs].join(' ');
}
/**
 * Write a flag file to the package's install directory, signifying that the install was successful.
 */
function _writeFlagFile(packageInstallFolder) {
    try {
        const flagFilePath = path.join(packageInstallFolder, INSTALLED_FLAG_FILENAME);
        fs.writeFileSync(flagFilePath, process.version);
    }
    catch (e) {
        throw new Error(`Unable to create installed.flag file in ${packageInstallFolder}`);
    }
}
/**
 * Run npm under the platform's shell and throw if it didn't succeed.
 */
function _runNpmConfirmSuccess(args, options, commandNameForLogging) {
    const command = getNpmPath();
    let result;
    if (executionUtilities_1.IS_WINDOWS) {
        result = childProcess.spawnSync(_buildShellCommand(command, args), {
            ...options,
            shell: true,
            windowsVerbatimArguments: false
        });
    }
    else {
        result = childProcess.spawnSync(command, args, options);
    }
    if (result.status !== 0) {
        if (!result.status) {
            // Is status null or undefined?
            if (result.error) {
                throw new Error(`"${commandNameForLogging}" failed: ${result.error.message.toString()}`);
            }
            else if (result.signal) {
                throw new Error(`"${commandNameForLogging}" was terminated by signal: ${result.signal}`);
            }
            else {
                throw new Error(`"${commandNameForLogging}" failed for an unknown reason`);
            }
        }
        else {
            throw new Error(`"${commandNameForLogging}" returned error code ${result.status}`);
        }
    }
    return result;
}
function installAndRun(logger, packageName, packageVersion, packageBinName, packageBinArgs, lockFilePath = process.env[INSTALL_RUN_LOCKFILE_PATH_VARIABLE]) {
    const rushJsonFolder = findRushJsonFolder();
    const rushCommonFolder = path.join(rushJsonFolder, 'common');
    const rushTempFolder = _getRushTempFolder(rushCommonFolder);
    const packageInstallFolder = _ensureAndJoinPath(rushTempFolder, 'install-run', `${packageName}@${packageVersion}`);
    if (!_isPackageAlreadyInstalled(packageInstallFolder)) {
        // The package isn't already installed
        _cleanInstallFolder(rushTempFolder, packageInstallFolder, lockFilePath);
        const sourceNpmrcFolder = path.join(rushCommonFolder, 'config', 'rush');
        (0, npmrcUtilities_1.syncNpmrc)({
            sourceNpmrcFolder,
            targetNpmrcFolder: packageInstallFolder,
            logger,
            supportEnvVarFallbackSyntax: false,
            // Always filter npm-incompatible properties in install-run scripts.
            // Any warnings will be shown when running Rush commands directly.
            filterNpmIncompatibleProperties: true
        });
        _createPackageJson(packageInstallFolder, packageName, packageVersion);
        const installCommand = lockFilePath ? 'ci' : 'install';
        _installPackage(logger, packageInstallFolder, packageName, packageVersion, installCommand);
        _writeFlagFile(packageInstallFolder);
    }
    const statusMessage = `Invoking "${packageBinName} ${packageBinArgs.join(' ')}"`;
    const statusMessageLine = new Array(statusMessage.length + 1).join('-');
    logger.info('\n' + statusMessage + '\n' + statusMessageLine + '\n');
    const binPath = _getBinPath(packageInstallFolder, packageBinName);
    const binFolderPath = path.resolve(packageInstallFolder, NODE_MODULES_FOLDER_NAME, '.bin');
    // Windows environment variables are case-insensitive.  Instead of using SpawnSyncOptions.env, we need to
    // assign via the process.env proxy to ensure that we append to the right PATH key.
    const originalEnvPath = process.env.PATH || '';
    let result;
    try {
        process.env.PATH = [binFolderPath, originalEnvPath].join(path.delimiter);
        const spawnOptions = {
            stdio: 'inherit',
            cwd: process.cwd(),
            env: process.env
        };
        if (executionUtilities_1.IS_WINDOWS) {
            result = childProcess.spawnSync(_buildShellCommand(binPath, packageBinArgs), {
                ...spawnOptions,
                windowsVerbatimArguments: false,
                // `npm` bin stubs on Windows are `.cmd` files
                // Node.js will not directly invoke a `.cmd` file unless `shell` is set to `true`
                shell: true
            });
        }
        else {
            result = childProcess.spawnSync(binPath, packageBinArgs, spawnOptions);
        }
    }
    finally {
        process.env.PATH = originalEnvPath;
    }
    if (result.status !== null) {
        return result.status;
    }
    else {
        throw result.error || new Error('An unknown error occurred.');
    }
}
function runWithErrorAndStatusCode(logger, fn) {
    process.exitCode = 1;
    try {
        const exitCode = fn();
        process.exitCode = exitCode;
    }
    catch (e) {
        logger.error('\n\n' + e.toString() + '\n\n');
    }
}
function _run() {
    const [nodePath /* Ex: /bin/node */, scriptPath /* /repo/common/scripts/install-run-rush.js */, rawPackageSpecifier /* qrcode@^1.2.0 */, packageBinName /* qrcode */, ...packageBinArgs /* [-f, myproject/lib] */] = process.argv;
    if (!nodePath) {
        throw new Error('Could not detect node path');
    }
    const scriptFileName = path.basename(scriptPath).toLowerCase();
    if (scriptFileName !== 'install-run.js' && scriptFileName !== 'install-run') {
        // If install-run.js wasn't directly invoked, don't execute the rest of this function. Return control
        // to the script that (presumably) imported this file
        return;
    }
    if (process.argv.length < 4) {
        console.log('Usage: install-run.js <package>@<version> <command> [args...]');
        console.log('Example: install-run.js qrcode@1.2.2 qrcode https://rushjs.io');
        process.exit(1);
    }
    const logger = { info: console.log, error: console.error };
    runWithErrorAndStatusCode(logger, () => {
        const rushJsonFolder = findRushJsonFolder();
        const rushCommonFolder = _ensureAndJoinPath(rushJsonFolder, 'common');
        const packageSpecifier = _parsePackageSpecifier(rawPackageSpecifier);
        const name = packageSpecifier.name;
        const version = _resolvePackageVersion(logger, rushCommonFolder, packageSpecifier);
        if (packageSpecifier.version !== version) {
            console.log(`Resolved to ${name}@${version}`);
        }
        return installAndRun(logger, name, version, packageBinName, packageBinArgs);
    });
}
_run();
//# sourceMappingURL=install-run.js.map