"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.flattenExitOption = void 0;
// ets_tracing: off
const CS = __importStar(require("../../../../Cause"));
const CK = __importStar(require("../../../../Collections/Immutable/Chunk"));
const Ex = __importStar(require("../../../../Exit"));
const O = __importStar(require("../../../../Option"));
const CH = __importStar(require("../../Channel"));
const C = __importStar(require("../core"));
/**
 * 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:
 */
function flattenExitOption(self) {
    const processChunk = (chunk, cont) => {
        const { tuple: [toEmit, rest] } = CK.splitWhere_(chunk, (_) => !Ex.succeeded(_));
        const next = O.fold_(CK.head(rest), () => cont, Ex.fold((cause) => O.fold_(CS.flipCauseOption(cause), () => CH.end(undefined), (cause) => CH.failCause(cause)), () => CH.end(undefined)));
        return CH.zipRight_(CH.write(CK.filterMap_(toEmit, Ex.fold(() => O.none, (a) => O.some(a)))), next);
    };
    const process = CH.readWithCause((chunk) => processChunk(chunk, process), (cause) => CH.failCause(cause), (_) => CH.end(undefined));
    return new C.Stream(self.channel[">>>"](process));
}
exports.flattenExitOption = flattenExitOption;
//# sourceMappingURL=flattenExitOption.js.map