"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.patchOptionsWithManifest = exports.log = exports.sequence = exports.CancellationToken = exports.isCancelledError = exports.nonnull = exports.flatten = exports.chain = exports.normalize = exports.getPublicGalleryAPI = exports.getSecurityRolesAPI = exports.getGalleryAPI = exports.getHubUrl = exports.getPublishedUrl = exports.read = void 0;
const util_1 = require("util");
const read_1 = __importDefault(require("read"));
const WebApi_1 = require("azure-devops-node-api/WebApi");
const GalleryApi_1 = require("azure-devops-node-api/GalleryApi");
const chalk_1 = __importDefault(require("chalk"));
const publicgalleryapi_1 = require("./publicgalleryapi");
const os_1 = require("os");
const __read = (0, util_1.promisify)(read_1.default);
function read(prompt, options = {}) {
    if (process.env['VSCE_TESTS'] || !process.stdout.isTTY) {
        return Promise.resolve('y');
    }
    return __read({ prompt, ...options });
}
exports.read = read;
const marketplaceUrl = process.env['VSCE_MARKETPLACE_URL'] || 'https://marketplace.visualstudio.com';
function getPublishedUrl(extension) {
    return `${marketplaceUrl}/items?itemName=${extension}`;
}
exports.getPublishedUrl = getPublishedUrl;
function getHubUrl(publisher, name) {
    return `${marketplaceUrl}/manage/publishers/${publisher}/extensions/${name}/hub`;
}
exports.getHubUrl = getHubUrl;
async function getGalleryAPI(pat) {
    // from https://github.com/Microsoft/tfs-cli/blob/master/app/exec/extension/default.ts#L287-L292
    const authHandler = (0, WebApi_1.getBasicHandler)('OAuth', pat);
    return new GalleryApi_1.GalleryApi(marketplaceUrl, [authHandler]);
    // const vsoapi = new WebApi(marketplaceUrl, authHandler);
    // return await vsoapi.getGalleryApi();
}
exports.getGalleryAPI = getGalleryAPI;
async function getSecurityRolesAPI(pat) {
    const authHandler = (0, WebApi_1.getBasicHandler)('OAuth', pat);
    const vsoapi = new WebApi_1.WebApi(marketplaceUrl, authHandler);
    return await vsoapi.getSecurityRolesApi();
}
exports.getSecurityRolesAPI = getSecurityRolesAPI;
function getPublicGalleryAPI() {
    return new publicgalleryapi_1.PublicGalleryAPI(marketplaceUrl, '3.0-preview.1');
}
exports.getPublicGalleryAPI = getPublicGalleryAPI;
function normalize(path) {
    return path.replace(/\\/g, '/');
}
exports.normalize = normalize;
function chain2(a, b, fn, index = 0) {
    if (index >= b.length) {
        return Promise.resolve(a);
    }
    return fn(a, b[index]).then(a => chain2(a, b, fn, index + 1));
}
function chain(initial, processors, process) {
    return chain2(initial, processors, process);
}
exports.chain = chain;
function flatten(arr) {
    return [].concat.apply([], arr);
}
exports.flatten = flatten;
function nonnull(arg) {
    return !!arg;
}
exports.nonnull = nonnull;
const CancelledError = 'Cancelled';
function isCancelledError(error) {
    return error === CancelledError;
}
exports.isCancelledError = isCancelledError;
class CancellationToken {
    constructor() {
        this.listeners = [];
        this._cancelled = false;
    }
    get isCancelled() {
        return this._cancelled;
    }
    subscribe(fn) {
        this.listeners.push(fn);
        return () => {
            const index = this.listeners.indexOf(fn);
            if (index > -1) {
                this.listeners.splice(index, 1);
            }
        };
    }
    cancel() {
        const emit = !this._cancelled;
        this._cancelled = true;
        if (emit) {
            this.listeners.forEach(l => l(CancelledError));
            this.listeners = [];
        }
    }
}
exports.CancellationToken = CancellationToken;
async function sequence(promiseFactories) {
    for (const factory of promiseFactories) {
        await factory();
    }
}
exports.sequence = sequence;
var LogMessageType;
(function (LogMessageType) {
    LogMessageType[LogMessageType["DONE"] = 0] = "DONE";
    LogMessageType[LogMessageType["INFO"] = 1] = "INFO";
    LogMessageType[LogMessageType["WARNING"] = 2] = "WARNING";
    LogMessageType[LogMessageType["ERROR"] = 3] = "ERROR";
})(LogMessageType || (LogMessageType = {}));
const LogPrefix = {
    [LogMessageType.DONE]: chalk_1.default.bgGreen.black(' DONE '),
    [LogMessageType.INFO]: chalk_1.default.bgBlueBright.black(' INFO '),
    [LogMessageType.WARNING]: chalk_1.default.bgYellow.black(' WARNING '),
    [LogMessageType.ERROR]: chalk_1.default.bgRed.black(' ERROR '),
};
function _log(type, msg, ...args) {
    args = [LogPrefix[type], msg, ...args];
    if (type === LogMessageType.WARNING) {
        process.env['GITHUB_ACTIONS'] ? logToGitHubActions('warning', msg) : console.warn(...args);
    }
    else if (type === LogMessageType.ERROR) {
        process.env['GITHUB_ACTIONS'] ? logToGitHubActions('error', msg) : console.error(...args);
    }
    else {
        process.env['GITHUB_ACTIONS'] ? logToGitHubActions('info', msg) : console.log(...args);
    }
}
const EscapeCharacters = new Map([
    ['%', '%25'],
    ['\r', '%0D'],
    ['\n', '%0A'],
]);
const EscapeRegex = new RegExp(`[${[...EscapeCharacters.keys()].join('')}]`, 'g');
function escapeGitHubActionsMessage(message) {
    return message.replace(EscapeRegex, c => EscapeCharacters.get(c) ?? c);
}
function logToGitHubActions(type, message) {
    const command = type === 'info' ? message : `::${type}::${escapeGitHubActionsMessage(message)}`;
    process.stdout.write(command + os_1.EOL);
}
exports.log = {
    done: _log.bind(null, LogMessageType.DONE),
    info: _log.bind(null, LogMessageType.INFO),
    warn: _log.bind(null, LogMessageType.WARNING),
    error: _log.bind(null, LogMessageType.ERROR),
};
function patchOptionsWithManifest(options, manifest) {
    if (!manifest.vsce) {
        return;
    }
    for (const key of Object.keys(manifest.vsce)) {
        const optionsKey = key === 'yarn' ? 'useYarn' : key;
        if (options[optionsKey] === undefined) {
            options[optionsKey] = manifest.vsce[key];
        }
    }
}
exports.patchOptionsWithManifest = patchOptionsWithManifest;
//# sourceMappingURL=util.js.map