veffect
Version:
powerful TypeScript validation library built on the robust foundation of Effect combining exceptional type safety, high performance, and developer experience. Taking inspiration from Effect's functional principles, VEffect delivers a balanced approach tha
717 lines (716 loc) • 154 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.fromIterableEffect = exports.fromIterable = exports.fromEffectOption = exports.fromEffect = exports.fromChunks = exports.fromChunkQueue = exports.fromChunkPubSub = exports.fromChunk = exports.fromChannel = exports.fromAsyncIterable = exports.forever = exports.flattenTake = exports.flattenIterables = exports.flattenExitOption = exports.flattenEffect = exports.flattenChunks = exports.flatten = exports.flatMap = exports.findEffect = exports.find = exports.finalizer = exports.filterMapWhileEffect = exports.filterMapWhile = exports.filterMapEffect = exports.filterMap = exports.filterEffect = exports.filter = exports.failSync = exports.failCauseSync = exports.failCause = exports.fail = exports.execute = exports.ensuringWith = exports.ensuring = exports.encodeText = exports.empty = exports.either = exports.dropWhileEffect = exports.dropWhile = exports.dropUntilEffect = exports.dropUntil = exports.dropRight = exports.drop = exports.drainFork = exports.drain = exports.distributedWithDynamicCallback = exports.distributedWithDynamic = exports.distributedWith = exports.dieSync = exports.dieMessage = exports.die = exports.decodeText = exports.debounce = exports.crossWith = exports.crossRight = exports.crossLeft = exports.cross = exports.contextWithStream = exports.contextWithEffect = exports.contextWith = exports.context = exports.concatAll = exports.concat = exports.combineChunks = exports.combine = exports.chunksWith = exports.chunks = exports.channelToStream = exports.changesWithEffect = exports.changesWith = exports.changes = exports.catchTags = exports.catchTag = exports.catchSomeCause = exports.catchSome = exports.catchAllCause = exports.catchAll = exports.bufferChunks = exports.buffer = exports.broadcastedQueuesDynamic = exports.broadcastedQueues = exports.broadcastDynamic = exports.broadcast = exports.branchAfter = exports.bindTo = exports.bind = exports.asyncScoped = exports.asyncEffect = exports.as = exports.aggregateWithinEither = exports.aggregateWithin = exports.aggregate = exports.acquireRelease = exports.accumulateChunks = exports.accumulate = exports._async = exports.StreamTypeId = exports.StreamImpl = exports.Do = exports.DefaultChunkSize = void 0;
exports.runFoldScoped = exports.runFoldEffect = exports.runFold = exports.runDrain = exports.runCount = exports.runCollect = exports.run = exports.retry = exports.repeatWith = exports.repeatValue = exports.repeatElementsWith = exports.repeatElements = exports.repeatEither = exports.repeatEffectWithSchedule = exports.repeatEffectOption = exports.repeatEffectChunkOption = exports.repeatEffectChunk = exports.repeatEffect = exports.repeat = exports.refineOrDieWith = exports.refineOrDie = exports.rechunk = exports.range = exports.provideSomeLayer = exports.provideServiceStream = exports.provideServiceEffect = exports.provideService = exports.provideLayer = exports.provideContext = exports.prepend = exports.pipeThroughChannelOrFail = exports.pipeThroughChannel = exports.pipeThrough = exports.peel = exports.partitionEither = exports.partition = exports.paginateEffect = exports.paginateChunkEffect = exports.paginateChunk = exports.paginate = exports.orElseSucceed = exports.orElseIfEmptyStream = exports.orElseIfEmptyChunk = exports.orElseIfEmpty = exports.orElseFail = exports.orElseEither = exports.orElse = exports.orDieWith = exports.orDie = exports.onError = exports.onDone = exports.never = exports.mkString = exports.mergeWith = exports.mergeRight = exports.mergeLeft = exports.mergeEither = exports.mergeAll = exports.merge = exports.matchConcurrency = exports.mapInputContext = exports.mapErrorCause = exports.mapError = exports.mapEffectSequential = exports.mapEffectPar = exports.mapConcatEffect = exports.mapConcatChunkEffect = exports.mapConcatChunk = exports.mapConcat = exports.mapChunksEffect = exports.mapChunks = exports.mapBoth = exports.mapAccumEffect = exports.mapAccum = exports.map = exports.make = exports.let_ = exports.iterate = exports.isStream = exports.intersperseAffixes = exports.intersperse = exports.interruptWhenDeferred = exports.interruptWhen = exports.interruptAfter = exports.interleaveWith = exports.interleave = exports.identityStream = exports.haltWhenDeferred = exports.haltWhen = exports.haltAfter = exports.groupedWithin = exports.grouped = exports.groupAdjacentBy = exports.fromSchedule = exports.fromReadableStreamByob = exports.fromReadableStream = exports.fromQueue = exports.fromPull = exports.fromPubSub = exports.fromIteratorSucceed = void 0;
exports.zipWithPreviousAndNext = exports.zipWithPrevious = exports.zipWithNext = exports.zipWithIndex = exports.zipWithChunks = exports.zipWith = exports.zipRight = exports.zipLeft = exports.zipLatestWith = exports.zipLatest = exports.zipFlatten = exports.zipAllWith = exports.zipAllSortedByKeyWith = exports.zipAllSortedByKeyRight = exports.zipAllSortedByKeyLeft = exports.zipAllSortedByKey = exports.zipAllRight = exports.zipAllLeft = exports.zipAll = exports.zip = exports.withSpan = exports.whenEffect = exports.whenCaseEffect = exports.whenCase = exports.when = exports.updateService = exports.unwrapScoped = exports.unwrap = exports.unit = exports.unfoldEffect = exports.unfoldChunkEffect = exports.unfoldChunk = exports.unfold = exports.transduce = exports.toReadableStream = exports.toQueueOfElements = exports.toQueue = exports.toPull = exports.toPubSub = exports.toChannel = exports.timeoutTo = exports.timeoutFailCause = exports.timeoutFail = exports.timeout = exports.tick = exports.throttleEffect = exports.throttle = exports.tapSink = exports.tapErrorCause = exports.tapError = exports.tapBoth = exports.tap = exports.takeWhile = exports.takeUntilEffect = exports.takeUntil = exports.takeRight = exports.take = exports.sync = exports.suspend = exports.succeed = exports.splitOnChunk = exports.splitLines = exports.split = exports.someOrFail = exports.someOrElse = exports.some = exports.slidingSize = exports.sliding = exports.scoped = exports.scheduleWith = exports.schedule = exports.scanReduceEffect = exports.scanReduce = exports.scanEffect = exports.scan = exports.runSum = exports.runScoped = exports.runLast = exports.runIntoQueueScoped = exports.runIntoQueueElementsScoped = exports.runIntoQueue = exports.runIntoPubSubScoped = exports.runIntoPubSub = exports.runHead = exports.runForEachWhileScoped = exports.runForEachWhile = exports.runForEachScoped = exports.runForEachChunkScoped = exports.runForEachChunk = exports.runForEach = exports.runFoldWhileScopedEffect = exports.runFoldWhileScoped = exports.runFoldWhileEffect = exports.runFoldWhile = exports.runFoldScopedEffect = void 0;
var Cause = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("../Cause.js"));
var Chunk = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("../Chunk.js"));
var Clock = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("../Clock.js"));
var Context = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("../Context.js"));
var Deferred = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("../Deferred.js"));
var Duration = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("../Duration.js"));
var Effect = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("../Effect.js"));
var Either = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("../Either.js"));
var Equal = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("../Equal.js"));
var Exit = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("../Exit.js"));
var Fiber = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("../Fiber.js"));
var _Function = /*#__PURE__*/require("../Function.js");
var Layer = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("../Layer.js"));
var MergeDecision = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("../MergeDecision.js"));
var Option = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("../Option.js"));
var _Pipeable = /*#__PURE__*/require("../Pipeable.js");
var _Predicate = /*#__PURE__*/require("../Predicate.js");
var PubSub = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("../PubSub.js"));
var Queue = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("../Queue.js"));
var Ref = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("../Ref.js"));
var Runtime = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("../Runtime.js"));
var Schedule = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("../Schedule.js"));
var Scope = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("../Scope.js"));
var HaltStrategy = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("../StreamHaltStrategy.js"));
var Tuple = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("../Tuple.js"));
var channel = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("./channel.js"));
var channelExecutor = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("./channel/channelExecutor.js"));
var MergeStrategy = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("./channel/mergeStrategy.js"));
var singleProducerAsyncInput = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("./channel/singleProducerAsyncInput.js"));
var core = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("./core-stream.js"));
var _ringBuffer = /*#__PURE__*/require("./ringBuffer.js");
var _sink = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("./sink.js"));
var DebounceState = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("./stream/debounceState.js"));
var emit = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("./stream/emit.js"));
var haltStrategy = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("./stream/haltStrategy.js"));
var Handoff = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("./stream/handoff.js"));
var HandoffSignal = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("./stream/handoffSignal.js"));
var pull = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("./stream/pull.js"));
var SinkEndReason = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("./stream/sinkEndReason.js"));
var ZipAllState = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("./stream/zipAllState.js"));
var ZipChunksState = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("./stream/zipChunksState.js"));
var InternalTake = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("./take.js"));
function _getRequireWildcardCache(e) {
if ("function" != typeof WeakMap) return null;
var r = new WeakMap(),
t = new WeakMap();
return (_getRequireWildcardCache = function (e) {
return e ? t : r;
})(e);
}
function _interopRequireWildcard(e, r) {
if (!r && e && e.__esModule) return e;
if (null === e || "object" != typeof e && "function" != typeof e) return {
default: e
};
var t = _getRequireWildcardCache(r);
if (t && t.has(e)) return t.get(e);
var n = {
__proto__: null
},
a = Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) {
var i = a ? Object.getOwnPropertyDescriptor(e, u) : null;
i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u];
}
return n.default = e, t && t.set(e, n), n;
}
/** @internal */
const StreamSymbolKey = "effect/Stream";
/** @internal */
const StreamTypeId = exports.StreamTypeId = /*#__PURE__*/Symbol.for(StreamSymbolKey);
/** @internal */
const streamVariance = {
_R: _ => _,
_E: _ => _,
_A: _ => _
};
/** @internal */
class StreamImpl {
channel;
[StreamTypeId] = streamVariance;
constructor(channel) {
this.channel = channel;
}
pipe() {
return (0, _Pipeable.pipeArguments)(this, arguments);
}
}
/** @internal */
exports.StreamImpl = StreamImpl;
const isStream = u => (0, _Predicate.hasProperty)(u, StreamTypeId) || Effect.isEffect(u);
/** @internal */
exports.isStream = isStream;
const DefaultChunkSize = exports.DefaultChunkSize = 4096;
/** @internal */
const accumulate = self => chunks(accumulateChunks(self));
/** @internal */
exports.accumulate = accumulate;
const accumulateChunks = self => {
const accumulator = s => core.readWith({
onInput: input => {
const next = Chunk.appendAll(s, input);
return core.flatMap(core.write(next), () => accumulator(next));
},
onFailure: core.fail,
onDone: () => core.unit
});
return new StreamImpl(core.pipeTo(toChannel(self), accumulator(Chunk.empty())));
};
/** @internal */
exports.accumulateChunks = accumulateChunks;
const acquireRelease = (acquire, release) => scoped(Effect.acquireRelease(acquire, release));
/** @internal */
exports.acquireRelease = acquireRelease;
const aggregate = exports.aggregate = /*#__PURE__*/(0, _Function.dual)(2, (self, sink) => aggregateWithin(self, sink, Schedule.forever));
/** @internal */
const aggregateWithin = exports.aggregateWithin = /*#__PURE__*/(0, _Function.dual)(3, (self, sink, schedule) => filterMap(aggregateWithinEither(self, sink, schedule), _ => Either.match(_, {
onLeft: Option.none,
onRight: Option.some
})));
/** @internal */
const aggregateWithinEither = exports.aggregateWithinEither = /*#__PURE__*/(0, _Function.dual)(3, (self, sink, schedule) => {
const layer = Effect.all([Handoff.make(), Ref.make(SinkEndReason.ScheduleEnd), Ref.make(Chunk.empty()), Schedule.driver(schedule), Ref.make(false), Ref.make(false)]);
return (0, _Function.pipe)(fromEffect(layer), flatMap(([handoff, sinkEndReason, sinkLeftovers, scheduleDriver, consumed, endAfterEmit]) => {
const handoffProducer = core.readWithCause({
onInput: input => core.flatMap(core.fromEffect((0, _Function.pipe)(handoff, Handoff.offer(HandoffSignal.emit(input)), Effect.when(() => Chunk.isNonEmpty(input)))), () => handoffProducer),
onFailure: cause => core.fromEffect(Handoff.offer(handoff, HandoffSignal.halt(cause))),
onDone: () => core.fromEffect(Handoff.offer(handoff, HandoffSignal.end(SinkEndReason.UpstreamEnd)))
});
const handoffConsumer = (0, _Function.pipe)(Ref.getAndSet(sinkLeftovers, Chunk.empty()), Effect.flatMap(leftovers => {
if (Chunk.isNonEmpty(leftovers)) {
return (0, _Function.pipe)(Ref.set(consumed, true), Effect.zipRight(Effect.succeed((0, _Function.pipe)(core.write(leftovers), core.flatMap(() => handoffConsumer)))));
}
return (0, _Function.pipe)(Handoff.take(handoff), Effect.map(signal => {
switch (signal._tag) {
case HandoffSignal.OP_EMIT:
{
return (0, _Function.pipe)(core.fromEffect(Ref.set(consumed, true)), channel.zipRight(core.write(signal.elements)), channel.zipRight(core.fromEffect(Ref.get(endAfterEmit))), core.flatMap(bool => bool ? core.unit : handoffConsumer));
}
case HandoffSignal.OP_HALT:
{
return core.failCause(signal.cause);
}
case HandoffSignal.OP_END:
{
if (signal.reason._tag === SinkEndReason.OP_SCHEDULE_END) {
return (0, _Function.pipe)(Ref.get(consumed), Effect.map(bool => bool ? core.fromEffect((0, _Function.pipe)(Ref.set(sinkEndReason, SinkEndReason.ScheduleEnd), Effect.zipRight(Ref.set(endAfterEmit, true)))) : (0, _Function.pipe)(core.fromEffect((0, _Function.pipe)(Ref.set(sinkEndReason, SinkEndReason.ScheduleEnd), Effect.zipRight(Ref.set(endAfterEmit, true)))), core.flatMap(() => handoffConsumer))), channel.unwrap);
}
return (0, _Function.pipe)(Ref.set(sinkEndReason, signal.reason), Effect.zipRight(Ref.set(endAfterEmit, true)), core.fromEffect);
}
}
}));
}), channel.unwrap);
const timeout = lastB => scheduleDriver.next(lastB);
const scheduledAggregator = (sinkFiber, scheduleFiber, scope) => {
const forkSink = (0, _Function.pipe)(Ref.set(consumed, false), Effect.zipRight(Ref.set(endAfterEmit, false)), Effect.zipRight((0, _Function.pipe)(handoffConsumer, channel.pipeToOrFail(_sink.toChannel(sink)), core.collectElements, channelExecutor.run, Effect.forkIn(scope))));
const handleSide = (leftovers, b, c) => (0, _Function.pipe)(Ref.set(sinkLeftovers, Chunk.flatten(leftovers)), Effect.zipRight(Effect.map(Ref.get(sinkEndReason), reason => {
switch (reason._tag) {
case SinkEndReason.OP_SCHEDULE_END:
{
return (0, _Function.pipe)(Effect.all([Ref.get(consumed), forkSink, (0, _Function.pipe)(timeout(Option.some(b)), Effect.forkIn(scope))]), Effect.map(([wasConsumed, sinkFiber, scheduleFiber]) => {
const toWrite = (0, _Function.pipe)(c, Option.match({
onNone: () => Chunk.of(Either.right(b)),
onSome: c => Chunk.make(Either.right(b), Either.left(c))
}));
if (wasConsumed) {
return (0, _Function.pipe)(core.write(toWrite), core.flatMap(() => scheduledAggregator(sinkFiber, scheduleFiber, scope)));
}
return scheduledAggregator(sinkFiber, scheduleFiber, scope);
}), channel.unwrap);
}
case SinkEndReason.OP_UPSTREAM_END:
{
return (0, _Function.pipe)(Ref.get(consumed), Effect.map(wasConsumed => wasConsumed ? core.write(Chunk.of(Either.right(b))) : core.unit), channel.unwrap);
}
}
})), channel.unwrap);
return channel.unwrap(Effect.raceWith(Fiber.join(sinkFiber), Fiber.join(scheduleFiber), {
onSelfDone: (sinkExit, _) => (0, _Function.pipe)(Fiber.interrupt(scheduleFiber), Effect.zipRight((0, _Function.pipe)(Effect.suspend(() => sinkExit), Effect.map(([leftovers, b]) => handleSide(leftovers, b, Option.none()))))),
onOtherDone: (scheduleExit, _) => Effect.matchCauseEffect(Effect.suspend(() => scheduleExit), {
onFailure: cause => Either.match(Cause.failureOrCause(cause), {
onLeft: () => (0, _Function.pipe)(handoff, Handoff.offer(HandoffSignal.end(SinkEndReason.ScheduleEnd)), Effect.forkDaemon, Effect.zipRight((0, _Function.pipe)(Fiber.join(sinkFiber), Effect.map(([leftovers, b]) => handleSide(leftovers, b, Option.none()))))),
onRight: cause => (0, _Function.pipe)(handoff, Handoff.offer(HandoffSignal.halt(cause)), Effect.forkDaemon, Effect.zipRight((0, _Function.pipe)(Fiber.join(sinkFiber), Effect.map(([leftovers, b]) => handleSide(leftovers, b, Option.none())))))
}),
onSuccess: c => (0, _Function.pipe)(handoff, Handoff.offer(HandoffSignal.end(SinkEndReason.ScheduleEnd)), Effect.forkDaemon, Effect.zipRight((0, _Function.pipe)(Fiber.join(sinkFiber), Effect.map(([leftovers, b]) => handleSide(leftovers, b, Option.some(c))))))
})
}));
};
return unwrapScoped((0, _Function.pipe)(self, toChannel, core.pipeTo(handoffProducer), channelExecutor.run, Effect.forkScoped, Effect.zipRight((0, _Function.pipe)(handoffConsumer, channel.pipeToOrFail(_sink.toChannel(sink)), core.collectElements, channelExecutor.run, Effect.forkScoped, Effect.flatMap(sinkFiber => (0, _Function.pipe)(Effect.forkScoped(timeout(Option.none())), Effect.flatMap(scheduleFiber => (0, _Function.pipe)(Effect.scope, Effect.map(scope => new StreamImpl(scheduledAggregator(sinkFiber, scheduleFiber, scope)))))))))));
}));
});
/** @internal */
const as = exports.as = /*#__PURE__*/(0, _Function.dual)(2, (self, value) => map(self, () => value));
/** @internal */
const _async = (register, outputBuffer = 16) => Effect.acquireRelease(Queue.bounded(outputBuffer), queue => Queue.shutdown(queue)).pipe(Effect.flatMap(output => Effect.runtime().pipe(Effect.flatMap(runtime => Effect.sync(() => {
const runPromiseExit = Runtime.runPromiseExit(runtime);
const canceler = register(emit.make(resume => InternalTake.fromPull(resume).pipe(Effect.flatMap(take => Queue.offer(output, take)), Effect.asUnit, runPromiseExit).then(exit => {
if (Exit.isFailure(exit)) {
if (!Cause.isInterrupted(exit.cause)) {
throw Cause.squash(exit.cause);
}
}
})));
return canceler;
})), Effect.map(value => {
const loop = Queue.take(output).pipe(Effect.flatMap(take => InternalTake.done(take)), Effect.match({
onFailure: maybeError => core.fromEffect(Queue.shutdown(output)).pipe(channel.zipRight(Option.match(maybeError, {
onNone: () => core.unit,
onSome: error => core.fail(error)
}))),
onSuccess: chunk => core.write(chunk).pipe(core.flatMap(() => loop))
}), channel.unwrap);
return fromChannel(loop).pipe(ensuring(value ?? Effect.unit));
}))), unwrapScoped);
/** @internal */
exports._async = _async;
const asyncEffect = (register, outputBuffer = 16) => (0, _Function.pipe)(Effect.acquireRelease(Queue.bounded(outputBuffer), queue => Queue.shutdown(queue)), Effect.flatMap(output => (0, _Function.pipe)(Effect.runtime(), Effect.flatMap(runtime => (0, _Function.pipe)(register(emit.make(k => (0, _Function.pipe)(InternalTake.fromPull(k), Effect.flatMap(take => Queue.offer(output, take)), Effect.asUnit, Runtime.runPromiseExit(runtime)).then(exit => {
if (Exit.isFailure(exit)) {
if (!Cause.isInterrupted(exit.cause)) {
throw Cause.squash(exit.cause);
}
}
}))), Effect.map(() => {
const loop = (0, _Function.pipe)(Queue.take(output), Effect.flatMap(InternalTake.done), Effect.match({
onFailure: maybeError => (0, _Function.pipe)(core.fromEffect(Queue.shutdown(output)), channel.zipRight(Option.match(maybeError, {
onNone: () => core.unit,
onSome: core.fail
}))),
onSuccess: chunk => (0, _Function.pipe)(core.write(chunk), core.flatMap(() => loop))
}), channel.unwrap);
return loop;
}))))), channel.unwrapScoped, fromChannel);
/** @internal */
exports.asyncEffect = asyncEffect;
const asyncScoped = (register, outputBuffer = 16) => (0, _Function.pipe)(Effect.acquireRelease(Queue.bounded(outputBuffer), queue => Queue.shutdown(queue)), Effect.flatMap(output => (0, _Function.pipe)(Effect.runtime(), Effect.flatMap(runtime => (0, _Function.pipe)(register(emit.make(k => (0, _Function.pipe)(InternalTake.fromPull(k), Effect.flatMap(take => Queue.offer(output, take)), Effect.asUnit, Runtime.runPromiseExit(runtime)).then(exit => {
if (Exit.isFailure(exit)) {
if (!Cause.isInterrupted(exit.cause)) {
throw Cause.squash(exit.cause);
}
}
}))), Effect.zipRight(Ref.make(false)), Effect.flatMap(ref => (0, _Function.pipe)(Ref.get(ref), Effect.map(isDone => isDone ? pull.end() : (0, _Function.pipe)(Queue.take(output), Effect.flatMap(InternalTake.done), Effect.onError(() => (0, _Function.pipe)(Ref.set(ref, true), Effect.zipRight(Queue.shutdown(output)))))))))))), scoped, flatMap(repeatEffectChunkOption));
/** @internal */
exports.asyncScoped = asyncScoped;
const branchAfter = exports.branchAfter = /*#__PURE__*/(0, _Function.dual)(3, (self, n, f) => suspend(() => {
const buffering = acc => core.readWith({
onInput: input => {
const nextSize = acc.length + input.length;
if (nextSize >= n) {
const [b1, b2] = (0, _Function.pipe)(input, Chunk.splitAt(n - acc.length));
return running((0, _Function.pipe)(acc, Chunk.appendAll(b1)), b2);
}
return buffering((0, _Function.pipe)(acc, Chunk.appendAll(input)));
},
onFailure: core.fail,
onDone: () => running(acc, Chunk.empty())
});
const running = (prefix, leftover) => core.pipeTo(channel.zipRight(core.write(leftover), channel.identityChannel()), toChannel(f(prefix)));
return new StreamImpl((0, _Function.pipe)(toChannel(self), channel.pipeToOrFail(buffering(Chunk.empty()))));
}));
/** @internal */
const broadcast = exports.broadcast = /*#__PURE__*/(0, _Function.dual)(3, (self, n, maximumLag) => (0, _Function.pipe)(self, broadcastedQueues(n, maximumLag), Effect.map(tuple => tuple.map(queue => flattenTake(fromQueue(queue, {
shutdown: true
}))))));
/** @internal */
const broadcastDynamic = exports.broadcastDynamic = /*#__PURE__*/(0, _Function.dual)(2, (self, maximumLag) => (0, _Function.pipe)(self, broadcastedQueuesDynamic(maximumLag), Effect.map(effect => flattenTake(flatMap(scoped(effect), fromQueue)))));
/** @internal */
const broadcastedQueues = exports.broadcastedQueues = /*#__PURE__*/(0, _Function.dual)(3, (self, n, maximumLag) => Effect.flatMap(PubSub.bounded(maximumLag), pubsub => (0, _Function.pipe)(Effect.all(Array.from({
length: n
}, () => PubSub.subscribe(pubsub))), Effect.tap(() => Effect.forkScoped(runIntoPubSubScoped(self, pubsub))))));
/** @internal */
const broadcastedQueuesDynamic = exports.broadcastedQueuesDynamic = /*#__PURE__*/(0, _Function.dual)(2, (self, maximumLag) => Effect.map(toPubSub(self, maximumLag), PubSub.subscribe));
/** @internal */
const buffer = exports.buffer = /*#__PURE__*/(0, _Function.dual)(2, (self, options) => {
if (options.capacity === "unbounded") {
return bufferUnbounded(self);
} else if (options.strategy === "dropping") {
return bufferDropping(self, options.capacity);
} else if (options.strategy === "sliding") {
return bufferSliding(self, options.capacity);
}
const queue = toQueueOfElements(self, options);
return new StreamImpl(channel.unwrapScoped(Effect.map(queue, queue => {
const process = (0, _Function.pipe)(core.fromEffect(Queue.take(queue)), core.flatMap(Exit.match({
onFailure: cause => (0, _Function.pipe)(Cause.flipCauseOption(cause), Option.match({
onNone: () => core.unit,
onSome: core.failCause
})),
onSuccess: value => core.flatMap(core.write(Chunk.of(value)), () => process)
})));
return process;
})));
});
/** @internal */
const bufferChunks = exports.bufferChunks = /*#__PURE__*/(0, _Function.dual)(2, (self, options) => {
if (options.strategy === "dropping") {
return bufferChunksDropping(self, options.capacity);
} else if (options.strategy === "sliding") {
return bufferChunksSliding(self, options.capacity);
}
const queue = toQueue(self, options);
return new StreamImpl(channel.unwrapScoped(Effect.map(queue, queue => {
const process = (0, _Function.pipe)(core.fromEffect(Queue.take(queue)), core.flatMap(InternalTake.match({
onEnd: () => core.unit,
onFailure: core.failCause,
onSuccess: value => (0, _Function.pipe)(core.write(value), core.flatMap(() => process))
})));
return process;
})));
});
const bufferChunksDropping = /*#__PURE__*/(0, _Function.dual)(2, (self, capacity) => {
const queue = Effect.acquireRelease(Queue.dropping(capacity), queue => Queue.shutdown(queue));
return new StreamImpl(bufferSignal(queue, toChannel(self)));
});
const bufferChunksSliding = /*#__PURE__*/(0, _Function.dual)(2, (self, capacity) => {
const queue = Effect.acquireRelease(Queue.sliding(capacity), queue => Queue.shutdown(queue));
return new StreamImpl(bufferSignal(queue, toChannel(self)));
});
const bufferDropping = /*#__PURE__*/(0, _Function.dual)(2, (self, capacity) => {
const queue = Effect.acquireRelease(Queue.dropping(capacity), queue => Queue.shutdown(queue));
return new StreamImpl(bufferSignal(queue, toChannel(rechunk(1)(self))));
});
const bufferSliding = /*#__PURE__*/(0, _Function.dual)(2, (self, capacity) => {
const queue = Effect.acquireRelease(Queue.sliding(capacity), queue => Queue.shutdown(queue));
return new StreamImpl(bufferSignal(queue, toChannel((0, _Function.pipe)(self, rechunk(1)))));
});
const bufferUnbounded = self => {
const queue = toQueue(self, {
strategy: "unbounded"
});
return new StreamImpl(channel.unwrapScoped(Effect.map(queue, queue => {
const process = (0, _Function.pipe)(core.fromEffect(Queue.take(queue)), core.flatMap(InternalTake.match({
onEnd: () => core.unit,
onFailure: core.failCause,
onSuccess: value => core.flatMap(core.write(value), () => process)
})));
return process;
})));
};
const bufferSignal = (scoped, bufferChannel) => {
const producer = (queue, ref) => {
const terminate = take => (0, _Function.pipe)(Ref.get(ref), Effect.tap(Deferred.await), Effect.zipRight(Deferred.make()), Effect.flatMap(deferred => (0, _Function.pipe)(Queue.offer(queue, [take, deferred]), Effect.zipRight(Ref.set(ref, deferred)), Effect.zipRight(Deferred.await(deferred)))), Effect.asUnit, core.fromEffect);
return core.readWithCause({
onInput: input => (0, _Function.pipe)(Deferred.make(), Effect.flatMap(deferred => (0, _Function.pipe)(Queue.offer(queue, [InternalTake.chunk(input), deferred]), Effect.flatMap(added => (0, _Function.pipe)(Ref.set(ref, deferred), Effect.when(() => added))))), Effect.asUnit, core.fromEffect, core.flatMap(() => producer(queue, ref))),
onFailure: error => terminate(InternalTake.failCause(error)),
onDone: () => terminate(InternalTake.end)
});
};
const consumer = queue => {
const process = (0, _Function.pipe)(core.fromEffect(Queue.take(queue)), core.flatMap(([take, deferred]) => channel.zipRight(core.fromEffect(Deferred.succeed(deferred, void 0)), InternalTake.match(take, {
onEnd: () => core.unit,
onFailure: core.failCause,
onSuccess: value => (0, _Function.pipe)(core.write(value), core.flatMap(() => process))
}))));
return process;
};
return channel.unwrapScoped((0, _Function.pipe)(scoped, Effect.flatMap(queue => (0, _Function.pipe)(Deferred.make(), Effect.tap(start => Deferred.succeed(start, void 0)), Effect.flatMap(start => (0, _Function.pipe)(Ref.make(start), Effect.flatMap(ref => (0, _Function.pipe)(bufferChannel, core.pipeTo(producer(queue, ref)), channelExecutor.runScoped, Effect.forkScoped)), Effect.as(consumer(queue))))))));
};
/** @internal */
const catchAll = exports.catchAll = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => catchAllCause(self, cause => Either.match(Cause.failureOrCause(cause), {
onLeft: f,
onRight: failCause
})));
/** @internal */
const catchAllCause = exports.catchAllCause = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => new StreamImpl((0, _Function.pipe)(toChannel(self), core.catchAllCause(cause => toChannel(f(cause))))));
/** @internal */
const catchSome = exports.catchSome = /*#__PURE__*/(0, _Function.dual)(2, (self, pf) => (0, _Function.pipe)(self, catchAll(error => (0, _Function.pipe)(pf(error), Option.getOrElse(() => fail(error))))));
/** @internal */
const catchSomeCause = exports.catchSomeCause = /*#__PURE__*/(0, _Function.dual)(2, (self, pf) => (0, _Function.pipe)(self, catchAllCause(cause => (0, _Function.pipe)(pf(cause), Option.getOrElse(() => failCause(cause))))));
/* @internal */
const catchTag = exports.catchTag = /*#__PURE__*/(0, _Function.dual)(3, (self, k, f) => catchAll(self, e => {
if ("_tag" in e && e["_tag"] === k) {
return f(e);
}
return fail(e);
}));
/** @internal */
const catchTags = exports.catchTags = /*#__PURE__*/(0, _Function.dual)(2, (self, cases) => catchAll(self, e => {
const keys = Object.keys(cases);
if ("_tag" in e && keys.includes(e["_tag"])) {
return cases[e["_tag"]](e);
}
return fail(e);
}));
/** @internal */
const changes = self => (0, _Function.pipe)(self, changesWith((x, y) => Equal.equals(y)(x)));
/** @internal */
exports.changes = changes;
const changesWith = exports.changesWith = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => {
const writer = last => core.readWithCause({
onInput: input => {
const [newLast, newChunk] = Chunk.reduce(input, [last, Chunk.empty()], ([option, outputs], output) => {
if (Option.isSome(option) && f(option.value, output)) {
return [Option.some(output), outputs];
}
return [Option.some(output), (0, _Function.pipe)(outputs, Chunk.append(output))];
});
return core.flatMap(core.write(newChunk), () => writer(newLast));
},
onFailure: core.failCause,
onDone: () => core.unit
});
return new StreamImpl((0, _Function.pipe)(toChannel(self), core.pipeTo(writer(Option.none()))));
});
/** @internal */
const changesWithEffect = exports.changesWithEffect = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => {
const writer = last => core.readWithCause({
onInput: input => (0, _Function.pipe)(input, Effect.reduce([last, Chunk.empty()], ([option, outputs], output) => {
if (Option.isSome(option)) {
return (0, _Function.pipe)(f(option.value, output), Effect.map(bool => bool ? [Option.some(output), outputs] : [Option.some(output), (0, _Function.pipe)(outputs, Chunk.append(output))]));
}
return Effect.succeed([Option.some(output), (0, _Function.pipe)(outputs, Chunk.append(output))]);
}), core.fromEffect, core.flatMap(([newLast, newChunk]) => (0, _Function.pipe)(core.write(newChunk), core.flatMap(() => writer(newLast))))),
onFailure: core.failCause,
onDone: () => core.unit
});
return new StreamImpl((0, _Function.pipe)(toChannel(self), core.pipeTo(writer(Option.none()))));
});
/** @internal */
const chunks = self => (0, _Function.pipe)(self, mapChunks(Chunk.of));
/** @internal */
exports.chunks = chunks;
const chunksWith = exports.chunksWith = /*#__PURE__*/(0, _Function.dual)(2, (self, f) => flattenChunks(f(chunks(self))));
const unsome = effect => Effect.catchAll(Effect.asSome(effect), o => o._tag === "None" ? Effect.succeedNone : Effect.fail(o.value));
/** @internal */
const combine = exports.combine = /*#__PURE__*/(0, _Function.dual)(4, (self, that, s, f) => {
const producer = (handoff, latch) => (0, _Function.pipe)(core.fromEffect(Handoff.take(latch)), channel.zipRight(core.readWithCause({
onInput: input => core.flatMap(core.fromEffect((0, _Function.pipe)(handoff, Handoff.offer(Exit.succeed(input)))), () => producer(handoff, latch)),
onFailure: cause => core.fromEffect(Handoff.offer(handoff, Exit.failCause((0, _Function.pipe)(cause, Cause.map(Option.some))))),
onDone: () => core.flatMap(core.fromEffect(Handoff.offer(handoff, Exit.fail(Option.none()))), () => producer(handoff, latch))
})));
return new StreamImpl(channel.unwrapScoped(Effect.gen(function* ($) {
const left = yield* $(Handoff.make());
const right = yield* $(Handoff.make());
const latchL = yield* $(Handoff.make());
const latchR = yield* $(Handoff.make());
yield* $(toChannel(self), channel.concatMap(channel.writeChunk), core.pipeTo(producer(left, latchL)), channelExecutor.runScoped, Effect.forkScoped);
yield* $(toChannel(that), channel.concatMap(channel.writeChunk), core.pipeTo(producer(right, latchR)), channelExecutor.runScoped, Effect.forkScoped);
const pullLeft = (0, _Function.pipe)(latchL, Handoff.offer(void 0),
// TODO: remove
Effect.zipRight((0, _Function.pipe)(Handoff.take(left), Effect.flatMap(exit => Effect.suspend(() => exit)))));
const pullRight = (0, _Function.pipe)(latchR, Handoff.offer(void 0),
// TODO: remove
Effect.zipRight((0, _Function.pipe)(Handoff.take(right), Effect.flatMap(exit => Effect.suspend(() => exit)))));
return toChannel(unfoldEffect(s, s => Effect.flatMap(f(s, pullLeft, pullRight), unsome)));
})));
});
/** @internal */
const combineChunks = exports.combineChunks = /*#__PURE__*/(0, _Function.dual)(4, (self, that, s, f) => {
const producer = (handoff, latch) => channel.zipRight(core.fromEffect(Handoff.take(latch)), core.readWithCause({
onInput: input => core.flatMap(core.fromEffect((0, _Function.pipe)(handoff, Handoff.offer(InternalTake.chunk(input)))), () => producer(handoff, latch)),
onFailure: cause => core.fromEffect(Handoff.offer(handoff, InternalTake.failCause(cause))),
onDone: () => core.fromEffect(Handoff.offer(handoff, InternalTake.end))
}));
return new StreamImpl((0, _Function.pipe)(Effect.all([Handoff.make(), Handoff.make(), Handoff.make(), Handoff.make()]), Effect.tap(([left, _, latchL]) => (0, _Function.pipe)(toChannel(self), core.pipeTo(producer(left, latchL)), channelExecutor.runScoped, Effect.forkScoped)), Effect.tap(([_, right, __, latchR]) => (0, _Function.pipe)(toChannel(that), core.pipeTo(producer(right, latchR)), channelExecutor.runScoped, Effect.forkScoped)), Effect.map(([left, right, latchL, latchR]) => {
const pullLeft = (0, _Function.pipe)(latchL, Handoff.offer(void 0), Effect.zipRight((0, _Function.pipe)(Handoff.take(left), Effect.flatMap(InternalTake.done))));
const pullRight = (0, _Function.pipe)(latchR, Handoff.offer(void 0), Effect.zipRight((0, _Function.pipe)(Handoff.take(right), Effect.flatMap(InternalTake.done))));
return toChannel(unfoldChunkEffect(s, s => Effect.flatMap(f(s, pullLeft, pullRight), unsome)));
}), channel.unwrapScoped));
});
/** @internal */
const concat = exports.concat = /*#__PURE__*/(0, _Function.dual)(2, (self, that) => new StreamImpl((0, _Function.pipe)(toChannel(self), channel.zipRight(toChannel(that)))));
/** @internal */
const concatAll = streams => suspend(() => (0, _Function.pipe)(streams, Chunk.reduce(empty, (x, y) => concat(y)(x))));
/** @internal */
exports.concatAll = concatAll;
const cross = exports.cross = /*#__PURE__*/(0, _Function.dual)(2, (self, that) => (0, _Function.pipe)(self, crossWith(that, (a, a2) => [a, a2])));
/** @internal */
const crossLeft = exports.crossLeft = /*#__PURE__*/(0, _Function.dual)(2, (self, that) => (0, _Function.pipe)(self, crossWith(that, (a, _) => a)));
/** @internal */
const crossRight = exports.crossRight = /*#__PURE__*/(0, _Function.dual)(2, (self, that) => flatMap(self, () => that));
/** @internal */
const crossWith = exports.crossWith = /*#__PURE__*/(0, _Function.dual)(3, (self, that, f) => (0, _Function.pipe)(self, flatMap(a => (0, _Function.pipe)(that, map(b => f(a, b))))));
/** @internal */
const debounce = exports.debounce = /*#__PURE__*/(0, _Function.dual)(2, (self, duration) => (0, _Function.pipe)(singleProducerAsyncInput.make(), Effect.flatMap(input => Effect.transplant(grafter => (0, _Function.pipe)(Handoff.make(), Effect.map(handoff => {
const enqueue = last => (0, _Function.pipe)(Clock.sleep(duration), Effect.as(last), Effect.fork, grafter, Effect.map(fiber => consumer(DebounceState.previous(fiber))));
const producer = core.readWithCause({
onInput: input => Option.match(Chunk.last(input), {
onNone: () => producer,
onSome: last => core.flatMap(core.fromEffect(Handoff.offer(handoff, HandoffSignal.emit(Chunk.of(last)))), () => producer)
}),
onFailure: cause => core.fromEffect(Handoff.offer(handoff, HandoffSignal.halt(cause))),
onDone: () => core.fromEffect(Handoff.offer(handoff, HandoffSignal.end(SinkEndReason.UpstreamEnd)))
});
const consumer = state => {
switch (state._tag) {
case DebounceState.OP_NOT_STARTED:
{
return (0, _Function.pipe)(Handoff.take(handoff), Effect.map(signal => {
switch (signal._tag) {
case HandoffSignal.OP_EMIT:
{
return channel.unwrap(enqueue(signal.elements));
}
case HandoffSignal.OP_HALT:
{
return core.failCause(signal.cause);
}
case HandoffSignal.OP_END:
{
return core.unit;
}
}
}), channel.unwrap);
}
case DebounceState.OP_PREVIOUS:
{
return channel.unwrap(Effect.raceWith(Fiber.join(state.fiber), Handoff.take(handoff), {
onSelfDone: (leftExit, current) => Exit.match(leftExit, {
onFailure: cause => (0, _Function.pipe)(Fiber.interrupt(current), Effect.as(core.failCause(cause))),
onSuccess: chunk => Effect.succeed((0, _Function.pipe)(core.write(chunk), core.flatMap(() => consumer(DebounceState.current(current)))))
}),
onOtherDone: (rightExit, previous) => Exit.match(rightExit, {
onFailure: cause => (0, _Function.pipe)(Fiber.interrupt(previous), Effect.as(core.failCause(cause))),
onSuccess: signal => {
switch (signal._tag) {
case HandoffSignal.OP_EMIT:
{
return (0, _Function.pipe)(Fiber.interrupt(previous), Effect.zipRight(enqueue(signal.elements)));
}
case HandoffSignal.OP_HALT:
{
return (0, _Function.pipe)(Fiber.interrupt(previous), Effect.as(core.failCause(signal.cause)));
}
case HandoffSignal.OP_END:
{
return (0, _Function.pipe)(Fiber.join(previous), Effect.map(chunk => (0, _Function.pipe)(core.write(chunk), channel.zipRight(core.unit))));
}
}
}
})
}));
}
case DebounceState.OP_CURRENT:
{
return (0, _Function.pipe)(Fiber.join(state.fiber), Effect.map(signal => {
switch (signal._tag) {
case HandoffSignal.OP_EMIT:
{
return channel.unwrap(enqueue(signal.elements));
}
case HandoffSignal.OP_HALT:
{
return core.failCause(signal.cause);
}
case HandoffSignal.OP_END:
{
return core.unit;
}
}
}), channel.unwrap);
}
}
};
const debounceChannel = (0, _Function.pipe)(channel.fromInput(input), core.pipeTo(producer), channelExecutor.run, Effect.forkScoped, Effect.as((0, _Function.pipe)(consumer(DebounceState.notStarted), core.embedInput(input))), channel.unwrapScoped);
return new StreamImpl((0, _Function.pipe)(toChannel(self), core.pipeTo(debounceChannel)));
})))), unwrap));
/** @internal */
const die = defect => fromEffect(Effect.die(defect));
/** @internal */
exports.die = die;
const dieSync = evaluate => fromEffect(Effect.dieSync(evaluate));
/** @internal */
exports.dieSync = dieSync;
const dieMessage = message => fromEffect(Effect.dieMessage(message));
/** @internal */
exports.dieMessage = dieMessage;
const distributedWith = exports.distributedWith = /*#__PURE__*/(0, _Function.dual)(2, (self, options) => (0, _Function.pipe)(Deferred.make(), Effect.flatMap(deferred => (0, _Function.pipe)(self, distributedWithDynamic({
maximumLag: options.maximumLag,
decide: a => Effect.flatMap(Deferred.await(deferred), f => f(a))
}), Effect.flatMap(next => (0, _Function.pipe)(Effect.all(Chunk.map(Chunk.range(0, options.size - 1), id => Effect.map(next, ([key, queue]) => [[key, id], queue]))), Effect.map(Chunk.unsafeFromArray), Effect.flatMap(entries => {
const [mappings, queues] = Chunk.reduceRight(entries, [new Map(), Chunk.empty()], ([mappings, queues], [mapping, queue]) => [mappings.set(mapping[0], mapping[1]), (0, _Function.pipe)(queues, Chunk.prepend(queue))]);
return (0, _Function.pipe)(Deferred.succeed(deferred, a => Effect.map(options.decide(a), f => key => (0, _Function.pipe)(f(mappings.get(key))))), Effect.as(Array.from(queues)));
})))))));
/** @internal */
const distributedWithDynamicId = {
ref: 0
};
const newDistributedWithDynamicId = () => {
const current = distributedWithDynamicId.ref;
distributedWithDynamicId.ref = current + 1;
return current;
};
/** @internal */
const distributedWithDynamic = exports.distributedWithDynamic = /*#__PURE__*/(0, _Function.dual)(2, (self, options) => distributedWithDynamicCallback(self, options.maximumLag, options.decide, () => Effect.unit));
/** @internal */
const distributedWithDynamicCallback = exports.distributedWithDynamicCallback = /*#__PURE__*/(0, _Function.dual)(4, (self, maximumLag, decide, done) => (0, _Function.pipe)(Effect.acquireRelease(Ref.make(new Map()), (ref, _) => (0, _Function.pipe)(Ref.get(ref), Effect.flatMap(queues => (0, _Function.pipe)(queues.values(), Effect.forEach(Queue.shutdown))))), Effect.flatMap(queuesRef => Effect.gen(function* ($) {
const offer = a => (0, _Function.pipe)(decide(a), Effect.flatMap(shouldProcess => (0, _Function.pipe)(Ref.get(queuesRef), Effect.flatMap(queues => (0, _Function.pipe)(queues.entries(), Effect.reduce(Chunk.empty(), (acc, [id, queue]) => {
if (shouldProcess(id)) {
return (0, _Function.pipe)(Queue.offer(queue, Exit.succeed(a)), Effect.matchCauseEffect({
onFailure: cause =>
// Ignore all downstream queues that were shut
// down and remove them later
Cause.isInterrupted(cause) ? Effect.succeed((0, _Function.pipe)(acc, Chunk.prepend(id))) : Effect.failCause(cause),
onSuccess: () => Effect.succeed(acc)
}));
}
return Effect.succeed(acc);
}), Effect.flatMap(ids => {
if (Chunk.isNonEmpty(ids)) {
return (0, _Function.pipe)(Ref.update(queuesRef, map => {
for (const id of ids) {
map.delete(id);
}
return map;
}));
}
return Effect.unit;
}))))), Effect.asUnit);
const queuesLock = yield* $(Effect.makeSemaphore(1));
const newQueue = yield* $(Ref.make((0, _Function.pipe)(Queue.bounded(maximumLag), Effect.flatMap(queue => {
const id = newDistributedWithDynamicId();
return (0, _Function.pipe)(Ref.update(queuesRef, map => map.set(id, queue)), Effect.as([id, queue]));
}))));
const finalize = endTake =>
// Make sure that no queues are currently being added
queuesLock.withPermits(1)((0, _Function.pipe)(Ref.set(newQueue, (0, _Function.pipe)(
// All newly created queues should end immediately
Queue.bounded(1), Effect.tap(queue => Queue.offer(queue, endTake)), Effect.flatMap(queue => {
const id = newDistributedWithDynamicId();
return (0, _Function.pipe)(Ref.update(queuesRef, map => map.set(id, queue)), Effect.as(Tuple.make(id, queue)));
}))), Effect.zipRight((0, _Function.pipe)(Ref.get(queuesRef), Effect.flatMap(map => (0, _Function.pipe)(Chunk.fromIterable(map.values()), Effect.forEach(queue => (0, _Function.pipe)(Queue.offer(queue, endTake), Effect.catchSomeCause(cause => Cause.isInterrupted(cause) ? Option.some(Effect.unit) : Option.none()))))))), Effect.zipRight(done(endTake)), Effect.asUnit));
yield* $(self, runForEachScoped(offer), Effect.matchCauseEffect({
onFailure: cause => finalize(Exit.failCause((0, _Function.pipe)(cause, Cause.map(Option.some)))),
onSuccess: () => finalize(Exit.fail(Option.none()))
}), Effect.forkScoped);
return queuesLock.withPermits(1)(Effect.flatten(Ref.get(newQueue)));
}))));
/** @internal */
const drain = self => new StreamImpl(channel.drain(toChannel(self)));
/** @internal */
exports.drain = drain;
const drainFork = exports.drainFork = /*#__PURE__*/(0, _Function.dual)(2, (self, that) => (0, _Function.pipe)(fromEffect(Deferred.make()), flatMap(backgroundDied => (0, _Function.pipe)(scoped((0, _Function.pipe)(that, runForEachScoped(() => Effect.unit), Effect.catchAllCause(cause => Deferred.failCause(backgroundDied, cause)), Effect.forkScoped)), crossRight((0, _Function.pipe)(self, interruptWhenDeferred(backgroundDied)))))));
/** @internal */
const drop = exports.drop = /*#__PURE__*/(0, _Function.dual)(2, (self, n) => {
const loop = r => core.readWith({
onInput: input => {
const dropped = (0, _Function.pipe)(input, Chunk.drop(r));
const leftover = Math.max(0, r - input.length);
const more = Chunk.isEmpty(input) || leftover > 0;
if (more) {
return loop(leftover);
}
return (0, _Function.pipe)(core.write(dropped), channel.zipRight(channel.identityChannel()));
},
onFailure: core.fail,
onDone: () => core.unit
});
return new StreamImpl((0, _Function.pipe)(toChannel(self), channel.pipeToOrFail(loop(n))));
});
/** @internal */
const dropRight = exports.dropRight = /*#__PURE__*/(0, _Function.dual)(2, (self, n) => {
if (n <= 0) {
return identityStream();
}
return suspend(() => {
const queue = new _ringBuffer.RingBuffer(n);
const reader = core.readWith({
onInput: input => {
const outputs = (0, _Function.pipe)(input, Chunk.filterMap(elem => {
const head = queue.head();
queue.put(elem);
return head;
}));
return (0, _Function.pipe)(core.write(outputs), core.flatMap(() => reader));
},
onFailure: core.fail,
onDone: () => core.unit
});
return new StreamImpl((0, _Function.pipe)(toChannel(self), channel.pipeToOrFail(reader)));
});
});
/** @internal */
const dropUntil = exports.dropUntil = /*#__PURE__*/(0, _Function.dual)(2, (self, predicate) => drop(dropWhile(self, a => !predicate(a)), 1));
/** @internal */
const dropUntilEffect = exports.dropUntilEffect = /*#__PURE__*/(0, _Function.dual)(2, (self, predicate) => {
const loop = core.readWith({
onInput: input => (0, _Function.pipe)(Effect.dropUntil(input, predicate), Effect.map(Chunk.unsafeFromArray), Effect.map(leftover => {
const more = Chunk.isEmpty(leftover);
if (more) {
return core.suspend(() => loop);
}
return (0, _Function.pipe)(core.write(leftover), channel.zipRight(channel.identityChannel()));
}), channel.unwrap),
onFailure: core.fail,
onDone: () => core.unit
});
return new StreamImpl((0, _Function.pipe)(toChannel(self), channel.pipeToOrFail(loop)));
});
/** @internal */
const dropWhile = exports.dropWhile = /*#__PURE__*/(0, _Function.dual)(2, (self, predicate) => {
const loop = core.readWith({
onInput: input => {
const output = Chunk.dropWhile(input, predicate);
if (Chunk.isEmpty(output)) {
return core.suspend(() => loop);
}
return channel.zipRight(core.write(output), channel.identityChannel());
},
onFailure: core.fail,
onDone: core.succeedNow
});
return new StreamImpl(channel.pipeToOrFail(toChannel(self), loop));
});
/** @internal */
const dropWhileEffect = exports.dropWhileEffect = /*#__PURE__*/(0, _Function.dual)(2, (self, predicate) => {
const loop = core.readWith({
onInput: input => (0, _Function.pipe)(Effect.dropWhile(input, predicate), Effect.map(Chunk.unsafeFromArray), Effect.map(leftover => {
const more = Chunk.isEmpty(leftover);
i