"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getYarnLock = getYarnLock;
exports.getZeroInstallPaths = getZeroInstallPaths;
exports.isZeroInstall = isZeroInstall;
exports.getYarnVersionFromLock = getYarnVersionFromLock;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const core_1 = require("@yarnpkg/core");
const parsers_1 = require("@yarnpkg/parsers");
const logger_1 = require("../../../../logger");
const fs_1 = require("../../../../util/fs");
async function getYarnLock(filePath) {
    // TODO #22198
    const yarnLockRaw = (await (0, fs_1.readLocalFile)(filePath, 'utf8'));
    try {
        const parsed = (0, parsers_1.parseSyml)(yarnLockRaw);
        const lockedVersions = {};
        let lockfileVersion;
        for (const [key, val] of Object.entries(parsed)) {
            if (key === '__metadata') {
                // yarn 2
                lockfileVersion = parseInt(val.cacheKey, 10);
                logger_1.logger.once.debug(`yarn.lock ${filePath} has __metadata.cacheKey=${lockfileVersion}`);
            }
            else {
                for (const entry of key.split(', ')) {
                    try {
                        const { scope, name, range } = core_1.structUtils.parseDescriptor(entry);
                        const packageName = scope ? `@${scope}/${name}` : name;
                        const { selector } = core_1.structUtils.parseRange(range);
                        logger_1.logger.trace({ entry, version: val.version });
                        lockedVersions[packageName + '@' + selector] = parsed[key].version;
                    }
                    catch (err) {
                        logger_1.logger.debug({ entry, err }, 'Invalid descriptor or range found in yarn.lock');
                    }
                }
            }
        }
        const isYarn1 = !('__metadata' in parsed);
        if (isYarn1) {
            logger_1.logger.once.debug(`yarn.lock ${filePath} is has no __metadata so is yarn 1`);
        }
        else {
            logger_1.logger.once.debug(`yarn.lock ${filePath} is has __metadata so is yarn 2+`);
        }
        return {
            isYarn1,
            lockfileVersion,
            lockedVersions,
        };
    }
    catch (err) {
        logger_1.logger.debug({ filePath, err }, 'Warning: Exception parsing yarn.lock');
        return { isYarn1: true, lockedVersions: {} };
    }
}
function getZeroInstallPaths(yarnrcYml) {
    let conf;
    try {
        conf = (0, parsers_1.parseSyml)(yarnrcYml);
    }
    catch (err) /* istanbul ignore next */ {
        logger_1.logger.warn({ err }, 'Error parsing .yarnrc.yml');
    }
    const paths = [
        conf?.cacheFolder || './.yarn/cache',
        '.pnp.cjs',
        '.pnp.js',
        '.pnp.loader.mjs',
    ];
    if (conf &&
        core_1.miscUtils.tryParseOptionalBoolean(conf.pnpEnableInlining) === false) {
        paths.push(conf.pnpDataPath || './.pnp.data.json');
    }
    return paths;
}
async function isZeroInstall(yarnrcYmlPath) {
    const yarnrcYml = await (0, fs_1.readLocalFile)(yarnrcYmlPath, 'utf8');
    if (is_1.default.string(yarnrcYml)) {
        const paths = getZeroInstallPaths(yarnrcYml);
        for (const p of paths) {
            if (await (0, fs_1.localPathExists)((0, fs_1.getSiblingFileName)(yarnrcYmlPath, p))) {
                logger_1.logger.debug(`Detected Yarn zero-install in ${p}`);
                return true;
            }
        }
    }
    return false;
}
function getYarnVersionFromLock(lockfile) {
    const { lockfileVersion, isYarn1 } = lockfile;
    if (isYarn1) {
        return '^1.22.18';
    }
    if (lockfileVersion && lockfileVersion >= 12) {
        // This will probably be v5
        return '>=4.0.0';
    }
    if (lockfileVersion && lockfileVersion >= 10) {
        return '^4.0.0';
    }
    if (lockfileVersion && lockfileVersion >= 8) {
        // https://github.com/yarnpkg/berry/commit/9bcd27ae34aee77a567dd104947407532fa179b3
        return '^3.0.0';
    }
    else if (lockfileVersion && lockfileVersion >= 6) {
        // https://github.com/yarnpkg/berry/commit/f753790380cbda5b55d028ea84b199445129f9ba
        return '^2.2.0';
    }
    return '^2.0.0';
}
//# sourceMappingURL=yarn.js.map