"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.asyncEffect = void 0;
// ets_tracing: off
const CS = __importStar(require("../../../../Cause"));
const T = __importStar(require("../../../../Effect"));
const E = __importStar(require("../../../../Either"));
const Function_1 = require("../../../../Function");
const M = __importStar(require("../../../../Managed"));
const O = __importStar(require("../../../../Option"));
const Q = __importStar(require("../../../../Queue"));
const CH = __importStar(require("../../Channel"));
const TK = __importStar(require("../../Take"));
const C = __importStar(require("../core"));
const Emit_1 = require("./_internal/Emit");
/**
 * Creates a stream from an asynchronous callback that can be called multiple times
 * The registration of the callback itself returns an effect. The optionality of the
 * error type `E` can be used to signal the end of the stream, by setting it to `None`.
 */
function asyncEffect(register, outputBuffer = 16) {
    return new C.Stream(CH.unwrapManaged((M.map_(M.tap_(M.bind_(M.bind_(M.do, "output", () => T.toManagedRelease_(Q.makeBounded(outputBuffer), Q.shutdown)), "runtime", () => M.runtime()), ({ output, runtime }) => T.toManaged(register((0, Emit_1.toEmit)((k) => {
        try {
            runtime.run(T.chain_(TK.fromPull(k), (_) => Q.offer_(output, _)));
        }
        catch (e) {
            if (CS.isFiberFailure(e)) {
                if (!CS.interrupted(e.cause)) {
                    throw e;
                }
            }
        }
    })))), ({ output }) => {
        const loop = CH.unwrap((T.foldCauseM_(T.chain_(Q.take(output), (_) => TK.done(_)), (maybeError) => {
            return T.as_(Q.shutdown(output), E.fold_(CS.failureOrCause(maybeError), (l) => O.fold_(l, () => CH.end(undefined), (failure) => CH.fail(failure)), (cause) => CH.failCause(cause)));
        }, (a) => T.succeed(CH.zipRight_(CH.write(a), loop)))));
        return loop;
    }))));
}
exports.asyncEffect = asyncEffect;
//# sourceMappingURL=asyncEffect.js.map