import * as tsplus_module_1 from "@effect/core/stream/Channel/operations/failCause";
import * as tsplus_module_2 from "@effect/core/stream/Channel/operations/unit";
import * as tsplus_module_3 from "@effect/core/stream/Channel/operations/readWithCause";
import * as tsplus_module_4 from "@effect/core/stream/Channel/operations/pipeTo";
import * as tsplus_module_5 from "@effect/core/io/Exit/operations/isSuccess";
import * as tsplus_module_6 from "@tsplus/stdlib/collections/Chunk/splitWhere";
import * as tsplus_module_7 from "@effect/core/io/Cause/operations/flipCauseMaybe";
import * as tsplus_module_8 from "@tsplus/stdlib/data/Maybe/fold";
import * as tsplus_module_9 from "@effect/core/io/Exit/operations/fold";
import * as tsplus_module_10 from "@tsplus/stdlib/collections/Chunk/head";
import * as tsplus_module_11 from "@tsplus/stdlib/data/Maybe/definition";
import * as tsplus_module_12 from "@tsplus/stdlib/collections/Chunk/collect";
import * as tsplus_module_13 from "@effect/core/stream/Channel/operations/write";
import * as tsplus_module_14 from "@effect/core/stream/Channel/operations/zipRight";
import { concreteStream, StreamInternal } from "@effect/core/stream/Stream/operations/_internal/StreamInternal";
/**
 * Unwraps `Exit` values that also signify end-of-stream by failing with `None`.
 *
 * For `Exit<E, A>` values that do not signal end-of-stream, prefer:
 *
 * ```typescript
 * stream.mapEffect((exit) => Effect.done(exit))
 * ```
 *
 * @tsplus fluent ets/Stream flattenExitMaybe
 */

export function flattenExitMaybe(self, __tsplusTrace) {
  const process = tsplus_module_3.readWithCause(chunk => processChunk(chunk, process), cause => tsplus_module_1.failCause(() => cause), () => tsplus_module_2.unit);
  void 0;
  return new StreamInternal(tsplus_module_4.pipeTo_(self.channel, () => process));
}

function processChunk(chunk, cont) {
  const {
    tuple: [toEmit, rest]
  } = tsplus_module_6.splitWhere_(chunk, exit => !tsplus_module_5.isSuccess(exit));
  const next = tsplus_module_8.fold_(tsplus_module_10.head(rest), () => cont, exit => tsplus_module_9.fold_(exit, cause => tsplus_module_8.fold_(tsplus_module_7.flipCauseMaybe(cause), () => tsplus_module_2.unit, cause => tsplus_module_1.failCause(() => cause)), () => tsplus_module_2.unit));
  return tsplus_module_14.zipRight_(tsplus_module_13.write(() => tsplus_module_12.collect_(toEmit, exit => tsplus_module_5.isSuccess(exit) ? tsplus_module_11.some(exit.value) : tsplus_module_11.none)), () => next);
}
//# sourceMappingURL=flattenExitMaybe.mjs.map