"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 normalizeRegistryUrl = require("normalize-registry-url");
const logger_1 = require("@pnpm/logger");
const parseWantedDependencies_1 = require("../parseWantedDependencies");
function default_1(fuzzyDeps, opts) {
    return __awaiter(this, void 0, void 0, function* () {
        const reporter = opts && opts.reporter;
        if (reporter) {
            logger_1.streamParser.on('data', reporter);
        }
        const deps = yield parseWantedDependencies_1.default(fuzzyDeps, {
            allowNew: true,
            currentPrefs: {},
            defaultTag: opts.tag || 'latest',
            dev: false,
            devDependencies: {},
            optional: false,
            optionalDependencies: {},
        });
        let hasFailures = false;
        yield Promise.all(deps.map((dep) => __awaiter(this, void 0, void 0, function* () {
            try {
                const pkgResponse = yield opts.storeController.requestPackage(dep, {
                    downloadPriority: 1,
                    loggedPkg: {
                        rawSpec: dep.raw,
                    },
                    preferredVersions: {},
                    prefix: opts.prefix || process.cwd(),
                    registry: normalizeRegistryUrl(opts.registry || 'https://registry.npmjs.org/'),
                    verifyStoreIntegrity: opts.verifyStoreIntegrity || true,
                });
                yield pkgResponse['fetchingFiles']; // tslint:disable-line:no-string-literal
                logger_1.default.info(`+ ${pkgResponse.body.id}`);
            }
            catch (e) {
                hasFailures = true;
                logger_1.default.error(e);
            }
        })));
        yield opts.storeController.saveState();
        if (reporter) {
            logger_1.streamParser.removeListener('data', reporter);
        }
        if (hasFailures) {
            const err = new Error('Some packages have not been added correctly');
            err['code'] = 'ERR_PNPM_STORE_ADD_FAILURE'; // tslint:disable-line:no-string-literal
            throw err;
        }
    });
}
exports.default = default_1;
//# sourceMappingURL=storeAdd.js.map