"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.collectAll = exports.BackPressureStrategy = void 0;
exports.collectAllDiscard = collectAllDiscard;
exports.collectAllPar = void 0;
exports.collectAllParDiscard = collectAllParDiscard;
exports.collectAllSuccesses = collectAllSuccesses;
exports.collectAllSuccessesPar = collectAllSuccessesPar;
exports.collectAllWithPar = exports.collectAllWith = void 0;
exports.createQueue = createQueue;
exports.fiberJoinAll = fiberJoinAll;
exports.fiberWaitAll = fiberWaitAll;
exports.forEachDiscard = exports.forEach = void 0;
exports.forEachExec = forEachExec;
exports.forEachParDiscard = exports.forEachPar = void 0;
exports.forEachParWithIndex = forEachParWithIndex;
exports.forEachWithIndex = forEachWithIndex;
exports.makeBackPressureStrategy = makeBackPressureStrategy;
exports.makeBoundedQueue = makeBoundedQueue;
exports.releaseMapReleaseAll = releaseMapReleaseAll;
exports.unsafeCreateQueue = unsafeCreateQueue;

var tsplus_module_1 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/collections/Chunk/definition"));

var tsplus_module_2 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Effect/operations/map"));

var tsplus_module_3 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Effect/operations/suspendSucceed"));

var tsplus_module_4 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Effect/operations/succeed"));

var tsplus_module_5 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Effect/operations/flatMap"));

var tsplus_module_6 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Effect/operations/unit"));

var tsplus_module_7 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Effect/operations/zipRight"));

var tsplus_module_8 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/data/Maybe/fold"));

var tsplus_module_9 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Effect/operations/parallelism"));

var tsplus_module_10 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/collections/Collection/functions"));

var tsplus_module_11 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Effect/operations/dieMessage"));

var tsplus_module_12 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/collections/Chunk/size"));

var tsplus_module_13 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/collections/Chunk/empty"));

var tsplus_module_14 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Effect/operations/succeedNow"));

var tsplus_module_15 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Effect/operations/tap"));

var tsplus_module_16 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/collections/Chunk/head"));

var tsplus_module_17 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Effect/operations/replicate"));

var tsplus_module_18 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/data/Function"));

var tsplus_module_19 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/collections/Chunk/zipWithIndex"));

var tsplus_module_20 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/FiberId/operations/none"));

var tsplus_module_21 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Deferred/operations/unsafeMake"));

var tsplus_module_22 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/data/AtomicNumber"));

var tsplus_module_23 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Exit/operations/collectAllPar"));

var tsplus_module_24 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Cause/operations/stripFailures"));

var tsplus_module_25 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Cause/definition"));

var tsplus_module_26 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Effect/operations/failCause"));

var tsplus_module_27 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Fiber/operations/interrupt"));

var tsplus_module_28 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Fiber/operations/inheritRefs"));

var tsplus_module_29 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Effect/operations/foldCauseEffect"));

var tsplus_module_30 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Effect/operations/failCauseNow"));

var tsplus_module_31 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Effect/operations/forkDaemon"));

var tsplus_module_32 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Effect/operations/transplant"));

var tsplus_module_33 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Effect/operations/interruption"));

var tsplus_module_34 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/collections/Chunk/collect"));

var tsplus_module_35 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Effect/operations/exit"));

var tsplus_module_36 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/data/Maybe/definition"));

var tsplus_module_37 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Effect/operations/done"));

var tsplus_module_38 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Fiber/operations/await"));

var tsplus_module_39 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/data/Tuple/make"));

var tsplus_module_40 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Exit/operations/unit"));

var tsplus_module_41 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Exit/operations/collectAll"));

var tsplus_module_42 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/data/Maybe/getOrElse"));

var tsplus_module_43 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Effect/operations/flatten"));

var tsplus_module_44 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/collections/mutable/MutableQueue/bounded"));

var tsplus_module_45 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/collections/mutable/MutableQueue/unbounded"));

var tsplus_module_46 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/data/AtomicBoolean"));

var tsplus_module_47 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Deferred/operations/make"));

var tsplus_module_48 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Effect/operations/whenEffect"));

var tsplus_module_49 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Effect/operations/suspendSucceedWith"));

var tsplus_module_50 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/collections/mutable/MutableQueue"));

var tsplus_module_51 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/collections/Chunk/single"));

var tsplus_module_52 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/collections/Chunk/splitAt"));

var tsplus_module_53 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/collections/Chunk/zip"));

var tsplus_module_54 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/collections/Chunk/forEach"));

var tsplus_module_55 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/collections/Chunk/isEmpty"));

var tsplus_module_56 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/collections/Chunk/filter"));

var tsplus_module_57 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/collections/Chunk/unsafeGet"));

var tsplus_module_58 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/collections/Chunk/drop"));

var tsplus_module_59 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@tsplus/stdlib/collections/Chunk/prepend"));

var tsplus_module_60 = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/core/io/Effect/operations/fiberId"));

var _definition4 = /*#__PURE__*/require("@effect/core/io/Queue/definition");

var _unsafeCompleteDeferred = /*#__PURE__*/require("@effect/core/io/Queue/operations/_internal/unsafeCompleteDeferred");

var _unsafeCompleteTakers = /*#__PURE__*/require("@effect/core/io/Queue/operations/_internal/unsafeCompleteTakers");

var _unsafeOfferAll = /*#__PURE__*/require("@effect/core/io/Queue/operations/_internal/unsafeOfferAll");

var _unsafePollAll = /*#__PURE__*/require("@effect/core/io/Queue/operations/_internal/unsafePollAll");

var _unsafePollN = /*#__PURE__*/require("@effect/core/io/Queue/operations/_internal/unsafePollN");

var _unsafeRemove = /*#__PURE__*/require("@effect/core/io/Queue/operations/_internal/unsafeRemove");

var _State = /*#__PURE__*/require("@effect/core/io/Scope/ReleaseMap/_internal/State");

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

const fileName_1 = "(@effect/core) _src/io/Effect/operations/excl-forEach.ts";
const forEach = forEach_1;
exports.forEach = forEach;
const forEachDiscard = forEachDiscard_1;
exports.forEachDiscard = forEachDiscard;
const forEachPar = forEachPar_1;
exports.forEachPar = forEachPar;
const forEachParDiscard = forEachParDiscard_1;
exports.forEachParDiscard = forEachParDiscard;
const collectAll = collectAll_1;
exports.collectAll = collectAll;
const collectAllPar = collectAllPar_1;
exports.collectAllPar = collectAllPar;
const collectAllWith = collectAllWith_1;
exports.collectAllWith = collectAllWith;
const collectAllWithPar = collectAllWithPar_1;
exports.collectAllWithPar = collectAllWithPar;

// -----------------------------------------------------------------------------
// forEach
// -----------------------------------------------------------------------------

/**
 * Applies the function `f` to each element of the `Collection<A>` and returns
 * the results in a new `Chunk<B>`.
 *
 * For a parallel version of this method, see `forEachPar`. If you do not need
 * the results, see `forEachDiscard` for a more efficient implementation.
 *
 * @tsplus static ets/Effect/Ops forEach
 */
function forEach_1(as, f, __tsplusTrace) {
  return tsplus_module_3.suspendSucceed(() => {
    const acc = [];
    return tsplus_module_2.map_(forEachDiscard_1(as, a => tsplus_module_2.map_(f(a), b => {
      acc.push(b);
    }, __tsplusTrace), __tsplusTrace), () => tsplus_module_1.from(acc), __tsplusTrace);
  }, __tsplusTrace);
} // -----------------------------------------------------------------------------
// forEachWithIndex
// -----------------------------------------------------------------------------

/**
 * Same as `forEach`, except that the function `f` is supplied
 * a second argument that corresponds to the index (starting from 0)
 * of the current element being iterated over.
 *
 * @tsplus static ets/Effect/Ops forEachWithIndex
 */


function forEachWithIndex(as, f, __tsplusTrace) {
  return tsplus_module_3.suspendSucceed(() => {
    let index = 0;
    const acc = [];
    return tsplus_module_2.map_(forEachDiscard_1(as, a => tsplus_module_2.map_(f(a, index), b => {
      acc.push(b);
      index++;
    }, __tsplusTrace), __tsplusTrace), () => tsplus_module_1.from(acc), __tsplusTrace);
  }, __tsplusTrace);
} // -----------------------------------------------------------------------------
// forEachDiscard
// -----------------------------------------------------------------------------

/**
 * Applies the function `f` to each element of the `Collection<A>` and runs
 * produced effects sequentially.
 *
 * Equivalent to `unit(forEach(as, f))`, but without the cost of building
 * the list of results.
 *
 * @tsplus static ets/Effect/Ops forEachDiscard
 */


function forEachDiscard_1(as, f, __tsplusTrace) {
  return tsplus_module_5.flatMap_(tsplus_module_4.succeed(as, __tsplusTrace), Collection => forEachDiscardLoop(Collection[Symbol.iterator](), f), __tsplusTrace);
}

function forEachDiscardLoop(iterator, f) {
  const next = iterator.next();
  return next.done ? tsplus_module_6.unit : tsplus_module_7.zipRight_(f(next.value), () => forEachDiscardLoop(iterator, f), fileName_1 + ":92:51");
} // -----------------------------------------------------------------------------
// forEachPar
// -----------------------------------------------------------------------------

/**
 * Applies the function `f` to each element of the `Collection<A>` in parallel,
 * and returns the results in a new `Chunk<B>`.
 *
 * For a sequential version of this method, see `forEach`.
 *
 * @tsplus static ets/Effect/Ops forEachPar
 */


function forEachPar_1(as, f, __tsplusTrace) {
  return tsplus_module_9.parallelismWith(option => tsplus_module_8.fold_(option, () => forEachParUnbounded(as, f, __tsplusTrace), n => forEachParN(as, n, f, __tsplusTrace)), __tsplusTrace);
}
/**
 * Applies the function `f` to each element of the `Collection<A>` in parallel,
 * and returns the results in a new `Chunk<B>`.
 */


function forEachParUnbounded(as, f, __tsplusTrace) {
  return tsplus_module_3.suspendSucceed(() => tsplus_module_5.flatMap_(tsplus_module_4.succeed(() => [], __tsplusTrace), array => tsplus_module_2.map_(forEachParUnboundedDiscard(() => tsplus_module_10.map_(as(), (a, n) => [a, n]), ([a, n]) => tsplus_module_5.flatMap_(tsplus_module_3.suspendSucceed(() => f(a), __tsplusTrace), b => tsplus_module_4.succeed(() => {
    array[n] = b;
  }, __tsplusTrace), __tsplusTrace), __tsplusTrace), () => tsplus_module_1.from(array), __tsplusTrace), __tsplusTrace), __tsplusTrace);
}

function forEachParN(as, n, f, __tsplusTrace) {
  return tsplus_module_3.suspendSucceed(() => {
    if (n < 1) {
      return tsplus_module_11.dieMessage(() => `Unexpected nonpositive value "${n}" passed to foreachParN`, __tsplusTrace);
    }

    const as0 = tsplus_module_1.from(as());
    const size = tsplus_module_12.size(as0);

    if (size === 0) {
      return tsplus_module_14.succeedNow(tsplus_module_13.empty(), __tsplusTrace);
    }

    function worker(queue, array) {
      return tsplus_module_5.flatMap_(tsplus_module_2.map_(queue.takeUpTo(1, __tsplusTrace), _ => tsplus_module_16.head(_), __tsplusTrace), _ => tsplus_module_8.fold_(_, () => tsplus_module_6.unit, ({
        tuple: [a, n]
      }) => tsplus_module_5.flatMap_(tsplus_module_15.tap_(f(a), b => tsplus_module_4.succeed(() => {
        array[n] = b;
      }, __tsplusTrace), __tsplusTrace), () => worker(queue, array), __tsplusTrace)), __tsplusTrace);
    }

    return tsplus_module_5.flatMap_(tsplus_module_4.succeed(() => new Array(size), __tsplusTrace), array => tsplus_module_5.flatMap_(makeBoundedQueue(size, __tsplusTrace), queue => tsplus_module_5.flatMap_(queue.offerAll(tsplus_module_19.zipWithIndex(as0), __tsplusTrace), () => tsplus_module_2.map_(forEachParUnboundedDiscard(() => tsplus_module_17.replicateNow_(worker(queue, array), n), tsplus_module_18.identity, __tsplusTrace), () => tsplus_module_1.from(array), __tsplusTrace), __tsplusTrace), __tsplusTrace), __tsplusTrace);
  }, __tsplusTrace);
} // -----------------------------------------------------------------------------
// forEachParWithIndex
// -----------------------------------------------------------------------------

/**
 * Same as `forEachPar_`, except that the function `f` is supplied
 * a second argument that corresponds to the index (starting from 0)
 * of the current element being iterated over.
 *
 * @tsplus static ets/Effect/Ops forEachParWithIndex
 */


function forEachParWithIndex(as, f, __tsplusTrace) {
  return tsplus_module_3.suspendSucceed(() => tsplus_module_5.flatMap_(tsplus_module_4.succeed(() => [], __tsplusTrace), array => tsplus_module_2.map_(forEachParDiscard_1(() => tsplus_module_10.map_(as(), (a, n) => [a, n]), ([a, n]) => tsplus_module_5.flatMap_(tsplus_module_3.suspendSucceed(() => f(a, n), __tsplusTrace), b => tsplus_module_4.succeed(() => {
    array[n] = b;
  }, __tsplusTrace), __tsplusTrace), __tsplusTrace), () => tsplus_module_1.from(array), __tsplusTrace), __tsplusTrace), __tsplusTrace);
} // -----------------------------------------------------------------------------
// forEachParDiscard
// -----------------------------------------------------------------------------

/**
 * Applies the function `f` to each element of the `Collection<A>` and runs
 * produced effects in parallel, discarding the results.
 *
 * For a sequential version of this method, see `forEachDiscard`.
 *
 * Optimized to avoid keeping full tree of effects, so that method could be
 * able to handle large input sequences. Additionally, interrupts all effects
 * on any failure.
 *
 * @tsplus static ets/Effect/Ops forEachParDiscard
 */


function forEachParDiscard_1(as, f, __tsplusTrace) {
  return tsplus_module_9.parallelismWith(option => tsplus_module_8.fold_(option, () => forEachParUnboundedDiscard(as, f, __tsplusTrace), n => forEachParNDiscard(as, n, f, __tsplusTrace)), __tsplusTrace);
}

function forEachParUnboundedDiscard(as, f, __tsplusTrace) {
  return tsplus_module_3.suspendSucceed(() => {
    const bs = tsplus_module_1.from(as());
    const size = tsplus_module_12.size(bs);

    if (size === 0) {
      return tsplus_module_6.unit;
    }

    return tsplus_module_33.uninterruptibleMask(({
      restore
    }) => {
      const deferred = tsplus_module_21.unsafeMake(tsplus_module_20.none);
      const ref = new tsplus_module_22.AtomicNumber(0);
      return tsplus_module_5.flatMap_(tsplus_module_32.transplant(graft => forEach_1(() => bs, a => tsplus_module_31.forkDaemon(graft(() => tsplus_module_29.foldCauseEffect_(restore(() => tsplus_module_3.suspendSucceed(() => f(a), __tsplusTrace), __tsplusTrace), cause => tsplus_module_7.zipRight_(deferred.fail(() => undefined, __tsplusTrace), () => tsplus_module_30.failCauseNow(cause, __tsplusTrace), __tsplusTrace), () => {
        if (ref.incrementAndGet() === size) {
          deferred.unsafeDone(tsplus_module_6.unit);
          return tsplus_module_6.unit;
        } else {
          return tsplus_module_6.unit;
        }
      }, __tsplusTrace), __tsplusTrace), __tsplusTrace), __tsplusTrace), __tsplusTrace), fibers => tsplus_module_29.foldCauseEffect_(restore(() => deferred.await(__tsplusTrace), __tsplusTrace), cause => tsplus_module_5.flatMap_(forEachParUnbounded(() => fibers, fiber => tsplus_module_27.interrupt(fiber, __tsplusTrace), __tsplusTrace), exits => {
        const collected = tsplus_module_23.collectAllPar(exits);

        if (collected._tag === "Some" && collected.value._tag === "Failure") {
          return tsplus_module_26.failCause(() => tsplus_module_25.combinePar(tsplus_module_24.stripFailures(cause), collected.value.cause), __tsplusTrace);
        }

        return tsplus_module_26.failCause(() => tsplus_module_24.stripFailures(cause), __tsplusTrace);
      }, __tsplusTrace), _ => forEachDiscard_1(() => fibers, fiber => tsplus_module_28.inheritRefs(fiber, __tsplusTrace), __tsplusTrace), __tsplusTrace), __tsplusTrace);
    }, __tsplusTrace);
  }, __tsplusTrace);
}

function forEachParNDiscard(as, n, f, __tsplusTrace) {
  return tsplus_module_3.suspendSucceed(() => {
    const as0 = as();
    const bs = tsplus_module_1.from(as0);
    const size = tsplus_module_12.size(bs);

    if (size === 0) {
      return tsplus_module_6.unit;
    }

    function worker(queue) {
      return tsplus_module_5.flatMap_(tsplus_module_2.map_(queue.takeUpTo(1, __tsplusTrace), chunk => tsplus_module_16.head(chunk), __tsplusTrace), option => tsplus_module_8.fold_(option, () => tsplus_module_6.unit, a => tsplus_module_5.flatMap_(f(a), () => worker(queue), __tsplusTrace)), __tsplusTrace);
    }

    return tsplus_module_5.flatMap_(makeBoundedQueue(size, __tsplusTrace), queue => tsplus_module_5.flatMap_(queue.offerAll(as0, __tsplusTrace), () => forEachParUnboundedDiscard(() => tsplus_module_17.replicateNow_(worker(queue), n), tsplus_module_18.identity, __tsplusTrace), __tsplusTrace), __tsplusTrace);
  }, __tsplusTrace);
} // -----------------------------------------------------------------------------
// forEachExec
// -----------------------------------------------------------------------------

/**
 * Applies the function `f` to each element of the `Collection<A>` and returns
 * the result in a new `Chunk<B>` using the specified execution strategy.
 *
 * @tsplus static ets/Effect/Ops forEachExec
 */


function forEachExec(as, f, strategy, __tsplusTrace) {
  return tsplus_module_3.suspendSucceed(() => {
    switch (strategy._tag) {
      case "Parallel":
        {
          return tsplus_module_9.withParallelismUnbounded(forEachPar_1(as, f, __tsplusTrace), __tsplusTrace);
        }

      case "ParallelN":
        {
          return tsplus_module_9.withParallelism_(forEachPar_1(as, f, __tsplusTrace), strategy.n, __tsplusTrace);
        }

      case "Sequential":
        {
          return forEach_1(as, f, __tsplusTrace);
        }
    }
  }, __tsplusTrace);
} // -----------------------------------------------------------------------------
// collectAll
// -----------------------------------------------------------------------------

/**
 * Evaluate each effect in the structure from left to right, and collect the
 * results. For a parallel version, see `collectAllPar`.
 *
 * @tsplus static ets/Effect/Ops collectAll
 */


function collectAll_1(as, __tsplusTrace) {
  return forEach_1(as, tsplus_module_18.identity, __tsplusTrace);
} // -----------------------------------------------------------------------------
// collectAllPar
// -----------------------------------------------------------------------------

/**
 * Evaluate each effect in the structure in parallel, and collect the
 * results. For a sequential version, see `collectAll`.
 *
 * @tsplus static ets/Effect/Ops collectAllPar
 */


function collectAllPar_1(as, __tsplusTrace) {
  return forEachPar_1(as, tsplus_module_18.identity, __tsplusTrace);
} // -----------------------------------------------------------------------------
// collectAllDiscard
// -----------------------------------------------------------------------------

/**
 * Evaluate each effect in the structure from left to right, and discard the
 * results. For a parallel version, see `collectAllParDiscard`.
 *
 * @tsplus static ets/Effect/Ops collectAllDiscard
 */


function collectAllDiscard(as, __tsplusTrace) {
  return forEachDiscard_1(as, tsplus_module_18.identity, __tsplusTrace);
} // -----------------------------------------------------------------------------
// collectAllParDiscard
// -----------------------------------------------------------------------------

/**
 * Evaluate each effect in the structure in parallel, and discard the
 * results. For a sequential version, see `collectAllDiscard`.
 *
 * @tsplus static ets/Effect/Ops collectAllParDiscard
 */


function collectAllParDiscard(as, __tsplusTrace) {
  return forEachParDiscard_1(as, tsplus_module_18.identity, __tsplusTrace);
} // -----------------------------------------------------------------------------
// collectAllWith
// -----------------------------------------------------------------------------

/**
 * Evaluate each effect in the structure with `collectAll`, and collect
 * the results with given partial function.
 *
 * @tsplus static ets/Effect/Ops collectAllWith
 */


function collectAllWith_1(as, pf, __tsplusTrace) {
  return tsplus_module_2.map_(collectAll_1(as, __tsplusTrace), chunk => tsplus_module_34.collect_(chunk, pf), __tsplusTrace);
} // -----------------------------------------------------------------------------
// collectAllWithPar
// -----------------------------------------------------------------------------

/**
 * Evaluate each effect in the structure with `collectAll`, and collect
 * the results with given partial function.
 *
 * @tsplus static ets/Effect/Ops collectAllWithPar
 */


function collectAllWithPar_1(as, pf, __tsplusTrace) {
  return tsplus_module_2.map_(collectAllPar_1(as, __tsplusTrace), chunk => tsplus_module_34.collect_(chunk, pf), __tsplusTrace);
} // -----------------------------------------------------------------------------
// collectAllSuccesses
// -----------------------------------------------------------------------------

/**
 * Evaluate and run each effect in the structure and collect discarding failed ones.
 *
 * @tsplus static ets/Effect/Ops collectAllSuccesses
 */


function collectAllSuccesses(as, __tsplusTrace) {
  return collectAllWith_1(() => tsplus_module_10.map_(as(), effect => tsplus_module_35.exit(effect, __tsplusTrace)), exit => exit._tag === "Success" ? tsplus_module_36.some(exit.value) : tsplus_module_36.none, __tsplusTrace);
} // -----------------------------------------------------------------------------
// collectAllSuccessesPar
// -----------------------------------------------------------------------------

/**
 * Evaluate and run each effect in the structure in parallel, and collect discarding failed ones.
 *
 * @tsplus static ets/Effect/Ops collectAllSuccessesPar
 */


function collectAllSuccessesPar(as, __tsplusTrace) {
  return collectAllWithPar_1(() => tsplus_module_10.map_(as(), effect => tsplus_module_35.exit(effect, __tsplusTrace)), exit => exit._tag === "Success" ? tsplus_module_36.some(exit.value) : tsplus_module_36.none, __tsplusTrace);
} // -----------------------------------------------------------------------------
// Fiber
// -----------------------------------------------------------------------------

/**
 * Joins all fibers, awaiting their _successful_ completion.
 * Attempting to join a fiber that has erred will result in
 * a catchable error, _if_ that error does not result from interruption.
 */


function fiberJoinAll(as, __tsplusTrace) {
  return tsplus_module_15.tap_(tsplus_module_5.flatMap_(fiberWaitAll(as, __tsplusTrace), exit => tsplus_module_37.done(() => exit, __tsplusTrace), __tsplusTrace), () => forEach_1(as, fiber => tsplus_module_28.inheritRefs(fiber, __tsplusTrace), __tsplusTrace), __tsplusTrace);
}
/**
 * Awaits on all fibers to be completed, successfully or not.
 */


function fiberWaitAll(as, __tsplusTrace) {
  return tsplus_module_35.exit(forEachPar_1(as, fiber => tsplus_module_5.flatMap_(tsplus_module_38._await(fiber, __tsplusTrace), exit => tsplus_module_37.done(() => exit, __tsplusTrace), __tsplusTrace), __tsplusTrace), __tsplusTrace);
} // -----------------------------------------------------------------------------
// ReleaseMap
// -----------------------------------------------------------------------------

/**
 * Releases all the finalizers in the releaseMap according to the ExecutionStrategy.
 */


function releaseMapReleaseAll(self, ex, execStrategy, __tsplusTrace) {
  return tsplus_module_43.flattenNow(self.ref.modify(s => {
    switch (s._tag) {
      case "Exited":
        {
          return tsplus_module_39.make(tsplus_module_6.unit, s);
        }

      case "Running":
        {
          switch (execStrategy._tag) {
            case "Sequential":
              {
                return tsplus_module_39.make(tsplus_module_5.flatMap_(forEach_1(() => Array.from(s.finalizers()).reverse(), ([_, f]) => tsplus_module_35.exit(s.update(f)(ex), __tsplusTrace), __tsplusTrace), results => tsplus_module_37.done(() => tsplus_module_42.getOrElse_(tsplus_module_41.collectAll(results), () => tsplus_module_40.unit), __tsplusTrace), __tsplusTrace), new _State.Exited(s.nextKey, ex, s.update));
              }

            case "Parallel":
              {
                return tsplus_module_39.make(tsplus_module_5.flatMap_(forEachPar_1(() => Array.from(s.finalizers()).reverse(), ([_, f]) => tsplus_module_35.exit(s.update(f)(ex), __tsplusTrace), __tsplusTrace), results => tsplus_module_37.done(() => tsplus_module_42.getOrElse_(tsplus_module_23.collectAllPar(results), () => tsplus_module_40.unit), __tsplusTrace), __tsplusTrace), new _State.Exited(s.nextKey, ex, s.update));
              }

            case "ParallelN":
              {
                return tsplus_module_39.make(tsplus_module_9.withParallelism_(tsplus_module_5.flatMap_(forEachPar_1(() => Array.from(s.finalizers()).reverse(), ([_, f]) => tsplus_module_35.exit(s.update(f)(ex), __tsplusTrace), __tsplusTrace), results => tsplus_module_37.done(() => tsplus_module_42.getOrElse_(tsplus_module_23.collectAllPar(results), () => tsplus_module_40.unit), __tsplusTrace), __tsplusTrace), execStrategy.n, __tsplusTrace), new _State.Exited(s.nextKey, ex, s.update));
              }
          }
        }
    }
  }, __tsplusTrace), __tsplusTrace);
} // -----------------------------------------------------------------------------
// ReleaseMap
// -----------------------------------------------------------------------------


function makeBoundedQueue(requestedCapacity, __tsplusTrace) {
  return tsplus_module_5.flatMap_(tsplus_module_4.succeed(() => tsplus_module_44.bounded(requestedCapacity), __tsplusTrace), queue => createQueue(queue, new BackPressureStrategy(), __tsplusTrace), __tsplusTrace);
}

function createQueue(queue, strategy, __tsplusTrace) {
  return tsplus_module_2.map_(tsplus_module_47.make(__tsplusTrace), deferred => unsafeCreateQueue(queue, tsplus_module_45.unbounded(), deferred, new tsplus_module_46.AtomicBoolean(false), strategy), __tsplusTrace);
}

const UnsafeQueueProto = { ..._definition4.QueueProto,

  get capacity() {
    return this.queue.capacity;
  },

  get size() {
    return tsplus_module_3.suspendSucceed(() => this.shutdownFlag.get ? tsplus_module_33.interrupt : tsplus_module_14.succeedNow(this.queue.size - this.takers.size + this.strategy.surplusSize, fileName_1 + ":639:28"), fileName_1 + ":636:33");
  },

  get awaitShutdown() {
    return this.shutdownHook.await(fileName_1 + ":646:62");
  },

  get isShutdown() {
    return tsplus_module_4.succeed(() => this.shutdownFlag.get, fileName_1 + ":649:26");
  },

  get shutdown() {
    return tsplus_module_33.uninterruptible(tsplus_module_49.suspendSucceedWith((_, fiberId) => {
      ;
      this.shutdownFlag.set(true);
      return tsplus_module_6.unit_(tsplus_module_48.whenEffect(() => this.shutdownHook.succeed(() => undefined, fileName_1 + ":655:61"), () => tsplus_module_7.zipRight_(forEachParDiscard_1(() => (0, _unsafePollAll.unsafePollAll)(this.takers), deferred => deferred.interruptAs(() => fiberId, fileName_1 + ":661:47"), fileName_1 + ":657:35"), () => this.strategy.shutdown, fileName_1 + ":662:14"), fileName_1 + ":654:31"), fileName_1 + ":663:13");
    }, fileName_1 + ":652:37"), fileName_1 + ":664:23");
  },

  offer(a, __tsplusTrace) {
    return tsplus_module_3.suspendSucceed(() => {
      if (this.shutdownFlag.get) {
        return tsplus_module_33.interrupt;
      }

      let noRemaining;

      if (this.queue.isEmpty) {
        const taker = this.takers.poll(tsplus_module_50.EmptyMutableQueue);

        if (taker !== tsplus_module_50.EmptyMutableQueue) {
          (0, _unsafeCompleteDeferred.unsafeCompleteDeferred)(taker, a);
          noRemaining = true;
        } else {
          noRemaining = false;
        }
      } else {
        noRemaining = false;
      }

      if (noRemaining) {
        return tsplus_module_14.succeedNow(true, fileName_1 + ":684:33");
      } // Not enough takers, offer to the queue


      const succeeded = this.queue.offer(a);
      (0, _unsafeCompleteTakers.unsafeCompleteTakers)(this.strategy, this.queue, this.takers);
      return succeeded ? tsplus_module_14.succeedNow(true, fileName_1 + ":694:28") : this.strategy.handleSurplus(tsplus_module_51.single(a), this.queue, this.takers, this.shutdownFlag, fileName_1 + ":695:61");
    }, fileName_1 + ":667:33");
  },

  offerAll(as, __tsplusTrace) {
    return tsplus_module_3.suspendSucceed(() => {
      if (this.shutdownFlag.get) {
        return tsplus_module_33.interrupt;
      }

      const as0 = tsplus_module_1.from(as);
      const pTakers = this.queue.isEmpty ? (0, _unsafePollN.unsafePollN)(this.takers, tsplus_module_12.size(as0)) : tsplus_module_13.empty();
      const {
        tuple: [forTakers, remaining]
      } = tsplus_module_52.splitAt_(as0, tsplus_module_12.size(pTakers));
      tsplus_module_54.forEach_(tsplus_module_53.zip_(pTakers, forTakers), ({
        tuple: [taker, item]
      }) => {
        (0, _unsafeCompleteDeferred.unsafeCompleteDeferred)(taker, item);
      });

      if (tsplus_module_55.isEmpty(remaining)) {
        return tsplus_module_14.succeedNow(true, fileName_1 + ":722:33");
      } // Not enough takers, offer to the queue


      const surplus = (0, _unsafeOfferAll.unsafeOfferAll)(this.queue, remaining);
      (0, _unsafeCompleteTakers.unsafeCompleteTakers)(this.strategy, this.queue, this.takers);
      return tsplus_module_55.isEmpty(surplus) ? tsplus_module_14.succeedNow(true, fileName_1 + ":732:28") : this.strategy.handleSurplus(surplus, this.queue, this.takers, this.shutdownFlag, fileName_1 + ":733:61");
    }, fileName_1 + ":704:33");
  },

  get take() {
    return tsplus_module_49.suspendSucceedWith((_, fiberId) => {
      if (this.shutdownFlag.get) {
        return tsplus_module_33.interrupt;
      }

      const item = this.queue.poll(tsplus_module_50.EmptyMutableQueue);

      if (item !== tsplus_module_50.EmptyMutableQueue) {
        ;
        this.strategy.unsafeOnQueueEmptySpace(this.queue, this.takers);
        return tsplus_module_14.succeedNow(item, fileName_1 + ":752:33");
      } else {
        // Add the deferred to takers, then:
        // - Try to take again in case a value was added since
        // - Wait for the deferred to be completed
        // - Clean up resources in case of interruption
        const deferred = tsplus_module_21.unsafeMake(fiberId);
        return tsplus_module_33.onInterrupt_(tsplus_module_3.suspendSucceed(() => {
          ;
          this.takers.offer(deferred);
          (0, _unsafeCompleteTakers.unsafeCompleteTakers)(this.strategy, this.queue, this.takers);
          return this.shutdownFlag.get ? tsplus_module_33.interrupt : deferred.await(fileName_1 + ":766:94");
        }, fileName_1 + ":759:37"), () => {
          return tsplus_module_4.succeed(() => (0, _unsafeRemove.unsafeRemove)(this.takers, deferred), fileName_1 + ":768:32");
        }, fileName_1 + ":767:23");
      }
    }, fileName_1 + ":742:37");
  },

  get takeAll() {
    return tsplus_module_3.suspendSucceed(() => this.shutdownFlag.get ? tsplus_module_33.interrupt : tsplus_module_4.succeed(() => {
      const as = (0, _unsafePollAll.unsafePollAll)(this.queue);
      this.strategy.unsafeOnQueueEmptySpace(this.queue, this.takers);
      return as;
    }, fileName_1 + ":777:25"), fileName_1 + ":774:33");
  },

  takeUpTo(n, __tsplusTrace) {
    return tsplus_module_3.suspendSucceed(() => this.shutdownFlag.get ? tsplus_module_33.interrupt : tsplus_module_4.succeed(() => {
      const as = (0, _unsafePollN.unsafePollN)(this.queue, n);
      this.strategy.unsafeOnQueueEmptySpace(this.queue, this.takers);
      return as;
    }, fileName_1 + ":791:25"), fileName_1 + ":788:33");
  }

};

function unsafeCreateQueue(queue, takers, shutdownHook, shutdownFlag, strategy) {
  return Object.setPrototypeOf({
    queue,
    takers,
    shutdownHook,
    shutdownFlag,
    strategy
  }, UnsafeQueueProto);
}

function makeBackPressureStrategy() {
  return new BackPressureStrategy();
}

class BackPressureStrategy {
  constructor() {
    /**
     * - `A` is an item to add
     * - `Deferred<never, boolean>` is the deferred completing the whole `offerAll`
     * - `boolean` indicates if it's the last item to offer (deferred should be
     *    completed once this item is added)
     */
    this.putters = tsplus_module_45.unbounded();
  }

  handleSurplus(as, queue, takers, isShutdown, __tsplusTrace) {
    return tsplus_module_49.suspendSucceedWith((_, fiberId) => {
      const deferred = tsplus_module_21.unsafeMake(fiberId);
      return tsplus_module_33.onInterrupt_(tsplus_module_3.suspendSucceed(() => {
        this.unsafeOffer(as, deferred);
        this.unsafeOnQueueEmptySpace(queue, takers);
        (0, _unsafeCompleteTakers.unsafeCompleteTakers)(this, queue, takers);
        return isShutdown.get ? tsplus_module_33.interrupt : deferred.await(fileName_1 + ":846:66");
      }, fileName_1 + ":842:35"), () => tsplus_module_4.succeed(() => this.unsafeRemove(deferred), fileName_1 + ":847:42"), fileName_1 + ":847:21");
    }, fileName_1 + ":839:37");
  }

  unsafeRemove(deferred) {
    (0, _unsafeOfferAll.unsafeOfferAll)(this.putters, tsplus_module_56.filter_((0, _unsafePollAll.unsafePollAll)(this.putters), ({
      tuple: [, _]
    }) => _ !== deferred));
  }

  unsafeOffer(as, deferred) {
    let bs = as;

    while (tsplus_module_12.size(bs) > 0) {
      const head = tsplus_module_57.unsafeGet_(bs, 0);
      bs = tsplus_module_58.drop_(bs, 1);

      if (tsplus_module_12.size(bs) === 0) {
        this.putters.offer(tsplus_module_39.make(head, deferred, true));
      } else {
        this.putters.offer(tsplus_module_39.make(head, deferred, false));
      }
    }
  }

  unsafeOnQueueEmptySpace(queue, takers) {
    let keepPolling = true;

    while (keepPolling && !queue.isFull) {
      const putter = this.putters.poll(tsplus_module_50.EmptyMutableQueue);

      if (putter !== tsplus_module_50.EmptyMutableQueue) {
        const offered = queue.offer(putter.get(0));

        if (offered && putter.get(2)) {
          (0, _unsafeCompleteDeferred.unsafeCompleteDeferred)(putter.get(1), true);
        } else if (!offered) {
          (0, _unsafeOfferAll.unsafeOfferAll)(this.putters, tsplus_module_59.prepend_((0, _unsafePollAll.unsafePollAll)(this.putters), putter));
        }

        (0, _unsafeCompleteTakers.unsafeCompleteTakers)(this, queue, takers);
      } else {
        keepPolling = false;
      }
    }
  }

  get surplusSize() {
    return this.putters.size;
  }

  get shutdown() {
    return tsplus_module_5.flatMap_(tsplus_module_60.fiberId, fiberId => tsplus_module_5.flatMap_(tsplus_module_4.succeed(() => (0, _unsafePollAll.unsafePollAll)(this.putters), fileName_1 + ":905:39"), putters => tsplus_module_2.map_(forEachPar_1(() => putters, ({
      tuple: [_, promise, lastItem]
    }) => lastItem ? promise.interruptAs(() => fiberId, fileName_1 + ":908:78") : tsplus_module_6.unit, fileName_1 + ":906:26"), () => void 0, fileName_1 + ":906:8"), fileName_1 + ":905:24"), fileName_1 + ":904:24");
  }

}

exports.BackPressureStrategy = BackPressureStrategy;
//# sourceMappingURL=excl-forEach.js.map