"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getNodeConstraint = getNodeConstraint;
exports.getNodeUpdate = getNodeUpdate;
exports.getNodeToolConstraint = getNodeToolConstraint;
const tslib_1 = require("tslib");
const semver_1 = tslib_1.__importDefault(require("semver"));
const upath_1 = tslib_1.__importDefault(require("upath"));
const logger_1 = require("../../../../logger");
const fs_1 = require("../../../../util/fs");
const regex_1 = require("../../../../util/regex");
async function getNodeFile(filename) {
    try {
        // TODO #22198
        const constraint = (await (0, fs_1.readLocalFile)(filename, 'utf8'))
            .split(regex_1.newlineRegex)[0]
            .replace((0, regex_1.regEx)(/^v/), '');
        if (semver_1.default.validRange(constraint)) {
            logger_1.logger.debug(`Using node constraint "${constraint}" from ${filename}`);
            return constraint;
        }
    }
    catch (err) {
        // do nothing
    }
    return null;
}
async function getPackageJsonConstraint(pkg) {
    const constraint = (await pkg.getValue()).engines?.node;
    if (constraint && semver_1.default.validRange(constraint)) {
        logger_1.logger.debug(`Using node constraint "${constraint}" from package.json`);
        return constraint;
    }
    return null;
}
// export only for testing
async function getNodeConstraint(config, upgrades, lockFileDir, pkg) {
    const constraint = getNodeUpdate(upgrades) ??
        config.constraints?.node ??
        (await getNodeFile(upath_1.default.join(lockFileDir, '.nvmrc'))) ??
        (await getNodeFile(upath_1.default.join(lockFileDir, '.node-version'))) ??
        (await getPackageJsonConstraint(pkg));
    if (!constraint) {
        logger_1.logger.debug('No node constraint found - using latest');
    }
    return constraint;
}
function getNodeUpdate(upgrades) {
    return upgrades.find((u) => u.depName === 'node')?.newValue;
}
async function getNodeToolConstraint(config, upgrades, lockFileDir, pkg) {
    const constraint = await getNodeConstraint(config, upgrades, lockFileDir, pkg);
    return {
        toolName: 'node',
        constraint,
    };
}
//# sourceMappingURL=node-version.js.map