"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const run_groups_1 = require("run-groups");
const runLifecycleHook_1 = require("./runLifecycleHook");
async function runLifecycleHooksConcurrently(stages, importers, childConcurrency, opts) {
    const importersByBuildIndex = new Map();
    for (const importer of importers) {
        if (!importersByBuildIndex.has(importer.buildIndex)) {
            importersByBuildIndex.set(importer.buildIndex, [importer]);
        }
        else {
            importersByBuildIndex.get(importer.buildIndex).push(importer);
        }
    }
    const sortedBuildIndexes = Array.from(importersByBuildIndex.keys()).sort();
    const groups = sortedBuildIndexes.map((buildIndex) => {
        const importers = importersByBuildIndex.get(buildIndex);
        return importers.map((importer) => async () => {
            const runLifecycleHookOpts = {
                depPath: importer.prefix,
                pkgRoot: importer.prefix,
                rawNpmConfig: opts.rawNpmConfig,
                rootNodeModulesDir: importer.modulesDir,
                stdio: opts.stdio,
                unsafePerm: opts.unsafePerm,
            };
            for (const stage of stages) {
                if (!importer.pkg.scripts || !importer.pkg.scripts[stage])
                    continue;
                await runLifecycleHook_1.default(stage, importer.pkg, runLifecycleHookOpts);
            }
        });
    });
    await run_groups_1.default(childConcurrency, groups);
}
exports.default = runLifecycleHooksConcurrently;
//# sourceMappingURL=runLifecycleHooksConcurrently.js.map