"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 lifecycle_1 = require("@pnpm/lifecycle");
const logger_1 = require("@pnpm/logger");
const utils_1 = require("@pnpm/utils");
const pLimit = require("p-limit");
const dividePackagesToChunks_1 = require("./dividePackagesToChunks");
exports.default = (pkgs, args, cmd, opts) => __awaiter(this, void 0, void 0, function* () {
    const scriptName = args[0];
    const { chunks, graph } = dividePackagesToChunks_1.default(pkgs);
    let hasCommand = 0;
    const limitRun = pLimit(opts.concurrency);
    for (const chunk of chunks) {
        yield Promise.all(chunk.map((prefix) => limitRun(() => __awaiter(this, void 0, void 0, function* () {
            const pkg = graph[prefix];
            if (!pkg.manifest.scripts || !pkg.manifest.scripts[scriptName]) {
                return;
            }
            hasCommand++;
            try {
                const lifecycleOpts = {
                    depPath: prefix,
                    pkgRoot: prefix,
                    rawNpmConfig: opts.rawNpmConfig,
                    rootNodeModulesDir: yield utils_1.realNodeModulesDir(prefix),
                    unsafePerm: opts.unsafePerm || false,
                };
                if (pkg.manifest.scripts[`pre${scriptName}`]) {
                    yield lifecycle_1.default(`pre${scriptName}`, pkg.manifest, lifecycleOpts);
                }
                yield lifecycle_1.default(scriptName, pkg.manifest, lifecycleOpts);
                if (pkg.manifest.scripts[`post${scriptName}`]) {
                    yield lifecycle_1.default(`post${scriptName}`, pkg.manifest, lifecycleOpts);
                }
            }
            catch (err) {
                logger_1.default.info(err);
                err['prefix'] = prefix; // tslint:disable-line:no-string-literal
                throw err;
            }
        }))));
    }
    if (scriptName !== 'test' && !hasCommand) {
        const err = new Error(`None of the packages has a "${scriptName}" script`);
        err['code'] = 'RECURSIVE_RUN_NO_SCRIPT'; // tslint:disable-line:no-string-literal
        throw err;
    }
});
//# sourceMappingURL=run.js.map