@ceschiatti/redistail 0.0.12 → 0.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Binary file
@@ -38,7 +38,7 @@ ${endStackCall}`,cache}},opts=options.spanOptions&&"captureStackTrace"in options
38
38
  `,from);else stringBuilder=stringBuilder+"\r";midCRLF=!1}while(indexOfCR!==-1||indexOfLF!==-1)if(indexOfCR===-1||indexOfLF!==-1&&indexOfLF<indexOfCR){if(stringBuilder.length===0)chunkBuilder.push(str.substring(from,indexOfLF));else chunkBuilder.push(stringBuilder+str.substring(from,indexOfLF)),stringBuilder="";from=indexOfLF+1,indexOfLF=str.indexOf(`
39
39
  `,from)}else if(str.length===indexOfCR+1)midCRLF=!0,indexOfCR=-1;else if(indexOfLF===indexOfCR+1){if(stringBuilder.length===0)chunkBuilder.push(str.substring(from,indexOfCR));else stringBuilder=stringBuilder+str.substring(from,indexOfCR),chunkBuilder.push(stringBuilder),stringBuilder="";from=indexOfCR+2,indexOfCR=str.indexOf("\r",from),indexOfLF=str.indexOf(`
40
40
  `,from)}else indexOfCR=str.indexOf("\r",indexOfCR+1);if(midCRLF)stringBuilder=stringBuilder+str.substring(from,str.length-1);else stringBuilder=stringBuilder+str.substring(from,str.length)}}),unsafeFromArray(chunkBuilder)},loop3=readWithCause({onInput:(input)=>{let out=splitLinesChunk(input);return isEmpty(out)?loop3:flatMap13(write(out),()=>loop3)},onFailure:(cause3)=>stringBuilder.length===0?failCause10(cause3):flatMap13(write(of2(stringBuilder)),()=>failCause10(cause3)),onDone:(done8)=>stringBuilder.length===0?succeed12(done8):flatMap13(write(of2(stringBuilder)),()=>succeed12(done8))});return loop3}),toPubSub=(pubsub)=>toQueue(pubsub),toPull=(self)=>flatMap11(scope3,(scope5)=>toPullIn(self,scope5)),toPullIn=dual(2,(self,scope5)=>zip5(sync4(()=>new ChannelExecutor(self,void 0,identity)),runtime3()).pipe(tap3(([executor,runtime4])=>addFinalizerExit(scope5,(exit3)=>{let finalizer=executor.close(exit3);return finalizer!==void 0?provide2(finalizer,runtime4):_void})),uninterruptible2,map16(([executor])=>suspend3(()=>interpretToPull(executor.run(),executor))))),interpretToPull=(channelState,exec)=>{let state=channelState;switch(state._tag){case OP_DONE3:return match9(exec.getDone(),{onFailure:failCause8,onSuccess:(done8)=>succeed9(left2(done8))});case OP_EMIT2:return succeed9(right2(exec.getEmit()));case OP_FROM_EFFECT3:return pipe(state.effect,flatMap11(()=>interpretToPull(exec.run(),exec)));case OP_READ2:return readUpstream(state,()=>interpretToPull(exec.run(),exec),(cause3)=>failCause8(cause3))}},toQueue=(queue)=>suspend5(()=>toQueueInternal(queue)),toQueueInternal=(queue)=>{return readWithCause({onInput:(elem)=>flatMap13(fromEffect4(offer3(queue,right2(elem))),()=>toQueueInternal(queue)),onFailure:(cause3)=>fromEffect4(offer3(queue,left2(failCause3(cause3)))),onDone:(done8)=>fromEffect4(offer3(queue,left2(succeed3(done8))))})},unwrap=(channel)=>flatten10(fromEffect4(channel)),unwrapScoped3=(self)=>concatAllWith(scoped4(self),(d,_)=>d,(d,_)=>d),unwrapScopedWith=(f)=>concatAllWith(scopedWith3(f),(d,_)=>d,(d,_)=>d);var withSpan5=function(){let dataFirst=typeof arguments[0]!=="string",name=dataFirst?arguments[1]:arguments[0],options=addSpanStackTrace(dataFirst?arguments[2]:arguments[1]),acquire=all5([makeSpan2(name,options),context3(),clock2,get13(currentTracerTimingEnabled2)]);if(dataFirst){let self=arguments[0];return acquireUseRelease3(acquire,([span4,context5])=>provideContext5(self,add4(context5,spanTag,span4)),([span4,,clock3,timingEnabled],exit3)=>endSpan(span4,exit3,clock3,timingEnabled))}return(self)=>acquireUseRelease3(acquire,([span4,context5])=>provideContext5(self,add4(context5,spanTag,span4)),([span4,,clock3,timingEnabled],exit3)=>endSpan(span4,exit3,clock3,timingEnabled))},writeAll=(...outs)=>writeChunk(fromIterable2(outs)),writeChunk=(outs)=>writeChunkWriter(0,outs.length,outs),writeChunkWriter=(idx,len,chunk2)=>{return idx===len?void_5:pipe(write(pipe(chunk2,unsafeGet2(idx))),flatMap13(()=>writeChunkWriter(idx+1,len,chunk2)))},zip6=dual((args2)=>isChannel(args2[1]),(self,that,options)=>options?.concurrent?mergeWith2(self,{other:that,onSelfDone:(exit1)=>Await((exit22)=>suspend3(()=>zip3(exit1,exit22))),onOtherDone:(exit22)=>Await((exit1)=>suspend3(()=>zip3(exit1,exit22)))}):flatMap13(self,(a)=>map19(that,(b)=>[a,b]))),zipLeft5=dual((args2)=>isChannel(args2[1]),(self,that,options)=>options?.concurrent?map19(zip6(self,that,{concurrent:!0}),(tuple2)=>tuple2[0]):flatMap13(self,(z)=>as6(that,z))),zipRight6=dual((args2)=>isChannel(args2[1]),(self,that,options)=>options?.concurrent?map19(zip6(self,that,{concurrent:!0}),(tuple2)=>tuple2[1]):flatMap13(self,()=>that)),ChannelExceptionTypeId=Symbol.for("effect/Channel/ChannelException"),ChannelException=(error2)=>({_tag:"ChannelException",[ChannelExceptionTypeId]:ChannelExceptionTypeId,error:error2}),isChannelException=(u)=>hasProperty(u,ChannelExceptionTypeId);var Done4=Done3,Await2=Await;var TypeId17=Symbol.for("effect/RcRef"),stateEmpty2={_tag:"Empty"},stateClosed={_tag:"Closed"},variance5={_A:identity,_E:identity};class RcRefImpl extends Class{acquire;context;scope;idleTimeToLive;[TypeId17]=variance5;[TypeId10]=TypeId10;state=stateEmpty2;semaphore=unsafeMakeSemaphore(1);constructor(acquire,context5,scope5,idleTimeToLive){super();this.acquire=acquire,this.context=context5,this.scope=scope5,this.idleTimeToLive=idleTimeToLive,this.get=get14(this)}get;commit(){return this.get}}var make43=(options)=>withFiberRuntime((fiber)=>{let context5=fiber.getFiberRef(currentContext),scope5=get5(context5,scopeTag),ref=new RcRefImpl(options.acquire,context5,scope5,options.idleTimeToLive?decode(options.idleTimeToLive):void 0);return as(scope5.addFinalizer(()=>ref.semaphore.withPermits(1)(suspend(()=>{let close2=ref.state._tag==="Acquired"?scopeClose(ref.state.scope,exitVoid):void_;return ref.state=stateClosed,close2}))),ref)}),get14=(self_)=>{let self=self_,isInfinite=self.idleTimeToLive&&!isFinite(self.idleTimeToLive);return uninterruptibleMask((restore)=>suspend(()=>{switch(self.state._tag){case"Closed":return interrupt2;case"Acquired":return self.state.refCount++,self.state.fiber?as(interruptFiber(self.state.fiber),self.state):succeed(self.state);case"Empty":return scopeMake().pipe(bindTo2("scope"),bind2("value",({scope:scope5})=>restore(fiberRefLocally(self.acquire,currentContext,add4(self.context,scopeTag,scope5)))),map10(({scope:scope5,value})=>{let state={_tag:"Acquired",value,scope:scope5,fiber:void 0,refCount:1};return self.state=state,state}))}})).pipe(self.semaphore.withPermits(1),bindTo2("state"),bind2("scope",()=>scopeTag),tap(({scope:scope5,state})=>scope5.addFinalizer(()=>suspend(()=>{if(state.refCount--,state.refCount>0||isInfinite)return void_;if(self.idleTimeToLive===void 0)return self.state=stateEmpty2,scopeClose(state.scope,exitVoid);return sleep3(self.idleTimeToLive).pipe(interruptible2,zipRight(suspend(()=>{if(self.state._tag==="Acquired"&&self.state.refCount===0)return self.state=stateEmpty2,scopeClose(state.scope,exitVoid);return void_})),ensuring(sync(()=>{state.fiber=void 0})),forkIn(self.scope),tap((fiber)=>{state.fiber=fiber}),self.semaphore.withPermits(1))}))),map10(({state})=>state.value))};var make44=make43,get15=get14;var runFork3=unsafeFork2;var runPromiseExit2=unsafeRunPromiseExit,defaultRuntime2=defaultRuntime;var OP_LEFT="Left",OP_RIGHT="Right",OP_BOTH="Both",OP_EITHER="Either";var Left={_tag:OP_LEFT},Right={_tag:OP_RIGHT},Both={_tag:OP_BOTH},Either={_tag:OP_EITHER},fromInput2=(input)=>{switch(input){case"left":return Left;case"right":return Right;case"both":return Both;case"either":return Either;default:return input}};var Both2=Both;var SinkTypeId2=Symbol.for("effect/Sink"),sinkVariance2={_A:(_)=>_,_In:(_)=>_,_L:(_)=>_,_E:(_)=>_,_R:(_)=>_};class SinkImpl{channel;[SinkTypeId2]=sinkVariance2;constructor(channel){this.channel=channel}pipe(){return pipeArguments(this,arguments)}}var isSink=(u)=>hasProperty(u,SinkTypeId2),suspend6=(evaluate2)=>new SinkImpl(suspend5(()=>toChannel(evaluate2())));var collectAll=()=>new SinkImpl(collectAllLoop(empty2())),collectAllLoop=(acc)=>readWithCause({onInput:(chunk2)=>collectAllLoop(pipe(acc,appendAll2(chunk2))),onFailure:failCause10,onDone:()=>succeed12(acc)}),collectAllN=(n)=>suspend6(()=>fromChannel(collectAllNLoop(n,empty2()))),collectAllNLoop=(n,acc)=>readWithCause({onInput:(chunk2)=>{let[collected,leftovers]=splitAt2(chunk2,n);if(collected.length<n)return collectAllNLoop(n-collected.length,appendAll2(acc,collected));if(isEmpty(leftovers))return succeed12(appendAll2(acc,collected));return flatMap13(write(leftovers),()=>succeed12(appendAll2(acc,collected)))},onFailure:failCause10,onDone:()=>succeed12(acc)});var collectLeftover=(self)=>new SinkImpl(pipe(collectElements(toChannel(self)),map19(([chunks,z])=>[z,flatten2(chunks)])));var drain2=new SinkImpl(drain(identityChannel()));var fail12=(e)=>new SinkImpl(fail11(e));var fold=(s,contFn,f)=>suspend6(()=>new SinkImpl(foldReader(s,contFn,f))),foldReader=(s,contFn,f)=>{if(!contFn(s))return succeedNow(s);return readWith({onInput:(input)=>{let[nextS,leftovers]=foldChunkSplit(s,input,contFn,f,0,input.length);if(isNonEmpty(leftovers))return pipe(write(leftovers),as6(nextS));return foldReader(nextS,contFn,f)},onFailure:fail11,onDone:()=>succeedNow(s)})},foldChunkSplit=(s,chunk2,contFn,f,index,length3)=>{if(index===length3)return[s,empty2()];let s1=f(s,pipe(chunk2,unsafeGet2(index)));if(contFn(s1))return foldChunkSplit(s1,chunk2,contFn,f,index+1,length3);return[s1,pipe(chunk2,drop2(index+1))]},foldSink=dual(2,(self,options)=>{let newChannel=pipe(toChannel(self),collectElements,foldChannel({onFailure:(error2)=>toChannel(options.onFailure(error2)),onSuccess:([leftovers,z])=>suspend5(()=>{let leftoversRef={ref:pipe(leftovers,filter2(isNonEmpty))},refReader=pipe(sync7(()=>{let ref=leftoversRef.ref;return leftoversRef.ref=empty2(),ref}),flatMap13((chunk2)=>writeChunk(chunk2))),passthrough5=identityChannel(),continuationSink=pipe(refReader,zipRight6(passthrough5),pipeTo(toChannel(options.onSuccess(z))));return flatMap13(collectElements(continuationSink),([newLeftovers,z1])=>pipe(succeed12(leftoversRef.ref),flatMap13(writeChunk),zipRight6(writeChunk(newLeftovers)),as6(z1)))})}));return new SinkImpl(newChannel)}),foldChunks=(s,contFn,f)=>suspend6(()=>new SinkImpl(foldChunksReader(s,contFn,f))),foldChunksReader=(s,contFn,f)=>{if(!contFn(s))return succeedNow(s);return readWith({onInput:(input)=>foldChunksReader(f(s,input),contFn,f),onFailure:fail11,onDone:()=>succeedNow(s)})};var foldEffect=(s,contFn,f)=>suspend6(()=>new SinkImpl(foldEffectReader(s,contFn,f))),foldEffectReader=(s,contFn,f)=>{if(!contFn(s))return succeedNow(s);return readWith({onInput:(input)=>pipe(fromEffect4(foldChunkSplitEffect(s,input,contFn,f)),flatMap13(([nextS,leftovers])=>pipe(leftovers,match2({onNone:()=>foldEffectReader(nextS,contFn,f),onSome:(leftover)=>pipe(write(leftover),as6(nextS))})))),onFailure:fail11,onDone:()=>succeedNow(s)})},foldChunkSplitEffect=(s,chunk2,contFn,f)=>foldChunkSplitEffectInternal(s,chunk2,0,chunk2.length,contFn,f),foldChunkSplitEffectInternal=(s,chunk2,index,length3,contFn,f)=>{if(index===length3)return succeed9([s,none2()]);return pipe(f(s,pipe(chunk2,unsafeGet2(index))),flatMap11((s1)=>contFn(s1)?foldChunkSplitEffectInternal(s1,chunk2,index+1,length3,contFn,f):succeed9([s1,some2(pipe(chunk2,drop2(index+1)))])))};var foldLeftChunks=(s,f)=>foldChunks(s,constTrue,f);var flatMap14=dual(2,(self,f)=>foldSink(self,{onFailure:fail12,onSuccess:f})),forEach7=(f)=>{let process2=readWithCause({onInput:(input)=>pipe(fromEffect4(forEach6(input,(v)=>f(v),{discard:!0})),flatMap13(()=>process2)),onFailure:failCause10,onDone:()=>void_5});return new SinkImpl(process2)},forEachChunk=(f)=>{let process2=readWithCause({onInput:(input)=>pipe(fromEffect4(f(input)),flatMap13(()=>process2)),onFailure:failCause10,onDone:()=>void_5});return new SinkImpl(process2)},forEachWhile=(f)=>{let process2=readWithCause({onInput:(input)=>forEachWhileReader(f,input,0,input.length,process2),onFailure:failCause10,onDone:()=>void_5});return new SinkImpl(process2)},forEachWhileReader=(f,input,index,length3,cont)=>{if(index===length3)return cont;return pipe(fromEffect4(f(pipe(input,unsafeGet2(index)))),flatMap13((bool)=>bool?forEachWhileReader(f,input,index+1,length3,cont):write(pipe(input,drop2(index)))),catchAll5((error2)=>pipe(write(pipe(input,drop2(index))),zipRight6(fail11(error2)))))};var fromChannel=(channel)=>new SinkImpl(channel),fromEffect6=(effect3)=>new SinkImpl(fromEffect4(effect3));var head5=()=>fold(none2(),isNone2,(option3,input)=>match2(option3,{onNone:()=>some2(input),onSome:()=>option3}));var last3=()=>foldLeftChunks(none2(),(s,input)=>orElse(last2(input),()=>s));var map20=dual(2,(self,f)=>{return new SinkImpl(pipe(toChannel(self),map19(f)))});var raceWith3=dual(2,(self,options)=>{function race3(scope5){return gen2(function*(){let pubsub=yield*bounded5(options?.capacity??16),subscription1=yield*extend2(subscribe2(pubsub),scope5),subscription2=yield*extend2(subscribe2(pubsub),scope5),reader=toPubSub(pubsub),writer=fromQueue(subscription1).pipe(pipeTo(toChannel(self)),zipLeft5(fromEffect4(shutdown2(subscription1))),mergeWith2({other:fromQueue(subscription2).pipe(pipeTo(toChannel(options.other)),zipLeft5(fromEffect4(shutdown2(subscription2)))),onSelfDone:options.onSelfDone,onOtherDone:options.onOtherDone})),racedChannel=mergeWith2(reader,{other:writer,onSelfDone:()=>Await(identity),onOtherDone:(exit3)=>Done3(exit3)});return new SinkImpl(racedChannel)})}return unwrapScopedWith2(race3)});var sum2=foldLeftChunks(0,(acc,chunk2)=>acc+reduce2(chunk2,0,(s,a)=>s+a));var toChannel=(self)=>isEffect2(self)?toChannel(fromEffect6(self)):self.channel;var unwrapScopedWith2=(f)=>new SinkImpl(unwrapScopedWith((scope5)=>f(scope5).pipe(map16((sink)=>toChannel(sink)))));var zipRight7=dual((args2)=>isSink(args2[1]),(self,that,options)=>zipWith9(self,that,(_,z2)=>z2,options)),zipWith9=dual((args2)=>isSink(args2[1]),(self,that,f,options)=>options?.concurrent?raceWith3(self,{other:that,onSelfDone:match9({onFailure:(cause3)=>Done3(failCause8(cause3)),onSuccess:(leftZ)=>Await(match9({onFailure:failCause8,onSuccess:(rightZ)=>succeed9(f(leftZ,rightZ))}))}),onOtherDone:match9({onFailure:(cause3)=>Done3(failCause8(cause3)),onSuccess:(rightZ)=>Await(match9({onFailure:failCause8,onSuccess:(leftZ)=>succeed9(f(leftZ,rightZ))}))})}):flatMap14(self,(z)=>map20(that,(z2)=>f(z,z2))));var count4=foldLeftChunks(0,(acc,chunk2)=>acc+chunk2.length),mkString=suspend6(()=>{let strings=[];return pipe(foldLeftChunks(void 0,(_,elems)=>map4(elems,(elem)=>{strings.push(String(elem))})),map20(()=>strings.join("")))});class Versioned{value;constructor(value){this.value=value}}var make45=(ref,isNew)=>({ref,isNew,isChanged:!1,expected:ref.versioned,newValue:ref.versioned.value}),unsafeGet6=(self)=>{return self.newValue},unsafeSet=(self,value)=>{self.isChanged=!0,self.newValue=value},commit=(self)=>{self.ref.versioned=new Versioned(self.newValue)};var isInvalid=(self)=>{return self.ref.versioned!==self.expected},isChanged=(self)=>{return self.isChanged};var JournalAnalysisInvalid="Invalid",JournalAnalysisReadWrite="ReadWrite",JournalAnalysisReadOnly="ReadOnly",commitJournal=(journal)=>{for(let entry of journal)commit(entry[1])},analyzeJournal=(journal)=>{let val=JournalAnalysisReadOnly;for(let[,entry]of journal)if(val=isInvalid(entry)?JournalAnalysisInvalid:isChanged(entry)?JournalAnalysisReadWrite:val,val===JournalAnalysisInvalid)return val;return val};var collectTodos=(journal)=>{let allTodos=new Map;for(let[,entry]of journal){for(let todo of entry.ref.todos)allTodos.set(todo[0],todo[1]);entry.ref.todos=new Map}return allTodos},execTodos=(todos)=>{let todosSorted=Array.from(todos.entries()).sort((x,y)=>x[0]-y[0]);for(let[_,todo]of todosSorted)todo()},addTodo=(txnId,journal,todoEffect)=>{let added=!1;for(let[,entry]of journal)if(!entry.ref.todos.has(txnId))entry.ref.todos.set(txnId,todoEffect),added=!0;return added};var OP_WITH_STM_RUNTIME="WithSTMRuntime",OP_ON_FAILURE2="OnFailure",OP_ON_RETRY="OnRetry",OP_ON_SUCCESS2="OnSuccess",OP_PROVIDE3="Provide",OP_SYNC2="Sync",OP_SUCCEED2="Succeed",OP_RETRY="Retry",OP_FAIL4="Fail",OP_DIE2="Die",OP_INTERRUPT2="Interrupt";var OP_FAIL5="Fail",OP_DIE3="Die",OP_INTERRUPT3="Interrupt",OP_SUCCEED3="Succeed",OP_RETRY2="Retry";var OP_DONE5="Done",OP_SUSPEND3="Suspend";var OP_DONE6="Done",OP_INTERRUPTED="Interrupted",OP_RUNNING2="Running";var STMStateSymbolKey="effect/STM/State",STMStateTypeId=Symbol.for(STMStateSymbolKey),isSTMState=(u)=>hasProperty(u,STMStateTypeId),isRunning2=(self)=>{return self._tag===OP_RUNNING2},isDone6=(self)=>{return self._tag===OP_DONE6};var done8=(exit3)=>{return{[STMStateTypeId]:STMStateTypeId,_tag:OP_DONE6,exit:exit3,[symbol](){return pipe(hash(STMStateSymbolKey),combine(hash(OP_DONE6)),combine(hash(exit3)),cached(this))},[symbol2](that){return isSTMState(that)&&that._tag===OP_DONE6&&equals(exit3,that.exit)}}},interruptedHash=pipe(hash(STMStateSymbolKey),combine(hash(OP_INTERRUPTED)),combine(hash("interrupted"))),interrupted2={[STMStateTypeId]:STMStateTypeId,_tag:OP_INTERRUPTED,[symbol](){return interruptedHash},[symbol2](that){return isSTMState(that)&&that._tag===OP_INTERRUPTED}},runningHash=pipe(hash(STMStateSymbolKey),combine(hash(OP_RUNNING2)),combine(hash("running"))),running3={[STMStateTypeId]:STMStateTypeId,_tag:OP_RUNNING2,[symbol](){return runningHash},[symbol2](that){return isSTMState(that)&&that._tag===OP_RUNNING2}},fromTExit=(tExit)=>{switch(tExit._tag){case OP_FAIL5:return done8(fail4(tExit.error));case OP_DIE3:return done8(die4(tExit.defect));case OP_INTERRUPT3:return done8(interrupt4(tExit.fiberId));case OP_SUCCEED3:return done8(succeed3(tExit.value));case OP_RETRY2:throw Error("BUG: STM.STMState.fromTExit - please report an issue at https://github.com/Effect-TS/effect/issues")}};var TExitSymbolKey="effect/TExit",TExitTypeId=Symbol.for(TExitSymbolKey),variance6={_A:(_)=>_,_E:(_)=>_},isExit2=(u)=>hasProperty(u,TExitTypeId);var isSuccess4=(self)=>{return self._tag===OP_SUCCEED3},isRetry=(self)=>{return self._tag===OP_RETRY2},fail13=(error2)=>({[TExitTypeId]:variance6,_tag:OP_FAIL5,error:error2,[symbol](){return pipe(hash(TExitSymbolKey),combine(hash(OP_FAIL5)),combine(hash(error2)),cached(this))},[symbol2](that){return isExit2(that)&&that._tag===OP_FAIL5&&equals(error2,that.error)}}),die8=(defect)=>({[TExitTypeId]:variance6,_tag:OP_DIE3,defect,[symbol](){return pipe(hash(TExitSymbolKey),combine(hash(OP_DIE3)),combine(hash(defect)),cached(this))},[symbol2](that){return isExit2(that)&&that._tag===OP_DIE3&&equals(defect,that.defect)}}),interrupt8=(fiberId3)=>({[TExitTypeId]:variance6,_tag:OP_INTERRUPT3,fiberId:fiberId3,[symbol](){return pipe(hash(TExitSymbolKey),combine(hash(OP_INTERRUPT3)),combine(hash(fiberId3)),cached(this))},[symbol2](that){return isExit2(that)&&that._tag===OP_INTERRUPT3&&equals(fiberId3,that.fiberId)}}),succeed13=(value)=>({[TExitTypeId]:variance6,_tag:OP_SUCCEED3,value,[symbol](){return pipe(hash(TExitSymbolKey),combine(hash(OP_SUCCEED3)),combine(hash(value)),cached(this))},[symbol2](that){return isExit2(that)&&that._tag===OP_SUCCEED3&&equals(value,that.value)}}),retryHash=pipe(hash(TExitSymbolKey),combine(hash(OP_RETRY2)),combine(hash("retry"))),retry4={[TExitTypeId]:variance6,_tag:OP_RETRY2,[symbol](){return retryHash},[symbol2](that){return isExit2(that)&&isRetry(that)}};var done9=(exit3)=>{return{_tag:OP_DONE5,exit:exit3}},suspend7=(journal)=>{return{_tag:OP_SUSPEND3,journal}};var txnCounter={ref:0},make46=()=>{let newId=txnCounter.ref+1;return txnCounter.ref=newId,newId};var STMSymbolKey2="effect/STM",STMTypeId2=Symbol.for(STMSymbolKey2),stmVariance={_R:(_)=>_,_E:(_)=>_,_A:(_)=>_};class STMPrimitive{effect_instruction_i0;_op=OP_COMMIT;effect_instruction_i1=void 0;effect_instruction_i2=void 0;[EffectTypeId3];[StreamTypeId];[SinkTypeId2];[ChannelTypeId2];get[STMTypeId2](){return stmVariance}constructor(effect_instruction_i0){this.effect_instruction_i0=effect_instruction_i0,this[EffectTypeId3]=effectVariance,this[StreamTypeId]=stmVariance,this[SinkTypeId2]=stmVariance,this[ChannelTypeId2]=stmVariance}[symbol2](that){return this===that}[symbol](){return cached(this,random(this))}[Symbol.iterator](){return new SingleShotGen2(new YieldWrap(this))}commit(){return unsafeAtomically(this,constVoid,constVoid)}pipe(){return pipeArguments(this,arguments)}}var unsafeAtomically=(self,onDone,onInterrupt3)=>withFiberRuntime((state)=>{let fiberId3=state.id(),env=state.getFiberRef(currentContext2),scheduler=state.getFiberRef(currentScheduler2),priority=state.getFiberRef(currentSchedulingPriority2),commitResult=tryCommitSync(fiberId3,self,env,scheduler,priority);switch(commitResult._tag){case OP_DONE5:return onDone(commitResult.exit),commitResult.exit;case OP_SUSPEND3:{let txnId=make46(),state2={value:running3},effect3=async((k)=>tryCommitAsync(fiberId3,self,txnId,state2,env,scheduler,priority,k));return uninterruptibleMask3((restore)=>pipe(restore(effect3),catchAllCause3((cause3)=>{let currentState=state2.value;if(isRunning2(currentState))state2.value=interrupted2;if(currentState=state2.value,isDone6(currentState))return onDone(currentState.exit),currentState.exit;return onInterrupt3(),failCause8(cause3)})))}}}),tryCommit=(fiberId3,stm,state,env,scheduler,priority)=>{let journal=new Map,tExit=new STMDriver(stm,journal,fiberId3,env).run(),analysis=analyzeJournal(journal);if(analysis===JournalAnalysisReadWrite)commitJournal(journal);else if(analysis===JournalAnalysisInvalid)throw Error("BUG: STM.TryCommit.tryCommit - please report an issue at https://github.com/Effect-TS/effect/issues");switch(tExit._tag){case OP_SUCCEED3:return state.value=fromTExit(tExit),completeTodos(succeed3(tExit.value),journal,scheduler,priority);case OP_FAIL5:{state.value=fromTExit(tExit);let cause3=fail3(tExit.error);return completeTodos(failCause3(cause3),journal,scheduler,priority)}case OP_DIE3:{state.value=fromTExit(tExit);let cause3=die3(tExit.defect);return completeTodos(failCause3(cause3),journal,scheduler,priority)}case OP_INTERRUPT3:{state.value=fromTExit(tExit);let cause3=interrupt3(fiberId3);return completeTodos(failCause3(cause3),journal,scheduler,priority)}case OP_RETRY2:return suspend7(journal)}},tryCommitSync=(fiberId3,stm,env,scheduler,priority)=>{let journal=new Map,tExit=new STMDriver(stm,journal,fiberId3,env).run(),analysis=analyzeJournal(journal);if(analysis===JournalAnalysisReadWrite&&isSuccess4(tExit))commitJournal(journal);else if(analysis===JournalAnalysisInvalid)throw Error("BUG: STM.TryCommit.tryCommitSync - please report an issue at https://github.com/Effect-TS/effect/issues");switch(tExit._tag){case OP_SUCCEED3:return completeTodos(succeed3(tExit.value),journal,scheduler,priority);case OP_FAIL5:{let cause3=fail3(tExit.error);return completeTodos(failCause3(cause3),journal,scheduler,priority)}case OP_DIE3:{let cause3=die3(tExit.defect);return completeTodos(failCause3(cause3),journal,scheduler,priority)}case OP_INTERRUPT3:{let cause3=interrupt3(fiberId3);return completeTodos(failCause3(cause3),journal,scheduler,priority)}case OP_RETRY2:return suspend7(journal)}},tryCommitAsync=(fiberId3,self,txnId,state,context5,scheduler,priority,k)=>{if(isRunning2(state.value)){let result=tryCommit(fiberId3,self,state,context5,scheduler,priority);switch(result._tag){case OP_DONE5:{completeTryCommit(result.exit,k);break}case OP_SUSPEND3:{addTodo(txnId,result.journal,()=>tryCommitAsync(fiberId3,self,txnId,state,context5,scheduler,priority,k));break}}}},completeTodos=(exit3,journal,scheduler,priority)=>{let todos=collectTodos(journal);if(todos.size>0)scheduler.scheduleTask(()=>execTodos(todos),priority);return done9(exit3)},completeTryCommit=(exit3,k)=>{k(exit3)};class STMDriver{self;journal;fiberId;contStack=[];env;constructor(self,journal,fiberId3,r0){this.self=self,this.journal=journal,this.fiberId=fiberId3,this.env=r0}getEnv(){return this.env}pushStack(cont){this.contStack.push(cont)}popStack(){return this.contStack.pop()}nextSuccess(){let current=this.popStack();while(current!==void 0&&current.effect_instruction_i0!==OP_ON_SUCCESS2)current=this.popStack();return current}nextFailure(){let current=this.popStack();while(current!==void 0&&current.effect_instruction_i0!==OP_ON_FAILURE2)current=this.popStack();return current}nextRetry(){let current=this.popStack();while(current!==void 0&&current.effect_instruction_i0!==OP_ON_RETRY)current=this.popStack();return current}run(){let curr=this.self,exit3=void 0;while(exit3===void 0&&curr!==void 0)try{let current=curr;if(current)switch(current._op){case"Tag":{curr=effect3((_,__,env)=>unsafeGet4(env,current));break}case"Left":{curr=fail14(current.left);break}case"None":{curr=fail14(new NoSuchElementException2);break}case"Right":{curr=succeed14(current.right);break}case"Some":{curr=succeed14(current.value);break}case"Commit":{switch(current.effect_instruction_i0){case OP_DIE2:{exit3=die8(internalCall(()=>current.effect_instruction_i1()));break}case OP_FAIL4:{let cont=this.nextFailure();if(cont===void 0)exit3=fail13(internalCall(()=>current.effect_instruction_i1()));else curr=internalCall(()=>cont.effect_instruction_i2(internalCall(()=>current.effect_instruction_i1())));break}case OP_RETRY:{let cont=this.nextRetry();if(cont===void 0)exit3=retry4;else curr=internalCall(()=>cont.effect_instruction_i2());break}case OP_INTERRUPT2:{exit3=interrupt8(this.fiberId);break}case OP_WITH_STM_RUNTIME:{curr=internalCall(()=>current.effect_instruction_i1(this));break}case OP_ON_SUCCESS2:case OP_ON_FAILURE2:case OP_ON_RETRY:{this.pushStack(current),curr=current.effect_instruction_i1;break}case OP_PROVIDE3:{let env=this.env;this.env=internalCall(()=>current.effect_instruction_i2(env)),curr=pipe(current.effect_instruction_i1,ensuring6(sync8(()=>this.env=env)));break}case OP_SUCCEED2:{let value=current.effect_instruction_i1,cont=this.nextSuccess();if(cont===void 0)exit3=succeed13(value);else curr=internalCall(()=>cont.effect_instruction_i2(value));break}case OP_SYNC2:{let value=internalCall(()=>current.effect_instruction_i1()),cont=this.nextSuccess();if(cont===void 0)exit3=succeed13(value);else curr=internalCall(()=>cont.effect_instruction_i2(value));break}}break}}}catch(e){curr=die9(e)}return exit3}}var catchAll6=dual(2,(self,f)=>{let stm=new STMPrimitive(OP_ON_FAILURE2);return stm.effect_instruction_i1=self,stm.effect_instruction_i2=f,stm});var die9=(defect)=>dieSync5(()=>defect);var dieSync5=(evaluate2)=>{let stm=new STMPrimitive(OP_DIE2);return stm.effect_instruction_i1=evaluate2,stm},effect3=(f)=>withSTMRuntime((_)=>succeed14(f(_.journal,_.fiberId,_.getEnv()))),ensuring6=dual(2,(self,finalizer)=>matchSTM(self,{onFailure:(e)=>zipRight8(finalizer,fail14(e)),onSuccess:(a)=>zipRight8(finalizer,succeed14(a))})),fail14=(error2)=>failSync6(()=>error2),failSync6=(evaluate2)=>{let stm=new STMPrimitive(OP_FAIL4);return stm.effect_instruction_i1=evaluate2,stm},flatMap15=dual(2,(self,f)=>{let stm=new STMPrimitive(OP_ON_SUCCESS2);return stm.effect_instruction_i1=self,stm.effect_instruction_i2=f,stm}),matchSTM=dual(2,(self,{onFailure,onSuccess})=>pipe(self,map21(right2),catchAll6((e)=>pipe(onFailure(e),map21(left2))),flatMap15((either6)=>{switch(either6._tag){case"Left":return succeed14(either6.left);case"Right":return onSuccess(either6.right)}}))),withSTMRuntime=(f)=>{let stm=new STMPrimitive(OP_WITH_STM_RUNTIME);return stm.effect_instruction_i1=f,stm};var interruptAs2=(fiberId3)=>{let stm=new STMPrimitive(OP_INTERRUPT2);return stm.effect_instruction_i1=fiberId3,stm},map21=dual(2,(self,f)=>pipe(self,flatMap15((a)=>sync8(()=>f(a)))));var retry5=new STMPrimitive(OP_RETRY),succeed14=(value)=>{let stm=new STMPrimitive(OP_SUCCEED2);return stm.effect_instruction_i1=value,stm},sync8=(evaluate2)=>{let stm=new STMPrimitive(OP_SYNC2);return stm.effect_instruction_i1=evaluate2,stm};var zipRight8=dual(2,(self,that)=>pipe(self,flatMap15(()=>that))),zipWith10=dual(3,(self,that,f)=>pipe(self,flatMap15((a)=>pipe(that,map21((b)=>f(a,b))))));var OP_BACKPRESSURE_STRATEGY="BackPressure",OP_DROPPING_STRATEGY="Dropping",OP_SLIDING_STRATEGY="Sliding";var as7=dual(2,(self,value)=>pipe(self,map21(()=>value)));var flatten11=(self)=>flatMap15(self,identity);var forEach8=dual((args2)=>isIterable(args2[0]),(iterable,f,options)=>{if(options?.discard)return pipe(sync8(()=>iterable[Symbol.iterator]()),flatMap15((iterator)=>{let loop3=suspend8(()=>{let next4=iterator.next();if(next4.done)return void_6;return pipe(f(next4.value),flatMap15(()=>loop3))});return loop3}));return suspend8(()=>fromIterable(iterable).reduce((acc,curr)=>zipWith10(acc,f(curr),(array4,elem)=>{return array4.push(elem),array4}),succeed14([])))});var all6=(input,options)=>{if(Symbol.iterator in input)return forEach8(input,identity,options);else if(options?.discard)return forEach8(Object.values(input),identity,options);return map21(forEach8(Object.entries(input),([_,e])=>map21(e,(a)=>[_,a])),(values3)=>{let res={};for(let[k,v]of values3)res[k]=v;return res})};var suspend8=(evaluate2)=>flatten11(sync8(evaluate2)),tap5=dual(2,(self,f)=>flatMap15(self,(a)=>as7(f(a),a)));var void_6=succeed14(void 0);var TRefSymbolKey="effect/TRef",TRefTypeId=Symbol.for(TRefSymbolKey),tRefVariance={_A:(_)=>_};class TRefImpl{[TRefTypeId]=tRefVariance;todos;versioned;constructor(value){this.versioned=new Versioned(value),this.todos=new Map}modify(f){return effect3((journal)=>{let entry=getOrMakeEntry(this,journal),[retValue,newValue]=f(unsafeGet6(entry));return unsafeSet(entry,newValue),retValue})}pipe(){return pipeArguments(this,arguments)}}var make47=(value)=>effect3((journal)=>{let ref=new TRefImpl(value);return journal.set(ref,make45(ref,!0)),ref}),get16=(self)=>self.modify((a)=>[a,a]),set7=dual(2,(self,value)=>self.modify(()=>[void 0,value]));var getOrMakeEntry=(self,journal)=>{if(journal.has(self))return journal.get(self);let entry=make45(self,!1);return journal.set(self,entry),entry},unsafeGet7=dual(2,(self,journal)=>unsafeGet6(getOrMakeEntry(self,journal))),unsafeSet2=dual(3,(self,value,journal)=>{let entry=getOrMakeEntry(self,journal);unsafeSet(entry,value);return});var TEnqueueSymbolKey="effect/TQueue/TEnqueue",TEnqueueTypeId=Symbol.for(TEnqueueSymbolKey),TDequeueSymbolKey="effect/TQueue/TDequeue",TDequeueTypeId=Symbol.for(TDequeueSymbolKey);var tDequeueVariance={_Out:(_)=>_},tEnqueueVariance={_In:(_)=>_};class TQueueImpl{ref;requestedCapacity;strategy;[TDequeueTypeId]=tDequeueVariance;[TEnqueueTypeId]=tEnqueueVariance;constructor(ref,requestedCapacity,strategy){this.ref=ref,this.requestedCapacity=requestedCapacity,this.strategy=strategy}capacity(){return this.requestedCapacity}size=withSTMRuntime((runtime4)=>{let queue=unsafeGet7(this.ref,runtime4.journal);if(queue===void 0)return interruptAs2(runtime4.fiberId);return succeed14(queue.length)});isFull=map21(this.size,(size12)=>size12===this.requestedCapacity);isEmpty=map21(this.size,(size12)=>size12===0);shutdown=withSTMRuntime((runtime4)=>{return unsafeSet2(this.ref,void 0,runtime4.journal),void_6});isShutdown=effect3((journal)=>{return unsafeGet7(this.ref,journal)===void 0});awaitShutdown=flatMap15(this.isShutdown,(isShutdown4)=>isShutdown4?void_6:retry5);offer(value){return withSTMRuntime((runtime4)=>{let queue=pipe(this.ref,unsafeGet7(runtime4.journal));if(queue===void 0)return interruptAs2(runtime4.fiberId);if(queue.length<this.requestedCapacity)return queue.push(value),unsafeSet2(this.ref,queue,runtime4.journal),succeed14(!0);switch(this.strategy._tag){case OP_BACKPRESSURE_STRATEGY:return retry5;case OP_DROPPING_STRATEGY:return succeed14(!1);case OP_SLIDING_STRATEGY:{if(queue.length===0)return succeed14(!0);return queue.shift(),queue.push(value),unsafeSet2(this.ref,queue,runtime4.journal),succeed14(!0)}}})}offerAll(iterable){return withSTMRuntime((runtime4)=>{let as8=Array.from(iterable),queue=unsafeGet7(this.ref,runtime4.journal);if(queue===void 0)return interruptAs2(runtime4.fiberId);if(queue.length+as8.length<=this.requestedCapacity)return unsafeSet2(this.ref,[...queue,...as8],runtime4.journal),succeed14(!0);switch(this.strategy._tag){case OP_BACKPRESSURE_STRATEGY:return retry5;case OP_DROPPING_STRATEGY:{let forQueue=as8.slice(0,this.requestedCapacity-queue.length);return unsafeSet2(this.ref,[...queue,...forQueue],runtime4.journal),succeed14(!1)}case OP_SLIDING_STRATEGY:{let forQueue=as8.slice(0,this.requestedCapacity-queue.length),toDrop=queue.length+forQueue.length-this.requestedCapacity,newQueue=queue.slice(toDrop);return unsafeSet2(this.ref,[...newQueue,...forQueue],runtime4.journal),succeed14(!0)}}})}peek=withSTMRuntime((runtime4)=>{let queue=unsafeGet7(this.ref,runtime4.journal);if(queue===void 0)return interruptAs2(runtime4.fiberId);if(queue.length===0)return retry5;return succeed14(queue[0])});peekOption=withSTMRuntime((runtime4)=>{let queue=unsafeGet7(this.ref,runtime4.journal);if(queue===void 0)return interruptAs2(runtime4.fiberId);return succeed14(fromNullable(queue[0]))});take=withSTMRuntime((runtime4)=>{let queue=unsafeGet7(this.ref,runtime4.journal);if(queue===void 0)return interruptAs2(runtime4.fiberId);if(queue.length===0)return retry5;let dequeued=queue.shift();return unsafeSet2(this.ref,queue,runtime4.journal),succeed14(dequeued)});takeAll=withSTMRuntime((runtime4)=>{let queue=unsafeGet7(this.ref,runtime4.journal);if(queue===void 0)return interruptAs2(runtime4.fiberId);return unsafeSet2(this.ref,[],runtime4.journal),succeed14(queue)});takeUpTo(max6){return withSTMRuntime((runtime4)=>{let queue=unsafeGet7(this.ref,runtime4.journal);if(queue===void 0)return interruptAs2(runtime4.fiberId);let[toTake,remaining]=splitAt2(unsafeFromArray(queue),max6);return unsafeSet2(this.ref,Array.from(remaining),runtime4.journal),succeed14(Array.from(toTake))})}}var isShutdown4=(self)=>self.isShutdown;var shutdown5=(self)=>self.shutdown;var take4=(self)=>self.take;var TPubSubSymbolKey="effect/TPubSub",TPubSubTypeId=Symbol.for(TPubSubSymbolKey),AbsentValue2=Symbol.for("effect/TPubSub/AbsentValue"),makeNode2=(head6,subscribers,tail)=>({head:head6,subscribers,tail});class TPubSubImpl{pubsubSize;publisherHead;publisherTail;requestedCapacity;strategy;subscriberCount;subscribers;[TPubSubTypeId]={_A:(_)=>_};[TEnqueueTypeId]=tEnqueueVariance;constructor(pubsubSize,publisherHead,publisherTail,requestedCapacity,strategy,subscriberCount,subscribers){this.pubsubSize=pubsubSize,this.publisherHead=publisherHead,this.publisherTail=publisherTail,this.requestedCapacity=requestedCapacity,this.strategy=strategy,this.subscriberCount=subscriberCount,this.subscribers=subscribers}isShutdown=effect3((journal)=>{return unsafeGet7(this.publisherTail,journal)===void 0});awaitShutdown=flatMap15(this.isShutdown,(isShutdown5)=>isShutdown5?void_6:retry5);capacity(){return this.requestedCapacity}size=withSTMRuntime((runtime4)=>{if(unsafeGet7(this.publisherTail,runtime4.journal)===void 0)return interruptAs2(runtime4.fiberId);return succeed14(unsafeGet7(this.pubsubSize,runtime4.journal))});isEmpty=map21(this.size,(size12)=>size12===0);isFull=map21(this.size,(size12)=>size12===this.capacity());offer(value){return withSTMRuntime((runtime4)=>{let currentPublisherTail=unsafeGet7(this.publisherTail,runtime4.journal);if(currentPublisherTail===void 0)return interruptAs2(runtime4.fiberId);let currentSubscriberCount=unsafeGet7(this.subscriberCount,runtime4.journal);if(currentSubscriberCount===0)return succeed14(!0);let currentPubSubSize=unsafeGet7(this.pubsubSize,runtime4.journal);if(currentPubSubSize<this.requestedCapacity){let updatedPublisherTail=new TRefImpl(void 0),updatedNode=makeNode2(value,currentSubscriberCount,updatedPublisherTail);return unsafeSet2(currentPublisherTail,updatedNode,runtime4.journal),unsafeSet2(this.publisherTail,updatedPublisherTail,runtime4.journal),unsafeSet2(this.pubsubSize,currentPubSubSize+1,runtime4.journal),succeed14(!0)}switch(this.strategy._tag){case OP_BACKPRESSURE_STRATEGY:return retry5;case OP_DROPPING_STRATEGY:return succeed14(!1);case OP_SLIDING_STRATEGY:{if(this.requestedCapacity>0){let currentPublisherHead=unsafeGet7(this.publisherHead,runtime4.journal),loop3=!0;while(loop3){let node=unsafeGet7(currentPublisherHead,runtime4.journal);if(node===void 0)return retry5;let{head:head6,tail}=node;if(head6!==AbsentValue2){let updatedNode2=makeNode2(AbsentValue2,node.subscribers,node.tail);unsafeSet2(currentPublisherHead,updatedNode2,runtime4.journal),unsafeSet2(this.publisherHead,tail,runtime4.journal),loop3=!1}else currentPublisherHead=tail}}let updatedPublisherTail=new TRefImpl(void 0),updatedNode=makeNode2(value,currentSubscriberCount,updatedPublisherTail);return unsafeSet2(currentPublisherTail,updatedNode,runtime4.journal),unsafeSet2(this.publisherTail,updatedPublisherTail,runtime4.journal),succeed14(!0)}}})}offerAll(iterable){return map21(forEach8(iterable,(a)=>this.offer(a)),every(identity))}shutdown=effect3((journal)=>{if(unsafeGet7(this.publisherTail,journal)!==void 0){unsafeSet2(this.publisherTail,void 0,journal);let currentSubscribers=unsafeGet7(this.subscribers,journal);forEach3(currentSubscribers,(subscriber)=>{unsafeSet2(subscriber,void 0,journal)}),unsafeSet2(this.subscribers,empty5(),journal)}})}class TPubSubSubscriptionImpl{pubsubSize;publisherHead;requestedCapacity;subscriberHead;subscriberCount;subscribers;[TPubSubTypeId]=TPubSubTypeId;[TDequeueTypeId]=tDequeueVariance;constructor(pubsubSize,publisherHead,requestedCapacity,subscriberHead,subscriberCount,subscribers){this.pubsubSize=pubsubSize,this.publisherHead=publisherHead,this.requestedCapacity=requestedCapacity,this.subscriberHead=subscriberHead,this.subscriberCount=subscriberCount,this.subscribers=subscribers}isShutdown=effect3((journal)=>{return unsafeGet7(this.subscriberHead,journal)===void 0});awaitShutdown=flatMap15(this.isShutdown,(isShutdown5)=>isShutdown5?void_6:retry5);capacity(){return this.requestedCapacity}size=withSTMRuntime((runtime4)=>{let currentSubscriberHead=unsafeGet7(this.subscriberHead,runtime4.journal);if(currentSubscriberHead===void 0)return interruptAs2(runtime4.fiberId);let loop3=!0,size12=0;while(loop3){let node=unsafeGet7(currentSubscriberHead,runtime4.journal);if(node===void 0)loop3=!1;else{let{head:head6,tail}=node;if(head6!==AbsentValue2){if(size12=size12+1,size12>=Number.MAX_SAFE_INTEGER)loop3=!1}currentSubscriberHead=tail}}return succeed14(size12)});isEmpty=map21(this.size,(size12)=>size12===0);isFull=map21(this.size,(size12)=>size12===this.capacity());peek=withSTMRuntime((runtime4)=>{let currentSubscriberHead=unsafeGet7(this.subscriberHead,runtime4.journal);if(currentSubscriberHead===void 0)return interruptAs2(runtime4.fiberId);let value=AbsentValue2,loop3=!0;while(loop3){let node=unsafeGet7(currentSubscriberHead,runtime4.journal);if(node===void 0)return retry5;let{head:head6,tail}=node;if(head6!==AbsentValue2)value=head6,loop3=!1;else currentSubscriberHead=tail}return succeed14(value)});peekOption=withSTMRuntime((runtime4)=>{let currentSubscriberHead=unsafeGet7(this.subscriberHead,runtime4.journal);if(currentSubscriberHead===void 0)return interruptAs2(runtime4.fiberId);let value=none2(),loop3=!0;while(loop3){let node=unsafeGet7(currentSubscriberHead,runtime4.journal);if(node===void 0)value=none2(),loop3=!1;else{let{head:head6,tail}=node;if(head6!==AbsentValue2)value=some2(head6),loop3=!1;else currentSubscriberHead=tail}}return succeed14(value)});shutdown=effect3((journal)=>{let currentSubscriberHead=unsafeGet7(this.subscriberHead,journal);if(currentSubscriberHead!==void 0){unsafeSet2(this.subscriberHead,void 0,journal);let loop3=!0;while(loop3){let node=unsafeGet7(currentSubscriberHead,journal);if(node===void 0)loop3=!1;else{let{head:head6,tail}=node;if(head6!==AbsentValue2){let subscribers=node.subscribers;if(subscribers===1){let size12=unsafeGet7(this.pubsubSize,journal),updatedNode=makeNode2(AbsentValue2,0,tail);unsafeSet2(currentSubscriberHead,updatedNode,journal),unsafeSet2(this.publisherHead,tail,journal),unsafeSet2(this.pubsubSize,size12-1,journal)}else{let updatedNode=makeNode2(head6,subscribers-1,tail);unsafeSet2(currentSubscriberHead,updatedNode,journal)}}currentSubscriberHead=tail}}let currentSubscriberCount=unsafeGet7(this.subscriberCount,journal);unsafeSet2(this.subscriberCount,currentSubscriberCount-1,journal),unsafeSet2(this.subscribers,remove4(unsafeGet7(this.subscribers,journal),this.subscriberHead),journal)}});take=withSTMRuntime((runtime4)=>{let currentSubscriberHead=unsafeGet7(this.subscriberHead,runtime4.journal);if(currentSubscriberHead===void 0)return interruptAs2(runtime4.fiberId);let value=AbsentValue2,loop3=!0;while(loop3){let node=unsafeGet7(currentSubscriberHead,runtime4.journal);if(node===void 0)return retry5;let{head:head6,tail}=node;if(head6!==AbsentValue2){let subscribers=node.subscribers;if(subscribers===1){let size12=unsafeGet7(this.pubsubSize,runtime4.journal),updatedNode=makeNode2(AbsentValue2,0,tail);unsafeSet2(currentSubscriberHead,updatedNode,runtime4.journal),unsafeSet2(this.publisherHead,tail,runtime4.journal),unsafeSet2(this.pubsubSize,size12-1,runtime4.journal)}else{let updatedNode=makeNode2(head6,subscribers-1,tail);unsafeSet2(currentSubscriberHead,updatedNode,runtime4.journal)}unsafeSet2(this.subscriberHead,tail,runtime4.journal),value=head6,loop3=!1}else currentSubscriberHead=tail}return succeed14(value)});takeAll=this.takeUpTo(Number.POSITIVE_INFINITY);takeUpTo(max6){return withSTMRuntime((runtime4)=>{let currentSubscriberHead=unsafeGet7(this.subscriberHead,runtime4.journal);if(currentSubscriberHead===void 0)return interruptAs2(runtime4.fiberId);let builder=[],n=0;while(n!==max6){let node=unsafeGet7(currentSubscriberHead,runtime4.journal);if(node===void 0)n=max6;else{let{head:head6,tail}=node;if(head6!==AbsentValue2){let subscribers=node.subscribers;if(subscribers===1){let size12=unsafeGet7(this.pubsubSize,runtime4.journal),updatedNode=makeNode2(AbsentValue2,0,tail);unsafeSet2(currentSubscriberHead,updatedNode,runtime4.journal),unsafeSet2(this.publisherHead,tail,runtime4.journal),unsafeSet2(this.pubsubSize,size12-1,runtime4.journal)}else{let updatedNode=makeNode2(head6,subscribers-1,tail);unsafeSet2(currentSubscriberHead,updatedNode,runtime4.journal)}builder.push(head6),n=n+1}currentSubscriberHead=tail}}return unsafeSet2(this.subscriberHead,currentSubscriberHead,runtime4.journal),succeed14(builder)})}}var makeSubscription2=(pubsubSize,publisherHead,publisherTail,requestedCapacity,subscriberCount,subscribers)=>pipe(get16(publisherTail),flatMap15((currentPublisherTail)=>pipe(all6([make47(currentPublisherTail),get16(subscriberCount),get16(subscribers)]),tap5(([_,currentSubscriberCount])=>pipe(subscriberCount,set7(currentSubscriberCount+1))),tap5(([subscriberHead,_,currentSubscribers])=>pipe(subscribers,set7(pipe(currentSubscribers,add2(subscriberHead))))),map21(([subscriberHead])=>new TPubSubSubscriptionImpl(pubsubSize,publisherHead,requestedCapacity,subscriberHead,subscriberCount,subscribers)))));var subscribe3=(self)=>makeSubscription2(self.pubsubSize,self.publisherHead,self.publisherTail,self.requestedCapacity,self.subscriberCount,self.subscribers),subscribeScoped=(self)=>acquireRelease2(subscribe3(self),(dequeue)=>shutdown5(dequeue));var subscribeScoped2=subscribeScoped;var isShutdown6=isShutdown4;var take5=take4;class RingBuffer{capacity;array;size=0;current=0;constructor(capacity7){this.capacity=capacity7,this.array=Array.from({length:capacity7},constUndefined)}head(){return fromNullable(this.array[this.current])}lastOrNull(){if(this.size===0)return;let index=this.current===0?this.array.length-1:this.current-1;return this.array[index]??void 0}put(value){this.array[this.current]=value,this.increment()}dropLast(){if(this.size>0)this.decrement(),this.array[this.current]=void 0}toChunk(){let begin=this.current-this.size,newArray=begin<0?[...this.array.slice(this.capacity+begin,this.capacity),...this.array.slice(0,this.current)]:this.array.slice(begin,this.current);return fromIterable2(newArray)}increment(){if(this.size<this.capacity)this.size+=1;this.current=(this.current+1)%this.capacity}decrement(){if(this.size-=1,this.current>0)this.current-=1;else this.current=this.capacity-1}}var OP_NOT_STARTED="NotStarted",OP_PREVIOUS="Previous",OP_CURRENT="Current",notStarted={_tag:"NotStarted"},previous=(fiber)=>({_tag:"Previous",fiber}),current=(fiber)=>({_tag:"Current",fiber});var make48=(emit)=>{return Object.assign(emit,{chunk(as8){return this(succeed9(as8))},die(defect){return this(die6(defect))},dieMessage(message){return this(dieMessage2(message))},done(exit3){return this(suspend3(()=>mapBoth2(exit3,{onFailure:some2,onSuccess:of2})))},end(){return this(fail9(none2()))},fail(e){return this(fail9(some2(e)))},fromEffect(effect4){return this(mapBoth4(effect4,{onFailure:some2,onSuccess:of2}))},fromEffectChunk(effect4){return this(pipe(effect4,mapError3(some2)))},halt(cause3){return this(failCause8(pipe(cause3,map11(some2))))},single(value){return this(succeed9(of2(value)))}})},makePush=(queue,scheduler)=>{let finished=!1,buffer=[],running4=!1;function array4(items){if(finished)return!1;if(items.length<=50000)buffer.push.apply(buffer,items);else for(let i=0;i<items.length;i++)buffer.push(items[0]);if(!running4)running4=!0,scheduler.scheduleTask(flush,0);return!0}function flush(){if(running4=!1,buffer.length>0)queue.unsafeOffer(buffer),buffer=[]}function done10(exit3){if(finished)return;if(finished=!0,exit3._tag==="Success")buffer.push(exit3.value);flush(),queue.unsafeOffer(exit3._tag==="Success"?void_3:exit3)}return{single(value){if(finished)return!1;if(buffer.push(value),!running4)running4=!0,scheduler.scheduleTask(flush,0);return!0},array:array4,chunk(chunk2){return array4(toReadonlyArray(chunk2))},done:done10,end(){if(finished)return;finished=!0,flush(),queue.unsafeOffer(void_3)},halt(cause3){return done10(failCause3(cause3))},fail(error2){return done10(fail4(error2))},die(defect){return done10(die4(defect))},dieMessage(message){return done10(die4(Error(message)))}}};var HandoffTypeId=Symbol.for("effect/Stream/Handoff"),OP_HANDOFF_STATE_EMPTY="Empty",OP_HANDOFF_STATE_FULL="Full",handoffStateEmpty=(notifyConsumer)=>({_tag:OP_HANDOFF_STATE_EMPTY,notifyConsumer}),handoffStateFull=(value,notifyProducer)=>({_tag:OP_HANDOFF_STATE_FULL,value,notifyProducer}),handoffStateMatch=(onEmpty,onFull)=>{return(self)=>{switch(self._tag){case OP_HANDOFF_STATE_EMPTY:return onEmpty(self.notifyConsumer);case OP_HANDOFF_STATE_FULL:return onFull(self.value,self.notifyProducer)}}},handoffVariance={_A:(_)=>_},make49=()=>pipe(make39(),flatMap11((deferred)=>make24(handoffStateEmpty(deferred))),map16((ref)=>({[HandoffTypeId]:handoffVariance,ref}))),offer5=dual(2,(self,value)=>{return flatMap11(make39(),(deferred)=>flatten8(modify4(self.ref,(state)=>pipe(state,handoffStateMatch((notifyConsumer)=>[zipRight4(succeed7(notifyConsumer,void 0),_await3(deferred)),handoffStateFull(value,deferred)],(_,notifyProducer)=>[flatMap11(_await3(notifyProducer),()=>pipe(self,offer5(value))),state])))))}),take6=(self)=>flatMap11(make39(),(deferred)=>flatten8(modify4(self.ref,(state)=>pipe(state,handoffStateMatch((notifyConsumer)=>[flatMap11(_await3(notifyConsumer),()=>take6(self)),state],(value,notifyProducer)=>[as4(succeed7(notifyProducer,void 0),value),handoffStateEmpty(deferred)])))));var OP_EMIT4="Emit",OP_HALT="Halt",OP_END="End",emit=(elements)=>({_tag:"Emit",elements}),halt=(cause3)=>({_tag:"Halt",cause:cause3}),end3=(reason)=>({_tag:"End",reason});var TakeSymbolKey="effect/Take",TakeTypeId=Symbol.for(TakeSymbolKey),takeVariance={_A:(_)=>_,_E:(_)=>_};class TakeImpl{exit;[TakeTypeId]=takeVariance;constructor(exit3){this.exit=exit3}pipe(){return pipeArguments(this,arguments)}}var chunk2=(chunk3)=>new TakeImpl(succeed3(chunk3));var done10=(self)=>suspend3(()=>self.exit),end4=new TakeImpl(fail4(none2()));var failCause11=(cause3)=>new TakeImpl(failCause3(pipe(cause3,map11(some2))));var fromPull=(pull)=>matchCause3(pull,{onFailure:(cause3)=>match2(flipCauseOption2(cause3),{onNone:()=>end4,onSome:failCause11}),onSuccess:chunk2});var match18=dual(2,(self,{onEnd,onFailure,onSuccess})=>match9(self.exit,{onFailure:(cause3)=>match2(flipCauseOption2(cause3),{onNone:onEnd,onSome:onFailure}),onSuccess}));var of5=(value)=>new TakeImpl(succeed3(of2(value)));var end5=()=>fail9(none2());var failCause12=(cause3)=>mapError3(failCause8(cause3),some2);var OP_SCHEDULE_END="ScheduleEnd",OP_UPSTREAM_END="UpstreamEnd",ScheduleEnd={_tag:"ScheduleEnd"},UpstreamEnd={_tag:"UpstreamEnd"};var OP_DRAIN_LEFT="DrainLeft",OP_DRAIN_RIGHT="DrainRight",OP_PULL_BOTH="PullBoth",OP_PULL_LEFT="PullLeft",OP_PULL_RIGHT="PullRight",DrainLeft={_tag:"DrainLeft"},DrainRight={_tag:"DrainRight"},PullBoth={_tag:"PullBoth"},PullLeft=(rightChunk)=>({_tag:"PullLeft",rightChunk}),PullRight=(leftChunk)=>({_tag:"PullRight",leftChunk});var OP_PULL_BOTH2="PullBoth",OP_PULL_LEFT2="PullLet",OP_PULL_RIGHT2="PullRight",PullBoth2={_tag:"PullBoth"},PullLeft2=(rightChunk)=>({_tag:"PullLet",rightChunk}),PullRight2=(leftChunk)=>({_tag:"PullRight",leftChunk});var StreamSymbolKey="effect/Stream",StreamTypeId2=Symbol.for(StreamSymbolKey),streamVariance={_R:(_)=>_,_E:(_)=>_,_A:(_)=>_};class StreamImpl{channel;[StreamTypeId2]=streamVariance;constructor(channel){this.channel=channel}pipe(){return pipeArguments(this,arguments)}}var isStream=(u)=>hasProperty(u,StreamTypeId2)||isEffect2(u),DefaultChunkSize=4096,accumulate=(self)=>chunks(accumulateChunks(self)),accumulateChunks=(self)=>{let accumulator=(s)=>readWith({onInput:(input)=>{let next4=appendAll2(s,input);return flatMap13(write(next4),()=>accumulator(next4))},onFailure:fail11,onDone:()=>void_5});return new StreamImpl(pipeTo(toChannel2(self),accumulator(empty2())))},acquireRelease3=(acquire,release)=>scoped5(acquireRelease2(acquire,release)),aggregate=dual(2,(self,sink)=>aggregateWithin(self,sink,forever4)),aggregateWithin=dual(3,(self,sink,schedule2)=>filterMap6(aggregateWithinEither(self,sink,schedule2),(_)=>match(_,{onLeft:none2,onRight:some2}))),aggregateWithinEither=dual(3,(self,sink,schedule2)=>{let layer=all5([make49(),make24(ScheduleEnd),make24(empty2()),driver2(schedule2),make24(!1),make24(!1)]);return fromEffect7(layer).pipe(flatMap16(([handoff,sinkEndReason,sinkLeftovers,scheduleDriver,consumed,endAfterEmit])=>{let handoffProducer=readWithCause({onInput:(input)=>flatMap13(fromEffect4(pipe(handoff,offer5(emit(input)),when2(()=>isNonEmpty(input)))),()=>handoffProducer),onFailure:(cause3)=>fromEffect4(offer5(handoff,halt(cause3))),onDone:()=>fromEffect4(offer5(handoff,end3(UpstreamEnd)))}),handoffConsumer=pipe(getAndSet2(sinkLeftovers,empty2()),flatMap11((leftovers)=>{if(isNonEmpty(leftovers))return pipe(set5(consumed,!0),zipRight4(succeed9(pipe(write(leftovers),flatMap13(()=>handoffConsumer)))));return pipe(take6(handoff),map16((signal)=>{switch(signal._tag){case OP_EMIT4:return pipe(fromEffect4(set5(consumed,!0)),zipRight6(write(signal.elements)),zipRight6(fromEffect4(get11(endAfterEmit))),flatMap13((bool)=>bool?void_5:handoffConsumer));case OP_HALT:return failCause10(signal.cause);case OP_END:{if(signal.reason._tag===OP_SCHEDULE_END)return pipe(get11(consumed),map16((bool)=>bool?fromEffect4(pipe(set5(sinkEndReason,ScheduleEnd),zipRight4(set5(endAfterEmit,!0)))):pipe(fromEffect4(pipe(set5(sinkEndReason,ScheduleEnd),zipRight4(set5(endAfterEmit,!0)))),flatMap13(()=>handoffConsumer))),unwrap);return pipe(set5(sinkEndReason,signal.reason),zipRight4(set5(endAfterEmit,!0)),fromEffect4)}}}))}),unwrap),timeout3=(lastB)=>scheduleDriver.next(lastB),scheduledAggregator=(sinkFiber,scheduleFiber,scope5)=>{let forkSink=pipe(set5(consumed,!1),zipRight4(set5(endAfterEmit,!1)),zipRight4(pipe(handoffConsumer,pipeToOrFail(toChannel(sink)),collectElements,run3,forkIn2(scope5)))),handleSide=(leftovers,b,c)=>pipe(set5(sinkLeftovers,flatten2(leftovers)),zipRight4(map16(get11(sinkEndReason),(reason)=>{switch(reason._tag){case OP_SCHEDULE_END:return pipe(all5([get11(consumed),forkSink,pipe(timeout3(some2(b)),forkIn2(scope5))]),map16(([wasConsumed,sinkFiber2,scheduleFiber2])=>{let toWrite=pipe(c,match2({onNone:()=>of2(right2(b)),onSome:(c2)=>make4(right2(b),left2(c2))}));if(wasConsumed)return pipe(write(toWrite),flatMap13(()=>scheduledAggregator(sinkFiber2,scheduleFiber2,scope5)));return scheduledAggregator(sinkFiber2,scheduleFiber2,scope5)}),unwrap);case OP_UPSTREAM_END:return pipe(get11(consumed),map16((wasConsumed)=>wasConsumed?write(of2(right2(b))):void_5),unwrap)}})),unwrap);return unwrap(raceWith2(join3(sinkFiber),join3(scheduleFiber),{onSelfDone:(sinkExit,_)=>pipe(interrupt5(scheduleFiber),zipRight4(pipe(suspend3(()=>sinkExit),map16(([leftovers,b])=>handleSide(leftovers,b,none2()))))),onOtherDone:(scheduleExit,_)=>matchCauseEffect3(suspend3(()=>scheduleExit),{onFailure:(cause3)=>match(failureOrCause2(cause3),{onLeft:()=>pipe(handoff,offer5(end3(ScheduleEnd)),forkDaemon2,zipRight4(pipe(join3(sinkFiber),map16(([leftovers,b])=>handleSide(leftovers,b,none2()))))),onRight:(cause4)=>pipe(handoff,offer5(halt(cause4)),forkDaemon2,zipRight4(pipe(join3(sinkFiber),map16(([leftovers,b])=>handleSide(leftovers,b,none2())))))}),onSuccess:(c)=>pipe(handoff,offer5(end3(ScheduleEnd)),forkDaemon2,zipRight4(pipe(join3(sinkFiber),map16(([leftovers,b])=>handleSide(leftovers,b,some2(c))))))})}))};return unwrapScopedWith3((scope5)=>pipeTo(toChannel2(self),handoffProducer).pipe(run3,forkIn2(scope5),zipRight4(pipeToOrFail(handoffConsumer,toChannel(sink)).pipe(collectElements,run3,forkIn2(scope5),flatMap11((sinkFiber)=>timeout3(none2()).pipe(forkIn2(scope5),map16((scheduleFiber)=>new StreamImpl(scheduledAggregator(sinkFiber,scheduleFiber,scope5)))))))))}))}),as8=dual(2,(self,value)=>map22(self,()=>value)),queueFromBufferOptions=(bufferSize)=>{if(bufferSize==="unbounded")return unbounded3();else if(typeof bufferSize==="number"||bufferSize===void 0)return bounded3(bufferSize??16);switch(bufferSize.strategy){case"dropping":return dropping2(bufferSize.bufferSize??16);case"sliding":return sliding2(bufferSize.bufferSize??16);default:return bounded3(bufferSize.bufferSize??16)}},_async=(register,bufferSize)=>acquireRelease2(queueFromBufferOptions(bufferSize),(queue)=>shutdown2(queue)).pipe(flatMap11((output)=>runtime3().pipe(flatMap11((runtime4)=>sync4(()=>{let runPromiseExit3=runPromiseExit2(runtime4);return register(make48((resume2)=>fromPull(resume2).pipe(flatMap11((take7)=>offer3(output,take7)),asVoid3,runPromiseExit3).then((exit3)=>{if(isFailure3(exit3)){if(!isInterrupted2(exit3.cause))throw squash(exit3.cause)}})))})),map16((value)=>{let loop3=take3(output).pipe(flatMap11((take7)=>done10(take7)),match13({onFailure:(maybeError)=>fromEffect4(shutdown2(output)).pipe(zipRight6(match2(maybeError,{onNone:()=>void_5,onSome:(error2)=>fail11(error2)}))),onSuccess:(chunk3)=>write(chunk3).pipe(flatMap13(()=>loop3))}),unwrap);return fromChannel2(loop3).pipe(ensuring7(value??_void))}))),unwrapScoped4),asyncEffect3=(register,bufferSize)=>pipe(acquireRelease2(queueFromBufferOptions(bufferSize),(queue)=>shutdown2(queue)),flatMap11((output)=>pipe(runtime3(),flatMap11((runtime4)=>pipe(register(make48((k)=>pipe(fromPull(k),flatMap11((take7)=>offer3(output,take7)),asVoid3,runPromiseExit2(runtime4)).then((exit3)=>{if(isFailure3(exit3)){if(!isInterrupted2(exit3.cause))throw squash(exit3.cause)}}))),map16(()=>{let loop3=pipe(take3(output),flatMap11(done10),match13({onFailure:(maybeError)=>pipe(fromEffect4(shutdown2(output)),zipRight6(match2(maybeError,{onNone:()=>void_5,onSome:fail11}))),onSuccess:(chunk3)=>pipe(write(chunk3),flatMap13(()=>loop3))}),unwrap);return loop3}))))),unwrapScoped3,fromChannel2),queueFromBufferOptionsPush=(options)=>{if(options?.bufferSize==="unbounded"||options?.bufferSize===void 0&&options?.strategy===void 0)return unbounded3();switch(options?.strategy){case"sliding":return sliding2(options.bufferSize??16);default:return dropping2(options?.bufferSize??16)}},asyncPush=(register,options)=>acquireRelease2(queueFromBufferOptionsPush(options),shutdown2).pipe(tap3((queue)=>getWith(currentScheduler2,(scheduler)=>register(makePush(queue,scheduler)))),map16((queue)=>{let loop3=flatMap13(take3(queue),(item)=>isExit(item)?isSuccess2(item)?void_5:failCause10(item.cause):zipRight6(write(unsafeFromArray(item)),loop3));return loop3}),unwrapScoped3,fromChannel2),asyncScoped=(register,bufferSize)=>pipe(acquireRelease2(queueFromBufferOptions(bufferSize),(queue)=>shutdown2(queue)),flatMap11((output)=>pipe(runtime3(),flatMap11((runtime4)=>pipe(register(make48((k)=>pipe(fromPull(k),flatMap11((take7)=>offer3(output,take7)),asVoid3,runPromiseExit2(runtime4)).then((exit3)=>{if(isFailure3(exit3)){if(!isInterrupted2(exit3.cause))throw squash(exit3.cause)}}))),zipRight4(make24(!1)),flatMap11((ref)=>pipe(get11(ref),map16((isDone7)=>isDone7?end5():pipe(take3(output),flatMap11(done10),onError2(()=>pipe(set5(ref,!0),zipRight4(shutdown2(output)))))))))))),scoped5,flatMap16(repeatEffectChunkOption)),branchAfter=dual(3,(self,n,f)=>suspend9(()=>{let buffering=(acc)=>readWith({onInput:(input)=>{if(acc.length+input.length>=n){let[b1,b2]=pipe(input,splitAt2(n-acc.length));return running4(pipe(acc,appendAll2(b1)),b2)}return buffering(pipe(acc,appendAll2(input)))},onFailure:fail11,onDone:()=>running4(acc,empty2())}),running4=(prefix,leftover)=>pipeTo(zipRight6(write(leftover),identityChannel()),toChannel2(f(prefix)));return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(buffering(empty2()))))})),broadcast=dual(3,(self,n,maximumLag)=>pipe(self,broadcastedQueues(n,maximumLag),map16((tuple2)=>tuple2.map((queue)=>flattenTake(fromQueue2(queue,{shutdown:!0})))))),broadcastDynamic=dual(2,(self,maximumLag)=>map16(toPubSub2(self,maximumLag),(pubsub)=>flattenTake(fromPubSub(pubsub)))),share=dual(2,(self,options)=>map16(make44({acquire:broadcastDynamic(self,options),idleTimeToLive:options.idleTimeToLive}),(rcRef)=>unwrapScoped4(get15(rcRef)))),broadcastedQueues=dual(3,(self,n,maximumLag)=>flatMap11(pubsubFromOptions(maximumLag),(pubsub)=>pipe(all5(Array.from({length:n},()=>subscribe2(pubsub))),tap3(()=>forkScoped2(runIntoPubSubScoped(self,pubsub)))))),broadcastedQueuesDynamic=dual(2,(self,maximumLag)=>map16(toPubSub2(self,maximumLag),subscribe2)),buffer=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);let queue=toQueueOfElements(self,options);return new StreamImpl(unwrapScoped3(map16(queue,(queue2)=>{let process2=pipe(fromEffect4(take3(queue2)),flatMap13(match9({onFailure:(cause3)=>pipe(flipCauseOption2(cause3),match2({onNone:()=>void_5,onSome:failCause10})),onSuccess:(value)=>flatMap13(write(of2(value)),()=>process2)})));return process2})))}),bufferChunks=dual(2,(self,options)=>{if(options.strategy==="dropping")return bufferChunksDropping(self,options.capacity);else if(options.strategy==="sliding")return bufferChunksSliding(self,options.capacity);let queue=toQueue2(self,options);return new StreamImpl(unwrapScoped3(map16(queue,(queue2)=>{let process2=pipe(fromEffect4(take3(queue2)),flatMap13(match18({onEnd:()=>void_5,onFailure:failCause10,onSuccess:(value)=>pipe(write(value),flatMap13(()=>process2))})));return process2})))}),bufferChunksDropping=dual(2,(self,capacity7)=>{let queue=acquireRelease2(dropping2(capacity7),(queue2)=>shutdown2(queue2));return new StreamImpl(bufferSignal(queue,toChannel2(self)))}),bufferChunksSliding=dual(2,(self,capacity7)=>{let queue=acquireRelease2(sliding2(capacity7),(queue2)=>shutdown2(queue2));return new StreamImpl(bufferSignal(queue,toChannel2(self)))}),bufferDropping=dual(2,(self,capacity7)=>{let queue=acquireRelease2(dropping2(capacity7),(queue2)=>shutdown2(queue2));return new StreamImpl(bufferSignal(queue,toChannel2(rechunk(1)(self))))}),bufferSliding=dual(2,(self,capacity7)=>{let queue=acquireRelease2(sliding2(capacity7),(queue2)=>shutdown2(queue2));return new StreamImpl(bufferSignal(queue,toChannel2(pipe(self,rechunk(1)))))}),bufferUnbounded=(self)=>{let queue=toQueue2(self,{strategy:"unbounded"});return new StreamImpl(unwrapScoped3(map16(queue,(queue2)=>{let process2=pipe(fromEffect4(take3(queue2)),flatMap13(match18({onEnd:()=>void_5,onFailure:failCause10,onSuccess:(value)=>flatMap13(write(value),()=>process2)})));return process2})))},bufferSignal=(scoped5,bufferChannel)=>{let producer=(queue,ref)=>{let terminate=(take7)=>pipe(get11(ref),tap3(_await3),zipRight4(make39()),flatMap11((deferred)=>pipe(offer3(queue,[take7,deferred]),zipRight4(set5(ref,deferred)),zipRight4(_await3(deferred)))),asVoid3,fromEffect4);return readWithCause({onInput:(input)=>pipe(make39(),flatMap11((deferred)=>pipe(offer3(queue,[chunk2(input),deferred]),flatMap11((added)=>pipe(set5(ref,deferred),when2(()=>added))))),asVoid3,fromEffect4,flatMap13(()=>producer(queue,ref))),onFailure:(error2)=>terminate(failCause11(error2)),onDone:()=>terminate(end4)})},consumer=(queue)=>{let process2=pipe(fromEffect4(take3(queue)),flatMap13(([take7,deferred])=>zipRight6(fromEffect4(succeed7(deferred,void 0)),match18(take7,{onEnd:()=>void_5,onFailure:failCause10,onSuccess:(value)=>pipe(write(value),flatMap13(()=>process2))}))));return process2};return unwrapScoped3(pipe(scoped5,flatMap11((queue)=>pipe(make39(),tap3((start3)=>succeed7(start3,void 0)),flatMap11((start3)=>pipe(make24(start3),flatMap11((ref)=>pipe(bufferChannel,pipeTo(producer(queue,ref)),runScoped,forkScoped2)),as4(consumer(queue))))))))},catchAll7=dual(2,(self,f)=>catchAllCause6(self,(cause3)=>match(failureOrCause2(cause3),{onLeft:f,onRight:failCause13}))),catchAllCause6=dual(2,(self,f)=>new StreamImpl(pipe(toChannel2(self),catchAllCause5((cause3)=>toChannel2(f(cause3)))))),catchSome3=dual(2,(self,pf)=>pipe(self,catchAll7((error2)=>pipe(pf(error2),getOrElse(()=>fail15(error2)))))),catchSomeCause3=dual(2,(self,pf)=>pipe(self,catchAllCause6((cause3)=>pipe(pf(cause3),getOrElse(()=>failCause13(cause3)))))),catchTag3=dual(3,(self,k,f)=>catchAll7(self,(e)=>{if("_tag"in e&&e._tag===k)return f(e);return fail15(e)})),catchTags3=dual(2,(self,cases)=>catchAll7(self,(e)=>{let keys3=Object.keys(cases);if("_tag"in e&&keys3.includes(e._tag))return cases[e._tag](e);return fail15(e)})),changes=(self)=>pipe(self,changesWith((x,y)=>equals(y)(x))),changesWith=dual(2,(self,f)=>{let writer=(last4)=>readWithCause({onInput:(input)=>{let[newLast,newChunk]=reduce2(input,[last4,empty2()],([option3,outputs],output)=>{if(isSome2(option3)&&f(option3.value,output))return[some2(output),outputs];return[some2(output),pipe(outputs,append2(output))]});return flatMap13(write(newChunk),()=>writer(newLast))},onFailure:failCause10,onDone:()=>void_5});return new StreamImpl(pipe(toChannel2(self),pipeTo(writer(none2()))))}),changesWithEffect=dual(2,(self,f)=>{let writer=(last4)=>readWithCause({onInput:(input)=>pipe(input,reduce11([last4,empty2()],([option3,outputs],output)=>{if(isSome2(option3))return pipe(f(option3.value,output),map16((bool)=>bool?[some2(output),outputs]:[some2(output),pipe(outputs,append2(output))]));return succeed9([some2(output),pipe(outputs,append2(output))])}),fromEffect4,flatMap13(([newLast,newChunk])=>pipe(write(newChunk),flatMap13(()=>writer(newLast))))),onFailure:failCause10,onDone:()=>void_5});return new StreamImpl(pipe(toChannel2(self),pipeTo(writer(none2()))))}),chunks=(self)=>pipe(self,mapChunks(of2)),chunksWith=dual(2,(self,f)=>flattenChunks(f(chunks(self)))),unsome=(effect4)=>catchAll3(asSome2(effect4),(o)=>o._tag==="None"?succeedNone2:fail9(o.value)),combine9=dual(4,(self,that,s,f)=>{function producer(handoff,latch){return fromEffect4(take6(latch)).pipe(zipRight6(readWithCause({onInput:(input)=>flatMap13(fromEffect4(offer5(handoff,succeed3(input))),()=>producer(handoff,latch)),onFailure:(cause3)=>fromEffect4(offer5(handoff,failCause3(pipe(cause3,map11(some2))))),onDone:()=>flatMap13(fromEffect4(offer5(handoff,fail4(none2()))),()=>producer(handoff,latch))})))}return new StreamImpl(unwrapScopedWith((scope5)=>all5([make49(),make49(),make49(),make49()]).pipe(tap3(([left3,_,latchL])=>toChannel2(self).pipe(concatMap(writeChunk),pipeTo(producer(left3,latchL)),runIn(scope5),forkIn2(scope5))),tap3(([,right3,_,rightL])=>toChannel2(that).pipe(concatMap(writeChunk),pipeTo(producer(right3,rightL)),runIn(scope5),forkIn2(scope5))),map16(([left3,right3,latchL,latchR])=>{let pullLeft=offer5(latchL,void 0).pipe(zipRight4(take6(left3).pipe(flatMap11(identity)))),pullRight=offer5(latchR,void 0).pipe(zipRight4(take6(right3).pipe(flatMap11(identity))));return toChannel2(unfoldEffect(s,(s2)=>flatMap11(f(s2,pullLeft,pullRight),unsome)))}))))}),combineChunks=dual(4,(self,that,s,f)=>{let producer=(handoff,latch)=>zipRight6(fromEffect4(take6(latch)),readWithCause({onInput:(input)=>flatMap13(fromEffect4(pipe(handoff,offer5(chunk2(input)))),()=>producer(handoff,latch)),onFailure:(cause3)=>fromEffect4(offer5(handoff,failCause11(cause3))),onDone:()=>fromEffect4(offer5(handoff,end4))}));return new StreamImpl(unwrapScopedWith((scope5)=>all5([make49(),make49(),make49(),make49()]).pipe(tap3(([left3,_,latchL])=>pipeTo(toChannel2(self),producer(left3,latchL)).pipe(runIn(scope5),forkIn2(scope5))),tap3(([_,right3,__,latchR])=>pipeTo(toChannel2(that),producer(right3,latchR)).pipe(runIn(scope5),forkIn2(scope5))),map16(([left3,right3,latchL,latchR])=>{let pullLeft=offer5(latchL,void 0).pipe(zipRight4(take6(left3).pipe(flatMap11(done10)))),pullRight=offer5(latchR,void 0).pipe(zipRight4(take6(right3).pipe(flatMap11(done10))));return toChannel2(unfoldChunkEffect(s,(s2)=>flatMap11(f(s2,pullLeft,pullRight),unsome)))}))))}),concat2=dual(2,(self,that)=>new StreamImpl(pipe(toChannel2(self),zipRight6(toChannel2(that))))),concatAll2=(streams)=>suspend9(()=>pipe(streams,reduce2(empty29,(x,y)=>concat2(y)(x)))),cross=dual(2,(left3,right3)=>pipe(left3,crossWith(right3,(a,a2)=>[a,a2]))),crossLeft=dual(2,(left3,right3)=>pipe(left3,crossWith(right3,(a,_)=>a))),crossRight=dual(2,(left3,right3)=>flatMap16(left3,()=>right3)),crossWith=dual(3,(left3,right3,f)=>pipe(left3,flatMap16((a)=>pipe(right3,map22((b)=>f(a,b)))))),debounce=dual(2,(self,duration3)=>unwrapScopedWith3((scope5)=>gen2(function*(){let handoff=yield*make49();function enqueue(last4){return sleep2(duration3).pipe(as4(last4),forkIn2(scope5),map16((fiber)=>consumer(previous(fiber))))}let producer=readWithCause({onInput:(input)=>match2(last2(input),{onNone:()=>producer,onSome:(elem)=>fromEffect4(offer5(handoff,emit(of2(elem)))).pipe(flatMap13(()=>producer))}),onFailure:(cause3)=>fromEffect4(offer5(handoff,halt(cause3))),onDone:()=>fromEffect4(offer5(handoff,end3(UpstreamEnd)))});function consumer(state){switch(state._tag){case OP_NOT_STARTED:return unwrap(take6(handoff).pipe(map16((signal)=>{switch(signal._tag){case OP_EMIT4:return unwrap(enqueue(signal.elements));case OP_HALT:return failCause10(signal.cause);case OP_END:return void_5}})));case OP_PREVIOUS:return unwrap(take6(handoff).pipe(forkIn2(scope5),flatMap11((handoffFiber)=>raceWith2(join3(state.fiber),join3(handoffFiber),{onSelfDone:(leftExit,current2)=>match9(leftExit,{onFailure:(cause3)=>interrupt5(current2).pipe(as4(failCause10(cause3))),onSuccess:(chunk3)=>interrupt5(current2).pipe(zipRight4(succeed9(write(chunk3).pipe(flatMap13(()=>consumer(current(handoffFiber)))))))}),onOtherDone:(rightExit,previous2)=>match9(rightExit,{onFailure:(cause3)=>interrupt5(previous2).pipe(as4(failCause10(cause3))),onSuccess:(signal)=>{switch(signal._tag){case OP_EMIT4:return interrupt5(previous2).pipe(zipRight4(enqueue(signal.elements)));case OP_HALT:return interrupt5(previous2).pipe(as4(failCause10(signal.cause)));case OP_END:return join3(previous2).pipe(map16((chunk3)=>write(chunk3).pipe(zipRight6(void_5))))}}})}))));case OP_CURRENT:return unwrap(join3(state.fiber).pipe(map16((signal)=>{switch(signal._tag){case OP_EMIT4:return unwrap(enqueue(signal.elements));case OP_HALT:return failCause10(signal.cause);case OP_END:return void_5}})))}}return scopedWith4((scope6)=>pipeTo(toChannel2(self),producer).pipe(runIn(scope6),forkIn2(scope6))).pipe(crossRight(new StreamImpl(consumer(notStarted))))}))),die10=(defect)=>fromEffect7(die6(defect)),dieSync6=(evaluate2)=>fromEffect7(dieSync3(evaluate2)),dieMessage4=(message)=>fromEffect7(dieMessage2(message)),distributedWith=dual(2,(self,options)=>pipe(make39(),flatMap11((deferred)=>pipe(self,distributedWithDynamic({maximumLag:options.maximumLag,decide:(a)=>flatMap11(_await3(deferred),(f)=>f(a))}),flatMap11((next4)=>pipe(all5(map4(range(0,options.size-1),(id2)=>map16(next4,([key,queue])=>[[key,id2],queue]))),map16(unsafeFromArray),flatMap11((entries2)=>{let[mappings,queues]=reduceRight2(entries2,[new Map,empty2()],([mappings2,queues2],[mapping,queue])=>[mappings2.set(mapping[0],mapping[1]),pipe(queues2,prepend2(queue))]);return pipe(succeed7(deferred,(a)=>map16(options.decide(a),(f)=>(key)=>f(mappings.get(key)))),as4(Array.from(queues)))}))))))),distributedWithDynamicId={ref:0},newDistributedWithDynamicId=()=>{let current2=distributedWithDynamicId.ref;return distributedWithDynamicId.ref=current2+1,current2},distributedWithDynamic=dual(2,(self,options)=>distributedWithDynamicCallback(self,options.maximumLag,options.decide,()=>_void)),distributedWithDynamicCallback=dual(4,(self,maximumLag,decide,done11)=>pipe(acquireRelease2(make24(new Map),(ref,_)=>pipe(get11(ref),flatMap11((queues)=>pipe(queues.values(),forEach6(shutdown2))))),flatMap11((queuesRef)=>gen2(function*(){let offer6=(a)=>pipe(decide(a),flatMap11((shouldProcess)=>pipe(get11(queuesRef),flatMap11((queues)=>pipe(queues.entries(),reduce11(empty2(),(acc,[id2,queue])=>{if(shouldProcess(id2))return pipe(offer3(queue,succeed3(a)),matchCauseEffect3({onFailure:(cause3)=>isInterrupted2(cause3)?succeed9(pipe(acc,prepend2(id2))):failCause8(cause3),onSuccess:()=>succeed9(acc)}));return succeed9(acc)}),flatMap11((ids3)=>{if(isNonEmpty(ids3))return update3(queuesRef,(map22)=>{for(let id2 of ids3)map22.delete(id2);return map22});return _void}))))),asVoid3),queuesLock=yield*makeSemaphore2(1),newQueue=yield*make24(pipe(bounded3(maximumLag),flatMap11((queue)=>{let id2=newDistributedWithDynamicId();return pipe(update3(queuesRef,(map22)=>map22.set(id2,queue)),as4([id2,queue]))}))),finalize=(endTake)=>queuesLock.withPermits(1)(pipe(set5(newQueue,pipe(bounded3(1),tap3((queue)=>offer3(queue,endTake)),flatMap11((queue)=>{let id2=newDistributedWithDynamicId();return pipe(update3(queuesRef,(map22)=>map22.set(id2,queue)),as4(make3(id2,queue)))}))),zipRight4(pipe(get11(queuesRef),flatMap11((map22)=>pipe(fromIterable2(map22.values()),forEach6((queue)=>pipe(offer3(queue,endTake),catchSomeCause2((cause3)=>isInterrupted2(cause3)?some2(_void):none2()))))))),zipRight4(done11(endTake)),asVoid3));return yield*pipe(self,runForEachScoped(offer6),matchCauseEffect3({onFailure:(cause3)=>finalize(failCause3(pipe(cause3,map11(some2)))),onSuccess:()=>finalize(fail4(none2()))}),forkScoped2),queuesLock.withPermits(1)(flatten8(get11(newQueue)))})))),drain3=(self)=>new StreamImpl(drain(toChannel2(self))),drainFork=dual(2,(self,that)=>fromEffect7(make39()).pipe(flatMap16((backgroundDied)=>scopedWith4((scope5)=>toChannel2(that).pipe(drain,runIn(scope5),catchAllCause3((cause3)=>failCause6(backgroundDied,cause3)),forkIn2(scope5))).pipe(crossRight(interruptWhenDeferred2(self,backgroundDied)))))),drop3=dual(2,(self,n)=>{let loop3=(r)=>readWith({onInput:(input)=>{let dropped=pipe(input,drop2(r)),leftover=Math.max(0,r-input.length);if(isEmpty(input)||leftover>0)return loop3(leftover);return pipe(write(dropped),zipRight6(identityChannel()))},onFailure:fail11,onDone:()=>void_5});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(loop3(n))))}),dropRight=dual(2,(self,n)=>{if(n<=0)return identityStream();return suspend9(()=>{let queue=new RingBuffer(n),reader=readWith({onInput:(input)=>{let outputs=pipe(input,filterMap2((elem)=>{let head6=queue.head();return queue.put(elem),head6}));return pipe(write(outputs),flatMap13(()=>reader))},onFailure:fail11,onDone:()=>void_5});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(reader)))})}),dropUntil3=dual(2,(self,predicate)=>drop3(dropWhile4(self,(a)=>!predicate(a)),1)),dropUntilEffect=dual(2,(self,predicate)=>{let loop3=readWith({onInput:(input)=>pipe(dropUntil2(input,predicate),map16(unsafeFromArray),map16((leftover)=>{if(isEmpty(leftover))return suspend5(()=>loop3);return pipe(write(leftover),zipRight6(identityChannel()))}),unwrap),onFailure:fail11,onDone:()=>void_5});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(loop3)))}),dropWhile4=dual(2,(self,predicate)=>{let loop3=readWith({onInput:(input)=>{let output=dropWhile(input,predicate);if(isEmpty(output))return suspend5(()=>loop3);return zipRight6(write(output),identityChannel())},onFailure:fail11,onDone:succeedNow});return new StreamImpl(pipeToOrFail(toChannel2(self),loop3))}),dropWhileEffect=dual(2,(self,predicate)=>{let loop3=readWith({onInput:(input)=>pipe(dropWhile3(input,predicate),map16(unsafeFromArray),map16((leftover)=>{if(isEmpty(leftover))return suspend5(()=>loop3);return zipRight6(write(leftover),identityChannel())}),unwrap),onFailure:fail11,onDone:()=>void_5});return new StreamImpl(pipeToOrFail(toChannel2(self),loop3))}),either6=(self)=>pipe(self,map22(right2),catchAll7((error2)=>make50(left2(error2)))),empty29=new StreamImpl(void_5),ensuring7=dual(2,(self,finalizer)=>new StreamImpl(pipe(toChannel2(self),ensuring5(finalizer)))),ensuringWith2=dual(2,(self,finalizer)=>new StreamImpl(ensuringWith(toChannel2(self),finalizer))),context5=()=>fromEffect7(context3()),contextWith3=(f)=>pipe(context5(),map22(f)),contextWithEffect3=(f)=>pipe(context5(),mapEffectSequential(f)),contextWithStream=(f)=>pipe(context5(),flatMap16(f)),execute=(effect4)=>drain3(fromEffect7(effect4)),fail15=(error2)=>fromEffectOption(fail9(some2(error2))),failSync7=(evaluate2)=>fromEffectOption(failSync3(()=>some2(evaluate2()))),failCause13=(cause3)=>fromEffect7(failCause8(cause3)),failCauseSync6=(evaluate2)=>fromEffect7(failCauseSync3(evaluate2)),filter8=dual(2,(self,predicate)=>mapChunks(self,filter2(predicate))),filterEffect=dual(2,(self,f)=>{let loop3=(iterator)=>{let next4=iterator.next();if(next4.done)return readWithCause({onInput:(input)=>loop3(input[Symbol.iterator]()),onFailure:failCause10,onDone:succeed12});else return pipe(f(next4.value),map16((bool)=>bool?pipe(write(of2(next4.value)),flatMap13(()=>loop3(iterator))):loop3(iterator)),unwrap)};return new StreamImpl(suspend5(()=>pipe(toChannel2(self),pipeTo(loop3(empty2()[Symbol.iterator]())))))}),filterMap6=dual(2,(self,pf)=>mapChunks(self,filterMap2(pf))),filterMapEffect=dual(2,(self,pf)=>suspend9(()=>{let loop3=(iterator)=>{let next4=iterator.next();if(next4.done)return readWithCause({onInput:(input)=>loop3(input[Symbol.iterator]()),onFailure:failCause10,onDone:succeed12});else return pipe(pf(next4.value),match2({onNone:()=>sync4(()=>loop3(iterator)),onSome:map16((a2)=>flatMap13(write(of2(a2)),()=>loop3(iterator)))}),unwrap)};return new StreamImpl(pipe(toChannel2(self),pipeTo(loop3(empty2()[Symbol.iterator]()))))})),filterMapWhile3=dual(2,(self,pf)=>{let loop3=readWith({onInput:(input)=>{let mapped=filterMapWhile2(input,pf);if(mapped.length===input.length)return pipe(write(mapped),flatMap13(()=>loop3));return write(mapped)},onFailure:fail11,onDone:succeed12});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(loop3)))}),filterMapWhileEffect=dual(2,(self,pf)=>suspend9(()=>{let loop3=(iterator)=>{let next4=iterator.next();if(next4.done)return readWithCause({onInput:(input)=>loop3(input[Symbol.iterator]()),onFailure:failCause10,onDone:succeed12});else return unwrap(match2(pf(next4.value),{onNone:()=>succeed9(void_5),onSome:map16((a2)=>flatMap13(write(of2(a2)),()=>loop3(iterator)))}))};return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(loop3(empty2()[Symbol.iterator]()))))})),finalizer=(finalizer2)=>acquireRelease3(_void,()=>finalizer2),find2=dual(2,(self,predicate)=>{let loop3=readWith({onInput:(input)=>match2(findFirst3(input,predicate),{onNone:()=>loop3,onSome:(n)=>write(of2(n))}),onFailure:fail11,onDone:()=>void_5});return new StreamImpl(pipe(toChannel2(self),pipeTo(loop3)))}),findEffect=dual(2,(self,predicate)=>{let loop3=readWith({onInput:(input)=>pipe(findFirst6(input,predicate),map16(match2({onNone:()=>loop3,onSome:(n)=>write(of2(n))})),unwrap),onFailure:fail11,onDone:()=>void_5});return new StreamImpl(pipe(toChannel2(self),pipeTo(loop3)))}),flatMap16=dual((args2)=>isStream(args2[0]),(self,f,options)=>{let bufferSize=options?.bufferSize??16;if(options?.switch)return matchConcurrency(options?.concurrency,()=>flatMapParSwitchBuffer(self,1,bufferSize,f),(n)=>flatMapParSwitchBuffer(self,n,bufferSize,f));return matchConcurrency(options?.concurrency,()=>new StreamImpl(concatMap(toChannel2(self),(as9)=>pipe(as9,map4((a)=>toChannel2(f(a))),reduce2(void_5,(left3,right3)=>pipe(left3,zipRight6(right3)))))),(_)=>new StreamImpl(pipe(toChannel2(self),concatMap(writeChunk),mergeMap((out)=>toChannel2(f(out)),options))))}),matchConcurrency=(concurrency,sequential4,bounded8)=>{switch(concurrency){case void 0:return sequential4();case"unbounded":return bounded8(Number.MAX_SAFE_INTEGER);default:return concurrency>1?bounded8(concurrency):sequential4()}},flatMapParSwitchBuffer=dual(4,(self,n,bufferSize,f)=>new StreamImpl(pipe(toChannel2(self),concatMap(writeChunk),mergeMap((out)=>toChannel2(f(out)),{concurrency:n,mergeStrategy:BufferSliding(),bufferSize})))),flatten12=dual((args2)=>isStream(args2[0]),(self,options)=>flatMap16(self,identity,options)),flattenChunks=(self)=>{let flatten13=readWithCause({onInput:(chunks2)=>flatMap13(writeChunk(chunks2),()=>flatten13),onFailure:failCause10,onDone:()=>void_5});return new StreamImpl(pipe(toChannel2(self),pipeTo(flatten13)))},flattenEffect=dual((args2)=>isStream(args2[0]),(self,options)=>options?.unordered?flatMap16(self,(a)=>fromEffect7(a),{concurrency:options.concurrency}):matchConcurrency(options?.concurrency,()=>mapEffectSequential(self,identity),(n)=>new StreamImpl(pipe(toChannel2(self),concatMap(writeChunk),mapOutEffectPar(identity,n),mapOut(of2))))),flattenExitOption=(self)=>{let processChunk=(chunk3,cont)=>{let[toEmit,rest]=pipe(chunk3,splitWhere((exit3)=>!isSuccess2(exit3))),next4=pipe(head2(rest),match2({onNone:()=>cont,onSome:match9({onFailure:(cause3)=>match2(flipCauseOption2(cause3),{onNone:()=>void_5,onSome:failCause10}),onSuccess:()=>void_5})}));return pipe(write(pipe(toEmit,filterMap2((exit3)=>isSuccess2(exit3)?some2(exit3.value):none2()))),flatMap13(()=>next4))},process2=readWithCause({onInput:(chunk3)=>processChunk(chunk3,process2),onFailure:(cause3)=>failCause10(cause3),onDone:()=>void_5});return new StreamImpl(pipe(toChannel2(self),pipeTo(process2)))},flattenIterables=(self)=>pipe(self,map22(fromIterable2),flattenChunks),flattenTake=(self)=>flattenChunks(flattenExitOption(pipe(self,map22((take7)=>take7.exit)))),forever5=(self)=>new StreamImpl(repeated(toChannel2(self))),fromAsyncIterable=(iterable,onError3)=>pipe(acquireRelease2(sync4(()=>iterable[Symbol.asyncIterator]()),(iterator)=>iterator.return?promise2(async()=>iterator.return()):_void),map16((iterator)=>repeatEffectOption(pipe(tryPromise2({try:async()=>iterator.next(),catch:(reason)=>some2(onError3(reason))}),flatMap11((result)=>result.done?fail9(none2()):succeed9(result.value))))),unwrapScoped4),fromChannel2=(channel)=>new StreamImpl(channel),toChannel2=(stream)=>{if("channel"in stream)return stream.channel;else if(isEffect2(stream))return toChannel2(fromEffect7(stream));else throw TypeError("Expected a Stream.")},fromChunk=(chunk3)=>new StreamImpl(isEmpty(chunk3)?void_5:write(chunk3)),fromChunkPubSub=(pubsub,options)=>{if(options?.scoped){let effect4=map16(subscribe2(pubsub),fromChunkQueue);return options.shutdown?map16(effect4,ensuring7(shutdown4(pubsub))):effect4}let stream=flatMap16(scoped5(subscribe2(pubsub)),fromChunkQueue);return options?.shutdown?ensuring7(stream,shutdown4(pubsub)):stream},fromChunkQueue=(queue,options)=>pipe(take3(queue),catchAllCause3((cause3)=>pipe(isShutdown2(queue),flatMap11((isShutdown7)=>isShutdown7&&isInterrupted2(cause3)?end5():failCause12(cause3)))),repeatEffectChunkOption,options?.shutdown?ensuring7(shutdown2(queue)):identity),fromChunks=(...chunks2)=>pipe(fromIterable9(chunks2),flatMap16(fromChunk)),fromEffect7=(effect4)=>pipe(effect4,mapError3(some2),fromEffectOption),fromEffectOption=(effect4)=>new StreamImpl(unwrap(match13(effect4,{onFailure:match2({onNone:()=>void_5,onSome:fail11}),onSuccess:(a)=>write(of2(a))}))),fromPubSub=(pubsub,options)=>{let maxChunkSize=options?.maxChunkSize??DefaultChunkSize;if(options?.scoped){let effect4=map16(subscribe2(pubsub),(queue)=>fromQueue2(queue,{maxChunkSize,shutdown:!0}));return options.shutdown?map16(effect4,ensuring7(shutdown4(pubsub))):effect4}let stream=flatMap16(scoped5(subscribe2(pubsub)),(queue)=>fromQueue2(queue,{maxChunkSize}));return options?.shutdown?ensuring7(stream,shutdown4(pubsub)):stream},fromTPubSub=(pubsub)=>{return unwrapScoped4(map16(subscribeScoped2(pubsub),(queue)=>fromTQueue(queue)))},fromIterable9=(iterable)=>suspend9(()=>isChunk(iterable)?fromChunk(iterable):fromIteratorSucceed(iterable[Symbol.iterator]())),fromIterableEffect=(effect4)=>pipe(effect4,map16(fromIterable9),unwrap2),fromIteratorSucceed=(iterator,maxChunkSize=DefaultChunkSize)=>{return pipe(sync4(()=>{let builder=[],loop3=(iterator2)=>pipe(sync4(()=>{let next4=iterator2.next();if(maxChunkSize===1){if(next4.done)return void_5;return pipe(write(of2(next4.value)),flatMap13(()=>loop3(iterator2)))}builder=[];let count5=0;while(next4.done===!1){if(builder.push(next4.value),count5=count5+1,count5>=maxChunkSize)break;next4=iterator2.next()}if(count5>0)return pipe(write(unsafeFromArray(builder)),flatMap13(()=>loop3(iterator2)));return void_5}),unwrap);return new StreamImpl(loop3(iterator))}),unwrap2)},fromPull2=(effect4)=>pipe(effect4,map16(repeatEffectChunkOption),unwrapScoped4),fromQueue2=(queue,options)=>pipe(takeBetween2(queue,1,options?.maxChunkSize??DefaultChunkSize),catchAllCause3((cause3)=>pipe(isShutdown2(queue),flatMap11((isShutdown7)=>isShutdown7&&isInterrupted2(cause3)?end5():failCause12(cause3)))),repeatEffectChunkOption,options?.shutdown?ensuring7(shutdown2(queue)):identity),fromTQueue=(queue)=>pipe(take5(queue),map16(of2),catchAllCause3((cause3)=>pipe(isShutdown6(queue),flatMap11((isShutdown7)=>isShutdown7&&isInterrupted2(cause3)?end5():failCause12(cause3)))),repeatEffectChunkOption),fromSchedule=(schedule2)=>pipe(driver2(schedule2),map16((driver3)=>repeatEffectOption(driver3.next(void 0))),unwrap2),fromReadableStream=(...args2)=>{let evaluate2=args2.length===1?args2[0].evaluate:args2[0],onError3=args2.length===1?args2[0].onError:args2[1],releaseLockOnEnd=args2.length===1?args2[0].releaseLockOnEnd===!0:!1;return unwrapScoped4(map16(acquireRelease2(sync4(()=>evaluate2().getReader()),(reader)=>releaseLockOnEnd?sync4(()=>reader.releaseLock()):promise2(()=>reader.cancel())),(reader)=>repeatEffectOption(flatMap11(tryPromise2({try:()=>reader.read(),catch:(reason)=>some2(onError3(reason))}),({done:done11,value})=>done11?fail9(none2()):succeed9(value)))))},fromReadableStreamByob=(...args2)=>{let evaluate2=args2.length===1?args2[0].evaluate:args2[0],onError3=args2.length===1?args2[0].onError:args2[1],allocSize=(args2.length===1?args2[0].bufferSize:args2[2])??4096,releaseLockOnEnd=args2.length===1?args2[0].releaseLockOnEnd===!0:!1;return unwrapScoped4(map16(acquireRelease2(sync4(()=>evaluate2().getReader({mode:"byob"})),(reader)=>releaseLockOnEnd?sync4(()=>reader.releaseLock()):promise2(()=>reader.cancel())),(reader)=>catchAll7(forever5(readChunkStreamByobReader(reader,onError3,allocSize)),(error2)=>error2===EOF?empty29:fail15(error2))))},EOF=Symbol.for("effect/Stream/EOF"),readChunkStreamByobReader=(reader,onError3,size14)=>{let buffer2=new ArrayBuffer(size14);return paginateEffect(0,(offset)=>flatMap11(tryPromise2({try:()=>reader.read(new Uint8Array(buffer2,offset,buffer2.byteLength-offset)),catch:(reason)=>onError3(reason)}),({done:done11,value})=>{if(done11)return fail9(EOF);let newOffset=offset+value.byteLength;return succeed9([value,newOffset>=buffer2.byteLength?none2():some2(newOffset)])}))},groupAdjacentBy=dual(2,(self,f)=>{let groupAdjacentByChunk=(state,chunk3)=>{if(isEmpty(chunk3))return[state,empty2()];let builder=[],from=0,until=0,key=void 0,previousChunk=empty2();switch(state._tag){case"Some":{let tuple2=state.value;key=tuple2[0];let loop3=!0;while(loop3&&until<chunk3.length){let input=unsafeGet2(chunk3,until),updatedKey=f(input);if(!equals(key,updatedKey)){let previousChunk2=tuple2[1],additionalChunk=unsafeFromArray(Array.from(chunk3).slice(from,until)),group2=appendAll2(previousChunk2,additionalChunk);builder.push([key,group2]),key=updatedKey,from=until,loop3=!1}until=until+1}if(loop3)previousChunk=tuple2[1];break}case"None":{key=f(unsafeGet2(chunk3,until)),until=until+1;break}}while(until<chunk3.length){let input=unsafeGet2(chunk3,until),updatedKey=f(input);if(!equals(key,updatedKey))builder.push([key,unsafeFromArray(Array.from(chunk3).slice(from,until))]),key=updatedKey,from=until;until=until+1}let nonEmptyChunk=appendAll2(previousChunk,unsafeFromArray(Array.from(chunk3).slice(from,until))),output=unsafeFromArray(builder);return[some2([key,nonEmptyChunk]),output]},groupAdjacent=(state)=>readWithCause({onInput:(input)=>{let[updatedState,output]=groupAdjacentByChunk(state,input);return isEmpty(output)?groupAdjacent(updatedState):flatMap13(write(output),()=>groupAdjacent(updatedState))},onFailure:(cause3)=>match2(state,{onNone:()=>failCause10(cause3),onSome:(output)=>flatMap13(write(of2(output)),()=>failCause10(cause3))}),onDone:(done11)=>match2(state,{onNone:()=>succeedNow(done11),onSome:(output)=>flatMap13(write(of2(output)),()=>succeedNow(done11))})});return new StreamImpl(pipeToOrFail(toChannel2(self),groupAdjacent(none2())))}),grouped=dual(2,(self,chunkSize)=>pipe(self,rechunk(chunkSize),chunks)),groupedWithin=dual(3,(self,chunkSize,duration3)=>aggregateWithin(self,collectAllN(chunkSize),spaced2(duration3))),haltWhen=dual(2,(self,effect4)=>{let writer=(fiber)=>pipe(poll2(fiber),map16(match2({onNone:()=>readWith({onInput:(input)=>flatMap13(write(input),()=>writer(fiber)),onFailure:fail11,onDone:()=>void_5}),onSome:match9({onFailure:failCause10,onSuccess:()=>void_5})})),unwrap);return new StreamImpl(unwrapScopedWith((scope5)=>effect4.pipe(forkIn2(scope5),map16((fiber)=>toChannel2(self).pipe(pipeTo(writer(fiber)))))))}),haltAfter=dual(2,(self,duration3)=>pipe(self,haltWhen(sleep2(duration3)))),haltWhenDeferred=dual(2,(self,deferred)=>{let writer=pipe(poll3(deferred),map16(match2({onNone:()=>readWith({onInput:(input)=>pipe(write(input),flatMap13(()=>writer)),onFailure:fail11,onDone:()=>void_5}),onSome:(effect4)=>unwrap(match13(effect4,{onFailure:fail11,onSuccess:()=>void_5}))})),unwrap);return new StreamImpl(pipe(toChannel2(self),pipeTo(writer)))}),identityStream=()=>new StreamImpl(identityChannel()),interleave=dual(2,(self,that)=>pipe(self,interleaveWith(that,forever5(make50(!0,!1))))),interleaveWith=dual(3,(self,that,decider)=>{let producer=(handoff)=>readWithCause({onInput:(value)=>flatMap13(fromEffect4(offer5(handoff,of5(value))),()=>producer(handoff)),onFailure:(cause3)=>fromEffect4(offer5(handoff,failCause11(cause3))),onDone:()=>fromEffect4(offer5(handoff,end4))});return new StreamImpl(unwrapScopedWith((scope5)=>pipe(make49(),zip5(make49()),tap3(([left3])=>toChannel2(self).pipe(concatMap(writeChunk),pipeTo(producer(left3)),runIn(scope5),forkIn2(scope5))),tap3(([_,right3])=>toChannel2(that).pipe(concatMap(writeChunk),pipeTo(producer(right3)),runIn(scope5),forkIn2(scope5))),map16(([left3,right3])=>{let process2=(leftDone,rightDone)=>readWithCause({onInput:(bool)=>{if(bool&&!leftDone)return pipe(fromEffect4(take6(left3)),flatMap13(match18({onEnd:()=>rightDone?void_5:process2(!0,rightDone),onFailure:failCause10,onSuccess:(chunk3)=>pipe(write(chunk3),flatMap13(()=>process2(leftDone,rightDone)))})));if(!bool&&!rightDone)return pipe(fromEffect4(take6(right3)),flatMap13(match18({onEnd:()=>leftDone?void_5:process2(leftDone,!0),onFailure:failCause10,onSuccess:(chunk3)=>pipe(write(chunk3),flatMap13(()=>process2(leftDone,rightDone)))})));return process2(leftDone,rightDone)},onFailure:failCause10,onDone:()=>void_5});return pipe(toChannel2(decider),concatMap(writeChunk),pipeTo(process2(!1,!1)))}))))}),intersperse=dual(2,(self,element)=>new StreamImpl(pipe(toChannel2(self),pipeToOrFail(suspend5(()=>{let writer=(isFirst)=>readWithCause({onInput:(chunk3)=>{let builder=[],flagResult=isFirst;for(let output of chunk3)if(flagResult)flagResult=!1,builder.push(output);else builder.push(element),builder.push(output);return pipe(write(unsafeFromArray(builder)),flatMap13(()=>writer(flagResult)))},onFailure:failCause10,onDone:()=>void_5});return writer(!0)}))))),intersperseAffixes=dual(2,(self,{end:end6,middle,start:start3})=>pipe(make50(start3),concat2(pipe(self,intersperse(middle))),concat2(make50(end6)))),interruptAfter=dual(2,(self,duration3)=>pipe(self,interruptWhen2(sleep2(duration3)))),interruptWhen2=dual(2,(self,effect4)=>new StreamImpl(pipe(toChannel2(self),interruptWhen(effect4)))),interruptWhenDeferred2=dual(2,(self,deferred)=>new StreamImpl(pipe(toChannel2(self),interruptWhenDeferred(deferred)))),iterate3=(value,next4)=>unfold4(value,(a)=>some2([a,next4(a)])),make50=(...as9)=>fromIterable9(as9),map22=dual(2,(self,f)=>new StreamImpl(pipe(toChannel2(self),mapOut(map4(f))))),mapAccum5=dual(3,(self,s,f)=>{let accumulator=(s2)=>readWith({onInput:(input)=>{let[nextS,chunk3]=mapAccum2(input,s2,f);return flatMap13(write(chunk3),()=>accumulator(nextS))},onFailure:fail11,onDone:()=>void_5});return new StreamImpl(pipe(toChannel2(self),pipeTo(accumulator(s))))}),mapAccumEffect=dual(3,(self,s,f)=>suspend9(()=>{let accumulator=(s2)=>readWith({onInput:(input)=>pipe(suspend3(()=>{let outputs=[],emit2=(output)=>sync4(()=>{outputs.push(output)});return pipe(input,reduce11(s2,(s3,a)=>pipe(f(s3,a),flatMap11(([s4,a2])=>pipe(emit2(a2),as4(s4))))),match13({onFailure:(error2)=>{if(outputs.length!==0)return zipRight6(write(unsafeFromArray(outputs)),fail11(error2));return fail11(error2)},onSuccess:(s3)=>flatMap13(write(unsafeFromArray(outputs)),()=>accumulator(s3))}))}),unwrap),onFailure:fail11,onDone:()=>void_5});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(accumulator(s))))})),mapBoth6=dual(2,(self,options)=>pipe(self,mapError6(options.onFailure),map22(options.onSuccess))),mapChunks=dual(2,(self,f)=>new StreamImpl(pipe(toChannel2(self),mapOut(f)))),mapChunksEffect=dual(2,(self,f)=>new StreamImpl(pipe(toChannel2(self),mapOutEffect(f)))),mapConcat=dual(2,(self,f)=>pipe(self,mapConcatChunk((a)=>fromIterable2(f(a))))),mapConcatChunk=dual(2,(self,f)=>pipe(self,mapChunks(flatMap3(f)))),mapConcatChunkEffect=dual(2,(self,f)=>pipe(self,mapEffectSequential(f),mapConcatChunk(identity))),mapConcatEffect=dual(2,(self,f)=>pipe(self,mapEffectSequential((a)=>pipe(f(a),map16(fromIterable2))),mapConcatChunk(identity))),mapEffectSequential=dual(2,(self,f)=>{let loop3=(iterator)=>{let next4=iterator.next();if(next4.done)return readWithCause({onInput:(elem)=>loop3(elem[Symbol.iterator]()),onFailure:failCause10,onDone:succeed12});else{let value=next4.value;return unwrap(map16(f(value),(a2)=>flatMap13(write(of2(a2)),()=>loop3(iterator))))}};return new StreamImpl(pipe(toChannel2(self),pipeTo(suspend5(()=>loop3(empty2()[Symbol.iterator]())))))}),mapEffectPar=dual(3,(self,n,f)=>new StreamImpl(pipe(toChannel2(self),concatMap(writeChunk),mapOutEffectPar(f,n),mapOut(of2)))),mapError6=dual(2,(self,f)=>new StreamImpl(pipe(toChannel2(self),mapError5(f)))),mapErrorCause4=dual(2,(self,f)=>new StreamImpl(pipe(toChannel2(self),mapErrorCause3(f)))),merge9=dual((args2)=>isStream(args2[1]),(self,that,options)=>mergeWith3(self,that,{onSelf:identity,onOther:identity,haltStrategy:options?.haltStrategy})),mergeAll8=dual((args2)=>(Symbol.iterator in args2[0]),(streams,options)=>flatten12(fromIterable9(streams),options)),mergeWithTag=dual(2,(streams,options)=>{let values3=Object.keys(streams).map((key)=>streams[key].pipe(map22((value)=>({_tag:key,value}))));return mergeAll8(values3,options)}),mergeEither=dual(2,(self,that)=>mergeWith3(self,that,{onSelf:left2,onOther:right2})),mergeLeft=dual(2,(left3,right3)=>pipe(left3,merge9(drain3(right3)))),mergeRight=dual(2,(left3,right3)=>pipe(drain3(left3),merge9(right3))),mergeWith3=dual(3,(self,other,options)=>{let strategy=options.haltStrategy?fromInput2(options.haltStrategy):Both2,handler=(terminate)=>(exit3)=>terminate||!isSuccess2(exit3)?Done4(suspend3(()=>exit3)):Await2((exit4)=>suspend3(()=>exit4));return new StreamImpl(mergeWith2(toChannel2(map22(self,options.onSelf)),{other:toChannel2(map22(other,options.onOther)),onSelfDone:handler(strategy._tag==="Either"||strategy._tag==="Left"),onOtherDone:handler(strategy._tag==="Either"||strategy._tag==="Right")}))}),mkString2=(self)=>run4(self,mkString),never4=fromEffect7(never3),onEnd=dual(2,(self,effect4)=>concat2(self,drain3(fromEffect7(effect4)))),onError3=dual(2,(self,cleanup)=>pipe(self,catchAllCause6((cause3)=>fromEffect7(pipe(cleanup(cause3),zipRight4(failCause8(cause3))))))),onDone=dual(2,(self,cleanup)=>new StreamImpl(pipe(toChannel2(self),ensuringWith((exit3)=>isSuccess2(exit3)?cleanup():_void)))),onStart=dual(2,(self,effect4)=>unwrap2(as4(effect4,self))),orDie5=(self)=>pipe(self,orDieWith4(identity)),orDieWith4=dual(2,(self,f)=>new StreamImpl(pipe(toChannel2(self),orDieWith3(f)))),orElse8=dual(2,(self,that)=>new StreamImpl(pipe(toChannel2(self),orElse7(()=>toChannel2(that()))))),orElseEither3=dual(2,(self,that)=>pipe(self,map22(left2),orElse8(()=>pipe(that(),map22(right2))))),orElseFail3=dual(2,(self,error2)=>pipe(self,orElse8(()=>failSync7(error2)))),orElseIfEmpty=dual(2,(self,element)=>pipe(self,orElseIfEmptyChunk(()=>of2(element())))),orElseIfEmptyChunk=dual(2,(self,chunk3)=>pipe(self,orElseIfEmptyStream(()=>new StreamImpl(write(chunk3()))))),orElseIfEmptyStream=dual(2,(self,stream)=>{let writer=readWith({onInput:(input)=>{if(isEmpty(input))return suspend5(()=>writer);return pipe(write(input),zipRight6(identityChannel()))},onFailure:fail11,onDone:()=>suspend5(()=>toChannel2(stream()))});return new StreamImpl(pipe(toChannel2(self),pipeTo(writer)))}),orElseSucceed3=dual(2,(self,value)=>pipe(self,orElse8(()=>sync9(value)))),paginate=(s,f)=>paginateChunk(s,(s2)=>{let page=f(s2);return[of2(page[0]),page[1]]}),paginateChunk=(s,f)=>{let loop3=(s2)=>{let page=f(s2);return match2(page[1],{onNone:()=>zipRight6(write(page[0]),void_5),onSome:(s3)=>flatMap13(write(page[0]),()=>loop3(s3))})};return new StreamImpl(suspend5(()=>loop3(s)))},paginateChunkEffect=(s,f)=>{let loop3=(s2)=>unwrap(map16(f(s2),([chunk3,option3])=>match2(option3,{onNone:()=>zipRight6(write(chunk3),void_5),onSome:(s3)=>flatMap13(write(chunk3),()=>loop3(s3))})));return new StreamImpl(suspend5(()=>loop3(s)))},paginateEffect=(s,f)=>paginateChunkEffect(s,(s2)=>pipe(f(s2),map16(([a,s3])=>[of2(a),s3]))),peel=dual(2,(self,sink)=>{return pipe(make39(),flatMap11((deferred)=>pipe(make49(),map16((handoff)=>{let consumer=foldSink(collectLeftover(sink),{onFailure:(error2)=>zipRight7(fromEffect6(fail7(deferred,error2)),fail12(error2)),onSuccess:([z,leftovers])=>{let loop3=readWithCause({onInput:(elements)=>flatMap13(fromEffect4(offer5(handoff,{_tag:"Emit",elements})),()=>loop3),onFailure:(cause3)=>zipRight6(fromEffect4(offer5(handoff,{_tag:"Halt",cause:cause3})),failCause10(cause3)),onDone:(_)=>zipRight6(fromEffect4(offer5(handoff,{_tag:"End"})),void_5)});return fromChannel(pipe(fromEffect4(succeed7(deferred,z)),zipRight6(fromEffect4(pipe(handoff,offer5({_tag:"Emit",elements:leftovers})))),zipRight6(loop3)))}}),producer=pipe(take6(handoff),map16((signal)=>{switch(signal._tag){case"Emit":return pipe(write(signal.elements),flatMap13(()=>producer));case"Halt":return failCause10(signal.cause);case"End":return void_5}}),unwrap);return pipe(self,tapErrorCause5((cause3)=>failCause6(deferred,cause3)),run4(consumer),forkScoped2,zipRight4(_await3(deferred)),map16((z)=>[z,new StreamImpl(producer)]))}))),flatten8)}),partition5=dual((args2)=>typeof args2[1]==="function",(self,predicate,options)=>partitionEither(self,(a)=>succeed9(predicate(a)?right2(a):left2(a)),options)),partitionEither=dual((args2)=>typeof args2[1]==="function",(self,predicate,options)=>pipe(mapEffectSequential(self,predicate),distributedWith({size:2,maximumLag:options?.bufferSize??16,decide:match({onLeft:()=>succeed9((n)=>n===0),onRight:()=>succeed9((n)=>n===1)})}),flatMap11(([queue1,queue2])=>succeed9([filterMap6(flattenExitOption(fromQueue2(queue1,{shutdown:!0})),(_)=>match(_,{onLeft:some2,onRight:none2})),filterMap6(flattenExitOption(fromQueue2(queue2,{shutdown:!0})),(_)=>match(_,{onLeft:none2,onRight:some2}))])))),pipeThrough=dual(2,(self,sink)=>new StreamImpl(pipe(toChannel2(self),pipeToOrFail(toChannel(sink))))),pipeThroughChannel=dual(2,(self,channel)=>new StreamImpl(pipeTo(toChannel2(self),channel))),pipeThroughChannelOrFail=dual(2,(self,chan)=>new StreamImpl(pipe(toChannel2(self),pipeToOrFail(chan)))),prepend4=dual(2,(self,values3)=>new StreamImpl(zipRight6(write(values3),toChannel2(self)))),provideContext6=dual(2,(self,context6)=>new StreamImpl(pipe(toChannel2(self),provideContext5(context6)))),provideSomeContext2=dual(2,(self,context6)=>mapInputContext6(self,merge3(context6))),provideLayer=dual(2,(self,layer)=>new StreamImpl(unwrapScopedWith((scope5)=>buildWithScope2(layer,scope5).pipe(map16((env)=>pipe(toChannel2(self),provideContext5(env))))))),provideService6=dual(3,(self,tag,resource)=>provideServiceEffect3(self,tag,succeed9(resource))),provideServiceEffect3=dual(3,(self,tag,effect4)=>provideServiceStream(self,tag,fromEffect7(effect4))),provideServiceStream=dual(3,(self,tag,stream)=>contextWithStream((env)=>flatMap16(stream,(service3)=>pipe(self,provideContext6(add4(env,tag,service3)))))),mapInputContext6=dual(2,(self,f)=>contextWithStream((env)=>pipe(self,provideContext6(f(env))))),provideSomeLayer2=dual(2,(self,layer)=>pipe(self,provideLayer(pipe(context4(),merge8(layer))))),range2=(min4,max6,chunkSize=DefaultChunkSize)=>suspend9(()=>{if(min4>max6)return empty29;let go=(min5,max7,chunkSize2)=>{let remaining=max7-min5+1;if(remaining>chunkSize2)return pipe(write(range(min5,min5+chunkSize2-1)),flatMap13(()=>go(min5+chunkSize2,max7,chunkSize2)));return write(range(min5,min5+remaining-1))};return new StreamImpl(go(min4,max6,chunkSize))}),race3=dual(2,(left3,right3)=>raceAll3(left3,right3)),raceAll3=(...streams)=>make39().pipe(map16((halt2)=>{let winner=null;return mergeAll8(streams.map((stream,index)=>stream.pipe(takeWhile4(()=>{if(winner===null)return winner=index,unsafeDone(halt2,void_3),!0;return winner===index}),interruptWhen2(_await3(halt2).pipe(flatMap11(()=>winner===index?never3:_void))))),{concurrency:streams.length})}),unwrap2),rechunk=dual(2,(self,n)=>suspend9(()=>{let target=Math.max(n,1),process2=rechunkProcess(new StreamRechunker(target),target);return new StreamImpl(pipe(toChannel2(self),pipeTo(process2)))})),rechunkProcess=(rechunker,target)=>readWithCause({onInput:(chunk3)=>{if(chunk3.length===target&&rechunker.isEmpty())return flatMap13(write(chunk3),()=>rechunkProcess(rechunker,target));if(chunk3.length>0){let chunks2=[],result=void 0,index=0;while(index<chunk3.length){while(index<chunk3.length&&result===void 0)result=rechunker.write(pipe(chunk3,unsafeGet2(index))),index=index+1;if(result!==void 0)chunks2.push(result),result=void 0}return flatMap13(writeAll(...chunks2),()=>rechunkProcess(rechunker,target))}return suspend5(()=>rechunkProcess(rechunker,target))},onFailure:(cause3)=>zipRight6(rechunker.emitIfNotEmpty(),failCause10(cause3)),onDone:()=>rechunker.emitIfNotEmpty()});class StreamRechunker{n;builder=[];pos=0;constructor(n){this.n=n}isEmpty(){return this.pos===0}write(elem){if(this.builder.push(elem),this.pos+=1,this.pos===this.n){let result=unsafeFromArray(this.builder);return this.builder=[],this.pos=0,result}return}emitIfNotEmpty(){if(this.pos!==0)return write(unsafeFromArray(this.builder));return void_5}}var refineOrDie=dual(2,(self,pf)=>pipe(self,refineOrDieWith(pf,identity))),refineOrDieWith=dual(3,(self,pf,f)=>new StreamImpl(catchAll5(toChannel2(self),(error2)=>match2(pf(error2),{onNone:()=>failCause10(die3(f(error2))),onSome:fail11})))),repeat2=dual(2,(self,schedule2)=>filterMap6(repeatEither(self,schedule2),(_)=>match(_,{onLeft:none2,onRight:some2}))),repeatEffect=(effect4)=>repeatEffectOption(pipe(effect4,mapError3(some2))),repeatEffectChunk=(effect4)=>repeatEffectChunkOption(pipe(effect4,mapError3(some2))),repeatEffectChunkOption=(effect4)=>unfoldChunkEffect(effect4,(effect5)=>pipe(map16(effect5,(chunk3)=>some2([chunk3,effect5])),catchAll3(match2({onNone:()=>succeed9(none2()),onSome:fail9})))),repeatEffectOption=(effect4)=>repeatEffectChunkOption(pipe(effect4,map16(of2))),repeatEither=dual(2,(self,schedule2)=>repeatWith(self,schedule2,{onElement:(a)=>right2(a),onSchedule:left2})),repeatElements=dual(2,(self,schedule2)=>filterMap6(repeatElementsWith(self,schedule2,{onElement:(a)=>some2(a),onSchedule:none2}),identity)),repeatElementsWith=dual(3,(self,schedule2,options)=>{let driver3=pipe(driver2(schedule2),map16((driver4)=>{let feed=(input)=>match2(head2(input),{onNone:()=>loop3,onSome:(a)=>zipRight6(write(of2(options.onElement(a))),step4(pipe(input,drop2(1)),a))}),step4=(input,a)=>{let advance=pipe(driver4.next(a),as4(pipe(write(of2(options.onElement(a))),flatMap13(()=>step4(input,a))))),reset=pipe(driver4.last,orDie3,flatMap11((b)=>pipe(driver4.reset,map16(()=>pipe(write(of2(options.onSchedule(b))),zipRight6(feed(input)))))));return pipe(advance,orElse5(()=>reset),unwrap)},loop3=readWith({onInput:feed,onFailure:fail11,onDone:()=>void_5});return loop3}),unwrap);return new StreamImpl(pipe(toChannel2(self),pipeTo(driver3)))}),repeatValue=(value)=>new StreamImpl(repeated(write(of2(value)))),repeatWith=dual(3,(self,schedule2,options)=>{return pipe(driver2(schedule2),map16((driver3)=>{let provideLastIterationInfo=provideServiceEffect3(CurrentIterationMetadata2,get11(driver3.iterationMeta)),process2=pipe(self,provideLastIterationInfo,map22(options.onElement),toChannel2),loop3=unwrap(match13(driver3.next(void 0),{onFailure:()=>void_5,onSuccess:(output)=>flatMap13(process2,()=>zipRight6(write(of2(options.onSchedule(output))),loop3))}));return new StreamImpl(zipRight6(process2,loop3))}),unwrap2)}),repeatWithSchedule=(value,schedule2)=>repeatEffectWithSchedule(succeed9(value),schedule2),repeatEffectWithSchedule=(effect4,schedule2)=>flatMap16(fromEffect7(zip5(effect4,driver2(schedule2))),([a,driver3])=>{let provideLastIterationInfo=provideServiceEffect2(CurrentIterationMetadata2,get11(driver3.iterationMeta));return concat2(succeed15(a),unfoldEffect(a,(s)=>matchEffect2(driver3.next(s),{onFailure:succeed9,onSuccess:()=>map16(provideLastIterationInfo(effect4),(nextA)=>some2([nextA,nextA]))})))}),retry6=dual(2,(self,policy)=>driver2(policy).pipe(map16((driver3)=>{let provideLastIterationInfo=provideServiceEffect3(CurrentIterationMetadata2,get11(driver3.iterationMeta)),loop3=toChannel2(provideLastIterationInfo(self)).pipe(mapOutEffect((out)=>as4(driver3.reset,out)),catchAll5((error2)=>driver3.next(error2).pipe(match13({onFailure:()=>fail11(error2),onSuccess:()=>loop3}),unwrap)));return loop3}),unwrap,fromChannel2)),withExecutionPlan3=dual((args2)=>isStream(args2[0]),(self,policy,options)=>suspend9(()=>{let preventFallbackOnPartialStream=options?.preventFallbackOnPartialStream??!1,i=0,lastError=none2(),loop3=suspend9(()=>{let step4=policy.steps[i++];if(!step4)return fail15(getOrThrow(lastError));let nextStream=isContext2(step4.provide)?provideSomeContext2(self,step4.provide):provideSomeLayer2(self,step4.provide),receivedElements=!1;if(isSome2(lastError)){let error2=lastError.value,attempted=!1,wrapped=nextStream;nextStream=suspend9(()=>{if(attempted)return wrapped;return attempted=!0,fail15(error2)}),nextStream=scheduleDefectRefail2(retry6(nextStream,scheduleFromStep(step4,!1)))}else{let schedule2=scheduleFromStep(step4,!0);nextStream=schedule2?scheduleDefectRefail2(retry6(nextStream,schedule2)):nextStream}return catchAll7(preventFallbackOnPartialStream?mapChunks(nextStream,(chunk3)=>{return receivedElements=!0,chunk3}):nextStream,(error2)=>{if(preventFallbackOnPartialStream&&receivedElements)return fail15(error2);return lastError=some2(error2),loop3})});return loop3})),scheduleDefectRefail2=(self)=>catchAllCause6(self,(cause3)=>failCause13(scheduleDefectRefailCause(cause3))),run4=dual(2,(self,sink)=>toChannel2(self).pipe(pipeToOrFail(toChannel(sink)),runDrain)),runCollect=(self)=>run4(self,collectAll()),runCount=(self)=>run4(self,count4),runDrain2=(self)=>run4(self,drain2),runFold=dual(3,(self,s,f)=>runFoldWhile(self,s,constTrue,f)),runFoldEffect=dual(3,(self,s,f)=>runFoldWhileEffect(self,s,constTrue,f)),runFoldScoped=dual(3,(self,s,f)=>pipe(self,runFoldWhileScoped(s,constTrue,f))),runFoldScopedEffect=dual(3,(self,s,f)=>pipe(self,runFoldWhileScopedEffect(s,constTrue,f))),runFoldWhile=dual(4,(self,s,cont,f)=>run4(self,fold(s,cont,f))),runFoldWhileEffect=dual(4,(self,s,cont,f)=>run4(self,foldEffect(s,cont,f))),runFoldWhileScoped=dual(4,(self,s,cont,f)=>pipe(self,runScoped2(fold(s,cont,f)))),runFoldWhileScopedEffect=dual(4,(self,s,cont,f)=>pipe(self,runScoped2(foldEffect(s,cont,f)))),runForEach=dual(2,(self,f)=>run4(self,forEach7(f))),runForEachChunk=dual(2,(self,f)=>run4(self,forEachChunk(f))),runForEachChunkScoped=dual(2,(self,f)=>pipe(self,runScoped2(forEachChunk(f)))),runForEachScoped=dual(2,(self,f)=>pipe(self,runScoped2(forEach7(f)))),runForEachWhile=dual(2,(self,f)=>run4(self,forEachWhile(f))),runForEachWhileScoped=dual(2,(self,f)=>pipe(self,runScoped2(forEachWhile(f)))),runHead=(self)=>run4(self,head5()),runIntoPubSub=dual(2,(self,pubsub)=>pipe(self,runIntoQueue(pubsub))),runIntoPubSubScoped=dual(2,(self,pubsub)=>pipe(self,runIntoQueueScoped(pubsub))),runIntoQueue=dual(2,(self,queue)=>pipe(self,runIntoQueueScoped(queue),scoped2)),runIntoQueueElementsScoped=dual(2,(self,queue)=>{let writer=readWithCause({onInput:(input)=>flatMap13(fromEffect4(offerAll3(queue,map4(input,succeed3))),()=>writer),onFailure:(cause3)=>fromEffect4(offer3(queue,failCause3(map11(cause3,some2)))),onDone:()=>fromEffect4(offer3(queue,fail4(none2())))});return pipe(pipeTo(toChannel2(self),writer),drain,runScoped,asVoid3)}),runIntoQueueScoped=dual(2,(self,queue)=>{let writer=readWithCause({onInput:(input)=>flatMap13(write(chunk2(input)),()=>writer),onFailure:(cause3)=>write(failCause11(cause3)),onDone:()=>write(end4)});return pipe(pipeTo(toChannel2(self),writer),mapOutEffect((take7)=>offer3(queue,take7)),drain,runScoped,asVoid3)}),runLast=(self)=>run4(self,last3()),runScoped2=dual(2,(self,sink)=>pipe(toChannel2(self),pipeToOrFail(toChannel(sink)),drain,runScoped)),runSum=(self)=>run4(self,sum2),scan=dual(3,(self,s,f)=>pipe(self,scanEffect(s,(s2,a)=>succeed9(f(s2,a))))),scanReduce=dual(2,(self,f)=>pipe(self,scanReduceEffect((a2,a)=>succeed9(f(a2,a))))),scanReduceEffect=dual(2,(self,f)=>pipe(self,mapAccumEffect(none2(),(option3,a)=>{switch(option3._tag){case"None":return succeed9([some2(a),a]);case"Some":return pipe(f(option3.value,a),map16((b)=>[some2(b),b]))}}))),schedule2=dual(2,(self,schedule3)=>filterMap6(scheduleWith(self,schedule3,{onElement:some2,onSchedule:none2}),identity)),scheduleWith=dual(3,(self,schedule3,options)=>{let loop3=(driver3,iterator)=>{let next4=iterator.next();if(next4.done)return readWithCause({onInput:(chunk3)=>loop3(driver3,chunk3[Symbol.iterator]()),onFailure:failCause10,onDone:succeedNow});return unwrap(matchEffect2(driver3.next(next4.value),{onFailure:()=>pipe(driver3.last,orDie3,map16((b)=>pipe(write(make4(options.onElement(next4.value),options.onSchedule(b))),flatMap13(()=>loop3(driver3,iterator)))),zipLeft3(driver3.reset)),onSuccess:()=>succeed9(pipe(write(of2(options.onElement(next4.value))),flatMap13(()=>loop3(driver3,iterator))))}))};return new StreamImpl(pipe(fromEffect4(driver2(schedule3)),flatMap13((driver3)=>pipe(toChannel2(self),pipeTo(loop3(driver3,empty2()[Symbol.iterator]()))))))}),scanEffect=dual(3,(self,s,f)=>new StreamImpl(pipe(write(of2(s)),flatMap13(()=>toChannel2(pipe(self,mapAccumEffect(s,(s2,a)=>pipe(f(s2,a),map16((s3)=>[s3,s3]))))))))),scoped5=(effect4)=>new StreamImpl(ensuring5(scoped4(pipe(effect4,map16(of2))),_void)),scopedWith4=(f)=>new StreamImpl(scopedWith3((scope5)=>f(scope5).pipe(map16(of2)))),some5=(self)=>pipe(self,mapError6(some2),someOrFail(()=>none2())),someOrElse=dual(2,(self,fallback)=>pipe(self,map22(getOrElse(fallback)))),someOrFail=dual(2,(self,error2)=>mapEffectSequential(self,match2({onNone:()=>failSync3(error2),onSome:succeed9}))),sliding7=dual(2,(self,chunkSize)=>slidingSize(self,chunkSize,1)),slidingSize=dual(3,(self,chunkSize,stepSize)=>{if(chunkSize<=0||stepSize<=0)return die10(new IllegalArgumentException2("Invalid bounds - `chunkSize` and `stepSize` must be greater than zero"));return new StreamImpl(suspend5(()=>{let queue=new RingBuffer(chunkSize),emitOnStreamEnd=(queueSize,channelEnd)=>{if(queueSize<chunkSize){let items=queue.toChunk(),result2=isEmpty(items)?empty2():of2(items);return pipe(write(result2),flatMap13(()=>channelEnd))}let lastEmitIndex=queueSize-(queueSize-chunkSize)%stepSize;if(lastEmitIndex===queueSize)return channelEnd;let leftovers=queueSize-(lastEmitIndex-chunkSize+stepSize),lastItems=pipe(queue.toChunk(),takeRight(leftovers)),result=isEmpty(lastItems)?empty2():of2(lastItems);return pipe(write(result),flatMap13(()=>channelEnd))},reader=(queueSize)=>readWithCause({onInput:(input)=>flatMap13(write(filterMap2(input,(element,index)=>{queue.put(element);let currentIndex=queueSize+index+1;if(currentIndex<chunkSize||(currentIndex-chunkSize)%stepSize>0)return none2();return some2(queue.toChunk())})),()=>reader(queueSize+input.length)),onFailure:(cause3)=>emitOnStreamEnd(queueSize,failCause10(cause3)),onDone:()=>emitOnStreamEnd(queueSize,void_5)});return pipe(toChannel2(self),pipeTo(reader(0)))}))}),split=dual(2,(self,predicate)=>{let split2=(leftovers,input)=>{let[chunk3,remaining]=pipe(leftovers,appendAll2(input),splitWhere(predicate));if(isEmpty(chunk3)||isEmpty(remaining))return loop3(pipe(chunk3,appendAll2(pipe(remaining,drop2(1)))));return pipe(write(of2(chunk3)),flatMap13(()=>split2(empty2(),pipe(remaining,drop2(1)))))},loop3=(leftovers)=>readWith({onInput:(input)=>split2(leftovers,input),onFailure:fail11,onDone:()=>{if(isEmpty(leftovers))return void_5;if(isNone2(pipe(leftovers,findFirst3(predicate))))return zipRight6(write(of2(leftovers)),void_5);return zipRight6(split2(empty2(),leftovers),void_5)}});return new StreamImpl(pipe(toChannel2(self),pipeTo(loop3(empty2()))))}),splitOnChunk=dual(2,(self,delimiter)=>{let next4=(leftover,delimiterIndex)=>readWithCause({onInput:(inputChunk)=>{let buffer2,[carry,delimiterCursor]=pipe(inputChunk,reduce2([pipe(leftover,getOrElse(()=>empty2())),delimiterIndex],([carry2,delimiterCursor2],a)=>{let concatenated=pipe(carry2,append2(a));if(delimiterCursor2<delimiter.length&&equals(a,pipe(delimiter,unsafeGet2(delimiterCursor2)))){if(delimiterCursor2+1===delimiter.length){if(buffer2===void 0)buffer2=[];return buffer2.push(pipe(concatenated,take(concatenated.length-delimiter.length))),[empty2(),0]}return[concatenated,delimiterCursor2+1]}return[concatenated,equals(a,pipe(delimiter,unsafeGet2(0)))?1:0]})),output=buffer2===void 0?empty2():unsafeFromArray(buffer2);return flatMap13(write(output),()=>next4(isNonEmpty(carry)?some2(carry):none2(),delimiterCursor))},onFailure:(cause3)=>match2(leftover,{onNone:()=>failCause10(cause3),onSome:(chunk3)=>zipRight6(write(of2(chunk3)),failCause10(cause3))}),onDone:(done11)=>match2(leftover,{onNone:()=>succeed12(done11),onSome:(chunk3)=>zipRight6(write(of2(chunk3)),succeed12(done11))})});return new StreamImpl(pipe(toChannel2(self),pipeTo(next4(none2(),0))))}),splitLines2=(self)=>pipeThroughChannel(self,splitLines()),succeed15=(value)=>fromChunk(of2(value)),sync9=(evaluate2)=>suspend9(()=>fromChunk(of2(evaluate2()))),suspend9=(stream)=>new StreamImpl(suspend5(()=>toChannel2(stream()))),take7=dual(2,(self,n)=>{if(!Number.isInteger(n))return die10(new IllegalArgumentException2(`${n} must be an integer`));let loop3=(n2)=>readWith({onInput:(input)=>{let taken=pipe(input,take(Math.min(n2,Number.POSITIVE_INFINITY))),leftover=Math.max(0,n2-taken.length);if(leftover>0)return pipe(write(taken),flatMap13(()=>loop3(leftover)));return write(taken)},onFailure:fail11,onDone:succeed12});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(0<n?loop3(n):void_5)))}),takeRight2=dual(2,(self,n)=>{if(n<=0)return empty29;return new StreamImpl(pipe(succeed9(new RingBuffer(n)),map16((queue)=>{let reader=readWith({onInput:(input)=>{for(let element of input)queue.put(element);return reader},onFailure:fail11,onDone:()=>pipe(write(queue.toChunk()),zipRight6(void_5))});return pipe(toChannel2(self),pipeTo(reader))}),unwrap))}),takeUntil3=dual(2,(self,predicate)=>{let loop3=readWith({onInput:(input)=>{let taken=pipe(input,takeWhile((a)=>!predicate(a))),last4=pipe(input,drop2(taken.length),take(1));if(isEmpty(last4))return pipe(write(taken),flatMap13(()=>loop3));return write(pipe(taken,appendAll2(last4)))},onFailure:fail11,onDone:succeed12});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(loop3)))}),takeUntilEffect=dual(2,(self,predicate)=>{let loop3=(iterator)=>{let next4=iterator.next();if(next4.done)return readWithCause({onInput:(elem)=>loop3(elem[Symbol.iterator]()),onFailure:failCause10,onDone:succeed12});return pipe(predicate(next4.value),map16((bool)=>bool?write(of2(next4.value)):pipe(write(of2(next4.value)),flatMap13(()=>loop3(iterator)))),unwrap)};return new StreamImpl(pipe(toChannel2(self),pipeTo(loop3(empty2()[Symbol.iterator]()))))}),takeWhile4=dual(2,(self,predicate)=>{let loop3=readWith({onInput:(input)=>{let taken=pipe(input,takeWhile(predicate));if(taken.length===input.length)return pipe(write(taken),flatMap13(()=>loop3));return write(taken)},onFailure:fail11,onDone:succeed12});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(loop3)))}),tap6=dual(2,(self,f)=>mapEffectSequential(self,(a)=>as4(f(a),a))),tapBoth3=dual(2,(self,options)=>pipe(self,tapError5(options.onFailure),tap6(options.onSuccess))),tapError5=dual(2,(self,f)=>catchAll7(self,(error2)=>fromEffect7(zipRight4(f(error2),fail9(error2))))),tapErrorCause5=dual(2,(self,f)=>{let loop3=readWithCause({onInput:(chunk3)=>flatMap13(write(chunk3),()=>loop3),onFailure:(cause3)=>fromEffect4(zipRight4(f(cause3),failCause8(cause3))),onDone:succeedNow});return new StreamImpl(pipe(toChannel2(self),pipeTo(loop3)))}),tapSink=dual(2,(self,sink)=>pipe(fromEffect7(all5([bounded3(1),make39()])),flatMap16(([queue,deferred])=>{let right3=flattenTake(fromQueue2(queue,{maxChunkSize:1})),loop3=readWithCause({onInput:(chunk3)=>pipe(fromEffect4(offer3(queue,chunk2(chunk3))),foldCauseChannel({onFailure:()=>flatMap13(write(chunk3),()=>identityChannel()),onSuccess:()=>flatMap13(write(chunk3),()=>loop3)})),onFailure:(cause3)=>pipe(fromEffect4(offer3(queue,failCause11(cause3))),foldCauseChannel({onFailure:()=>failCause10(cause3),onSuccess:()=>failCause10(cause3)})),onDone:()=>pipe(fromEffect4(offer3(queue,end4)),foldCauseChannel({onFailure:()=>void_5,onSuccess:()=>void_5}))});return pipe(new StreamImpl(pipe(pipeTo(toChannel2(self),loop3),ensuring5(zipRight4(forkDaemon2(offer3(queue,end4)),_await3(deferred))))),merge9(execute(pipe(run4(right3,sink),ensuring3(zipRight4(shutdown2(queue),succeed7(deferred,void 0)))))))}))),throttle=dual(2,(self,options)=>throttleEffect(self,{...options,cost:(chunk3)=>succeed9(options.cost(chunk3))})),throttleEffect=dual(2,(self,options)=>{if(options.strategy==="enforce")return throttleEnforceEffect(self,options.cost,options.units,options.duration,options.burst??0);return throttleShapeEffect(self,options.cost,options.units,options.duration,options.burst??0)}),throttleEnforceEffect=(self,cost,units,duration3,burst)=>{let loop3=(tokens,timestampMillis)=>readWithCause({onInput:(input)=>pipe(cost(input),zip5(currentTimeMillis2),map16(([weight,currentTimeMillis3])=>{let cycles=(currentTimeMillis3-timestampMillis)/toMillis(duration3),sum3=tokens+cycles*units,max6=units+burst<0?Number.POSITIVE_INFINITY:units+burst,available=sum3<0?max6:Math.min(sum3,max6);if(weight<=available)return pipe(write(input),flatMap13(()=>loop3(available-weight,currentTimeMillis3)));return loop3(tokens,timestampMillis)}),unwrap),onFailure:failCause10,onDone:()=>void_5}),throttled=pipe(currentTimeMillis2,map16((currentTimeMillis3)=>loop3(units,currentTimeMillis3)),unwrap);return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(throttled)))},throttleShapeEffect=(self,costFn,units,duration3,burst)=>{let loop3=(tokens,timestampMillis)=>readWithCause({onInput:(input)=>pipe(costFn(input),zip5(currentTimeMillis2),map16(([weight,currentTimeMillis3])=>{let cycles=(currentTimeMillis3-timestampMillis)/toMillis(duration3),sum3=tokens+cycles*units,max6=units+burst<0?Number.POSITIVE_INFINITY:units+burst,remaining=(sum3<0?max6:Math.min(sum3,max6))-weight,waitCycles=remaining>=0?0:-remaining/units,delay3=millis(Math.max(0,waitCycles*toMillis(duration3)));if(greaterThan2(delay3,zero))return pipe(fromEffect4(sleep2(delay3)),zipRight6(write(input)),flatMap13(()=>loop3(remaining,currentTimeMillis3)));return flatMap13(write(input),()=>loop3(remaining,currentTimeMillis3))}),unwrap),onFailure:failCause10,onDone:()=>void_5}),throttled=pipe(currentTimeMillis2,map16((currentTimeMillis3)=>loop3(units,currentTimeMillis3)),unwrap);return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(throttled)))},tick=(interval)=>repeatWithSchedule(void 0,spaced2(interval)),timeout3=dual(2,(self,duration3)=>pipe(toPull2(self),map16(timeoutFail2({onTimeout:()=>none2(),duration:duration3})),fromPull2)),timeoutFail3=dual(3,(self,error2,duration3)=>pipe(self,timeoutTo3(duration3,failSync7(error2)))),timeoutFailCause3=dual(3,(self,cause3,duration3)=>pipe(toPull2(self),map16(timeoutFailCause2({onTimeout:()=>map11(cause3(),some2),duration:duration3})),fromPull2)),timeoutTo3=dual(3,(self,duration3,that)=>{let StreamTimeout=new RuntimeException2("Stream Timeout");return pipe(self,timeoutFailCause3(()=>die3(StreamTimeout),duration3),catchSomeCause3((cause3)=>isDieType2(cause3)&&isRuntimeException2(cause3.defect)&&cause3.defect.message!==void 0&&cause3.defect.message==="Stream Timeout"?some2(that):none2()))}),pubsubFromOptions=(options)=>{if(typeof options==="number")return bounded5(options);else if(options.capacity==="unbounded")return unbounded5({replay:options.replay});switch(options.strategy){case"dropping":return dropping4(options);case"sliding":return sliding4(options);default:return bounded5(options)}},toPubSub2=dual(2,(self,capacity7)=>pipe(acquireRelease2(pubsubFromOptions(capacity7),(pubsub)=>shutdown4(pubsub)),tap3((pubsub)=>pipe(self,runIntoPubSubScoped(pubsub),forkScoped2)))),toPull2=(self)=>map16(toPull(toChannel2(self)),(pull)=>pipe(pull,mapError3(some2),flatMap11(match({onLeft:()=>fail9(none2()),onRight:succeed9})))),toQueue2=dual((args2)=>isStream(args2[0]),(self,options)=>tap3(acquireRelease2(options?.strategy==="unbounded"?unbounded3():options?.strategy==="dropping"?dropping2(options.capacity??2):options?.strategy==="sliding"?sliding2(options.capacity??2):bounded3(options?.capacity??2),(queue)=>shutdown2(queue)),(queue)=>forkScoped2(runIntoQueueScoped(self,queue)))),toQueueOfElements=dual((args2)=>isStream(args2[0]),(self,options)=>tap3(acquireRelease2(bounded3(options?.capacity??2),(queue)=>shutdown2(queue)),(queue)=>forkScoped2(runIntoQueueElementsScoped(self,queue)))),toReadableStream=dual((args2)=>isStream(args2[0]),(self,options)=>toReadableStreamRuntime(self,defaultRuntime2,options)),toReadableStreamEffect=dual((args2)=>isStream(args2[0]),(self,options)=>map16(runtime3(),(runtime4)=>toReadableStreamRuntime(self,runtime4,options))),toReadableStreamRuntime=dual((args2)=>isStream(args2[0]),(self,runtime4,options)=>{let runFork4=runFork3(runtime4),currentResolve=void 0,fiber=void 0,latch=unsafeMakeLatch2(!1);return new ReadableStream({start(controller){fiber=runFork4(runForEachChunk(self,(chunk3)=>{if(chunk3.length===0)return _void;return latch.whenOpen(sync4(()=>{latch.unsafeClose();for(let item of chunk3)controller.enqueue(item);currentResolve(),currentResolve=void 0}))})),fiber.addObserver((exit3)=>{try{if(exit3._tag==="Failure")controller.error(squash(exit3.cause));else controller.close()}catch{}})},pull(){return new Promise((resolve)=>{currentResolve=resolve,runSync(latch.open)})},cancel(){if(!fiber)return;return runPromise(asVoid3(interrupt5(fiber)))}},options?.strategy)}),transduce=dual(2,(self,sink)=>{let newChannel=suspend5(()=>{let leftovers={ref:empty2()},upstreamDone={ref:!1},buffer2=suspend5(()=>{let leftover=leftovers.ref;if(isEmpty(leftover))return readWith({onInput:(input)=>pipe(write(input),flatMap13(()=>buffer2)),onFailure:fail11,onDone:succeedNow});return leftovers.ref=empty2(),pipe(writeChunk(leftover),flatMap13(()=>buffer2))}),concatAndGet=(chunk3)=>{let leftover=leftovers.ref,concatenated=appendAll2(leftover,filter2(chunk3,(chunk4)=>chunk4.length!==0));return leftovers.ref=concatenated,concatenated},upstreamMarker=readWith({onInput:(input)=>flatMap13(write(input),()=>upstreamMarker),onFailure:fail11,onDone:(done11)=>zipRight6(sync7(()=>{upstreamDone.ref=!0}),succeedNow(done11))}),transducer=pipe(sink,toChannel,collectElements,flatMap13(([leftover,z])=>pipe(succeed12([upstreamDone.ref,concatAndGet(leftover)]),flatMap13(([done11,newLeftovers])=>{let nextChannel=done11&&isEmpty(newLeftovers)?void_5:transducer;return pipe(write(of2(z)),flatMap13(()=>nextChannel))}))));return pipe(toChannel2(self),pipeTo(upstreamMarker),pipeTo(buffer2),pipeToOrFail(transducer))});return new StreamImpl(newChannel)}),toAsyncIterableRuntime=dual((args2)=>isStream(args2[0]),(self,runtime4)=>{let runFork4=runFork3(runtime4);return{[Symbol.asyncIterator](){let currentResolve=void 0,currentReject=void 0,fiber=void 0,latch=unsafeMakeLatch2(!1),returned=!1;return{next(){if(!fiber)fiber=runFork4(runForEach(self,(value)=>latch.whenOpen(sync4(()=>{latch.unsafeClose(),currentResolve({done:!1,value}),currentResolve=currentReject=void 0})))),fiber.addObserver((exit3)=>{if(returned)return;fiber=runFork2(latch.whenOpen(sync4(()=>{if(exit3._tag==="Failure")currentReject(squash(exit3.cause));else currentResolve({done:!0,value:void 0});currentResolve=currentReject=void 0})))});return new Promise((resolve,reject)=>{currentResolve=resolve,currentReject=reject,latch.unsafeOpen()})},return(){if(returned=!0,!fiber)return Promise.resolve({done:!0,value:void 0});return runPromise(as4(interrupt5(fiber),{done:!0,value:void 0}))}}}}}),toAsyncIterable=(self)=>toAsyncIterableRuntime(self,defaultRuntime2),toAsyncIterableEffect=(self)=>map16(runtime3(),(runtime4)=>toAsyncIterableRuntime(self,runtime4)),unfold4=(s,f)=>unfoldChunk(s,(s2)=>pipe(f(s2),map2(([a,s3])=>[of2(a),s3]))),unfoldChunk=(s,f)=>{let loop3=(s2)=>match2(f(s2),{onNone:()=>void_5,onSome:([chunk3,s3])=>flatMap13(write(chunk3),()=>loop3(s3))});return new StreamImpl(suspend5(()=>loop3(s)))},unfoldChunkEffect=(s,f)=>suspend9(()=>{let loop3=(s2)=>unwrap(map16(f(s2),match2({onNone:()=>void_5,onSome:([chunk3,s3])=>flatMap13(write(chunk3),()=>loop3(s3))})));return new StreamImpl(loop3(s))}),unfoldEffect=(s,f)=>unfoldChunkEffect(s,(s2)=>pipe(f(s2),map16(map2(([a,s3])=>[of2(a),s3])))),void_7=succeed15(void 0);var unwrap2=(effect4)=>flatten12(fromEffect7(effect4)),unwrapScoped4=(effect4)=>flatten12(scoped5(effect4)),unwrapScopedWith3=(f)=>flatten12(scopedWith4((scope5)=>f(scope5))),updateService4=dual(3,(self,tag,f)=>pipe(self,mapInputContext6((context6)=>pipe(context6,add4(tag,f(pipe(context6,unsafeGet4(tag)))))))),when3=dual(2,(self,test)=>pipe(self,whenEffect3(sync4(test)))),whenCase=(evaluate2,pf)=>whenCaseEffect(pf)(sync4(evaluate2)),whenCaseEffect=dual(2,(self,pf)=>pipe(fromEffect7(self),flatMap16((a)=>pipe(pf(a),getOrElse(()=>empty29))))),whenEffect3=dual(2,(self,effect4)=>pipe(fromEffect7(effect4),flatMap16((bool)=>bool?self:empty29))),withSpan6=function(){let dataFirst=typeof arguments[0]!=="string",name=dataFirst?arguments[1]:arguments[0],options=addSpanStackTrace(dataFirst?arguments[2]:arguments[1]);if(dataFirst){let self=arguments[0];return new StreamImpl(withSpan5(toChannel2(self),name,options))}return(self)=>new StreamImpl(withSpan5(toChannel2(self),name,options))},zip7=dual(2,(self,that)=>pipe(self,zipWith11(that,(a,a2)=>[a,a2]))),zipFlatten=dual(2,(self,that)=>pipe(self,zipWith11(that,(a,a2)=>[...a,a2]))),zipAll=dual(2,(self,options)=>zipAllWith(self,{other:options.other,onSelf:(a)=>[a,options.defaultOther],onOther:(a2)=>[options.defaultSelf,a2],onBoth:(a,a2)=>[a,a2]})),zipAllLeft=dual(3,(self,other,defaultSelf)=>zipAllWith(self,{other,onSelf:identity,onOther:()=>defaultSelf,onBoth:(a)=>a})),zipAllRight=dual(3,(self,other,defaultRight)=>zipAllWith(self,{other,onSelf:()=>defaultRight,onOther:identity,onBoth:(_,a2)=>a2})),zipAllSortedByKey=dual(2,(self,options)=>zipAllSortedByKeyWith(self,{other:options.other,onSelf:(a)=>[a,options.defaultOther],onOther:(a2)=>[options.defaultSelf,a2],onBoth:(a,a2)=>[a,a2],order:options.order})),zipAllSortedByKeyLeft=dual(2,(self,options)=>zipAllSortedByKeyWith(self,{other:options.other,onSelf:identity,onOther:()=>options.defaultSelf,onBoth:(a)=>a,order:options.order})),zipAllSortedByKeyRight=dual(2,(self,options)=>zipAllSortedByKeyWith(self,{other:options.other,onSelf:()=>options.defaultOther,onOther:identity,onBoth:(_,a2)=>a2,order:options.order})),zipAllSortedByKeyWith=dual(2,(self,options)=>{let pull=(state,pullLeft,pullRight)=>{switch(state._tag){case OP_DRAIN_LEFT:return pipe(pullLeft,match13({onFailure:fail4,onSuccess:(leftChunk)=>succeed3([map4(leftChunk,([k,a])=>[k,options.onSelf(a)]),DrainLeft])}));case OP_DRAIN_RIGHT:return pipe(pullRight,match13({onFailure:fail4,onSuccess:(rightChunk)=>succeed3([map4(rightChunk,([k,a2])=>[k,options.onOther(a2)]),DrainRight])}));case OP_PULL_BOTH:return pipe(unsome(pullLeft),zip5(unsome(pullRight),{concurrent:!0}),matchEffect2({onFailure:(error2)=>succeed9(fail4(some2(error2))),onSuccess:([leftOption,rightOption])=>{if(isSome2(leftOption)&&isSome2(rightOption)){if(isEmpty(leftOption.value)&&isEmpty(rightOption.value))return pull(PullBoth,pullLeft,pullRight);if(isEmpty(leftOption.value))return pull(PullLeft(rightOption.value),pullLeft,pullRight);if(isEmpty(rightOption.value))return pull(PullRight(leftOption.value),pullLeft,pullRight);return succeed9(succeed3(merge10(leftOption.value,rightOption.value)))}if(isSome2(leftOption)&&isNone2(rightOption)){if(isEmpty(leftOption.value))return pull(DrainLeft,pullLeft,pullRight);return succeed9(succeed3([pipe(leftOption.value,map4(([k,a])=>[k,options.onSelf(a)])),DrainLeft]))}if(isNone2(leftOption)&&isSome2(rightOption)){if(isEmpty(rightOption.value))return pull(DrainRight,pullLeft,pullRight);return succeed9(succeed3([pipe(rightOption.value,map4(([k,a2])=>[k,options.onOther(a2)])),DrainRight]))}return succeed9(fail4(none2()))}}));case OP_PULL_LEFT:return matchEffect2(pullLeft,{onFailure:match2({onNone:()=>succeed9(succeed3([pipe(state.rightChunk,map4(([k,a2])=>[k,options.onOther(a2)])),DrainRight])),onSome:(error2)=>succeed9(fail4(some2(error2)))}),onSuccess:(leftChunk)=>isEmpty(leftChunk)?pull(PullLeft(state.rightChunk),pullLeft,pullRight):succeed9(succeed3(merge10(leftChunk,state.rightChunk)))});case OP_PULL_RIGHT:return matchEffect2(pullRight,{onFailure:match2({onNone:()=>succeed9(succeed3([map4(state.leftChunk,([k,a])=>[k,options.onSelf(a)]),DrainLeft])),onSome:(error2)=>succeed9(fail4(some2(error2)))}),onSuccess:(rightChunk)=>isEmpty(rightChunk)?pull(PullRight(state.leftChunk),pullLeft,pullRight):succeed9(succeed3(merge10(state.leftChunk,rightChunk)))})}},merge10=(leftChunk,rightChunk)=>{let hasNext=(chunk3,index)=>index<chunk3.length-1,builder=[],state=void 0,leftIndex=0,rightIndex=0,leftTuple=pipe(leftChunk,unsafeGet2(leftIndex)),rightTuple=pipe(rightChunk,unsafeGet2(rightIndex)),k1=leftTuple[0],a=leftTuple[1],k2=rightTuple[0],a2=rightTuple[1],loop3=!0;while(loop3){let compare=options.order(k1,k2);if(compare===0)if(builder.push([k1,options.onBoth(a,a2)]),hasNext(leftChunk,leftIndex)&&hasNext(rightChunk,rightIndex))leftIndex=leftIndex+1,rightIndex=rightIndex+1,leftTuple=pipe(leftChunk,unsafeGet2(leftIndex)),rightTuple=pipe(rightChunk,unsafeGet2(rightIndex)),k1=leftTuple[0],a=leftTuple[1],k2=rightTuple[0],a2=rightTuple[1];else if(hasNext(leftChunk,leftIndex))state=PullRight(pipe(leftChunk,drop2(leftIndex+1))),loop3=!1;else if(hasNext(rightChunk,rightIndex))state=PullLeft(pipe(rightChunk,drop2(rightIndex+1))),loop3=!1;else state=PullBoth,loop3=!1;else if(compare<0)if(builder.push([k1,options.onSelf(a)]),hasNext(leftChunk,leftIndex))leftIndex=leftIndex+1,leftTuple=pipe(leftChunk,unsafeGet2(leftIndex)),k1=leftTuple[0],a=leftTuple[1];else{let rightBuilder=[];rightBuilder.push(rightTuple);while(hasNext(rightChunk,rightIndex))rightIndex=rightIndex+1,rightTuple=pipe(rightChunk,unsafeGet2(rightIndex)),rightBuilder.push(rightTuple);state=PullLeft(unsafeFromArray(rightBuilder)),loop3=!1}else if(builder.push([k2,options.onOther(a2)]),hasNext(rightChunk,rightIndex))rightIndex=rightIndex+1,rightTuple=pipe(rightChunk,unsafeGet2(rightIndex)),k2=rightTuple[0],a2=rightTuple[1];else{let leftBuilder=[];leftBuilder.push(leftTuple);while(hasNext(leftChunk,leftIndex))leftIndex=leftIndex+1,leftTuple=pipe(leftChunk,unsafeGet2(leftIndex)),leftBuilder.push(leftTuple);state=PullRight(unsafeFromArray(leftBuilder)),loop3=!1}}return[unsafeFromArray(builder),state]};return combineChunks(self,options.other,PullBoth,pull)}),zipAllWith=dual(2,(self,options)=>{let pull=(state,pullLeft,pullRight)=>{switch(state._tag){case OP_DRAIN_LEFT:return matchEffect2(pullLeft,{onFailure:(error2)=>succeed9(fail4(error2)),onSuccess:(leftChunk)=>succeed9(succeed3([map4(leftChunk,options.onSelf),DrainLeft]))});case OP_DRAIN_RIGHT:return matchEffect2(pullRight,{onFailure:(error2)=>succeed9(fail4(error2)),onSuccess:(rightChunk)=>succeed9(succeed3([map4(rightChunk,options.onOther),DrainRight]))});case OP_PULL_BOTH:return pipe(unsome(pullLeft),zip5(unsome(pullRight),{concurrent:!0}),matchEffect2({onFailure:(error2)=>succeed9(fail4(some2(error2))),onSuccess:([leftOption,rightOption])=>{if(isSome2(leftOption)&&isSome2(rightOption)){if(isEmpty(leftOption.value)&&isEmpty(rightOption.value))return pull(PullBoth,pullLeft,pullRight);if(isEmpty(leftOption.value))return pull(PullLeft(rightOption.value),pullLeft,pullRight);if(isEmpty(rightOption.value))return pull(PullRight(leftOption.value),pullLeft,pullRight);return succeed9(succeed3(zip8(leftOption.value,rightOption.value,options.onBoth)))}if(isSome2(leftOption)&&isNone2(rightOption))return succeed9(succeed3([map4(leftOption.value,options.onSelf),DrainLeft]));if(isNone2(leftOption)&&isSome2(rightOption))return succeed9(succeed3([map4(rightOption.value,options.onOther),DrainRight]));return succeed9(fail4(none2()))}}));case OP_PULL_LEFT:return matchEffect2(pullLeft,{onFailure:match2({onNone:()=>succeed9(succeed3([map4(state.rightChunk,options.onOther),DrainRight])),onSome:(error2)=>succeed9(fail4(some2(error2)))}),onSuccess:(leftChunk)=>{if(isEmpty(leftChunk))return pull(PullLeft(state.rightChunk),pullLeft,pullRight);if(isEmpty(state.rightChunk))return pull(PullRight(leftChunk),pullLeft,pullRight);return succeed9(succeed3(zip8(leftChunk,state.rightChunk,options.onBoth)))}});case OP_PULL_RIGHT:return matchEffect2(pullRight,{onFailure:match2({onNone:()=>succeed9(succeed3([map4(state.leftChunk,options.onSelf),DrainLeft])),onSome:(error2)=>succeed9(fail4(some2(error2)))}),onSuccess:(rightChunk)=>{if(isEmpty(rightChunk))return pull(PullRight(state.leftChunk),pullLeft,pullRight);if(isEmpty(state.leftChunk))return pull(PullLeft(rightChunk),pullLeft,pullRight);return succeed9(succeed3(zip8(state.leftChunk,rightChunk,options.onBoth)))}})}},zip8=(leftChunk,rightChunk,f)=>{let[output,either7]=zipChunks(leftChunk,rightChunk,f);switch(either7._tag){case"Left":{if(isEmpty(either7.left))return[output,PullBoth];return[output,PullRight(either7.left)]}case"Right":{if(isEmpty(either7.right))return[output,PullBoth];return[output,PullLeft(either7.right)]}}};return combineChunks(self,options.other,PullBoth,pull)}),zipLatest=dual(2,(left3,right3)=>pipe(left3,zipLatestWith(right3,(a,a2)=>[a,a2]))),zipLatestAll=(...streams)=>{if(streams.length===0)return empty29;else if(streams.length===1)return map22(streams[0],(x)=>[x]);let[head6,...tail]=streams;return zipLatestWith(head6,zipLatestAll(...tail),(first,second)=>[first,...second])},zipLatestWith=dual(3,(left3,right3,f)=>{let pullNonEmpty=(pull)=>pipe(pull,flatMap11((chunk3)=>isEmpty(chunk3)?pullNonEmpty(pull):succeed9(chunk3)));return pipe(toPull2(left3),map16(pullNonEmpty),zip5(pipe(toPull2(right3),map16(pullNonEmpty))),flatMap11(([left4,right4])=>pipe(fromEffectOption(raceWith2(left4,right4,{onSelfDone:(leftDone,rightFiber)=>pipe(suspend3(()=>leftDone),zipWith6(join3(rightFiber),(l,r)=>[l,r,!0])),onOtherDone:(rightDone,leftFiber)=>pipe(suspend3(()=>rightDone),zipWith6(join3(leftFiber),(l,r)=>[r,l,!1]))})),flatMap16(([l,r,leftFirst])=>pipe(fromEffect7(make24([unsafeLast(l),unsafeLast(r)])),flatMap16((latest)=>pipe(fromChunk(leftFirst?pipe(r,map4((a2)=>f(unsafeLast(l),a2))):pipe(l,map4((a)=>f(a,unsafeLast(r))))),concat2(pipe(repeatEffectOption(left4),mergeEither(repeatEffectOption(right4)),mapEffectSequential(match({onLeft:(leftChunk)=>modify4(latest,([_,rightLatest])=>[pipe(leftChunk,map4((a)=>f(a,rightLatest))),[unsafeLast(leftChunk),rightLatest]]),onRight:(rightChunk)=>modify4(latest,([leftLatest,_])=>[pipe(rightChunk,map4((a2)=>f(leftLatest,a2))),[leftLatest,unsafeLast(rightChunk)]])})),flatMap16(fromChunk))))))),toPull2)),fromPull2)}),zipLeft6=dual(2,(left3,right3)=>pipe(left3,zipWithChunks(right3,(left4,right4)=>{if(left4.length>right4.length)return[pipe(left4,take(right4.length)),left2(pipe(left4,take(right4.length)))];return[left4,right2(pipe(right4,drop2(left4.length)))]}))),zipRight9=dual(2,(left3,right3)=>pipe(left3,zipWithChunks(right3,(left4,right4)=>{if(left4.length>right4.length)return[right4,left2(pipe(left4,take(right4.length)))];return[pipe(right4,take(left4.length)),right2(pipe(right4,drop2(left4.length)))]}))),zipWith11=dual(3,(left3,right3,f)=>pipe(left3,zipWithChunks(right3,(leftChunk,rightChunk)=>zipChunks(leftChunk,rightChunk,f)))),zipWithChunks=dual(3,(self,that,f)=>{let pull=(state,pullLeft,pullRight)=>{switch(state._tag){case OP_PULL_BOTH2:return pipe(unsome(pullLeft),zip5(unsome(pullRight),{concurrent:!0}),matchEffect2({onFailure:(error2)=>succeed9(fail4(some2(error2))),onSuccess:([leftOption,rightOption])=>{if(isSome2(leftOption)&&isSome2(rightOption)){if(isEmpty(leftOption.value)&&isEmpty(rightOption.value))return pull(PullBoth2,pullLeft,pullRight);if(isEmpty(leftOption.value))return pull(PullLeft2(rightOption.value),pullLeft,pullRight);if(isEmpty(rightOption.value))return pull(PullRight2(leftOption.value),pullLeft,pullRight);return succeed9(succeed3(zip8(leftOption.value,rightOption.value)))}return succeed9(fail4(none2()))}}));case OP_PULL_LEFT2:return matchEffect2(pullLeft,{onFailure:(error2)=>succeed9(fail4(error2)),onSuccess:(leftChunk)=>{if(isEmpty(leftChunk))return pull(PullLeft2(state.rightChunk),pullLeft,pullRight);if(isEmpty(state.rightChunk))return pull(PullRight2(leftChunk),pullLeft,pullRight);return succeed9(succeed3(zip8(leftChunk,state.rightChunk)))}});case OP_PULL_RIGHT2:return matchEffect2(pullRight,{onFailure:(error2)=>succeed9(fail4(error2)),onSuccess:(rightChunk)=>{if(isEmpty(rightChunk))return pull(PullRight2(state.leftChunk),pullLeft,pullRight);if(isEmpty(state.leftChunk))return pull(PullLeft2(rightChunk),pullLeft,pullRight);return succeed9(succeed3(zip8(state.leftChunk,rightChunk)))}})}},zip8=(leftChunk,rightChunk)=>{let[output,either7]=f(leftChunk,rightChunk);switch(either7._tag){case"Left":{if(isEmpty(either7.left))return[output,PullBoth2];return[output,PullRight2(either7.left)]}case"Right":{if(isEmpty(either7.right))return[output,PullBoth2];return[output,PullLeft2(either7.right)]}}};return pipe(self,combineChunks(that,PullBoth2,pull))}),zipWithIndex=(self)=>pipe(self,mapAccum5(0,(index,a)=>[index+1,[a,index]])),zipWithNext=(self)=>{let process2=(last4)=>readWithCause({onInput:(input)=>{let[newLast,chunk3]=mapAccum2(input,last4,(prev,curr)=>[some2(curr),pipe(prev,map2((a)=>[a,curr]))]),output=filterMap2(chunk3,(option3)=>isSome2(option3)?some2([option3.value[0],some2(option3.value[1])]):none2());return flatMap13(write(output),()=>process2(newLast))},onFailure:failCause10,onDone:()=>match2(last4,{onNone:()=>void_5,onSome:(value)=>zipRight6(write(of2([value,none2()])),void_5)})});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(process2(none2()))))},zipWithPrevious=(self)=>pipe(self,mapAccum5(none2(),(prev,curr)=>[some2(curr),[prev,curr]])),zipWithPreviousAndNext=(self)=>pipe(zipWithNext(zipWithPrevious(self)),map22(([[prev,curr],next4])=>[prev,curr,pipe(next4,map2((tuple2)=>tuple2[1]))])),zipChunks=(left3,right3,f)=>{if(left3.length>right3.length)return[pipe(left3,take(right3.length),zipWith2(right3,f)),left2(pipe(left3,drop2(right3.length)))];return[pipe(left3,zipWith2(pipe(right3,take(left3.length)),f)),right2(pipe(right3,drop2(left3.length)))]},Do3=succeed15({}),bind4=dual((args2)=>typeof args2[0]!=="string",(self,tag,f,options)=>flatMap16(self,(k)=>map22(f(k),(a)=>({...k,[tag]:a})),options)),bindTo4=bindTo(map22),let_4=let_(map22);var decodeText=dual((args2)=>isStream(args2[0]),(self,encoding="utf-8")=>suspend9(()=>{let decoder=new TextDecoder(encoding);return map22(self,(s)=>decoder.decode(s))})),encodeText=(self)=>suspend9(()=>{let encoder=new TextEncoder;return map22(self,(s)=>encoder.encode(s))}),fromEventListener=(target,type,options)=>asyncPush((emit2)=>acquireRelease2(sync4(()=>target.addEventListener(type,emit2.single,options)),()=>sync4(()=>target.removeEventListener(type,emit2.single,options))),{bufferSize:typeof options==="object"?options.bufferSize:void 0});var GroupBySymbolKey="effect/GroupBy",GroupByTypeId=Symbol.for(GroupBySymbolKey),groupByVariance={_R:(_)=>_,_E:(_)=>_,_K:(_)=>_,_V:(_)=>_},isGroupBy=(u)=>hasProperty(u,GroupByTypeId),evaluate2=dual((args2)=>isGroupBy(args2[0]),(self,f,options)=>flatMap16(self.grouped,([key,queue])=>f(key,flattenTake(fromQueue2(queue,{shutdown:!0}))),{concurrency:"unbounded",bufferSize:options?.bufferSize??16}));var make51=(grouped2)=>({[GroupByTypeId]:groupByVariance,pipe(){return pipeArguments(this,arguments)},grouped:grouped2}),groupBy=dual((args2)=>isStream(args2[0]),(self,f,options)=>make51(unwrapScoped4(gen2(function*(){let decider=yield*make39(),output=yield*acquireRelease2(bounded3(options?.bufferSize??16),(queue)=>shutdown2(queue)),ref=yield*make24(new Map),add5=yield*pipe(mapEffectSequential(self,f),distributedWithDynamicCallback(options?.bufferSize??16,([key,value])=>flatMap11(_await3(decider),(f2)=>f2(key,value)),(exit3)=>offer3(output,exit3)));return yield*succeed7(decider,(key,_)=>pipe(get11(ref),map16((map23)=>fromNullable(map23.get(key))),flatMap11(match2({onNone:()=>flatMap11(add5,([index,queue])=>zipRight4(update3(ref,(map23)=>map23.set(key,index)),pipe(offer3(output,succeed3([key,mapDequeue(queue,(exit3)=>new TakeImpl(pipe(exit3,map12((tuple2)=>of2(tuple2[1])))))])),as4((n)=>n===index)))),onSome:(index)=>succeed9((n)=>n===index)})))),flattenExitOption(fromQueue2(output,{shutdown:!0}))})))),mapEffectOptions=dual((args2)=>typeof args2[0]!=="function",(self,f,options)=>{if(options?.key)return evaluate2(groupByKey(self,options.key,{bufferSize:options.bufferSize}),(_,s)=>mapEffectSequential(s,f));return matchConcurrency(options?.concurrency,()=>mapEffectSequential(self,f),(n)=>options?.unordered?flatMap16(self,(a)=>fromEffect7(f(a)),{concurrency:n}):mapEffectPar(self,n,f))}),bindEffect=dual((args2)=>typeof args2[0]!=="string",(self,tag,f,options)=>mapEffectOptions(self,(k)=>map16(f(k),(a)=>({...k,[tag]:a})),options)),mapDequeue=(dequeue,f)=>new MapDequeue(dequeue,f);class MapDequeue extends Class{dequeue;f;[DequeueTypeId2]={_Out:(_)=>_};constructor(dequeue,f){super();this.dequeue=dequeue,this.f=f}capacity(){return capacity3(this.dequeue)}get size(){return size10(this.dequeue)}unsafeSize(){return this.dequeue.unsafeSize()}get awaitShutdown(){return awaitShutdown2(this.dequeue)}isActive(){return this.dequeue.isActive()}get isShutdown(){return isShutdown2(this.dequeue)}get shutdown(){return shutdown2(this.dequeue)}get isFull(){return isFull2(this.dequeue)}get isEmpty(){return isEmpty11(this.dequeue)}get take(){return pipe(take3(this.dequeue),map16((a)=>this.f(a)))}get takeAll(){return pipe(takeAll2(this.dequeue),map16(map4((a)=>this.f(a))))}takeUpTo(max6){return pipe(takeUpTo2(this.dequeue,max6),map16(map4((a)=>this.f(a))))}takeBetween(min4,max6){return pipe(takeBetween2(this.dequeue,min4,max6),map16(map4((a)=>this.f(a))))}takeN(n){return pipe(takeN2(this.dequeue,n),map16(map4((a)=>this.f(a))))}poll(){return pipe(poll6(this.dequeue),map16(map2((a)=>this.f(a))))}pipe(){return pipeArguments(this,arguments)}commit(){return this.take}}var groupByKey=dual((args2)=>typeof args2[0]!=="function",(self,f,options)=>{let loop3=(map23,outerQueue)=>readWithCause({onInput:(input)=>flatMap13(fromEffect4(forEach6(groupByIterable(input,f),([key,values3])=>{let innerQueue=map23.get(key);if(innerQueue===void 0)return pipe(bounded3(options?.bufferSize??16),flatMap11((innerQueue2)=>pipe(sync4(()=>{map23.set(key,innerQueue2)}),zipRight4(offer3(outerQueue,of5([key,innerQueue2]))),zipRight4(pipe(offer3(innerQueue2,chunk2(values3)),catchSomeCause2((cause3)=>isInterruptedOnly2(cause3)?some2(_void):none2()))))));return catchSomeCause2(offer3(innerQueue,chunk2(values3)),(cause3)=>isInterruptedOnly2(cause3)?some2(_void):none2())},{discard:!0})),()=>loop3(map23,outerQueue)),onFailure:(cause3)=>fromEffect4(offer3(outerQueue,failCause11(cause3))),onDone:()=>fromEffect4(pipe(forEach6(map23.entries(),([_,innerQueue])=>pipe(offer3(innerQueue,end4),catchSomeCause2((cause3)=>isInterruptedOnly2(cause3)?some2(_void):none2())),{discard:!0}),zipRight4(offer3(outerQueue,end4))))});return make51(unwrapScopedWith3((scope5)=>gen2(function*(){let map23=new Map,queue=yield*unbounded3();return yield*addFinalizer2(scope5,shutdown2(queue)),yield*toChannel2(self).pipe(pipeTo(loop3(map23,queue)),drain,runIn(scope5),forkIn2(scope5),as4(flattenTake(fromQueue2(queue,{shutdown:!0}))))})))}),groupByIterable=dual(2,(iterable,f)=>{let builder=[],iterator=iterable[Symbol.iterator](),map23=new Map,next4;while((next4=iterator.next())&&!next4.done){let value=next4.value,key=f(value);if(map23.has(key))map23.get(key).push(value);else{let innerBuilder=[value];builder.push([key,innerBuilder]),map23.set(key,innerBuilder)}}return unsafeFromArray(builder.map((tuple2)=>[tuple2[0],unsafeFromArray(tuple2[1])]))});var StreamTypeId3=StreamTypeId2,DefaultChunkSize2=DefaultChunkSize,accumulate2=accumulate,accumulateChunks2=accumulateChunks,acquireRelease4=acquireRelease3,aggregate2=aggregate,aggregateWithin2=aggregateWithin,aggregateWithinEither2=aggregateWithinEither,as9=as8,_async2=_async;var asyncEffect4=asyncEffect3,asyncPush2=asyncPush,asyncScoped2=asyncScoped,branchAfter2=branchAfter,broadcast2=broadcast,share2=share,broadcastDynamic2=broadcastDynamic,broadcastedQueues2=broadcastedQueues,broadcastedQueuesDynamic2=broadcastedQueuesDynamic,buffer2=buffer,bufferChunks2=bufferChunks,catchAll8=catchAll7,catchAllCause7=catchAllCause6,catchSome4=catchSome3,catchTag4=catchTag3,catchTags4=catchTags3,catchSomeCause4=catchSomeCause3,changes2=changes,changesWith2=changesWith,changesWithEffect2=changesWithEffect,chunks2=chunks,chunksWith2=chunksWith,combine10=combine9,combineChunks2=combineChunks,concat3=concat2,concatAll3=concatAll2,cross2=cross,crossLeft2=crossLeft,crossRight2=crossRight,crossWith2=crossWith,debounce2=debounce,die11=die10,dieSync7=dieSync6,dieMessage5=dieMessage4,distributedWith2=distributedWith,distributedWithDynamic2=distributedWithDynamic,drain4=drain3,drainFork2=drainFork,drop4=drop3,dropRight2=dropRight,dropUntil4=dropUntil3,dropUntilEffect2=dropUntilEffect,dropWhile5=dropWhile4,dropWhileEffect2=dropWhileEffect,either7=either6,empty30=empty29,ensuring8=ensuring7,ensuringWith3=ensuringWith2,context6=context5,contextWith4=contextWith3,contextWithEffect4=contextWithEffect3,contextWithStream2=contextWithStream,execute2=execute,fail16=fail15,failSync8=failSync7,failCause14=failCause13,failCauseSync7=failCauseSync6,filter9=filter8,filterEffect2=filterEffect,filterMap7=filterMap6,filterMapEffect2=filterMapEffect,filterMapWhile4=filterMapWhile3,filterMapWhileEffect2=filterMapWhileEffect,finalizer2=finalizer,find3=find2,findEffect2=findEffect,flatMap17=flatMap16,flatten13=flatten12,flattenChunks2=flattenChunks,flattenEffect2=flattenEffect,flattenExitOption2=flattenExitOption,flattenIterables2=flattenIterables,flattenTake2=flattenTake,forever6=forever5,fromAsyncIterable2=fromAsyncIterable,fromChannel3=fromChannel2,toChannel3=toChannel2,fromChunk2=fromChunk,fromChunkPubSub2=fromChunkPubSub,fromChunkQueue2=fromChunkQueue,fromChunks2=fromChunks,fromEffect8=fromEffect7,fromEffectOption2=fromEffectOption,fromPubSub2=fromPubSub,fromTPubSub2=fromTPubSub,fromIterable10=fromIterable9,fromIterableEffect2=fromIterableEffect,fromIteratorSucceed2=fromIteratorSucceed,fromPull3=fromPull2,fromQueue3=fromQueue2,fromTQueue2=fromTQueue,fromReadableStream2=fromReadableStream,fromReadableStreamByob2=fromReadableStreamByob,fromSchedule2=fromSchedule,groupAdjacentBy2=groupAdjacentBy,groupBy2=groupBy,groupByKey2=groupByKey,grouped2=grouped,groupedWithin2=groupedWithin,haltAfter2=haltAfter,haltWhen2=haltWhen,haltWhenDeferred2=haltWhenDeferred,identity4=identityStream,interleave2=interleave,interleaveWith2=interleaveWith,intersperse2=intersperse,intersperseAffixes2=intersperseAffixes,interruptAfter2=interruptAfter,interruptWhen3=interruptWhen2,interruptWhenDeferred3=interruptWhenDeferred2,iterate4=iterate3,make52=make50,map23=map22,mapAccum6=mapAccum5,mapAccumEffect2=mapAccumEffect,mapBoth7=mapBoth6,mapChunks2=mapChunks,mapChunksEffect2=mapChunksEffect,mapConcat2=mapConcat,mapConcatChunk2=mapConcatChunk,mapConcatChunkEffect2=mapConcatChunkEffect,mapConcatEffect2=mapConcatEffect,mapEffect5=mapEffectOptions,mapError7=mapError6,mapErrorCause5=mapErrorCause4,merge10=merge9,mergeAll9=mergeAll8,mergeWithTag2=mergeWithTag,mergeWith4=mergeWith3,mergeEither2=mergeEither,mergeLeft2=mergeLeft,mergeRight2=mergeRight,mkString3=mkString2,never5=never4,onEnd2=onEnd,onError4=onError3,onDone2=onDone,onStart2=onStart,orDie6=orDie5,orDieWith5=orDieWith4,orElse9=orElse8,orElseEither4=orElseEither3,orElseFail4=orElseFail3,orElseIfEmpty2=orElseIfEmpty,orElseIfEmptyChunk2=orElseIfEmptyChunk,orElseIfEmptyStream2=orElseIfEmptyStream,orElseSucceed4=orElseSucceed3,paginate2=paginate,paginateChunk2=paginateChunk,paginateChunkEffect2=paginateChunkEffect,paginateEffect2=paginateEffect,partition6=partition5,partitionEither2=partitionEither,peel2=peel,pipeThrough2=pipeThrough,pipeThroughChannel2=pipeThroughChannel,pipeThroughChannelOrFail2=pipeThroughChannelOrFail,prepend5=prepend4,provideContext7=provideContext6,provideSomeContext3=provideSomeContext2,provideLayer2=provideLayer,provideService7=provideService6,provideServiceEffect4=provideServiceEffect3,provideServiceStream2=provideServiceStream,mapInputContext7=mapInputContext6,provideSomeLayer3=provideSomeLayer2,race4=race3,raceAll4=raceAll3,range3=range2,rechunk2=rechunk,refineOrDie2=refineOrDie,refineOrDieWith2=refineOrDieWith,repeat3=repeat2,repeatEffect2=repeatEffect,repeatEffectChunk2=repeatEffectChunk,repeatEffectChunkOption2=repeatEffectChunkOption,repeatEffectOption2=repeatEffectOption,repeatEffectWithSchedule2=repeatEffectWithSchedule,repeatEither2=repeatEither,repeatElements2=repeatElements,repeatElementsWith2=repeatElementsWith,repeatValue2=repeatValue,repeatWith2=repeatWith,retry7=retry6,withExecutionPlan4=withExecutionPlan3,run5=run4,runCollect2=runCollect,runCount2=runCount,runDrain3=runDrain2,runFold2=runFold,runFoldEffect2=runFoldEffect,runFoldScoped2=runFoldScoped,runFoldScopedEffect2=runFoldScopedEffect,runFoldWhile2=runFoldWhile,runFoldWhileEffect2=runFoldWhileEffect,runFoldWhileScoped2=runFoldWhileScoped,runFoldWhileScopedEffect2=runFoldWhileScopedEffect,runForEach2=runForEach,runForEachChunk2=runForEachChunk,runForEachChunkScoped2=runForEachChunkScoped,runForEachScoped2=runForEachScoped,runForEachWhile2=runForEachWhile,runForEachWhileScoped2=runForEachWhileScoped,runHead2=runHead,runIntoPubSub2=runIntoPubSub,runIntoPubSubScoped2=runIntoPubSubScoped,runIntoQueue2=runIntoQueue,runIntoQueueElementsScoped2=runIntoQueueElementsScoped,runIntoQueueScoped2=runIntoQueueScoped,runLast2=runLast,runScoped3=runScoped2,runSum2=runSum,scan2=scan,scanEffect2=scanEffect,scanReduce2=scanReduce,scanReduceEffect2=scanReduceEffect,schedule3=schedule2,scheduleWith2=scheduleWith,scoped6=scoped5,scopedWith5=scopedWith4,sliding8=sliding7,slidingSize2=slidingSize,some6=some5,someOrElse2=someOrElse,someOrFail2=someOrFail,split2=split,splitOnChunk2=splitOnChunk,splitLines3=splitLines2,succeed16=succeed15,sync10=sync9,suspend10=suspend9,take8=take7,takeRight3=takeRight2,takeUntil4=takeUntil3,takeUntilEffect2=takeUntilEffect,takeWhile5=takeWhile4,tap7=tap6,tapBoth4=tapBoth3,tapError6=tapError5,tapErrorCause6=tapErrorCause5,tapSink2=tapSink,throttle2=throttle,throttleEffect2=throttleEffect,tick2=tick,timeout4=timeout3,timeoutFail4=timeoutFail3,timeoutFailCause4=timeoutFailCause3,timeoutTo4=timeoutTo3,toPubSub3=toPubSub2,toPull3=toPull2,toQueue3=toQueue2,toQueueOfElements2=toQueueOfElements,toReadableStream2=toReadableStream,toReadableStreamEffect2=toReadableStreamEffect,toReadableStreamRuntime2=toReadableStreamRuntime,toAsyncIterableRuntime2=toAsyncIterableRuntime,toAsyncIterableEffect2=toAsyncIterableEffect,toAsyncIterable2=toAsyncIterable,transduce2=transduce,unfold5=unfold4,unfoldChunk2=unfoldChunk,unfoldChunkEffect2=unfoldChunkEffect,unfoldEffect2=unfoldEffect,void_8=void_7;var unwrap3=unwrap2,unwrapScoped5=unwrapScoped4,unwrapScopedWith4=unwrapScopedWith3,updateService5=updateService4,when4=when3,whenCase2=whenCase,whenCaseEffect2=whenCaseEffect,whenEffect4=whenEffect3,withSpan7=withSpan6,zip8=zip7,zipFlatten2=zipFlatten,zipAll2=zipAll,zipAllLeft2=zipAllLeft,zipAllRight2=zipAllRight,zipAllSortedByKey2=zipAllSortedByKey,zipAllSortedByKeyLeft2=zipAllSortedByKeyLeft,zipAllSortedByKeyRight2=zipAllSortedByKeyRight,zipAllSortedByKeyWith2=zipAllSortedByKeyWith,zipAllWith2=zipAllWith,zipLatest2=zipLatest,zipLatestAll2=zipLatestAll,zipLatestWith2=zipLatestWith,zipLeft7=zipLeft6,zipRight10=zipRight9,zipWith12=zipWith11,zipWithChunks2=zipWithChunks,zipWithNext2=zipWithNext,zipWithPrevious2=zipWithPrevious,zipWithPreviousAndNext2=zipWithPreviousAndNext,zipWithIndex2=zipWithIndex,Do4=Do3,bind5=bind4,bindEffect2=bindEffect,bindTo5=bindTo4,let_5=let_4;var decodeText2=decodeText,encodeText2=encodeText,fromEventListener2=fromEventListener;var exports_Config={};__export(exports_Config,{zipWith:()=>zipWith14,zip:()=>zip10,withDescription:()=>withDescription2,withDefault:()=>withDefault2,validate:()=>validate4,url:()=>url2,unwrap:()=>unwrap5,sync:()=>sync12,suspend:()=>suspend12,succeed:()=>succeed18,string:()=>string3,secret:()=>secret2,repeat:()=>repeat5,redacted:()=>redacted2,primitive:()=>primitive2,port:()=>port2,orElseIf:()=>orElseIf2,orElse:()=>orElse11,option:()=>option4,number:()=>number5,nonEmptyString:()=>nonEmptyString2,nested:()=>nested3,mapOrFail:()=>mapOrFail2,mapAttempt:()=>mapAttempt2,map:()=>map25,logLevel:()=>logLevel2,literal:()=>literal2,isConfig:()=>isConfig2,integer:()=>integer2,hashSet:()=>hashSet3,hashMap:()=>hashMap3,fail:()=>fail18,duration:()=>duration4,date:()=>date2,chunk:()=>chunk4,branded:()=>branded2,boolean:()=>boolean2,array:()=>array5,all:()=>all8,ConfigTypeId:()=>ConfigTypeId2});var isMissingDataOnly2=isMissingDataOnly;var RedactedSymbolKey="effect/Redacted",redactedRegistry=globalValue("effect/Redacted/redactedRegistry",()=>new WeakMap),RedactedTypeId=Symbol.for(RedactedSymbolKey),proto12={[RedactedTypeId]:{_A:(_)=>_},pipe(){return pipeArguments(this,arguments)},toString(){return"<redacted>"},toJSON(){return"<redacted>"},[NodeInspectSymbol](){return"<redacted>"},[symbol](){return pipe(hash(RedactedSymbolKey),combine(hash(redactedRegistry.get(this))),cached(this))},[symbol2](that){return isRedacted(that)&&equals(redactedRegistry.get(this),redactedRegistry.get(that))}},isRedacted=(u)=>hasProperty(u,RedactedTypeId),make53=(value)=>{let redacted=Object.create(proto12);return redactedRegistry.set(redacted,value),redacted};var SecretSymbolKey="effect/Secret",SecretTypeId=Symbol.for(SecretSymbolKey);var SecretProto={...proto12,[SecretTypeId]:SecretTypeId},make54=(bytes)=>{let secret=Object.create(SecretProto);return Object.defineProperty(secret,"toString",{enumerable:!1,value(){return"Secret(<redacted>)"}}),Object.defineProperty(secret,"toJSON",{enumerable:!1,value(){return"<redacted>"}}),Object.defineProperty(secret,"raw",{enumerable:!1,value:bytes}),redactedRegistry.set(secret,bytes.map((byte)=>String.fromCharCode(byte)).join("")),secret};var fromString=(text)=>{return make54(text.split("").map((char)=>char.charCodeAt(0)))};var ConfigSymbolKey="effect/Config",ConfigTypeId=Symbol.for(ConfigSymbolKey),configVariance={_A:(_)=>_},proto13={...CommitPrototype,[ConfigTypeId]:configVariance,commit(){return config(this)}},boolean=(name)=>{let config2=primitive("a boolean property",(text)=>{switch(text){case"true":case"yes":case"on":case"1":return right2(!0);case"false":case"no":case"off":case"0":return right2(!1);default:{let error2=InvalidData([],`Expected a boolean value but received ${formatUnknown(text)}`);return left2(error2)}}});return name===void 0?config2:nested2(config2,name)},url=(name)=>{let config2=primitive("an URL property",(text)=>try_({try:()=>new URL(text),catch:(_)=>InvalidData([],`Expected an URL value but received ${formatUnknown(text)}`)}));return name===void 0?config2:nested2(config2,name)},port=(name)=>{let config2=primitive("a network port property",(text)=>{let result=Number(text);if(Number.isNaN(result)||result.toString()!==text.toString()||!Number.isInteger(result)||result<1||result>65535)return left2(InvalidData([],`Expected a network port value but received ${formatUnknown(text)}`));return right2(result)});return name===void 0?config2:nested2(config2,name)},array4=(config2,name)=>{return pipe(chunk3(config2,name),map24(toArray2))},chunk3=(config2,name)=>{return map24(name===void 0?repeat4(config2):nested2(repeat4(config2),name),unsafeFromArray)},date=(name)=>{let config2=primitive("a date property",(text)=>{let result=Date.parse(text);if(Number.isNaN(result))return left2(InvalidData([],`Expected a Date value but received ${formatUnknown(text)}`));return right2(new Date(result))});return name===void 0?config2:nested2(config2,name)},fail17=(message)=>{let fail18=Object.create(proto13);return fail18._tag=OP_FAIL2,fail18.message=message,fail18.parse=()=>left2(Unsupported([],message)),fail18},number4=(name)=>{let config2=primitive("a number property",(text)=>{let result=Number(text);if(Number.isNaN(result))return left2(InvalidData([],`Expected a number value but received ${formatUnknown(text)}`));return right2(result)});return name===void 0?config2:nested2(config2,name)},integer=(name)=>{let config2=primitive("an integer property",(text)=>{let result=Number(text);if(!Number.isInteger(result))return left2(InvalidData([],`Expected an integer value but received ${formatUnknown(text)}`));return right2(result)});return name===void 0?config2:nested2(config2,name)},literal=(...literals)=>(name)=>{let valuesString=literals.map(String).join(", "),config2=primitive(`one of (${valuesString})`,(text)=>{let found=literals.find((value)=>String(value)===text);if(found===void 0)return left2(InvalidData([],`Expected one of (${valuesString}) but received ${formatUnknown(text)}`));return right2(found)});return name===void 0?config2:nested2(config2,name)},logLevel=(name)=>{let config2=mapOrFail(string2(),(value)=>{let label=value.toUpperCase(),level=allLogLevels.find((level2)=>level2.label===label);return level===void 0?left2(InvalidData([],`Expected a log level but received ${formatUnknown(value)}`)):right2(level)});return name===void 0?config2:nested2(config2,name)},duration3=(name)=>{let config2=mapOrFail(string2(),(value)=>{let duration4=decodeUnknown(value);return fromOption2(duration4,()=>InvalidData([],`Expected a duration but received ${formatUnknown(value)}`))});return name===void 0?config2:nested2(config2,name)},map24=dual(2,(self,f)=>mapOrFail(self,(a)=>right2(f(a)))),mapAttempt=dual(2,(self,f)=>mapOrFail(self,(a)=>{try{return right2(f(a))}catch(error2){return left2(InvalidData([],error2 instanceof Error?error2.message:`${error2}`))}})),mapOrFail=dual(2,(self,f)=>{let mapOrFail2=Object.create(proto13);return mapOrFail2._tag=OP_MAP_OR_FAIL,mapOrFail2.original=self,mapOrFail2.mapOrFail=f,mapOrFail2}),nested2=dual(2,(self,name)=>{let nested3=Object.create(proto13);return nested3._tag=OP_NESTED,nested3.name=name,nested3.config=self,nested3}),orElse10=dual(2,(self,that)=>{let fallback=Object.create(proto13);return fallback._tag=OP_FALLBACK,fallback.first=self,fallback.second=suspend11(that),fallback.condition=constTrue,fallback}),orElseIf=dual(2,(self,options)=>{let fallback=Object.create(proto13);return fallback._tag=OP_FALLBACK,fallback.first=self,fallback.second=suspend11(options.orElse),fallback.condition=options.if,fallback}),option3=(self)=>{return pipe(self,map24(some2),orElseIf({orElse:()=>succeed17(none2()),if:isMissingDataOnly2}))},primitive=(description,parse2)=>{let primitive2=Object.create(proto13);return primitive2._tag=OP_PRIMITIVE,primitive2.description=description,primitive2.parse=parse2,primitive2},repeat4=(self)=>{let repeat5=Object.create(proto13);return repeat5._tag=OP_SEQUENCE,repeat5.config=self,repeat5},secret=(name)=>{let config2=primitive("a secret property",(text)=>right2(fromString(text)));return name===void 0?config2:nested2(config2,name)},redacted=(nameOrConfig)=>{let config2=isConfig(nameOrConfig)?nameOrConfig:string2(nameOrConfig);return map24(config2,make53)},branded=dual(2,(nameOrConfig,constructor)=>{let config2=isConfig(nameOrConfig)?nameOrConfig:string2(nameOrConfig);return mapOrFail(config2,(a)=>constructor.either(a).pipe(mapLeft((brandErrors)=>InvalidData([],brandErrors.map((brandError)=>brandError.message).join(`
41
- `)))))}),hashSet2=(config2,name)=>{let newConfig=map24(chunk3(config2),fromIterable5);return name===void 0?newConfig:nested2(newConfig,name)},string2=(name)=>{let config2=primitive("a text property",right2);return name===void 0?config2:nested2(config2,name)},nonEmptyString=(name)=>{let config2=primitive("a non-empty text property",liftPredicate((text)=>text.length>0,()=>MissingData([],"Expected a non-empty string")));return name===void 0?config2:nested2(config2,name)},all7=(arg)=>{if(Array.isArray(arg))return tuple2(arg);else if(Symbol.iterator in arg)return tuple2([...arg]);return struct3(arg)},struct3=(r)=>{let entries2=Object.entries(r),result=pipe(entries2[0][1],map24((value)=>({[entries2[0][0]]:value})));if(entries2.length===1)return result;let rest=entries2.slice(1);for(let[key,config2]of rest)result=pipe(result,zipWith13(config2,(record,value)=>({...record,[key]:value})));return result},succeed17=(value)=>{let constant2=Object.create(proto13);return constant2._tag=OP_CONSTANT,constant2.value=value,constant2.parse=()=>right2(value),constant2},suspend11=(config2)=>{let lazy=Object.create(proto13);return lazy._tag=OP_LAZY,lazy.config=config2,lazy},sync11=(value)=>{return suspend11(()=>succeed17(value()))},hashMap2=(config2,name)=>{let table2=Object.create(proto13);return table2._tag=OP_HASHMAP,table2.valueConfig=config2,name===void 0?table2:nested2(table2,name)},isConfig=(u)=>hasProperty(u,ConfigTypeId),tuple2=(tuple3)=>{if(tuple3.length===0)return succeed17([]);if(tuple3.length===1)return map24(tuple3[0],(x)=>[x]);let result=map24(tuple3[0],(x)=>[x]);for(let i=1;i<tuple3.length;i++){let config2=tuple3[i];result=pipe(result,zipWith13(config2,(tuple4,value)=>[...tuple4,value]))}return result},unwrap4=(wrapped)=>{if(isConfig(wrapped))return wrapped;return struct3(Object.fromEntries(Object.entries(wrapped).map(([k,a])=>[k,unwrap4(a)])))},validate3=dual(2,(self,{message,validation})=>mapOrFail(self,(a)=>{if(validation(a))return right2(a);return left2(InvalidData([],message))})),withDefault=dual(2,(self,def)=>orElseIf(self,{orElse:()=>succeed17(def),if:isMissingDataOnly2})),withDescription=dual(2,(self,description)=>{let described=Object.create(proto13);return described._tag=OP_DESCRIBED,described.config=self,described.description=description,described}),zip9=dual(2,(self,that)=>zipWith13(self,that,(a,b)=>[a,b])),zipWith13=dual(3,(self,that,f)=>{let zipWith14=Object.create(proto13);return zipWith14._tag=OP_ZIP_WITH,zipWith14.left=self,zipWith14.right=that,zipWith14.zip=f,zipWith14});var ConfigTypeId2=ConfigTypeId,all8=all7,array5=array4,boolean2=boolean,port2=port,url2=url,chunk4=chunk3,date2=date,fail18=fail17,number5=number4,integer2=integer,literal2=literal,logLevel2=logLevel,duration4=duration3,isConfig2=isConfig,map25=map24,mapAttempt2=mapAttempt,mapOrFail2=mapOrFail,nested3=nested2,orElse11=orElse10,orElseIf2=orElseIf,option4=option3,primitive2=primitive,repeat5=repeat4,secret2=secret,redacted2=redacted,branded2=branded,hashSet3=hashSet2,string3=string2,nonEmptyString2=nonEmptyString,succeed18=succeed17,suspend12=suspend11,sync12=sync11,hashMap3=hashMap2,unwrap5=unwrap4,validate4=validate3,withDefault2=withDefault,withDescription2=withDescription,zip10=zip9,zipWith14=zipWith13;var exports_BunRuntime={};__export(exports_BunRuntime,{runMain:()=>runMain3});var defaultLogger2=defaultLogger;var prettyLoggerDefault2=prettyLoggerDefault;var defaultTeardown=(exit3,onExit4)=>{onExit4(isFailure3(exit3)&&!isInterruptedOnly2(exit3.cause)?1:0)},addPrettyLogger=(refs,fiberId3)=>{let loggers=getOrDefault2(refs,currentLoggers2);if(!has3(loggers,defaultLogger2))return refs;return updateAs2(refs,{fiberId:fiberId3,fiberRef:currentLoggers2,value:loggers.pipe(remove4(defaultLogger2),add2(prettyLoggerDefault2))})},makeRunMain=(f)=>dual((args2)=>isEffect2(args2[0]),(effect4,options)=>{let fiber=options?.disableErrorReporting===!0?runFork2(effect4,{updateRefs:options?.disablePrettyLogger===!0?void 0:addPrettyLogger}):runFork2(tapErrorCause3(effect4,(cause3)=>{if(isInterruptedOnly2(cause3))return _void;return logError2(cause3)}),{updateRefs:options?.disablePrettyLogger===!0?void 0:addPrettyLogger}),teardown=options?.teardown??defaultTeardown;return f({fiber,teardown})});var runMain=makeRunMain(({fiber,teardown})=>{let keepAlive=setInterval(constVoid,2147483647),receivedSignal=!1;fiber.addObserver((exit3)=>{if(!receivedSignal)process.removeListener("SIGINT",onSigint),process.removeListener("SIGTERM",onSigint);clearInterval(keepAlive),teardown(exit3,(code)=>{if(receivedSignal||code!==0)process.exit(code)})});function onSigint(){receivedSignal=!0,process.removeListener("SIGINT",onSigint),process.removeListener("SIGTERM",onSigint),fiber.unsafeInterruptAsFork(fiber.id())}process.on("SIGINT",onSigint),process.on("SIGTERM",onSigint)});var runMain2=runMain;var runMain3=runMain2;var exports_Console={};__export(exports_Console,{withTime:()=>withTime2,withGroup:()=>withGroup2,withConsole:()=>withConsole3,warn:()=>warn2,trace:()=>trace2,timeLog:()=>timeLog2,time:()=>time2,table:()=>table2,setConsole:()=>setConsole2,log:()=>log4,info:()=>info2,group:()=>group2,error:()=>error2,dirxml:()=>dirxml2,dir:()=>dir2,debug:()=>debug2,countReset:()=>countReset2,count:()=>count5,consoleWith:()=>consoleWith3,clear:()=>clear2,assert:()=>assert2,TypeId:()=>TypeId18,Console:()=>Console});var TypeId18=TypeId8,Console=consoleTag,withConsole3=withConsole,setConsole2=setConsole,consoleWith3=consoleWith,assert2=assert,clear2=clear,count5=count,countReset2=countReset,debug2=debug,dir2=dir,dirxml2=dirxml,error2=error,group2=group,info2=info,log4=log2,table2=table,time2=time,timeLog2=timeLog,trace2=trace,warn2=warn,withGroup2=withGroup,withTime2=withTime;var BUILD_COMMIT="9f86cd7",BUILD_VERSION="0.0.11";var getVersionInfo=()=>({version:"0.0.11",commit:"9f86cd7",timestamp:"2026-01-10T07:09:03.385Z",isDev:!1,isDevTimestamp:!1});var CLIConfig=exports_Data.struct,RedistailConfig=exports_Data.struct,PubSubMessage=exports_Data.struct,StreamMessage=exports_Data.struct;class CLIError extends exports_Data.TaggedError("CLIError"){}class ConfigError extends exports_Data.TaggedError("ConfigError"){}class MonitoringError extends exports_Data.TaggedError("MonitoringError"){}var StreamMonitorOptions=exports_Data.struct,isValidConnectionType=(type)=>type==="pubsub"||type==="stream",isValidTopicName=(name)=>typeof name==="string"&&name.trim().length>0,createInvalidArgumentError=(message,context7)=>new CLIError({reason:"InvalidArguments",message,context:context7}),createMissingArgumentError=(message,context7)=>new CLIError({reason:"MissingArguments",message,context:context7}),createDateFilterError=(message,context7)=>new CLIError({reason:"InvalidDateFormat",message,context:context7}),createEnvironmentError=(message,cause3,context7)=>new ConfigError({reason:"InvalidEnvironment",message,cause:cause3,context:context7});var createConnectionLostError=(message,cause3)=>new MonitoringError({reason:"ConnectionLost",message,retryable:!0,cause:cause3}),createSubscriptionFailedError=(message,retryable=!0,cause3)=>new MonitoringError({reason:"SubscriptionFailed",message,retryable,cause:cause3}),createStreamReadFailedError=(message,retryable=!0,cause3)=>new MonitoringError({reason:"StreamReadFailed",message,retryable,cause:cause3}),DEFAULT_CLI_REDIS_CONFIG={host:"127.0.0.1",port:6379,timeout:5000,retryAttempts:3,retryDelay:1000},DEFAULT_DISPLAY_CONFIG={colors:!0,timestamps:!0,prettyJson:!0},DEFAULT_MONITORING_CONFIG={blockTimeout:5000,maxReconnectAttempts:5};var CLIConfigService=exports_Context.GenericTag("CLIConfigService"),redisHost=exports_Config.withDefault(exports_Config.string("REDIS_HOST"),DEFAULT_CLI_REDIS_CONFIG.host),redisPort=exports_Config.withDefault(exports_Config.integer("REDIS_PORT"),DEFAULT_CLI_REDIS_CONFIG.port),redisUrl=exports_Config.option(exports_Config.string("REDIS_URL")),redisTimeout=exports_Config.withDefault(exports_Config.integer("REDIS_TIMEOUT"),DEFAULT_CLI_REDIS_CONFIG.timeout),redisRetryAttempts=exports_Config.withDefault(exports_Config.integer("REDIS_RETRY_ATTEMPTS"),DEFAULT_CLI_REDIS_CONFIG.retryAttempts),redisRetryDelay=exports_Config.withDefault(exports_Config.integer("REDIS_RETRY_DELAY"),DEFAULT_CLI_REDIS_CONFIG.retryDelay),redistailColors=exports_Config.withDefault(exports_Config.boolean("REDISTAIL_COLORS"),DEFAULT_DISPLAY_CONFIG.colors),redistailTimestamps=exports_Config.withDefault(exports_Config.boolean("REDISTAIL_TIMESTAMPS"),DEFAULT_DISPLAY_CONFIG.timestamps),redistailPrettyJson=exports_Config.withDefault(exports_Config.boolean("REDISTAIL_PRETTY_JSON"),DEFAULT_DISPLAY_CONFIG.prettyJson),redistailBlockTimeout=exports_Config.withDefault(exports_Config.integer("REDISTAIL_BLOCK_TIMEOUT"),DEFAULT_MONITORING_CONFIG.blockTimeout),redistailMaxReconnectAttempts=exports_Config.withDefault(exports_Config.integer("REDISTAIL_MAX_RECONNECT_ATTEMPTS"),DEFAULT_MONITORING_CONFIG.maxReconnectAttempts),parseDateFilter=(dateStr)=>exports_Effect.gen(function*(){let lowerDateStr=dateStr.toLowerCase().trim();if(lowerDateStr==="today"){let today=new Date;return today.setHours(0,0,0,0),today}if(lowerDateStr==="yesterday"){let yesterday=new Date;return yesterday.setDate(yesterday.getDate()-1),yesterday.setHours(0,0,0,0),yesterday}let parsedDate=new Date(dateStr);if(Number.isNaN(parsedDate.getTime()))return yield*exports_Effect.fail(createDateFilterError(`Invalid date format: "${dateStr}". Supported formats:
41
+ `)))))}),hashSet2=(config2,name)=>{let newConfig=map24(chunk3(config2),fromIterable5);return name===void 0?newConfig:nested2(newConfig,name)},string2=(name)=>{let config2=primitive("a text property",right2);return name===void 0?config2:nested2(config2,name)},nonEmptyString=(name)=>{let config2=primitive("a non-empty text property",liftPredicate((text)=>text.length>0,()=>MissingData([],"Expected a non-empty string")));return name===void 0?config2:nested2(config2,name)},all7=(arg)=>{if(Array.isArray(arg))return tuple2(arg);else if(Symbol.iterator in arg)return tuple2([...arg]);return struct3(arg)},struct3=(r)=>{let entries2=Object.entries(r),result=pipe(entries2[0][1],map24((value)=>({[entries2[0][0]]:value})));if(entries2.length===1)return result;let rest=entries2.slice(1);for(let[key,config2]of rest)result=pipe(result,zipWith13(config2,(record,value)=>({...record,[key]:value})));return result},succeed17=(value)=>{let constant2=Object.create(proto13);return constant2._tag=OP_CONSTANT,constant2.value=value,constant2.parse=()=>right2(value),constant2},suspend11=(config2)=>{let lazy=Object.create(proto13);return lazy._tag=OP_LAZY,lazy.config=config2,lazy},sync11=(value)=>{return suspend11(()=>succeed17(value()))},hashMap2=(config2,name)=>{let table2=Object.create(proto13);return table2._tag=OP_HASHMAP,table2.valueConfig=config2,name===void 0?table2:nested2(table2,name)},isConfig=(u)=>hasProperty(u,ConfigTypeId),tuple2=(tuple3)=>{if(tuple3.length===0)return succeed17([]);if(tuple3.length===1)return map24(tuple3[0],(x)=>[x]);let result=map24(tuple3[0],(x)=>[x]);for(let i=1;i<tuple3.length;i++){let config2=tuple3[i];result=pipe(result,zipWith13(config2,(tuple4,value)=>[...tuple4,value]))}return result},unwrap4=(wrapped)=>{if(isConfig(wrapped))return wrapped;return struct3(Object.fromEntries(Object.entries(wrapped).map(([k,a])=>[k,unwrap4(a)])))},validate3=dual(2,(self,{message,validation})=>mapOrFail(self,(a)=>{if(validation(a))return right2(a);return left2(InvalidData([],message))})),withDefault=dual(2,(self,def)=>orElseIf(self,{orElse:()=>succeed17(def),if:isMissingDataOnly2})),withDescription=dual(2,(self,description)=>{let described=Object.create(proto13);return described._tag=OP_DESCRIBED,described.config=self,described.description=description,described}),zip9=dual(2,(self,that)=>zipWith13(self,that,(a,b)=>[a,b])),zipWith13=dual(3,(self,that,f)=>{let zipWith14=Object.create(proto13);return zipWith14._tag=OP_ZIP_WITH,zipWith14.left=self,zipWith14.right=that,zipWith14.zip=f,zipWith14});var ConfigTypeId2=ConfigTypeId,all8=all7,array5=array4,boolean2=boolean,port2=port,url2=url,chunk4=chunk3,date2=date,fail18=fail17,number5=number4,integer2=integer,literal2=literal,logLevel2=logLevel,duration4=duration3,isConfig2=isConfig,map25=map24,mapAttempt2=mapAttempt,mapOrFail2=mapOrFail,nested3=nested2,orElse11=orElse10,orElseIf2=orElseIf,option4=option3,primitive2=primitive,repeat5=repeat4,secret2=secret,redacted2=redacted,branded2=branded,hashSet3=hashSet2,string3=string2,nonEmptyString2=nonEmptyString,succeed18=succeed17,suspend12=suspend11,sync12=sync11,hashMap3=hashMap2,unwrap5=unwrap4,validate4=validate3,withDefault2=withDefault,withDescription2=withDescription,zip10=zip9,zipWith14=zipWith13;var exports_BunRuntime={};__export(exports_BunRuntime,{runMain:()=>runMain3});var defaultLogger2=defaultLogger;var prettyLoggerDefault2=prettyLoggerDefault;var defaultTeardown=(exit3,onExit4)=>{onExit4(isFailure3(exit3)&&!isInterruptedOnly2(exit3.cause)?1:0)},addPrettyLogger=(refs,fiberId3)=>{let loggers=getOrDefault2(refs,currentLoggers2);if(!has3(loggers,defaultLogger2))return refs;return updateAs2(refs,{fiberId:fiberId3,fiberRef:currentLoggers2,value:loggers.pipe(remove4(defaultLogger2),add2(prettyLoggerDefault2))})},makeRunMain=(f)=>dual((args2)=>isEffect2(args2[0]),(effect4,options)=>{let fiber=options?.disableErrorReporting===!0?runFork2(effect4,{updateRefs:options?.disablePrettyLogger===!0?void 0:addPrettyLogger}):runFork2(tapErrorCause3(effect4,(cause3)=>{if(isInterruptedOnly2(cause3))return _void;return logError2(cause3)}),{updateRefs:options?.disablePrettyLogger===!0?void 0:addPrettyLogger}),teardown=options?.teardown??defaultTeardown;return f({fiber,teardown})});var runMain=makeRunMain(({fiber,teardown})=>{let keepAlive=setInterval(constVoid,2147483647),receivedSignal=!1;fiber.addObserver((exit3)=>{if(!receivedSignal)process.removeListener("SIGINT",onSigint),process.removeListener("SIGTERM",onSigint);clearInterval(keepAlive),teardown(exit3,(code)=>{if(receivedSignal||code!==0)process.exit(code)})});function onSigint(){receivedSignal=!0,process.removeListener("SIGINT",onSigint),process.removeListener("SIGTERM",onSigint),fiber.unsafeInterruptAsFork(fiber.id())}process.on("SIGINT",onSigint),process.on("SIGTERM",onSigint)});var runMain2=runMain;var runMain3=runMain2;var exports_Console={};__export(exports_Console,{withTime:()=>withTime2,withGroup:()=>withGroup2,withConsole:()=>withConsole3,warn:()=>warn2,trace:()=>trace2,timeLog:()=>timeLog2,time:()=>time2,table:()=>table2,setConsole:()=>setConsole2,log:()=>log4,info:()=>info2,group:()=>group2,error:()=>error2,dirxml:()=>dirxml2,dir:()=>dir2,debug:()=>debug2,countReset:()=>countReset2,count:()=>count5,consoleWith:()=>consoleWith3,clear:()=>clear2,assert:()=>assert2,TypeId:()=>TypeId18,Console:()=>Console});var TypeId18=TypeId8,Console=consoleTag,withConsole3=withConsole,setConsole2=setConsole,consoleWith3=consoleWith,assert2=assert,clear2=clear,count5=count,countReset2=countReset,debug2=debug,dir2=dir,dirxml2=dirxml,error2=error,group2=group,info2=info,log4=log2,table2=table,time2=time,timeLog2=timeLog,trace2=trace,warn2=warn,withGroup2=withGroup,withTime2=withTime;var BUILD_COMMIT="9f86cd7",BUILD_VERSION="0.0.13";var getVersionInfo=()=>({version:"0.0.13",commit:"9f86cd7",timestamp:"2026-01-10T07:09:50.152Z",isDev:!1,isDevTimestamp:!1});var CLIConfig=exports_Data.struct,RedistailConfig=exports_Data.struct,PubSubMessage=exports_Data.struct,StreamMessage=exports_Data.struct;class CLIError extends exports_Data.TaggedError("CLIError"){}class ConfigError extends exports_Data.TaggedError("ConfigError"){}class MonitoringError extends exports_Data.TaggedError("MonitoringError"){}var StreamMonitorOptions=exports_Data.struct,isValidConnectionType=(type)=>type==="pubsub"||type==="stream",isValidTopicName=(name)=>typeof name==="string"&&name.trim().length>0,createInvalidArgumentError=(message,context7)=>new CLIError({reason:"InvalidArguments",message,context:context7}),createMissingArgumentError=(message,context7)=>new CLIError({reason:"MissingArguments",message,context:context7}),createDateFilterError=(message,context7)=>new CLIError({reason:"InvalidDateFormat",message,context:context7}),createEnvironmentError=(message,cause3,context7)=>new ConfigError({reason:"InvalidEnvironment",message,cause:cause3,context:context7});var createConnectionLostError=(message,cause3)=>new MonitoringError({reason:"ConnectionLost",message,retryable:!0,cause:cause3}),createSubscriptionFailedError=(message,retryable=!0,cause3)=>new MonitoringError({reason:"SubscriptionFailed",message,retryable,cause:cause3}),createStreamReadFailedError=(message,retryable=!0,cause3)=>new MonitoringError({reason:"StreamReadFailed",message,retryable,cause:cause3}),DEFAULT_CLI_REDIS_CONFIG={host:"127.0.0.1",port:6379,timeout:5000,retryAttempts:3,retryDelay:1000},DEFAULT_DISPLAY_CONFIG={colors:!0,timestamps:!0,prettyJson:!0},DEFAULT_MONITORING_CONFIG={blockTimeout:5000,maxReconnectAttempts:5};var CLIConfigService=exports_Context.GenericTag("CLIConfigService"),redisHost=exports_Config.withDefault(exports_Config.string("REDIS_HOST"),DEFAULT_CLI_REDIS_CONFIG.host),redisPort=exports_Config.withDefault(exports_Config.integer("REDIS_PORT"),DEFAULT_CLI_REDIS_CONFIG.port),redisUrl=exports_Config.option(exports_Config.string("REDIS_URL")),redisTimeout=exports_Config.withDefault(exports_Config.integer("REDIS_TIMEOUT"),DEFAULT_CLI_REDIS_CONFIG.timeout),redisRetryAttempts=exports_Config.withDefault(exports_Config.integer("REDIS_RETRY_ATTEMPTS"),DEFAULT_CLI_REDIS_CONFIG.retryAttempts),redisRetryDelay=exports_Config.withDefault(exports_Config.integer("REDIS_RETRY_DELAY"),DEFAULT_CLI_REDIS_CONFIG.retryDelay),redistailColors=exports_Config.withDefault(exports_Config.boolean("REDISTAIL_COLORS"),DEFAULT_DISPLAY_CONFIG.colors),redistailTimestamps=exports_Config.withDefault(exports_Config.boolean("REDISTAIL_TIMESTAMPS"),DEFAULT_DISPLAY_CONFIG.timestamps),redistailPrettyJson=exports_Config.withDefault(exports_Config.boolean("REDISTAIL_PRETTY_JSON"),DEFAULT_DISPLAY_CONFIG.prettyJson),redistailBlockTimeout=exports_Config.withDefault(exports_Config.integer("REDISTAIL_BLOCK_TIMEOUT"),DEFAULT_MONITORING_CONFIG.blockTimeout),redistailMaxReconnectAttempts=exports_Config.withDefault(exports_Config.integer("REDISTAIL_MAX_RECONNECT_ATTEMPTS"),DEFAULT_MONITORING_CONFIG.maxReconnectAttempts),parseDateFilter=(dateStr)=>exports_Effect.gen(function*(){let lowerDateStr=dateStr.toLowerCase().trim();if(lowerDateStr==="today"){let today=new Date;return today.setHours(0,0,0,0),today}if(lowerDateStr==="yesterday"){let yesterday=new Date;return yesterday.setDate(yesterday.getDate()-1),yesterday.setHours(0,0,0,0),yesterday}let parsedDate=new Date(dateStr);if(Number.isNaN(parsedDate.getTime()))return yield*exports_Effect.fail(createDateFilterError(`Invalid date format: "${dateStr}". Supported formats:
42
42
  - Keywords: "today" or "yesterday"
43
43
  - ISO 8601: "2026-01-09T10:00:00Z" or "2026-01-09"
44
44
  - RFC 2822: "Fri, 09 Jan 2026 10:00:00 GMT"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ceschiatti/redistail",
3
- "version": "0.0.12",
3
+ "version": "0.0.13",
4
4
  "description": "CLI tool for monitoring Redis streams and PubSub",
5
5
  "type": "module",
6
6
  "bin": {
@@ -7,8 +7,8 @@
7
7
 
8
8
  // These values are replaced at build time by build-cli.js
9
9
  export const BUILD_COMMIT: string = '9f86cd7';
10
- export const BUILD_VERSION: string = '0.0.11';
11
- export const BUILD_TIMESTAMP: string = '2026-01-10T07:09:03.385Z';
10
+ export const BUILD_VERSION: string = '0.0.13';
11
+ export const BUILD_TIMESTAMP: string = '2026-01-10T07:09:50.152Z';
12
12
 
13
13
  /**
14
14
  * Get formatted version information for display