"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 registryUrl = require("registry-url");
const loadJsonFile = require("load-json-file");
const writeJsonFile = require("write-json-file");
const path = require("path");
const pnpm_logger_1 = require("pnpm-logger");
const pLimit = require("p-limit");
// prevents simultainous operations on the meta.json
// otherwise it would cause EPERM exceptions
const metafileOperationLimits = {};
function loadPkgMetaNonCached(spec, storePath, got, metaCache) {
    return __awaiter(this, void 0, void 0, function* () {
        if (metaCache.has(spec.name)) {
            return metaCache.get(spec.name);
        }
        const registry = url.parse(registryUrl(spec.scope)).host.replace(':', '+');
        const pkgStore = path.join(storePath, registry, spec.name);
        const limit = metafileOperationLimits[pkgStore] = metafileOperationLimits[pkgStore] || pLimit(1);
        if (spec.type === 'version') {
            const meta = yield limit(() => loadMeta(pkgStore));
            // use the cached meta only if it has the required package version
            // otherwise it is probably out of date
            if (meta && meta.versions && meta.versions[spec.spec]) {
                return meta;
            }
        }
        try {
            const meta = yield fromRegistry(got, spec);
            // only save meta to cache, when it is fresh
            metaCache.set(spec.name, meta);
            limit(() => saveMeta(pkgStore, meta));
            return meta;
        }
        catch (err) {
            const meta = yield loadMeta(storePath);
            if (!meta)
                throw err;
            pnpm_logger_1.default.error(err);
            pnpm_logger_1.default.info(`Using cached meta from ${storePath}`);
            return meta;
        }
    });
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = loadPkgMetaNonCached;
function fromRegistry(got, spec) {
    return __awaiter(this, void 0, void 0, function* () {
        const uri = toUri(spec);
        const meta = yield got.getJSON(uri);
        return meta;
    });
}
const META_FILENAME = 'meta.json';
function loadMeta(pkgStore) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            return yield loadJsonFile(path.join(pkgStore, META_FILENAME));
        }
        catch (err) {
            return null;
        }
    });
}
function saveMeta(pkgStore, meta) {
    return writeJsonFile(path.join(pkgStore, META_FILENAME), meta);
}
/**
 * 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 = '@' + encodeURIComponent(spec.name.substr(1));
    }
    else {
        name = encodeURIComponent(spec.name);
    }
    return url.resolve(registryUrl(spec.scope), name);
}
//# sourceMappingURL=loadPackageMeta.js.map