"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const npm_registry_agent_1 = require("@pnpm/npm-registry-agent");
const createFetchRetry = require("@zeit/fetch-retry");
const nodeFetch = require("node-fetch");
const USER_AGENT = 'pnpm'; // or maybe make it `${pkg.name}/${pkg.version} (+https://npm.im/${pkg.name})`
const fetch = createFetchRetry(nodeFetch);
const CORGI_DOC = 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*';
const JSON_DOC = 'application/json';
function default_1(defaultOpts) {
    return (url, opts) => {
        const agent = npm_registry_agent_1.default(url, Object.assign({}, defaultOpts, opts)); // tslint:disable-line
        const headers = Object.assign({ 'connection': agent ? 'keep-alive' : 'close', 'user-agent': USER_AGENT }, getHeaders({
            auth: opts && opts.auth,
            fullMetadata: defaultOpts.fullMetadata,
            userAgent: defaultOpts.userAgent,
        }));
        return fetch(url, {
            agent,
            // if verifying integrity, node-fetch must not decompress
            compress: false,
            headers,
            redirect: 'follow',
            retry: defaultOpts.retry,
        });
    };
}
exports.default = default_1;
function getHeaders(opts) {
    const headers = {
        accept: opts.fullMetadata === true ? JSON_DOC : CORGI_DOC,
    };
    if (opts.auth) {
        const authorization = authObjectToHeaderValue(opts.auth);
        if (authorization) {
            headers['authorization'] = authorization; // tslint:disable-line
        }
    }
    if (opts.userAgent) {
        headers['user-agent'] = opts.userAgent;
    }
    return headers;
}
function authObjectToHeaderValue(auth) {
    if (auth.token) {
        return `Bearer ${auth.token}`;
    }
    if (auth.username && auth.password) {
        const encoded = Buffer.from(`${auth.username}:${auth.password}`, 'utf8').toString('base64');
        return `Basic ${encoded}`;
    }
    if (auth._auth) {
        return `Basic ${auth._auth}`;
    }
    return undefined;
}
//# sourceMappingURL=index.js.map