"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderDetails = exports.renderLatest = exports.renderCurrent = exports.renderPackageName = exports.toOutdatedWithVersionDiff = exports.getCellWidth = exports.handler = exports.completion = exports.help = exports.commandNames = exports.shorthands = exports.cliOptionsTypes = exports.rcOptionsTypes = void 0;
const cli_utils_1 = require("@pnpm/cli-utils");
const colorize_semver_diff_1 = __importDefault(require("@pnpm/colorize-semver-diff"));
const common_cli_options_help_1 = require("@pnpm/common-cli-options-help");
const config_1 = require("@pnpm/config");
const outdated_1 = require("@pnpm/outdated");
const semver_diff_1 = __importDefault(require("@pnpm/semver-diff"));
const table_1 = require("@zkochan/table");
const recursive_1 = __importDefault(require("./recursive"));
const utils_1 = require("./utils");
const chalk = require("chalk");
const R = require("ramda");
const renderHelp = require("render-help");
const stripAnsi = require("strip-ansi");
const wrapAnsi = require("wrap-ansi");
function rcOptionsTypes() {
    return {
        ...R.pick([
            'depth',
            'dev',
            'global-dir',
            'global',
            'long',
            'optional',
            'production',
        ], config_1.types),
        compatible: Boolean,
        table: Boolean,
    };
}
exports.rcOptionsTypes = rcOptionsTypes;
exports.cliOptionsTypes = () => ({
    ...rcOptionsTypes(),
    recursive: Boolean,
});
exports.shorthands = {
    D: '--dev',
    P: '--production',
};
exports.commandNames = ['outdated'];
function help() {
    return renderHelp({
        description: `Check for outdated packages. The check can be limited to a subset of the installed packages by providing arguments (patterns are supported).

Examples:
pnpm outdated
pnpm outdated --long
pnpm outdated gulp-* @babel/core`,
        descriptionLists: [
            {
                title: 'Options',
                list: [
                    {
                        description: 'Print only versions that satisfy specs in package.json',
                        name: '--compatible',
                    },
                    {
                        description: 'By default, details about the outdated packages (such as a link to the repo) are not displayed. \
To display the details, pass this option.',
                        name: '--long',
                    },
                    {
                        description: 'Check for outdated dependencies in every package found in subdirectories \
or in every workspace package, when executed inside a workspace. \
For options that may be used with `-r`, see "pnpm help recursive"',
                        name: '--recursive',
                        shortAlias: '-r',
                    },
                    {
                        description: 'Prints the outdated packages in a list. Good for small consoles',
                        name: '--no-table',
                    },
                    {
                        description: 'Check only "dependencies" and "optionalDependencies"',
                        name: '--prod',
                        shortAlias: '-P',
                    },
                    {
                        description: 'Check only "devDependencies"',
                        name: '--dev',
                        shortAlias: '-D',
                    },
                    {
                        description: 'Don\'t check "optionalDependencies"',
                        name: '--no-optional',
                    },
                    common_cli_options_help_1.OPTIONS.globalDir,
                    ...common_cli_options_help_1.UNIVERSAL_OPTIONS,
                ],
            },
            common_cli_options_help_1.FILTERING,
        ],
        url: cli_utils_1.docsUrl('outdated'),
        usages: ['pnpm outdated [<pkg> ...]'],
    });
}
exports.help = help;
exports.completion = (cliOpts) => {
    return cli_utils_1.readDepNameCompletions(cliOpts.dir);
};
async function handler(opts, params = []) {
    const include = {
        dependencies: opts.production !== false,
        devDependencies: opts.dev !== false,
        optionalDependencies: opts.optional !== false,
    };
    if (opts.recursive && opts.selectedProjectsGraph) {
        const pkgs = Object.values(opts.selectedProjectsGraph).map((wsPkg) => wsPkg.package);
        return recursive_1.default(pkgs, params, { ...opts, include });
    }
    const packages = [
        {
            dir: opts.dir,
            manifest: await cli_utils_1.readProjectManifestOnly(opts.dir, opts),
        },
    ];
    const [outdatedPackages] = await outdated_1.outdatedDepsOfProjects(packages, params, {
        ...opts,
        fullMetadata: opts.long,
        include,
    });
    if (!outdatedPackages.length)
        return { output: '', exitCode: 0 };
    if (opts.table !== false) {
        return { output: renderOutdatedTable(outdatedPackages, opts), exitCode: 1 };
    }
    else {
        return { output: renderOutdatedList(outdatedPackages, opts), exitCode: 1 };
    }
}
exports.handler = handler;
function renderOutdatedTable(outdatedPackages, opts) {
    const columnNames = [
        'Package',
        'Current',
        'Latest',
    ];
    const columnFns = [
        renderPackageName,
        renderCurrent,
        renderLatest,
    ];
    if (opts.long) {
        columnNames.push('Details');
        columnFns.push(renderDetails);
    }
    // Avoid the overhead of allocating a new array caused by calling `array.map()`
    for (let i = 0; i < columnNames.length; i++)
        columnNames[i] = chalk.blueBright(columnNames[i]);
    return table_1.table([
        columnNames,
        ...sortOutdatedPackages(outdatedPackages)
            .map((outdatedPkg) => columnFns.map((fn) => fn(outdatedPkg))),
    ], cli_utils_1.TABLE_OPTIONS);
}
function renderOutdatedList(outdatedPackages, opts) {
    return sortOutdatedPackages(outdatedPackages)
        .map((outdatedPkg) => {
        let info = `${chalk.bold(renderPackageName(outdatedPkg))}
${renderCurrent(outdatedPkg)} ${chalk.grey('=>')} ${renderLatest(outdatedPkg)}`;
        if (opts.long) {
            const details = renderDetails(outdatedPkg);
            if (details) {
                info += `\n${details}`;
            }
        }
        return info;
    })
        .join('\n\n') + '\n';
}
function sortOutdatedPackages(outdatedPackages) {
    return R.sortWith(utils_1.DEFAULT_COMPARATORS, outdatedPackages.map(toOutdatedWithVersionDiff));
}
function getCellWidth(data, columnNumber, maxWidth) {
    const maxCellWidth = data.reduce((cellWidth, row) => {
        const cellLines = stripAnsi(row[columnNumber]).split('\n');
        const currentCellWidth = cellLines.reduce((lineWidth, line) => {
            return Math.max(lineWidth, line.length);
        }, 0);
        return Math.max(cellWidth, currentCellWidth);
    }, 0);
    return Math.min(maxWidth, maxCellWidth);
}
exports.getCellWidth = getCellWidth;
function toOutdatedWithVersionDiff(outdated) {
    if (outdated.latestManifest) {
        return {
            ...outdated,
            ...semver_diff_1.default(outdated.wanted, outdated.latestManifest.version),
        };
    }
    return {
        ...outdated,
        change: 'unknown',
    };
}
exports.toOutdatedWithVersionDiff = toOutdatedWithVersionDiff;
function renderPackageName({ belongsTo, packageName }) {
    switch (belongsTo) {
        case 'devDependencies': return `${packageName} ${chalk.dim('(dev)')}`;
        case 'optionalDependencies': return `${packageName} ${chalk.dim('(optional)')}`;
        default: return packageName;
    }
}
exports.renderPackageName = renderPackageName;
function renderCurrent({ current, wanted }) {
    const output = current !== null && current !== void 0 ? current : 'missing';
    if (current === wanted)
        return output;
    return `${output} (wanted ${wanted})`;
}
exports.renderCurrent = renderCurrent;
function renderLatest(outdatedPkg) {
    const { latestManifest, change, diff } = outdatedPkg;
    if (!latestManifest)
        return '';
    if (change === null || !diff) {
        return latestManifest.deprecated
            ? chalk.redBright.bold('Deprecated')
            : latestManifest.version;
    }
    return colorize_semver_diff_1.default({ change, diff });
}
exports.renderLatest = renderLatest;
function renderDetails({ latestManifest }) {
    if (!latestManifest)
        return '';
    const outputs = [];
    if (latestManifest.deprecated) {
        outputs.push(wrapAnsi(chalk.redBright(latestManifest.deprecated), 40));
    }
    if (latestManifest.homepage) {
        outputs.push(chalk.underline(latestManifest.homepage));
    }
    return outputs.join('\n');
}
exports.renderDetails = renderDetails;
//# sourceMappingURL=outdated.js.map