"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.effectAsyncM = void 0;
const Function_1 = require("../../Function");
const Q = __importStar(require("../../Queue"));
const T = __importStar(require("../_internal/effect"));
const M = __importStar(require("../_internal/managed"));
const Ref = __importStar(require("../_internal/ref"));
const Pull = __importStar(require("../Pull"));
const Take = __importStar(require("../Take"));
const chain_1 = require("./chain");
const managed_1 = require("./managed");
const repeatEffectChunkOption_1 = require("./repeatEffectChunkOption");
/**
 * 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 effectAsyncM(register, outputBuffer = 16) {
    return ((0, chain_1.chain)(repeatEffectChunkOption_1.repeatEffectChunkOption)((0, managed_1.managed)(M.map_(M.let_(M.bind_(M.tap_(M.bind_(M.bind_(M.do, "output", () => (T.toManaged(Q.makeBounded(outputBuffer)))), "runtime", () => (T.toManaged(T.runtime()))), ({ output, runtime }) => T.toManaged(register((k, cb) => (((x) => runtime.runCancel(x, cb))(T.chain_(Take.fromPull(k), (x) => Q.offer_(output, x))))))), "done", () => Ref.makeManagedRef(false)), "pull", ({ done, output }) => (T.chain_(done.get, (b) => b
        ? Pull.end
        : (T.onError_(T.chain_(Q.take(output), Take.done), () => (T.chain_(done.set(true), () => Q.shutdown(output)))))))), ({ pull }) => pull))));
}
exports.effectAsyncM = effectAsyncM;
//# sourceMappingURL=effectAsyncM.js.map