"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const error_1 = require("@pnpm/error");
const url = require("url");
// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string
const semvarRegex = new RegExp(/(.*)(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/);
class RegistryResponseError extends error_1.default {
    constructor(opts) {
        let info = '';
        const matched = opts.package.match(semvarRegex);
        if (matched) {
            info = ` Did you mean ${matched[1]}?`;
        }
        super(`REGISTRY_META_RESPONSE_${opts.response.status}`, `${opts.response.status} ${opts.response.statusText}: ${opts.package} (via ${opts.uri})${info}`);
        this.package = opts.package;
        this.response = opts.response;
        this.uri = opts.uri;
    }
}
async function fromRegistry(fetch, retry, pkgName, registry, authHeaderValue) {
    const uri = toUri(pkgName, registry);
    const response = await fetch(uri, { authHeaderValue, retry });
    if (response.status > 400) {
        throw new RegistryResponseError({
            package: pkgName,
            response,
            uri,
        });
    }
    return response.json();
}
exports.default = fromRegistry;
function toUri(pkgName, registry) {
    let encodedName;
    if (pkgName[0] === '@') {
        encodedName = `@${encodeURIComponent(pkgName.substr(1))}`;
    }
    else {
        encodedName = encodeURIComponent(pkgName);
    }
    return url.resolve(registry, encodedName);
}
//# sourceMappingURL=fetch.js.map