"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const pauseStream = require("pause-stream");
const getRegistryAuthInfo = require("registry-auth-token");
const memoize = require("lodash.memoize");
const pLimit = require("p-limit");
exports.default = (client, opts) => {
    const limit = pLimit(opts.networkConcurrency);
    function getJSON(url) {
        return __awaiter(this, void 0, void 0, function* () {
            return limit(() => new Promise((resolve, reject) => {
                client.get(url, createOptions(url), (err, data, raw, res) => {
                    if (err)
                        return reject(err);
                    resolve(data);
                });
            }));
        });
    }
    const getStream = function (url) {
        return limit(() => new Promise((resolve, reject) => {
            client.fetch(url, createOptions(url), (err, res) => {
                if (err)
                    return reject(err);
                const ps = pauseStream();
                // without pausing, gunzip/tar-fs would miss the beginning of the stream
                res.pipe(ps.pause());
                resolve(ps);
            });
        }));
    };
    function createOptions(url) {
        const authInfo = getRegistryAuthInfo(url, { recursive: true });
        if (!authInfo)
            return {};
        switch (authInfo.type) {
            case 'Bearer':
                return {
                    auth: {
                        token: authInfo.token
                    }
                };
            case 'Basic':
                return {
                    auth: {
                        username: authInfo.username,
                        password: authInfo.password
                    }
                };
            default:
                throw new Error(`Unsupported authorization type '${authInfo.type}'`);
        }
    }
    return {
        getJSON: memoize(getJSON),
        getStream: getStream,
    };
};
//# sourceMappingURL=got.js.map