"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const error_1 = require("@pnpm/error");
const lockfile_file_1 = require("@pnpm/lockfile-file");
const outdated_1 = require("@pnpm/outdated");
const store_path_1 = require("@pnpm/store-path");
const chalk_1 = require("chalk");
const stripColor = require("strip-color");
const table = require("text-table");
const createLatestVersionGetter_1 = require("../createLatestVersionGetter");
const readImporterManifest_1 = require("../readImporterManifest");
async function default_1(args, opts, command) {
    const packages = [
        {
            manifest: await readImporterManifest_1.readImporterManifestOnly(opts.prefix, opts),
            path: opts.prefix,
        },
    ];
    const { outdatedPackages } = (await outdatedDependenciesOfWorkspacePackages(packages, args, opts))[0];
    if (!outdatedPackages.length)
        return;
    const columnNames = ['Package', 'Current', 'Wanted', 'Latest'].map((txt) => chalk_1.default.underline(txt));
    console.log(table([columnNames].concat(outdatedPackages.map((outdatedPkg) => [
        chalk_1.default.yellow(outdatedPkg.packageName),
        outdatedPkg.current || 'missing',
        chalk_1.default.green(outdatedPkg.wanted),
        chalk_1.default.magenta(outdatedPkg.latest || ''),
    ])), {
        stringLength: (s) => stripColor(s).length,
    }));
}
exports.default = default_1;
async function outdatedDependenciesOfWorkspacePackages(pkgs, args, opts) {
    const lockfileDirectory = opts.lockfileDirectory || opts.prefix;
    const currentLockfile = await lockfile_file_1.readCurrentLockfile(lockfileDirectory, { ignoreIncompatible: false });
    const wantedLockfile = await lockfile_file_1.readWantedLockfile(lockfileDirectory, { ignoreIncompatible: false }) || currentLockfile;
    if (!wantedLockfile) {
        throw new error_1.default('OUTDATED_NO_LOCKFILE', 'No lockfile in this directory. Run `pnpm install` to generate one.');
    }
    const store = await store_path_1.default(opts.prefix, opts.store);
    const getLatestVersion = createLatestVersionGetter_1.default(Object.assign({}, opts, { lockfileDirectory,
        store }));
    return Promise.all(pkgs.map(async ({ manifest, path }) => {
        const optsForOutdated = {
            currentLockfile,
            getLatestVersion,
            lockfileDirectory,
            manifest,
            prefix: path,
            wantedLockfile,
        };
        return {
            outdatedPackages: args.length
                ? await outdated_1.forPackages(args, optsForOutdated)
                : await outdated_1.default(optsForOutdated),
            prefix: lockfile_file_1.getLockfileImporterId(lockfileDirectory, path),
        };
    }));
}
exports.outdatedDependenciesOfWorkspacePackages = outdatedDependenciesOfWorkspacePackages;
