"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());
    });
};
const url = require('url');
const enc = encodeURIComponent;
const createPkgId_1 = require('./createPkgId');
const registryUrl = require('registry-url');
const semver = require('semver');
const fetch_1 = require('./fetch');
/**
 * Resolves a package in the NPM registry. Done as part of `install()`.
 *
 * @example
 *     var npa = require('npm-package-arg')
 *     resolve(npa('rimraf@2'))
 *       .then((res) => {
 *         res.id == 'rimraf@2.5.1'
 *         res.dist == {
 *           shasum: '0a1b2c...'
 *           tarball: 'http://...'
 *         }
 *       })
 */
function resolveNpm(spec, opts) {
    return __awaiter(this, void 0, void 0, function* () {
        // { raw: 'rimraf@2', scope: null, name: 'rimraf', rawSpec: '2' || '' }
        try {
            const url = toUri(spec);
            if (opts.log)
                opts.log('resolving');
            const parsedBody = (yield opts.got.getJSON(url));
            const correctPkg = pickVersionFromRegistryDocument(parsedBody, spec, opts.tag);
            return {
                id: createPkgId_1.default(correctPkg),
                pkg: correctPkg,
                fetch: fetch_1.createRemoteTarballFetcher({
                    shasum: correctPkg.dist.shasum,
                    tarball: correctPkg.dist.tarball
                }, opts)
            };
        }
        catch (err) {
            if (err['statusCode'] === 404) {
                throw new Error("Module '" + spec.raw + "' not found");
            }
            throw err;
        }
    });
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = resolveNpm;
function pickVersionFromRegistryDocument(pkg, dep, latestTag) {
    const versions = Object.keys(pkg.versions);
    if (dep.type === 'tag') {
        const tagVersion = pkg['dist-tags'][dep.spec];
        if (pkg.versions[tagVersion]) {
            return pkg.versions[tagVersion];
        }
    }
    else {
        const latest = pkg['dist-tags'][latestTag];
        if (semver.satisfies(latest, dep.spec, true)) {
            return pkg.versions[latest];
        }
        const maxVersion = semver.maxSatisfying(versions, dep.spec, true);
        if (maxVersion) {
            return pkg.versions[maxVersion];
        }
    }
    const message = versions.length
        ? 'Versions in registry:\n' + versions.join(', ') + '\n'
        : 'No valid version found.';
    const er = new Error('No compatible version found: ' +
        dep.raw + '\n' + message);
    throw er;
}
/**
 * Converts package data (from `npa()`) to a URI
 *
 * @example
 *     toUri({ name: 'rimraf', rawSpec: '2' })
 *     // => 'https://registry.npmjs.org/rimraf/2'
 */
function toUri(spec) {
    let name;
    if (spec.name.substr(0, 1) === '@') {
        name = '@' + enc(spec.name.substr(1));
    }
    else {
        name = enc(spec.name);
    }
    return url.resolve(registryUrl(spec.scope), name);
}
//# sourceMappingURL=npm.js.map