"use strict";
/* IMPORT */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const aborter_1 = __importDefault(require("aborter"));
const colorette_1 = require("colorette");
const simple_get_1 = __importDefault(require("simple-get"));
const semver_compare_1 = __importDefault(require("semver-compare"));
const signal_exit_1 = __importDefault(require("signal-exit"));
/* MAIN */
const Utils = {
    /* API */
    fetch: (url) => {
        return new Promise((resolve, reject) => {
            const signal = Utils.getExitSignal();
            const request = simple_get_1.default.concat(url, (error, response, data) => {
                if (error)
                    return reject(error);
                return resolve(JSON.parse(data.toString()));
            });
            signal.addEventListener('abort', request.abort.bind(request));
        });
    },
    getExitSignal: () => {
        const aborter = new aborter_1.default();
        signal_exit_1.default(() => aborter.abort());
        return aborter.signal;
    },
    getLatestVersion: async (name) => {
        const latestUrl = `http://registry.npmjs.org/${name}/latest`;
        const latest = await Utils.fetch(latestUrl);
        return latest.version;
    },
    isUpdateAvailable: (current, latest) => {
        return semver_compare_1.default(current, latest) === -1;
    },
    notify: (name, version, latest) => {
        const log = () => console.log(`\n\n📦 Update available for ${colorette_1.cyan(name)}: ${colorette_1.gray(version)} → ${colorette_1.green(latest)}`);
        signal_exit_1.default(log, { alwaysLast: true });
    }
};
/* EXPORT */
exports.default = Utils;
