@6qat/tcp-connection 0.2.3 → 0.2.4
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.
- package/dist/index.js +5 -5
- package/package.json +5 -4
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __defProp=Object.defineProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:(newValue)=>all[name]=()=>newValue})};var isFunction=(input)=>typeof input==="function",dual=function(arity,body){if(typeof arity==="function")return function(){if(arity(arguments))return body.apply(this,arguments);return(self)=>body(self,...arguments)};switch(arity){case 0:case 1:throw new RangeError(`Invalid arity ${arity}`);case 2:return function(a,b){if(arguments.length>=2)return body(a,b);return function(self){return body(self,a)}};case 3:return function(a,b,c){if(arguments.length>=3)return body(a,b,c);return function(self){return body(self,a,b)}};case 4:return function(a,b,c,d){if(arguments.length>=4)return body(a,b,c,d);return function(self){return body(self,a,b,c)}};case 5:return function(a,b,c,d,e){if(arguments.length>=5)return body(a,b,c,d,e);return function(self){return body(self,a,b,c,d)}};default:return function(){if(arguments.length>=arity)return body.apply(this,arguments);let args=arguments;return function(self){return body(self,...args)}}}};var identity=(a)=>a;var constant=(value)=>()=>value,constTrue=constant(!0),constFalse=constant(!1);var constUndefined=constant(void 0),constVoid=constUndefined;function pipe(a,ab,bc,cd,de,ef,fg,gh,hi){switch(arguments.length){case 1:return a;case 2:return ab(a);case 3:return bc(ab(a));case 4:return cd(bc(ab(a)));case 5:return de(cd(bc(ab(a))));case 6:return ef(de(cd(bc(ab(a)))));case 7:return fg(ef(de(cd(bc(ab(a))))));case 8:return gh(fg(ef(de(cd(bc(ab(a)))))));case 9:return hi(gh(fg(ef(de(cd(bc(ab(a))))))));default:{let ret=arguments[0];for(let i=1;i<arguments.length;i++)ret=arguments[i](ret);return ret}}}var make=(isEquivalent)=>(self,that)=>self===that||isEquivalent(self,that),isStrictEquivalent=(x,y)=>x===y,strict=()=>isStrictEquivalent;var number=strict();var mapInput=dual(2,(self,f)=>make((x,y)=>self(f(x),f(y)))),Date2=mapInput(number,(date)=>date.getTime());var array=(item)=>make((self,that)=>{if(self.length!==that.length)return!1;for(let i=0;i<self.length;i++)if(!item(self[i],that[i]))return!1;return!0});var let_=(map)=>dual(3,(self,name,f)=>map(self,(a)=>Object.assign({},a,{[name]:f(a)}))),bindTo=(map)=>dual(2,(self,name)=>map(self,(a)=>({[name]:a}))),bind=(map,flatMap)=>dual(3,(self,name,f)=>flatMap(self,(a)=>map(f(a),(b)=>Object.assign({},a,{[name]:b}))));var moduleVersion="3.14.18",getCurrentVersion=()=>moduleVersion;var globalStoreId=`effect/GlobalValue/globalStoreId/${getCurrentVersion()}`,globalStore,globalValue=(id,compute)=>{if(!globalStore)globalThis[globalStoreId]??=new Map,globalStore=globalThis[globalStoreId];if(!globalStore.has(id))globalStore.set(id,compute());return globalStore.get(id)};var isString=(input)=>typeof input==="string",isNumber=(input)=>typeof input==="number",isBoolean=(input)=>typeof input==="boolean",isBigInt=(input)=>typeof input==="bigint",isSymbol=(input)=>typeof input==="symbol";var isFunction2=isFunction,isUndefined=(input)=>input===void 0;var isNever=(_)=>!1;var isRecordOrArray=(input)=>typeof input==="object"&&input!==null,isObject=(input)=>isRecordOrArray(input)||isFunction2(input),hasProperty=dual(2,(self,property)=>isObject(self)&&(property in self)),isTagged=dual(2,(self,tag)=>hasProperty(self,"_tag")&&self._tag===tag),isNullable=(input)=>input===null||input===void 0,isNotNullable=(input)=>input!==null&&input!==void 0;var isDate=(input)=>input instanceof Date,isIterable=(input)=>hasProperty(input,Symbol.iterator),isRecord=(input)=>isRecordOrArray(input)&&!Array.isArray(input);var isPromiseLike=(input)=>hasProperty(input,"then")&&isFunction2(input.then);var getBugErrorMessage=(message)=>`BUG: ${message} - please report an issue at https://github.com/Effect-TS/effect/issues`;class SingleShotGen{self;called=!1;constructor(self){this.self=self}next(a){return this.called?{value:a,done:!0}:(this.called=!0,{value:this.self,done:!1})}return(a){return{value:a,done:!0}}throw(e){throw e}[Symbol.iterator](){return new SingleShotGen(this.self)}}var defaultIncHi=335903614,defaultIncLo=4150755663,MUL_HI=1481765933,MUL_LO=1284865837,BIT_53=9007199254740992,BIT_27=134217728;class PCGRandom{_state;constructor(seedHi,seedLo,incHi,incLo){if(isNullable(seedLo)&&isNullable(seedHi))seedLo=Math.random()*4294967295>>>0,seedHi=0;else if(isNullable(seedLo))seedLo=seedHi,seedHi=0;if(isNullable(incLo)&&isNullable(incHi))incLo=this._state?this._state[3]:defaultIncLo,incHi=this._state?this._state[2]:defaultIncHi;else if(isNullable(incLo))incLo=incHi,incHi=0;return this._state=new Int32Array([0,0,incHi>>>0,((incLo||0)|1)>>>0]),this._next(),add64(this._state,this._state[0],this._state[1],seedHi>>>0,seedLo>>>0),this._next(),this}getState(){return[this._state[0],this._state[1],this._state[2],this._state[3]]}setState(state){this._state[0]=state[0],this._state[1]=state[1],this._state[2]=state[2],this._state[3]=state[3]|1}integer(max){return Math.round(this.number()*Number.MAX_SAFE_INTEGER)%max}number(){let hi=(this._next()&67108863)*1,lo=(this._next()&134217727)*1;return(hi*BIT_27+lo)/BIT_53}_next(){let oldHi=this._state[0]>>>0,oldLo=this._state[1]>>>0;mul64(this._state,oldHi,oldLo,MUL_HI,MUL_LO),add64(this._state,this._state[0],this._state[1],this._state[2],this._state[3]);let xsHi=oldHi>>>18,xsLo=(oldLo>>>18|oldHi<<14)>>>0;xsHi=(xsHi^oldHi)>>>0,xsLo=(xsLo^oldLo)>>>0;let xorshifted=(xsLo>>>27|xsHi<<5)>>>0,rot=oldHi>>>27,rot2=(-rot>>>0&31)>>>0;return(xorshifted>>>rot|xorshifted<<rot2)>>>0}}function mul64(out,aHi,aLo,bHi,bLo){let c1=(aLo>>>16)*(bLo&65535)>>>0,c0=(aLo&65535)*(bLo>>>16)>>>0,lo=(aLo&65535)*(bLo&65535)>>>0,hi=(aLo>>>16)*(bLo>>>16)+((c0>>>16)+(c1>>>16))>>>0;if(c0=c0<<16>>>0,lo=lo+c0>>>0,lo>>>0<c0>>>0)hi=hi+1>>>0;if(c1=c1<<16>>>0,lo=lo+c1>>>0,lo>>>0<c1>>>0)hi=hi+1>>>0;hi=hi+Math.imul(aLo,bHi)>>>0,hi=hi+Math.imul(aHi,bLo)>>>0,out[0]=hi,out[1]=lo}function add64(out,aHi,aLo,bHi,bLo){let hi=aHi+bHi>>>0,lo=aLo+bLo>>>0;if(lo>>>0<aLo>>>0)hi=hi+1|0;out[0]=hi,out[1]=lo}var YieldWrapTypeId=Symbol.for("effect/Utils/YieldWrap");class YieldWrap{#value;constructor(value){this.#value=value}[YieldWrapTypeId](){return this.#value}}function yieldWrapGet(self){if(typeof self==="object"&&self!==null&&YieldWrapTypeId in self)return self[YieldWrapTypeId]();throw new Error(getBugErrorMessage("yieldWrapGet"))}var structuralRegionState=globalValue("effect/Utils/isStructuralRegion",()=>({enabled:!1,tester:void 0}));var standard={effect_internal_function:(body)=>{return body()}},forced={effect_internal_function:(body)=>{try{return body()}finally{}}},isNotOptimizedAway=standard.effect_internal_function(()=>new Error().stack)?.includes("effect_internal_function")===!0,internalCall=isNotOptimizedAway?standard.effect_internal_function:forced.effect_internal_function,genConstructor=function*(){}.constructor,isGeneratorFunction=(u)=>isObject(u)&&u.constructor===genConstructor;var randomHashCache=globalValue(Symbol.for("effect/Hash/randomHashCache"),()=>new WeakMap),symbol=Symbol.for("effect/Hash"),hash=(self)=>{if(structuralRegionState.enabled===!0)return 0;switch(typeof self){case"number":return number2(self);case"bigint":return string(self.toString(10));case"boolean":return string(String(self));case"symbol":return string(String(self));case"string":return string(self);case"undefined":return string("undefined");case"function":case"object":if(self===null)return string("null");else if(self instanceof Date)return hash(self.toISOString());else if(self instanceof URL)return hash(self.href);else if(isHash(self))return self[symbol]();else return random(self);default:throw new Error(`BUG: unhandled typeof ${typeof self} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},random=(self)=>{if(!randomHashCache.has(self))randomHashCache.set(self,number2(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)));return randomHashCache.get(self)},combine=(b)=>(self)=>self*53^b,optimize=(n)=>n&3221225471|n>>>1&1073741824,isHash=(u)=>hasProperty(u,symbol),number2=(n)=>{if(n!==n||n===1/0)return 0;let h=n|0;if(h!==n)h^=n*4294967295;while(n>4294967295)h^=n/=4294967295;return optimize(h)},string=(str)=>{let h=5381,i=str.length;while(i)h=h*33^str.charCodeAt(--i);return optimize(h)},structureKeys=(o,keys)=>{let h=12289;for(let i=0;i<keys.length;i++)h^=pipe(string(keys[i]),combine(hash(o[keys[i]])));return optimize(h)},structure=(o)=>structureKeys(o,Object.keys(o)),array2=(arr)=>{let h=6151;for(let i=0;i<arr.length;i++)h=pipe(h,combine(hash(arr[i])));return optimize(h)},cached=function(){if(arguments.length===1){let self2=arguments[0];return function(hash3){return Object.defineProperty(self2,symbol,{value(){return hash3},enumerable:!1}),hash3}}let self=arguments[0],hash2=arguments[1];return Object.defineProperty(self,symbol,{value(){return hash2},enumerable:!1}),hash2};var symbol2=Symbol.for("effect/Equal");function equals(){if(arguments.length===1)return(self)=>compareBoth(self,arguments[0]);return compareBoth(arguments[0],arguments[1])}function compareBoth(self,that){if(self===that)return!0;let selfType=typeof self;if(selfType!==typeof that)return!1;if(selfType==="object"||selfType==="function"){if(self!==null&&that!==null){if(isEqual(self)&&isEqual(that))if(hash(self)===hash(that)&&self[symbol2](that))return!0;else return structuralRegionState.enabled&&structuralRegionState.tester?structuralRegionState.tester(self,that):!1;else if(self instanceof Date&&that instanceof Date)return self.toISOString()===that.toISOString();else if(self instanceof URL&&that instanceof URL)return self.href===that.href}if(structuralRegionState.enabled){if(Array.isArray(self)&&Array.isArray(that))return self.length===that.length&&self.every((v,i)=>compareBoth(v,that[i]));if(Object.getPrototypeOf(self)===Object.prototype&&Object.getPrototypeOf(self)===Object.prototype){let keysSelf=Object.keys(self),keysThat=Object.keys(that);if(keysSelf.length===keysThat.length){for(let key of keysSelf)if(!((key in that)&&compareBoth(self[key],that[key])))return structuralRegionState.tester?structuralRegionState.tester(self,that):!1;return!0}}return structuralRegionState.tester?structuralRegionState.tester(self,that):!1}}return structuralRegionState.enabled&&structuralRegionState.tester?structuralRegionState.tester(self,that):!1}var isEqual=(u)=>hasProperty(u,symbol2),equivalence=()=>equals;var NodeInspectSymbol=Symbol.for("nodejs.util.inspect.custom"),toJSON=(x)=>{try{if(hasProperty(x,"toJSON")&&isFunction2(x.toJSON)&&x.toJSON.length===0)return x.toJSON();else if(Array.isArray(x))return x.map(toJSON)}catch(_){return{}}return redact(x)},format=(x)=>JSON.stringify(x,null,2),BaseProto={toJSON(){return toJSON(this)},[NodeInspectSymbol](){return this.toJSON()},toString(){return format(this.toJSON())}};var toStringUnknown=(u,whitespace=2)=>{if(typeof u==="string")return u;try{return typeof u==="object"?stringifyCircular(u,whitespace):String(u)}catch(_){return String(u)}},stringifyCircular=(obj,whitespace)=>{let cache=[],retVal=JSON.stringify(obj,(_key,value)=>typeof value==="object"&&value!==null?cache.includes(value)?void 0:cache.push(value)&&(redactableState.fiberRefs!==void 0&&isRedactable(value)?value[symbolRedactable](redactableState.fiberRefs):value):value,whitespace);return cache=void 0,retVal},symbolRedactable=Symbol.for("effect/Inspectable/Redactable"),isRedactable=(u)=>typeof u==="object"&&u!==null&&(symbolRedactable in u),redactableState=globalValue("effect/Inspectable/redactableState",()=>({fiberRefs:void 0})),withRedactableContext=(context,f)=>{let prev=redactableState.fiberRefs;redactableState.fiberRefs=context;try{return f()}finally{redactableState.fiberRefs=prev}},redact=(u)=>{if(isRedactable(u)&&redactableState.fiberRefs!==void 0)return u[symbolRedactable](redactableState.fiberRefs);return u};var pipeArguments=(self,args)=>{switch(args.length){case 0:return self;case 1:return args[0](self);case 2:return args[1](args[0](self));case 3:return args[2](args[1](args[0](self)));case 4:return args[3](args[2](args[1](args[0](self))));case 5:return args[4](args[3](args[2](args[1](args[0](self)))));case 6:return args[5](args[4](args[3](args[2](args[1](args[0](self))))));case 7:return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))));case 8:return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))));case 9:return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))));default:{let ret=self;for(let i=0,len=args.length;i<len;i++)ret=args[i](ret);return ret}}};var OP_ASYNC="Async",OP_COMMIT="Commit",OP_FAILURE="Failure",OP_ON_FAILURE="OnFailure",OP_ON_SUCCESS="OnSuccess",OP_ON_SUCCESS_AND_FAILURE="OnSuccessAndFailure",OP_SUCCESS="Success",OP_SYNC="Sync",OP_TAG="Tag",OP_UPDATE_RUNTIME_FLAGS="UpdateRuntimeFlags",OP_WHILE="While",OP_ITERATOR="Iterator",OP_WITH_RUNTIME="WithRuntime",OP_YIELD="Yield",OP_REVERT_FLAGS="RevertFlags";var EffectTypeId=Symbol.for("effect/Effect"),StreamTypeId=Symbol.for("effect/Stream"),SinkTypeId=Symbol.for("effect/Sink"),ChannelTypeId=Symbol.for("effect/Channel"),effectVariance={_R:(_)=>_,_E:(_)=>_,_A:(_)=>_,_V:getCurrentVersion()},sinkVariance={_A:(_)=>_,_In:(_)=>_,_L:(_)=>_,_E:(_)=>_,_R:(_)=>_},channelVariance={_Env:(_)=>_,_InErr:(_)=>_,_InElem:(_)=>_,_InDone:(_)=>_,_OutErr:(_)=>_,_OutElem:(_)=>_,_OutDone:(_)=>_},EffectPrototype={[EffectTypeId]:effectVariance,[StreamTypeId]:effectVariance,[SinkTypeId]:sinkVariance,[ChannelTypeId]:channelVariance,[symbol2](that){return this===that},[symbol](){return cached(this,random(this))},[Symbol.iterator](){return new SingleShotGen(new YieldWrap(this))},pipe(){return pipeArguments(this,arguments)}},StructuralPrototype={[symbol](){return cached(this,structure(this))},[symbol2](that){let selfKeys=Object.keys(this),thatKeys=Object.keys(that);if(selfKeys.length!==thatKeys.length)return!1;for(let key of selfKeys)if(!((key in that)&&equals(this[key],that[key])))return!1;return!0}},CommitPrototype={...EffectPrototype,_op:OP_COMMIT},StructuralCommitPrototype={...CommitPrototype,...StructuralPrototype},Base=function(){function Base2(){}return Base2.prototype=CommitPrototype,Base2}();var TypeId=Symbol.for("effect/Option"),CommonProto={...EffectPrototype,[TypeId]:{_A:(_)=>_},[NodeInspectSymbol](){return this.toJSON()},toString(){return format(this.toJSON())}},SomeProto=Object.assign(Object.create(CommonProto),{_tag:"Some",_op:"Some",[symbol2](that){return isOption(that)&&isSome(that)&&equals(this.value,that.value)},[symbol](){return cached(this,combine(hash(this._tag))(hash(this.value)))},toJSON(){return{_id:"Option",_tag:this._tag,value:toJSON(this.value)}}}),NoneHash=hash("None"),NoneProto=Object.assign(Object.create(CommonProto),{_tag:"None",_op:"None",[symbol2](that){return isOption(that)&&isNone(that)},[symbol](){return NoneHash},toJSON(){return{_id:"Option",_tag:this._tag}}}),isOption=(input)=>hasProperty(input,TypeId),isNone=(fa)=>fa._tag==="None",isSome=(fa)=>fa._tag==="Some",none=Object.create(NoneProto),some=(value)=>{let a=Object.create(SomeProto);return a.value=value,a};var TypeId2=Symbol.for("effect/Either"),CommonProto2={...EffectPrototype,[TypeId2]:{_R:(_)=>_},[NodeInspectSymbol](){return this.toJSON()},toString(){return format(this.toJSON())}},RightProto=Object.assign(Object.create(CommonProto2),{_tag:"Right",_op:"Right",[symbol2](that){return isEither(that)&&isRight(that)&&equals(this.right,that.right)},[symbol](){return combine(hash(this._tag))(hash(this.right))},toJSON(){return{_id:"Either",_tag:this._tag,right:toJSON(this.right)}}}),LeftProto=Object.assign(Object.create(CommonProto2),{_tag:"Left",_op:"Left",[symbol2](that){return isEither(that)&&isLeft(that)&&equals(this.left,that.left)},[symbol](){return combine(hash(this._tag))(hash(this.left))},toJSON(){return{_id:"Either",_tag:this._tag,left:toJSON(this.left)}}}),isEither=(input)=>hasProperty(input,TypeId2),isLeft=(ma)=>ma._tag==="Left",isRight=(ma)=>ma._tag==="Right",left=(left2)=>{let a=Object.create(LeftProto);return a.left=left2,a},right=(right2)=>{let a=Object.create(RightProto);return a.right=right2,a};var right2=right;var left2=left;var isEither2=isEither,isLeft2=isLeft,isRight2=isRight;var mapLeft=dual(2,(self,f)=>isLeft2(self)?left2(f(self.left)):right2(self.right)),map=dual(2,(self,f)=>isRight2(self)?right2(f(self.right)):left2(self.left)),match=dual(2,(self,{onLeft,onRight})=>isLeft2(self)?onLeft(self.left):onRight(self.right));var merge=match({onLeft:identity,onRight:identity});var getOrThrowWith=dual(2,(self,onLeft)=>{if(isRight2(self))return self.right;throw onLeft(self.left)}),getOrThrow=getOrThrowWith(()=>new Error("getOrThrow called on a Left"));var isNonEmptyArray=(self)=>self.length>0;var make2=(compare)=>(self,that)=>self===that?0:compare(self,that);var number3=make2((self,that)=>self<that?-1:1);var mapInput2=dual(2,(self,f)=>make2((b1,b2)=>self(f(b1),f(b2))));var all=(collection)=>{return make2((x,y)=>{let len=Math.min(x.length,y.length),collectionLength=0;for(let O of collection){if(collectionLength>=len)break;let o=O(x[collectionLength],y[collectionLength]);if(o!==0)return o;collectionLength++}return 0})};var tuple=(...elements)=>all(elements);var lessThan=(O)=>dual(2,(self,that)=>O(self,that)===-1),greaterThan=(O)=>dual(2,(self,that)=>O(self,that)===1);var min=(O)=>dual(2,(self,that)=>self===that||O(self,that)<1?self:that),max=(O)=>dual(2,(self,that)=>self===that||O(self,that)>-1?self:that),clamp=(O)=>dual(2,(self,options)=>min(O)(options.maximum,max(O)(options.minimum,self))),between=(O)=>dual(2,(self,options)=>!lessThan(O)(self,options.minimum)&&!greaterThan(O)(self,options.maximum));var none2=()=>none,some2=some;var isNone2=isNone,isSome2=isSome,match2=dual(2,(self,{onNone,onSome})=>isNone2(self)?onNone():onSome(self.value));var getOrElse=dual(2,(self,onNone)=>isNone2(self)?onNone():self.value),orElse=dual(2,(self,that)=>isNone2(self)?that():self),orElseSome=dual(2,(self,onNone)=>isNone2(self)?some2(onNone()):self);var fromNullable=(nullableValue)=>nullableValue==null?none2():some2(nullableValue);var getOrUndefined=getOrElse(constUndefined),liftThrowable=(f)=>(...a)=>{try{return some2(f(...a))}catch(e){return none2()}},getOrThrowWith2=dual(2,(self,onNone)=>{if(isSome2(self))return self.value;throw onNone()}),getOrThrow2=getOrThrowWith2(()=>new Error("getOrThrow called on a None")),map2=dual(2,(self,f)=>isNone2(self)?none2():some2(f(self.value)));var flatMap=dual(2,(self,f)=>isNone2(self)?none2():f(self.value));var flatMapNullable=dual(2,(self,f)=>isNone2(self)?none2():fromNullable(f(self.value)));var containsWith=(isEquivalent)=>dual(2,(self,a)=>isNone2(self)?!1:isEquivalent(self.value,a)),_equivalence=equivalence(),contains=containsWith(_equivalence),exists=dual(2,(self,refinement)=>isNone2(self)?!1:refinement(self.value));var mergeWith=(f)=>(o1,o2)=>{if(isNone2(o1))return o2;else if(isNone2(o2))return o1;return some2(f(o1.value,o2.value))};var make3=(...elements)=>elements;var unsafeHead=(self)=>{let result=self[Symbol.iterator]().next();if(result.done)throw new Error("unsafeHead: empty iterable");return result.value};var findFirst=dual(2,(self,f)=>{let i=0;for(let a of self){let o=f(a,i);if(isBoolean(o)){if(o)return some2(a)}else if(isSome2(o))return o;i++}return none2()});var constEmpty={[Symbol.iterator](){return constEmptyIterator}},constEmptyIterator={next(){return{done:!0,value:void 0}}},empty=()=>constEmpty;var allocate=(n)=>new Array(n),makeBy=dual(2,(n,f)=>{let max2=Math.max(1,Math.floor(n)),out=new Array(max2);for(let i=0;i<max2;i++)out[i]=f(i);return out});var fromIterable=(collection)=>Array.isArray(collection)?collection:Array.from(collection),ensure=(self)=>Array.isArray(self)?self:[self];var matchLeft=dual(2,(self,{onEmpty,onNonEmpty})=>isNonEmptyReadonlyArray(self)?onNonEmpty(headNonEmpty(self),tailNonEmpty(self)):onEmpty());var prepend=dual(2,(self,head)=>[head,...self]);var append=dual(2,(self,last)=>[...self,last]),appendAll=dual(2,(self,that)=>fromIterable(self).concat(fromIterable(that)));var isArray=Array.isArray,isEmptyArray=(self)=>self.length===0,isEmptyReadonlyArray=isEmptyArray,isNonEmptyArray2=isNonEmptyArray,isNonEmptyReadonlyArray=isNonEmptyArray;var isOutOfBounds=(i,as)=>i<0||i>=as.length,clamp2=(i,as)=>Math.floor(Math.min(Math.max(0,i),as.length)),get=dual(2,(self,index)=>{let i=Math.floor(index);return isOutOfBounds(i,self)?none2():some2(self[i])}),unsafeGet=dual(2,(self,index)=>{let i=Math.floor(index);if(isOutOfBounds(i,self))throw new Error(`Index ${i} out of bounds`);return self[i]});var head=get(0),headNonEmpty=unsafeGet(0),last=(self)=>isNonEmptyReadonlyArray(self)?some2(lastNonEmpty(self)):none2(),lastNonEmpty=(self)=>self[self.length-1];var tailNonEmpty=(self)=>self.slice(1);var spanIndex=(self,predicate)=>{let i=0;for(let a of self){if(!predicate(a,i))break;i++}return i},span=dual(2,(self,predicate)=>splitAt(self,spanIndex(self,predicate))),drop=dual(2,(self,n)=>{let input=fromIterable(self);return input.slice(clamp2(n,input),input.length)});var findFirst2=findFirst;var reverse=(self)=>Array.from(self).reverse(),sort=dual(2,(self,O)=>{let out=Array.from(self);return out.sort(O),out});var zip=dual(2,(self,that)=>zipWith(self,that,make3)),zipWith=dual(3,(self,that,f)=>{let as=fromIterable(self),bs=fromIterable(that);if(isNonEmptyReadonlyArray(as)&&isNonEmptyReadonlyArray(bs)){let out=[f(headNonEmpty(as),headNonEmpty(bs))],len=Math.min(as.length,bs.length);for(let i=1;i<len;i++)out[i]=f(as[i],bs[i]);return out}return[]});var _equivalence2=equivalence();var splitAt=dual(2,(self,n)=>{let input=Array.from(self),_n=Math.floor(n);if(isNonEmptyReadonlyArray(input)){if(_n>=1)return splitNonEmptyAt(input,_n);return[[],input]}return[input,[]]}),splitNonEmptyAt=dual(2,(self,n)=>{let _n=Math.max(1,Math.floor(n));return _n>=self.length?[copy(self),[]]:[prepend(self.slice(1,_n),headNonEmpty(self)),self.slice(_n)]});var copy=(self)=>self.slice();var unionWith=dual(3,(self,that,isEquivalent)=>{let a=fromIterable(self),b=fromIterable(that);if(isNonEmptyReadonlyArray(a)){if(isNonEmptyReadonlyArray(b))return dedupeWith(isEquivalent)(appendAll(a,b));return a}return b}),union=dual(2,(self,that)=>unionWith(self,that,_equivalence2));var empty2=()=>[],of=(a)=>[a],map3=dual(2,(self,f)=>self.map(f)),flatMap2=dual(2,(self,f)=>{if(isEmptyReadonlyArray(self))return[];let out=[];for(let i=0;i<self.length;i++){let inner=f(self[i],i);for(let j=0;j<inner.length;j++)out.push(inner[j])}return out}),flatten=flatMap2(identity),filterMap=dual(2,(self,f)=>{let as=fromIterable(self),out=[];for(let i=0;i<as.length;i++){let o=f(as[i],i);if(isSome2(o))out.push(o.value)}return out}),filterMapWhile=dual(2,(self,f)=>{let i=0,out=[];for(let a of self){let b=f(a,i);if(isSome2(b))out.push(b.value);else break;i++}return out}),partitionMap=dual(2,(self,f)=>{let left3=[],right3=[],as=fromIterable(self);for(let i=0;i<as.length;i++){let e=f(as[i],i);if(isLeft2(e))left3.push(e.left);else right3.push(e.right)}return[left3,right3]}),getSomes=filterMap(identity);var filter=dual(2,(self,predicate)=>{let as=fromIterable(self),out=[];for(let i=0;i<as.length;i++)if(predicate(as[i],i))out.push(as[i]);return out});var reduce=dual(3,(self,b,f)=>fromIterable(self).reduce((b2,a,i)=>f(b2,a,i),b)),reduceRight=dual(3,(self,b,f)=>fromIterable(self).reduceRight((b2,a,i)=>f(b2,a,i),b));var every=dual(2,(self,refinement)=>self.every(refinement));var unfold=(b,f)=>{let out=[],next=b,o;while(isSome2(o=f(next))){let[a,b2]=o.value;out.push(a),next=b2}return out};var getEquivalence=array;var dedupeWith=dual(2,(self,isEquivalent)=>{let input=fromIterable(self);if(isNonEmptyReadonlyArray(input)){let out=[headNonEmpty(input)],rest=tailNonEmpty(input);for(let r of rest)if(out.every((a)=>!isEquivalent(r,a)))out.push(r);return out}return[]}),dedupe=(self)=>dedupeWith(self,equivalence());var join=dual(2,(self,sep)=>fromIterable(self).join(sep)),mapAccum=dual(3,(self,s,f)=>{let i=0,s1=s,out=[];for(let a of self){let r=f(s1,a,i);s1=r[0],out.push(r[1]),i++}return[s1,out]});var getKeysForIndexSignature=(input,parameter)=>{switch(parameter._tag){case"StringKeyword":case"TemplateLiteral":return Object.keys(input);case"SymbolKeyword":return Object.getOwnPropertySymbols(input);case"Refinement":return getKeysForIndexSignature(input,parameter.from)}},ownKeys=(o)=>Object.keys(o).concat(Object.getOwnPropertySymbols(o)),memoizeThunk=(f)=>{let done=!1,a;return()=>{if(done)return a;return a=f(),done=!0,a}},formatDate=(date)=>{try{return date.toISOString()}catch(e){return String(date)}},formatUnknown=(u,checkCircular=!0)=>{if(Array.isArray(u))return`[${u.map((i)=>formatUnknown(i,checkCircular)).join(",")}]`;if(isDate(u))return formatDate(u);if(hasProperty(u,"toString")&&isFunction2(u.toString)&&u.toString!==Object.prototype.toString)return u.toString();if(isString(u))return JSON.stringify(u);if(isNumber(u)||u==null||isBoolean(u)||isSymbol(u))return String(u);if(isBigInt(u))return String(u)+"n";if(isIterable(u))return`${u.constructor.name}(${formatUnknown(Array.from(u),checkCircular)})`;try{if(checkCircular)JSON.stringify(u);let pojo=`{${ownKeys(u).map((k)=>`${isString(k)?JSON.stringify(k):String(k)}:${formatUnknown(u[k],!1)}`).join(",")}}`,name=u.constructor.name;return u.constructor!==Object.prototype.constructor?`${name}(${pojo})`:pojo}catch(e){return"<circular structure>"}},formatPropertyKey=(name)=>typeof name==="string"?JSON.stringify(name):String(name),isNonEmpty=(x)=>Array.isArray(x),isSingle=(x)=>!Array.isArray(x),formatPathKey=(key)=>`[${formatPropertyKey(key)}]`,formatPath=(path)=>isNonEmpty(path)?path.map(formatPathKey).join(""):formatPathKey(path);var getErrorMessage=(reason,details,path,ast)=>{let out=reason;if(path&&isNonEmptyReadonlyArray(path))out+=`
|
|
1
|
+
var __defProp=Object.defineProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:(newValue)=>all[name]=()=>newValue})};var isFunction=(input)=>typeof input==="function",dual=function(arity,body){if(typeof arity==="function")return function(){if(arity(arguments))return body.apply(this,arguments);return(self)=>body(self,...arguments)};switch(arity){case 0:case 1:throw new RangeError(`Invalid arity ${arity}`);case 2:return function(a,b){if(arguments.length>=2)return body(a,b);return function(self){return body(self,a)}};case 3:return function(a,b,c){if(arguments.length>=3)return body(a,b,c);return function(self){return body(self,a,b)}};case 4:return function(a,b,c,d){if(arguments.length>=4)return body(a,b,c,d);return function(self){return body(self,a,b,c)}};case 5:return function(a,b,c,d,e){if(arguments.length>=5)return body(a,b,c,d,e);return function(self){return body(self,a,b,c,d)}};default:return function(){if(arguments.length>=arity)return body.apply(this,arguments);let args=arguments;return function(self){return body(self,...args)}}}};var identity=(a)=>a;var constant=(value)=>()=>value,constTrue=constant(!0),constFalse=constant(!1);var constUndefined=constant(void 0),constVoid=constUndefined;function pipe(a,ab,bc,cd,de,ef,fg,gh,hi){switch(arguments.length){case 1:return a;case 2:return ab(a);case 3:return bc(ab(a));case 4:return cd(bc(ab(a)));case 5:return de(cd(bc(ab(a))));case 6:return ef(de(cd(bc(ab(a)))));case 7:return fg(ef(de(cd(bc(ab(a))))));case 8:return gh(fg(ef(de(cd(bc(ab(a)))))));case 9:return hi(gh(fg(ef(de(cd(bc(ab(a))))))));default:{let ret=arguments[0];for(let i=1;i<arguments.length;i++)ret=arguments[i](ret);return ret}}}var make=(isEquivalent)=>(self,that)=>self===that||isEquivalent(self,that),isStrictEquivalent=(x,y)=>x===y,strict=()=>isStrictEquivalent;var number=strict();var mapInput=dual(2,(self,f)=>make((x,y)=>self(f(x),f(y)))),Date2=mapInput(number,(date)=>date.getTime());var array=(item)=>make((self,that)=>{if(self.length!==that.length)return!1;for(let i=0;i<self.length;i++)if(!item(self[i],that[i]))return!1;return!0});var let_=(map)=>dual(3,(self,name,f)=>map(self,(a)=>Object.assign({},a,{[name]:f(a)}))),bindTo=(map)=>dual(2,(self,name)=>map(self,(a)=>({[name]:a}))),bind=(map,flatMap)=>dual(3,(self,name,f)=>flatMap(self,(a)=>map(f(a),(b)=>Object.assign({},a,{[name]:b}))));var moduleVersion="3.14.21",getCurrentVersion=()=>moduleVersion;var globalStoreId=`effect/GlobalValue/globalStoreId/${getCurrentVersion()}`,globalStore,globalValue=(id,compute)=>{if(!globalStore)globalThis[globalStoreId]??=new Map,globalStore=globalThis[globalStoreId];if(!globalStore.has(id))globalStore.set(id,compute());return globalStore.get(id)};var isString=(input)=>typeof input==="string",isNumber=(input)=>typeof input==="number",isBoolean=(input)=>typeof input==="boolean",isBigInt=(input)=>typeof input==="bigint",isSymbol=(input)=>typeof input==="symbol";var isFunction2=isFunction,isUndefined=(input)=>input===void 0;var isNever=(_)=>!1;var isRecordOrArray=(input)=>typeof input==="object"&&input!==null,isObject=(input)=>isRecordOrArray(input)||isFunction2(input),hasProperty=dual(2,(self,property)=>isObject(self)&&(property in self)),isTagged=dual(2,(self,tag)=>hasProperty(self,"_tag")&&self._tag===tag),isNullable=(input)=>input===null||input===void 0,isNotNullable=(input)=>input!==null&&input!==void 0;var isDate=(input)=>input instanceof Date,isIterable=(input)=>hasProperty(input,Symbol.iterator),isRecord=(input)=>isRecordOrArray(input)&&!Array.isArray(input);var isPromiseLike=(input)=>hasProperty(input,"then")&&isFunction2(input.then);var getBugErrorMessage=(message)=>`BUG: ${message} - please report an issue at https://github.com/Effect-TS/effect/issues`;class SingleShotGen{self;called=!1;constructor(self){this.self=self}next(a){return this.called?{value:a,done:!0}:(this.called=!0,{value:this.self,done:!1})}return(a){return{value:a,done:!0}}throw(e){throw e}[Symbol.iterator](){return new SingleShotGen(this.self)}}var defaultIncHi=335903614,defaultIncLo=4150755663,MUL_HI=1481765933,MUL_LO=1284865837,BIT_53=9007199254740992,BIT_27=134217728;class PCGRandom{_state;constructor(seedHi,seedLo,incHi,incLo){if(isNullable(seedLo)&&isNullable(seedHi))seedLo=Math.random()*4294967295>>>0,seedHi=0;else if(isNullable(seedLo))seedLo=seedHi,seedHi=0;if(isNullable(incLo)&&isNullable(incHi))incLo=this._state?this._state[3]:defaultIncLo,incHi=this._state?this._state[2]:defaultIncHi;else if(isNullable(incLo))incLo=incHi,incHi=0;return this._state=new Int32Array([0,0,incHi>>>0,((incLo||0)|1)>>>0]),this._next(),add64(this._state,this._state[0],this._state[1],seedHi>>>0,seedLo>>>0),this._next(),this}getState(){return[this._state[0],this._state[1],this._state[2],this._state[3]]}setState(state){this._state[0]=state[0],this._state[1]=state[1],this._state[2]=state[2],this._state[3]=state[3]|1}integer(max){return Math.round(this.number()*Number.MAX_SAFE_INTEGER)%max}number(){let hi=(this._next()&67108863)*1,lo=(this._next()&134217727)*1;return(hi*BIT_27+lo)/BIT_53}_next(){let oldHi=this._state[0]>>>0,oldLo=this._state[1]>>>0;mul64(this._state,oldHi,oldLo,MUL_HI,MUL_LO),add64(this._state,this._state[0],this._state[1],this._state[2],this._state[3]);let xsHi=oldHi>>>18,xsLo=(oldLo>>>18|oldHi<<14)>>>0;xsHi=(xsHi^oldHi)>>>0,xsLo=(xsLo^oldLo)>>>0;let xorshifted=(xsLo>>>27|xsHi<<5)>>>0,rot=oldHi>>>27,rot2=(-rot>>>0&31)>>>0;return(xorshifted>>>rot|xorshifted<<rot2)>>>0}}function mul64(out,aHi,aLo,bHi,bLo){let c1=(aLo>>>16)*(bLo&65535)>>>0,c0=(aLo&65535)*(bLo>>>16)>>>0,lo=(aLo&65535)*(bLo&65535)>>>0,hi=(aLo>>>16)*(bLo>>>16)+((c0>>>16)+(c1>>>16))>>>0;if(c0=c0<<16>>>0,lo=lo+c0>>>0,lo>>>0<c0>>>0)hi=hi+1>>>0;if(c1=c1<<16>>>0,lo=lo+c1>>>0,lo>>>0<c1>>>0)hi=hi+1>>>0;hi=hi+Math.imul(aLo,bHi)>>>0,hi=hi+Math.imul(aHi,bLo)>>>0,out[0]=hi,out[1]=lo}function add64(out,aHi,aLo,bHi,bLo){let hi=aHi+bHi>>>0,lo=aLo+bLo>>>0;if(lo>>>0<aLo>>>0)hi=hi+1|0;out[0]=hi,out[1]=lo}var YieldWrapTypeId=Symbol.for("effect/Utils/YieldWrap");class YieldWrap{#value;constructor(value){this.#value=value}[YieldWrapTypeId](){return this.#value}}function yieldWrapGet(self){if(typeof self==="object"&&self!==null&&YieldWrapTypeId in self)return self[YieldWrapTypeId]();throw new Error(getBugErrorMessage("yieldWrapGet"))}var structuralRegionState=globalValue("effect/Utils/isStructuralRegion",()=>({enabled:!1,tester:void 0}));var standard={effect_internal_function:(body)=>{return body()}},forced={effect_internal_function:(body)=>{try{return body()}finally{}}},isNotOptimizedAway=standard.effect_internal_function(()=>new Error().stack)?.includes("effect_internal_function")===!0,internalCall=isNotOptimizedAway?standard.effect_internal_function:forced.effect_internal_function,genConstructor=function*(){}.constructor,isGeneratorFunction=(u)=>isObject(u)&&u.constructor===genConstructor;var randomHashCache=globalValue(Symbol.for("effect/Hash/randomHashCache"),()=>new WeakMap),symbol=Symbol.for("effect/Hash"),hash=(self)=>{if(structuralRegionState.enabled===!0)return 0;switch(typeof self){case"number":return number2(self);case"bigint":return string(self.toString(10));case"boolean":return string(String(self));case"symbol":return string(String(self));case"string":return string(self);case"undefined":return string("undefined");case"function":case"object":if(self===null)return string("null");else if(self instanceof Date)return hash(self.toISOString());else if(self instanceof URL)return hash(self.href);else if(isHash(self))return self[symbol]();else return random(self);default:throw new Error(`BUG: unhandled typeof ${typeof self} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},random=(self)=>{if(!randomHashCache.has(self))randomHashCache.set(self,number2(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)));return randomHashCache.get(self)},combine=(b)=>(self)=>self*53^b,optimize=(n)=>n&3221225471|n>>>1&1073741824,isHash=(u)=>hasProperty(u,symbol),number2=(n)=>{if(n!==n||n===1/0)return 0;let h=n|0;if(h!==n)h^=n*4294967295;while(n>4294967295)h^=n/=4294967295;return optimize(h)},string=(str)=>{let h=5381,i=str.length;while(i)h=h*33^str.charCodeAt(--i);return optimize(h)},structureKeys=(o,keys)=>{let h=12289;for(let i=0;i<keys.length;i++)h^=pipe(string(keys[i]),combine(hash(o[keys[i]])));return optimize(h)},structure=(o)=>structureKeys(o,Object.keys(o)),array2=(arr)=>{let h=6151;for(let i=0;i<arr.length;i++)h=pipe(h,combine(hash(arr[i])));return optimize(h)},cached=function(){if(arguments.length===1){let self2=arguments[0];return function(hash3){return Object.defineProperty(self2,symbol,{value(){return hash3},enumerable:!1}),hash3}}let self=arguments[0],hash2=arguments[1];return Object.defineProperty(self,symbol,{value(){return hash2},enumerable:!1}),hash2};var symbol2=Symbol.for("effect/Equal");function equals(){if(arguments.length===1)return(self)=>compareBoth(self,arguments[0]);return compareBoth(arguments[0],arguments[1])}function compareBoth(self,that){if(self===that)return!0;let selfType=typeof self;if(selfType!==typeof that)return!1;if(selfType==="object"||selfType==="function"){if(self!==null&&that!==null){if(isEqual(self)&&isEqual(that))if(hash(self)===hash(that)&&self[symbol2](that))return!0;else return structuralRegionState.enabled&&structuralRegionState.tester?structuralRegionState.tester(self,that):!1;else if(self instanceof Date&&that instanceof Date)return self.toISOString()===that.toISOString();else if(self instanceof URL&&that instanceof URL)return self.href===that.href}if(structuralRegionState.enabled){if(Array.isArray(self)&&Array.isArray(that))return self.length===that.length&&self.every((v,i)=>compareBoth(v,that[i]));if(Object.getPrototypeOf(self)===Object.prototype&&Object.getPrototypeOf(self)===Object.prototype){let keysSelf=Object.keys(self),keysThat=Object.keys(that);if(keysSelf.length===keysThat.length){for(let key of keysSelf)if(!((key in that)&&compareBoth(self[key],that[key])))return structuralRegionState.tester?structuralRegionState.tester(self,that):!1;return!0}}return structuralRegionState.tester?structuralRegionState.tester(self,that):!1}}return structuralRegionState.enabled&&structuralRegionState.tester?structuralRegionState.tester(self,that):!1}var isEqual=(u)=>hasProperty(u,symbol2),equivalence=()=>equals;var NodeInspectSymbol=Symbol.for("nodejs.util.inspect.custom"),toJSON=(x)=>{try{if(hasProperty(x,"toJSON")&&isFunction2(x.toJSON)&&x.toJSON.length===0)return x.toJSON();else if(Array.isArray(x))return x.map(toJSON)}catch(_){return{}}return redact(x)},format=(x)=>JSON.stringify(x,null,2),BaseProto={toJSON(){return toJSON(this)},[NodeInspectSymbol](){return this.toJSON()},toString(){return format(this.toJSON())}};var toStringUnknown=(u,whitespace=2)=>{if(typeof u==="string")return u;try{return typeof u==="object"?stringifyCircular(u,whitespace):String(u)}catch(_){return String(u)}},stringifyCircular=(obj,whitespace)=>{let cache=[],retVal=JSON.stringify(obj,(_key,value)=>typeof value==="object"&&value!==null?cache.includes(value)?void 0:cache.push(value)&&(redactableState.fiberRefs!==void 0&&isRedactable(value)?value[symbolRedactable](redactableState.fiberRefs):value):value,whitespace);return cache=void 0,retVal},symbolRedactable=Symbol.for("effect/Inspectable/Redactable"),isRedactable=(u)=>typeof u==="object"&&u!==null&&(symbolRedactable in u),redactableState=globalValue("effect/Inspectable/redactableState",()=>({fiberRefs:void 0})),withRedactableContext=(context,f)=>{let prev=redactableState.fiberRefs;redactableState.fiberRefs=context;try{return f()}finally{redactableState.fiberRefs=prev}},redact=(u)=>{if(isRedactable(u)&&redactableState.fiberRefs!==void 0)return u[symbolRedactable](redactableState.fiberRefs);return u};var pipeArguments=(self,args)=>{switch(args.length){case 0:return self;case 1:return args[0](self);case 2:return args[1](args[0](self));case 3:return args[2](args[1](args[0](self)));case 4:return args[3](args[2](args[1](args[0](self))));case 5:return args[4](args[3](args[2](args[1](args[0](self)))));case 6:return args[5](args[4](args[3](args[2](args[1](args[0](self))))));case 7:return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))));case 8:return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))));case 9:return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))));default:{let ret=self;for(let i=0,len=args.length;i<len;i++)ret=args[i](ret);return ret}}};var OP_ASYNC="Async",OP_COMMIT="Commit",OP_FAILURE="Failure",OP_ON_FAILURE="OnFailure",OP_ON_SUCCESS="OnSuccess",OP_ON_SUCCESS_AND_FAILURE="OnSuccessAndFailure",OP_SUCCESS="Success",OP_SYNC="Sync",OP_TAG="Tag",OP_UPDATE_RUNTIME_FLAGS="UpdateRuntimeFlags",OP_WHILE="While",OP_ITERATOR="Iterator",OP_WITH_RUNTIME="WithRuntime",OP_YIELD="Yield",OP_REVERT_FLAGS="RevertFlags";var EffectTypeId=Symbol.for("effect/Effect"),StreamTypeId=Symbol.for("effect/Stream"),SinkTypeId=Symbol.for("effect/Sink"),ChannelTypeId=Symbol.for("effect/Channel"),effectVariance={_R:(_)=>_,_E:(_)=>_,_A:(_)=>_,_V:getCurrentVersion()},sinkVariance={_A:(_)=>_,_In:(_)=>_,_L:(_)=>_,_E:(_)=>_,_R:(_)=>_},channelVariance={_Env:(_)=>_,_InErr:(_)=>_,_InElem:(_)=>_,_InDone:(_)=>_,_OutErr:(_)=>_,_OutElem:(_)=>_,_OutDone:(_)=>_},EffectPrototype={[EffectTypeId]:effectVariance,[StreamTypeId]:effectVariance,[SinkTypeId]:sinkVariance,[ChannelTypeId]:channelVariance,[symbol2](that){return this===that},[symbol](){return cached(this,random(this))},[Symbol.iterator](){return new SingleShotGen(new YieldWrap(this))},pipe(){return pipeArguments(this,arguments)}},StructuralPrototype={[symbol](){return cached(this,structure(this))},[symbol2](that){let selfKeys=Object.keys(this),thatKeys=Object.keys(that);if(selfKeys.length!==thatKeys.length)return!1;for(let key of selfKeys)if(!((key in that)&&equals(this[key],that[key])))return!1;return!0}},CommitPrototype={...EffectPrototype,_op:OP_COMMIT},StructuralCommitPrototype={...CommitPrototype,...StructuralPrototype},Base=function(){function Base2(){}return Base2.prototype=CommitPrototype,Base2}();var TypeId=Symbol.for("effect/Option"),CommonProto={...EffectPrototype,[TypeId]:{_A:(_)=>_},[NodeInspectSymbol](){return this.toJSON()},toString(){return format(this.toJSON())}},SomeProto=Object.assign(Object.create(CommonProto),{_tag:"Some",_op:"Some",[symbol2](that){return isOption(that)&&isSome(that)&&equals(this.value,that.value)},[symbol](){return cached(this,combine(hash(this._tag))(hash(this.value)))},toJSON(){return{_id:"Option",_tag:this._tag,value:toJSON(this.value)}}}),NoneHash=hash("None"),NoneProto=Object.assign(Object.create(CommonProto),{_tag:"None",_op:"None",[symbol2](that){return isOption(that)&&isNone(that)},[symbol](){return NoneHash},toJSON(){return{_id:"Option",_tag:this._tag}}}),isOption=(input)=>hasProperty(input,TypeId),isNone=(fa)=>fa._tag==="None",isSome=(fa)=>fa._tag==="Some",none=Object.create(NoneProto),some=(value)=>{let a=Object.create(SomeProto);return a.value=value,a};var TypeId2=Symbol.for("effect/Either"),CommonProto2={...EffectPrototype,[TypeId2]:{_R:(_)=>_},[NodeInspectSymbol](){return this.toJSON()},toString(){return format(this.toJSON())}},RightProto=Object.assign(Object.create(CommonProto2),{_tag:"Right",_op:"Right",[symbol2](that){return isEither(that)&&isRight(that)&&equals(this.right,that.right)},[symbol](){return combine(hash(this._tag))(hash(this.right))},toJSON(){return{_id:"Either",_tag:this._tag,right:toJSON(this.right)}}}),LeftProto=Object.assign(Object.create(CommonProto2),{_tag:"Left",_op:"Left",[symbol2](that){return isEither(that)&&isLeft(that)&&equals(this.left,that.left)},[symbol](){return combine(hash(this._tag))(hash(this.left))},toJSON(){return{_id:"Either",_tag:this._tag,left:toJSON(this.left)}}}),isEither=(input)=>hasProperty(input,TypeId2),isLeft=(ma)=>ma._tag==="Left",isRight=(ma)=>ma._tag==="Right",left=(left2)=>{let a=Object.create(LeftProto);return a.left=left2,a},right=(right2)=>{let a=Object.create(RightProto);return a.right=right2,a};var right2=right;var left2=left;var isEither2=isEither,isLeft2=isLeft,isRight2=isRight;var mapLeft=dual(2,(self,f)=>isLeft2(self)?left2(f(self.left)):right2(self.right)),map=dual(2,(self,f)=>isRight2(self)?right2(f(self.right)):left2(self.left)),match=dual(2,(self,{onLeft,onRight})=>isLeft2(self)?onLeft(self.left):onRight(self.right));var merge=match({onLeft:identity,onRight:identity});var getOrThrowWith=dual(2,(self,onLeft)=>{if(isRight2(self))return self.right;throw onLeft(self.left)}),getOrThrow=getOrThrowWith(()=>new Error("getOrThrow called on a Left"));var isNonEmptyArray=(self)=>self.length>0;var make2=(compare)=>(self,that)=>self===that?0:compare(self,that);var number3=make2((self,that)=>self<that?-1:1);var mapInput2=dual(2,(self,f)=>make2((b1,b2)=>self(f(b1),f(b2))));var all=(collection)=>{return make2((x,y)=>{let len=Math.min(x.length,y.length),collectionLength=0;for(let O of collection){if(collectionLength>=len)break;let o=O(x[collectionLength],y[collectionLength]);if(o!==0)return o;collectionLength++}return 0})};var tuple=(...elements)=>all(elements);var lessThan=(O)=>dual(2,(self,that)=>O(self,that)===-1),greaterThan=(O)=>dual(2,(self,that)=>O(self,that)===1);var min=(O)=>dual(2,(self,that)=>self===that||O(self,that)<1?self:that),max=(O)=>dual(2,(self,that)=>self===that||O(self,that)>-1?self:that),clamp=(O)=>dual(2,(self,options)=>min(O)(options.maximum,max(O)(options.minimum,self))),between=(O)=>dual(2,(self,options)=>!lessThan(O)(self,options.minimum)&&!greaterThan(O)(self,options.maximum));var none2=()=>none,some2=some;var isNone2=isNone,isSome2=isSome,match2=dual(2,(self,{onNone,onSome})=>isNone2(self)?onNone():onSome(self.value));var getOrElse=dual(2,(self,onNone)=>isNone2(self)?onNone():self.value),orElse=dual(2,(self,that)=>isNone2(self)?that():self),orElseSome=dual(2,(self,onNone)=>isNone2(self)?some2(onNone()):self);var fromNullable=(nullableValue)=>nullableValue==null?none2():some2(nullableValue);var getOrUndefined=getOrElse(constUndefined),liftThrowable=(f)=>(...a)=>{try{return some2(f(...a))}catch(e){return none2()}},getOrThrowWith2=dual(2,(self,onNone)=>{if(isSome2(self))return self.value;throw onNone()}),getOrThrow2=getOrThrowWith2(()=>new Error("getOrThrow called on a None")),map2=dual(2,(self,f)=>isNone2(self)?none2():some2(f(self.value)));var flatMap=dual(2,(self,f)=>isNone2(self)?none2():f(self.value));var flatMapNullable=dual(2,(self,f)=>isNone2(self)?none2():fromNullable(f(self.value)));var containsWith=(isEquivalent)=>dual(2,(self,a)=>isNone2(self)?!1:isEquivalent(self.value,a)),_equivalence=equivalence(),contains=containsWith(_equivalence),exists=dual(2,(self,refinement)=>isNone2(self)?!1:refinement(self.value));var mergeWith=(f)=>(o1,o2)=>{if(isNone2(o1))return o2;else if(isNone2(o2))return o1;return some2(f(o1.value,o2.value))};var make3=(...elements)=>elements;var unsafeHead=(self)=>{let result=self[Symbol.iterator]().next();if(result.done)throw new Error("unsafeHead: empty iterable");return result.value};var findFirst=dual(2,(self,f)=>{let i=0;for(let a of self){let o=f(a,i);if(isBoolean(o)){if(o)return some2(a)}else if(isSome2(o))return o;i++}return none2()});var constEmpty={[Symbol.iterator](){return constEmptyIterator}},constEmptyIterator={next(){return{done:!0,value:void 0}}},empty=()=>constEmpty;var allocate=(n)=>new Array(n),makeBy=dual(2,(n,f)=>{let max2=Math.max(1,Math.floor(n)),out=new Array(max2);for(let i=0;i<max2;i++)out[i]=f(i);return out});var fromIterable=(collection)=>Array.isArray(collection)?collection:Array.from(collection),ensure=(self)=>Array.isArray(self)?self:[self];var matchLeft=dual(2,(self,{onEmpty,onNonEmpty})=>isNonEmptyReadonlyArray(self)?onNonEmpty(headNonEmpty(self),tailNonEmpty(self)):onEmpty());var prepend=dual(2,(self,head)=>[head,...self]);var append=dual(2,(self,last)=>[...self,last]),appendAll=dual(2,(self,that)=>fromIterable(self).concat(fromIterable(that)));var isArray=Array.isArray,isEmptyArray=(self)=>self.length===0,isEmptyReadonlyArray=isEmptyArray,isNonEmptyArray2=isNonEmptyArray,isNonEmptyReadonlyArray=isNonEmptyArray;var isOutOfBounds=(i,as)=>i<0||i>=as.length,clamp2=(i,as)=>Math.floor(Math.min(Math.max(0,i),as.length)),get=dual(2,(self,index)=>{let i=Math.floor(index);return isOutOfBounds(i,self)?none2():some2(self[i])}),unsafeGet=dual(2,(self,index)=>{let i=Math.floor(index);if(isOutOfBounds(i,self))throw new Error(`Index ${i} out of bounds`);return self[i]});var head=get(0),headNonEmpty=unsafeGet(0),last=(self)=>isNonEmptyReadonlyArray(self)?some2(lastNonEmpty(self)):none2(),lastNonEmpty=(self)=>self[self.length-1];var tailNonEmpty=(self)=>self.slice(1);var spanIndex=(self,predicate)=>{let i=0;for(let a of self){if(!predicate(a,i))break;i++}return i},span=dual(2,(self,predicate)=>splitAt(self,spanIndex(self,predicate))),drop=dual(2,(self,n)=>{let input=fromIterable(self);return input.slice(clamp2(n,input),input.length)});var findFirst2=findFirst;var reverse=(self)=>Array.from(self).reverse(),sort=dual(2,(self,O)=>{let out=Array.from(self);return out.sort(O),out});var zip=dual(2,(self,that)=>zipWith(self,that,make3)),zipWith=dual(3,(self,that,f)=>{let as=fromIterable(self),bs=fromIterable(that);if(isNonEmptyReadonlyArray(as)&&isNonEmptyReadonlyArray(bs)){let out=[f(headNonEmpty(as),headNonEmpty(bs))],len=Math.min(as.length,bs.length);for(let i=1;i<len;i++)out[i]=f(as[i],bs[i]);return out}return[]});var _equivalence2=equivalence();var splitAt=dual(2,(self,n)=>{let input=Array.from(self),_n=Math.floor(n);if(isNonEmptyReadonlyArray(input)){if(_n>=1)return splitNonEmptyAt(input,_n);return[[],input]}return[input,[]]}),splitNonEmptyAt=dual(2,(self,n)=>{let _n=Math.max(1,Math.floor(n));return _n>=self.length?[copy(self),[]]:[prepend(self.slice(1,_n),headNonEmpty(self)),self.slice(_n)]});var copy=(self)=>self.slice();var unionWith=dual(3,(self,that,isEquivalent)=>{let a=fromIterable(self),b=fromIterable(that);if(isNonEmptyReadonlyArray(a)){if(isNonEmptyReadonlyArray(b))return dedupeWith(isEquivalent)(appendAll(a,b));return a}return b}),union=dual(2,(self,that)=>unionWith(self,that,_equivalence2));var empty2=()=>[],of=(a)=>[a],map3=dual(2,(self,f)=>self.map(f)),flatMap2=dual(2,(self,f)=>{if(isEmptyReadonlyArray(self))return[];let out=[];for(let i=0;i<self.length;i++){let inner=f(self[i],i);for(let j=0;j<inner.length;j++)out.push(inner[j])}return out}),flatten=flatMap2(identity),filterMap=dual(2,(self,f)=>{let as=fromIterable(self),out=[];for(let i=0;i<as.length;i++){let o=f(as[i],i);if(isSome2(o))out.push(o.value)}return out}),filterMapWhile=dual(2,(self,f)=>{let i=0,out=[];for(let a of self){let b=f(a,i);if(isSome2(b))out.push(b.value);else break;i++}return out}),partitionMap=dual(2,(self,f)=>{let left3=[],right3=[],as=fromIterable(self);for(let i=0;i<as.length;i++){let e=f(as[i],i);if(isLeft2(e))left3.push(e.left);else right3.push(e.right)}return[left3,right3]}),getSomes=filterMap(identity);var filter=dual(2,(self,predicate)=>{let as=fromIterable(self),out=[];for(let i=0;i<as.length;i++)if(predicate(as[i],i))out.push(as[i]);return out});var reduce=dual(3,(self,b,f)=>fromIterable(self).reduce((b2,a,i)=>f(b2,a,i),b)),reduceRight=dual(3,(self,b,f)=>fromIterable(self).reduceRight((b2,a,i)=>f(b2,a,i),b));var every=dual(2,(self,refinement)=>self.every(refinement));var unfold=(b,f)=>{let out=[],next=b,o;while(isSome2(o=f(next))){let[a,b2]=o.value;out.push(a),next=b2}return out};var getEquivalence=array;var dedupeWith=dual(2,(self,isEquivalent)=>{let input=fromIterable(self);if(isNonEmptyReadonlyArray(input)){let out=[headNonEmpty(input)],rest=tailNonEmpty(input);for(let r of rest)if(out.every((a)=>!isEquivalent(r,a)))out.push(r);return out}return[]}),dedupe=(self)=>dedupeWith(self,equivalence());var join=dual(2,(self,sep)=>fromIterable(self).join(sep)),mapAccum=dual(3,(self,s,f)=>{let i=0,s1=s,out=[];for(let a of self){let r=f(s1,a,i);s1=r[0],out.push(r[1]),i++}return[s1,out]});var getKeysForIndexSignature=(input,parameter)=>{switch(parameter._tag){case"StringKeyword":case"TemplateLiteral":return Object.keys(input);case"SymbolKeyword":return Object.getOwnPropertySymbols(input);case"Refinement":return getKeysForIndexSignature(input,parameter.from)}},ownKeys=(o)=>Object.keys(o).concat(Object.getOwnPropertySymbols(o)),memoizeThunk=(f)=>{let done=!1,a;return()=>{if(done)return a;return a=f(),done=!0,a}},formatDate=(date)=>{try{return date.toISOString()}catch(e){return String(date)}},formatUnknown=(u,checkCircular=!0)=>{if(Array.isArray(u))return`[${u.map((i)=>formatUnknown(i,checkCircular)).join(",")}]`;if(isDate(u))return formatDate(u);if(hasProperty(u,"toString")&&isFunction2(u.toString)&&u.toString!==Object.prototype.toString)return u.toString();if(isString(u))return JSON.stringify(u);if(isNumber(u)||u==null||isBoolean(u)||isSymbol(u))return String(u);if(isBigInt(u))return String(u)+"n";if(isIterable(u))return`${u.constructor.name}(${formatUnknown(Array.from(u),checkCircular)})`;try{if(checkCircular)JSON.stringify(u);let pojo=`{${ownKeys(u).map((k)=>`${isString(k)?JSON.stringify(k):String(k)}:${formatUnknown(u[k],!1)}`).join(",")}}`,name=u.constructor.name;return u.constructor!==Object.prototype.constructor?`${name}(${pojo})`:pojo}catch(e){return"<circular structure>"}},formatPropertyKey=(name)=>typeof name==="string"?JSON.stringify(name):String(name),isNonEmpty=(x)=>Array.isArray(x),isSingle=(x)=>!Array.isArray(x),formatPathKey=(key)=>`[${formatPropertyKey(key)}]`,formatPath=(path)=>isNonEmpty(path)?path.map(formatPathKey).join(""):formatPathKey(path);var getErrorMessage=(reason,details,path,ast)=>{let out=reason;if(path&&isNonEmptyReadonlyArray(path))out+=`
|
|
2
2
|
at path: ${formatPath(path)}`;if(details!==void 0)out+=`
|
|
3
3
|
details: ${details}`;if(ast)out+=`
|
|
4
4
|
schema (${ast._tag}): ${ast}`;return out};var getASTDuplicateIndexSignatureErrorMessage=(type)=>getErrorMessage("Duplicate index signature",`${type} index signature`),getASTIndexSignatureParameterErrorMessage=getErrorMessage("Unsupported index signature parameter","An index signature parameter type must be `string`, `symbol`, a template literal type or a refinement of the previous types"),getASTRequiredElementFollowinAnOptionalElementErrorMessage=getErrorMessage("Invalid element","A required element cannot follow an optional element. ts(1257)");var getASTDuplicatePropertySignatureErrorMessage=(key)=>getErrorMessage("Duplicate property signature",`Duplicate key ${formatUnknown(key)}`);var DateFromSelfSchemaId=Symbol.for("effect/SchemaId/DateFromSelf");var Order=number3;var nextPow2=(n)=>{let nextPow=Math.ceil(Math.log(n)/Math.log(2));return Math.max(Math.pow(2,nextPow),2)};var escape=(string2)=>string2.replace(/[/\\^$*+?.()|[\]{}]/g,"\\$&");var BrandAnnotationId=Symbol.for("effect/annotation/Brand"),SchemaIdAnnotationId=Symbol.for("effect/annotation/SchemaId"),MessageAnnotationId=Symbol.for("effect/annotation/Message"),MissingMessageAnnotationId=Symbol.for("effect/annotation/MissingMessage"),IdentifierAnnotationId=Symbol.for("effect/annotation/Identifier"),TitleAnnotationId=Symbol.for("effect/annotation/Title"),AutoTitleAnnotationId=Symbol.for("effect/annotation/AutoTitle"),DescriptionAnnotationId=Symbol.for("effect/annotation/Description"),ExamplesAnnotationId=Symbol.for("effect/annotation/Examples"),DefaultAnnotationId=Symbol.for("effect/annotation/Default"),JSONSchemaAnnotationId=Symbol.for("effect/annotation/JSONSchema"),ArbitraryAnnotationId=Symbol.for("effect/annotation/Arbitrary"),PrettyAnnotationId=Symbol.for("effect/annotation/Pretty"),EquivalenceAnnotationId=Symbol.for("effect/annotation/Equivalence"),DocumentationAnnotationId=Symbol.for("effect/annotation/Documentation"),ConcurrencyAnnotationId=Symbol.for("effect/annotation/Concurrency"),BatchingAnnotationId=Symbol.for("effect/annotation/Batching"),ParseIssueTitleAnnotationId=Symbol.for("effect/annotation/ParseIssueTitle"),ParseOptionsAnnotationId=Symbol.for("effect/annotation/ParseOptions"),DecodingFallbackAnnotationId=Symbol.for("effect/annotation/DecodingFallback"),SurrogateAnnotationId=Symbol.for("effect/annotation/Surrogate"),StableFilterAnnotationId=Symbol.for("effect/annotation/StableFilter"),getAnnotation=dual(2,(annotated,key)=>Object.prototype.hasOwnProperty.call(annotated.annotations,key)?some2(annotated.annotations[key]):none2()),getBrandAnnotation=getAnnotation(BrandAnnotationId);var getMessageAnnotation=getAnnotation(MessageAnnotationId),getMissingMessageAnnotation=getAnnotation(MissingMessageAnnotationId),getTitleAnnotation=getAnnotation(TitleAnnotationId),getAutoTitleAnnotation=getAnnotation(AutoTitleAnnotationId),getIdentifierAnnotation=getAnnotation(IdentifierAnnotationId),getDescriptionAnnotation=getAnnotation(DescriptionAnnotationId);var getConcurrencyAnnotation=getAnnotation(ConcurrencyAnnotationId),getBatchingAnnotation=getAnnotation(BatchingAnnotationId),getParseIssueTitleAnnotation=getAnnotation(ParseIssueTitleAnnotationId),getParseOptionsAnnotation=getAnnotation(ParseOptionsAnnotationId),getDecodingFallbackAnnotation=getAnnotation(DecodingFallbackAnnotationId),getSurrogateAnnotation=getAnnotation(SurrogateAnnotationId),getStableFilterAnnotation=getAnnotation(StableFilterAnnotationId),hasStableFilter=(annotated)=>exists(getStableFilterAnnotation(annotated),(b)=>b===!0),JSONIdentifierAnnotationId=Symbol.for("effect/annotation/JSONIdentifier"),getJSONIdentifierAnnotation=getAnnotation(JSONIdentifierAnnotationId),getJSONIdentifier=(annotated)=>orElse(getJSONIdentifierAnnotation(annotated),()=>getIdentifierAnnotation(annotated));class Declaration{typeParameters;decodeUnknown;encodeUnknown;annotations;_tag="Declaration";constructor(typeParameters,decodeUnknown,encodeUnknown,annotations={}){this.typeParameters=typeParameters,this.decodeUnknown=decodeUnknown,this.encodeUnknown=encodeUnknown,this.annotations=annotations}toString(){return getOrElse(getExpected(this),()=>"<declaration schema>")}toJSON(){return{_tag:this._tag,typeParameters:this.typeParameters.map((ast)=>ast.toJSON()),annotations:toJSONAnnotations(this.annotations)}}}var createASTGuard=(tag)=>(ast)=>ast._tag===tag;class Literal{literal;annotations;_tag="Literal";constructor(literal,annotations={}){this.literal=literal,this.annotations=annotations}toString(){return getOrElse(getExpected(this),()=>formatUnknown(this.literal))}toJSON(){return{_tag:this._tag,literal:isBigInt(this.literal)?String(this.literal):this.literal,annotations:toJSONAnnotations(this.annotations)}}}var isLiteral=createASTGuard("Literal");class UniqueSymbol{symbol;annotations;_tag="UniqueSymbol";constructor(symbol3,annotations={}){this.symbol=symbol3,this.annotations=annotations}toString(){return getOrElse(getExpected(this),()=>formatUnknown(this.symbol))}toJSON(){return{_tag:this._tag,symbol:String(this.symbol),annotations:toJSONAnnotations(this.annotations)}}}class UndefinedKeyword{annotations;_tag="UndefinedKeyword";constructor(annotations={}){this.annotations=annotations}toString(){return formatKeyword(this)}toJSON(){return{_tag:this._tag,annotations:toJSONAnnotations(this.annotations)}}}var undefinedKeyword=new UndefinedKeyword({[TitleAnnotationId]:"undefined"});class VoidKeyword{annotations;_tag="VoidKeyword";constructor(annotations={}){this.annotations=annotations}toString(){return formatKeyword(this)}toJSON(){return{_tag:this._tag,annotations:toJSONAnnotations(this.annotations)}}}var voidKeyword=new VoidKeyword({[TitleAnnotationId]:"void"});class NeverKeyword{annotations;_tag="NeverKeyword";constructor(annotations={}){this.annotations=annotations}toString(){return formatKeyword(this)}toJSON(){return{_tag:this._tag,annotations:toJSONAnnotations(this.annotations)}}}var neverKeyword=new NeverKeyword({[TitleAnnotationId]:"never"});class UnknownKeyword{annotations;_tag="UnknownKeyword";constructor(annotations={}){this.annotations=annotations}toString(){return formatKeyword(this)}toJSON(){return{_tag:this._tag,annotations:toJSONAnnotations(this.annotations)}}}var unknownKeyword=new UnknownKeyword({[TitleAnnotationId]:"unknown"});class AnyKeyword{annotations;_tag="AnyKeyword";constructor(annotations={}){this.annotations=annotations}toString(){return formatKeyword(this)}toJSON(){return{_tag:this._tag,annotations:toJSONAnnotations(this.annotations)}}}var anyKeyword=new AnyKeyword({[TitleAnnotationId]:"any"});class StringKeyword{annotations;_tag="StringKeyword";constructor(annotations={}){this.annotations=annotations}toString(){return formatKeyword(this)}toJSON(){return{_tag:this._tag,annotations:toJSONAnnotations(this.annotations)}}}var stringKeyword=new StringKeyword({[TitleAnnotationId]:"string",[DescriptionAnnotationId]:"a string"}),isStringKeyword=createASTGuard("StringKeyword");class NumberKeyword{annotations;_tag="NumberKeyword";constructor(annotations={}){this.annotations=annotations}toString(){return formatKeyword(this)}toJSON(){return{_tag:this._tag,annotations:toJSONAnnotations(this.annotations)}}}var numberKeyword=new NumberKeyword({[TitleAnnotationId]:"number",[DescriptionAnnotationId]:"a number"});class BooleanKeyword{annotations;_tag="BooleanKeyword";constructor(annotations={}){this.annotations=annotations}toString(){return formatKeyword(this)}toJSON(){return{_tag:this._tag,annotations:toJSONAnnotations(this.annotations)}}}var booleanKeyword=new BooleanKeyword({[TitleAnnotationId]:"boolean",[DescriptionAnnotationId]:"a boolean"});class BigIntKeyword{annotations;_tag="BigIntKeyword";constructor(annotations={}){this.annotations=annotations}toString(){return formatKeyword(this)}toJSON(){return{_tag:this._tag,annotations:toJSONAnnotations(this.annotations)}}}var bigIntKeyword=new BigIntKeyword({[TitleAnnotationId]:"bigint",[DescriptionAnnotationId]:"a bigint"});class SymbolKeyword{annotations;_tag="SymbolKeyword";constructor(annotations={}){this.annotations=annotations}toString(){return formatKeyword(this)}toJSON(){return{_tag:this._tag,annotations:toJSONAnnotations(this.annotations)}}}var symbolKeyword=new SymbolKeyword({[TitleAnnotationId]:"symbol",[DescriptionAnnotationId]:"a symbol"}),isSymbolKeyword=createASTGuard("SymbolKeyword");class ObjectKeyword{annotations;_tag="ObjectKeyword";constructor(annotations={}){this.annotations=annotations}toString(){return formatKeyword(this)}toJSON(){return{_tag:this._tag,annotations:toJSONAnnotations(this.annotations)}}}var objectKeyword=new ObjectKeyword({[TitleAnnotationId]:"object",[DescriptionAnnotationId]:"an object in the TypeScript meaning, i.e. the `object` type"});class Type{type;annotations;constructor(type,annotations={}){this.type=type,this.annotations=annotations}toJSON(){return{type:this.type.toJSON(),annotations:toJSONAnnotations(this.annotations)}}toString(){return String(this.type)}}class OptionalType extends Type{isOptional;constructor(type,isOptional,annotations={}){super(type,annotations);this.isOptional=isOptional}toJSON(){return{type:this.type.toJSON(),isOptional:this.isOptional,annotations:toJSONAnnotations(this.annotations)}}toString(){return String(this.type)+(this.isOptional?"?":"")}}var getRestASTs=(rest)=>rest.map((annotatedAST)=>annotatedAST.type);class TupleType{elements;rest;isReadonly;annotations;_tag="TupleType";constructor(elements,rest,isReadonly,annotations={}){this.elements=elements,this.rest=rest,this.isReadonly=isReadonly,this.annotations=annotations;let hasOptionalElement=!1,hasIllegalRequiredElement=!1;for(let e of elements)if(e.isOptional)hasOptionalElement=!0;else if(hasOptionalElement){hasIllegalRequiredElement=!0;break}if(hasIllegalRequiredElement||hasOptionalElement&&rest.length>1)throw new Error(getASTRequiredElementFollowinAnOptionalElementErrorMessage)}toString(){return getOrElse(getExpected(this),()=>formatTuple(this))}toJSON(){return{_tag:this._tag,elements:this.elements.map((e)=>e.toJSON()),rest:this.rest.map((ast)=>ast.toJSON()),isReadonly:this.isReadonly,annotations:toJSONAnnotations(this.annotations)}}}var formatTuple=(ast)=>{let formattedElements=ast.elements.map(String).join(", ");return matchLeft(ast.rest,{onEmpty:()=>`readonly [${formattedElements}]`,onNonEmpty:(head2,tail)=>{let formattedHead=String(head2),wrappedHead=formattedHead.includes(" | ")?`(${formattedHead})`:formattedHead;if(tail.length>0){let formattedTail=tail.map(String).join(", ");if(ast.elements.length>0)return`readonly [${formattedElements}, ...${wrappedHead}[], ${formattedTail}]`;else return`readonly [...${wrappedHead}[], ${formattedTail}]`}else if(ast.elements.length>0)return`readonly [${formattedElements}, ...${wrappedHead}[]]`;else return`ReadonlyArray<${formattedHead}>`}})};class PropertySignature extends OptionalType{name;isReadonly;constructor(name,type,isOptional,isReadonly,annotations){super(type,isOptional,annotations);this.name=name,this.isReadonly=isReadonly}toString(){return(this.isReadonly?"readonly ":"")+String(this.name)+(this.isOptional?"?":"")+": "+this.type}toJSON(){return{name:String(this.name),type:this.type.toJSON(),isOptional:this.isOptional,isReadonly:this.isReadonly,annotations:toJSONAnnotations(this.annotations)}}}var isParameter=(ast)=>{switch(ast._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return!0;case"Refinement":return isParameter(ast.from)}return!1};class IndexSignature{type;isReadonly;parameter;constructor(parameter,type,isReadonly){if(this.type=type,this.isReadonly=isReadonly,isParameter(parameter))this.parameter=parameter;else throw new Error(getASTIndexSignatureParameterErrorMessage)}toString(){return(this.isReadonly?"readonly ":"")+`[x: ${this.parameter}]: ${this.type}`}toJSON(){return{parameter:this.parameter.toJSON(),type:this.type.toJSON(),isReadonly:this.isReadonly}}}class TypeLiteral{annotations;_tag="TypeLiteral";propertySignatures;indexSignatures;constructor(propertySignatures,indexSignatures,annotations={}){this.annotations=annotations;let keys={};for(let i=0;i<propertySignatures.length;i++){let name=propertySignatures[i].name;if(Object.prototype.hasOwnProperty.call(keys,name))throw new Error(getASTDuplicatePropertySignatureErrorMessage(name));keys[name]=null}let parameters={string:!1,symbol:!1};for(let i=0;i<indexSignatures.length;i++){let encodedParameter=getEncodedParameter(indexSignatures[i].parameter);if(isStringKeyword(encodedParameter)){if(parameters.string)throw new Error(getASTDuplicateIndexSignatureErrorMessage("string"));parameters.string=!0}else if(isSymbolKeyword(encodedParameter)){if(parameters.symbol)throw new Error(getASTDuplicateIndexSignatureErrorMessage("symbol"));parameters.symbol=!0}}this.propertySignatures=propertySignatures,this.indexSignatures=indexSignatures}toString(){return getOrElse(getExpected(this),()=>formatTypeLiteral(this))}toJSON(){return{_tag:this._tag,propertySignatures:this.propertySignatures.map((ps)=>ps.toJSON()),indexSignatures:this.indexSignatures.map((ps)=>ps.toJSON()),annotations:toJSONAnnotations(this.annotations)}}}var formatIndexSignatures=(iss)=>iss.map(String).join("; "),formatTypeLiteral=(ast)=>{if(ast.propertySignatures.length>0){let pss=ast.propertySignatures.map(String).join("; ");if(ast.indexSignatures.length>0)return`{ ${pss}; ${formatIndexSignatures(ast.indexSignatures)} }`;else return`{ ${pss} }`}else if(ast.indexSignatures.length>0)return`{ ${formatIndexSignatures(ast.indexSignatures)} }`;else return"{}"};var sortCandidates=sort(mapInput2(Order,(ast)=>{switch(ast._tag){case"AnyKeyword":return 0;case"UnknownKeyword":return 1;case"ObjectKeyword":return 2;case"StringKeyword":case"NumberKeyword":case"BooleanKeyword":case"BigIntKeyword":case"SymbolKeyword":return 3}return 4})),literalMap={string:"StringKeyword",number:"NumberKeyword",boolean:"BooleanKeyword",bigint:"BigIntKeyword"},flatten2=(candidates)=>flatMap2(candidates,(ast)=>isUnion(ast)?flatten2(ast.types):[ast]),unify=(candidates)=>{let cs=sortCandidates(candidates),out=[],uniques={},literals=[];for(let ast of cs)switch(ast._tag){case"NeverKeyword":break;case"AnyKeyword":return[anyKeyword];case"UnknownKeyword":return[unknownKeyword];case"ObjectKeyword":case"UndefinedKeyword":case"VoidKeyword":case"StringKeyword":case"NumberKeyword":case"BooleanKeyword":case"BigIntKeyword":case"SymbolKeyword":{if(!uniques[ast._tag])uniques[ast._tag]=ast,out.push(ast);break}case"Literal":{let type=typeof ast.literal;switch(type){case"string":case"number":case"bigint":case"boolean":{let _tag=literalMap[type];if(!uniques[_tag]&&!literals.includes(ast.literal))literals.push(ast.literal),out.push(ast);break}case"object":{if(!literals.includes(ast.literal))literals.push(ast.literal),out.push(ast);break}}break}case"UniqueSymbol":{if(!uniques.SymbolKeyword&&!literals.includes(ast.symbol))literals.push(ast.symbol),out.push(ast);break}case"TupleType":{if(!uniques.ObjectKeyword)out.push(ast);break}case"TypeLiteral":{if(ast.propertySignatures.length===0&&ast.indexSignatures.length===0){if(!uniques["{}"])uniques["{}"]=ast,out.push(ast)}else if(!uniques.ObjectKeyword)out.push(ast);break}default:out.push(ast)}return out};class Union{types;annotations;static make=(types,annotations)=>{return isMembers(types)?new Union(types,annotations):types.length===1?types[0]:neverKeyword};static unify=(candidates,annotations)=>{return Union.make(unify(flatten2(candidates)),annotations)};_tag="Union";constructor(types,annotations={}){this.types=types,this.annotations=annotations}toString(){return getOrElse(getExpected(this),()=>this.types.map(String).join(" | "))}toJSON(){return{_tag:this._tag,types:this.types.map((ast)=>ast.toJSON()),annotations:toJSONAnnotations(this.annotations)}}}var isMembers=(as)=>as.length>1,isUnion=createASTGuard("Union"),toJSONMemoMap=globalValue(Symbol.for("effect/Schema/AST/toJSONMemoMap"),()=>new WeakMap);class Suspend{f;annotations;_tag="Suspend";constructor(f,annotations={}){this.f=f,this.annotations=annotations,this.f=memoizeThunk(f)}toString(){return getExpected(this).pipe(orElse(()=>flatMap(liftThrowable(this.f)(),(ast)=>getExpected(ast))),getOrElse(()=>"<suspended schema>"))}toJSON(){let ast=this.f(),out=toJSONMemoMap.get(ast);if(out)return out;return toJSONMemoMap.set(ast,{_tag:this._tag}),out={_tag:this._tag,ast:ast.toJSON(),annotations:toJSONAnnotations(this.annotations)},toJSONMemoMap.set(ast,out),out}}class Refinement{from;filter;annotations;_tag="Refinement";constructor(from,filter2,annotations={}){this.from=from,this.filter=filter2,this.annotations=annotations}toString(){return getIdentifierAnnotation(this).pipe(getOrElse(()=>match2(getOrElseExpected(this),{onNone:()=>`{ ${this.from} | filter }`,onSome:(expected)=>isRefinement(this.from)?String(this.from)+" & "+expected:expected})))}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),annotations:toJSONAnnotations(this.annotations)}}}var isRefinement=createASTGuard("Refinement"),defaultParseOption={};var annotations=(ast,overrides)=>{let d=Object.getOwnPropertyDescriptors(ast),value={...ast.annotations,...overrides},surrogate=getSurrogateAnnotation(ast);if(isSome2(surrogate))value[SurrogateAnnotationId]=annotations(surrogate.value,overrides);return d.annotations.value=value,Object.create(Object.getPrototypeOf(ast),d)};var STRING_KEYWORD_PATTERN="[\\s\\S]*",NUMBER_KEYWORD_PATTERN="[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?",getTemplateLiteralSpanTypePattern=(type,capture)=>{switch(type._tag){case"Literal":return escape(String(type.literal));case"StringKeyword":return STRING_KEYWORD_PATTERN;case"NumberKeyword":return NUMBER_KEYWORD_PATTERN;case"TemplateLiteral":return getTemplateLiteralPattern(type,capture,!1);case"Union":return type.types.map((type2)=>getTemplateLiteralSpanTypePattern(type2,capture)).join("|")}},handleTemplateLiteralSpanTypeParens=(type,s,capture,top)=>{if(isUnion(type)){if(capture&&!top)return`(?:${s})`}else if(!capture||!top)return s;return`(${s})`},getTemplateLiteralPattern=(ast,capture,top)=>{let pattern="";if(ast.head!==""){let head2=escape(ast.head);pattern+=capture&&top?`(${head2})`:head2}for(let span2 of ast.spans){let spanPattern=getTemplateLiteralSpanTypePattern(span2.type,capture);if(pattern+=handleTemplateLiteralSpanTypeParens(span2.type,spanPattern,capture,top),span2.literal!==""){let literal=escape(span2.literal);pattern+=capture&&top?`(${literal})`:literal}}return pattern},getTemplateLiteralRegExp=(ast)=>new RegExp(`^${getTemplateLiteralPattern(ast,!1,!0)}$`);var pickAnnotations=(annotationIds)=>(annotated)=>{let out=void 0;for(let id of annotationIds)if(Object.prototype.hasOwnProperty.call(annotated.annotations,id)){if(out===void 0)out={};out[id]=annotated.annotations[id]}return out};var preserveTransformationAnnotations=pickAnnotations([ExamplesAnnotationId,DefaultAnnotationId,JSONSchemaAnnotationId,ArbitraryAnnotationId,PrettyAnnotationId,EquivalenceAnnotationId]),typeAST=(ast)=>{switch(ast._tag){case"Declaration":{let typeParameters=changeMap(ast.typeParameters,typeAST);return typeParameters===ast.typeParameters?ast:new Declaration(typeParameters,ast.decodeUnknown,ast.encodeUnknown,ast.annotations)}case"TupleType":{let elements=changeMap(ast.elements,(e)=>{let type=typeAST(e.type);return type===e.type?e:new OptionalType(type,e.isOptional)}),restASTs=getRestASTs(ast.rest),rest=changeMap(restASTs,typeAST);return elements===ast.elements&&rest===restASTs?ast:new TupleType(elements,rest.map((type)=>new Type(type)),ast.isReadonly,ast.annotations)}case"TypeLiteral":{let propertySignatures=changeMap(ast.propertySignatures,(p)=>{let type=typeAST(p.type);return type===p.type?p:new PropertySignature(p.name,type,p.isOptional,p.isReadonly)}),indexSignatures=changeMap(ast.indexSignatures,(is)=>{let type=typeAST(is.type);return type===is.type?is:new IndexSignature(is.parameter,type,is.isReadonly)});return propertySignatures===ast.propertySignatures&&indexSignatures===ast.indexSignatures?ast:new TypeLiteral(propertySignatures,indexSignatures,ast.annotations)}case"Union":{let types=changeMap(ast.types,typeAST);return types===ast.types?ast:Union.make(types,ast.annotations)}case"Suspend":return new Suspend(()=>typeAST(ast.f()),ast.annotations);case"Refinement":{let from=typeAST(ast.from);return from===ast.from?ast:new Refinement(from,ast.filter,ast.annotations)}case"Transformation":{let preserve=preserveTransformationAnnotations(ast);return typeAST(preserve!==void 0?annotations(ast.to,preserve):ast.to)}}return ast},createJSONIdentifierAnnotation=(annotated)=>match2(getJSONIdentifier(annotated),{onNone:()=>{return},onSome:(identifier)=>({[JSONIdentifierAnnotationId]:identifier})});function changeMap(as,f){let changed=!1,out=allocate(as.length);for(let i=0;i<as.length;i++){let a=as[i],fa=f(a);if(fa!==a)changed=!0;out[i]=fa}return changed?out:as}var getTransformationFrom=(ast)=>{switch(ast._tag){case"Transformation":return ast.from;case"Refinement":return getTransformationFrom(ast.from);case"Suspend":return getTransformationFrom(ast.f())}},encodedAST_=(ast,isBound)=>{switch(ast._tag){case"Declaration":{let typeParameters=changeMap(ast.typeParameters,(ast2)=>encodedAST_(ast2,isBound));return typeParameters===ast.typeParameters?ast:new Declaration(typeParameters,ast.decodeUnknown,ast.encodeUnknown,ast.annotations)}case"TupleType":{let elements=changeMap(ast.elements,(e)=>{let type=encodedAST_(e.type,isBound);return type===e.type?e:new OptionalType(type,e.isOptional)}),restASTs=getRestASTs(ast.rest),rest=changeMap(restASTs,(ast2)=>encodedAST_(ast2,isBound));return elements===ast.elements&&rest===restASTs?ast:new TupleType(elements,rest.map((ast2)=>new Type(ast2)),ast.isReadonly,createJSONIdentifierAnnotation(ast))}case"TypeLiteral":{let propertySignatures=changeMap(ast.propertySignatures,(ps)=>{let type=encodedAST_(ps.type,isBound);return type===ps.type?ps:new PropertySignature(ps.name,type,ps.isOptional,ps.isReadonly)}),indexSignatures=changeMap(ast.indexSignatures,(is)=>{let type=encodedAST_(is.type,isBound);return type===is.type?is:new IndexSignature(is.parameter,type,is.isReadonly)});return propertySignatures===ast.propertySignatures&&indexSignatures===ast.indexSignatures?ast:new TypeLiteral(propertySignatures,indexSignatures,createJSONIdentifierAnnotation(ast))}case"Union":{let types=changeMap(ast.types,(ast2)=>encodedAST_(ast2,isBound));return types===ast.types?ast:Union.make(types,createJSONIdentifierAnnotation(ast))}case"Suspend":return new Suspend(()=>encodedAST_(ast.f(),isBound),createJSONIdentifierAnnotation(ast));case"Refinement":{let from=encodedAST_(ast.from,isBound);if(isBound){if(from===ast.from)return ast;if(getTransformationFrom(ast.from)===void 0&&hasStableFilter(ast))return new Refinement(from,ast.filter,ast.annotations)}let identifier=createJSONIdentifierAnnotation(ast);return identifier?annotations(from,identifier):from}case"Transformation":{let identifier=createJSONIdentifierAnnotation(ast);return encodedAST_(identifier?annotations(ast.from,identifier):ast.from,isBound)}}return ast},encodedAST=(ast)=>encodedAST_(ast,!1);var toJSONAnnotations=(annotations2)=>{let out={};for(let k of Object.getOwnPropertySymbols(annotations2))out[String(k)]=annotations2[k];return out},getEncodedParameter=(ast)=>{switch(ast._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return ast;case"Refinement":return getEncodedParameter(ast.from)}};var formatKeyword=(ast)=>getOrElse(getExpected(ast),()=>ast._tag);function getBrands(ast){return match2(getBrandAnnotation(ast),{onNone:()=>"",onSome:(brands)=>brands.map((brand)=>` & Brand<${formatUnknown(brand)}>`).join("")})}var getOrElseExpected=(ast)=>getTitleAnnotation(ast).pipe(orElse(()=>getDescriptionAnnotation(ast)),orElse(()=>getAutoTitleAnnotation(ast)),map2((s)=>s+getBrands(ast))),getExpected=(ast)=>orElse(getIdentifierAnnotation(ast),()=>getOrElseExpected(ast));var TypeId3=Symbol.for("effect/BigDecimal"),BigDecimalProto={[TypeId3]:TypeId3,[symbol](){let normalized=normalize(this);return pipe(hash(normalized.value),combine(number2(normalized.scale)),cached(this))},[symbol2](that){return isBigDecimal(that)&&equals2(this,that)},toString(){return`BigDecimal(${format2(this)})`},toJSON(){return{_id:"BigDecimal",value:String(this.value),scale:this.scale}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}},isBigDecimal=(u)=>hasProperty(u,TypeId3),make4=(value,scale)=>{let o=Object.create(BigDecimalProto);return o.value=value,o.scale=scale,o},unsafeMakeNormalized=(value,scale)=>{if(value!==bigint0&&value%bigint10===bigint0)throw new RangeError("Value must be normalized");let o=make4(value,scale);return o.normalized=o,o},bigint0=BigInt(0);var bigint10=BigInt(10),zero=unsafeMakeNormalized(bigint0,0),normalize=(self)=>{if(self.normalized===void 0)if(self.value===bigint0)self.normalized=zero;else{let digits=`${self.value}`,trail=0;for(let i=digits.length-1;i>=0;i--)if(digits[i]==="0")trail++;else break;if(trail===0)self.normalized=self;let value=BigInt(digits.substring(0,digits.length-trail)),scale=self.scale-trail;self.normalized=unsafeMakeNormalized(value,scale)}return self.normalized},scale=dual(2,(self,scale2)=>{if(scale2>self.scale)return make4(self.value*bigint10**BigInt(scale2-self.scale),scale2);if(scale2<self.scale)return make4(self.value/bigint10**BigInt(self.scale-scale2),scale2);return self});var abs=(n)=>n.value<bigint0?make4(-n.value,n.scale):n;var Equivalence=make((self,that)=>{if(self.scale>that.scale)return scale(that,self.scale).value===self.value;if(self.scale<that.scale)return scale(self,that.scale).value===that.value;return self.value===that.value}),equals2=dual(2,(self,that)=>Equivalence(self,that));var format2=(n)=>{let normalized=normalize(n);if(Math.abs(normalized.scale)>=16)return toExponential(normalized);let negative=normalized.value<bigint0,absolute=negative?`${normalized.value}`.substring(1):`${normalized.value}`,before,after;if(normalized.scale>=absolute.length)before="0",after="0".repeat(normalized.scale-absolute.length)+absolute;else{let location=absolute.length-normalized.scale;if(location>absolute.length){let zeros=location-absolute.length;before=`${absolute}${"0".repeat(zeros)}`,after=""}else after=absolute.slice(location),before=absolute.slice(0,location)}let complete=after===""?before:`${before}.${after}`;return negative?`-${complete}`:complete},toExponential=(n)=>{if(isZero(n))return"0e+0";let normalized=normalize(n),digits=`${abs(normalized).value}`,head2=digits.slice(0,1),tail=digits.slice(1),output=`${isNegative(normalized)?"-":""}${head2}`;if(tail!=="")output+=`.${tail}`;let exp=tail.length-normalized.scale;return`${output}e${exp>=0?"+":""}${exp}`};var isZero=(n)=>n.value===bigint0,isNegative=(n)=>n.value<bigint0;var not=(self)=>!self;var TagTypeId=Symbol.for("effect/Context/Tag"),ReferenceTypeId=Symbol.for("effect/Context/Reference"),STMSymbolKey="effect/STM",STMTypeId=Symbol.for(STMSymbolKey),TagProto={...EffectPrototype,_op:"Tag",[STMTypeId]:effectVariance,[TagTypeId]:{_Service:(_)=>_,_Identifier:(_)=>_},toString(){return format(this.toJSON())},toJSON(){return{_id:"Tag",key:this.key,stack:this.stack}},[NodeInspectSymbol](){return this.toJSON()},of(self){return self},context(self){return make5(this,self)}},ReferenceProto={...TagProto,[ReferenceTypeId]:ReferenceTypeId},makeGenericTag=(key)=>{let limit=Error.stackTraceLimit;Error.stackTraceLimit=2;let creationError=new Error;Error.stackTraceLimit=limit;let tag=Object.create(TagProto);return Object.defineProperty(tag,"stack",{get(){return creationError.stack}}),tag.key=key,tag};var Reference=()=>(id,options)=>{let limit=Error.stackTraceLimit;Error.stackTraceLimit=2;let creationError=new Error;Error.stackTraceLimit=limit;function ReferenceClass(){}return Object.setPrototypeOf(ReferenceClass,ReferenceProto),ReferenceClass.key=id,ReferenceClass.defaultValue=options.defaultValue,Object.defineProperty(ReferenceClass,"stack",{get(){return creationError.stack}}),ReferenceClass},TypeId4=Symbol.for("effect/Context"),ContextProto={[TypeId4]:{_Services:(_)=>_},[symbol2](that){if(isContext(that)){if(this.unsafeMap.size===that.unsafeMap.size){for(let k of this.unsafeMap.keys())if(!that.unsafeMap.has(k)||!equals(this.unsafeMap.get(k),that.unsafeMap.get(k)))return!1;return!0}}return!1},[symbol](){return cached(this,number2(this.unsafeMap.size))},pipe(){return pipeArguments(this,arguments)},toString(){return format(this.toJSON())},toJSON(){return{_id:"Context",services:Array.from(this.unsafeMap).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()}},makeContext=(unsafeMap)=>{let context=Object.create(ContextProto);return context.unsafeMap=unsafeMap,context},serviceNotFoundError=(tag)=>{let error=new Error(`Service not found${tag.key?`: ${String(tag.key)}`:""}`);if(tag.stack){let lines=tag.stack.split(`
|
|
@@ -28,10 +28,10 @@ ${this.stack.split(`
|
|
|
28
28
|
`)}`;super(message);this._tag=_tag,this.traces=traces,this[MicroCauseTypeId]=microCauseVariance,this.name=name,this.stack=stack}pipe(){return pipeArguments(this,arguments)}toString(){return this.stack}[NodeInspectSymbol](){return this.stack}}class Die extends MicroCauseImpl{defect;constructor(defect,traces=[]){super("Die",defect,traces);this.defect=defect}}var causeDie=(defect,traces=[])=>new Die(defect,traces);class Interrupt extends MicroCauseImpl{constructor(traces=[]){super("Interrupt","interrupted",traces)}}var causeInterrupt=(traces=[])=>new Interrupt(traces);var causeIsInterrupt=(self)=>self._tag==="Interrupt";var MicroFiberTypeId=Symbol.for("effect/Micro/MicroFiber"),fiberVariance={_A:identity,_E:identity};class MicroFiberImpl{context;interruptible;[MicroFiberTypeId];_stack=[];_observers=[];_exit;_children;currentOpCount=0;constructor(context2,interruptible3=!0){this.context=context2,this.interruptible=interruptible3,this[MicroFiberTypeId]=fiberVariance}getRef(ref){return unsafeGetReference(this.context,ref)}addObserver(cb){if(this._exit)return cb(this._exit),constVoid;return this._observers.push(cb),()=>{let index=this._observers.indexOf(cb);if(index>=0)this._observers.splice(index,1)}}_interrupted=!1;unsafeInterrupt(){if(this._exit)return;if(this._interrupted=!0,this.interruptible)this.evaluate(exitInterrupt2)}unsafePoll(){return this._exit}evaluate(effect){if(this._exit)return;else if(this._yielded!==void 0){let yielded=this._yielded;this._yielded=void 0,yielded()}let exit2=this.runLoop(effect);if(exit2===Yield)return;let interruptChildren=fiberMiddleware.interruptChildren&&fiberMiddleware.interruptChildren(this);if(interruptChildren!==void 0)return this.evaluate(flatMap9(interruptChildren,()=>exit2));this._exit=exit2;for(let i=0;i<this._observers.length;i++)this._observers[i](exit2);this._observers.length=0}runLoop(effect){let yielding=!1,current=effect;this.currentOpCount=0;try{while(!0){if(this.currentOpCount++,!yielding&&this.getRef(CurrentScheduler).shouldYield(this)){yielding=!0;let prev=current;current=flatMap9(yieldNow2,()=>prev)}if(current=current[evaluate](this),current===Yield){let yielded=this._yielded;if(MicroExitTypeId in yielded)return this._yielded=void 0,yielded;return Yield}}}catch(error){if(!hasProperty(current,evaluate))return exitDie2(`MicroFiber.runLoop: Not a valid effect: ${String(current)}`);return exitDie2(error)}}getCont(symbol3){while(!0){let op=this._stack.pop();if(!op)return;let cont=op[ensureCont]&&op[ensureCont](this);if(cont)return{[symbol3]:cont};if(op[symbol3])return op}}_yielded=void 0;yieldWith(value){return this._yielded=value,Yield}children(){return this._children??=new Set}}var fiberMiddleware=globalValue("effect/Micro/fiberMiddleware",()=>({interruptChildren:void 0}));var identifier=Symbol.for("effect/Micro/identifier"),args=Symbol.for("effect/Micro/args"),evaluate=Symbol.for("effect/Micro/evaluate"),successCont=Symbol.for("effect/Micro/successCont"),failureCont=Symbol.for("effect/Micro/failureCont"),ensureCont=Symbol.for("effect/Micro/ensureCont"),Yield=Symbol.for("effect/Micro/Yield"),microVariance={_A:identity,_E:identity,_R:identity},MicroProto={...EffectPrototype2,_op:"Micro",[TypeId14]:microVariance,pipe(){return pipeArguments(this,arguments)},[Symbol.iterator](){return new SingleShotGen(new YieldWrap(this))},toJSON(){return{_id:"Micro",op:this[identifier],...args in this?{args:this[args]}:void 0}},toString(){return format(this)},[NodeInspectSymbol](){return format(this)}};function defaultEvaluate(_fiber){return exitDie2("Micro.evaluate: Not implemented")}var makePrimitiveProto=(options)=>({...MicroProto,[identifier]:options.op,[evaluate]:options.eval??defaultEvaluate,[successCont]:options.contA,[failureCont]:options.contE,[ensureCont]:options.ensure}),makePrimitive=(options)=>{let Proto2=makePrimitiveProto(options);return function(){let self=Object.create(Proto2);return self[args]=options.single===!1?arguments:arguments[0],self}},makeExit=(options)=>{let Proto2={...makePrimitiveProto(options),[MicroExitTypeId]:MicroExitTypeId,_tag:options.op,get[options.prop](){return this[args]},toJSON(){return{_id:"MicroExit",_tag:options.op,[options.prop]:this[args]}},[symbol2](that){return isMicroExit(that)&&that._tag===options.op&&equals(this[args],that[args])},[symbol](){return cached(this,combine(string(options.op))(hash(this[args])))}};return function(value){let self=Object.create(Proto2);return self[args]=value,self[successCont]=void 0,self[failureCont]=void 0,self[ensureCont]=void 0,self}},succeed4=makeExit({op:"Success",prop:"value",eval(fiber){let cont=fiber.getCont(successCont);return cont?cont[successCont](this[args],fiber):fiber.yieldWith(this)}}),failCause4=makeExit({op:"Failure",prop:"cause",eval(fiber){let cont=fiber.getCont(failureCont);while(causeIsInterrupt(this[args])&&cont&&fiber.interruptible)cont=fiber.getCont(failureCont);return cont?cont[failureCont](this[args],fiber):fiber.yieldWith(this)}});var yieldNowWith=makePrimitive({op:"Yield",eval(fiber){let resumed=!1;return fiber.getRef(CurrentScheduler).scheduleTask(()=>{if(resumed)return;fiber.evaluate(exitVoid2)},this[args]??0),fiber.yieldWith(()=>{resumed=!0})}}),yieldNow2=yieldNowWith(0);var void_3=succeed4(void 0);var withMicroFiber=makePrimitive({op:"WithMicroFiber",eval(fiber){return this[args](fiber)}});var flatMap9=dual(2,(self,f)=>{let onSuccess=Object.create(OnSuccessProto);return onSuccess[args]=self,onSuccess[successCont]=f,onSuccess}),OnSuccessProto=makePrimitiveProto({op:"OnSuccess",eval(fiber){return fiber._stack.push(this),this[args]}});var isMicroExit=(u)=>hasProperty(u,MicroExitTypeId),exitSucceed2=succeed4,exitFailCause2=failCause4,exitInterrupt2=exitFailCause2(causeInterrupt());var exitDie2=(defect)=>exitFailCause2(causeDie(defect));var exitVoid2=exitSucceed2(void 0);var setImmediate="setImmediate"in globalThis?globalThis.setImmediate:(f)=>setTimeout(f,0);class MicroSchedulerDefault{tasks=[];running=!1;scheduleTask(task,_priority){if(this.tasks.push(task),!this.running)this.running=!0,setImmediate(this.afterScheduled)}afterScheduled=()=>{this.running=!1,this.runTasks()};runTasks(){let tasks=this.tasks;this.tasks=[];for(let i=0,len=tasks.length;i<len;i++)tasks[i]()}shouldYield(fiber){return fiber.currentOpCount>=fiber.getRef(MaxOpsBeforeYield)}flush(){while(this.tasks.length>0)this.runTasks()}}var updateContext=dual(2,(self,f)=>withMicroFiber((fiber)=>{let prev=fiber.context;return fiber.context=f(prev),onExit2(self,()=>{return fiber.context=prev,void_3})}));var provideContext2=dual(2,(self,provided)=>updateContext(self,merge3(provided)));class MaxOpsBeforeYield extends Reference2()("effect/Micro/currentMaxOpsBeforeYield",{defaultValue:()=>2048}){}class CurrentScheduler extends Reference2()("effect/Micro/currentScheduler",{defaultValue:()=>new MicroSchedulerDefault}){}var matchCauseEffect2=dual(2,(self,options)=>{let primitive=Object.create(OnSuccessAndFailureProto);return primitive[args]=self,primitive[successCont]=options.onSuccess,primitive[failureCont]=options.onFailure,primitive}),OnSuccessAndFailureProto=makePrimitiveProto({op:"OnSuccessAndFailure",eval(fiber){return fiber._stack.push(this),this[args]}});var onExit2=dual(2,(self,f)=>uninterruptibleMask2((restore)=>matchCauseEffect2(restore(self),{onFailure:(cause2)=>flatMap9(f(exitFailCause2(cause2)),()=>failCause4(cause2)),onSuccess:(a)=>flatMap9(f(exitSucceed2(a)),()=>succeed4(a))})));var setInterruptible=makePrimitive({op:"SetInterruptible",ensure(fiber){if(fiber.interruptible=this[args],fiber._interrupted&&fiber.interruptible)return()=>exitInterrupt2}}),interruptible3=(self)=>withMicroFiber((fiber)=>{if(fiber.interruptible)return self;if(fiber.interruptible=!0,fiber._stack.push(setInterruptible(!1)),fiber._interrupted)return exitInterrupt2;return self}),uninterruptibleMask2=(f)=>withMicroFiber((fiber)=>{if(!fiber.interruptible)return f(identity);return fiber.interruptible=!1,fiber._stack.push(setInterruptible(!0)),f(interruptible3)});var runFork=(effect,options)=>{let fiber=new MicroFiberImpl(CurrentScheduler.context(options?.scheduler??new MicroSchedulerDefault));if(fiber.evaluate(effect),options?.signal)if(options.signal.aborted)fiber.unsafeInterrupt();else{let abort=()=>fiber.unsafeInterrupt();options.signal.addEventListener("abort",abort,{once:!0}),fiber.addObserver(()=>options.signal.removeEventListener("abort",abort))}return fiber};class PriorityBuckets{buckets=[];scheduleTask(task,priority){let length3=this.buckets.length,bucket=void 0,index=0;for(;index<length3;index++)if(this.buckets[index][0]<=priority)bucket=this.buckets[index];else break;if(bucket&&bucket[0]===priority)bucket[1].push(task);else if(index===length3)this.buckets.push([priority,[task]]);else this.buckets.splice(index,0,[priority,[task]])}}class MixedScheduler{maxNextTickBeforeTimer;running=!1;tasks=new PriorityBuckets;constructor(maxNextTickBeforeTimer){this.maxNextTickBeforeTimer=maxNextTickBeforeTimer}starveInternal(depth){let tasks=this.tasks.buckets;this.tasks.buckets=[];for(let[_,toRun]of tasks)for(let i=0;i<toRun.length;i++)toRun[i]();if(this.tasks.buckets.length===0)this.running=!1;else this.starve(depth)}starve(depth=0){if(depth>=this.maxNextTickBeforeTimer)setTimeout(()=>this.starveInternal(0),0);else Promise.resolve(void 0).then(()=>this.starveInternal(depth+1))}shouldYield(fiber){return fiber.currentOpCount>fiber.getFiberRef(currentMaxOpsBeforeYield)?fiber.getFiberRef(currentSchedulingPriority):!1}scheduleTask(task,priority){if(this.tasks.scheduleTask(task,priority),!this.running)this.running=!0,this.starve()}}var defaultScheduler=globalValue(Symbol.for("effect/Scheduler/defaultScheduler"),()=>new MixedScheduler(2048));class SyncScheduler{tasks=new PriorityBuckets;deferred=!1;scheduleTask(task,priority){if(this.deferred)defaultScheduler.scheduleTask(task,priority);else this.tasks.scheduleTask(task,priority)}shouldYield(fiber){return fiber.currentOpCount>fiber.getFiberRef(currentMaxOpsBeforeYield)?fiber.getFiberRef(currentSchedulingPriority):!1}flush(){while(this.tasks.buckets.length>0){let tasks=this.tasks.buckets;this.tasks.buckets=[];for(let[_,toRun]of tasks)for(let i=0;i<toRun.length;i++)toRun[i]()}this.deferred=!0}}var currentScheduler=globalValue(Symbol.for("effect/FiberRef/currentScheduler"),()=>fiberRefUnsafeMake(defaultScheduler)),withScheduler=dual(2,(self,scheduler)=>fiberRefLocally(self,currentScheduler,scheduler));var currentRequestMap=globalValue(Symbol.for("effect/FiberRef/currentRequestMap"),()=>fiberRefUnsafeMake(new Map));var match9=(concurrency,sequential4,unbounded2,bounded2)=>{switch(concurrency){case void 0:return sequential4();case"unbounded":return unbounded2();case"inherit":return fiberRefGetWith(currentConcurrency,(concurrency2)=>concurrency2==="unbounded"?unbounded2():concurrency2>1?bounded2(concurrency2):sequential4());default:return concurrency>1?bounded2(concurrency):sequential4()}},matchSimple=(concurrency,sequential4,concurrent)=>{switch(concurrency){case void 0:return sequential4();case"unbounded":return concurrent();case"inherit":return fiberRefGetWith(currentConcurrency,(concurrency2)=>concurrency2==="unbounded"||concurrency2>1?concurrent():sequential4());default:return concurrency>1?concurrent():sequential4()}};var OP_INTERRUPT_SIGNAL="InterruptSignal",OP_STATEFUL="Stateful",OP_RESUME="Resume",OP_YIELD_NOW="YieldNow",interruptSignal=(cause2)=>({_tag:"InterruptSignal",cause:cause2}),stateful=(onFiber)=>({_tag:"Stateful",onFiber}),resume=(effect)=>({_tag:"Resume",effect}),yieldNow3=()=>({_tag:"YieldNow"});var FiberScopeSymbolKey="effect/FiberScope",FiberScopeTypeId=Symbol.for(FiberScopeSymbolKey);class Global{[FiberScopeTypeId]=FiberScopeTypeId;fiberId=none4;roots=new Set;add(_runtimeFlags,child){this.roots.add(child),child.addObserver(()=>{this.roots.delete(child)})}}class Local{fiberId;parent;[FiberScopeTypeId]=FiberScopeTypeId;constructor(fiberId2,parent){this.fiberId=fiberId2,this.parent=parent}add(_runtimeFlags,child){this.parent.tell(stateful((parentFiber)=>{parentFiber.addChild(child),child.addObserver(()=>{parentFiber.removeChild(child)})}))}}var unsafeMake7=(fiber)=>{return new Local(fiber.id(),fiber)},globalScope=globalValue(Symbol.for("effect/FiberScope/Global"),()=>new Global);var FiberSymbolKey="effect/Fiber",FiberTypeId=Symbol.for(FiberSymbolKey),fiberVariance2={_E:(_)=>_,_A:(_)=>_},fiberProto={[FiberTypeId]:fiberVariance2,pipe(){return pipeArguments(this,arguments)}},RuntimeFiberSymbolKey="effect/Fiber",RuntimeFiberTypeId=Symbol.for(RuntimeFiberSymbolKey),Order4=pipe(tuple(Order,Order),mapInput2((fiber)=>[fiber.id().startTimeMillis,fiber.id().id])),isFiber=(u)=>hasProperty(u,FiberTypeId),isRuntimeFiber=(self)=>(RuntimeFiberTypeId in self),_await2=(self)=>self.await,children=(self)=>self.children,done5=(exit2)=>{return{...CommitPrototype,commit(){return join2(this)},...fiberProto,id:()=>none4,await:succeed(exit2),children:succeed([]),inheritAll:void_,poll:succeed(some2(exit2)),interruptAsFork:()=>void_}},dump=(self)=>map10(self.status,(status)=>({id:self.id(),status})),dumpAll=(fibers)=>forEachSequential(fibers,dump),fail5=(error)=>done5(fail4(error)),failCause5=(cause2)=>done5(failCause3(cause2)),fromEffect=(effect)=>map10(exit(effect),done5),id=(self)=>self.id(),inheritAll=(self)=>self.inheritAll,interrupted=(fiberId2)=>done5(interrupt4(fiberId2)),interruptAll=(fibers)=>flatMap8(fiberId,(fiberId2)=>pipe(fibers,interruptAllAs(fiberId2))),interruptAllAs=dual(2,(fibers,fiberId2)=>pipe(forEachSequentialDiscard(fibers,interruptAsFork(fiberId2)),zipRight(pipe(fibers,forEachSequentialDiscard(_await2))))),interruptAsFork=dual(2,(self,fiberId2)=>self.interruptAsFork(fiberId2)),join2=(self)=>zipLeft(flatten6(self.await),self.inheritAll),map12=dual(2,(self,f)=>mapEffect(self,(a)=>sync(()=>f(a)))),mapEffect=dual(2,(self,f)=>{return{...CommitPrototype,commit(){return join2(this)},...fiberProto,id:()=>self.id(),await:flatMap8(self.await,forEachEffect(f)),children:self.children,inheritAll:self.inheritAll,poll:flatMap8(self.poll,(result)=>{switch(result._tag){case"None":return succeed(none2());case"Some":return pipe(forEachEffect(result.value,f),map10(some2))}}),interruptAsFork:(id2)=>self.interruptAsFork(id2)}}),mapFiber=dual(2,(self,f)=>map10(self.await,match6({onFailure:(cause2)=>failCause5(cause2),onSuccess:(a)=>f(a)}))),match10=dual(2,(self,{onFiber,onRuntimeFiber})=>{if(isRuntimeFiber(self))return onRuntimeFiber(self);return onFiber(self)}),_never={...CommitPrototype,commit(){return join2(this)},...fiberProto,id:()=>none4,await:never,children:succeed([]),inheritAll:never,poll:succeed(none2()),interruptAsFork:()=>never},never2=_never,orElse3=dual(2,(self,that)=>({...CommitPrototype,commit(){return join2(this)},...fiberProto,id:()=>getOrElse4(self.id(),that.id()),await:zipWith3(self.await,that.await,(exit1,exit2)=>isSuccess(exit1)?exit1:exit2),children:self.children,inheritAll:zipRight(that.inheritAll,self.inheritAll),poll:zipWith3(self.poll,that.poll,(option1,option2)=>{switch(option1._tag){case"None":return none2();case"Some":return isSuccess(option1.value)?option1:option2}}),interruptAsFork:(id2)=>pipe(interruptAsFiber(self,id2),zipRight(pipe(that,interruptAsFiber(id2))),asVoid)})),orElseEither=dual(2,(self,that)=>orElse3(map12(self,left2),map12(that,right2))),poll3=(self)=>self.poll,parseMs=(milliseconds)=>{let roundTowardsZero=milliseconds>0?Math.floor:Math.ceil;return{days:roundTowardsZero(milliseconds/86400000),hours:roundTowardsZero(milliseconds/3600000)%24,minutes:roundTowardsZero(milliseconds/60000)%60,seconds:roundTowardsZero(milliseconds/1000)%60,milliseconds:roundTowardsZero(milliseconds)%1000,microseconds:roundTowardsZero(milliseconds*1000)%1000,nanoseconds:roundTowardsZero(milliseconds*1e6)%1000}},renderStatus=(status)=>{if(isDone3(status))return"Done";if(isRunning2(status))return"Running";return`Suspended(${interruptible(status.runtimeFlags)?"interruptible":"uninterruptible"})`},pretty2=(self)=>flatMap8(currentTimeMillis2,(now)=>map10(dump(self),(dump2)=>{let time=now-dump2.id.startTimeMillis,{days:days2,hours:hours2,milliseconds,minutes:minutes2,seconds:seconds2}=parseMs(time),lifeMsg=(days2===0?"":`${days2}d`)+(days2===0&&hours2===0?"":`${hours2}h`)+(days2===0&&hours2===0&&minutes2===0?"":`${minutes2}m`)+(days2===0&&hours2===0&&minutes2===0&&seconds2===0?"":`${seconds2}s`)+`${milliseconds}ms`,waitMsg=isSuspended2(dump2.status)?(()=>{let ids3=ids2(dump2.status.blockingOn);return size3(ids3)>0?"waiting on "+Array.from(ids3).map((id2)=>`${id2}`).join(", "):""})():"",statusMsg=renderStatus(dump2.status);return`[Fiber](#${dump2.id.id}) (${lifeMsg}) ${waitMsg}
|
|
29
29
|
Status: ${statusMsg}`})),unsafeRoots=()=>Array.from(globalScope.roots),roots=sync(unsafeRoots),status=(self)=>self.status,succeed5=(value)=>done5(succeed3(value)),void_4=succeed5(void 0);var currentFiberURI="effect/FiberCurrent",getCurrentFiber=()=>fromNullable(globalThis[currentFiberURI]);var LoggerSymbolKey="effect/Logger",LoggerTypeId=Symbol.for(LoggerSymbolKey),loggerVariance={_Message:(_)=>_,_Output:(_)=>_},makeLogger=(log2)=>({[LoggerTypeId]:loggerVariance,log:log2,pipe(){return pipeArguments(this,arguments)}});var none7={[LoggerTypeId]:loggerVariance,log:constVoid,pipe(){return pipeArguments(this,arguments)}};var textOnly=/^[^\s"=]*$/,format4=(quoteValue,whitespace)=>({annotations:annotations2,cause:cause2,date,fiberId:fiberId2,logLevel,message,spans})=>{let formatValue=(value)=>value.match(textOnly)?value:quoteValue(value),format5=(label,value)=>`${formatLabel(label)}=${formatValue(value)}`,append4=(label,value)=>" "+format5(label,value),out=format5("timestamp",date.toISOString());out+=append4("level",logLevel.label),out+=append4("fiber",threadName(fiberId2));let messages=ensure(message);for(let i=0;i<messages.length;i++)out+=append4("message",toStringUnknown(messages[i],whitespace));if(!isEmptyType(cause2))out+=append4("cause",pretty(cause2,{renderErrorCause:!0}));for(let span2 of spans)out+=" "+render(date.getTime())(span2);for(let[label,value]of annotations2)out+=append4(label,toStringUnknown(value,whitespace));return out},escapeDoubleQuotes=(s)=>`"${s.replace(/\\([\s\S])|(")/g,"\\$1$2")}"`,stringLogger=makeLogger(format4(escapeDoubleQuotes)),logfmtLogger=makeLogger(format4(JSON.stringify,0));var colors={bold:"1",red:"31",green:"32",yellow:"33",blue:"34",cyan:"36",white:"37",gray:"90",black:"30",bgBrightRed:"101"},logLevelColors={None:[],All:[],Trace:[colors.gray],Debug:[colors.blue],Info:[colors.green],Warning:[colors.yellow],Error:[colors.red],Fatal:[colors.bgBrightRed,colors.black]};var hasProcessStdout=typeof process==="object"&&process!==null&&typeof process.stdout==="object"&&process.stdout!==null,processStdoutIsTTY=hasProcessStdout&&process.stdout.isTTY===!0,hasProcessStdoutOrDeno=hasProcessStdout||"Deno"in globalThis;var MetricBoundariesSymbolKey="effect/MetricBoundaries",MetricBoundariesTypeId=Symbol.for(MetricBoundariesSymbolKey);class MetricBoundariesImpl{values;[MetricBoundariesTypeId]=MetricBoundariesTypeId;constructor(values3){this.values=values3,this._hash=pipe(string(MetricBoundariesSymbolKey),combine(array2(this.values)))}_hash;[symbol](){return this._hash}[symbol2](u){return isMetricBoundaries(u)&&equals(this.values,u.values)}pipe(){return pipeArguments(this,arguments)}}var isMetricBoundaries=(u)=>hasProperty(u,MetricBoundariesTypeId),fromIterable7=(iterable)=>{let values3=pipe(iterable,appendAll(of2(Number.POSITIVE_INFINITY)),dedupe);return new MetricBoundariesImpl(values3)};var exponential=(options)=>pipe(makeBy(options.count-1,(i)=>options.start*Math.pow(options.factor,i)),unsafeFromArray,fromIterable7);var MetricKeyTypeSymbolKey="effect/MetricKeyType",MetricKeyTypeTypeId=Symbol.for(MetricKeyTypeSymbolKey),CounterKeyTypeSymbolKey="effect/MetricKeyType/Counter",CounterKeyTypeTypeId=Symbol.for(CounterKeyTypeSymbolKey),FrequencyKeyTypeSymbolKey="effect/MetricKeyType/Frequency",FrequencyKeyTypeTypeId=Symbol.for(FrequencyKeyTypeSymbolKey),GaugeKeyTypeSymbolKey="effect/MetricKeyType/Gauge",GaugeKeyTypeTypeId=Symbol.for(GaugeKeyTypeSymbolKey),HistogramKeyTypeSymbolKey="effect/MetricKeyType/Histogram",HistogramKeyTypeTypeId=Symbol.for(HistogramKeyTypeSymbolKey),SummaryKeyTypeSymbolKey="effect/MetricKeyType/Summary",SummaryKeyTypeTypeId=Symbol.for(SummaryKeyTypeSymbolKey),metricKeyTypeVariance={_In:(_)=>_,_Out:(_)=>_};class CounterKeyType{incremental;bigint;[MetricKeyTypeTypeId]=metricKeyTypeVariance;[CounterKeyTypeTypeId]=CounterKeyTypeTypeId;constructor(incremental,bigint3){this.incremental=incremental,this.bigint=bigint3,this._hash=string(CounterKeyTypeSymbolKey)}_hash;[symbol](){return this._hash}[symbol2](that){return isCounterKey(that)}pipe(){return pipeArguments(this,arguments)}}class HistogramKeyType{boundaries;[MetricKeyTypeTypeId]=metricKeyTypeVariance;[HistogramKeyTypeTypeId]=HistogramKeyTypeTypeId;constructor(boundaries){this.boundaries=boundaries,this._hash=pipe(string(HistogramKeyTypeSymbolKey),combine(hash(this.boundaries)))}_hash;[symbol](){return this._hash}[symbol2](that){return isHistogramKey(that)&&equals(this.boundaries,that.boundaries)}pipe(){return pipeArguments(this,arguments)}}var counter=(options)=>new CounterKeyType(options?.incremental??!1,options?.bigint??!1);var histogram=(boundaries)=>{return new HistogramKeyType(boundaries)};var isCounterKey=(u)=>hasProperty(u,CounterKeyTypeTypeId),isFrequencyKey=(u)=>hasProperty(u,FrequencyKeyTypeTypeId),isGaugeKey=(u)=>hasProperty(u,GaugeKeyTypeTypeId),isHistogramKey=(u)=>hasProperty(u,HistogramKeyTypeTypeId),isSummaryKey=(u)=>hasProperty(u,SummaryKeyTypeTypeId);var MetricKeySymbolKey="effect/MetricKey",MetricKeyTypeId=Symbol.for(MetricKeySymbolKey),metricKeyVariance={_Type:(_)=>_},arrayEquivilence=getEquivalence(equals);class MetricKeyImpl{name;keyType;description;tags;[MetricKeyTypeId]=metricKeyVariance;constructor(name,keyType,description,tags=[]){this.name=name,this.keyType=keyType,this.description=description,this.tags=tags,this._hash=pipe(string(this.name+this.description),combine(hash(this.keyType)),combine(array2(this.tags)))}_hash;[symbol](){return this._hash}[symbol2](u){return isMetricKey(u)&&this.name===u.name&&equals(this.keyType,u.keyType)&&equals(this.description,u.description)&&arrayEquivilence(this.tags,u.tags)}pipe(){return pipeArguments(this,arguments)}}var isMetricKey=(u)=>hasProperty(u,MetricKeyTypeId),counter2=(name,options)=>new MetricKeyImpl(name,counter(options),fromNullable(options?.description));var histogram2=(name,boundaries,description)=>new MetricKeyImpl(name,histogram(boundaries),fromNullable(description));var taggedWithLabels=dual(2,(self,extraTags)=>extraTags.length===0?self:new MetricKeyImpl(self.name,self.keyType,self.description,union(self.tags,extraTags)));var MetricStateSymbolKey="effect/MetricState",MetricStateTypeId=Symbol.for(MetricStateSymbolKey),CounterStateSymbolKey="effect/MetricState/Counter",CounterStateTypeId=Symbol.for(CounterStateSymbolKey),FrequencyStateSymbolKey="effect/MetricState/Frequency",FrequencyStateTypeId=Symbol.for(FrequencyStateSymbolKey),GaugeStateSymbolKey="effect/MetricState/Gauge",GaugeStateTypeId=Symbol.for(GaugeStateSymbolKey),HistogramStateSymbolKey="effect/MetricState/Histogram",HistogramStateTypeId=Symbol.for(HistogramStateSymbolKey),SummaryStateSymbolKey="effect/MetricState/Summary",SummaryStateTypeId=Symbol.for(SummaryStateSymbolKey),metricStateVariance={_A:(_)=>_};class CounterState{count;[MetricStateTypeId]=metricStateVariance;[CounterStateTypeId]=CounterStateTypeId;constructor(count){this.count=count}[symbol](){return pipe(hash(CounterStateSymbolKey),combine(hash(this.count)),cached(this))}[symbol2](that){return isCounterState(that)&&this.count===that.count}pipe(){return pipeArguments(this,arguments)}}var arrayEquals=getEquivalence(equals);class FrequencyState{occurrences;[MetricStateTypeId]=metricStateVariance;[FrequencyStateTypeId]=FrequencyStateTypeId;constructor(occurrences){this.occurrences=occurrences}_hash;[symbol](){return pipe(string(FrequencyStateSymbolKey),combine(array2(fromIterable(this.occurrences.entries()))),cached(this))}[symbol2](that){return isFrequencyState(that)&&arrayEquals(fromIterable(this.occurrences.entries()),fromIterable(that.occurrences.entries()))}pipe(){return pipeArguments(this,arguments)}}class GaugeState{value;[MetricStateTypeId]=metricStateVariance;[GaugeStateTypeId]=GaugeStateTypeId;constructor(value){this.value=value}[symbol](){return pipe(hash(GaugeStateSymbolKey),combine(hash(this.value)),cached(this))}[symbol2](u){return isGaugeState(u)&&this.value===u.value}pipe(){return pipeArguments(this,arguments)}}class HistogramState{buckets;count;min;max;sum;[MetricStateTypeId]=metricStateVariance;[HistogramStateTypeId]=HistogramStateTypeId;constructor(buckets,count,min3,max3,sum2){this.buckets=buckets,this.count=count,this.min=min3,this.max=max3,this.sum=sum2}[symbol](){return pipe(hash(HistogramStateSymbolKey),combine(hash(this.buckets)),combine(hash(this.count)),combine(hash(this.min)),combine(hash(this.max)),combine(hash(this.sum)),cached(this))}[symbol2](that){return isHistogramState(that)&&equals(this.buckets,that.buckets)&&this.count===that.count&&this.min===that.min&&this.max===that.max&&this.sum===that.sum}pipe(){return pipeArguments(this,arguments)}}class SummaryState{error;quantiles;count;min;max;sum;[MetricStateTypeId]=metricStateVariance;[SummaryStateTypeId]=SummaryStateTypeId;constructor(error,quantiles,count,min3,max3,sum2){this.error=error,this.quantiles=quantiles,this.count=count,this.min=min3,this.max=max3,this.sum=sum2}[symbol](){return pipe(hash(SummaryStateSymbolKey),combine(hash(this.error)),combine(hash(this.quantiles)),combine(hash(this.count)),combine(hash(this.min)),combine(hash(this.max)),combine(hash(this.sum)),cached(this))}[symbol2](that){return isSummaryState(that)&&this.error===that.error&&equals(this.quantiles,that.quantiles)&&this.count===that.count&&this.min===that.min&&this.max===that.max&&this.sum===that.sum}pipe(){return pipeArguments(this,arguments)}}var counter3=(count)=>new CounterState(count),frequency2=(occurrences)=>{return new FrequencyState(occurrences)},gauge2=(count)=>new GaugeState(count),histogram3=(options)=>new HistogramState(options.buckets,options.count,options.min,options.max,options.sum),summary2=(options)=>new SummaryState(options.error,options.quantiles,options.count,options.min,options.max,options.sum);var isCounterState=(u)=>hasProperty(u,CounterStateTypeId),isFrequencyState=(u)=>hasProperty(u,FrequencyStateTypeId),isGaugeState=(u)=>hasProperty(u,GaugeStateTypeId),isHistogramState=(u)=>hasProperty(u,HistogramStateTypeId),isSummaryState=(u)=>hasProperty(u,SummaryStateTypeId);var MetricHookSymbolKey="effect/MetricHook",MetricHookTypeId=Symbol.for(MetricHookSymbolKey),metricHookVariance={_In:(_)=>_,_Out:(_)=>_},make31=(options)=>({[MetricHookTypeId]:metricHookVariance,pipe(){return pipeArguments(this,arguments)},...options});var bigint04=BigInt(0),counter4=(key)=>{let sum2=key.keyType.bigint?bigint04:0,canUpdate=key.keyType.incremental?key.keyType.bigint?(value)=>value>=bigint04:(value)=>value>=0:(_value)=>!0,update4=(value)=>{if(canUpdate(value))sum2=sum2+value};return make31({get:()=>counter3(sum2),update:update4,modify:update4})},frequency3=(key)=>{let values3=new Map;for(let word of key.keyType.preregisteredWords)values3.set(word,0);let update4=(word)=>{let slotCount=values3.get(word)??0;values3.set(word,slotCount+1)};return make31({get:()=>frequency2(values3),update:update4,modify:update4})},gauge3=(_key,startAt)=>{let value=startAt;return make31({get:()=>gauge2(value),update:(v)=>{value=v},modify:(v)=>{value=value+v}})},histogram4=(key)=>{let bounds=key.keyType.boundaries.values,size6=bounds.length,values3=new Uint32Array(size6+1),boundaries=new Float32Array(size6),count=0,sum2=0,min3=Number.MAX_VALUE,max3=Number.MIN_VALUE;pipe(bounds,sort(Order),map3((n,i)=>{boundaries[i]=n}));let update4=(value)=>{let from=0,to=size6;while(from!==to){let mid=Math.floor(from+(to-from)/2),boundary=boundaries[mid];if(value<=boundary)to=mid;else from=mid;if(to===from+1)if(value<=boundaries[from])to=from;else from=to}if(values3[from]=values3[from]+1,count=count+1,sum2=sum2+value,value<min3)min3=value;if(value>max3)max3=value},getBuckets=()=>{let builder=allocate(size6),cumulated=0;for(let i=0;i<size6;i++){let boundary=boundaries[i],value=values3[i];cumulated=cumulated+value,builder[i]=[boundary,cumulated]}return builder};return make31({get:()=>histogram3({buckets:getBuckets(),count,min:min3,max:max3,sum:sum2}),update:update4,modify:update4})},summary3=(key)=>{let{error,maxAge,maxSize,quantiles}=key.keyType,sortedQuantiles=pipe(quantiles,sort(Order)),values3=allocate(maxSize),head4=0,count=0,sum2=0,min3=Number.MAX_VALUE,max3=Number.MIN_VALUE,snapshot=(now)=>{let builder=[],i=0;while(i!==maxSize-1){let item=values3[i];if(item!=null){let[t,v]=item,age=millis(now-t);if(greaterThanOrEqualTo2(age,zero2)&&lessThanOrEqualTo2(age,maxAge))builder.push(v)}i=i+1}return calculateQuantiles(error,sortedQuantiles,sort(builder,Order))},observe=(value,timestamp)=>{if(maxSize>0){head4=head4+1;let target=head4%maxSize;values3[target]=[timestamp,value]}if(count=count+1,sum2=sum2+value,value<min3)min3=value;if(value>max3)max3=value};return make31({get:()=>summary2({error,quantiles:snapshot(Date.now()),count,min:min3,max:max3,sum:sum2}),update:([value,timestamp])=>observe(value,timestamp),modify:([value,timestamp])=>observe(value,timestamp)})},calculateQuantiles=(error,sortedQuantiles,sortedSamples)=>{let sampleCount=sortedSamples.length;if(!isNonEmptyReadonlyArray(sortedQuantiles))return empty2();let head4=sortedQuantiles[0],tail=sortedQuantiles.slice(1),resolvedHead=resolveQuantile(error,sampleCount,none2(),0,head4,sortedSamples),resolved=of(resolvedHead);return tail.forEach((quantile)=>{resolved.push(resolveQuantile(error,sampleCount,resolvedHead.value,resolvedHead.consumed,quantile,resolvedHead.rest))}),map3(resolved,(rq)=>[rq.quantile,rq.value])},resolveQuantile=(error,sampleCount,current,consumed,quantile,rest)=>{let error_1=error,sampleCount_1=sampleCount,current_1=current,consumed_1=consumed,quantile_1=quantile,rest_1=rest,error_2=error,sampleCount_2=sampleCount,current_2=current,consumed_2=consumed,quantile_2=quantile,rest_2=rest;while(!0){if(!isNonEmptyReadonlyArray(rest_1))return{quantile:quantile_1,value:none2(),consumed:consumed_1,rest:[]};if(quantile_1===1)return{quantile:quantile_1,value:some2(lastNonEmpty(rest_1)),consumed:consumed_1+rest_1.length,rest:[]};let headValue=headNonEmpty(rest_1),sameHead=span(rest_1,(n)=>n===headValue),desired=quantile_1*sampleCount_1,allowedError=error_1/2*desired,candConsumed=consumed_1+sameHead[0].length,candError=Math.abs(candConsumed-desired);if(candConsumed<desired-allowedError){error_2=error_1,sampleCount_2=sampleCount_1,current_2=head(rest_1),consumed_2=candConsumed,quantile_2=quantile_1,rest_2=sameHead[1],error_1=error_2,sampleCount_1=sampleCount_2,current_1=current_2,consumed_1=consumed_2,quantile_1=quantile_2,rest_1=rest_2;continue}if(candConsumed>desired+allowedError){let valueToReturn=isNone2(current_1)?some2(headValue):current_1;return{quantile:quantile_1,value:valueToReturn,consumed:consumed_1,rest:rest_1}}switch(current_1._tag){case"None":{error_2=error_1,sampleCount_2=sampleCount_1,current_2=head(rest_1),consumed_2=candConsumed,quantile_2=quantile_1,rest_2=sameHead[1],error_1=error_2,sampleCount_1=sampleCount_2,current_1=current_2,consumed_1=consumed_2,quantile_1=quantile_2,rest_1=rest_2;continue}case"Some":{let prevError=Math.abs(desired-current_1.value);if(candError<prevError){error_2=error_1,sampleCount_2=sampleCount_1,current_2=head(rest_1),consumed_2=candConsumed,quantile_2=quantile_1,rest_2=sameHead[1],error_1=error_2,sampleCount_1=sampleCount_2,current_1=current_2,consumed_1=consumed_2,quantile_1=quantile_2,rest_1=rest_2;continue}return{quantile:quantile_1,value:some2(current_1.value),consumed:consumed_1,rest:rest_1}}}}throw new Error("BUG: MetricHook.resolveQuantiles - please report an issue at https://github.com/Effect-TS/effect/issues")};var MetricPairSymbolKey="effect/MetricPair",MetricPairTypeId=Symbol.for(MetricPairSymbolKey),metricPairVariance={_Type:(_)=>_};var unsafeMake8=(metricKey,metricState)=>{return{[MetricPairTypeId]:metricPairVariance,metricKey,metricState,pipe(){return pipeArguments(this,arguments)}}};var MetricRegistrySymbolKey="effect/MetricRegistry",MetricRegistryTypeId=Symbol.for(MetricRegistrySymbolKey);class MetricRegistryImpl{[MetricRegistryTypeId]=MetricRegistryTypeId;map=empty21();snapshot(){let result=[];for(let[key,hook]of this.map)result.push(unsafeMake8(key,hook.get()));return result}get(key){let hook=pipe(this.map,get8(key),getOrUndefined);if(hook==null){if(isCounterKey(key.keyType))return this.getCounter(key);if(isGaugeKey(key.keyType))return this.getGauge(key);if(isFrequencyKey(key.keyType))return this.getFrequency(key);if(isHistogramKey(key.keyType))return this.getHistogram(key);if(isSummaryKey(key.keyType))return this.getSummary(key);throw new Error("BUG: MetricRegistry.get - unknown MetricKeyType - please report an issue at https://github.com/Effect-TS/effect/issues")}else return hook}getCounter(key){let value=pipe(this.map,get8(key),getOrUndefined);if(value==null){let counter5=counter4(key);if(!pipe(this.map,has4(key)))pipe(this.map,set4(key,counter5));value=counter5}return value}getFrequency(key){let value=pipe(this.map,get8(key),getOrUndefined);if(value==null){let frequency4=frequency3(key);if(!pipe(this.map,has4(key)))pipe(this.map,set4(key,frequency4));value=frequency4}return value}getGauge(key){let value=pipe(this.map,get8(key),getOrUndefined);if(value==null){let gauge4=gauge3(key,key.keyType.bigint?BigInt(0):0);if(!pipe(this.map,has4(key)))pipe(this.map,set4(key,gauge4));value=gauge4}return value}getHistogram(key){let value=pipe(this.map,get8(key),getOrUndefined);if(value==null){let histogram5=histogram4(key);if(!pipe(this.map,has4(key)))pipe(this.map,set4(key,histogram5));value=histogram5}return value}getSummary(key){let value=pipe(this.map,get8(key),getOrUndefined);if(value==null){let summary4=summary3(key);if(!pipe(this.map,has4(key)))pipe(this.map,set4(key,summary4));value=summary4}return value}}var make32=()=>{return new MetricRegistryImpl};var MetricSymbolKey="effect/Metric",MetricTypeId=Symbol.for(MetricSymbolKey),metricVariance={_Type:(_)=>_,_In:(_)=>_,_Out:(_)=>_},globalMetricRegistry=globalValue(Symbol.for("effect/Metric/globalMetricRegistry"),()=>make32()),make33=function(keyType,unsafeUpdate,unsafeValue,unsafeModify){let metric=Object.assign((effect)=>tap(effect,(a)=>update4(metric,a)),{[MetricTypeId]:metricVariance,keyType,unsafeUpdate,unsafeValue,unsafeModify,register(){return this.unsafeValue([]),this},pipe(){return pipeArguments(this,arguments)}});return metric};var counter5=(name,options)=>fromMetricKey(counter2(name,options));var fromMetricKey=(key)=>{let untaggedHook,hookCache=new WeakMap,hook=(extraTags)=>{if(extraTags.length===0){if(untaggedHook!==void 0)return untaggedHook;return untaggedHook=globalMetricRegistry.get(key),untaggedHook}let hook2=hookCache.get(extraTags);if(hook2!==void 0)return hook2;return hook2=globalMetricRegistry.get(taggedWithLabels(key,extraTags)),hookCache.set(extraTags,hook2),hook2};return make33(key.keyType,(input,extraTags)=>hook(extraTags).update(input),(extraTags)=>hook(extraTags).get(),(input,extraTags)=>hook(extraTags).modify(input))};var histogram5=(name,boundaries,description)=>fromMetricKey(histogram2(name,boundaries,description));var tagged=dual(3,(self,key,value)=>taggedWithLabels2(self,[make30(key,value)]));var taggedWithLabels2=dual(2,(self,extraTags)=>{return make33(self.keyType,(input,extraTags1)=>self.unsafeUpdate(input,union(extraTags,extraTags1)),(extraTags1)=>self.unsafeValue(union(extraTags,extraTags1)),(input,extraTags1)=>self.unsafeModify(input,union(extraTags,extraTags1)))});var update4=dual(2,(self,input)=>fiberRefGetWith(currentMetricLabels,(tags)=>sync(()=>self.unsafeUpdate(input,tags))));var RequestSymbolKey="effect/Request",RequestTypeId=Symbol.for(RequestSymbolKey),requestVariance={_E:(_)=>_,_A:(_)=>_},RequestPrototype={...StructuralPrototype,[RequestTypeId]:requestVariance},isRequest=(u)=>hasProperty(u,RequestTypeId);var complete=dual(2,(self,result)=>fiberRefGetWith(currentRequestMap,(map13)=>sync(()=>{if(map13.has(self)){let entry=map13.get(self);if(!entry.state.completed)entry.state.completed=!0,deferredUnsafeDone(entry.result,result)}})));class Listeners{count=0;observers=new Set;interrupted=!1;addObserver(f){this.observers.add(f)}removeObserver(f){this.observers.delete(f)}increment(){this.count++,this.observers.forEach((f)=>f(this.count))}decrement(){this.count--,this.observers.forEach((f)=>f(this.count))}}var Direction={Forward:0,Backward:1};class RedBlackTreeIterator{self;stack;direction;count=0;constructor(self,stack,direction){this.self=self,this.stack=stack,this.direction=direction}clone(){return new RedBlackTreeIterator(this.self,this.stack.slice(),this.direction)}reversed(){return new RedBlackTreeIterator(this.self,this.stack.slice(),this.direction===Direction.Forward?Direction.Backward:Direction.Forward)}next(){let entry=this.entry;if(this.count++,this.direction===Direction.Forward)this.moveNext();else this.movePrev();switch(entry._tag){case"None":return{done:!0,value:this.count};case"Some":return{done:!1,value:entry.value}}}get key(){if(this.stack.length>0)return some2(this.stack[this.stack.length-1].key);return none2()}get value(){if(this.stack.length>0)return some2(this.stack[this.stack.length-1].value);return none2()}get entry(){return map2(last(this.stack),(node)=>[node.key,node.value])}get index(){let idx=0,stack=this.stack;if(stack.length===0){let r=this.self._root;if(r!=null)return r.count;return 0}else if(stack[stack.length-1].left!=null)idx=stack[stack.length-1].left.count;for(let s=stack.length-2;s>=0;--s)if(stack[s+1]===stack[s].right){if(++idx,stack[s].left!=null)idx+=stack[s].left.count}return idx}moveNext(){let stack=this.stack;if(stack.length===0)return;let n=stack[stack.length-1];if(n.right!=null){n=n.right;while(n!=null)stack.push(n),n=n.left}else{stack.pop();while(stack.length>0&&stack[stack.length-1].right===n)n=stack[stack.length-1],stack.pop()}}get hasNext(){let stack=this.stack;if(stack.length===0)return!1;if(stack[stack.length-1].right!=null)return!0;for(let s=stack.length-1;s>0;--s)if(stack[s-1].left===stack[s])return!0;return!1}movePrev(){let stack=this.stack;if(stack.length===0)return;let n=stack[stack.length-1];if(n!=null&&n.left!=null){n=n.left;while(n!=null)stack.push(n),n=n.right}else{stack.pop();while(stack.length>0&&stack[stack.length-1].left===n)n=stack[stack.length-1],stack.pop()}}get hasPrev(){let stack=this.stack;if(stack.length===0)return!1;if(stack[stack.length-1].left!=null)return!0;for(let s=stack.length-1;s>0;--s)if(stack[s-1].right===stack[s])return!0;return!1}}var RedBlackTreeSymbolKey="effect/RedBlackTree",RedBlackTreeTypeId=Symbol.for(RedBlackTreeSymbolKey),redBlackTreeVariance={_Key:(_)=>_,_Value:(_)=>_},RedBlackTreeProto={[RedBlackTreeTypeId]:redBlackTreeVariance,[symbol](){let hash2=hash(RedBlackTreeSymbolKey);for(let item of this)hash2^=pipe(hash(item[0]),combine(hash(item[1])));return cached(this,hash2)},[symbol2](that){if(isRedBlackTree(that)){if((this._root?.count??0)!==(that._root?.count??0))return!1;let entries2=Array.from(that);return Array.from(this).every((itemSelf,i)=>{let itemThat=entries2[i];return equals(itemSelf[0],itemThat[0])&&equals(itemSelf[1],itemThat[1])})}return!1},[Symbol.iterator](){let stack=[],n=this._root;while(n!=null)stack.push(n),n=n.left;return new RedBlackTreeIterator(this,stack,Direction.Forward)},toString(){return format(this.toJSON())},toJSON(){return{_id:"RedBlackTree",values:Array.from(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}};var isRedBlackTree=(u)=>hasProperty(u,RedBlackTreeTypeId);var keysForward=(self)=>keys3(self,Direction.Forward);var keys3=(self,direction)=>{let begin=self[Symbol.iterator](),count=0;return{[Symbol.iterator]:()=>keys3(self,direction),next:()=>{count++;let entry=begin.key;if(direction===Direction.Forward)begin.moveNext();else begin.movePrev();switch(entry._tag){case"None":return{done:!0,value:count};case"Some":return{done:!1,value:entry.value}}}}};var keys4=keysForward;var TypeId15=Symbol.for("effect/SortedSet"),SortedSetProto={[TypeId15]:{_A:(_)=>_},[symbol](){return pipe(hash(this.keyTree),combine(hash(TypeId15)),cached(this))},[symbol2](that){return isSortedSet(that)&&equals(this.keyTree,that.keyTree)},[Symbol.iterator](){return keys4(this.keyTree)},toString(){return format(this.toJSON())},toJSON(){return{_id:"SortedSet",values:Array.from(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}};var isSortedSet=(u)=>hasProperty(u,TypeId15);var SupervisorSymbolKey="effect/Supervisor",SupervisorTypeId=Symbol.for(SupervisorSymbolKey),supervisorVariance={_T:(_)=>_};class ProxySupervisor{underlying;value0;[SupervisorTypeId]=supervisorVariance;constructor(underlying,value0){this.underlying=underlying,this.value0=value0}get value(){return this.value0}onStart(context2,effect,parent,fiber){this.underlying.onStart(context2,effect,parent,fiber)}onEnd(value,fiber){this.underlying.onEnd(value,fiber)}onEffect(fiber,effect){this.underlying.onEffect(fiber,effect)}onSuspend(fiber){this.underlying.onSuspend(fiber)}onResume(fiber){this.underlying.onResume(fiber)}map(f){return new ProxySupervisor(this,pipe(this.value,map10(f)))}zip(right3){return new Zip(this,right3)}}class Zip{left;right;_tag="Zip";[SupervisorTypeId]=supervisorVariance;constructor(left3,right3){this.left=left3,this.right=right3}get value(){return zip2(this.left.value,this.right.value)}onStart(context2,effect,parent,fiber){this.left.onStart(context2,effect,parent,fiber),this.right.onStart(context2,effect,parent,fiber)}onEnd(value,fiber){this.left.onEnd(value,fiber),this.right.onEnd(value,fiber)}onEffect(fiber,effect){this.left.onEffect(fiber,effect),this.right.onEffect(fiber,effect)}onSuspend(fiber){this.left.onSuspend(fiber),this.right.onSuspend(fiber)}onResume(fiber){this.left.onResume(fiber),this.right.onResume(fiber)}map(f){return new ProxySupervisor(this,pipe(this.value,map10(f)))}zip(right3){return new Zip(this,right3)}}var isZip=(self)=>hasProperty(self,SupervisorTypeId)&&isTagged(self,"Zip");class Track{[SupervisorTypeId]=supervisorVariance;fibers=new Set;get value(){return sync(()=>Array.from(this.fibers))}onStart(_context,_effect,_parent,fiber){this.fibers.add(fiber)}onEnd(_value,fiber){this.fibers.delete(fiber)}onEffect(_fiber,_effect){}onSuspend(_fiber){}onResume(_fiber){}map(f){return new ProxySupervisor(this,pipe(this.value,map10(f)))}zip(right3){return new Zip(this,right3)}onRun(execution,_fiber){return execution()}}class Const{effect;[SupervisorTypeId]=supervisorVariance;constructor(effect){this.effect=effect}get value(){return this.effect}onStart(_context,_effect,_parent,_fiber){}onEnd(_value,_fiber){}onEffect(_fiber,_effect){}onSuspend(_fiber){}onResume(_fiber){}map(f){return new ProxySupervisor(this,pipe(this.value,map10(f)))}zip(right3){return new Zip(this,right3)}onRun(execution,_fiber){return execution()}}var unsafeTrack=()=>{return new Track},track=sync(unsafeTrack),fromEffect2=(effect)=>{return new Const(effect)},none8=globalValue("effect/Supervisor/none",()=>fromEffect2(void_));var make35=make15;var OP_EMPTY3="Empty",OP_ADD_SUPERVISOR="AddSupervisor",OP_REMOVE_SUPERVISOR="RemoveSupervisor",OP_AND_THEN2="AndThen",empty29={_tag:OP_EMPTY3},combine11=(self,that)=>{return{_tag:OP_AND_THEN2,first:self,second:that}},patch11=(self,supervisor)=>{return patchLoop(supervisor,of2(self))},patchLoop=(_supervisor,_patches)=>{let supervisor=_supervisor,patches=_patches;while(isNonEmpty2(patches)){let head4=headNonEmpty2(patches);switch(head4._tag){case OP_EMPTY3:{patches=tailNonEmpty2(patches);break}case OP_ADD_SUPERVISOR:{supervisor=supervisor.zip(head4.supervisor),patches=tailNonEmpty2(patches);break}case OP_REMOVE_SUPERVISOR:{supervisor=removeSupervisor(supervisor,head4.supervisor),patches=tailNonEmpty2(patches);break}case OP_AND_THEN2:{patches=prepend2(head4.first)(prepend2(head4.second)(tailNonEmpty2(patches)));break}}}return supervisor},removeSupervisor=(self,that)=>{if(equals(self,that))return none8;else if(isZip(self))return removeSupervisor(self.left,that).zip(removeSupervisor(self.right,that));else return self},toSet2=(self)=>{if(equals(self,none8))return empty8();else if(isZip(self))return pipe(toSet2(self.left),union3(toSet2(self.right)));else return make11(self)},diff10=(oldValue,newValue)=>{if(equals(oldValue,newValue))return empty29;let oldSupervisors=toSet2(oldValue),newSupervisors=toSet2(newValue),added=pipe(newSupervisors,difference3(oldSupervisors),reduce6(empty29,(patch12,supervisor)=>combine11(patch12,{_tag:OP_ADD_SUPERVISOR,supervisor}))),removed=pipe(oldSupervisors,difference3(newSupervisors),reduce6(empty29,(patch12,supervisor)=>combine11(patch12,{_tag:OP_REMOVE_SUPERVISOR,supervisor})));return combine11(added,removed)},differ2=make35({empty:empty29,patch:patch11,combine:combine11,diff:diff10});var fiberStarted=counter5("effect_fiber_started",{incremental:!0}),fiberActive=counter5("effect_fiber_active"),fiberSuccesses=counter5("effect_fiber_successes",{incremental:!0}),fiberFailures=counter5("effect_fiber_failures",{incremental:!0}),fiberLifetimes=tagged(histogram5("effect_fiber_lifetimes",exponential({start:0.5,factor:2,count:35})),"time_unit","milliseconds"),EvaluationSignalContinue="Continue",EvaluationSignalDone="Done",EvaluationSignalYieldNow="Yield",runtimeFiberVariance={_E:(_)=>_,_A:(_)=>_},absurd=(_)=>{throw new Error(`BUG: FiberRuntime - ${toStringUnknown(_)} - please report an issue at https://github.com/Effect-TS/effect/issues`)},YieldedOp=Symbol.for("effect/internal/fiberRuntime/YieldedOp"),yieldedOpChannel=globalValue("effect/internal/fiberRuntime/yieldedOpChannel",()=>({currentOp:null})),contOpSuccess={[OP_ON_SUCCESS]:(_,cont,value)=>{return internalCall(()=>cont.effect_instruction_i1(value))},["OnStep"]:(_,_cont,value)=>{return exitSucceed(exitSucceed(value))},[OP_ON_SUCCESS_AND_FAILURE]:(_,cont,value)=>{return internalCall(()=>cont.effect_instruction_i2(value))},[OP_REVERT_FLAGS]:(self,cont,value)=>{if(self.patchRuntimeFlags(self.currentRuntimeFlags,cont.patch),interruptible(self.currentRuntimeFlags)&&self.isInterrupted())return exitFailCause(self.getInterruptedCause());else return exitSucceed(value)},[OP_WHILE]:(self,cont,value)=>{if(internalCall(()=>cont.effect_instruction_i2(value)),internalCall(()=>cont.effect_instruction_i0()))return self.pushStack(cont),internalCall(()=>cont.effect_instruction_i1());else return void_},[OP_ITERATOR]:(self,cont,value)=>{let state=internalCall(()=>cont.effect_instruction_i0.next(value));if(state.done)return exitSucceed(state.value);return self.pushStack(cont),yieldWrapGet(state.value)}},drainQueueWhileRunningTable={[OP_INTERRUPT_SIGNAL]:(self,runtimeFlags2,cur,message)=>{return self.processNewInterruptSignal(message.cause),interruptible(runtimeFlags2)?exitFailCause(message.cause):cur},[OP_RESUME]:(_self,_runtimeFlags,_cur,_message)=>{throw new Error("It is illegal to have multiple concurrent run loops in a single fiber")},[OP_STATEFUL]:(self,runtimeFlags2,cur,message)=>{return message.onFiber(self,running2(runtimeFlags2)),cur},[OP_YIELD_NOW]:(_self,_runtimeFlags,cur,_message)=>{return flatMap8(yieldNow(),()=>cur)}},runBlockedRequests=(self)=>forEachSequentialDiscard(flatten4(self),(requestsByRequestResolver)=>forEachConcurrentDiscard(sequentialCollectionToChunk(requestsByRequestResolver),([dataSource,sequential4])=>{let map13=new Map,arr=[];for(let block of sequential4){arr.push(toReadonlyArray(block));for(let entry of block)map13.set(entry.request,entry)}let flat=arr.flat();return fiberRefLocally(invokeWithInterrupt(dataSource.runAll(arr),flat,()=>flat.forEach((entry)=>{entry.listeners.interrupted=!0})),currentRequestMap,map13)},!1,!1)),_version=getCurrentVersion();class FiberRuntime extends Class{[FiberTypeId]=fiberVariance2;[RuntimeFiberTypeId]=runtimeFiberVariance;_fiberRefs;_fiberId;_queue=new Array;_children=null;_observers=new Array;_running=!1;_stack=[];_asyncInterruptor=null;_asyncBlockingOn=null;_exitValue=null;_steps=[];_isYielding=!1;currentRuntimeFlags;currentOpCount=0;currentSupervisor;currentScheduler;currentTracer;currentSpan;currentContext;currentDefaultServices;constructor(fiberId2,fiberRefs0,runtimeFlags0){super();if(this.currentRuntimeFlags=runtimeFlags0,this._fiberId=fiberId2,this._fiberRefs=fiberRefs0,runtimeMetrics(runtimeFlags0)){let tags=this.getFiberRef(currentMetricLabels);fiberStarted.unsafeUpdate(1,tags),fiberActive.unsafeUpdate(1,tags)}this.refreshRefCache()}commit(){return join2(this)}id(){return this._fiberId}resume(effect){this.tell(resume(effect))}get status(){return this.ask((_,status2)=>status2)}get runtimeFlags(){return this.ask((state,status2)=>{if(isDone3(status2))return state.currentRuntimeFlags;return status2.runtimeFlags})}scope(){return unsafeMake7(this)}get children(){return this.ask((fiber)=>Array.from(fiber.getChildren()))}getChildren(){if(this._children===null)this._children=new Set;return this._children}getInterruptedCause(){return this.getFiberRef(currentInterruptedCause)}fiberRefs(){return this.ask((fiber)=>fiber.getFiberRefs())}ask(f){return suspend(()=>{let deferred=deferredUnsafeMake(this._fiberId);return this.tell(stateful((fiber,status2)=>{deferredUnsafeDone(deferred,sync(()=>f(fiber,status2)))})),deferredAwait(deferred)})}tell(message){if(this._queue.push(message),!this._running)this._running=!0,this.drainQueueLaterOnExecutor()}get await(){return async_((resume2)=>{let cb=(exit2)=>resume2(succeed(exit2));return this.tell(stateful((fiber,_)=>{if(fiber._exitValue!==null)cb(this._exitValue);else fiber.addObserver(cb)})),sync(()=>this.tell(stateful((fiber,_)=>{fiber.removeObserver(cb)})))},this.id())}get inheritAll(){return withFiberRuntime((parentFiber,parentStatus)=>{let parentFiberId=parentFiber.id(),parentFiberRefs=parentFiber.getFiberRefs(),parentRuntimeFlags=parentStatus.runtimeFlags,childFiberRefs=this.getFiberRefs(),updatedFiberRefs=joinAs(parentFiberRefs,parentFiberId,childFiberRefs);parentFiber.setFiberRefs(updatedFiberRefs);let updatedRuntimeFlags=parentFiber.getFiberRef(currentRuntimeFlags),patch12=pipe(diff7(parentRuntimeFlags,updatedRuntimeFlags),exclude2(Interruption),exclude2(WindDown));return updateRuntimeFlags(patch12)})}get poll(){return sync(()=>fromNullable(this._exitValue))}unsafePoll(){return this._exitValue}interruptAsFork(fiberId2){return sync(()=>this.tell(interruptSignal(interrupt(fiberId2))))}unsafeInterruptAsFork(fiberId2){this.tell(interruptSignal(interrupt(fiberId2)))}addObserver(observer){if(this._exitValue!==null)observer(this._exitValue);else this._observers.push(observer)}removeObserver(observer){this._observers=this._observers.filter((o)=>o!==observer)}getFiberRefs(){return this.setFiberRef(currentRuntimeFlags,this.currentRuntimeFlags),this._fiberRefs}unsafeDeleteFiberRef(fiberRef){this._fiberRefs=delete_(this._fiberRefs,fiberRef)}getFiberRef(fiberRef){if(this._fiberRefs.locals.has(fiberRef))return this._fiberRefs.locals.get(fiberRef)[0][1];return fiberRef.initial}setFiberRef(fiberRef,value){this._fiberRefs=updateAs(this._fiberRefs,{fiberId:this._fiberId,fiberRef,value}),this.refreshRefCache()}refreshRefCache(){this.currentDefaultServices=this.getFiberRef(currentServices),this.currentTracer=this.currentDefaultServices.unsafeMap.get(tracerTag.key),this.currentSupervisor=this.getFiberRef(currentSupervisor),this.currentScheduler=this.getFiberRef(currentScheduler),this.currentContext=this.getFiberRef(currentContext),this.currentSpan=this.currentContext.unsafeMap.get(spanTag.key)}setFiberRefs(fiberRefs3){this._fiberRefs=fiberRefs3,this.refreshRefCache()}addChild(child){this.getChildren().add(child)}removeChild(child){this.getChildren().delete(child)}transferChildren(scope){let children2=this._children;if(this._children=null,children2!==null&&children2.size>0){for(let child of children2)if(child._exitValue===null)scope.add(this.currentRuntimeFlags,child)}}drainQueueOnCurrentThread(){let recurse=!0;while(recurse){let evaluationSignal=EvaluationSignalContinue,prev=globalThis[currentFiberURI];globalThis[currentFiberURI]=this;try{while(evaluationSignal===EvaluationSignalContinue)evaluationSignal=this._queue.length===0?EvaluationSignalDone:this.evaluateMessageWhileSuspended(this._queue.splice(0,1)[0])}finally{this._running=!1,globalThis[currentFiberURI]=prev}if(this._queue.length>0&&!this._running)if(this._running=!0,evaluationSignal===EvaluationSignalYieldNow)this.drainQueueLaterOnExecutor(),recurse=!1;else recurse=!0;else recurse=!1}}drainQueueLaterOnExecutor(){this.currentScheduler.scheduleTask(this.run,this.getFiberRef(currentSchedulingPriority))}drainQueueWhileRunning(runtimeFlags2,cur0){let cur=cur0;while(this._queue.length>0){let message=this._queue.splice(0,1)[0];cur=drainQueueWhileRunningTable[message._tag](this,runtimeFlags2,cur,message)}return cur}isInterrupted(){return!isEmpty5(this.getFiberRef(currentInterruptedCause))}addInterruptedCause(cause2){let oldSC=this.getFiberRef(currentInterruptedCause);this.setFiberRef(currentInterruptedCause,sequential(oldSC,cause2))}processNewInterruptSignal(cause2){this.addInterruptedCause(cause2),this.sendInterruptSignalToAllChildren()}sendInterruptSignalToAllChildren(){if(this._children===null||this._children.size===0)return!1;let told=!1;for(let child of this._children)child.tell(interruptSignal(interrupt(this.id()))),told=!0;return told}interruptAllChildren(){if(this.sendInterruptSignalToAllChildren()){let it=this._children.values();this._children=null;let isDone4=!1;return whileLoop({while:()=>!isDone4,body:()=>{let next=it.next();if(!next.done)return asVoid(next.value.await);else return sync(()=>{isDone4=!0})},step:()=>{}})}return null}reportExitValue(exit2){if(runtimeMetrics(this.currentRuntimeFlags)){let tags=this.getFiberRef(currentMetricLabels),startTimeMillis=this.id().startTimeMillis,endTimeMillis=Date.now();switch(fiberLifetimes.unsafeUpdate(endTimeMillis-startTimeMillis,tags),fiberActive.unsafeUpdate(-1,tags),exit2._tag){case OP_SUCCESS:{fiberSuccesses.unsafeUpdate(1,tags);break}case OP_FAILURE:{fiberFailures.unsafeUpdate(1,tags);break}}}if(exit2._tag==="Failure"){let level=this.getFiberRef(currentUnhandledErrorLogLevel);if(!isInterruptedOnly(exit2.cause)&&level._tag==="Some")this.log("Fiber terminated with an unhandled error",exit2.cause,level)}}setExitValue(exit2){this._exitValue=exit2,this.reportExitValue(exit2);for(let i=this._observers.length-1;i>=0;i--)this._observers[i](exit2);this._observers=[]}getLoggers(){return this.getFiberRef(currentLoggers)}log(message,cause2,overrideLogLevel){let logLevel=isSome2(overrideLogLevel)?overrideLogLevel.value:this.getFiberRef(currentLogLevel),minimumLogLevel=this.getFiberRef(currentMinimumLogLevel);if(greaterThan3(minimumLogLevel,logLevel))return;let spans=this.getFiberRef(currentLogSpan),annotations2=this.getFiberRef(currentLogAnnotations),loggers=this.getLoggers(),contextMap=this.getFiberRefs();if(size3(loggers)>0){let clockService=get3(this.getFiberRef(currentServices),clockTag),date=new Date(clockService.unsafeCurrentTimeMillis());withRedactableContext(contextMap,()=>{for(let logger of loggers)logger.log({fiberId:this.id(),logLevel,message,cause:cause2,context:contextMap,spans,annotations:annotations2,date})})}}evaluateMessageWhileSuspended(message){switch(message._tag){case OP_YIELD_NOW:return EvaluationSignalYieldNow;case OP_INTERRUPT_SIGNAL:{if(this.processNewInterruptSignal(message.cause),this._asyncInterruptor!==null)this._asyncInterruptor(exitFailCause(message.cause)),this._asyncInterruptor=null;return EvaluationSignalContinue}case OP_RESUME:return this._asyncInterruptor=null,this._asyncBlockingOn=null,this.evaluateEffect(message.effect),EvaluationSignalContinue;case OP_STATEFUL:return message.onFiber(this,this._exitValue!==null?done4:suspended2(this.currentRuntimeFlags,this._asyncBlockingOn)),EvaluationSignalContinue;default:return absurd(message)}}evaluateEffect(effect0){this.currentSupervisor.onResume(this);try{let effect=interruptible(this.currentRuntimeFlags)&&this.isInterrupted()?exitFailCause(this.getInterruptedCause()):effect0;while(effect!==null){let eff=effect,exit2=this.runLoop(eff);if(exit2===YieldedOp){let op=yieldedOpChannel.currentOp;if(yieldedOpChannel.currentOp=null,op._op===OP_YIELD)if(cooperativeYielding(this.currentRuntimeFlags))this.tell(yieldNow3()),this.tell(resume(exitVoid)),effect=null;else effect=exitVoid;else if(op._op===OP_ASYNC)effect=null}else{this.currentRuntimeFlags=pipe(this.currentRuntimeFlags,enable2(WindDown));let interruption2=this.interruptAllChildren();if(interruption2!==null)effect=flatMap8(interruption2,()=>exit2);else{if(this._queue.length===0)this.setExitValue(exit2);else this.tell(resume(exit2));effect=null}}}}finally{this.currentSupervisor.onSuspend(this)}}start(effect){if(!this._running){this._running=!0;let prev=globalThis[currentFiberURI];globalThis[currentFiberURI]=this;try{this.evaluateEffect(effect)}finally{if(this._running=!1,globalThis[currentFiberURI]=prev,this._queue.length>0)this.drainQueueLaterOnExecutor()}}else this.tell(resume(effect))}startFork(effect){this.tell(resume(effect))}patchRuntimeFlags(oldRuntimeFlags,patch12){let newRuntimeFlags=patch7(oldRuntimeFlags,patch12);return globalThis[currentFiberURI]=this,this.currentRuntimeFlags=newRuntimeFlags,newRuntimeFlags}initiateAsync(runtimeFlags2,asyncRegister){let alreadyCalled=!1,callback=(effect)=>{if(!alreadyCalled)alreadyCalled=!0,this.tell(resume(effect))};if(interruptible(runtimeFlags2))this._asyncInterruptor=callback;try{asyncRegister(callback)}catch(e){callback(failCause(die(e)))}}pushStack(cont){if(this._stack.push(cont),cont._op==="OnStep")this._steps.push({refs:this.getFiberRefs(),flags:this.currentRuntimeFlags})}popStack(){let item=this._stack.pop();if(item){if(item._op==="OnStep")this._steps.pop();return item}return}getNextSuccessCont(){let frame=this.popStack();while(frame){if(frame._op!==OP_ON_FAILURE)return frame;frame=this.popStack()}}getNextFailCont(){let frame=this.popStack();while(frame){if(frame._op!==OP_ON_SUCCESS&&frame._op!==OP_WHILE&&frame._op!==OP_ITERATOR)return frame;frame=this.popStack()}}[OP_TAG](op){return sync(()=>unsafeGet3(this.currentContext,op))}["Left"](op){return fail2(op.left)}["None"](_){return fail2(new NoSuchElementException)}["Right"](op){return exitSucceed(op.right)}["Some"](op){return exitSucceed(op.value)}["Micro"](op){return unsafeAsync((microResume)=>{let resume2=microResume,fiber=runFork(provideContext2(op,this.currentContext));return fiber.addObserver((exit2)=>{if(exit2._tag==="Success")return resume2(exitSucceed(exit2.value));switch(exit2.cause._tag){case"Interrupt":return resume2(exitFailCause(interrupt(none4)));case"Fail":return resume2(fail2(exit2.cause.error));case"Die":return resume2(die2(exit2.cause.defect))}}),unsafeAsync((abortResume)=>{resume2=(_)=>{abortResume(void_)},fiber.unsafeInterrupt()})})}[OP_SYNC](op){let value=internalCall(()=>op.effect_instruction_i0()),cont=this.getNextSuccessCont();if(cont!==void 0){if(!(cont._op in contOpSuccess))absurd(cont);return contOpSuccess[cont._op](this,cont,value)}else return yieldedOpChannel.currentOp=exitSucceed(value),YieldedOp}[OP_SUCCESS](op){let oldCur=op,cont=this.getNextSuccessCont();if(cont!==void 0){if(!(cont._op in contOpSuccess))absurd(cont);return contOpSuccess[cont._op](this,cont,oldCur.effect_instruction_i0)}else return yieldedOpChannel.currentOp=oldCur,YieldedOp}[OP_FAILURE](op){let cause2=op.effect_instruction_i0,cont=this.getNextFailCont();if(cont!==void 0)switch(cont._op){case OP_ON_FAILURE:case OP_ON_SUCCESS_AND_FAILURE:if(!(interruptible(this.currentRuntimeFlags)&&this.isInterrupted()))return internalCall(()=>cont.effect_instruction_i1(cause2));else return exitFailCause(stripFailures(cause2));case"OnStep":if(!(interruptible(this.currentRuntimeFlags)&&this.isInterrupted()))return exitSucceed(exitFailCause(cause2));else return exitFailCause(stripFailures(cause2));case OP_REVERT_FLAGS:if(this.patchRuntimeFlags(this.currentRuntimeFlags,cont.patch),interruptible(this.currentRuntimeFlags)&&this.isInterrupted())return exitFailCause(sequential(cause2,this.getInterruptedCause()));else return exitFailCause(cause2);default:absurd(cont)}else return yieldedOpChannel.currentOp=exitFailCause(cause2),YieldedOp}[OP_WITH_RUNTIME](op){return internalCall(()=>op.effect_instruction_i0(this,running2(this.currentRuntimeFlags)))}["Blocked"](op){let refs=this.getFiberRefs(),flags=this.currentRuntimeFlags;if(this._steps.length>0){let frames=[],snap=this._steps[this._steps.length-1],frame=this.popStack();while(frame&&frame._op!=="OnStep")frames.push(frame),frame=this.popStack();this.setFiberRefs(snap.refs),this.currentRuntimeFlags=snap.flags;let patchRefs=diff9(snap.refs,refs),patchFlags=diff7(snap.flags,flags);return exitSucceed(blocked(op.effect_instruction_i0,withFiberRuntime((newFiber)=>{while(frames.length>0)newFiber.pushStack(frames.pop());return newFiber.setFiberRefs(patch10(newFiber.id(),newFiber.getFiberRefs())(patchRefs)),newFiber.currentRuntimeFlags=patch7(patchFlags)(newFiber.currentRuntimeFlags),op.effect_instruction_i1})))}return uninterruptibleMask((restore)=>flatMap8(forkDaemon(runRequestBlock(op.effect_instruction_i0)),()=>restore(op.effect_instruction_i1)))}["RunBlocked"](op){return runBlockedRequests(op.effect_instruction_i0)}[OP_UPDATE_RUNTIME_FLAGS](op){let updateFlags=op.effect_instruction_i0,oldRuntimeFlags=this.currentRuntimeFlags,newRuntimeFlags=patch7(oldRuntimeFlags,updateFlags);if(interruptible(newRuntimeFlags)&&this.isInterrupted())return exitFailCause(this.getInterruptedCause());else if(this.patchRuntimeFlags(this.currentRuntimeFlags,updateFlags),op.effect_instruction_i1){let revertFlags=diff7(newRuntimeFlags,oldRuntimeFlags);return this.pushStack(new RevertFlags(revertFlags,op)),internalCall(()=>op.effect_instruction_i1(oldRuntimeFlags))}else return exitVoid}[OP_ON_SUCCESS](op){return this.pushStack(op),op.effect_instruction_i0}["OnStep"](op){return this.pushStack(op),op.effect_instruction_i0}[OP_ON_FAILURE](op){return this.pushStack(op),op.effect_instruction_i0}[OP_ON_SUCCESS_AND_FAILURE](op){return this.pushStack(op),op.effect_instruction_i0}[OP_ASYNC](op){return this._asyncBlockingOn=op.effect_instruction_i1,this.initiateAsync(this.currentRuntimeFlags,op.effect_instruction_i0),yieldedOpChannel.currentOp=op,YieldedOp}[OP_YIELD](op){return this._isYielding=!1,yieldedOpChannel.currentOp=op,YieldedOp}[OP_WHILE](op){let{effect_instruction_i0:check,effect_instruction_i1:body}=op;if(check())return this.pushStack(op),body();else return exitVoid}[OP_ITERATOR](op){return contOpSuccess[OP_ITERATOR](this,op,void 0)}[OP_COMMIT](op){return internalCall(()=>op.commit())}runLoop(effect0){let cur=effect0;this.currentOpCount=0;while(!0){if((this.currentRuntimeFlags&OpSupervision)!==0)this.currentSupervisor.onEffect(this,cur);if(this._queue.length>0)cur=this.drainQueueWhileRunning(this.currentRuntimeFlags,cur);if(!this._isYielding){this.currentOpCount+=1;let shouldYield=this.currentScheduler.shouldYield(this);if(shouldYield!==!1){this._isYielding=!0,this.currentOpCount=0;let oldCur=cur;cur=flatMap8(yieldNow({priority:shouldYield}),()=>oldCur)}}try{if(cur=this.currentTracer.context(()=>{if(_version!==cur[EffectTypeId2]._V)return dieMessage(`Cannot execute an Effect versioned ${cur[EffectTypeId2]._V} with a Runtime of version ${getCurrentVersion()}`);return this[cur._op](cur)},this),cur===YieldedOp){let op=yieldedOpChannel.currentOp;if(op._op===OP_YIELD||op._op===OP_ASYNC)return YieldedOp;return yieldedOpChannel.currentOp=null,op._op===OP_SUCCESS||op._op===OP_FAILURE?op:exitFailCause(die(op))}}catch(e){if(cur!==YieldedOp&&!hasProperty(cur,"_op")||!(cur._op in this))cur=dieMessage(`Not a valid effect: ${toStringUnknown(cur)}`);else if(isInterruptedException(e))cur=exitFailCause(sequential(die(e),interrupt(none4)));else cur=die2(e)}}}run=()=>{this.drainQueueOnCurrentThread()}}var currentMinimumLogLevel=globalValue("effect/FiberRef/currentMinimumLogLevel",()=>fiberRefUnsafeMake(fromLiteral("Info"))),loggerWithConsoleLog=(self)=>makeLogger((opts)=>{let services=getOrDefault2(opts.context,currentServices);get3(services,consoleTag).unsafe.log(self.log(opts))});var defaultLogger=globalValue(Symbol.for("effect/Logger/defaultLogger"),()=>loggerWithConsoleLog(stringLogger));var tracerLogger=globalValue(Symbol.for("effect/Logger/tracerLogger"),()=>makeLogger(({annotations:annotations2,cause:cause2,context:context2,fiberId:fiberId2,logLevel,message})=>{let span2=getOption2(getOrDefault(context2,currentContext),spanTag);if(span2._tag==="None"||span2.value._tag==="ExternalSpan")return;let clockService=unsafeGet3(getOrDefault(context2,currentServices),clockTag),attributes={};for(let[key,value]of annotations2)attributes[key]=value;if(attributes["effect.fiberId"]=threadName2(fiberId2),attributes["effect.logLevel"]=logLevel.label,cause2!==null&&cause2._tag!=="Empty")attributes["effect.cause"]=pretty(cause2,{renderErrorCause:!0});span2.value.event(toStringUnknown(Array.isArray(message)?message[0]:message),clockService.unsafeCurrentTimeNanos(),attributes)}));var currentLoggers=globalValue(Symbol.for("effect/FiberRef/currentLoggers"),()=>fiberRefUnsafeMakeHashSet(make11(defaultLogger,tracerLogger)));var annotateLogsScoped=function(){if(typeof arguments[0]==="string")return fiberRefLocallyScopedWith(currentLogAnnotations,set3(arguments[0],arguments[1]));let entries2=Object.entries(arguments[0]);return fiberRefLocallyScopedWith(currentLogAnnotations,mutate3((annotations2)=>{for(let i=0;i<entries2.length;i++){let[key,value]=entries2[i];set3(annotations2,key,value)}return annotations2}))},whenLogLevel=dual(2,(effect,level)=>{let requiredLogLevel=typeof level==="string"?fromLiteral(level):level;return withFiberRuntime((fiberState)=>{let minimumLogLevel=fiberState.getFiberRef(currentMinimumLogLevel);if(greaterThan3(minimumLogLevel,requiredLogLevel))return succeed(none2());return map10(effect,some2)})}),acquireRelease=dual((args2)=>isEffect(args2[0]),(acquire,release)=>uninterruptible(tap(acquire,(a)=>addFinalizer((exit2)=>release(a,exit2))))),acquireReleaseInterruptible=dual((args2)=>isEffect(args2[0]),(acquire,release)=>ensuring(acquire,addFinalizer((exit2)=>release(exit2)))),addFinalizer=(finalizer)=>withFiberRuntime((runtime2)=>{let acquireRefs=runtime2.getFiberRefs(),acquireFlags=runtime2.currentRuntimeFlags;return flatMap8(scope,(scope)=>scopeAddFinalizerExit(scope,(exit2)=>withFiberRuntime((runtimeFinalizer)=>{let preRefs=runtimeFinalizer.getFiberRefs(),preFlags=runtimeFinalizer.currentRuntimeFlags,patchRefs=diff9(preRefs,acquireRefs),patchFlags=diff7(preFlags,acquireFlags),inverseRefs=diff9(acquireRefs,preRefs);return runtimeFinalizer.setFiberRefs(patch10(patchRefs,runtimeFinalizer.id(),acquireRefs)),ensuring(withRuntimeFlags(finalizer(exit2),patchFlags),sync(()=>{runtimeFinalizer.setFiberRefs(patch10(inverseRefs,runtimeFinalizer.id(),runtimeFinalizer.getFiberRefs()))}))})))}),daemonChildren=(self)=>{return fiberRefLocally(currentForkScopeOverride,some2(globalScope))(self)},_existsParFound=Symbol.for("effect/Effect/existsPar/found"),exists2=dual((args2)=>isIterable(args2[0])&&!isEffect(args2[0]),(elements,predicate,options)=>matchSimple(options?.concurrency,()=>suspend(()=>existsLoop(elements[Symbol.iterator](),0,predicate)),()=>matchEffect(forEach7(elements,(a,i)=>if_(predicate(a,i),{onTrue:()=>fail2(_existsParFound),onFalse:()=>void_}),options),{onFailure:(e)=>e===_existsParFound?succeed(!0):fail2(e),onSuccess:()=>succeed(!1)}))),existsLoop=(iterator,index,f)=>{let next=iterator.next();if(next.done)return succeed(!1);return pipe(flatMap8(f(next.value,index),(b)=>b?succeed(b):existsLoop(iterator,index+1,f)))},filter6=dual((args2)=>isIterable(args2[0])&&!isEffect(args2[0]),(elements,predicate,options)=>{let predicate_=options?.negate?(a,i)=>map10(predicate(a,i),not):predicate;return matchSimple(options?.concurrency,()=>suspend(()=>fromIterable(elements).reduceRight((effect,a,i)=>zipWith3(effect,suspend(()=>predicate_(a,i)),(list,b)=>b?[a,...list]:list),sync(()=>new Array))),()=>map10(forEach7(elements,(a,i)=>map10(predicate_(a,i),(b)=>b?some2(a):none2()),options),getSomes))}),allResolveInput=(input)=>{if(Array.isArray(input)||isIterable(input))return[input,none2()];let keys5=Object.keys(input),size8=keys5.length;return[keys5.map((k)=>input[k]),some2((values3)=>{let res={};for(let i=0;i<size8;i++)res[keys5[i]]=values3[i];return res})]},allValidate=(effects,reconcile,options)=>{let eitherEffects=[];for(let effect of effects)eitherEffects.push(either2(effect));return flatMap8(forEach7(eitherEffects,identity,{concurrency:options?.concurrency,batching:options?.batching,concurrentFinalizers:options?.concurrentFinalizers}),(eithers)=>{let none9=none2(),size8=eithers.length,errors=new Array(size8),successes=new Array(size8),errored=!1;for(let i=0;i<size8;i++){let either3=eithers[i];if(either3._tag==="Left")errors[i]=some2(either3.left),errored=!0;else successes[i]=either3.right,errors[i]=none9}if(errored)return reconcile._tag==="Some"?fail2(reconcile.value(errors)):fail2(errors);else if(options?.discard)return void_;return reconcile._tag==="Some"?succeed(reconcile.value(successes)):succeed(successes)})},allEither=(effects,reconcile,options)=>{let eitherEffects=[];for(let effect of effects)eitherEffects.push(either2(effect));if(options?.discard)return forEach7(eitherEffects,identity,{concurrency:options?.concurrency,batching:options?.batching,discard:!0,concurrentFinalizers:options?.concurrentFinalizers});return map10(forEach7(eitherEffects,identity,{concurrency:options?.concurrency,batching:options?.batching,concurrentFinalizers:options?.concurrentFinalizers}),(eithers)=>reconcile._tag==="Some"?reconcile.value(eithers):eithers)},all4=(arg,options)=>{let[effects,reconcile]=allResolveInput(arg);if(options?.mode==="validate")return allValidate(effects,reconcile,options);else if(options?.mode==="either")return allEither(effects,reconcile,options);return options?.discard!==!0&&reconcile._tag==="Some"?map10(forEach7(effects,identity,options),reconcile.value):forEach7(effects,identity,options)},allWith=(options)=>(arg)=>all4(arg,options),allSuccesses=(elements,options)=>map10(all4(fromIterable(elements).map(exit),options),filterMap((exit2)=>exitIsSuccess(exit2)?some2(exit2.effect_instruction_i0):none2())),replicate=dual(2,(self,n)=>Array.from({length:n},()=>self)),replicateEffect=dual((args2)=>isEffect(args2[0]),(self,n,options)=>all4(replicate(self,n),options)),forEach7=dual((args2)=>isIterable(args2[0]),(self,f,options)=>withFiberRuntime((r)=>{let isRequestBatchingEnabled=options?.batching===!0||options?.batching==="inherit"&&r.getFiberRef(currentRequestBatching);if(options?.discard)return match9(options.concurrency,()=>finalizersMaskInternal(sequential3,options?.concurrentFinalizers)((restore)=>isRequestBatchingEnabled?forEachConcurrentDiscard(self,(a,i)=>restore(f(a,i)),!0,!1,1):forEachSequentialDiscard(self,(a,i)=>restore(f(a,i)))),()=>finalizersMaskInternal(parallel3,options?.concurrentFinalizers)((restore)=>forEachConcurrentDiscard(self,(a,i)=>restore(f(a,i)),isRequestBatchingEnabled,!1)),(n)=>finalizersMaskInternal(parallelN2(n),options?.concurrentFinalizers)((restore)=>forEachConcurrentDiscard(self,(a,i)=>restore(f(a,i)),isRequestBatchingEnabled,!1,n)));return match9(options?.concurrency,()=>finalizersMaskInternal(sequential3,options?.concurrentFinalizers)((restore)=>isRequestBatchingEnabled?forEachParN(self,1,(a,i)=>restore(f(a,i)),!0):forEachSequential(self,(a,i)=>restore(f(a,i)))),()=>finalizersMaskInternal(parallel3,options?.concurrentFinalizers)((restore)=>forEachParUnbounded(self,(a,i)=>restore(f(a,i)),isRequestBatchingEnabled)),(n)=>finalizersMaskInternal(parallelN2(n),options?.concurrentFinalizers)((restore)=>forEachParN(self,n,(a,i)=>restore(f(a,i)),isRequestBatchingEnabled)))})),forEachParUnbounded=(self,f,batching)=>suspend(()=>{let as2=fromIterable(self),array4=new Array(as2.length);return zipRight(forEachConcurrentDiscard(as2,(a,i)=>flatMap8(f(a,i),(b)=>sync(()=>array4[i]=b)),batching,!1),succeed(array4))}),forEachConcurrentDiscard=(self,f,batching,processAll,n)=>uninterruptibleMask((restore)=>transplant((graft)=>withFiberRuntime((parent)=>{let todos=Array.from(self).reverse(),target=todos.length;if(target===0)return void_;let counter6=0,interrupted2=!1,fibersCount=n?Math.min(todos.length,n):todos.length,fibers=new Set,results=new Array,interruptAll2=()=>fibers.forEach((fiber)=>{fiber.currentScheduler.scheduleTask(()=>{fiber.unsafeInterruptAsFork(parent.id())},0)}),startOrder=new Array,joinOrder=new Array,residual=new Array,collectExits=()=>{let exits=results.filter(({exit:exit2})=>exit2._tag==="Failure").sort((a,b)=>a.index<b.index?-1:a.index===b.index?0:1).map(({exit:exit2})=>exit2);if(exits.length===0)exits.push(exitVoid);return exits},runFiber=(eff,interruptImmediately=!1)=>{let runnable=uninterruptible(graft(eff)),fiber=unsafeForkUnstarted(runnable,parent,parent.currentRuntimeFlags,globalScope);return parent.currentScheduler.scheduleTask(()=>{if(interruptImmediately)fiber.unsafeInterruptAsFork(parent.id());fiber.resume(runnable)},0),fiber},onInterruptSignal=()=>{if(!processAll)target-=todos.length,todos=[];interrupted2=!0,interruptAll2()},stepOrExit=batching?step2:exit,processingFiber=runFiber(async_((resume2)=>{let pushResult=(res,index)=>{if(res._op==="Blocked")residual.push(res);else if(results.push({index,exit:res}),res._op==="Failure"&&!interrupted2)onInterruptSignal()},next=()=>{if(todos.length>0){let a=todos.pop(),index=counter6++,returnNextElement=()=>{let a2=todos.pop();return index=counter6++,flatMap8(yieldNow(),()=>flatMap8(stepOrExit(restore(f(a2,index))),onRes))},onRes=(res)=>{if(todos.length>0){if(pushResult(res,index),todos.length>0)return returnNextElement()}return succeed(res)},todo=flatMap8(stepOrExit(restore(f(a,index))),onRes),fiber=runFiber(todo);if(startOrder.push(fiber),fibers.add(fiber),interrupted2)fiber.currentScheduler.scheduleTask(()=>{fiber.unsafeInterruptAsFork(parent.id())},0);fiber.addObserver((wrapped)=>{let exit2;if(wrapped._op==="Failure")exit2=wrapped;else exit2=wrapped.effect_instruction_i0;if(joinOrder.push(fiber),fibers.delete(fiber),pushResult(exit2,index),results.length===target)resume2(succeed(getOrElse(exitCollectAll(collectExits(),{parallel:!0}),()=>exitVoid)));else if(residual.length+results.length===target){let exits=collectExits(),requests=residual.map((blocked2)=>blocked2.effect_instruction_i0).reduce(par);resume2(succeed(blocked(requests,forEachConcurrentDiscard([getOrElse(exitCollectAll(exits,{parallel:!0}),()=>exitVoid),...residual.map((blocked2)=>blocked2.effect_instruction_i1)],(i)=>i,batching,!0,n))))}else next()})}};for(let i=0;i<fibersCount;i++)next()}));return asVoid(onExit(flatten6(restore(join2(processingFiber))),exitMatch({onFailure:(cause2)=>{onInterruptSignal();let target2=residual.length+1,concurrency=Math.min(typeof n==="number"?n:residual.length,residual.length),toPop=Array.from(residual);return async_((cb)=>{let exits=[],count=0,index=0,check=(index2,hitNext)=>(exit2)=>{if(exits[index2]=exit2,count++,count===target2)cb(exitSucceed(exitFailCause(cause2)));if(toPop.length>0&&hitNext)next()},next=()=>{runFiber(toPop.pop(),!0).addObserver(check(index,!0)),index++};processingFiber.addObserver(check(index,!1)),index++;for(let i=0;i<concurrency;i++)next()})},onSuccess:()=>forEachSequential(joinOrder,(f2)=>f2.inheritAll)})))}))),forEachParN=(self,n,f,batching)=>suspend(()=>{let as2=fromIterable(self),array4=new Array(as2.length);return zipRight(forEachConcurrentDiscard(as2,(a,i)=>map10(f(a,i),(b)=>array4[i]=b),batching,!1,n),succeed(array4))}),fork=(self)=>withFiberRuntime((state,status2)=>succeed(unsafeFork(self,state,status2.runtimeFlags))),forkDaemon=(self)=>forkWithScopeOverride(self,globalScope),forkWithErrorHandler=dual(2,(self,handler)=>fork(onError(self,(cause2)=>{let either3=failureOrCause(cause2);switch(either3._tag){case"Left":return handler(either3.left);case"Right":return failCause(either3.right)}}))),unsafeFork=(effect,parentFiber,parentRuntimeFlags,overrideScope=null)=>{let childFiber=unsafeMakeChildFiber(effect,parentFiber,parentRuntimeFlags,overrideScope);return childFiber.resume(effect),childFiber},unsafeForkUnstarted=(effect,parentFiber,parentRuntimeFlags,overrideScope=null)=>{return unsafeMakeChildFiber(effect,parentFiber,parentRuntimeFlags,overrideScope)},unsafeMakeChildFiber=(effect,parentFiber,parentRuntimeFlags,overrideScope=null)=>{let childId=unsafeMake2(),parentFiberRefs=parentFiber.getFiberRefs(),childFiberRefs=forkAs(parentFiberRefs,childId),childFiber=new FiberRuntime(childId,childFiberRefs,parentRuntimeFlags),childContext=getOrDefault(childFiberRefs,currentContext),supervisor=childFiber.currentSupervisor;return supervisor.onStart(childContext,effect,some2(parentFiber),childFiber),childFiber.addObserver((exit2)=>supervisor.onEnd(exit2,childFiber)),(overrideScope!==null?overrideScope:pipe(parentFiber.getFiberRef(currentForkScopeOverride),getOrElse(()=>parentFiber.scope()))).add(parentRuntimeFlags,childFiber),childFiber},forkWithScopeOverride=(self,scopeOverride)=>withFiberRuntime((parentFiber,parentStatus)=>succeed(unsafeFork(self,parentFiber,parentStatus.runtimeFlags,scopeOverride))),mergeAll2=dual((args2)=>isFunction2(args2[2]),(elements,zero3,f,options)=>matchSimple(options?.concurrency,()=>fromIterable(elements).reduce((acc,a,i)=>zipWith3(acc,a,(acc2,a2)=>f(acc2,a2,i)),succeed(zero3)),()=>flatMap8(make29(zero3),(acc)=>flatMap8(forEach7(elements,(effect,i)=>flatMap8(effect,(a)=>update3(acc,(b)=>f(b,a,i))),options),()=>get12(acc))))),partition3=dual((args2)=>isIterable(args2[0]),(elements,f,options)=>pipe(forEach7(elements,(a,i)=>either2(f(a,i)),options),map10((chunk2)=>partitionMap2(chunk2,identity)))),validateAll=dual((args2)=>isIterable(args2[0]),(elements,f,options)=>flatMap8(partition3(elements,f,{concurrency:options?.concurrency,batching:options?.batching,concurrentFinalizers:options?.concurrentFinalizers}),([es,bs])=>isNonEmptyArray2(es)?fail2(es):options?.discard?void_:succeed(bs))),raceAll=(all5)=>{let list=fromIterable2(all5);if(!isNonEmpty2(list))return dieSync(()=>new IllegalArgumentException("Received an empty collection of effects"));let self=headNonEmpty2(list),effects=tailNonEmpty2(list),inheritAll2=(res)=>pipe(inheritAll(res[1]),as(res[0]));return pipe(deferredMake(),flatMap8((done6)=>pipe(make29(effects.length),flatMap8((fails)=>uninterruptibleMask((restore)=>pipe(fork(interruptible2(self)),flatMap8((head4)=>pipe(effects,forEachSequential((effect)=>fork(interruptible2(effect))),map10((fibers)=>unsafeFromArray(fibers)),map10((tail)=>pipe(tail,prepend2(head4))),tap((fibers)=>pipe(fibers,reduce(void_,(effect,fiber)=>pipe(effect,zipRight(pipe(_await2(fiber),flatMap8(raceAllArbiter(fibers,fiber,done6,fails)),fork,asVoid)))))),flatMap8((fibers)=>pipe(restore(pipe(_await(done6),flatMap8(inheritAll2))),onInterrupt(()=>pipe(fibers,reduce(void_,(effect,fiber)=>pipe(effect,zipLeft(interruptFiber(fiber))))))))))))))))},raceAllArbiter=(fibers,winner,deferred,fails)=>(exit2)=>exitMatchEffect(exit2,{onFailure:(cause2)=>pipe(modify3(fails,(fails2)=>[fails2===0?pipe(deferredFailCause(deferred,cause2),asVoid):void_,fails2-1]),flatten6),onSuccess:(value)=>pipe(deferredSucceed(deferred,[value,winner]),flatMap8((set7)=>set7?pipe(fromIterable2(fibers),reduce(void_,(effect,fiber)=>fiber===winner?effect:pipe(effect,zipLeft(interruptFiber(fiber))))):void_))}),reduceEffect=dual((args2)=>isIterable(args2[0])&&!isEffect(args2[0]),(elements,zero3,f,options)=>matchSimple(options?.concurrency,()=>fromIterable(elements).reduce((acc,a,i)=>zipWith3(acc,a,(acc2,a2)=>f(acc2,a2,i)),zero3),()=>suspend(()=>pipe(mergeAll2([zero3,...elements],none2(),(acc,elem,i)=>{switch(acc._tag){case"None":return some2(elem);case"Some":return some2(f(acc.value,elem,i))}},options),map10((option2)=>{switch(option2._tag){case"None":throw new Error("BUG: Effect.reduceEffect - please report an issue at https://github.com/Effect-TS/effect/issues");case"Some":return option2.value}}))))),parallelFinalizers=(self)=>contextWithEffect((context2)=>match2(getOption2(context2,scopeTag),{onNone:()=>self,onSome:(scope)=>{switch(scope.strategy._tag){case"Parallel":return self;case"Sequential":case"ParallelN":return flatMap8(scopeFork(scope,parallel3),(inner)=>scopeExtend(self,inner))}}})),parallelNFinalizers=(parallelism)=>(self)=>contextWithEffect((context2)=>match2(getOption2(context2,scopeTag),{onNone:()=>self,onSome:(scope)=>{if(scope.strategy._tag==="ParallelN"&&scope.strategy.parallelism===parallelism)return self;return flatMap8(scopeFork(scope,parallelN2(parallelism)),(inner)=>scopeExtend(self,inner))}})),finalizersMask=(strategy)=>(self)=>finalizersMaskInternal(strategy,!0)(self),finalizersMaskInternal=(strategy,concurrentFinalizers)=>(self)=>contextWithEffect((context2)=>match2(getOption2(context2,scopeTag),{onNone:()=>self(identity),onSome:(scope)=>{if(concurrentFinalizers===!0){let patch12=strategy._tag==="Parallel"?parallelFinalizers:strategy._tag==="Sequential"?sequentialFinalizers:parallelNFinalizers(strategy.parallelism);switch(scope.strategy._tag){case"Parallel":return patch12(self(parallelFinalizers));case"Sequential":return patch12(self(sequentialFinalizers));case"ParallelN":return patch12(self(parallelNFinalizers(scope.strategy.parallelism)))}}else return self(identity)}})),scopeWith=(f)=>flatMap8(scopeTag,f),scopedWith=(f)=>flatMap8(scopeMake(),(scope)=>onExit(f(scope),(exit2)=>scope.close(exit2))),scopedEffect=(effect)=>flatMap8(scopeMake(),(scope)=>scopeUse(effect,scope)),sequentialFinalizers=(self)=>contextWithEffect((context2)=>match2(getOption2(context2,scopeTag),{onNone:()=>self,onSome:(scope)=>{switch(scope.strategy._tag){case"Sequential":return self;case"Parallel":case"ParallelN":return flatMap8(scopeFork(scope,sequential3),(inner)=>scopeExtend(self,inner))}}})),tagMetricsScoped=(key,value)=>labelMetricsScoped([make30(key,value)]),labelMetricsScoped=(labels)=>fiberRefLocallyScopedWith(currentMetricLabels,(old)=>union(old,labels)),using=dual(2,(self,use)=>scopedWith((scope)=>flatMap8(scopeExtend(self,scope),use))),validate=dual((args2)=>isEffect(args2[1]),(self,that,options)=>validateWith(self,that,(a,b)=>[a,b],options)),validateWith=dual((args2)=>isEffect(args2[1]),(self,that,f,options)=>flatten6(zipWithOptions(exit(self),exit(that),(ea,eb)=>exitZipWith(ea,eb,{onSuccess:f,onFailure:(ca,cb)=>options?.concurrent?parallel(ca,cb):sequential(ca,cb)}),options)));var validateFirst=dual((args2)=>isIterable(args2[0]),(elements,f,options)=>flip(forEach7(elements,(a,i)=>flip(f(a,i)),options))),withClockScoped=(c)=>fiberRefLocallyScopedWith(currentServices,add2(clockTag,c)),withRandomScoped=(value)=>fiberRefLocallyScopedWith(currentServices,add2(randomTag,value)),withConfigProviderScoped=(provider)=>fiberRefLocallyScopedWith(currentServices,add2(configProviderTag,provider)),withEarlyRelease=(self)=>scopeWith((parent)=>flatMap8(scopeFork(parent,sequential2),(child)=>pipe(self,scopeExtend(child),map10((value)=>[fiberIdWith((fiberId2)=>scopeClose(child,exitInterrupt(fiberId2))),value])))),zipOptions=dual((args2)=>isEffect(args2[1]),(self,that,options)=>zipWithOptions(self,that,(a,b)=>[a,b],options)),zipLeftOptions=dual((args2)=>isEffect(args2[1]),(self,that,options)=>{if(options?.concurrent!==!0&&(options?.batching===void 0||options.batching===!1))return zipLeft(self,that);return zipWithOptions(self,that,(a,_)=>a,options)}),zipRightOptions=dual((args2)=>isEffect(args2[1]),(self,that,options)=>{if(options?.concurrent!==!0&&(options?.batching===void 0||options.batching===!1))return zipRight(self,that);return zipWithOptions(self,that,(_,b)=>b,options)}),zipWithOptions=dual((args2)=>isEffect(args2[1]),(self,that,f,options)=>map10(all4([self,that],{concurrency:options?.concurrent?2:1,batching:options?.batching,concurrentFinalizers:options?.concurrentFinalizers}),([a,a2])=>f(a,a2))),withRuntimeFlagsScoped=(update5)=>{if(update5===empty18)return void_;return pipe(runtimeFlags,flatMap8((runtimeFlags2)=>{let updatedRuntimeFlags=patch7(runtimeFlags2,update5),revertRuntimeFlags=diff7(updatedRuntimeFlags,runtimeFlags2);return pipe(updateRuntimeFlags(update5),zipRight(addFinalizer(()=>updateRuntimeFlags(revertRuntimeFlags))),asVoid)}),uninterruptible)},scopeTag=GenericTag("effect/Scope"),scope=scopeTag,scopeUnsafeAddFinalizer=(scope2,fin)=>{if(scope2.state._tag==="Open")scope2.state.finalizers.set({},fin)},ScopeImplProto={[ScopeTypeId]:ScopeTypeId,[CloseableScopeTypeId]:CloseableScopeTypeId,pipe(){return pipeArguments(this,arguments)},fork(strategy){return sync(()=>{let newScope=scopeUnsafeMake(strategy);if(this.state._tag==="Closed")return newScope.state=this.state,newScope;let key={},fin=(exit2)=>newScope.close(exit2);return this.state.finalizers.set(key,fin),scopeUnsafeAddFinalizer(newScope,(_)=>sync(()=>{if(this.state._tag==="Open")this.state.finalizers.delete(key)})),newScope})},close(exit2){return suspend(()=>{if(this.state._tag==="Closed")return void_;let finalizers=Array.from(this.state.finalizers.values()).reverse();if(this.state={_tag:"Closed",exit:exit2},finalizers.length===0)return void_;return isSequential(this.strategy)?pipe(forEachSequential(finalizers,(fin)=>exit(fin(exit2))),flatMap8((results)=>pipe(exitCollectAll(results),map2(exitAsVoid),getOrElse(()=>exitVoid)))):isParallel(this.strategy)?pipe(forEachParUnbounded(finalizers,(fin)=>exit(fin(exit2)),!1),flatMap8((results)=>pipe(exitCollectAll(results,{parallel:!0}),map2(exitAsVoid),getOrElse(()=>exitVoid)))):pipe(forEachParN(finalizers,this.strategy.parallelism,(fin)=>exit(fin(exit2)),!1),flatMap8((results)=>pipe(exitCollectAll(results,{parallel:!0}),map2(exitAsVoid),getOrElse(()=>exitVoid))))})},addFinalizer(fin){return suspend(()=>{if(this.state._tag==="Closed")return fin(this.state.exit);return this.state.finalizers.set({},fin),void_})}},scopeUnsafeMake=(strategy=sequential2)=>{let scope2=Object.create(ScopeImplProto);return scope2.strategy=strategy,scope2.state={_tag:"Open",finalizers:new Map},scope2},scopeMake=(strategy=sequential2)=>sync(()=>scopeUnsafeMake(strategy)),scopeExtend=dual(2,(effect,scope2)=>mapInputContext(effect,merge3(make6(scopeTag,scope2)))),scopeUse=dual(2,(effect,scope2)=>pipe(effect,scopeExtend(scope2),onExit((exit2)=>scope2.close(exit2)))),fiberRefUnsafeMakeSupervisor=(initial)=>fiberRefUnsafeMakePatch(initial,{differ:differ2,fork:empty29}),fiberRefLocallyScoped=dual(2,(self,value)=>asVoid(acquireRelease(flatMap8(fiberRefGet(self),(oldValue)=>as(fiberRefSet(self,value),oldValue)),(oldValue)=>fiberRefSet(self,oldValue)))),fiberRefLocallyScopedWith=dual(2,(self,f)=>fiberRefGetWith(self,(a)=>fiberRefLocallyScoped(self,f(a))));var currentRuntimeFlags=fiberRefUnsafeMakeRuntimeFlags(none5),currentSupervisor=fiberRefUnsafeMakeSupervisor(none8),fiberAwaitAll=(fibers)=>forEach7(fibers,_await2),fiberAll=(fibers)=>{return{...CommitPrototype2,commit(){return join2(this)},[FiberTypeId]:fiberVariance2,id:()=>fromIterable(fibers).reduce((id2,fiber)=>combine3(id2,fiber.id()),none4),await:exit(forEachParUnbounded(fibers,(fiber)=>flatten6(fiber.await),!1)),children:map10(forEachParUnbounded(fibers,(fiber)=>fiber.children,!1),flatten),inheritAll:forEachSequentialDiscard(fibers,(fiber)=>fiber.inheritAll),poll:map10(forEachSequential(fibers,(fiber)=>fiber.poll),reduceRight(some2(exitSucceed(new Array)),(optionB,optionA)=>{switch(optionA._tag){case"None":return none2();case"Some":switch(optionB._tag){case"None":return none2();case"Some":return some2(exitZipWith(optionA.value,optionB.value,{onSuccess:(a,chunk2)=>[a,...chunk2],onFailure:parallel}))}}})),interruptAsFork:(fiberId2)=>forEachSequentialDiscard(fibers,(fiber)=>fiber.interruptAsFork(fiberId2))}},fiberInterruptFork=(self)=>asVoid(forkDaemon(interruptFiber(self))),fiberJoinAll=(fibers)=>join2(fiberAll(fibers)),fiberScoped=(self)=>acquireRelease(succeed(self),interruptFiber),raceWith=dual(3,(self,other,options)=>raceFibersWith(self,other,{onSelfWin:(winner,loser)=>flatMap8(winner.await,(exit2)=>{switch(exit2._tag){case OP_SUCCESS:return flatMap8(winner.inheritAll,()=>options.onSelfDone(exit2,loser));case OP_FAILURE:return options.onSelfDone(exit2,loser)}}),onOtherWin:(winner,loser)=>flatMap8(winner.await,(exit2)=>{switch(exit2._tag){case OP_SUCCESS:return flatMap8(winner.inheritAll,()=>options.onOtherDone(exit2,loser));case OP_FAILURE:return options.onOtherDone(exit2,loser)}})})),disconnect=(self)=>uninterruptibleMask((restore)=>fiberIdWith((fiberId2)=>flatMap8(forkDaemon(restore(self)),(fiber)=>pipe(restore(join2(fiber)),onInterrupt(()=>pipe(fiber,interruptAsFork(fiberId2))))))),race=dual(2,(self,that)=>fiberIdWith((parentFiberId)=>raceWith(self,that,{onSelfDone:(exit2,right3)=>exitMatchEffect(exit2,{onFailure:(cause2)=>pipe(join2(right3),mapErrorCause((cause22)=>parallel(cause2,cause22))),onSuccess:(value)=>pipe(right3,interruptAsFiber(parentFiberId),as(value))}),onOtherDone:(exit2,left3)=>exitMatchEffect(exit2,{onFailure:(cause2)=>pipe(join2(left3),mapErrorCause((cause22)=>parallel(cause22,cause2))),onSuccess:(value)=>pipe(left3,interruptAsFiber(parentFiberId),as(value))})}))),raceFibersWith=dual(3,(self,other,options)=>withFiberRuntime((parentFiber,parentStatus)=>{let parentRuntimeFlags=parentStatus.runtimeFlags,raceIndicator=make12(!0),leftFiber=unsafeMakeChildFiber(self,parentFiber,parentRuntimeFlags,options.selfScope),rightFiber=unsafeMakeChildFiber(other,parentFiber,parentRuntimeFlags,options.otherScope);return async_((cb)=>{leftFiber.addObserver(()=>completeRace(leftFiber,rightFiber,options.onSelfWin,raceIndicator,cb)),rightFiber.addObserver(()=>completeRace(rightFiber,leftFiber,options.onOtherWin,raceIndicator,cb)),leftFiber.startFork(self),rightFiber.startFork(other)},combine3(leftFiber.id(),rightFiber.id()))})),completeRace=(winner,loser,cont,ab,cb)=>{if(compareAndSet(!0,!1)(ab))cb(cont(winner,loser))},ensuring=dual(2,(self,finalizer)=>uninterruptibleMask((restore)=>matchCauseEffect(restore(self),{onFailure:(cause1)=>matchCauseEffect(finalizer,{onFailure:(cause2)=>failCause(sequential(cause1,cause2)),onSuccess:()=>failCause(cause1)}),onSuccess:(a)=>as(finalizer,a)}))),invokeWithInterrupt=(self,entries2,onInterrupt2)=>fiberIdWith((id2)=>flatMap8(flatMap8(forkDaemon(interruptible2(self)),(processing)=>async_((cb)=>{let counts=entries2.map((_)=>_.listeners.count),checkDone=()=>{if(counts.every((count)=>count===0)){if(entries2.every((_)=>{if(_.result.state.current._tag==="Pending")return!0;else if(_.result.state.current._tag==="Done"&&exitIsExit(_.result.state.current.effect)&&_.result.state.current.effect._tag==="Failure"&&isInterrupted(_.result.state.current.effect.cause))return!0;else return!1}))cleanup.forEach((f)=>f()),onInterrupt2?.(),cb(interruptFiber(processing))}};processing.addObserver((exit2)=>{cleanup.forEach((f)=>f()),cb(exit2)});let cleanup=entries2.map((r,i)=>{let observer=(count)=>{counts[i]=count,checkDone()};return r.listeners.addObserver(observer),()=>r.listeners.removeObserver(observer)});return checkDone(),sync(()=>{cleanup.forEach((f)=>f())})})),()=>suspend(()=>{let residual=entries2.flatMap((entry)=>{if(!entry.state.completed)return[entry];return[]});return forEachSequentialDiscard(residual,(entry)=>complete(entry.request,exitInterrupt(id2)))})));var makeSpanScoped=(name,options)=>{return options=addSpanStackTrace(options),uninterruptible(withFiberRuntime((fiber)=>{let scope2=unsafeGet3(fiber.getFiberRef(currentContext),scopeTag),span2=unsafeMakeSpan(fiber,name,options),timingEnabled=fiber.getFiberRef(currentTracerTimingEnabled),clock_=get3(fiber.getFiberRef(currentServices),clockTag);return as(scopeAddFinalizerExit(scope2,(exit2)=>endSpan(span2,exit2,clock_,timingEnabled)),span2)}))},withTracerScoped=(value)=>fiberRefLocallyScopedWith(currentServices,add2(tracerTag,value)),withSpanScoped=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 flatMap8(makeSpanScoped(name,addSpanStackTrace(options)),(span2)=>provideService(self,spanTag,span2))}return(self)=>flatMap8(makeSpanScoped(name,addSpanStackTrace(options)),(span2)=>provideService(self,spanTag,span2))};var complete2=(key,exit2,entryStats,timeToLiveMillis)=>struct({_tag:"Complete",key,exit:exit2,entryStats,timeToLiveMillis}),pending2=(key,deferred)=>struct({_tag:"Pending",key,deferred}),refreshing=(deferred,complete3)=>struct({_tag:"Refreshing",deferred,complete:complete3}),MapKeyTypeId=Symbol.for("effect/Cache/MapKey");class MapKeyImpl{current;[MapKeyTypeId]=MapKeyTypeId;previous=void 0;next=void 0;constructor(current){this.current=current}[symbol](){return pipe(hash(this.current),combine(hash(this.previous)),combine(hash(this.next)),cached(this))}[symbol2](that){if(this===that)return!0;return isMapKey(that)&&equals(this.current,that.current)&&equals(this.previous,that.previous)&&equals(this.next,that.next)}}var makeMapKey=(current)=>new MapKeyImpl(current),isMapKey=(u)=>hasProperty(u,MapKeyTypeId);class KeySetImpl{head=void 0;tail=void 0;add(key){if(key!==this.tail)if(this.tail===void 0)this.head=key,this.tail=key;else{let{previous,next}=key;if(next!==void 0)if(key.next=void 0,previous!==void 0)previous.next=next,next.previous=previous;else this.head=next,this.head.previous=void 0;this.tail.next=key,key.previous=this.tail,this.tail=key}}remove(){let key=this.head;if(key!==void 0){let next=key.next;if(next!==void 0)key.next=void 0,this.head=next,this.head.previous=void 0;else this.head=void 0,this.tail=void 0}return key}}var makeKeySet=()=>new KeySetImpl,makeCacheState=(map13,keys5,accesses,updating,hits,misses)=>({map:map13,keys:keys5,accesses,updating,hits,misses}),initialCacheState=()=>makeCacheState(empty21(),makeKeySet(),unbounded(),make12(!1),0,0),CacheSymbolKey="effect/Cache",CacheTypeId=Symbol.for(CacheSymbolKey),cacheVariance={_Key:(_)=>_,_Error:(_)=>_,_Value:(_)=>_},ConsumerCacheSymbolKey="effect/ConsumerCache",ConsumerCacheTypeId=Symbol.for(ConsumerCacheSymbolKey),consumerCacheVariance={_Key:(_)=>_,_Error:(_)=>_,_Value:(_)=>_},makeCacheStats=(options)=>options,makeEntryStats=(loadedMillis)=>({loadedMillis});class CacheImpl{capacity;context;fiberId;lookup;timeToLive;[CacheTypeId]=cacheVariance;[ConsumerCacheTypeId]=consumerCacheVariance;cacheState;constructor(capacity2,context2,fiberId2,lookup,timeToLive){this.capacity=capacity2,this.context=context2,this.fiberId=fiberId2,this.lookup=lookup,this.timeToLive=timeToLive,this.cacheState=initialCacheState()}get(key){return map10(this.getEither(key),merge)}get cacheStats(){return sync(()=>makeCacheStats({hits:this.cacheState.hits,misses:this.cacheState.misses,size:size4(this.cacheState.map)}))}getOption(key){return suspend(()=>match2(get8(this.cacheState.map,key),{onNone:()=>{let mapKey=makeMapKey(key);return this.trackAccess(mapKey),this.trackMiss(),succeed(none2())},onSome:(value)=>this.resolveMapValue(value)}))}getOptionComplete(key){return suspend(()=>match2(get8(this.cacheState.map,key),{onNone:()=>{let mapKey=makeMapKey(key);return this.trackAccess(mapKey),this.trackMiss(),succeed(none2())},onSome:(value)=>this.resolveMapValue(value,!0)}))}contains(key){return sync(()=>has4(this.cacheState.map,key))}entryStats(key){return sync(()=>{let option2=get8(this.cacheState.map,key);if(isSome2(option2))switch(option2.value._tag){case"Complete":{let loaded=option2.value.entryStats.loadedMillis;return some2(makeEntryStats(loaded))}case"Pending":return none2();case"Refreshing":{let loaded=option2.value.complete.entryStats.loadedMillis;return some2(makeEntryStats(loaded))}}return none2()})}getEither(key){return suspend(()=>{let k=key,mapKey=void 0,deferred=void 0,value=getOrUndefined(get8(this.cacheState.map,k));if(value===void 0)if(deferred=unsafeMake3(this.fiberId),mapKey=makeMapKey(k),has4(this.cacheState.map,k))value=getOrUndefined(get8(this.cacheState.map,k));else set4(this.cacheState.map,k,pending2(mapKey,deferred));if(value===void 0)return this.trackAccess(mapKey),this.trackMiss(),map10(this.lookupValueOf(key,deferred),right2);else return flatMap8(this.resolveMapValue(value),match2({onNone:()=>this.getEither(key),onSome:(value2)=>succeed(left2(value2))}))})}invalidate(key){return sync(()=>{remove6(this.cacheState.map,key)})}invalidateWhen(key,when2){return sync(()=>{let value=get8(this.cacheState.map,key);if(isSome2(value)&&value.value._tag==="Complete"){if(value.value.exit._tag==="Success"){if(when2(value.value.exit.value))remove6(this.cacheState.map,key)}}})}get invalidateAll(){return sync(()=>{this.cacheState.map=empty21()})}refresh(key){return clockWith3((clock2)=>suspend(()=>{let k=key,deferred=unsafeMake3(this.fiberId),value=getOrUndefined(get8(this.cacheState.map,k));if(value===void 0)if(has4(this.cacheState.map,k))value=getOrUndefined(get8(this.cacheState.map,k));else set4(this.cacheState.map,k,pending2(makeMapKey(k),deferred));if(value===void 0)return asVoid(this.lookupValueOf(key,deferred));else switch(value._tag){case"Complete":{if(this.hasExpired(clock2,value.timeToLiveMillis)){let found=getOrUndefined(get8(this.cacheState.map,k));if(equals(found,value))remove6(this.cacheState.map,k);return asVoid(this.get(key))}return pipe(this.lookupValueOf(key,deferred),when(()=>{let current=getOrUndefined(get8(this.cacheState.map,k));if(equals(current,value)){let mapValue=refreshing(deferred,value);return set4(this.cacheState.map,k,mapValue),!0}return!1}),asVoid)}case"Pending":return _await(value.deferred);case"Refreshing":return _await(value.deferred)}}))}set(key,value){return clockWith3((clock2)=>sync(()=>{let now=clock2.unsafeCurrentTimeMillis(),k=key,lookupResult=succeed3(value),mapValue=complete2(makeMapKey(k),lookupResult,makeEntryStats(now),now+toMillis(decode(this.timeToLive(lookupResult))));set4(this.cacheState.map,k,mapValue)}))}get size(){return sync(()=>{return size4(this.cacheState.map)})}get values(){return sync(()=>{let values3=[];for(let entry of this.cacheState.map)if(entry[1]._tag==="Complete"&&entry[1].exit._tag==="Success")values3.push(entry[1].exit.value);return values3})}get entries(){return sync(()=>{let values3=[];for(let entry of this.cacheState.map)if(entry[1]._tag==="Complete"&&entry[1].exit._tag==="Success")values3.push([entry[0],entry[1].exit.value]);return values3})}get keys(){return sync(()=>{let keys5=[];for(let entry of this.cacheState.map)if(entry[1]._tag==="Complete"&&entry[1].exit._tag==="Success")keys5.push(entry[0]);return keys5})}resolveMapValue(value,ignorePending=!1){return clockWith3((clock2)=>{switch(value._tag){case"Complete":{if(this.trackAccess(value.key),this.hasExpired(clock2,value.timeToLiveMillis))return remove6(this.cacheState.map,value.key.current),succeed(none2());return this.trackHit(),map10(value.exit,some2)}case"Pending":{if(this.trackAccess(value.key),this.trackHit(),ignorePending)return succeed(none2());return map10(_await(value.deferred),some2)}case"Refreshing":{if(this.trackAccess(value.complete.key),this.trackHit(),this.hasExpired(clock2,value.complete.timeToLiveMillis)){if(ignorePending)return succeed(none2());return map10(_await(value.deferred),some2)}return map10(value.complete.exit,some2)}}})}trackHit(){this.cacheState.hits=this.cacheState.hits+1}trackMiss(){this.cacheState.misses=this.cacheState.misses+1}trackAccess(key){if(offer(this.cacheState.accesses,key),compareAndSet(this.cacheState.updating,!1,!0)){let loop2=!0;while(loop2){let key2=poll2(this.cacheState.accesses,EmptyMutableQueue);if(key2===EmptyMutableQueue)loop2=!1;else this.cacheState.keys.add(key2)}let size8=size4(this.cacheState.map);loop2=size8>this.capacity;while(loop2){let key2=this.cacheState.keys.remove();if(key2!==void 0){if(has4(this.cacheState.map,key2.current))remove6(this.cacheState.map,key2.current),size8=size8-1,loop2=size8>this.capacity}else loop2=!1}set2(this.cacheState.updating,!1)}}hasExpired(clock2,timeToLiveMillis){return clock2.unsafeCurrentTimeMillis()>timeToLiveMillis}lookupValueOf(input,deferred){return clockWith3((clock2)=>suspend(()=>{let key=input;return pipe(this.lookup(input),provideContext(this.context),exit,flatMap8((exit2)=>{let now=clock2.unsafeCurrentTimeMillis(),stats=makeEntryStats(now),value=complete2(makeMapKey(key),exit2,stats,now+toMillis(decode(this.timeToLive(exit2))));return set4(this.cacheState.map,key,value),zipRight(done2(deferred,exit2),exit2)}),onInterrupt(()=>zipRight(interrupt3(deferred),sync(()=>{remove6(this.cacheState.map,key)}))))}))}}var unsafeMakeWith=(capacity2,lookup,timeToLive)=>new CacheImpl(capacity2,empty4(),none3,lookup,(exit2)=>decode(timeToLive(exit2)));var fail6=fail,die4=die,interrupt5=interrupt;var isFailType2=isFailType,isDieType2=isDieType;var isInterrupted2=isInterrupted,isInterruptedOnly2=isInterruptedOnly;var interruptors2=interruptors;var failureOrCause2=failureOrCause,flipCauseOption2=flipCauseOption;var map13=map9;var squash=causeSquash;var IllegalArgumentException2=IllegalArgumentException;var NoSuchElementException2=NoSuchElementException;var RuntimeException2=RuntimeException,isRuntimeException2=isRuntimeException;var pretty3=pretty;var exports_Effect={};__export(exports_Effect,{zipWith:()=>zipWith8,zipRight:()=>zipRight4,zipLeft:()=>zipLeft3,zip:()=>zip6,yieldNow:()=>yieldNow4,withUnhandledErrorLogLevel:()=>withUnhandledErrorLogLevel2,withTracerTiming:()=>withTracerTiming2,withTracerScoped:()=>withTracerScoped2,withTracerEnabled:()=>withTracerEnabled2,withTracer:()=>withTracer2,withSpanScoped:()=>withSpanScoped2,withSpan:()=>withSpan2,withSchedulingPriority:()=>withSchedulingPriority2,withScheduler:()=>withScheduler2,withRuntimeFlagsPatchScoped:()=>withRuntimeFlagsPatchScoped,withRuntimeFlagsPatch:()=>withRuntimeFlagsPatch,withRequestCaching:()=>withRequestCaching2,withRequestCache:()=>withRequestCache2,withRequestBatching:()=>withRequestBatching2,withRandomScoped:()=>withRandomScoped2,withRandom:()=>withRandom2,withParentSpan:()=>withParentSpan2,withMetric:()=>withMetric2,withMaxOpsBeforeYield:()=>withMaxOpsBeforeYield2,withLogSpan:()=>withLogSpan2,withFiberRuntime:()=>withFiberRuntime2,withEarlyRelease:()=>withEarlyRelease2,withConsoleScoped:()=>withConsoleScoped2,withConsole:()=>withConsole2,withConfigProviderScoped:()=>withConfigProviderScoped2,withConfigProvider:()=>withConfigProvider2,withConcurrency:()=>withConcurrency2,withClockScoped:()=>withClockScoped2,withClock:()=>withClock2,whileLoop:()=>whileLoop2,whenRef:()=>whenRef2,whenLogLevel:()=>whenLogLevel2,whenFiberRef:()=>whenFiberRef2,whenEffect:()=>whenEffect2,when:()=>when2,void:()=>_void,validateWith:()=>validateWith2,validateFirst:()=>validateFirst2,validateAll:()=>validateAll2,validate:()=>validate2,using:()=>using2,useSpan:()=>useSpan2,updateService:()=>updateService2,updateFiberRefs:()=>updateFiberRefs2,unsandbox:()=>unsandbox2,unsafeMakeSemaphore:()=>unsafeMakeSemaphore2,unsafeMakeLatch:()=>unsafeMakeLatch2,unlessEffect:()=>unlessEffect2,unless:()=>unless2,uninterruptibleMask:()=>uninterruptibleMask3,uninterruptible:()=>uninterruptible2,tryPromise:()=>tryPromise2,tryMapPromise:()=>tryMapPromise2,tryMap:()=>tryMap2,try:()=>try_2,transposeOption:()=>transposeOption,transposeMapOption:()=>transposeMapOption,transplant:()=>transplant2,tracerWith:()=>tracerWith4,tracer:()=>tracer2,timeoutTo:()=>timeoutTo2,timeoutOption:()=>timeoutOption2,timeoutFailCause:()=>timeoutFailCause2,timeoutFail:()=>timeoutFail2,timeout:()=>timeout2,timedWith:()=>timedWith2,timed:()=>timed2,tapErrorTag:()=>tapErrorTag2,tapErrorCause:()=>tapErrorCause2,tapError:()=>tapError2,tapDefect:()=>tapDefect2,tapBoth:()=>tapBoth2,tap:()=>tap2,takeWhile:()=>takeWhile3,takeUntil:()=>takeUntil2,tagMetricsScoped:()=>tagMetricsScoped2,tagMetrics:()=>tagMetrics2,sync:()=>sync3,suspend:()=>suspend3,supervised:()=>supervised2,summarized:()=>summarized2,succeedSome:()=>succeedSome2,succeedNone:()=>succeedNone2,succeed:()=>succeed9,step:()=>step3,spanLinks:()=>spanLinks2,spanAnnotations:()=>spanAnnotations2,sleep:()=>sleep4,setFiberRefs:()=>setFiberRefs2,serviceOptional:()=>serviceOptional2,serviceOption:()=>serviceOption2,serviceMembers:()=>serviceMembers2,serviceFunctions:()=>serviceFunctions2,serviceFunctionEffect:()=>serviceFunctionEffect2,serviceFunction:()=>serviceFunction2,serviceConstants:()=>serviceConstants2,sequentialFinalizers:()=>sequentialFinalizers2,scopedWith:()=>scopedWith2,scoped:()=>scoped3,scopeWith:()=>scopeWith2,scope:()=>scope2,scheduleFrom:()=>scheduleFrom,scheduleForked:()=>scheduleForked2,schedule:()=>schedule,sandbox:()=>sandbox2,runtime:()=>runtime3,runSyncExit:()=>runSyncExit,runSync:()=>runSync,runRequestBlock:()=>runRequestBlock2,runPromiseExit:()=>runPromiseExit,runPromise:()=>runPromise,runFork:()=>runFork2,runCallback:()=>runCallback,retryOrElse:()=>retryOrElse,retry:()=>retry,request:()=>request,replicateEffect:()=>replicateEffect2,replicate:()=>replicate2,repeatOrElse:()=>repeatOrElse,repeatN:()=>repeatN2,repeat:()=>repeat,reduceWhile:()=>reduceWhile2,reduceRight:()=>reduceRight4,reduceEffect:()=>reduceEffect2,reduce:()=>reduce13,randomWith:()=>randomWith2,random:()=>random3,raceWith:()=>raceWith2,raceFirst:()=>raceFirst2,raceAll:()=>raceAll2,race:()=>race2,provideServiceEffect:()=>provideServiceEffect2,provideService:()=>provideService2,provide:()=>provide2,promise:()=>promise2,patchRuntimeFlags:()=>patchRuntimeFlags,patchFiberRefs:()=>patchFiberRefs2,partition:()=>partition4,parallelFinalizers:()=>parallelFinalizers2,parallelErrors:()=>parallelErrors2,orElseSucceed:()=>orElseSucceed2,orElseFail:()=>orElseFail2,orElse:()=>orElse5,orDieWith:()=>orDieWith2,orDie:()=>orDie2,optionFromOptional:()=>optionFromOptional2,option:()=>option2,once:()=>once2,onInterrupt:()=>onInterrupt2,onExit:()=>onExit3,onError:()=>onError2,none:()=>none9,never:()=>never4,negate:()=>negate2,metricLabels:()=>metricLabels2,mergeAll:()=>mergeAll4,merge:()=>merge7,matchEffect:()=>matchEffect2,matchCauseEffect:()=>matchCauseEffect3,matchCause:()=>matchCause2,match:()=>match13,mapInputContext:()=>mapInputContext2,mapErrorCause:()=>mapErrorCause2,mapError:()=>mapError2,mapBoth:()=>mapBoth3,mapAccum:()=>mapAccum4,map:()=>map16,makeSpanScoped:()=>makeSpanScoped2,makeSpan:()=>makeSpan2,makeSemaphore:()=>makeSemaphore2,makeLatch:()=>makeLatch2,loop:()=>loop2,logWithLevel:()=>logWithLevel2,logWarning:()=>logWarning2,logTrace:()=>logTrace2,logInfo:()=>logInfo2,logFatal:()=>logFatal2,logError:()=>logError2,logDebug:()=>logDebug2,logAnnotations:()=>logAnnotations2,log:()=>log2,locallyWith:()=>locallyWith,locallyScopedWith:()=>locallyScopedWith,locallyScoped:()=>locallyScoped,locally:()=>locally,linkSpans:()=>linkSpans2,linkSpanCurrent:()=>linkSpanCurrent2,liftPredicate:()=>liftPredicate2,let:()=>let_3,labelMetricsScoped:()=>labelMetricsScoped2,labelMetrics:()=>labelMetrics2,iterate:()=>iterate2,isSuccess:()=>isSuccess3,isFailure:()=>isFailure4,isEffect:()=>isEffect2,intoDeferred:()=>intoDeferred2,interruptibleMask:()=>interruptibleMask2,interruptible:()=>interruptible4,interruptWith:()=>interruptWith2,interrupt:()=>interrupt7,inheritFiberRefs:()=>inheritFiberRefs2,ignoreLogged:()=>ignoreLogged2,ignore:()=>ignore2,if:()=>if_2,head:()=>head4,getRuntimeFlags:()=>getRuntimeFlags,getFiberRefs:()=>getFiberRefs,gen:()=>gen2,functionWithSpan:()=>functionWithSpan2,fromNullable:()=>fromNullable3,fromFiberEffect:()=>fromFiberEffect2,fromFiber:()=>fromFiber2,forkWithErrorHandler:()=>forkWithErrorHandler2,forkScoped:()=>forkScoped2,forkIn:()=>forkIn2,forkDaemon:()=>forkDaemon2,forkAll:()=>forkAll2,fork:()=>fork3,forever:()=>forever3,forEach:()=>forEach8,fnUntraced:()=>fnUntraced2,fn:()=>fn,flipWith:()=>flipWith2,flip:()=>flip2,flatten:()=>flatten8,flatMap:()=>flatMap10,firstSuccessOf:()=>firstSuccessOf2,findFirst:()=>findFirst7,finalizersMask:()=>finalizersMask2,filterOrFail:()=>filterOrFail2,filterOrElse:()=>filterOrElse2,filterOrDieMessage:()=>filterOrDieMessage2,filterOrDie:()=>filterOrDie2,filterMap:()=>filterMap5,filterEffectOrFail:()=>filterEffectOrFail2,filterEffectOrElse:()=>filterEffectOrElse2,filter:()=>filter8,fiberIdWith:()=>fiberIdWith2,fiberId:()=>fiberId2,failSync:()=>failSync2,failCauseSync:()=>failCauseSync2,failCause:()=>failCause8,fail:()=>fail9,exit:()=>exit2,exists:()=>exists3,every:()=>every6,eventually:()=>eventually2,ensuringChildren:()=>ensuringChildren2,ensuringChild:()=>ensuringChild2,ensuring:()=>ensuring2,either:()=>either3,dropWhile:()=>dropWhile3,dropUntil:()=>dropUntil2,disconnect:()=>disconnect2,diffFiberRefs:()=>diffFiberRefs2,dieSync:()=>dieSync2,dieMessage:()=>dieMessage2,die:()=>die5,descriptorWith:()=>descriptorWith2,descriptor:()=>descriptor2,delay:()=>delay2,daemonChildren:()=>daemonChildren2,custom:()=>custom2,currentSpan:()=>currentSpan2,currentParentSpan:()=>currentParentSpan2,contextWithEffect:()=>contextWithEffect2,contextWith:()=>contextWith2,context:()=>context3,consoleWith:()=>consoleWith2,console:()=>console3,configProviderWith:()=>configProviderWith2,clockWith:()=>clockWith4,clock:()=>clock2,checkInterruptible:()=>checkInterruptible2,cause:()=>cause2,catchTags:()=>catchTags2,catchTag:()=>catchTag2,catchSomeDefect:()=>catchSomeDefect2,catchSomeCause:()=>catchSomeCause2,catchSome:()=>catchSome2,catchIf:()=>catchIf2,catchAllDefect:()=>catchAllDefect2,catchAllCause:()=>catchAllCause2,catchAll:()=>catchAll2,catch:()=>_catch2,cachedWithTTL:()=>cachedWithTTL,cachedInvalidateWithTTL:()=>cachedInvalidateWithTTL2,cachedFunction:()=>cachedFunction2,cached:()=>cached3,cacheRequestResult:()=>cacheRequestResult,blocked:()=>blocked2,bindTo:()=>bindTo3,bindAll:()=>bindAll2,bind:()=>bind3,awaitAllChildren:()=>awaitAllChildren2,asyncEffect:()=>asyncEffect2,async:()=>async,asVoid:()=>asVoid2,asSomeError:()=>asSomeError2,asSome:()=>asSome2,as:()=>as3,ap:()=>ap,annotateSpans:()=>annotateSpans2,annotateLogsScoped:()=>annotateLogsScoped2,annotateLogs:()=>annotateLogs2,annotateCurrentSpan:()=>annotateCurrentSpan2,andThen:()=>andThen4,allowInterrupt:()=>allowInterrupt2,allWith:()=>allWith2,allSuccesses:()=>allSuccesses2,all:()=>all7,addFinalizer:()=>addFinalizer3,acquireUseRelease:()=>acquireUseRelease2,acquireReleaseInterruptible:()=>acquireReleaseInterruptible2,acquireRelease:()=>acquireRelease2,Tag:()=>Tag2,Service:()=>Service,EffectTypeId:()=>EffectTypeId3,Do:()=>Do2});var IntervalSymbolKey="effect/ScheduleInterval",IntervalTypeId=Symbol.for(IntervalSymbolKey),empty30={[IntervalTypeId]:IntervalTypeId,startMillis:0,endMillis:0},make37=(startMillis,endMillis)=>{if(startMillis>endMillis)return empty30;return{[IntervalTypeId]:IntervalTypeId,startMillis,endMillis}},lessThan3=dual(2,(self,that)=>min3(self,that)===self),min3=dual(2,(self,that)=>{if(self.endMillis<=that.startMillis)return self;if(that.endMillis<=self.startMillis)return that;if(self.startMillis<that.startMillis)return self;if(that.startMillis<self.startMillis)return that;if(self.endMillis<=that.endMillis)return self;return that});var isEmpty8=(self)=>{return self.startMillis>=self.endMillis};var intersect=dual(2,(self,that)=>{let start=Math.max(self.startMillis,that.startMillis),end=Math.min(self.endMillis,that.endMillis);return make37(start,end)}),size9=(self)=>{return millis(self.endMillis-self.startMillis)};var after=(startMilliseconds)=>{return make37(startMilliseconds,Number.POSITIVE_INFINITY)};var make38=make37,empty31=empty30,lessThan4=lessThan3;var isEmpty9=isEmpty8;var intersect2=intersect,size10=size9;var after2=after;var IntervalsSymbolKey="effect/ScheduleIntervals",IntervalsTypeId=Symbol.for(IntervalsSymbolKey),make39=(intervals)=>{return{[IntervalsTypeId]:IntervalsTypeId,intervals}};var intersect3=dual(2,(self,that)=>intersectLoop(self.intervals,that.intervals,empty5())),intersectLoop=(_left,_right,_acc)=>{let left3=_left,right3=_right,acc=_acc;while(isNonEmpty2(left3)&&isNonEmpty2(right3)){let interval=pipe(headNonEmpty2(left3),intersect2(headNonEmpty2(right3))),intervals=isEmpty9(interval)?acc:pipe(acc,prepend2(interval));if(pipe(headNonEmpty2(left3),lessThan4(headNonEmpty2(right3))))left3=tailNonEmpty2(left3);else right3=tailNonEmpty2(right3);acc=intervals}return make39(reverse2(acc))},start=(self)=>{return pipe(self.intervals,head2,getOrElse(()=>empty31)).startMillis},end=(self)=>{return pipe(self.intervals,head2,getOrElse(()=>empty31)).endMillis},lessThan5=dual(2,(self,that)=>start(self)<start(that)),isNonEmpty4=(self)=>{return isNonEmpty2(self.intervals)};var make40=make39;var intersect4=intersect3,start2=start,end2=end,lessThan6=lessThan5,isNonEmpty5=isNonEmpty4;var OP_CONTINUE="Continue",OP_DONE2="Done",_continue=(intervals)=>{return{_tag:OP_CONTINUE,intervals}},continueWith=(interval)=>{return{_tag:OP_CONTINUE,intervals:make40(of2(interval))}},done6={_tag:OP_DONE2},isContinue=(self)=>{return self._tag===OP_CONTINUE},isDone4=(self)=>{return self._tag===OP_DONE2};var _continue2=_continue;var continueWith2=continueWith,done7=done6,isContinue2=isContinue,isDone5=isDone4;var addFinalizer2=scopeAddFinalizer,addFinalizerExit=scopeAddFinalizerExit,close=scopeClose,extend2=scopeExtend,fork2=scopeFork;var make41=scopeMake;var Error3=function(){let plainArgsSymbol=Symbol.for("effect/Data/Error/plainArgs");return{BaseEffectError:class extends YieldableError{constructor(args2){super(args2?.message,args2?.cause?{cause:args2.cause}:void 0);if(args2)Object.assign(this,args2),Object.defineProperty(this,plainArgsSymbol,{value:args2,enumerable:!1})}toJSON(){return{...this[plainArgsSymbol],...this}}}}.BaseEffectError}(),TaggedError=(tag)=>{let O={BaseEffectError:class extends Error3{_tag=tag}};return O.BaseEffectError.prototype.name=tag,O.BaseEffectError};var TypeId16=Symbol.for("effect/DateTime"),TimeZoneTypeId=Symbol.for("effect/DateTime/TimeZone"),Proto2={[TypeId16]:TypeId16,pipe(){return pipeArguments(this,arguments)},[NodeInspectSymbol](){return this.toString()},toJSON(){return toDateUtc(this).toJSON()}},ProtoUtc={...Proto2,_tag:"Utc",[symbol](){return cached(this,number2(this.epochMillis))},[symbol2](that){return isDateTime(that)&&that._tag==="Utc"&&this.epochMillis===that.epochMillis},toString(){return`DateTime.Utc(${toDateUtc(this).toJSON()})`}},ProtoZoned={...Proto2,_tag:"Zoned",[symbol](){return pipe(number2(this.epochMillis),combine(hash(this.zone)),cached(this))},[symbol2](that){return isDateTime(that)&&that._tag==="Zoned"&&this.epochMillis===that.epochMillis&&equals(this.zone,that.zone)},toString(){return`DateTime.Zoned(${formatIsoZoned(this)})`}},ProtoTimeZone={[TimeZoneTypeId]:TimeZoneTypeId,[NodeInspectSymbol](){return this.toString()}},ProtoTimeZoneNamed={...ProtoTimeZone,_tag:"Named",[symbol](){return cached(this,string(`Named:${this.id}`))},[symbol2](that){return isTimeZone(that)&&that._tag==="Named"&&this.id===that.id},toString(){return`TimeZone.Named(${this.id})`},toJSON(){return{_id:"TimeZone",_tag:"Named",id:this.id}}},ProtoTimeZoneOffset={...ProtoTimeZone,_tag:"Offset",[symbol](){return cached(this,string(`Offset:${this.offset}`))},[symbol2](that){return isTimeZone(that)&&that._tag==="Offset"&&this.offset===that.offset},toString(){return`TimeZone.Offset(${offsetToString(this.offset)})`},toJSON(){return{_id:"TimeZone",_tag:"Offset",offset:this.offset}}};var isDateTime=(u)=>hasProperty(u,TypeId16);var isTimeZone=(u)=>hasProperty(u,TimeZoneTypeId);var toDateUtc=(self)=>new Date(self.epochMillis),toDate=(self)=>{if(self._tag==="Utc")return new Date(self.epochMillis);else if(self.zone._tag==="Offset")return new Date(self.epochMillis+self.zone.offset);else if(self.adjustedEpochMillis!==void 0)return new Date(self.adjustedEpochMillis);let parts2=self.zone.format.formatToParts(self.epochMillis).filter((_)=>_.type!=="literal"),date=new Date(0);return date.setUTCFullYear(Number(parts2[2].value),Number(parts2[0].value)-1,Number(parts2[1].value)),date.setUTCHours(Number(parts2[3].value),Number(parts2[4].value),Number(parts2[5].value),Number(parts2[6].value)),self.adjustedEpochMillis=date.getTime(),date},zonedOffset=(self)=>{return toDate(self).getTime()-toEpochMillis(self)},offsetToString=(offset)=>{let abs2=Math.abs(offset),hours2=Math.floor(abs2/3600000),minutes2=Math.round(abs2%3600000/60000);if(minutes2===60)hours2+=1,minutes2=0;return`${offset<0?"-":"+"}${String(hours2).padStart(2,"0")}:${String(minutes2).padStart(2,"0")}`},zonedOffsetIso=(self)=>offsetToString(zonedOffset(self)),toEpochMillis=(self)=>self.epochMillis;var formatIsoOffset=(self)=>{let date=toDate(self);return self._tag==="Utc"?date.toISOString():`${date.toISOString().slice(0,-1)}${zonedOffsetIso(self)}`},formatIsoZoned=(self)=>self.zone._tag==="Offset"?formatIsoOffset(self):`${formatIsoOffset(self)}[${self.zone.id}]`;var TypeId17=Symbol.for("effect/Cron"),CronProto={[TypeId17]:TypeId17,[symbol2](that){return isCron(that)&&equals4(this,that)},[symbol](){return pipe(hash(this.tz),combine(array2(fromIterable(this.seconds))),combine(array2(fromIterable(this.minutes))),combine(array2(fromIterable(this.hours))),combine(array2(fromIterable(this.days))),combine(array2(fromIterable(this.months))),combine(array2(fromIterable(this.weekdays))),cached(this))},toString(){return format(this.toJSON())},toJSON(){return{_id:"Cron",tz:this.tz,seconds:fromIterable(this.seconds),minutes:fromIterable(this.minutes),hours:fromIterable(this.hours),days:fromIterable(this.days),months:fromIterable(this.months),weekdays:fromIterable(this.weekdays)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}},isCron=(u)=>hasProperty(u,TypeId17);var Equivalence3=make((self,that)=>restrictionsEquals(self.seconds,that.seconds)&&restrictionsEquals(self.minutes,that.minutes)&&restrictionsEquals(self.hours,that.hours)&&restrictionsEquals(self.days,that.days)&&restrictionsEquals(self.months,that.months)&&restrictionsEquals(self.weekdays,that.weekdays)),restrictionsArrayEquals=array(number),restrictionsEquals=(self,that)=>restrictionsArrayEquals(fromIterable(self),fromIterable(that)),equals4=dual(2,(self,that)=>Equivalence3(self,that));var ScheduleSymbolKey="effect/Schedule",ScheduleTypeId=Symbol.for(ScheduleSymbolKey),isSchedule=(u)=>hasProperty(u,ScheduleTypeId),ScheduleDriverSymbolKey="effect/ScheduleDriver",ScheduleDriverTypeId=Symbol.for(ScheduleDriverSymbolKey),scheduleVariance={_Out:(_)=>_,_In:(_)=>_,_R:(_)=>_},scheduleDriverVariance={_Out:(_)=>_,_In:(_)=>_,_R:(_)=>_};class ScheduleImpl{initial;step;[ScheduleTypeId]=scheduleVariance;constructor(initial,step3){this.initial=initial,this.step=step3}pipe(){return pipeArguments(this,arguments)}}class ScheduleDriverImpl{schedule;ref;[ScheduleDriverTypeId]=scheduleDriverVariance;constructor(schedule,ref){this.schedule=schedule,this.ref=ref}get state(){return map10(get11(this.ref),(tuple3)=>tuple3[1])}get last(){return flatMap8(get11(this.ref),([element,_])=>{switch(element._tag){case"None":return failSync(()=>new NoSuchElementException);case"Some":return succeed(element.value)}})}get reset(){return set5(this.ref,[none2(),this.schedule.initial])}next(input){return pipe(map10(get11(this.ref),(tuple3)=>tuple3[1]),flatMap8((state)=>pipe(currentTimeMillis2,flatMap8((now)=>pipe(suspend(()=>this.schedule.step(now,input,state)),flatMap8(([state2,out,decision])=>{let setState=set5(this.ref,[some2(out),state2]);if(isDone5(decision))return zipRight(setState,fail2(none2()));let millis2=start2(decision.intervals)-now;if(millis2<=0)return as(setState,out);return pipe(setState,zipRight(sleep3(millis(millis2))),as(out))}))))))}}var makeWithState=(initial,step3)=>new ScheduleImpl(initial,step3),addDelay=dual(2,(self,f)=>addDelayEffect(self,(out)=>sync(()=>f(out)))),addDelayEffect=dual(2,(self,f)=>modifyDelayEffect(self,(out,duration)=>map10(f(out),(delay2)=>sum(duration,decode(delay2)))));var check=dual(2,(self,test)=>checkEffect(self,(input,out)=>sync(()=>test(input,out)))),checkEffect=dual(2,(self,test)=>makeWithState(self.initial,(now,input,state)=>flatMap8(self.step(now,input,state),([state2,out,decision])=>{if(isDone5(decision))return succeed([state2,out,done7]);return map10(test(input,out),(cont)=>cont?[state2,out,decision]:[state2,out,done7])})));var driver=(self)=>pipe(make28([none2(),self.initial]),map10((ref)=>new ScheduleDriverImpl(self,ref)));var intersect5=dual(2,(self,that)=>intersectWith(self,that,intersect4)),intersectWith=dual(3,(self,that,f)=>makeWithState([self.initial,that.initial],(now,input,state)=>pipe(zipWith3(self.step(now,input,state[0]),that.step(now,input,state[1]),(a,b)=>[a,b]),flatMap8(([[lState,out,lDecision],[rState,out2,rDecision]])=>{if(isContinue2(lDecision)&&isContinue2(rDecision))return intersectWithLoop(self,that,input,lState,out,lDecision.intervals,rState,out2,rDecision.intervals,f);return succeed([[lState,rState],[out,out2],done7])})))),intersectWithLoop=(self,that,input,lState,out,lInterval,rState,out2,rInterval,f)=>{let combined=f(lInterval,rInterval);if(isNonEmpty5(combined))return succeed([[lState,rState],[out,out2],_continue2(combined)]);if(pipe(lInterval,lessThan6(rInterval)))return flatMap8(self.step(end2(lInterval),input,lState),([lState2,out3,decision])=>{if(isDone5(decision))return succeed([[lState2,rState],[out3,out2],done7]);return intersectWithLoop(self,that,input,lState2,out3,decision.intervals,rState,out2,rInterval,f)});return flatMap8(that.step(end2(rInterval),input,rState),([rState2,out22,decision])=>{if(isDone5(decision))return succeed([[lState,rState2],[out,out22],done7]);return intersectWithLoop(self,that,input,lState,out,lInterval,rState2,out22,decision.intervals,f)})};var map14=dual(2,(self,f)=>mapEffect2(self,(out)=>sync(()=>f(out)))),mapEffect2=dual(2,(self,f)=>makeWithState(self.initial,(now,input,state)=>flatMap8(self.step(now,input,state),([state2,out,decision])=>map10(f(out),(out2)=>[state2,out2,decision]))));var modifyDelayEffect=dual(2,(self,f)=>makeWithState(self.initial,(now,input,state)=>flatMap8(self.step(now,input,state),([state2,out,decision])=>{if(isDone5(decision))return succeed([state2,out,decision]);let intervals=decision.intervals,delay2=size10(make38(now,start2(intervals)));return map10(f(out,delay2),(durationInput)=>{let duration=decode(durationInput),oldStart=start2(intervals),newStart=now+toMillis(duration),delta=newStart-oldStart,newEnd=Math.max(0,end2(intervals)+delta),newInterval=make38(newStart,newEnd);return[state2,out,continueWith2(newInterval)]})})));var passthrough=(self)=>makeWithState(self.initial,(now,input,state)=>pipe(self.step(now,input,state),map10(([state2,_,decision])=>[state2,input,decision])));var recurs=(n)=>whileOutput(forever2,(out)=>out<n);var spaced=(duration)=>addDelay(forever2,()=>duration);var unfold2=(initial,f)=>makeWithState(initial,(now,_,state)=>sync(()=>[f(state),state,continueWith2(after2(now))]));var untilInputEffect=dual(2,(self,f)=>checkEffect(self,(input,_)=>negate(f(input))));var whileInputEffect=dual(2,(self,f)=>checkEffect(self,(input,_)=>f(input))),whileOutput=dual(2,(self,f)=>check(self,(_,out)=>f(out)));var ScheduleDefectTypeId=Symbol.for("effect/Schedule/ScheduleDefect");class ScheduleDefect{error;[ScheduleDefectTypeId];constructor(error){this.error=error,this[ScheduleDefectTypeId]=ScheduleDefectTypeId}}var isScheduleDefect=(u)=>hasProperty(u,ScheduleDefectTypeId),scheduleDefectWrap=(self)=>catchAll(self,(e)=>die2(new ScheduleDefect(e))),scheduleDefectRefail=(self)=>catchAllCause(self,(cause2)=>match2(find(cause2,(_)=>isDieType(_)&&isScheduleDefect(_.defect)?some2(_.defect):none2()),{onNone:()=>failCause(cause2),onSome:(error)=>fail2(error.error)})),repeat_Effect=dual(2,(self,schedule)=>repeatOrElse_Effect(self,schedule,(e,_)=>fail2(e))),repeat_combined=dual(2,(self,options)=>{if(isSchedule(options))return repeat_Effect(self,options);let base=options.schedule??passthrough(forever2),withWhile=options.while?whileInputEffect(base,(a)=>{let applied=options.while(a);if(typeof applied==="boolean")return succeed(applied);return scheduleDefectWrap(applied)}):base,withUntil=options.until?untilInputEffect(withWhile,(a)=>{let applied=options.until(a);if(typeof applied==="boolean")return succeed(applied);return scheduleDefectWrap(applied)}):withWhile,withTimes=options.times?intersect5(withUntil,recurs(options.times)).pipe(map14((intersectionPair)=>intersectionPair[0])):withUntil;return scheduleDefectRefail(repeat_Effect(self,withTimes))}),repeatOrElse_Effect=dual(3,(self,schedule,orElse4)=>flatMap8(driver(schedule),(driver2)=>matchEffect(self,{onFailure:(error)=>orElse4(error,none2()),onSuccess:(value)=>repeatOrElseEffectLoop(self,driver2,orElse4,value)}))),repeatOrElseEffectLoop=(self,driver2,orElse4,value)=>{return matchEffect(driver2.next(value),{onFailure:()=>orDie(driver2.last),onSuccess:(b)=>matchEffect(self,{onFailure:(error)=>orElse4(error,some2(b)),onSuccess:(value2)=>repeatOrElseEffectLoop(self,driver2,orElse4,value2)})})},retry_Effect=dual(2,(self,policy)=>retryOrElse_Effect(self,policy,(e,_)=>fail2(e))),retry_combined=dual(2,(self,options)=>{if(isSchedule(options))return retry_Effect(self,options);let base=options.schedule??forever2,withWhile=options.while?whileInputEffect(base,(e)=>{let applied=options.while(e);if(typeof applied==="boolean")return succeed(applied);return scheduleDefectWrap(applied)}):base,withUntil=options.until?untilInputEffect(withWhile,(e)=>{let applied=options.until(e);if(typeof applied==="boolean")return succeed(applied);return scheduleDefectWrap(applied)}):withWhile,withTimes=options.times?intersect5(withUntil,recurs(options.times)):withUntil;return scheduleDefectRefail(retry_Effect(self,withTimes))}),retryOrElse_Effect=dual(3,(self,policy,orElse4)=>flatMap8(driver(policy),(driver2)=>retryOrElse_EffectLoop(self,driver2,orElse4))),retryOrElse_EffectLoop=(self,driver2,orElse4)=>{return catchAll(self,(e)=>matchEffect(driver2.next(e),{onFailure:()=>pipe(driver2.last,orDie,flatMap8((out)=>orElse4(e,out))),onSuccess:()=>retryOrElse_EffectLoop(self,driver2,orElse4)}))},schedule_Effect=dual(2,(self,schedule)=>scheduleFrom_Effect(self,void 0,schedule)),scheduleFrom_Effect=dual(3,(self,initial,schedule)=>flatMap8(driver(schedule),(driver2)=>scheduleFrom_EffectLoop(self,initial,driver2))),scheduleFrom_EffectLoop=(self,initial,driver2)=>matchEffect(driver2.next(initial),{onFailure:()=>orDie(driver2.last),onSuccess:()=>flatMap8(self,(a)=>scheduleFrom_EffectLoop(self,a,driver2))});var forever2=unfold2(0,(n)=>n+1);class Semaphore{permits;waiters=new Set;taken=0;constructor(permits){this.permits=permits}get free(){return this.permits-this.taken}take=(n)=>asyncInterrupt((resume2)=>{if(this.free<n){let observer=()=>{if(this.free<n)return;this.waiters.delete(observer),this.taken+=n,resume2(succeed(n))};return this.waiters.add(observer),sync(()=>{this.waiters.delete(observer)})}return this.taken+=n,resume2(succeed(n))});updateTaken=(f)=>withFiberRuntime((fiber)=>{if(this.taken=f(this.taken),this.waiters.size>0)fiber.getFiberRef(currentScheduler).scheduleTask(()=>{let iter=this.waiters.values(),item=iter.next();while(item.done===!1&&this.free>0)item.value(),item=iter.next()},fiber.getFiberRef(currentSchedulingPriority));return succeed(this.free)});release=(n)=>this.updateTaken((taken)=>taken-n);releaseAll=this.updateTaken((_)=>0);withPermits=(n)=>(self)=>uninterruptibleMask((restore)=>flatMap8(restore(this.take(n)),(permits)=>ensuring(restore(self),this.release(permits))));withPermitsIfAvailable=(n)=>(self)=>uninterruptibleMask((restore)=>suspend(()=>{if(this.free<n)return succeedNone;return this.taken+=n,ensuring(restore(asSome(self)),this.release(n))}))}var unsafeMakeSemaphore=(permits)=>new Semaphore(permits),makeSemaphore=(permits)=>sync(()=>unsafeMakeSemaphore(permits));class Latch extends Class{isOpen;waiters=[];scheduled=!1;constructor(isOpen){super();this.isOpen=isOpen}commit(){return this.await}unsafeSchedule(fiber){if(this.scheduled||this.waiters.length===0)return void_;return this.scheduled=!0,fiber.currentScheduler.scheduleTask(this.flushWaiters,fiber.getFiberRef(currentSchedulingPriority)),void_}flushWaiters=()=>{this.scheduled=!1;let waiters=this.waiters;this.waiters=[];for(let i=0;i<waiters.length;i++)waiters[i](exitVoid)};open=withFiberRuntime((fiber)=>{if(this.isOpen)return void_;return this.isOpen=!0,this.unsafeSchedule(fiber)});unsafeOpen(){if(this.isOpen)return;this.isOpen=!0,this.flushWaiters()}release=withFiberRuntime((fiber)=>{if(this.isOpen)return void_;return this.unsafeSchedule(fiber)});await=asyncInterrupt((resume2)=>{if(this.isOpen)return resume2(void_);return this.waiters.push(resume2),sync(()=>{let index=this.waiters.indexOf(resume2);if(index!==-1)this.waiters.splice(index,1)})});unsafeClose(){this.isOpen=!1}close=sync(()=>{this.isOpen=!1});whenOpen=(self)=>{return zipRight(this.await,self)}}var unsafeMakeLatch=(open)=>new Latch(open??!1),makeLatch=(open)=>sync(()=>unsafeMakeLatch(open)),awaitAllChildren=(self)=>ensuringChildren(self,fiberAwaitAll),cached2=dual(2,(self,timeToLive)=>map10(cachedInvalidateWithTTL(self,timeToLive),(tuple3)=>tuple3[0])),cachedInvalidateWithTTL=dual(2,(self,timeToLive)=>{let duration=decode(timeToLive);return flatMap8(context(),(env)=>map10(makeSynchronized(none2()),(cache)=>[provideContext(getCachedValue(self,duration,cache),env),invalidateCache(cache)]))}),computeCachedValue=(self,timeToLive,start3)=>{let timeToLiveMillis=toMillis(decode(timeToLive));return pipe(deferredMake(),tap((deferred)=>intoDeferred(self,deferred)),map10((deferred)=>some2([start3+timeToLiveMillis,deferred])))},getCachedValue=(self,timeToLive,cache)=>uninterruptibleMask((restore)=>pipe(clockWith3((clock2)=>clock2.currentTimeMillis),flatMap8((time)=>updateSomeAndGetEffectSynchronized(cache,(option2)=>{switch(option2._tag){case"None":return some2(computeCachedValue(self,timeToLive,time));case"Some":{let[end3]=option2.value;return end3-time<=0?some2(computeCachedValue(self,timeToLive,time)):none2()}}})),flatMap8((option2)=>isNone2(option2)?dieMessage("BUG: Effect.cachedInvalidate - please report an issue at https://github.com/Effect-TS/effect/issues"):restore(deferredAwait(option2.value[1]))))),invalidateCache=(cache)=>set5(cache,none2()),ensuringChild=dual(2,(self,f)=>ensuringChildren(self,(children2)=>f(fiberAll(children2)))),ensuringChildren=dual(2,(self,children2)=>flatMap8(track,(supervisor)=>pipe(supervised(self,supervisor),ensuring(flatMap8(supervisor.value,children2))))),forkAll=dual((args2)=>isIterable(args2[0]),(effects,options)=>options?.discard?forEachSequentialDiscard(effects,fork):map10(forEachSequential(effects,fork),fiberAll)),forkIn=dual(2,(self,scope2)=>withFiberRuntime((parent,parentStatus)=>{let scopeImpl=scope2,fiber=unsafeFork(self,parent,parentStatus.runtimeFlags,globalScope);if(scopeImpl.state._tag==="Open"){let finalizer=()=>fiberIdWith((fiberId2)=>equals(fiberId2,fiber.id())?void_:asVoid(interruptFiber(fiber))),key={};scopeImpl.state.finalizers.set(key,finalizer),fiber.addObserver(()=>{if(scopeImpl.state._tag==="Closed")return;scopeImpl.state.finalizers.delete(key)})}else fiber.unsafeInterruptAsFork(parent.id());return succeed(fiber)})),forkScoped=(self)=>scopeWith((scope2)=>forkIn(self,scope2)),fromFiber=(fiber)=>join2(fiber),fromFiberEffect=(fiber)=>suspend(()=>flatMap8(fiber,join2)),memoKeySymbol=Symbol.for("effect/Effect/memoizeFunction.key");class Key{a;eq;[memoKeySymbol]=memoKeySymbol;constructor(a,eq){this.a=a,this.eq=eq}[symbol2](that){if(hasProperty(that,memoKeySymbol))if(this.eq)return this.eq(this.a,that.a);else return equals(this.a,that.a);return!1}[symbol](){return this.eq?0:cached(this,hash(this.a))}}var cachedFunction=(f,eq)=>{return pipe(sync(()=>empty21()),flatMap8(makeSynchronized),map10((ref)=>(a)=>pipe(ref.modifyEffect((map15)=>{let result=pipe(map15,get8(new Key(a,eq)));if(isNone2(result))return pipe(deferredMake(),tap((deferred)=>pipe(diffFiberRefs(f(a)),intoDeferred(deferred),fork)),map10((deferred)=>[deferred,pipe(map15,set4(new Key(a,eq),deferred))]));return succeed([result.value,map15])}),flatMap8(deferredAwait),flatMap8(([patch12,b])=>pipe(patchFiberRefs(patch12),as(b))))))},raceFirst=dual(2,(self,that)=>pipe(exit(self),race(exit(that)),(effect)=>flatten6(effect))),scheduleForked=dual(2,(self,schedule)=>pipe(self,schedule_Effect(schedule),forkScoped)),supervised=dual(2,(self,supervisor)=>{return fiberRefLocallyWith(currentSupervisor,(s)=>s.zip(supervisor))(self)}),timeout=dual(2,(self,duration)=>timeoutFail(self,{onTimeout:()=>timeoutExceptionFromDuration(duration),duration})),timeoutFail=dual(2,(self,{duration,onTimeout})=>flatten6(timeoutTo(self,{onTimeout:()=>failSync(onTimeout),onSuccess:succeed,duration}))),timeoutFailCause=dual(2,(self,{duration,onTimeout})=>flatten6(timeoutTo(self,{onTimeout:()=>failCauseSync(onTimeout),onSuccess:succeed,duration}))),timeoutOption=dual(2,(self,duration)=>timeoutTo(self,{duration,onSuccess:some2,onTimeout:none2})),timeoutTo=dual(2,(self,{duration,onSuccess,onTimeout})=>fiberIdWith((parentFiberId)=>uninterruptibleMask((restore)=>raceFibersWith(restore(self),interruptible2(sleep3(duration)),{onSelfWin:(winner,loser)=>flatMap8(winner.await,(exit2)=>{if(exit2._tag==="Success")return flatMap8(winner.inheritAll,()=>as(interruptAsFiber(loser,parentFiberId),onSuccess(exit2.value)));else return flatMap8(interruptAsFiber(loser,parentFiberId),()=>exitFailCause(exit2.cause))}),onOtherWin:(winner,loser)=>flatMap8(winner.await,(exit2)=>{if(exit2._tag==="Success")return flatMap8(winner.inheritAll,()=>as(interruptAsFiber(loser,parentFiberId),onTimeout()));else return flatMap8(interruptAsFiber(loser,parentFiberId),()=>exitFailCause(exit2.cause))}),otherScope:globalScope})))),SynchronizedSymbolKey="effect/Ref/SynchronizedRef",SynchronizedTypeId=Symbol.for(SynchronizedSymbolKey),synchronizedVariance={_A:(_)=>_};class SynchronizedImpl extends Class{ref;withLock;[SynchronizedTypeId]=synchronizedVariance;[RefTypeId]=refVariance;[TypeId13]=TypeId13;constructor(ref,withLock){super();this.ref=ref,this.withLock=withLock,this.get=get11(this.ref)}get;commit(){return this.get}modify(f){return this.modifyEffect((a)=>succeed(f(a)))}modifyEffect(f){return this.withLock(pipe(flatMap8(get11(this.ref),f),flatMap8(([b,a])=>as(set5(this.ref,a),b))))}}var makeSynchronized=(value)=>sync(()=>unsafeMakeSynchronized(value)),unsafeMakeSynchronized=(value)=>{let ref=unsafeMake5(value),sem=unsafeMakeSemaphore(1);return new SynchronizedImpl(ref,sem.withPermits(1))},updateSomeAndGetEffectSynchronized=dual(2,(self,pf)=>self.modifyEffect((value)=>{let result=pf(value);switch(result._tag){case"None":return succeed([value,value]);case"Some":return map10(result.value,(a)=>[a,a])}})),zipFiber=dual(2,(self,that)=>zipWithFiber(self,that,(a,b)=>[a,b])),zipLeftFiber=dual(2,(self,that)=>zipWithFiber(self,that,(a,_)=>a)),zipRightFiber=dual(2,(self,that)=>zipWithFiber(self,that,(_,b)=>b)),zipWithFiber=dual(3,(self,that,f)=>({...CommitPrototype2,commit(){return join2(this)},[FiberTypeId]:fiberVariance2,id:()=>pipe(self.id(),getOrElse4(that.id())),await:pipe(self.await,flatten6,zipWithOptions(flatten6(that.await),f,{concurrent:!0}),exit),children:self.children,inheritAll:zipRight(that.inheritAll,self.inheritAll),poll:zipWith3(self.poll,that.poll,(optionA,optionB)=>pipe(optionA,flatMap((exitA)=>pipe(optionB,map2((exitB)=>zipWith4(exitA,exitB,{onSuccess:f,onFailure:parallel})))))),interruptAsFork:(id2)=>zipRight(self.interruptAsFork(id2),that.interruptAsFork(id2)),pipe(){return pipeArguments(this,arguments)}})),bindAll=dual((args2)=>isEffect(args2[0]),(self,f,options)=>flatMap8(self,(a)=>all4(f(a),options).pipe(map10((record)=>Object.assign({},a,record)))));var TypeId18=Symbol.for("effect/ManagedRuntime");var OP_FRESH="Fresh",OP_FROM_EFFECT="FromEffect",OP_SCOPED="Scoped",OP_SUSPEND="Suspend",OP_PROVIDE="Provide",OP_PROVIDE_MERGE="ProvideMerge",OP_ZIP_WITH2="ZipWith";var exports_Fiber={};__export(exports_Fiber,{zipWith:()=>zipWith6,zipRight:()=>zipRight3,zipLeft:()=>zipLeft2,zip:()=>zip5,void:()=>void_5,unsafeRoots:()=>unsafeRoots2,succeed:()=>succeed6,status:()=>status2,scoped:()=>scoped,roots:()=>roots2,pretty:()=>pretty4,poll:()=>poll4,orElseEither:()=>orElseEither3,orElse:()=>orElse4,never:()=>never3,match:()=>match12,mapFiber:()=>mapFiber2,mapEffect:()=>mapEffect3,map:()=>map15,joinAll:()=>joinAll,join:()=>join3,isRuntimeFiber:()=>isRuntimeFiber2,isFiber:()=>isFiber2,interrupted:()=>interrupted2,interruptFork:()=>interruptFork,interruptAsFork:()=>interruptAsFork2,interruptAs:()=>interruptAs,interruptAllAs:()=>interruptAllAs2,interruptAll:()=>interruptAll2,interrupt:()=>interrupt6,inheritAll:()=>inheritAll2,id:()=>id2,getCurrentFiber:()=>getCurrentFiber2,fromEffect:()=>fromEffect3,failCause:()=>failCause6,fail:()=>fail7,dumpAll:()=>dumpAll2,dump:()=>dump2,done:()=>done8,children:()=>children2,awaitAll:()=>awaitAll,await:()=>_await3,all:()=>all6,RuntimeFiberTypeId:()=>RuntimeFiberTypeId2,Order:()=>Order5,FiberTypeId:()=>FiberTypeId2});var FiberTypeId2=FiberTypeId,RuntimeFiberTypeId2=RuntimeFiberTypeId,Order5=Order4,isFiber2=isFiber,isRuntimeFiber2=isRuntimeFiber,id2=id,_await3=_await2;var awaitAll=fiberAwaitAll,children2=children,all6=fiberAll,done8=done5,dump2=dump,dumpAll2=dumpAll,fail7=fail5,failCause6=failCause5,fromEffect3=fromEffect,getCurrentFiber2=getCurrentFiber,inheritAll2=inheritAll,interrupt6=interruptFiber,interrupted2=interrupted,interruptAs=interruptAsFiber,interruptAsFork2=interruptAsFork,interruptAll2=interruptAll,interruptAllAs2=interruptAllAs,interruptFork=fiberInterruptFork,join3=join2,joinAll=fiberJoinAll,map15=map12,mapEffect3=mapEffect,mapFiber2=mapFiber,match12=match10,never3=never2,orElse4=orElse3,orElseEither3=orElseEither,poll4=poll3,pretty4=pretty2,roots2=roots,unsafeRoots2=unsafeRoots,scoped=fiberScoped,status2=status,succeed6=succeed5,void_5=void_4;var zip5=zipFiber,zipLeft2=zipLeftFiber,zipRight3=zipRightFiber,zipWith6=zipWithFiber;var makeDual=(f)=>function(){if(arguments.length===1){let runtime2=arguments[0];return(effect,...args2)=>f(runtime2,effect,...args2)}return f.apply(this,arguments)},unsafeFork2=makeDual((runtime2,self,options)=>{let fiberId2=unsafeMake2(),fiberRefUpdates=[[currentContext,[[fiberId2,runtime2.context]]]];if(options?.scheduler)fiberRefUpdates.push([currentScheduler,[[fiberId2,options.scheduler]]]);let fiberRefs3=updateManyAs2(runtime2.fiberRefs,{entries:fiberRefUpdates,forkAs:fiberId2});if(options?.updateRefs)fiberRefs3=options.updateRefs(fiberRefs3,fiberId2);let fiberRuntime=new FiberRuntime(fiberId2,fiberRefs3,runtime2.runtimeFlags),effect=self;if(options?.scope)effect=flatMap8(fork2(options.scope,sequential2),(closeableScope)=>zipRight(scopeAddFinalizer(closeableScope,fiberIdWith((id3)=>equals(id3,fiberRuntime.id())?void_:interruptAsFiber(fiberRuntime,id3))),onExit(self,(exit2)=>close(closeableScope,exit2))));let supervisor=fiberRuntime.currentSupervisor;if(supervisor!==none8)supervisor.onStart(runtime2.context,effect,none2(),fiberRuntime),fiberRuntime.addObserver((exit2)=>supervisor.onEnd(exit2,fiberRuntime));if(globalScope.add(runtime2.runtimeFlags,fiberRuntime),options?.immediate===!1)fiberRuntime.resume(effect);else fiberRuntime.start(effect);return fiberRuntime}),unsafeRunCallback=makeDual((runtime2,effect,options={})=>{let fiberRuntime=unsafeFork2(runtime2,effect,options);if(options.onExit)fiberRuntime.addObserver((exit2)=>{options.onExit(exit2)});return(id3,cancelOptions)=>unsafeRunCallback(runtime2)(pipe(fiberRuntime,interruptAs(id3??none4)),{...cancelOptions,onExit:cancelOptions?.onExit?(exit2)=>cancelOptions.onExit(flatten7(exit2)):void 0})}),unsafeRunSync=makeDual((runtime2,effect)=>{let result=unsafeRunSyncExit(runtime2)(effect);if(result._tag==="Failure")throw fiberFailure(result.effect_instruction_i0);return result.effect_instruction_i0});class AsyncFiberExceptionImpl extends Error{fiber;_tag="AsyncFiberException";constructor(fiber){super(`Fiber #${fiber.id().id} cannot be resolved synchronously. This is caused by using runSync on an effect that performs async work`);this.fiber=fiber,this.name=this._tag,this.stack=this.message}}var asyncFiberException=(fiber)=>{let limit=Error.stackTraceLimit;Error.stackTraceLimit=0;let error=new AsyncFiberExceptionImpl(fiber);return Error.stackTraceLimit=limit,error};var FiberFailureId=Symbol.for("effect/Runtime/FiberFailure"),FiberFailureCauseId=Symbol.for("effect/Runtime/FiberFailure/Cause");class FiberFailureImpl extends Error{[FiberFailureId];[FiberFailureCauseId];constructor(cause2){let head4=prettyErrors(cause2)[0];super(head4?.message||"An error has occurred");if(this[FiberFailureId]=FiberFailureId,this[FiberFailureCauseId]=cause2,this.name=head4?`(FiberFailure) ${head4.name}`:"FiberFailure",head4?.stack)this.stack=head4.stack}toJSON(){return{_id:"FiberFailure",cause:this[FiberFailureCauseId].toJSON()}}toString(){return"(FiberFailure) "+pretty(this[FiberFailureCauseId],{renderErrorCause:!0})}[NodeInspectSymbol](){return this.toString()}}var fiberFailure=(cause2)=>{let limit=Error.stackTraceLimit;Error.stackTraceLimit=0;let error=new FiberFailureImpl(cause2);return Error.stackTraceLimit=limit,error};var fastPath=(effect)=>{let op=effect;switch(op._op){case"Failure":case"Success":return op;case"Left":return exitFail(op.left);case"Right":return exitSucceed(op.right);case"Some":return exitSucceed(op.value);case"None":return exitFail(NoSuchElementException())}},unsafeRunSyncExit=makeDual((runtime2,effect)=>{let op=fastPath(effect);if(op)return op;let scheduler=new SyncScheduler,fiberRuntime=unsafeFork2(runtime2)(effect,{scheduler});scheduler.flush();let result=fiberRuntime.unsafePoll();if(result)return result;return exitDie(capture(asyncFiberException(fiberRuntime),currentSpanFromFiber(fiberRuntime)))}),unsafeRunPromise=makeDual((runtime2,effect,options)=>unsafeRunPromiseExit(runtime2,effect,options).then((result)=>{switch(result._tag){case OP_SUCCESS:return result.effect_instruction_i0;case OP_FAILURE:throw fiberFailure(result.effect_instruction_i0)}})),unsafeRunPromiseExit=makeDual((runtime2,effect,options)=>new Promise((resolve)=>{let op=fastPath(effect);if(op)resolve(op);let fiber=unsafeFork2(runtime2)(effect);if(fiber.addObserver((exit2)=>{resolve(exit2)}),options?.signal!==void 0)if(options.signal.aborted)fiber.unsafeInterruptAsFork(fiber.id());else options.signal.addEventListener("abort",()=>{fiber.unsafeInterruptAsFork(fiber.id())},{once:!0})}));class RuntimeImpl{context;runtimeFlags;fiberRefs;constructor(context2,runtimeFlags2,fiberRefs3){this.context=context2,this.runtimeFlags=runtimeFlags2,this.fiberRefs=fiberRefs3}pipe(){return pipeArguments(this,arguments)}}var make42=(options)=>new RuntimeImpl(options.context,options.runtimeFlags,options.fiberRefs),runtime2=()=>withFiberRuntime((state,status3)=>succeed(new RuntimeImpl(state.getFiberRef(currentContext),status3.runtimeFlags,state.getFiberRefs()))),defaultRuntimeFlags=make17(Interruption,CooperativeYielding,RuntimeMetrics),defaultRuntime=make42({context:empty4(),runtimeFlags:defaultRuntimeFlags,fiberRefs:empty25()});var unsafeRunEffect=unsafeRunCallback(defaultRuntime),unsafeForkEffect=unsafeFork2(defaultRuntime),unsafeRunPromiseEffect=unsafeRunPromise(defaultRuntime),unsafeRunPromiseExitEffect=unsafeRunPromiseExit(defaultRuntime),unsafeRunSyncEffect=unsafeRunSync(defaultRuntime),unsafeRunSyncExitEffect=unsafeRunSyncExit(defaultRuntime),asyncEffect=(register)=>suspend(()=>{let cleanup=void 0;return flatMap8(deferredMake(),(deferred)=>flatMap8(runtime2(),(runtime3)=>uninterruptibleMask((restore)=>zipRight(fork(restore(matchCauseEffect(register((cb)=>unsafeRunCallback(runtime3)(intoDeferred(cb,deferred))),{onFailure:(cause2)=>deferredFailCause(deferred,cause2),onSuccess:(cleanup_)=>{return cleanup=cleanup_,void_}}))),restore(onInterrupt(deferredAwait(deferred),()=>cleanup??void_))))))});var modifyEffect=dual(2,(self,f)=>self.modifyEffect(f));var LayerSymbolKey="effect/Layer",LayerTypeId=Symbol.for(LayerSymbolKey),layerVariance={_RIn:(_)=>_,_E:(_)=>_,_ROut:(_)=>_},proto3={[LayerTypeId]:layerVariance,pipe(){return pipeArguments(this,arguments)}},MemoMapTypeIdKey="effect/Layer/MemoMap",MemoMapTypeId=Symbol.for(MemoMapTypeIdKey),CurrentMemoMap=Reference2()("effect/Layer/CurrentMemoMap",{defaultValue:()=>unsafeMakeMemoMap()}),isLayer=(u)=>hasProperty(u,LayerTypeId),isFresh=(self)=>{return self._op_layer===OP_FRESH};class MemoMapImpl{ref;[MemoMapTypeId];constructor(ref){this.ref=ref,this[MemoMapTypeId]=MemoMapTypeId}getOrElseMemoize(layer,scope2){return pipe(modifyEffect(this.ref,(map16)=>{let inMap=map16.get(layer);if(inMap!==void 0){let[acquire,release]=inMap,cached3=pipe(acquire,flatMap8(([patch12,b])=>pipe(patchFiberRefs(patch12),as(b))),onExit(exitMatch({onFailure:()=>void_,onSuccess:()=>scopeAddFinalizerExit(scope2,release)})));return succeed([cached3,map16])}return pipe(make28(0),flatMap8((observers)=>pipe(deferredMake(),flatMap8((deferred)=>pipe(make28(()=>void_),map10((finalizerRef)=>{let resource=uninterruptibleMask((restore)=>pipe(scopeMake(),flatMap8((innerScope)=>pipe(restore(flatMap8(makeBuilder(layer,innerScope,!0),(f)=>diffFiberRefs(f(this)))),exit,flatMap8((exit2)=>{switch(exit2._tag){case OP_FAILURE:return pipe(deferredFailCause(deferred,exit2.effect_instruction_i0),zipRight(scopeClose(innerScope,exit2)),zipRight(failCause(exit2.effect_instruction_i0)));case OP_SUCCESS:return pipe(set5(finalizerRef,(exit3)=>pipe(scopeClose(innerScope,exit3),whenEffect(modify2(observers,(n)=>[n===1,n-1])),asVoid)),zipRight(update2(observers,(n)=>n+1)),zipRight(scopeAddFinalizerExit(scope2,(exit3)=>pipe(sync(()=>map16.delete(layer)),zipRight(get11(finalizerRef)),flatMap8((finalizer)=>finalizer(exit3))))),zipRight(deferredSucceed(deferred,exit2.effect_instruction_i0)),as(exit2.effect_instruction_i0[1]))}}))))),memoized=[pipe(deferredAwait(deferred),onExit(exitMatchEffect({onFailure:()=>void_,onSuccess:()=>update2(observers,(n)=>n+1)}))),(exit2)=>pipe(get11(finalizerRef),flatMap8((finalizer)=>finalizer(exit2)))];return[resource,isFresh(layer)?map16:map16.set(layer,memoized)]}))))))}),flatten6)}}var makeMemoMap=suspend(()=>map10(makeSynchronized(new Map),(ref)=>new MemoMapImpl(ref))),unsafeMakeMemoMap=()=>new MemoMapImpl(unsafeMakeSynchronized(new Map));var buildWithScope=dual(2,(self,scope2)=>flatMap8(makeMemoMap,(memoMap)=>buildWithMemoMap(self,memoMap,scope2))),buildWithMemoMap=dual(3,(self,memoMap,scope2)=>flatMap8(makeBuilder(self,scope2),(run)=>provideService(run(memoMap),CurrentMemoMap,memoMap))),makeBuilder=(self,scope2,inMemoMap=!1)=>{let op=self;switch(op._op_layer){case"Locally":return sync(()=>(memoMap)=>op.f(memoMap.getOrElseMemoize(op.self,scope2)));case"ExtendScope":return sync(()=>(memoMap)=>scopeWith((scope3)=>memoMap.getOrElseMemoize(op.layer,scope3)));case"Fold":return sync(()=>(memoMap)=>pipe(memoMap.getOrElseMemoize(op.layer,scope2),matchCauseEffect({onFailure:(cause2)=>memoMap.getOrElseMemoize(op.failureK(cause2),scope2),onSuccess:(value)=>memoMap.getOrElseMemoize(op.successK(value),scope2)})));case"Fresh":return sync(()=>(_)=>pipe(op.layer,buildWithScope(scope2)));case"FromEffect":return inMemoMap?sync(()=>(_)=>op.effect):sync(()=>(memoMap)=>memoMap.getOrElseMemoize(self,scope2));case"Provide":return sync(()=>(memoMap)=>pipe(memoMap.getOrElseMemoize(op.first,scope2),flatMap8((env)=>pipe(memoMap.getOrElseMemoize(op.second,scope2),provideContext(env)))));case"Scoped":return inMemoMap?sync(()=>(_)=>scopeExtend(op.effect,scope2)):sync(()=>(memoMap)=>memoMap.getOrElseMemoize(self,scope2));case"Suspend":return sync(()=>(memoMap)=>memoMap.getOrElseMemoize(op.evaluate(),scope2));case"ProvideMerge":return sync(()=>(memoMap)=>pipe(memoMap.getOrElseMemoize(op.first,scope2),zipWith3(memoMap.getOrElseMemoize(op.second,scope2),op.zipK)));case"ZipWith":return sync(()=>(memoMap)=>pipe(memoMap.getOrElseMemoize(op.first,scope2),zipWithOptions(memoMap.getOrElseMemoize(op.second,scope2),op.zipK,{concurrent:!0})))}};var context2=()=>fromEffectContext(context());var fromEffect4=dual(2,(a,b)=>{let tagFirst=isTag2(a),tag=tagFirst?a:b;return fromEffectContext(map10(tagFirst?b:a,(service)=>make6(tag,service)))});function fromEffectContext(effect){let fromEffect5=Object.create(proto3);return fromEffect5._op_layer=OP_FROM_EFFECT,fromEffect5.effect=effect,fromEffect5}var merge6=dual(2,(self,that)=>zipWith7(self,that,(a,b)=>merge3(a,b))),mergeAll3=(...layers)=>{let final=layers[0];for(let i=1;i<layers.length;i++)final=merge6(final,layers[i]);return final};var scoped2=dual(2,(a,b)=>{let tagFirst=isTag2(a),tag=tagFirst?a:b;return scopedContext(map10(tagFirst?b:a,(service)=>make6(tag,service)))});var scopedContext=(effect)=>{let scoped3=Object.create(proto3);return scoped3._op_layer=OP_SCOPED,scoped3.effect=effect,scoped3};var succeed7=dual(2,(a,b)=>{let tagFirst=isTag2(a);return fromEffectContext(succeed(make6(tagFirst?a:b,tagFirst?b:a)))});var suspend2=(evaluate2)=>{let suspend3=Object.create(proto3);return suspend3._op_layer=OP_SUSPEND,suspend3.evaluate=evaluate2,suspend3},sync2=dual(2,(a,b)=>{let tagFirst=isTag2(a),tag=tagFirst?a:b,evaluate2=tagFirst?b:a;return fromEffectContext(sync(()=>make6(tag,evaluate2())))});var provide=dual(2,(self,that)=>suspend2(()=>{let provideTo=Object.create(proto3);return provideTo._op_layer=OP_PROVIDE,provideTo.first=Object.create(proto3,{_op_layer:{value:OP_PROVIDE_MERGE,enumerable:!0},first:{value:context2(),enumerable:!0},second:{value:Array.isArray(that)?mergeAll3(...that):that},zipK:{value:(a,b)=>pipe(a,merge3(b))}}),provideTo.second=self,provideTo}));var zipWith7=dual(3,(self,that,f)=>suspend2(()=>{let zipWith8=Object.create(proto3);return zipWith8._op_layer=OP_ZIP_WITH2,zipWith8.first=self,zipWith8.second=that,zipWith8.zipK=f,zipWith8}));var provideSomeLayer=dual(2,(self,layer)=>scopedWith((scope2)=>flatMap8(buildWithScope(layer,scope2),(context3)=>provideSomeContext(self,context3)))),provideSomeRuntime=dual(2,(self,rt)=>{let patchRefs=diff9(defaultRuntime.fiberRefs,rt.fiberRefs),patchFlags=diff7(defaultRuntime.runtimeFlags,rt.runtimeFlags);return uninterruptibleMask((restore)=>withFiberRuntime((fiber)=>{let oldContext=fiber.getFiberRef(currentContext),oldRefs=fiber.getFiberRefs(),newRefs=patch10(fiber.id(),oldRefs)(patchRefs),oldFlags=fiber.currentRuntimeFlags,newFlags=patch7(patchFlags)(oldFlags),rollbackRefs=diff9(newRefs,oldRefs),rollbackFlags=diff7(newFlags,oldFlags);return fiber.setFiberRefs(newRefs),fiber.currentRuntimeFlags=newFlags,ensuring(provideSomeContext(restore(self),merge3(oldContext,rt.context)),withFiberRuntime((fiber2)=>{return fiber2.setFiberRefs(patch10(fiber2.id(),fiber2.getFiberRefs())(rollbackRefs)),fiber2.currentRuntimeFlags=patch7(rollbackFlags)(fiber2.currentRuntimeFlags),void_}))}))}),effect_provide=dual(2,(self,source)=>{if(Array.isArray(source))return provideSomeLayer(self,mergeAll3(...source));else if(isLayer(source))return provideSomeLayer(self,source);else if(isContext2(source))return provideSomeContext(self,source);else if(TypeId18 in source)return flatMap8(source.runtimeEffect,(rt)=>provideSomeRuntime(self,rt));else return provideSomeRuntime(self,source)});var console2=map10(fiberRefGet(currentServices),get3(consoleTag)),consoleWith=(f)=>fiberRefGetWith(currentServices,(services)=>f(get3(services,consoleTag))),withConsole=dual(2,(effect,value)=>fiberRefLocallyWith(effect,currentServices,add2(consoleTag,value))),withConsoleScoped=(console3)=>fiberRefLocallyScopedWith(currentServices,add2(consoleTag,console3));var currentCache=globalValue(Symbol.for("effect/FiberRef/currentCache"),()=>fiberRefUnsafeMake(unsafeMakeWith(65536,()=>map10(deferredMake(),(handle)=>({listeners:new Listeners,handle})),()=>seconds(60)))),currentCacheEnabled=globalValue(Symbol.for("effect/FiberRef/currentCacheEnabled"),()=>fiberRefUnsafeMake(!1)),fromRequest=(request,dataSource)=>flatMap8(isEffect(dataSource)?dataSource:succeed(dataSource),(ds)=>fiberIdWith((id3)=>{let proxy=new Proxy(request,{});return fiberRefGetWith(currentCacheEnabled,(cacheEnabled)=>{if(cacheEnabled){let cached3=fiberRefGetWith(currentCache,(cache)=>flatMap8(cache.getEither(proxy),(orNew)=>{switch(orNew._tag){case"Left":{if(orNew.left.listeners.interrupted)return flatMap8(cache.invalidateWhen(proxy,(entry)=>entry.handle===orNew.left.handle),()=>cached3);return orNew.left.listeners.increment(),uninterruptibleMask((restore)=>flatMap8(exit(blocked(empty19,restore(deferredAwait(orNew.left.handle)))),(exit2)=>{return orNew.left.listeners.decrement(),exit2}))}case"Right":return orNew.right.listeners.increment(),uninterruptibleMask((restore)=>flatMap8(exit(blocked(single(ds,makeEntry({request:proxy,result:orNew.right.handle,listeners:orNew.right.listeners,ownerId:id3,state:{completed:!1}})),restore(deferredAwait(orNew.right.handle)))),()=>{return orNew.right.listeners.decrement(),deferredAwait(orNew.right.handle)}))}}));return cached3}let listeners=new Listeners;return listeners.increment(),flatMap8(deferredMake(),(ref)=>ensuring(blocked(single(ds,makeEntry({request:proxy,result:ref,listeners,ownerId:id3,state:{completed:!1}})),deferredAwait(ref)),sync(()=>listeners.decrement())))})})),cacheRequest=(request,result)=>{return fiberRefGetWith(currentCacheEnabled,(cacheEnabled)=>{if(cacheEnabled)return fiberRefGetWith(currentCache,(cache)=>flatMap8(cache.getEither(request),(orNew)=>{switch(orNew._tag){case"Left":return void_;case"Right":return deferredComplete(orNew.right.handle,result)}}));return void_})},withRequestCaching=dual(2,(self,strategy)=>fiberRefLocally(self,currentCacheEnabled,strategy)),withRequestCache=dual(2,(self,cache)=>fiberRefLocally(self,currentCache,cache));var isRequest2=isRequest;var EffectTypeId3=EffectTypeId2,isEffect2=isEffect,cachedWithTTL=cached2,cachedInvalidateWithTTL2=cachedInvalidateWithTTL,cached3=memoize,cachedFunction2=cachedFunction,once2=once,all7=all4,allWith2=allWith,allSuccesses2=allSuccesses,dropUntil2=dropUntil,dropWhile3=dropWhile2,takeUntil2=takeUntil,takeWhile3=takeWhile2,every6=every5,exists3=exists2,filter8=filter6,filterMap5=filterMap4,findFirst7=findFirst5,forEach8=forEach7,head4=head3,mergeAll4=mergeAll2,partition4=partition3,reduce13=reduce11,reduceWhile2=reduceWhile,reduceRight4=reduceRight3,reduceEffect2=reduceEffect,replicate2=replicate,replicateEffect2=replicateEffect,validateAll2=validateAll,validateFirst2=validateFirst,async=async_,asyncEffect2=asyncEffect,custom2=custom,withFiberRuntime2=withFiberRuntime,fail9=fail2,failSync2=failSync,failCause8=failCause,failCauseSync2=failCauseSync,die5=die2,dieMessage2=dieMessage,dieSync2=dieSync,gen2=gen,never4=never,none9=none6,promise2=promise,succeed9=succeed,succeedNone2=succeedNone,succeedSome2=succeedSome,suspend3=suspend,sync3=sync,_void=void_;var yieldNow4=yieldNow,_catch2=_catch;var catchAll2=catchAll,catchAllCause2=catchAllCause,catchAllDefect2=catchAllDefect,catchIf2=catchIf,catchSome2=catchSome,catchSomeCause2=catchSomeCause,catchSomeDefect2=catchSomeDefect,catchTag2=catchTag,catchTags2=catchTags,cause2=cause,eventually2=eventually,ignore2=ignore,ignoreLogged2=ignoreLogged,parallelErrors2=parallelErrors,sandbox2=sandbox,retry=retry_combined,retryOrElse=retryOrElse_Effect,try_2=try_;var tryMap2=tryMap,tryMapPromise2=tryMapPromise,tryPromise2=tryPromise,unsandbox2=unsandbox,allowInterrupt2=allowInterrupt,checkInterruptible2=checkInterruptible,disconnect2=disconnect,interrupt7=interrupt2,interruptWith2=interruptWith,interruptible4=interruptible2,interruptibleMask2=interruptibleMask,onInterrupt2=onInterrupt,uninterruptible2=uninterruptible,uninterruptibleMask3=uninterruptibleMask,liftPredicate2=liftPredicate,as3=as,asSome2=asSome,asSomeError2=asSomeError,asVoid2=asVoid,flip2=flip,flipWith2=flipWith,map16=map10,mapAccum4=mapAccum3,mapBoth3=mapBoth,mapError2=mapError,mapErrorCause2=mapErrorCause,merge7=merge5,negate2=negate,acquireRelease2=acquireRelease,acquireReleaseInterruptible2=acquireReleaseInterruptible,acquireUseRelease2=acquireUseRelease,addFinalizer3=addFinalizer,ensuring2=ensuring,onError2=onError,onExit3=onExit,parallelFinalizers2=parallelFinalizers,sequentialFinalizers2=sequentialFinalizers,finalizersMask2=finalizersMask,scope2=scope,scopeWith2=scopeWith,scopedWith2=scopedWith,scoped3=scopedEffect,using2=using,withEarlyRelease2=withEarlyRelease,awaitAllChildren2=awaitAllChildren,daemonChildren2=daemonChildren,descriptor2=descriptor,descriptorWith2=descriptorWith,diffFiberRefs2=diffFiberRefs,ensuringChild2=ensuringChild,ensuringChildren2=ensuringChildren,fiberId2=fiberId,fiberIdWith2=fiberIdWith,fork3=fork,forkDaemon2=forkDaemon,forkAll2=forkAll,forkIn2=forkIn,forkScoped2=forkScoped,forkWithErrorHandler2=forkWithErrorHandler,fromFiber2=fromFiber,fromFiberEffect2=fromFiberEffect,supervised2=supervised,transplant2=transplant,withConcurrency2=withConcurrency,withScheduler2=withScheduler,withSchedulingPriority2=withSchedulingPriority,withMaxOpsBeforeYield2=withMaxOpsBeforeYield,clock2=clock,clockWith4=clockWith3,withClockScoped2=withClockScoped,withClock2=withClock,console3=console2,consoleWith2=consoleWith,withConsoleScoped2=withConsoleScoped,withConsole2=withConsole,delay2=delay,sleep4=sleep3,timed2=timed,timedWith2=timedWith,timeout2=timeout,timeoutOption2=timeoutOption,timeoutFail2=timeoutFail,timeoutFailCause2=timeoutFailCause,timeoutTo2=timeoutTo,configProviderWith2=configProviderWith,withConfigProvider2=withConfigProvider,withConfigProviderScoped2=withConfigProviderScoped,context3=context,contextWith2=contextWith,contextWithEffect2=contextWithEffect,mapInputContext2=mapInputContext,provide2=effect_provide,provideService2=provideService,provideServiceEffect2=provideServiceEffect,serviceFunction2=serviceFunction,serviceFunctionEffect2=serviceFunctionEffect,serviceFunctions2=serviceFunctions,serviceConstants2=serviceConstants,serviceMembers2=serviceMembers,serviceOption2=serviceOption,serviceOptional2=serviceOptional,updateService2=updateService,Do2=Do,bind3=bind2,bindAll2=bindAll,bindTo3=bindTo2,let_3=let_2;var option2=option,either3=either2,exit2=exit,intoDeferred2=intoDeferred,if_2=if_;var filterOrDie2=filterOrDie,filterOrDieMessage2=filterOrDieMessage,filterOrElse2=filterOrElse,filterOrFail2=filterOrFail,filterEffectOrElse2=filterEffectOrElse,filterEffectOrFail2=filterEffectOrFail,unless2=unless,unlessEffect2=unlessEffect,when2=when,whenEffect2=whenEffect,whenFiberRef2=whenFiberRef,whenRef2=whenRef,flatMap10=flatMap8,andThen4=andThen2,flatten8=flatten6,race2=race,raceAll2=raceAll,raceFirst2=raceFirst,raceWith2=raceWith,summarized2=summarized,tap2=tap,tapBoth2=tapBoth,tapDefect2=tapDefect,tapError2=tapError,tapErrorTag2=tapErrorTag,tapErrorCause2=tapErrorCause,forever3=forever,iterate2=iterate,loop2=loop,repeat=repeat_combined,repeatN2=repeatN,repeatOrElse=repeatOrElse_Effect,schedule=schedule_Effect,scheduleForked2=scheduleForked,scheduleFrom=scheduleFrom_Effect,whileLoop2=whileLoop,getFiberRefs=fiberRefs2,inheritFiberRefs2=inheritFiberRefs,locally=fiberRefLocally,locallyWith=fiberRefLocallyWith,locallyScoped=fiberRefLocallyScoped,locallyScopedWith=fiberRefLocallyScopedWith,patchFiberRefs2=patchFiberRefs,setFiberRefs2=setFiberRefs,updateFiberRefs2=updateFiberRefs,isFailure4=isFailure2,isSuccess3=isSuccess2,match13=match7,matchCause2=matchCause,matchCauseEffect3=matchCauseEffect,matchEffect2=matchEffect,log2=log,logWithLevel2=(level,...message)=>logWithLevel(level)(...message),logTrace2=logTrace,logDebug2=logDebug,logInfo2=logInfo,logWarning2=logWarning,logError2=logError,logFatal2=logFatal,withLogSpan2=withLogSpan,annotateLogs2=annotateLogs,annotateLogsScoped2=annotateLogsScoped,logAnnotations2=logAnnotations,withUnhandledErrorLogLevel2=withUnhandledErrorLogLevel,whenLogLevel2=whenLogLevel,orDie2=orDie,orDieWith2=orDieWith,orElse5=orElse2,orElseFail2=orElseFail,orElseSucceed2=orElseSucceed,firstSuccessOf2=firstSuccessOf,random3=random2,randomWith2=randomWith,withRandom2=withRandom,withRandomScoped2=withRandomScoped,runtime3=runtime2,getRuntimeFlags=runtimeFlags,patchRuntimeFlags=updateRuntimeFlags,withRuntimeFlagsPatch=withRuntimeFlags,withRuntimeFlagsPatchScoped=withRuntimeFlagsScoped,tagMetrics2=tagMetrics,labelMetrics2=labelMetrics,tagMetricsScoped2=tagMetricsScoped,labelMetricsScoped2=labelMetricsScoped,metricLabels2=metricLabels,withMetric2=withMetric,unsafeMakeSemaphore2=unsafeMakeSemaphore,makeSemaphore2=makeSemaphore,unsafeMakeLatch2=unsafeMakeLatch,makeLatch2=makeLatch,runFork2=unsafeForkEffect,runCallback=unsafeRunEffect,runPromise=unsafeRunPromiseEffect,runPromiseExit=unsafeRunPromiseExitEffect,runSync=unsafeRunSyncEffect,runSyncExit=unsafeRunSyncExitEffect,validate2=validate,validateWith2=validateWith,zip6=zipOptions,zipLeft3=zipLeftOptions,zipRight4=zipRightOptions,zipWith8=zipWithOptions,ap=dual(2,(self,that)=>zipWith8(self,that,(f,a)=>f(a))),blocked2=blocked,runRequestBlock2=runRequestBlock,step3=step2,request=dual((args2)=>isRequest2(args2[0]),fromRequest),cacheRequestResult=cacheRequest,withRequestBatching2=withRequestBatching,withRequestCaching2=withRequestCaching,withRequestCache2=withRequestCache,tracer2=tracer,tracerWith4=tracerWith,withTracer2=withTracer,withTracerScoped2=withTracerScoped,withTracerEnabled2=withTracerEnabled,withTracerTiming2=withTracerTiming,annotateSpans2=annotateSpans,annotateCurrentSpan2=annotateCurrentSpan,currentSpan2=currentSpan,currentParentSpan2=currentParentSpan,spanAnnotations2=spanAnnotations,spanLinks2=spanLinks,linkSpans2=linkSpans,linkSpanCurrent2=linkSpanCurrent,makeSpan2=makeSpan,makeSpanScoped2=makeSpanScoped,useSpan2=useSpan,withSpan2=withSpan,functionWithSpan2=functionWithSpan,withSpanScoped2=withSpanScoped,withParentSpan2=withParentSpan,fromNullable3=fromNullable2,optionFromOptional2=optionFromOptional,transposeOption=(self)=>{return isNone(self)?succeedNone2:map16(self.value,some)},transposeMapOption=dual(2,(self,f)=>isNone(self)?succeedNone2:map16(f(self.value),some)),makeTagProxy=(TagClass)=>{let cache=new Map;return new Proxy(TagClass,{get(target,prop,receiver){if(prop in target)return Reflect.get(target,prop,receiver);if(cache.has(prop))return cache.get(prop);let fn=(...args2)=>andThen2(target,(s)=>{if(typeof s[prop]==="function")return cache.set(prop,(...args3)=>andThen2(target,(s2)=>s2[prop](...args3))),s[prop](...args2);return cache.set(prop,andThen2(target,(s2)=>s2[prop])),s[prop]}),cn=andThen2(target,(s)=>s[prop]);return Object.assign(fn,cn),Object.setPrototypeOf(fn,Object.getPrototypeOf(cn)),cache.set(prop,fn),fn}})},Tag2=(id3)=>()=>{let limit=Error.stackTraceLimit;Error.stackTraceLimit=2;let creationError=new Error;Error.stackTraceLimit=limit;function TagClass(){}return Object.setPrototypeOf(TagClass,TagProto),TagClass.key=id3,Object.defineProperty(TagClass,"use",{get(){return(body)=>andThen2(this,body)}}),Object.defineProperty(TagClass,"stack",{get(){return creationError.stack}}),makeTagProxy(TagClass)},Service=function(){return function(){let[id3,maker]=arguments,proxy="accessors"in maker?maker.accessors:!1,limit=Error.stackTraceLimit;Error.stackTraceLimit=2;let creationError=new Error;Error.stackTraceLimit=limit;let patchState="unchecked",TagClass=function(service){if(patchState==="unchecked"){let proto4=Object.getPrototypeOf(service);if(proto4===Object.prototype||proto4===null)patchState="plain";else{let selfProto=Object.getPrototypeOf(this);Object.setPrototypeOf(selfProto,proto4),patchState="patched"}}if(patchState==="plain")Object.assign(this,service);else if(patchState==="patched")return Object.setPrototypeOf(service,Object.getPrototypeOf(this)),service};TagClass.prototype._tag=id3,Object.defineProperty(TagClass,"make",{get(){return(service)=>new this(service)}}),Object.defineProperty(TagClass,"use",{get(){return(body)=>andThen2(this,body)}}),TagClass.key=id3,Object.assign(TagClass,TagProto),Object.defineProperty(TagClass,"stack",{get(){return creationError.stack}});let hasDeps="dependencies"in maker&&maker.dependencies.length>0,layerName=hasDeps?"DefaultWithoutDependencies":"Default",layerCache;if("effect"in maker)Object.defineProperty(TagClass,layerName,{get(){return layerCache??=fromEffect4(TagClass,map16(maker.effect,(_)=>new this(_)))}});else if("scoped"in maker)Object.defineProperty(TagClass,layerName,{get(){return layerCache??=scoped2(TagClass,map16(maker.scoped,(_)=>new this(_)))}});else if("sync"in maker)Object.defineProperty(TagClass,layerName,{get(){return layerCache??=sync2(TagClass,()=>new this(maker.sync()))}});else Object.defineProperty(TagClass,layerName,{get(){return layerCache??=succeed7(TagClass,new this(maker.succeed))}});if(hasDeps){let layerWithDepsCache;Object.defineProperty(TagClass,"Default",{get(){return layerWithDepsCache??=provide(this.DefaultWithoutDependencies,maker.dependencies)}})}return proxy===!0?makeTagProxy(TagClass):TagClass}},fn=function(nameOrBody,...pipeables){let limit=Error.stackTraceLimit;Error.stackTraceLimit=2;let errorDef=new Error;if(Error.stackTraceLimit=limit,typeof nameOrBody!=="string")return defineLength(nameOrBody.length,function(...args2){let limit2=Error.stackTraceLimit;Error.stackTraceLimit=2;let errorCall=new Error;return Error.stackTraceLimit=limit2,fnApply({self:this,body:nameOrBody,args:args2,pipeables,spanName:"<anonymous>",spanOptions:{context:DisablePropagation.context(!0)},errorDef,errorCall})});let name=nameOrBody,options=pipeables[0];return(body,...pipeables2)=>defineLength(body.length,function(...args2){let limit2=Error.stackTraceLimit;Error.stackTraceLimit=2;let errorCall=new Error;return Error.stackTraceLimit=limit2,fnApply({self:this,body,args:args2,pipeables:pipeables2,spanName:name,spanOptions:options,errorDef,errorCall})})};function defineLength(length3,fn2){return Object.defineProperty(fn2,"length",{value:length3,configurable:!0})}function fnApply(options){let effect,fnError=void 0;if(isGeneratorFunction(options.body))effect=fromIterator(()=>options.body.apply(options.self,options.args));else try{effect=options.body.apply(options.self,options.args)}catch(error){fnError=error,effect=die5(error)}if(options.pipeables.length>0)try{for(let x of options.pipeables)effect=x(effect,...options.args)}catch(error){effect=fnError?failCause8(sequential(die(fnError),die(error))):die5(error)}let cache=!1,captureStackTrace=()=>{if(cache!==!1)return cache;if(options.errorCall.stack){let stackDef=options.errorDef.stack.trim().split(`
|
|
30
30
|
`),stackCall=options.errorCall.stack.trim().split(`
|
|
31
|
-
`),
|
|
32
|
-
`).trim();if(!
|
|
33
|
-
|
|
34
|
-
`).trim()}`,cache}},opts=options.spanOptions&&"captureStackTrace"in options.spanOptions?options.spanOptions:{captureStackTrace,...options.spanOptions};return withSpan2(effect,options.spanName,opts)}var fnUntraced2=fnUntraced;var get13=fiberRefGet;var getWith=fiberRefGetWith;var currentContext2=currentContext,currentSchedulingPriority2=currentSchedulingPriority;var currentScheduler2=currentScheduler;var currentTracerTimingEnabled2=currentTracerTimingEnabled;var buildWithScope2=buildWithScope;var context4=context2;var merge8=merge6;var EnqueueSymbolKey="effect/QueueEnqueue",EnqueueTypeId=Symbol.for(EnqueueSymbolKey),DequeueSymbolKey="effect/QueueDequeue",DequeueTypeId=Symbol.for(DequeueSymbolKey),QueueStrategySymbolKey="effect/QueueStrategy",QueueStrategyTypeId=Symbol.for(QueueStrategySymbolKey),BackingQueueSymbolKey="effect/BackingQueue",BackingQueueTypeId=Symbol.for(BackingQueueSymbolKey),queueStrategyVariance={_A:(_)=>_},backingQueueVariance={_A:(_)=>_},enqueueVariance={_In:(_)=>_},dequeueVariance={_Out:(_)=>_};class QueueImpl extends Class{queue;takers;shutdownHook;shutdownFlag;strategy;[EnqueueTypeId]=enqueueVariance;[DequeueTypeId]=dequeueVariance;constructor(queue,takers,shutdownHook,shutdownFlag,strategy){super();this.queue=queue,this.takers=takers,this.shutdownHook=shutdownHook,this.shutdownFlag=shutdownFlag,this.strategy=strategy}pipe(){return pipeArguments(this,arguments)}commit(){return this.take}capacity(){return this.queue.capacity()}get size(){return suspend(()=>catchAll(this.unsafeSize(),()=>interrupt2))}unsafeSize(){if(get6(this.shutdownFlag))return none2();return some2(this.queue.length()-length2(this.takers)+this.strategy.surplusSize())}get isEmpty(){return map10(this.size,(size11)=>size11<=0)}get isFull(){return map10(this.size,(size11)=>size11>=this.capacity())}get shutdown(){return uninterruptible(withFiberRuntime((state)=>{return pipe(this.shutdownFlag,set2(!0)),pipe(forEachConcurrentDiscard(unsafePollAll(this.takers),(d)=>deferredInterruptWith(d,state.id()),!1,!1),zipRight(this.strategy.shutdown),whenEffect(deferredSucceed(this.shutdownHook,void 0)),asVoid)}))}get isShutdown(){return sync(()=>get6(this.shutdownFlag))}get awaitShutdown(){return deferredAwait(this.shutdownHook)}isActive(){return!get6(this.shutdownFlag)}unsafeOffer(value){if(get6(this.shutdownFlag))return!1;let noRemaining;if(this.queue.length()===0){let taker=pipe(this.takers,poll2(EmptyMutableQueue));if(taker!==EmptyMutableQueue)unsafeCompleteDeferred(taker,value),noRemaining=!0;else noRemaining=!1}else noRemaining=!1;if(noRemaining)return!0;let succeeded=this.queue.offer(value);return unsafeCompleteTakers(this.strategy,this.queue,this.takers),succeeded}offer(value){return suspend(()=>{if(get6(this.shutdownFlag))return interrupt2;let noRemaining;if(this.queue.length()===0){let taker=pipe(this.takers,poll2(EmptyMutableQueue));if(taker!==EmptyMutableQueue)unsafeCompleteDeferred(taker,value),noRemaining=!0;else noRemaining=!1}else noRemaining=!1;if(noRemaining)return succeed(!0);let succeeded=this.queue.offer(value);return unsafeCompleteTakers(this.strategy,this.queue,this.takers),succeeded?succeed(!0):this.strategy.handleSurplus([value],this.queue,this.takers,this.shutdownFlag)})}offerAll(iterable){return suspend(()=>{if(get6(this.shutdownFlag))return interrupt2;let values3=fromIterable(iterable),pTakers=this.queue.length()===0?fromIterable(unsafePollN(this.takers,values3.length)):empty2,[forTakers,remaining]=pipe(values3,splitAt(pTakers.length));for(let i=0;i<pTakers.length;i++){let taker=pTakers[i],item=forTakers[i];unsafeCompleteDeferred(taker,item)}if(remaining.length===0)return succeed(!0);let surplus=this.queue.offerAll(remaining);return unsafeCompleteTakers(this.strategy,this.queue,this.takers),isEmpty(surplus)?succeed(!0):this.strategy.handleSurplus(surplus,this.queue,this.takers,this.shutdownFlag)})}get take(){return withFiberRuntime((state)=>{if(get6(this.shutdownFlag))return interrupt2;let item=this.queue.poll(EmptyMutableQueue);if(item!==EmptyMutableQueue)return this.strategy.unsafeOnQueueEmptySpace(this.queue,this.takers),succeed(item);else{let deferred=deferredUnsafeMake(state.id());return pipe(suspend(()=>{return pipe(this.takers,offer(deferred)),unsafeCompleteTakers(this.strategy,this.queue,this.takers),get6(this.shutdownFlag)?interrupt2:deferredAwait(deferred)}),onInterrupt(()=>{return sync(()=>unsafeRemove(this.takers,deferred))}))}})}get takeAll(){return suspend(()=>{return get6(this.shutdownFlag)?interrupt2:sync(()=>{let values3=this.queue.pollUpTo(Number.POSITIVE_INFINITY);return this.strategy.unsafeOnQueueEmptySpace(this.queue,this.takers),fromIterable2(values3)})})}takeUpTo(max6){return suspend(()=>get6(this.shutdownFlag)?interrupt2:sync(()=>{let values3=this.queue.pollUpTo(max6);return this.strategy.unsafeOnQueueEmptySpace(this.queue,this.takers),fromIterable2(values3)}))}takeBetween(min4,max6){return suspend(()=>takeRemainderLoop(this,min4,max6,empty5()))}}var takeRemainderLoop=(self,min4,max6,acc)=>{if(max6<min4)return succeed(acc);return pipe(takeUpTo(self,max6),flatMap8((bs)=>{let remaining=min4-bs.length;if(remaining===1)return pipe(take2(self),map10((b)=>pipe(acc,appendAll2(bs),append2(b))));if(remaining>1)return pipe(take2(self),flatMap8((b)=>takeRemainderLoop(self,remaining-1,max6-bs.length-1,pipe(acc,appendAll2(bs),append2(b)))));return succeed(pipe(acc,appendAll2(bs)))}))},isQueue=(u)=>isEnqueue(u)&&isDequeue(u),isEnqueue=(u)=>hasProperty(u,EnqueueTypeId),isDequeue=(u)=>hasProperty(u,DequeueTypeId),bounded2=(requestedCapacity)=>pipe(sync(()=>bounded(requestedCapacity)),flatMap8((queue)=>make43(backingQueueFromMutableQueue(queue),backPressureStrategy()))),dropping=(requestedCapacity)=>pipe(sync(()=>bounded(requestedCapacity)),flatMap8((queue)=>make43(backingQueueFromMutableQueue(queue),droppingStrategy()))),sliding=(requestedCapacity)=>pipe(sync(()=>bounded(requestedCapacity)),flatMap8((queue)=>make43(backingQueueFromMutableQueue(queue),slidingStrategy()))),unbounded2=()=>pipe(sync(()=>unbounded()),flatMap8((queue)=>make43(backingQueueFromMutableQueue(queue),droppingStrategy()))),unsafeMake9=(queue,takers,shutdownHook,shutdownFlag,strategy)=>{return new QueueImpl(queue,takers,shutdownHook,shutdownFlag,strategy)},make43=(queue,strategy)=>pipe(deferredMake(),map10((deferred)=>unsafeMake9(queue,unbounded(),deferred,make12(!1),strategy)));class BackingQueueFromMutableQueue{mutable;[BackingQueueTypeId]=backingQueueVariance;constructor(mutable){this.mutable=mutable}poll(def){return poll2(this.mutable,def)}pollUpTo(limit){return pollUpTo(this.mutable,limit)}offerAll(elements){return offerAll(this.mutable,elements)}offer(element){return offer(this.mutable,element)}capacity(){return capacity(this.mutable)}length(){return length2(this.mutable)}}var backingQueueFromMutableQueue=(mutable)=>new BackingQueueFromMutableQueue(mutable),capacity2=(self)=>self.capacity(),size11=(self)=>self.size,isFull=(self)=>self.isFull,isEmpty10=(self)=>self.isEmpty,isShutdown=(self)=>self.isShutdown,awaitShutdown=(self)=>self.awaitShutdown,shutdown=(self)=>self.shutdown,offer2=dual(2,(self,value)=>self.offer(value)),unsafeOffer=dual(2,(self,value)=>self.unsafeOffer(value)),offerAll2=dual(2,(self,iterable)=>self.offerAll(iterable)),poll5=(self)=>map10(self.takeUpTo(1),head2),take2=(self)=>self.take,takeAll=(self)=>self.takeAll,takeUpTo=dual(2,(self,max6)=>self.takeUpTo(max6)),takeBetween=dual(3,(self,min4,max6)=>self.takeBetween(min4,max6)),takeN=dual(2,(self,n)=>self.takeBetween(n,n)),backPressureStrategy=()=>new BackPressureStrategy,droppingStrategy=()=>new DroppingStrategy,slidingStrategy=()=>new SlidingStrategy;class BackPressureStrategy{[QueueStrategyTypeId]=queueStrategyVariance;putters=unbounded();surplusSize(){return length2(this.putters)}onCompleteTakersWithEmptyQueue(takers){while(!isEmpty7(this.putters)&&!isEmpty7(takers)){let taker=poll2(takers,void 0),putter=poll2(this.putters,void 0);if(putter[2])unsafeCompleteDeferred(putter[1],!0);unsafeCompleteDeferred(taker,putter[0])}}get shutdown(){return pipe(fiberId,flatMap8((fiberId3)=>pipe(sync(()=>unsafePollAll(this.putters)),flatMap8((putters)=>forEachConcurrentDiscard(putters,([_,deferred,isLastItem])=>isLastItem?pipe(deferredInterruptWith(deferred,fiberId3),asVoid):void_,!1,!1)))))}handleSurplus(iterable,queue,takers,isShutdown2){return withFiberRuntime((state)=>{let deferred=deferredUnsafeMake(state.id());return pipe(suspend(()=>{return this.unsafeOffer(iterable,deferred),this.unsafeOnQueueEmptySpace(queue,takers),unsafeCompleteTakers(this,queue,takers),get6(isShutdown2)?interrupt2:deferredAwait(deferred)}),onInterrupt(()=>sync(()=>this.unsafeRemove(deferred))))})}unsafeOnQueueEmptySpace(queue,takers){let keepPolling=!0;while(keepPolling&&(queue.capacity()===Number.POSITIVE_INFINITY||queue.length()<queue.capacity())){let putter=pipe(this.putters,poll2(EmptyMutableQueue));if(putter===EmptyMutableQueue)keepPolling=!1;else{let offered=queue.offer(putter[0]);if(offered&&putter[2])unsafeCompleteDeferred(putter[1],!0);else if(!offered)unsafeOfferAll(this.putters,pipe(unsafePollAll(this.putters),prepend2(putter)));unsafeCompleteTakers(this,queue,takers)}}}unsafeOffer(iterable,deferred){let stuff=fromIterable(iterable);for(let i=0;i<stuff.length;i++){let value=stuff[i];if(i===stuff.length-1)pipe(this.putters,offer([value,deferred,!0]));else pipe(this.putters,offer([value,deferred,!1]))}}unsafeRemove(deferred){unsafeOfferAll(this.putters,pipe(unsafePollAll(this.putters),filter3(([,_])=>_!==deferred)))}}class DroppingStrategy{[QueueStrategyTypeId]=queueStrategyVariance;surplusSize(){return 0}get shutdown(){return void_}onCompleteTakersWithEmptyQueue(){}handleSurplus(_iterable,_queue,_takers,_isShutdown){return succeed(!1)}unsafeOnQueueEmptySpace(_queue,_takers){}}class SlidingStrategy{[QueueStrategyTypeId]=queueStrategyVariance;surplusSize(){return 0}get shutdown(){return void_}onCompleteTakersWithEmptyQueue(){}handleSurplus(iterable,queue,takers,_isShutdown){return sync(()=>{return this.unsafeOffer(queue,iterable),unsafeCompleteTakers(this,queue,takers),!0})}unsafeOnQueueEmptySpace(_queue,_takers){}unsafeOffer(queue,iterable){let iterator=iterable[Symbol.iterator](),next4,offering=!0;while(!(next4=iterator.next()).done&&offering){if(queue.capacity()===0)return;queue.poll(EmptyMutableQueue),offering=queue.offer(next4.value)}}}var unsafeCompleteDeferred=(deferred,a)=>{return deferredUnsafeDone(deferred,succeed(a))},unsafeOfferAll=(queue,as4)=>{return pipe(queue,offerAll(as4))},unsafePollAll=(queue)=>{return pipe(queue,pollUpTo(Number.POSITIVE_INFINITY))},unsafePollN=(queue,max6)=>{return pipe(queue,pollUpTo(max6))},unsafeRemove=(queue,a)=>{unsafeOfferAll(queue,pipe(unsafePollAll(queue),filter3((b)=>a!==b)))},unsafeCompleteTakers=(strategy,queue,takers)=>{let keepPolling=!0;while(keepPolling&&queue.length()!==0){let taker=pipe(takers,poll2(EmptyMutableQueue));if(taker!==EmptyMutableQueue){let element=queue.poll(EmptyMutableQueue);if(element!==EmptyMutableQueue)unsafeCompleteDeferred(taker,element),strategy.unsafeOnQueueEmptySpace(queue,takers);else unsafeOfferAll(takers,pipe(unsafePollAll(takers),prepend2(taker)));keepPolling=!0}else keepPolling=!1}if(keepPolling&&queue.length()===0&&!isEmpty7(takers))strategy.onCompleteTakersWithEmptyQueue(takers)};var AbsentValue=Symbol.for("effect/PubSub/AbsentValue"),addSubscribers=(subscription,pollers)=>(subscribers)=>{if(!subscribers.has(subscription))subscribers.set(subscription,new Set);subscribers.get(subscription).add(pollers)},removeSubscribers=(subscription,pollers)=>(subscribers)=>{if(!subscribers.has(subscription))return;let set7=subscribers.get(subscription);if(set7.delete(pollers),set7.size===0)subscribers.delete(subscription)},bounded3=(capacity3)=>suspend(()=>{let pubsub=makeBoundedPubSub(capacity3);return makePubSub(pubsub,new BackPressureStrategy2)}),dropping2=(capacity3)=>suspend(()=>{let pubsub=makeBoundedPubSub(capacity3);return makePubSub(pubsub,new DroppingStrategy2)}),sliding2=(capacity3)=>suspend(()=>{let pubsub=makeBoundedPubSub(capacity3);return makePubSub(pubsub,new SlidingStrategy2)}),unbounded3=(options)=>suspend(()=>{let pubsub=makeUnboundedPubSub(options);return makePubSub(pubsub,new DroppingStrategy2)});var shutdown2=(self)=>self.shutdown;var subscribe=(self)=>self.subscribe,makeBoundedPubSub=(capacity3)=>{let options=typeof capacity3==="number"?{capacity:capacity3}:capacity3;ensureCapacity(options.capacity);let replayBuffer=options.replay&&options.replay>0?new ReplayBuffer(Math.ceil(options.replay)):void 0;if(options.capacity===1)return new BoundedPubSubSingle(replayBuffer);else if(nextPow2(options.capacity)===options.capacity)return new BoundedPubSubPow2(options.capacity,replayBuffer);else return new BoundedPubSubArb(options.capacity,replayBuffer)},makeUnboundedPubSub=(options)=>new UnboundedPubSub(options?.replay?new ReplayBuffer(options.replay):void 0),makeSubscription=(pubsub,subscribers,strategy)=>map10(deferredMake(),(deferred)=>unsafeMakeSubscription(pubsub,subscribers,pubsub.subscribe(),unbounded(),deferred,make12(!1),strategy)),unsafeMakeSubscription=(pubsub,subscribers,subscription,pollers,shutdownHook,shutdownFlag,strategy)=>new SubscriptionImpl(pubsub,subscribers,subscription,pollers,shutdownHook,shutdownFlag,strategy,pubsub.replayWindow());class BoundedPubSubArb{capacity;replayBuffer;array;publisherIndex=0;subscribers;subscriberCount=0;subscribersIndex=0;constructor(capacity3,replayBuffer){this.capacity=capacity3,this.replayBuffer=replayBuffer,this.array=Array.from({length:capacity3}),this.subscribers=Array.from({length:capacity3})}replayWindow(){return this.replayBuffer?new ReplayWindowImpl(this.replayBuffer):emptyReplayWindow}isEmpty(){return this.publisherIndex===this.subscribersIndex}isFull(){return this.publisherIndex===this.subscribersIndex+this.capacity}size(){return this.publisherIndex-this.subscribersIndex}publish(value){if(this.isFull())return!1;if(this.subscriberCount!==0){let index=this.publisherIndex%this.capacity;this.array[index]=value,this.subscribers[index]=this.subscriberCount,this.publisherIndex+=1}if(this.replayBuffer)this.replayBuffer.offer(value);return!0}publishAll(elements){if(this.subscriberCount===0){if(this.replayBuffer)this.replayBuffer.offerAll(elements);return empty5()}let chunk2=fromIterable2(elements),n=chunk2.length,size12=this.publisherIndex-this.subscribersIndex,available=this.capacity-size12,forPubSub=Math.min(n,available);if(forPubSub===0)return chunk2;let iteratorIndex=0,publishAllIndex=this.publisherIndex+forPubSub;while(this.publisherIndex!==publishAllIndex){let a=unsafeGet4(chunk2,iteratorIndex++),index=this.publisherIndex%this.capacity;if(this.array[index]=a,this.subscribers[index]=this.subscriberCount,this.publisherIndex+=1,this.replayBuffer)this.replayBuffer.offer(a)}return drop2(chunk2,iteratorIndex)}slide(){if(this.subscribersIndex!==this.publisherIndex){let index=this.subscribersIndex%this.capacity;this.array[index]=AbsentValue,this.subscribers[index]=0,this.subscribersIndex+=1}if(this.replayBuffer)this.replayBuffer.slide()}subscribe(){return this.subscriberCount+=1,new BoundedPubSubArbSubscription(this,this.publisherIndex,!1)}}class BoundedPubSubArbSubscription{self;subscriberIndex;unsubscribed;constructor(self,subscriberIndex,unsubscribed){this.self=self,this.subscriberIndex=subscriberIndex,this.unsubscribed=unsubscribed}isEmpty(){return this.unsubscribed||this.self.publisherIndex===this.subscriberIndex||this.self.publisherIndex===this.self.subscribersIndex}size(){if(this.unsubscribed)return 0;return this.self.publisherIndex-Math.max(this.subscriberIndex,this.self.subscribersIndex)}poll(default_){if(this.unsubscribed)return default_;if(this.subscriberIndex=Math.max(this.subscriberIndex,this.self.subscribersIndex),this.subscriberIndex!==this.self.publisherIndex){let index=this.subscriberIndex%this.self.capacity,elem=this.self.array[index];if(this.self.subscribers[index]-=1,this.self.subscribers[index]===0)this.self.array[index]=AbsentValue,this.self.subscribersIndex+=1;return this.subscriberIndex+=1,elem}return default_}pollUpTo(n){if(this.unsubscribed)return empty5();this.subscriberIndex=Math.max(this.subscriberIndex,this.self.subscribersIndex);let size12=this.self.publisherIndex-this.subscriberIndex,toPoll=Math.min(n,size12);if(toPoll<=0)return empty5();let builder=[],pollUpToIndex=this.subscriberIndex+toPoll;while(this.subscriberIndex!==pollUpToIndex){let index=this.subscriberIndex%this.self.capacity,a=this.self.array[index];if(this.self.subscribers[index]-=1,this.self.subscribers[index]===0)this.self.array[index]=AbsentValue,this.self.subscribersIndex+=1;builder.push(a),this.subscriberIndex+=1}return fromIterable2(builder)}unsubscribe(){if(!this.unsubscribed){this.unsubscribed=!0,this.self.subscriberCount-=1,this.subscriberIndex=Math.max(this.subscriberIndex,this.self.subscribersIndex);while(this.subscriberIndex!==this.self.publisherIndex){let index=this.subscriberIndex%this.self.capacity;if(this.self.subscribers[index]-=1,this.self.subscribers[index]===0)this.self.array[index]=AbsentValue,this.self.subscribersIndex+=1;this.subscriberIndex+=1}}}}class BoundedPubSubPow2{capacity;replayBuffer;array;mask;publisherIndex=0;subscribers;subscriberCount=0;subscribersIndex=0;constructor(capacity3,replayBuffer){this.capacity=capacity3,this.replayBuffer=replayBuffer,this.array=Array.from({length:capacity3}),this.mask=capacity3-1,this.subscribers=Array.from({length:capacity3})}replayWindow(){return this.replayBuffer?new ReplayWindowImpl(this.replayBuffer):emptyReplayWindow}isEmpty(){return this.publisherIndex===this.subscribersIndex}isFull(){return this.publisherIndex===this.subscribersIndex+this.capacity}size(){return this.publisherIndex-this.subscribersIndex}publish(value){if(this.isFull())return!1;if(this.subscriberCount!==0){let index=this.publisherIndex&this.mask;this.array[index]=value,this.subscribers[index]=this.subscriberCount,this.publisherIndex+=1}if(this.replayBuffer)this.replayBuffer.offer(value);return!0}publishAll(elements){if(this.subscriberCount===0){if(this.replayBuffer)this.replayBuffer.offerAll(elements);return empty5()}let chunk2=fromIterable2(elements),n=chunk2.length,size12=this.publisherIndex-this.subscribersIndex,available=this.capacity-size12,forPubSub=Math.min(n,available);if(forPubSub===0)return chunk2;let iteratorIndex=0,publishAllIndex=this.publisherIndex+forPubSub;while(this.publisherIndex!==publishAllIndex){let elem=unsafeGet4(chunk2,iteratorIndex++),index=this.publisherIndex&this.mask;if(this.array[index]=elem,this.subscribers[index]=this.subscriberCount,this.publisherIndex+=1,this.replayBuffer)this.replayBuffer.offer(elem)}return drop2(chunk2,iteratorIndex)}slide(){if(this.subscribersIndex!==this.publisherIndex){let index=this.subscribersIndex&this.mask;this.array[index]=AbsentValue,this.subscribers[index]=0,this.subscribersIndex+=1}if(this.replayBuffer)this.replayBuffer.slide()}subscribe(){return this.subscriberCount+=1,new BoundedPubSubPow2Subscription(this,this.publisherIndex,!1)}}class BoundedPubSubPow2Subscription{self;subscriberIndex;unsubscribed;constructor(self,subscriberIndex,unsubscribed){this.self=self,this.subscriberIndex=subscriberIndex,this.unsubscribed=unsubscribed}isEmpty(){return this.unsubscribed||this.self.publisherIndex===this.subscriberIndex||this.self.publisherIndex===this.self.subscribersIndex}size(){if(this.unsubscribed)return 0;return this.self.publisherIndex-Math.max(this.subscriberIndex,this.self.subscribersIndex)}poll(default_){if(this.unsubscribed)return default_;if(this.subscriberIndex=Math.max(this.subscriberIndex,this.self.subscribersIndex),this.subscriberIndex!==this.self.publisherIndex){let index=this.subscriberIndex&this.self.mask,elem=this.self.array[index];if(this.self.subscribers[index]-=1,this.self.subscribers[index]===0)this.self.array[index]=AbsentValue,this.self.subscribersIndex+=1;return this.subscriberIndex+=1,elem}return default_}pollUpTo(n){if(this.unsubscribed)return empty5();this.subscriberIndex=Math.max(this.subscriberIndex,this.self.subscribersIndex);let size12=this.self.publisherIndex-this.subscriberIndex,toPoll=Math.min(n,size12);if(toPoll<=0)return empty5();let builder=[],pollUpToIndex=this.subscriberIndex+toPoll;while(this.subscriberIndex!==pollUpToIndex){let index=this.subscriberIndex&this.self.mask,elem=this.self.array[index];if(this.self.subscribers[index]-=1,this.self.subscribers[index]===0)this.self.array[index]=AbsentValue,this.self.subscribersIndex+=1;builder.push(elem),this.subscriberIndex+=1}return fromIterable2(builder)}unsubscribe(){if(!this.unsubscribed){this.unsubscribed=!0,this.self.subscriberCount-=1,this.subscriberIndex=Math.max(this.subscriberIndex,this.self.subscribersIndex);while(this.subscriberIndex!==this.self.publisherIndex){let index=this.subscriberIndex&this.self.mask;if(this.self.subscribers[index]-=1,this.self.subscribers[index]===0)this.self.array[index]=AbsentValue,this.self.subscribersIndex+=1;this.subscriberIndex+=1}}}}class BoundedPubSubSingle{replayBuffer;publisherIndex=0;subscriberCount=0;subscribers=0;value=AbsentValue;capacity=1;constructor(replayBuffer){this.replayBuffer=replayBuffer}replayWindow(){return this.replayBuffer?new ReplayWindowImpl(this.replayBuffer):emptyReplayWindow}pipe(){return pipeArguments(this,arguments)}isEmpty(){return this.subscribers===0}isFull(){return!this.isEmpty()}size(){return this.isEmpty()?0:1}publish(value){if(this.isFull())return!1;if(this.subscriberCount!==0)this.value=value,this.subscribers=this.subscriberCount,this.publisherIndex+=1;if(this.replayBuffer)this.replayBuffer.offer(value);return!0}publishAll(elements){if(this.subscriberCount===0){if(this.replayBuffer)this.replayBuffer.offerAll(elements);return empty5()}let chunk2=fromIterable2(elements);if(isEmpty(chunk2))return chunk2;if(this.publish(unsafeHead2(chunk2)))return drop2(chunk2,1);else return chunk2}slide(){if(this.isFull())this.subscribers=0,this.value=AbsentValue;if(this.replayBuffer)this.replayBuffer.slide()}subscribe(){return this.subscriberCount+=1,new BoundedPubSubSingleSubscription(this,this.publisherIndex,!1)}}class BoundedPubSubSingleSubscription{self;subscriberIndex;unsubscribed;constructor(self,subscriberIndex,unsubscribed){this.self=self,this.subscriberIndex=subscriberIndex,this.unsubscribed=unsubscribed}isEmpty(){return this.unsubscribed||this.self.subscribers===0||this.subscriberIndex===this.self.publisherIndex}size(){return this.isEmpty()?0:1}poll(default_){if(this.isEmpty())return default_;let elem=this.self.value;if(this.self.subscribers-=1,this.self.subscribers===0)this.self.value=AbsentValue;return this.subscriberIndex+=1,elem}pollUpTo(n){if(this.isEmpty()||n<1)return empty5();let a=this.self.value;if(this.self.subscribers-=1,this.self.subscribers===0)this.self.value=AbsentValue;return this.subscriberIndex+=1,of2(a)}unsubscribe(){if(!this.unsubscribed){if(this.unsubscribed=!0,this.self.subscriberCount-=1,this.subscriberIndex!==this.self.publisherIndex){if(this.self.subscribers-=1,this.self.subscribers===0)this.self.value=AbsentValue}}}}class UnboundedPubSub{replayBuffer;publisherHead={value:AbsentValue,subscribers:0,next:null};publisherTail=this.publisherHead;publisherIndex=0;subscribersIndex=0;capacity=Number.MAX_SAFE_INTEGER;constructor(replayBuffer){this.replayBuffer=replayBuffer}replayWindow(){return this.replayBuffer?new ReplayWindowImpl(this.replayBuffer):emptyReplayWindow}isEmpty(){return this.publisherHead===this.publisherTail}isFull(){return!1}size(){return this.publisherIndex-this.subscribersIndex}publish(value){let subscribers=this.publisherTail.subscribers;if(subscribers!==0)this.publisherTail.next={value,subscribers,next:null},this.publisherTail=this.publisherTail.next,this.publisherIndex+=1;if(this.replayBuffer)this.replayBuffer.offer(value);return!0}publishAll(elements){if(this.publisherTail.subscribers!==0)for(let a of elements)this.publish(a);else if(this.replayBuffer)this.replayBuffer.offerAll(elements);return empty5()}slide(){if(this.publisherHead!==this.publisherTail)this.publisherHead=this.publisherHead.next,this.publisherHead.value=AbsentValue,this.subscribersIndex+=1;if(this.replayBuffer)this.replayBuffer.slide()}subscribe(){return this.publisherTail.subscribers+=1,new UnboundedPubSubSubscription(this,this.publisherTail,this.publisherIndex,!1)}}class UnboundedPubSubSubscription{self;subscriberHead;subscriberIndex;unsubscribed;constructor(self,subscriberHead,subscriberIndex,unsubscribed){this.self=self,this.subscriberHead=subscriberHead,this.subscriberIndex=subscriberIndex,this.unsubscribed=unsubscribed}isEmpty(){if(this.unsubscribed)return!0;let empty34=!0,loop3=!0;while(loop3)if(this.subscriberHead===this.self.publisherTail)loop3=!1;else if(this.subscriberHead.next.value!==AbsentValue)empty34=!1,loop3=!1;else this.subscriberHead=this.subscriberHead.next,this.subscriberIndex+=1;return empty34}size(){if(this.unsubscribed)return 0;return this.self.publisherIndex-Math.max(this.subscriberIndex,this.self.subscribersIndex)}poll(default_){if(this.unsubscribed)return default_;let loop3=!0,polled=default_;while(loop3)if(this.subscriberHead===this.self.publisherTail)loop3=!1;else{let elem=this.subscriberHead.next.value;if(elem!==AbsentValue){if(polled=elem,this.subscriberHead.subscribers-=1,this.subscriberHead.subscribers===0)this.self.publisherHead=this.self.publisherHead.next,this.self.publisherHead.value=AbsentValue,this.self.subscribersIndex+=1;loop3=!1}this.subscriberHead=this.subscriberHead.next,this.subscriberIndex+=1}return polled}pollUpTo(n){let builder=[],default_=AbsentValue,i=0;while(i!==n){let a=this.poll(default_);if(a===default_)i=n;else builder.push(a),i+=1}return fromIterable2(builder)}unsubscribe(){if(!this.unsubscribed){this.unsubscribed=!0,this.self.publisherTail.subscribers-=1;while(this.subscriberHead!==this.self.publisherTail){if(this.subscriberHead.next.value!==AbsentValue){if(this.subscriberHead.subscribers-=1,this.subscriberHead.subscribers===0)this.self.publisherHead=this.self.publisherHead.next,this.self.publisherHead.value=AbsentValue,this.self.subscribersIndex+=1}this.subscriberHead=this.subscriberHead.next}}}}class SubscriptionImpl extends Class{pubsub;subscribers;subscription;pollers;shutdownHook;shutdownFlag;strategy;replayWindow;[DequeueTypeId]=dequeueVariance;constructor(pubsub,subscribers,subscription,pollers,shutdownHook,shutdownFlag,strategy,replayWindow){super();this.pubsub=pubsub,this.subscribers=subscribers,this.subscription=subscription,this.pollers=pollers,this.shutdownHook=shutdownHook,this.shutdownFlag=shutdownFlag,this.strategy=strategy,this.replayWindow=replayWindow}commit(){return this.take}pipe(){return pipeArguments(this,arguments)}capacity(){return this.pubsub.capacity}isActive(){return!get6(this.shutdownFlag)}get size(){return suspend(()=>get6(this.shutdownFlag)?interrupt2:succeed(this.subscription.size()+this.replayWindow.remaining))}unsafeSize(){if(get6(this.shutdownFlag))return none2();return some2(this.subscription.size()+this.replayWindow.remaining)}get isFull(){return suspend(()=>get6(this.shutdownFlag)?interrupt2:succeed(this.subscription.size()===this.capacity()))}get isEmpty(){return map10(this.size,(size12)=>size12===0)}get shutdown(){return uninterruptible(withFiberRuntime((state)=>{return set2(this.shutdownFlag,!0),pipe(forEachParUnbounded(unsafePollAllQueue(this.pollers),(d)=>deferredInterruptWith(d,state.id()),!1),zipRight(sync(()=>{this.subscribers.delete(this.subscription),this.subscription.unsubscribe(),this.strategy.unsafeOnPubSubEmptySpace(this.pubsub,this.subscribers)})),whenEffect(deferredSucceed(this.shutdownHook,void 0)),asVoid)}))}get isShutdown(){return sync(()=>get6(this.shutdownFlag))}get awaitShutdown(){return deferredAwait(this.shutdownHook)}get take(){return withFiberRuntime((state)=>{if(get6(this.shutdownFlag))return interrupt2;if(this.replayWindow.remaining>0){let message2=this.replayWindow.take();return succeed(message2)}let message=isEmpty7(this.pollers)?this.subscription.poll(EmptyMutableQueue):EmptyMutableQueue;if(message===EmptyMutableQueue){let deferred=deferredUnsafeMake(state.id());return pipe(suspend(()=>{return pipe(this.pollers,offer(deferred)),pipe(this.subscribers,addSubscribers(this.subscription,this.pollers)),this.strategy.unsafeCompletePollers(this.pubsub,this.subscribers,this.subscription,this.pollers),get6(this.shutdownFlag)?interrupt2:deferredAwait(deferred)}),onInterrupt(()=>sync(()=>unsafeRemove2(this.pollers,deferred))))}else return this.strategy.unsafeOnPubSubEmptySpace(this.pubsub,this.subscribers),succeed(message)})}get takeAll(){return suspend(()=>{if(get6(this.shutdownFlag))return interrupt2;let as4=isEmpty7(this.pollers)?unsafePollAllSubscription(this.subscription):empty5();if(this.strategy.unsafeOnPubSubEmptySpace(this.pubsub,this.subscribers),this.replayWindow.remaining>0)return succeed(appendAll2(this.replayWindow.takeAll(),as4));return succeed(as4)})}takeUpTo(max6){return suspend(()=>{if(get6(this.shutdownFlag))return interrupt2;let replay=void 0;if(this.replayWindow.remaining>=max6){let as5=this.replayWindow.takeN(max6);return succeed(as5)}else if(this.replayWindow.remaining>0)replay=this.replayWindow.takeAll(),max6=max6-replay.length;let as4=isEmpty7(this.pollers)?unsafePollN2(this.subscription,max6):empty5();return this.strategy.unsafeOnPubSubEmptySpace(this.pubsub,this.subscribers),replay?succeed(appendAll2(replay,as4)):succeed(as4)})}takeBetween(min4,max6){return suspend(()=>takeRemainderLoop2(this,min4,max6,empty5()))}}var takeRemainderLoop2=(self,min4,max6,acc)=>{if(max6<min4)return succeed(acc);return pipe(self.takeUpTo(max6),flatMap8((bs)=>{let remaining=min4-bs.length;if(remaining===1)return pipe(self.take,map10((b)=>pipe(acc,appendAll2(bs),append2(b))));if(remaining>1)return pipe(self.take,flatMap8((b)=>takeRemainderLoop2(self,remaining-1,max6-bs.length-1,pipe(acc,appendAll2(bs),append2(b)))));return succeed(pipe(acc,appendAll2(bs)))}))};class PubSubImpl{pubsub;subscribers;scope;shutdownHook;shutdownFlag;strategy;[EnqueueTypeId]=enqueueVariance;[DequeueTypeId]=dequeueVariance;constructor(pubsub,subscribers,scope4,shutdownHook,shutdownFlag,strategy){this.pubsub=pubsub,this.subscribers=subscribers,this.scope=scope4,this.shutdownHook=shutdownHook,this.shutdownFlag=shutdownFlag,this.strategy=strategy}capacity(){return this.pubsub.capacity}get size(){return suspend(()=>get6(this.shutdownFlag)?interrupt2:sync(()=>this.pubsub.size()))}unsafeSize(){if(get6(this.shutdownFlag))return none2();return some2(this.pubsub.size())}get isFull(){return map10(this.size,(size12)=>size12===this.capacity())}get isEmpty(){return map10(this.size,(size12)=>size12===0)}get awaitShutdown(){return deferredAwait(this.shutdownHook)}get isShutdown(){return sync(()=>get6(this.shutdownFlag))}get shutdown(){return uninterruptible(withFiberRuntime((state)=>{return pipe(this.shutdownFlag,set2(!0)),pipe(this.scope.close(exitInterrupt(state.id())),zipRight(this.strategy.shutdown),whenEffect(deferredSucceed(this.shutdownHook,void 0)),asVoid)}))}publish(value){return suspend(()=>{if(get6(this.shutdownFlag))return interrupt2;if(this.pubsub.publish(value))return this.strategy.unsafeCompleteSubscribers(this.pubsub,this.subscribers),succeed(!0);return this.strategy.handleSurplus(this.pubsub,this.subscribers,of2(value),this.shutdownFlag)})}isActive(){return!get6(this.shutdownFlag)}unsafeOffer(value){if(get6(this.shutdownFlag))return!1;if(this.pubsub.publish(value))return this.strategy.unsafeCompleteSubscribers(this.pubsub,this.subscribers),!0;return!1}publishAll(elements){return suspend(()=>{if(get6(this.shutdownFlag))return interrupt2;let surplus=unsafePublishAll(this.pubsub,elements);if(this.strategy.unsafeCompleteSubscribers(this.pubsub,this.subscribers),isEmpty(surplus))return succeed(!0);return this.strategy.handleSurplus(this.pubsub,this.subscribers,surplus,this.shutdownFlag)})}get subscribe(){let acquire=tap(all4([this.scope.fork(sequential2),makeSubscription(this.pubsub,this.subscribers,this.strategy)]),(tuple3)=>tuple3[0].addFinalizer(()=>tuple3[1].shutdown));return map10(acquireRelease(acquire,(tuple3,exit3)=>tuple3[0].close(exit3)),(tuple3)=>tuple3[1])}offer(value){return this.publish(value)}offerAll(elements){return this.publishAll(elements)}pipe(){return pipeArguments(this,arguments)}}var makePubSub=(pubsub,strategy)=>flatMap8(scopeMake(),(scope4)=>map10(deferredMake(),(deferred)=>unsafeMakePubSub(pubsub,new Map,scope4,deferred,make12(!1),strategy))),unsafeMakePubSub=(pubsub,subscribers,scope4,shutdownHook,shutdownFlag,strategy)=>new PubSubImpl(pubsub,subscribers,scope4,shutdownHook,shutdownFlag,strategy),ensureCapacity=(capacity3)=>{if(capacity3<=0)throw new InvalidPubSubCapacityException(`Cannot construct PubSub with capacity of ${capacity3}`)},unsafeCompleteDeferred2=(deferred,a)=>{deferredUnsafeDone(deferred,succeed(a))},unsafeOfferAll2=(queue,as4)=>{return pipe(queue,offerAll(as4))},unsafePollAllQueue=(queue)=>{return pipe(queue,pollUpTo(Number.POSITIVE_INFINITY))},unsafePollAllSubscription=(subscription)=>{return subscription.pollUpTo(Number.POSITIVE_INFINITY)},unsafePollN2=(subscription,max6)=>{return subscription.pollUpTo(max6)},unsafePublishAll=(pubsub,as4)=>{return pubsub.publishAll(as4)},unsafeRemove2=(queue,value)=>{unsafeOfferAll2(queue,pipe(unsafePollAllQueue(queue),filter3((elem)=>elem!==value)))};class BackPressureStrategy2{publishers=unbounded();get shutdown(){return flatMap8(fiberId,(fiberId3)=>flatMap8(sync(()=>unsafePollAllQueue(this.publishers)),(publishers)=>forEachConcurrentDiscard(publishers,([_,deferred,last4])=>last4?pipe(deferredInterruptWith(deferred,fiberId3),asVoid):void_,!1,!1)))}handleSurplus(pubsub,subscribers,elements,isShutdown2){return withFiberRuntime((state)=>{let deferred=deferredUnsafeMake(state.id());return pipe(suspend(()=>{return this.unsafeOffer(elements,deferred),this.unsafeOnPubSubEmptySpace(pubsub,subscribers),this.unsafeCompleteSubscribers(pubsub,subscribers),get6(isShutdown2)?interrupt2:deferredAwait(deferred)}),onInterrupt(()=>sync(()=>this.unsafeRemove(deferred))))})}unsafeOnPubSubEmptySpace(pubsub,subscribers){let keepPolling=!0;while(keepPolling&&!pubsub.isFull()){let publisher=pipe(this.publishers,poll2(EmptyMutableQueue));if(publisher===EmptyMutableQueue)keepPolling=!1;else{let published=pubsub.publish(publisher[0]);if(published&&publisher[2])unsafeCompleteDeferred2(publisher[1],!0);else if(!published)unsafeOfferAll2(this.publishers,pipe(unsafePollAllQueue(this.publishers),prepend2(publisher)));this.unsafeCompleteSubscribers(pubsub,subscribers)}}}unsafeCompletePollers(pubsub,subscribers,subscription,pollers){return unsafeStrategyCompletePollers(this,pubsub,subscribers,subscription,pollers)}unsafeCompleteSubscribers(pubsub,subscribers){return unsafeStrategyCompleteSubscribers(this,pubsub,subscribers)}unsafeOffer(elements,deferred){let iterator=elements[Symbol.iterator](),next4=iterator.next();if(!next4.done)while(!0){let value=next4.value;if(next4=iterator.next(),next4.done){pipe(this.publishers,offer([value,deferred,!0]));break}pipe(this.publishers,offer([value,deferred,!1]))}}unsafeRemove(deferred){unsafeOfferAll2(this.publishers,pipe(unsafePollAllQueue(this.publishers),filter3(([_,a])=>a!==deferred)))}}class DroppingStrategy2{get shutdown(){return void_}handleSurplus(_pubsub,_subscribers,_elements,_isShutdown){return succeed(!1)}unsafeOnPubSubEmptySpace(_pubsub,_subscribers){}unsafeCompletePollers(pubsub,subscribers,subscription,pollers){return unsafeStrategyCompletePollers(this,pubsub,subscribers,subscription,pollers)}unsafeCompleteSubscribers(pubsub,subscribers){return unsafeStrategyCompleteSubscribers(this,pubsub,subscribers)}}class SlidingStrategy2{get shutdown(){return void_}handleSurplus(pubsub,subscribers,elements,_isShutdown){return sync(()=>{return this.unsafeSlidingPublish(pubsub,elements),this.unsafeCompleteSubscribers(pubsub,subscribers),!0})}unsafeOnPubSubEmptySpace(_pubsub,_subscribers){}unsafeCompletePollers(pubsub,subscribers,subscription,pollers){return unsafeStrategyCompletePollers(this,pubsub,subscribers,subscription,pollers)}unsafeCompleteSubscribers(pubsub,subscribers){return unsafeStrategyCompleteSubscribers(this,pubsub,subscribers)}unsafeSlidingPublish(pubsub,elements){let it=elements[Symbol.iterator](),next4=it.next();if(!next4.done&&pubsub.capacity>0){let a=next4.value,loop3=!0;while(loop3){pubsub.slide();let pub=pubsub.publish(a);if(pub&&(next4=it.next())&&!next4.done)a=next4.value;else if(pub)loop3=!1}}}}var unsafeStrategyCompletePollers=(strategy,pubsub,subscribers,subscription,pollers)=>{let keepPolling=!0;while(keepPolling&&!subscription.isEmpty()){let poller=pipe(pollers,poll2(EmptyMutableQueue));if(poller===EmptyMutableQueue)if(pipe(subscribers,removeSubscribers(subscription,pollers)),isEmpty7(pollers))keepPolling=!1;else pipe(subscribers,addSubscribers(subscription,pollers));else{let pollResult=subscription.poll(EmptyMutableQueue);if(pollResult===EmptyMutableQueue)unsafeOfferAll2(pollers,pipe(unsafePollAllQueue(pollers),prepend2(poller)));else unsafeCompleteDeferred2(poller,pollResult),strategy.unsafeOnPubSubEmptySpace(pubsub,subscribers)}}},unsafeStrategyCompleteSubscribers=(strategy,pubsub,subscribers)=>{for(let[subscription,pollersSet]of subscribers)for(let pollers of pollersSet)strategy.unsafeCompletePollers(pubsub,subscribers,subscription,pollers)};class ReplayBuffer{capacity;constructor(capacity3){this.capacity=capacity3}head={value:AbsentValue,next:null};tail=this.head;size=0;index=0;slide(){this.index++}offer(a){if(this.tail.value=a,this.tail.next={value:AbsentValue,next:null},this.tail=this.tail.next,this.size===this.capacity)this.head=this.head.next;else this.size+=1}offerAll(as4){for(let a of as4)this.offer(a)}}class ReplayWindowImpl{buffer;head;index;remaining;constructor(buffer){this.buffer=buffer,this.index=buffer.index,this.remaining=buffer.size,this.head=buffer.head}fastForward(){while(this.index<this.buffer.index)this.head=this.head.next,this.index++}take(){if(this.remaining===0)return;else if(this.index<this.buffer.index)this.fastForward();this.remaining--;let value=this.head.value;return this.head=this.head.next,value}takeN(n){if(this.remaining===0)return empty5();else if(this.index<this.buffer.index)this.fastForward();let len=Math.min(n,this.remaining),items=new Array(len);for(let i=0;i<len;i++){let value=this.head.value;this.head=this.head.next,items[i]=value}return this.remaining-=len,unsafeFromArray(items)}takeAll(){return this.takeN(this.remaining)}}var emptyReplayWindow={remaining:0,take:()=>{return},takeN:()=>empty5(),takeAll:()=>empty5()};var bounded4=bounded3,dropping3=dropping2,sliding3=sliding2,unbounded4=unbounded3;var shutdown3=shutdown2;var subscribe2=subscribe;var exports_Queue={};__export(exports_Queue,{unsafeOffer:()=>unsafeOffer2,unbounded:()=>unbounded5,takeUpTo:()=>takeUpTo2,takeN:()=>takeN2,takeBetween:()=>takeBetween2,takeAll:()=>takeAll2,take:()=>take3,slidingStrategy:()=>slidingStrategy2,sliding:()=>sliding4,size:()=>size13,shutdown:()=>shutdown4,poll:()=>poll6,offerAll:()=>offerAll3,offer:()=>offer3,make:()=>make44,isShutdown:()=>isShutdown3,isQueue:()=>isQueue2,isFull:()=>isFull3,isEnqueue:()=>isEnqueue2,isEmpty:()=>isEmpty12,isDequeue:()=>isDequeue2,droppingStrategy:()=>droppingStrategy2,dropping:()=>dropping4,capacity:()=>capacity4,bounded:()=>bounded5,backPressureStrategy:()=>backPressureStrategy2,awaitShutdown:()=>awaitShutdown3,QueueStrategyTypeId:()=>QueueStrategyTypeId2,EnqueueTypeId:()=>EnqueueTypeId2,DequeueTypeId:()=>DequeueTypeId2,BackingQueueTypeId:()=>BackingQueueTypeId2});var EnqueueTypeId2=EnqueueTypeId,DequeueTypeId2=DequeueTypeId,QueueStrategyTypeId2=QueueStrategyTypeId,BackingQueueTypeId2=BackingQueueTypeId,isQueue2=isQueue,isDequeue2=isDequeue,isEnqueue2=isEnqueue,backPressureStrategy2=backPressureStrategy,droppingStrategy2=droppingStrategy,slidingStrategy2=slidingStrategy,make44=make43,bounded5=bounded2,dropping4=dropping,sliding4=sliding,unbounded5=unbounded2,capacity4=capacity2,size13=size11,isEmpty12=isEmpty10,isFull3=isFull,isShutdown3=isShutdown,awaitShutdown3=awaitShutdown,shutdown4=shutdown,offer3=offer2,unsafeOffer2=unsafeOffer,offerAll3=offerAll2,poll6=poll5,take3=take2,takeAll2=takeAll,takeUpTo2=takeUpTo,takeBetween2=takeBetween,takeN2=takeN;var OP_CONTINUE2="Continue",OP_CLOSE="Close",OP_YIELD2="Yield";var ChildExecutorDecisionSymbolKey="effect/ChannelChildExecutorDecision",ChildExecutorDecisionTypeId=Symbol.for(ChildExecutorDecisionSymbolKey),proto4={[ChildExecutorDecisionTypeId]:ChildExecutorDecisionTypeId},Continue=(_)=>{let op=Object.create(proto4);return op._tag=OP_CONTINUE2,op};var OP_CONTINUATION_K="ContinuationK",OP_CONTINUATION_FINALIZER="ContinuationFinalizer";var ContinuationTypeId=Symbol.for("effect/ChannelContinuation"),continuationVariance={_Env:(_)=>_,_InErr:(_)=>_,_InElem:(_)=>_,_InDone:(_)=>_,_OutErr:(_)=>_,_OutDone:(_)=>_,_OutErr2:(_)=>_,_OutElem:(_)=>_,_OutDone2:(_)=>_};class ContinuationKImpl{onSuccess;onHalt;_tag=OP_CONTINUATION_K;[ContinuationTypeId]=continuationVariance;constructor(onSuccess,onHalt){this.onSuccess=onSuccess,this.onHalt=onHalt}onExit(exit3){return isFailure(exit3)?this.onHalt(exit3.cause):this.onSuccess(exit3.value)}}class ContinuationFinalizerImpl{finalizer;_tag=OP_CONTINUATION_FINALIZER;[ContinuationTypeId]=continuationVariance;constructor(finalizer){this.finalizer=finalizer}}var OP_PULL_AFTER_NEXT="PullAfterNext",OP_PULL_AFTER_ALL_ENQUEUED="PullAfterAllEnqueued";var UpstreamPullStrategySymbolKey="effect/ChannelUpstreamPullStrategy",UpstreamPullStrategyTypeId=Symbol.for(UpstreamPullStrategySymbolKey),upstreamPullStrategyVariance={_A:(_)=>_},proto5={[UpstreamPullStrategyTypeId]:upstreamPullStrategyVariance},PullAfterNext=(emitSeparator)=>{let op=Object.create(proto5);return op._tag=OP_PULL_AFTER_NEXT,op.emitSeparator=emitSeparator,op};var OP_BRACKET_OUT="BracketOut",OP_BRIDGE="Bridge",OP_CONCAT_ALL="ConcatAll",OP_EMIT="Emit",OP_ENSURING="Ensuring",OP_FAIL3="Fail",OP_FOLD2="Fold",OP_FROM_EFFECT2="FromEffect",OP_PIPE_TO="PipeTo",OP_PROVIDE2="Provide",OP_READ="Read",OP_SUCCEED="Succeed",OP_SUCCEED_NOW="SucceedNow",OP_SUSPEND2="Suspend";var ChannelSymbolKey="effect/Channel",ChannelTypeId2=Symbol.for(ChannelSymbolKey),channelVariance2={_Env:(_)=>_,_InErr:(_)=>_,_InElem:(_)=>_,_InDone:(_)=>_,_OutErr:(_)=>_,_OutElem:(_)=>_,_OutDone:(_)=>_},proto6={[ChannelTypeId2]:channelVariance2,pipe(){return pipeArguments(this,arguments)}},isChannel=(u)=>hasProperty(u,ChannelTypeId2)||isEffect2(u),acquireReleaseOut=dual(2,(self,release)=>{let op=Object.create(proto6);return op._tag=OP_BRACKET_OUT,op.acquire=()=>self,op.finalizer=release,op}),catchAllCause4=dual(2,(self,f)=>{let op=Object.create(proto6);return op._tag=OP_FOLD2,op.channel=self,op.k=new ContinuationKImpl(succeed10,f),op}),collectElements=(self)=>{return suspend4(()=>{let builder=[];return flatMap12(pipeTo(self,collectElementsReader(builder)),(value)=>sync4(()=>[fromIterable2(builder),value]))})},collectElementsReader=(builder)=>readWith({onInput:(outElem)=>flatMap12(sync4(()=>{builder.push(outElem)}),()=>collectElementsReader(builder)),onFailure:fail11,onDone:succeedNow});var concatAllWith=(channels,f,g)=>{let op=Object.create(proto6);return op._tag=OP_CONCAT_ALL,op.combineInners=f,op.combineAll=g,op.onPull=()=>PullAfterNext(none2()),op.onEmit=()=>Continue,op.value=()=>channels,op.k=identity,op},concatMapWith=dual(4,(self,f,g,h)=>{let op=Object.create(proto6);return op._tag=OP_CONCAT_ALL,op.combineInners=g,op.combineAll=h,op.onPull=()=>PullAfterNext(none2()),op.onEmit=()=>Continue,op.value=()=>self,op.k=f,op});var embedInput=dual(2,(self,input)=>{let op=Object.create(proto6);return op._tag=OP_BRIDGE,op.input=input,op.channel=self,op}),ensuringWith=dual(2,(self,finalizer)=>{let op=Object.create(proto6);return op._tag=OP_ENSURING,op.channel=self,op.finalizer=finalizer,op}),fail11=(error)=>failCause10(fail6(error));var failCause10=(cause3)=>failCauseSync4(()=>cause3),failCauseSync4=(evaluate2)=>{let op=Object.create(proto6);return op._tag=OP_FAIL3,op.error=evaluate2,op},flatMap12=dual(2,(self,f)=>{let op=Object.create(proto6);return op._tag=OP_FOLD2,op.channel=self,op.k=new ContinuationKImpl(f,failCause10),op}),foldCauseChannel=dual(2,(self,options)=>{let op=Object.create(proto6);return op._tag=OP_FOLD2,op.channel=self,op.k=new ContinuationKImpl(options.onSuccess,options.onFailure),op}),fromEffect5=(effect)=>{let op=Object.create(proto6);return op._tag=OP_FROM_EFFECT2,op.effect=()=>effect,op},pipeTo=dual(2,(self,that)=>{let op=Object.create(proto6);return op._tag=OP_PIPE_TO,op.left=()=>self,op.right=()=>that,op}),provideContext3=dual(2,(self,env)=>{let op=Object.create(proto6);return op._tag=OP_PROVIDE2,op.context=()=>env,op.inner=self,op});var readWith=(options)=>readWithCause({onInput:options.onInput,onFailure:(cause3)=>match(failureOrCause2(cause3),{onLeft:options.onFailure,onRight:failCause10}),onDone:options.onDone}),readWithCause=(options)=>{let op=Object.create(proto6);return op._tag=OP_READ,op.more=options.onInput,op.done=new ContinuationKImpl(options.onDone,options.onFailure),op},succeed10=(value)=>sync4(()=>value),succeedNow=(result)=>{let op=Object.create(proto6);return op._tag=OP_SUCCEED_NOW,op.terminal=result,op},suspend4=(evaluate2)=>{let op=Object.create(proto6);return op._tag=OP_SUSPEND2,op.channel=evaluate2,op},sync4=(evaluate2)=>{let op=Object.create(proto6);return op._tag=OP_SUCCEED,op.evaluate=evaluate2,op},void_6=succeedNow(void 0);var write=(out)=>{let op=Object.create(proto6);return op._tag=OP_EMIT,op.out=out,op};var OP_DONE3="Done",OP_EMIT2="Emit",OP_FROM_EFFECT3="FromEffect",OP_READ2="Read";var ChannelStateTypeId=Symbol.for("effect/ChannelState"),channelStateVariance={_E:(_)=>_,_R:(_)=>_},proto7={[ChannelStateTypeId]:channelStateVariance},Done2=()=>{let op=Object.create(proto7);return op._tag=OP_DONE3,op},Emit=()=>{let op=Object.create(proto7);return op._tag=OP_EMIT2,op},fromEffect6=(effect)=>{let op=Object.create(proto7);return op._tag=OP_FROM_EFFECT3,op.effect=effect,op},Read=(upstream,onEffect,onEmit,onDone)=>{let op=Object.create(proto7);return op._tag=OP_READ2,op.upstream=upstream,op.onEffect=onEffect,op.onEmit=onEmit,op.onDone=onDone,op};var isFromEffect=(self)=>self._tag===OP_FROM_EFFECT3;var effect=(self)=>isFromEffect(self)?self.effect:_void,effectOrUndefinedIgnored=(self)=>isFromEffect(self)?ignore2(self.effect):void 0;var OP_PULL_FROM_CHILD="PullFromChild",OP_PULL_FROM_UPSTREAM="PullFromUpstream",OP_DRAIN_CHILD_EXECUTORS="DrainChildExecutors",OP_EMIT3="Emit";class PullFromChild{childExecutor;parentSubexecutor;onEmit;_tag=OP_PULL_FROM_CHILD;constructor(childExecutor,parentSubexecutor,onEmit){this.childExecutor=childExecutor,this.parentSubexecutor=parentSubexecutor,this.onEmit=onEmit}close(exit3){let fin1=this.childExecutor.close(exit3),fin2=this.parentSubexecutor.close(exit3);if(fin1!==void 0&&fin2!==void 0)return zipWith8(exit2(fin1),exit2(fin2),(exit1,exit22)=>pipe(exit1,zipRight2(exit22)));else if(fin1!==void 0)return fin1;else if(fin2!==void 0)return fin2;else return}enqueuePullFromChild(_child){return this}}class PullFromUpstream{upstreamExecutor;createChild;lastDone;activeChildExecutors;combineChildResults;combineWithChildResult;onPull;onEmit;_tag=OP_PULL_FROM_UPSTREAM;constructor(upstreamExecutor,createChild,lastDone,activeChildExecutors,combineChildResults,combineWithChildResult,onPull,onEmit){this.upstreamExecutor=upstreamExecutor,this.createChild=createChild,this.lastDone=lastDone,this.activeChildExecutors=activeChildExecutors,this.combineChildResults=combineChildResults,this.combineWithChildResult=combineWithChildResult,this.onPull=onPull,this.onEmit=onEmit}close(exit3){let fin1=this.upstreamExecutor.close(exit3),result=[...this.activeChildExecutors.map((child)=>child!==void 0?child.childExecutor.close(exit3):void 0),fin1].reduce((acc,next4)=>{if(acc!==void 0&&next4!==void 0)return zipWith8(acc,exit2(next4),(exit1,exit22)=>zipRight2(exit1,exit22));else if(acc!==void 0)return acc;else if(next4!==void 0)return exit2(next4);else return},void 0);return result===void 0?result:result}enqueuePullFromChild(child){return new PullFromUpstream(this.upstreamExecutor,this.createChild,this.lastDone,[...this.activeChildExecutors,child],this.combineChildResults,this.combineWithChildResult,this.onPull,this.onEmit)}}class DrainChildExecutors{upstreamExecutor;lastDone;activeChildExecutors;upstreamDone;combineChildResults;combineWithChildResult;onPull;_tag=OP_DRAIN_CHILD_EXECUTORS;constructor(upstreamExecutor,lastDone,activeChildExecutors,upstreamDone,combineChildResults,combineWithChildResult,onPull){this.upstreamExecutor=upstreamExecutor,this.lastDone=lastDone,this.activeChildExecutors=activeChildExecutors,this.upstreamDone=upstreamDone,this.combineChildResults=combineChildResults,this.combineWithChildResult=combineWithChildResult,this.onPull=onPull}close(exit3){let fin1=this.upstreamExecutor.close(exit3),result=[...this.activeChildExecutors.map((child)=>child!==void 0?child.childExecutor.close(exit3):void 0),fin1].reduce((acc,next4)=>{if(acc!==void 0&&next4!==void 0)return zipWith8(acc,exit2(next4),(exit1,exit22)=>zipRight2(exit1,exit22));else if(acc!==void 0)return acc;else if(next4!==void 0)return exit2(next4);else return},void 0);return result===void 0?result:result}enqueuePullFromChild(child){return new DrainChildExecutors(this.upstreamExecutor,this.lastDone,[...this.activeChildExecutors,child],this.upstreamDone,this.combineChildResults,this.combineWithChildResult,this.onPull)}}class Emit2{value;next;_tag=OP_EMIT3;constructor(value,next4){this.value=value,this.next=next4}close(exit3){let result=this.next.close(exit3);return result===void 0?result:result}enqueuePullFromChild(_child){return this}}var OP_PULLED="Pulled",OP_NO_UPSTREAM="NoUpstream";var UpstreamPullRequestSymbolKey="effect/ChannelUpstreamPullRequest",UpstreamPullRequestTypeId=Symbol.for(UpstreamPullRequestSymbolKey),upstreamPullRequestVariance={_A:(_)=>_},proto8={[UpstreamPullRequestTypeId]:upstreamPullRequestVariance},Pulled=(value)=>{let op=Object.create(proto8);return op._tag=OP_PULLED,op.value=value,op},NoUpstream=(activeDownstreamCount)=>{let op=Object.create(proto8);return op._tag=OP_NO_UPSTREAM,op.activeDownstreamCount=activeDownstreamCount,op};class ChannelExecutor{_activeSubexecutor=void 0;_cancelled=void 0;_closeLastSubstream=void 0;_currentChannel;_done=void 0;_doneStack=[];_emitted=void 0;_executeCloseLastSubstream;_input=void 0;_inProgressFinalizer=void 0;_providedEnv;constructor(initialChannel,providedEnv,executeCloseLastSubstream){this._currentChannel=initialChannel,this._executeCloseLastSubstream=executeCloseLastSubstream,this._providedEnv=providedEnv}run(){let result=void 0;while(result===void 0)if(this._cancelled!==void 0)result=this.processCancellation();else if(this._activeSubexecutor!==void 0)result=this.runSubexecutor();else try{if(this._currentChannel===void 0)result=Done2();else{if(isEffect2(this._currentChannel))this._currentChannel=fromEffect5(this._currentChannel);switch(this._currentChannel._tag){case OP_BRACKET_OUT:{result=this.runBracketOut(this._currentChannel);break}case OP_BRIDGE:{let bridgeInput=this._currentChannel.input;if(this._currentChannel=this._currentChannel.channel,this._input!==void 0){let inputExecutor=this._input;this._input=void 0;let drainer=()=>flatMap10(bridgeInput.awaitRead(),()=>suspend3(()=>{let state=inputExecutor.run();switch(state._tag){case OP_DONE3:return match6(inputExecutor.getDone(),{onFailure:(cause3)=>bridgeInput.error(cause3),onSuccess:(value)=>bridgeInput.done(value)});case OP_EMIT2:return flatMap10(bridgeInput.emit(inputExecutor.getEmit()),()=>drainer());case OP_FROM_EFFECT3:return matchCauseEffect3(state.effect,{onFailure:(cause3)=>bridgeInput.error(cause3),onSuccess:()=>drainer()});case OP_READ2:return readUpstream(state,()=>drainer(),(cause3)=>bridgeInput.error(cause3))}}));result=fromEffect6(flatMap10(forkDaemon2(interruptible4(drainer())),(fiber)=>sync3(()=>this.addFinalizer((exit3)=>flatMap10(interrupt6(fiber),()=>suspend3(()=>{let effect2=this.restorePipe(exit3,inputExecutor);return effect2!==void 0?effect2:_void}))))))}break}case OP_CONCAT_ALL:{let executor=new ChannelExecutor(this._currentChannel.value(),this._providedEnv,(effect2)=>sync3(()=>{let prevLastClose=this._closeLastSubstream===void 0?_void:this._closeLastSubstream;this._closeLastSubstream=pipe(prevLastClose,zipRight4(effect2))}));executor._input=this._input;let channel=this._currentChannel;this._activeSubexecutor=new PullFromUpstream(executor,(value)=>channel.k(value),void 0,[],(x,y)=>channel.combineInners(x,y),(x,y)=>channel.combineAll(x,y),(request2)=>channel.onPull(request2),(value)=>channel.onEmit(value)),this._closeLastSubstream=void 0,this._currentChannel=void 0;break}case OP_EMIT:{this._emitted=this._currentChannel.out,this._currentChannel=this._activeSubexecutor!==void 0?void 0:void_6,result=Emit();break}case OP_ENSURING:{this.runEnsuring(this._currentChannel);break}case OP_FAIL3:{result=this.doneHalt(this._currentChannel.error());break}case OP_FOLD2:{this._doneStack.push(this._currentChannel.k),this._currentChannel=this._currentChannel.channel;break}case OP_FROM_EFFECT2:{let effect2=this._providedEnv===void 0?this._currentChannel.effect():pipe(this._currentChannel.effect(),provide2(this._providedEnv));result=fromEffect6(matchCauseEffect3(effect2,{onFailure:(cause3)=>{let state=this.doneHalt(cause3);return state!==void 0&&isFromEffect(state)?state.effect:_void},onSuccess:(value)=>{let state=this.doneSucceed(value);return state!==void 0&&isFromEffect(state)?state.effect:_void}}));break}case OP_PIPE_TO:{let previousInput=this._input,leftExec=new ChannelExecutor(this._currentChannel.left(),this._providedEnv,(effect2)=>this._executeCloseLastSubstream(effect2));leftExec._input=previousInput,this._input=leftExec,this.addFinalizer((exit3)=>{let effect2=this.restorePipe(exit3,previousInput);return effect2!==void 0?effect2:_void}),this._currentChannel=this._currentChannel.right();break}case OP_PROVIDE2:{let previousEnv=this._providedEnv;this._providedEnv=this._currentChannel.context(),this._currentChannel=this._currentChannel.inner,this.addFinalizer(()=>sync3(()=>{this._providedEnv=previousEnv}));break}case OP_READ:{let read=this._currentChannel;result=Read(this._input,identity,(emitted)=>{try{this._currentChannel=read.more(emitted)}catch(error){this._currentChannel=read.done.onExit(die3(error))}return},(exit3)=>{let onExit4=(exit4)=>{return read.done.onExit(exit4)};this._currentChannel=onExit4(exit3);return});break}case OP_SUCCEED:{result=this.doneSucceed(this._currentChannel.evaluate());break}case OP_SUCCEED_NOW:{result=this.doneSucceed(this._currentChannel.terminal);break}case OP_SUSPEND2:{this._currentChannel=this._currentChannel.channel();break}default:this._currentChannel._tag}}}catch(error){this._currentChannel=failCause10(die4(error))}return result}getDone(){return this._done}getEmit(){return this._emitted}cancelWith(exit3){this._cancelled=exit3}clearInProgressFinalizer(){this._inProgressFinalizer=void 0}storeInProgressFinalizer(finalizer){this._inProgressFinalizer=finalizer}popAllFinalizers(exit3){let finalizers=[],next4=this._doneStack.pop();while(next4){if(next4._tag==="ContinuationFinalizer")finalizers.push(next4.finalizer);next4=this._doneStack.pop()}let effect2=finalizers.length===0?_void:runFinalizers(finalizers,exit3);return this.storeInProgressFinalizer(effect2),effect2}popNextFinalizers(){let builder=[];while(this._doneStack.length!==0){let cont=this._doneStack[this._doneStack.length-1];if(cont._tag===OP_CONTINUATION_K)return builder;builder.push(cont),this._doneStack.pop()}return builder}restorePipe(exit3,prev){let currInput=this._input;if(this._input=prev,currInput!==void 0)return currInput.close(exit3);return _void}close(exit3){let runInProgressFinalizers=void 0,finalizer=this._inProgressFinalizer;if(finalizer!==void 0)runInProgressFinalizers=pipe(finalizer,ensuring2(sync3(()=>this.clearInProgressFinalizer())));let closeSelf=void 0,selfFinalizers=this.popAllFinalizers(exit3);if(selfFinalizers!==void 0)closeSelf=pipe(selfFinalizers,ensuring2(sync3(()=>this.clearInProgressFinalizer())));let closeSubexecutors=this._activeSubexecutor===void 0?void 0:this._activeSubexecutor.close(exit3);if(closeSubexecutors===void 0&&runInProgressFinalizers===void 0&&closeSelf===void 0)return;return pipe(exit2(ifNotNull(closeSubexecutors)),zip6(exit2(ifNotNull(runInProgressFinalizers))),zip6(exit2(ifNotNull(closeSelf))),map16(([[exit1,exit22],exit32])=>pipe(exit1,zipRight2(exit22),zipRight2(exit32))),uninterruptible2,flatMap10((exit4)=>suspend3(()=>exit4)))}doneSucceed(value){if(this._doneStack.length===0)return this._done=succeed3(value),this._currentChannel=void 0,Done2();let head5=this._doneStack[this._doneStack.length-1];if(head5._tag===OP_CONTINUATION_K){this._doneStack.pop(),this._currentChannel=head5.onSuccess(value);return}let finalizers=this.popNextFinalizers();if(this._doneStack.length===0)return this._doneStack=finalizers.reverse(),this._done=succeed3(value),this._currentChannel=void 0,Done2();let finalizerEffect=runFinalizers(finalizers.map((f)=>f.finalizer),succeed3(value));this.storeInProgressFinalizer(finalizerEffect);let effect2=pipe(finalizerEffect,ensuring2(sync3(()=>this.clearInProgressFinalizer())),uninterruptible2,flatMap10(()=>sync3(()=>this.doneSucceed(value))));return fromEffect6(effect2)}doneHalt(cause3){if(this._doneStack.length===0)return this._done=failCause3(cause3),this._currentChannel=void 0,Done2();let head5=this._doneStack[this._doneStack.length-1];if(head5._tag===OP_CONTINUATION_K){this._doneStack.pop();try{this._currentChannel=head5.onHalt(cause3)}catch(error){this._currentChannel=failCause10(die4(error))}return}let finalizers=this.popNextFinalizers();if(this._doneStack.length===0)return this._doneStack=finalizers.reverse(),this._done=failCause3(cause3),this._currentChannel=void 0,Done2();let finalizerEffect=runFinalizers(finalizers.map((f)=>f.finalizer),failCause3(cause3));this.storeInProgressFinalizer(finalizerEffect);let effect2=pipe(finalizerEffect,ensuring2(sync3(()=>this.clearInProgressFinalizer())),uninterruptible2,flatMap10(()=>sync3(()=>this.doneHalt(cause3))));return fromEffect6(effect2)}processCancellation(){return this._currentChannel=void 0,this._done=this._cancelled,this._cancelled=void 0,Done2()}runBracketOut(bracketOut){let effect2=uninterruptible2(matchCauseEffect3(this.provide(bracketOut.acquire()),{onFailure:(cause3)=>sync3(()=>{this._currentChannel=failCause10(cause3)}),onSuccess:(out)=>sync3(()=>{this.addFinalizer((exit3)=>this.provide(bracketOut.finalizer(out,exit3))),this._currentChannel=write(out)})}));return fromEffect6(effect2)}provide(effect2){if(this._providedEnv===void 0)return effect2;return pipe(effect2,provide2(this._providedEnv))}runEnsuring(ensuring3){this.addFinalizer(ensuring3.finalizer),this._currentChannel=ensuring3.channel}addFinalizer(f){this._doneStack.push(new ContinuationFinalizerImpl(f))}runSubexecutor(){let subexecutor=this._activeSubexecutor;switch(subexecutor._tag){case OP_PULL_FROM_CHILD:return this.pullFromChild(subexecutor.childExecutor,subexecutor.parentSubexecutor,subexecutor.onEmit,subexecutor);case OP_PULL_FROM_UPSTREAM:return this.pullFromUpstream(subexecutor);case OP_DRAIN_CHILD_EXECUTORS:return this.drainChildExecutors(subexecutor);case OP_EMIT3:return this._emitted=subexecutor.value,this._activeSubexecutor=subexecutor.next,Emit()}}replaceSubexecutor(nextSubExec){this._currentChannel=void 0,this._activeSubexecutor=nextSubExec}finishWithExit(exit3){let state=match6(exit3,{onFailure:(cause3)=>this.doneHalt(cause3),onSuccess:(value)=>this.doneSucceed(value)});return this._activeSubexecutor=void 0,state===void 0?_void:effect(state)}finishSubexecutorWithCloseEffect(subexecutorDone,...closeFuncs){this.addFinalizer(()=>pipe(closeFuncs,forEach8((closeFunc)=>pipe(sync3(()=>closeFunc(subexecutorDone)),flatMap10((closeEffect)=>closeEffect!==void 0?closeEffect:_void)),{discard:!0})));let state=pipe(subexecutorDone,match6({onFailure:(cause3)=>this.doneHalt(cause3),onSuccess:(value)=>this.doneSucceed(value)}));return this._activeSubexecutor=void 0,state}applyUpstreamPullStrategy(upstreamFinished,queue,strategy){switch(strategy._tag){case OP_PULL_AFTER_NEXT:{let shouldPrepend=!upstreamFinished||queue.some((subexecutor)=>subexecutor!==void 0);return[strategy.emitSeparator,shouldPrepend?[void 0,...queue]:queue]}case OP_PULL_AFTER_ALL_ENQUEUED:{let shouldEnqueue=!upstreamFinished||queue.some((subexecutor)=>subexecutor!==void 0);return[strategy.emitSeparator,shouldEnqueue?[...queue,void 0]:queue]}}}pullFromChild(childExecutor,parentSubexecutor,onEmitted,subexecutor){return Read(childExecutor,identity,(emitted)=>{let childExecutorDecision=onEmitted(emitted);switch(childExecutorDecision._tag){case OP_CONTINUE2:break;case OP_CLOSE:{this.finishWithDoneValue(childExecutor,parentSubexecutor,childExecutorDecision.value);break}case OP_YIELD2:{let modifiedParent=parentSubexecutor.enqueuePullFromChild(subexecutor);this.replaceSubexecutor(modifiedParent);break}}this._activeSubexecutor=new Emit2(emitted,this._activeSubexecutor);return},match6({onFailure:(cause3)=>{let state=this.handleSubexecutorFailure(childExecutor,parentSubexecutor,cause3);return state===void 0?void 0:effectOrUndefinedIgnored(state)},onSuccess:(doneValue)=>{this.finishWithDoneValue(childExecutor,parentSubexecutor,doneValue);return}}))}finishWithDoneValue(childExecutor,parentSubexecutor,doneValue){let subexecutor=parentSubexecutor;switch(subexecutor._tag){case OP_PULL_FROM_UPSTREAM:{let modifiedParent=new PullFromUpstream(subexecutor.upstreamExecutor,subexecutor.createChild,subexecutor.lastDone!==void 0?subexecutor.combineChildResults(subexecutor.lastDone,doneValue):doneValue,subexecutor.activeChildExecutors,subexecutor.combineChildResults,subexecutor.combineWithChildResult,subexecutor.onPull,subexecutor.onEmit);this._closeLastSubstream=childExecutor.close(succeed3(doneValue)),this.replaceSubexecutor(modifiedParent);break}case OP_DRAIN_CHILD_EXECUTORS:{let modifiedParent=new DrainChildExecutors(subexecutor.upstreamExecutor,subexecutor.lastDone!==void 0?subexecutor.combineChildResults(subexecutor.lastDone,doneValue):doneValue,subexecutor.activeChildExecutors,subexecutor.upstreamDone,subexecutor.combineChildResults,subexecutor.combineWithChildResult,subexecutor.onPull);this._closeLastSubstream=childExecutor.close(succeed3(doneValue)),this.replaceSubexecutor(modifiedParent);break}default:break}}handleSubexecutorFailure(childExecutor,parentSubexecutor,cause3){return this.finishSubexecutorWithCloseEffect(failCause3(cause3),(exit3)=>parentSubexecutor.close(exit3),(exit3)=>childExecutor.close(exit3))}pullFromUpstream(subexecutor){if(subexecutor.activeChildExecutors.length===0)return this.performPullFromUpstream(subexecutor);let activeChild=subexecutor.activeChildExecutors[0],parentSubexecutor=new PullFromUpstream(subexecutor.upstreamExecutor,subexecutor.createChild,subexecutor.lastDone,subexecutor.activeChildExecutors.slice(1),subexecutor.combineChildResults,subexecutor.combineWithChildResult,subexecutor.onPull,subexecutor.onEmit);if(activeChild===void 0)return this.performPullFromUpstream(parentSubexecutor);this.replaceSubexecutor(new PullFromChild(activeChild.childExecutor,parentSubexecutor,activeChild.onEmit));return}performPullFromUpstream(subexecutor){return Read(subexecutor.upstreamExecutor,(effect2)=>{let closeLastSubstream=this._closeLastSubstream===void 0?_void:this._closeLastSubstream;return this._closeLastSubstream=void 0,pipe(this._executeCloseLastSubstream(closeLastSubstream),zipRight4(effect2))},(emitted)=>{if(this._closeLastSubstream!==void 0){let closeLastSubstream=this._closeLastSubstream;return this._closeLastSubstream=void 0,pipe(this._executeCloseLastSubstream(closeLastSubstream),map16(()=>{let childExecutor2=new ChannelExecutor(subexecutor.createChild(emitted),this._providedEnv,this._executeCloseLastSubstream);childExecutor2._input=this._input;let[emitSeparator2,updatedChildExecutors2]=this.applyUpstreamPullStrategy(!1,subexecutor.activeChildExecutors,subexecutor.onPull(Pulled(emitted)));if(this._activeSubexecutor=new PullFromChild(childExecutor2,new PullFromUpstream(subexecutor.upstreamExecutor,subexecutor.createChild,subexecutor.lastDone,updatedChildExecutors2,subexecutor.combineChildResults,subexecutor.combineWithChildResult,subexecutor.onPull,subexecutor.onEmit),subexecutor.onEmit),isSome2(emitSeparator2))this._activeSubexecutor=new Emit2(emitSeparator2.value,this._activeSubexecutor);return}))}let childExecutor=new ChannelExecutor(subexecutor.createChild(emitted),this._providedEnv,this._executeCloseLastSubstream);childExecutor._input=this._input;let[emitSeparator,updatedChildExecutors]=this.applyUpstreamPullStrategy(!1,subexecutor.activeChildExecutors,subexecutor.onPull(Pulled(emitted)));if(this._activeSubexecutor=new PullFromChild(childExecutor,new PullFromUpstream(subexecutor.upstreamExecutor,subexecutor.createChild,subexecutor.lastDone,updatedChildExecutors,subexecutor.combineChildResults,subexecutor.combineWithChildResult,subexecutor.onPull,subexecutor.onEmit),subexecutor.onEmit),isSome2(emitSeparator))this._activeSubexecutor=new Emit2(emitSeparator.value,this._activeSubexecutor);return},(exit3)=>{if(subexecutor.activeChildExecutors.some((subexecutor2)=>subexecutor2!==void 0)){let drain=new DrainChildExecutors(subexecutor.upstreamExecutor,subexecutor.lastDone,[void 0,...subexecutor.activeChildExecutors],subexecutor.upstreamExecutor.getDone(),subexecutor.combineChildResults,subexecutor.combineWithChildResult,subexecutor.onPull);if(this._closeLastSubstream!==void 0){let closeLastSubstream2=this._closeLastSubstream;return this._closeLastSubstream=void 0,pipe(this._executeCloseLastSubstream(closeLastSubstream2),map16(()=>this.replaceSubexecutor(drain)))}this.replaceSubexecutor(drain);return}let closeLastSubstream=this._closeLastSubstream,state=this.finishSubexecutorWithCloseEffect(pipe(exit3,map11((a)=>subexecutor.combineWithChildResult(subexecutor.lastDone,a))),()=>closeLastSubstream,(exit4)=>subexecutor.upstreamExecutor.close(exit4));return state===void 0?void 0:effectOrUndefinedIgnored(state)})}drainChildExecutors(subexecutor){if(subexecutor.activeChildExecutors.length===0){let lastClose=this._closeLastSubstream;if(lastClose!==void 0)this.addFinalizer(()=>succeed9(lastClose));return this.finishSubexecutorWithCloseEffect(subexecutor.upstreamDone,()=>lastClose,(exit3)=>subexecutor.upstreamExecutor.close(exit3))}let activeChild=subexecutor.activeChildExecutors[0],rest=subexecutor.activeChildExecutors.slice(1);if(activeChild===void 0){let[emitSeparator,remainingExecutors]=this.applyUpstreamPullStrategy(!0,rest,subexecutor.onPull(NoUpstream(rest.reduce((n,curr)=>curr!==void 0?n+1:n,0))));if(this.replaceSubexecutor(new DrainChildExecutors(subexecutor.upstreamExecutor,subexecutor.lastDone,remainingExecutors,subexecutor.upstreamDone,subexecutor.combineChildResults,subexecutor.combineWithChildResult,subexecutor.onPull)),isSome2(emitSeparator))return this._emitted=emitSeparator.value,Emit();return}let parentSubexecutor=new DrainChildExecutors(subexecutor.upstreamExecutor,subexecutor.lastDone,rest,subexecutor.upstreamDone,subexecutor.combineChildResults,subexecutor.combineWithChildResult,subexecutor.onPull);this.replaceSubexecutor(new PullFromChild(activeChild.childExecutor,parentSubexecutor,activeChild.onEmit));return}}var ifNotNull=(effect2)=>effect2!==void 0?effect2:_void,runFinalizers=(finalizers,exit3)=>{return pipe(forEach8(finalizers,(fin)=>exit2(fin(exit3))),map16((exits)=>pipe(all2(exits),getOrElse(()=>void_2))),flatMap10((exit4)=>suspend3(()=>exit4)))},readUpstream=(r,onSuccess,onFailure)=>{let readStack=[r],read=()=>{let current=readStack.pop();if(current===void 0||current.upstream===void 0)return dieMessage2("Unexpected end of input for channel execution");let state=current.upstream.run();switch(state._tag){case OP_EMIT2:{let emitEffect=current.onEmit(current.upstream.getEmit());if(readStack.length===0){if(emitEffect===void 0)return suspend3(onSuccess);return pipe(emitEffect,matchCauseEffect3({onFailure,onSuccess}))}if(emitEffect===void 0)return suspend3(()=>read());return pipe(emitEffect,matchCauseEffect3({onFailure,onSuccess:()=>read()}))}case OP_DONE3:{let doneEffect=current.onDone(current.upstream.getDone());if(readStack.length===0){if(doneEffect===void 0)return suspend3(onSuccess);return pipe(doneEffect,matchCauseEffect3({onFailure,onSuccess}))}if(doneEffect===void 0)return suspend3(()=>read());return pipe(doneEffect,matchCauseEffect3({onFailure,onSuccess:()=>read()}))}case OP_FROM_EFFECT3:return readStack.push(current),pipe(current.onEffect(state.effect),catchAllCause2((cause3)=>suspend3(()=>{let doneEffect=current.onDone(failCause3(cause3));return doneEffect===void 0?_void:doneEffect})),matchCauseEffect3({onFailure,onSuccess:()=>read()}));case OP_READ2:return readStack.push(current),readStack.push(state),suspend3(()=>read())}};return read()},runIn=dual(2,(self,scope4)=>{let run=(channelDeferred,scopeDeferred,scope5)=>acquireUseRelease2(sync3(()=>new ChannelExecutor(self,void 0,identity)),(exec)=>suspend3(()=>runScopedInterpret(exec.run(),exec).pipe(intoDeferred2(channelDeferred),zipRight4(_await(channelDeferred)),zipLeft3(_await(scopeDeferred)))),(exec,exit3)=>{let finalize=exec.close(exit3);if(finalize===void 0)return _void;return tapErrorCause2(finalize,(cause3)=>addFinalizer2(scope5,failCause8(cause3)))});return uninterruptibleMask3((restore)=>all7([fork2(scope4,sequential3),make19(),make19()]).pipe(flatMap10(([child,channelDeferred,scopeDeferred])=>restore(run(channelDeferred,scopeDeferred,child)).pipe(forkIn2(scope4),flatMap10((fiber)=>scope4.addFinalizer((exit3)=>{let interruptors3=isFailure(exit3)?interruptors2(exit3.cause):void 0;return isDone(channelDeferred).pipe(flatMap10((isDone6)=>isDone6?succeed2(scopeDeferred,void 0).pipe(zipRight4(_await3(fiber)),zipRight4(inheritAll2(fiber))):succeed2(scopeDeferred,void 0).pipe(zipRight4(interruptors3&&size3(interruptors3)>0?interruptAs(fiber,combineAll3(interruptors3)):interrupt6(fiber)),zipRight4(inheritAll2(fiber)))))}).pipe(zipRight4(restore(_await(channelDeferred)))))))))}),runScopedInterpret=(channelState,exec)=>{let op=channelState;switch(op._tag){case OP_FROM_EFFECT3:return pipe(op.effect,flatMap10(()=>runScopedInterpret(exec.run(),exec)));case OP_EMIT2:return runScopedInterpret(exec.run(),exec);case OP_DONE3:return suspend3(()=>exec.getDone());case OP_READ2:return readUpstream(op,()=>runScopedInterpret(exec.run(),exec),failCause8)}};var OP_DONE4="Done",OP_AWAIT="Await";var MergeDecisionSymbolKey="effect/ChannelMergeDecision",MergeDecisionTypeId=Symbol.for(MergeDecisionSymbolKey),proto9={[MergeDecisionTypeId]:{_R:(_)=>_,_E0:(_)=>_,_Z0:(_)=>_,_E:(_)=>_,_Z:(_)=>_}},Done3=(effect2)=>{let op=Object.create(proto9);return op._tag=OP_DONE4,op.effect=effect2,op},Await=(f)=>{let op=Object.create(proto9);return op._tag=OP_AWAIT,op.f=f,op};var OP_BOTH_RUNNING="BothRunning",OP_LEFT_DONE="LeftDone",OP_RIGHT_DONE="RightDone";var MergeStateSymbolKey="effect/ChannelMergeState",MergeStateTypeId=Symbol.for(MergeStateSymbolKey),proto10={[MergeStateTypeId]:MergeStateTypeId},BothRunning=(left3,right3)=>{let op=Object.create(proto10);return op._tag=OP_BOTH_RUNNING,op.left=left3,op.right=right3,op},LeftDone=(f)=>{let op=Object.create(proto10);return op._tag=OP_LEFT_DONE,op.f=f,op},RightDone=(f)=>{let op=Object.create(proto10);return op._tag=OP_RIGHT_DONE,op.f=f,op};var OP_BACK_PRESSURE="BackPressure",OP_BUFFER_SLIDING="BufferSliding";var MergeStrategySymbolKey="effect/ChannelMergeStrategy",MergeStrategyTypeId=Symbol.for(MergeStrategySymbolKey),proto11={[MergeStrategyTypeId]:MergeStrategyTypeId},BackPressure=(_)=>{let op=Object.create(proto11);return op._tag=OP_BACK_PRESSURE,op},BufferSliding=(_)=>{let op=Object.create(proto11);return op._tag=OP_BUFFER_SLIDING,op};var match15=dual(2,(self,{onBackPressure,onBufferSliding})=>{switch(self._tag){case OP_BACK_PRESSURE:return onBackPressure();case OP_BUFFER_SLIDING:return onBufferSliding()}});var OP_STATE_EMPTY="Empty",OP_STATE_EMIT="Emit",OP_STATE_ERROR="Error",OP_STATE_DONE2="Done",stateEmpty=(notifyProducer)=>({_tag:OP_STATE_EMPTY,notifyProducer}),stateEmit=(notifyConsumers)=>({_tag:OP_STATE_EMIT,notifyConsumers}),stateError=(cause3)=>({_tag:OP_STATE_ERROR,cause:cause3}),stateDone=(done9)=>({_tag:OP_STATE_DONE2,done:done9});class SingleProducerAsyncInputImpl{ref;constructor(ref){this.ref=ref}awaitRead(){return flatten8(modify3(this.ref,(state)=>state._tag===OP_STATE_EMPTY?[_await(state.notifyProducer),state]:[_void,state]))}get close(){return fiberIdWith2((fiberId3)=>this.error(interrupt5(fiberId3)))}done(value){return flatten8(modify3(this.ref,(state)=>{switch(state._tag){case OP_STATE_EMPTY:return[_await(state.notifyProducer),state];case OP_STATE_EMIT:return[forEach8(state.notifyConsumers,(deferred)=>succeed2(deferred,left2(value)),{discard:!0}),stateDone(value)];case OP_STATE_ERROR:return[interrupt7,state];case OP_STATE_DONE2:return[interrupt7,state]}}))}emit(element){return flatMap10(make19(),(deferred)=>flatten8(modify3(this.ref,(state)=>{switch(state._tag){case OP_STATE_EMPTY:return[_await(state.notifyProducer),state];case OP_STATE_EMIT:{let notifyConsumer=state.notifyConsumers[0],notifyConsumers=state.notifyConsumers.slice(1);if(notifyConsumer!==void 0)return[succeed2(notifyConsumer,right2(element)),notifyConsumers.length===0?stateEmpty(deferred):stateEmit(notifyConsumers)];throw new Error("Bug: Channel.SingleProducerAsyncInput.emit - Queue was empty! please report an issue at https://github.com/Effect-TS/effect/issues")}case OP_STATE_ERROR:return[interrupt7,state];case OP_STATE_DONE2:return[interrupt7,state]}})))}error(cause3){return flatten8(modify3(this.ref,(state)=>{switch(state._tag){case OP_STATE_EMPTY:return[_await(state.notifyProducer),state];case OP_STATE_EMIT:return[forEach8(state.notifyConsumers,(deferred)=>failCause2(deferred,cause3),{discard:!0}),stateError(cause3)];case OP_STATE_ERROR:return[interrupt7,state];case OP_STATE_DONE2:return[interrupt7,state]}}))}get take(){return this.takeWith((cause3)=>failCause3(map13(cause3,left2)),(elem)=>succeed3(elem),(done9)=>fail4(right2(done9)))}takeWith(onError3,onElement,onDone){return flatMap10(make19(),(deferred)=>flatten8(modify3(this.ref,(state)=>{switch(state._tag){case OP_STATE_EMPTY:return[zipRight4(succeed2(state.notifyProducer,void 0),matchCause2(_await(deferred),{onFailure:onError3,onSuccess:match({onLeft:onDone,onRight:onElement})})),stateEmit([deferred])];case OP_STATE_EMIT:return[matchCause2(_await(deferred),{onFailure:onError3,onSuccess:match({onLeft:onDone,onRight:onElement})}),stateEmit([...state.notifyConsumers,deferred])];case OP_STATE_ERROR:return[succeed9(onError3(state.cause)),state];case OP_STATE_DONE2:return[succeed9(onDone(state.done)),state]}})))}}var make45=()=>pipe(make19(),flatMap10((deferred)=>make29(stateEmpty(deferred))),map16((ref)=>new SingleProducerAsyncInputImpl(ref)));var acquireUseRelease3=(acquire,use,release)=>flatMap12(fromEffect5(make29(()=>_void)),(ref)=>pipe(fromEffect5(uninterruptible2(tap2(acquire,(a)=>set6(ref,(exit3)=>release(a,exit3))))),flatMap12(use),ensuringWith((exit3)=>flatMap10(get12(ref),(f)=>f(exit3))))),as4=dual(2,(self,value)=>map18(self,()=>value));var catchAll4=dual(2,(self,f)=>catchAllCause4(self,(cause3)=>match(failureOrCause2(cause3),{onLeft:f,onRight:failCause10}))),concatMap=dual(2,(self,f)=>concatMapWith(self,f,()=>{return},()=>{return}));var drain=(self)=>{let drainer=readWithCause({onInput:()=>drainer,onFailure:failCause10,onDone:succeed10});return pipeTo(self,drainer)};var ensuring3=dual(2,(self,finalizer)=>ensuringWith(self,()=>finalizer));var flatten10=(self)=>flatMap12(self,identity),foldChannel=dual(2,(self,options)=>foldCauseChannel(self,{onFailure:(cause3)=>{let either4=failureOrCause2(cause3);switch(either4._tag){case"Left":return options.onFailure(either4.left);case"Right":return failCause10(either4.right)}},onSuccess:options.onSuccess}));var fromInput=(input)=>unwrap(input.takeWith(failCause10,(elem)=>flatMap12(write(elem),()=>fromInput(input)),succeed10));var fromQueue=(queue)=>suspend4(()=>fromQueueInternal(queue)),fromQueueInternal=(queue)=>pipe(fromEffect5(take3(queue)),flatMap12(match({onLeft:match6({onFailure:failCause10,onSuccess:succeedNow}),onRight:(elem)=>flatMap12(write(elem),()=>fromQueueInternal(queue))}))),identityChannel=()=>readWith({onInput:(input)=>flatMap12(write(input),()=>identityChannel()),onFailure:fail11,onDone:succeedNow}),interruptWhen=dual(2,(self,effect2)=>mergeWith2(self,{other:fromEffect5(effect2),onSelfDone:(selfDone)=>Done3(suspend3(()=>selfDone)),onOtherDone:(effectDone)=>Done3(suspend3(()=>effectDone))})),interruptWhenDeferred=dual(2,(self,deferred)=>interruptWhen(self,_await(deferred))),map18=dual(2,(self,f)=>flatMap12(self,(a)=>sync4(()=>f(a))));var mapError4=dual(2,(self,f)=>mapErrorCause3(self,map13(f))),mapErrorCause3=dual(2,(self,f)=>catchAllCause4(self,(cause3)=>failCause10(f(cause3)))),mapOut=dual(2,(self,f)=>{let reader=readWith({onInput:(outElem)=>flatMap12(write(f(outElem)),()=>reader),onFailure:fail11,onDone:succeedNow});return pipeTo(self,reader)}),mapOutEffect=dual(2,(self,f)=>{let reader=readWithCause({onInput:(outElem)=>pipe(fromEffect5(f(outElem)),flatMap12(write),flatMap12(()=>reader)),onFailure:failCause10,onDone:succeedNow});return pipeTo(self,reader)}),mapOutEffectPar=dual(3,(self,f,n)=>unwrapScopedWith((scope4)=>gen2(function*(){let input=yield*make45(),queueReader=fromInput(input),queue=yield*bounded5(n);yield*addFinalizer2(scope4,shutdown4(queue));let errorSignal=yield*make19(),withPermits=n===Number.POSITIVE_INFINITY?(_)=>identity:(yield*makeSemaphore2(n)).withPermits;yield*(yield*queueReader.pipe(pipeTo(self),toPullIn(scope4))).pipe(matchCauseEffect3({onFailure:(cause3)=>offer3(queue,failCause8(cause3)),onSuccess:match({onLeft:(outDone)=>zipRight4(interruptible4(withPermits(n)(_void)),asVoid2(offer3(queue,succeed9(left2(outDone))))),onRight:(outElem)=>gen2(function*(){let deferred=yield*make19(),latch=yield*make19();yield*offer3(queue,map16(_await(deferred),right2)),yield*succeed2(latch,void 0).pipe(zipRight4(uninterruptibleMask3((restore)=>exit2(restore(_await(errorSignal))).pipe(raceFirst2(exit2(restore(f(outElem)))),flatMap10(identity))).pipe(tapErrorCause2((cause3)=>failCause2(errorSignal,cause3)),intoDeferred2(deferred))),withPermits(1),forkIn2(scope4)),yield*_await(latch)})})}),forever3,interruptible4,forkIn2(scope4));let consumer=unwrap(matchCause2(flatten8(take3(queue)),{onFailure:failCause10,onSuccess:match({onLeft:succeedNow,onRight:(outElem)=>flatMap12(write(outElem),()=>consumer)})}));return embedInput(consumer,input)}))),mergeAll5=(options)=>{return(channels)=>mergeAllWith(options)(channels,constVoid)};var mergeAllWith=({bufferSize=16,concurrency,mergeStrategy=BackPressure()})=>(channels,f)=>unwrapScopedWith((scope4)=>gen2(function*(){let concurrencyN=concurrency==="unbounded"?Number.MAX_SAFE_INTEGER:concurrency,input=yield*make45(),queueReader=fromInput(input),queue=yield*bounded5(bufferSize);yield*addFinalizer2(scope4,shutdown4(queue));let cancelers=yield*unbounded5();yield*addFinalizer2(scope4,shutdown4(cancelers));let lastDone=yield*make29(none2()),errorSignal=yield*make19(),withPermits=(yield*makeSemaphore2(concurrencyN)).withPermits,pull=yield*toPullIn(pipeTo(queueReader,channels),scope4);function evaluatePull(pull2){return pull2.pipe(flatMap10(match({onLeft:(done9)=>succeed9(some2(done9)),onRight:(outElem)=>as3(offer3(queue,succeed9(right2(outElem))),none2())})),repeat({until:(_)=>isSome2(_)}),flatMap10((outDone)=>update3(lastDone,match2({onNone:()=>some2(outDone.value),onSome:(lastDone2)=>some2(f(lastDone2,outDone.value))}))),catchAllCause2((cause3)=>isInterrupted2(cause3)?failCause8(cause3):offer3(queue,failCause8(cause3)).pipe(zipRight4(succeed2(errorSignal,void 0)),asVoid2)))}yield*pull.pipe(matchCauseEffect3({onFailure:(cause3)=>offer3(queue,failCause8(cause3)).pipe(zipRight4(succeed9(!1))),onSuccess:match({onLeft:(outDone)=>raceWith2(interruptible4(_await(errorSignal)),interruptible4(withPermits(concurrencyN)(_void)),{onSelfDone:(_,permitAcquisition)=>as3(interrupt6(permitAcquisition),!1),onOtherDone:(_,failureAwait)=>zipRight4(interrupt6(failureAwait),get12(lastDone).pipe(flatMap10(match2({onNone:()=>offer3(queue,succeed9(left2(outDone))),onSome:(lastDone2)=>offer3(queue,succeed9(left2(f(lastDone2,outDone))))})),as3(!1)))}),onRight:(channel)=>match15(mergeStrategy,{onBackPressure:()=>gen2(function*(){let latch=yield*make19(),raceEffects=scopedWith2((scope5)=>toPullIn(pipeTo(queueReader,channel),scope5).pipe(flatMap10((pull2)=>race2(exit2(evaluatePull(pull2)),exit2(interruptible4(_await(errorSignal))))),flatMap10(identity)));return yield*succeed2(latch,void 0).pipe(zipRight4(raceEffects),withPermits(1),forkIn2(scope4)),yield*_await(latch),!(yield*isDone(errorSignal))}),onBufferSliding:()=>gen2(function*(){let canceler=yield*make19(),latch=yield*make19(),size14=yield*size13(cancelers);yield*take3(cancelers).pipe(flatMap10((canceler2)=>succeed2(canceler2,void 0)),when2(()=>size14>=concurrencyN)),yield*offer3(cancelers,canceler);let raceEffects=scopedWith2((scope5)=>toPullIn(pipeTo(queueReader,channel),scope5).pipe(flatMap10((pull2)=>exit2(evaluatePull(pull2)).pipe(race2(exit2(interruptible4(_await(errorSignal)))),race2(exit2(interruptible4(_await(canceler)))))),flatMap10(identity)));return yield*succeed2(latch,void 0).pipe(zipRight4(raceEffects),withPermits(1),forkIn2(scope4)),yield*_await(latch),!(yield*isDone(errorSignal))})})})}),repeat({while:(_)=>_}),forkIn2(scope4));let consumer=pipe(take3(queue),flatten8,matchCause2({onFailure:failCause10,onSuccess:match({onLeft:succeedNow,onRight:(outElem)=>flatMap12(write(outElem),()=>consumer)})}),unwrap);return embedInput(consumer,input)})),mergeMap=dual(3,(self,f,options)=>mergeAll5(options)(mapOut(self,f)));var mergeWith2=dual(2,(self,options)=>{function merge9(scope4){return gen2(function*(){let input=yield*make45(),queueReader=fromInput(input),pullL=yield*toPullIn(pipeTo(queueReader,self),scope4),pullR=yield*toPullIn(pipeTo(queueReader,options.other),scope4);function handleSide(exit3,fiber,pull){return(done9,both2,single2)=>{function onDecision(decision){let op=decision;if(op._tag===OP_DONE4)return succeed9(fromEffect5(zipRight4(interrupt6(fiber),op.effect)));return map16(_await3(fiber),match6({onFailure:(cause3)=>fromEffect5(op.f(failCause3(cause3))),onSuccess:match({onLeft:(done10)=>fromEffect5(op.f(succeed3(done10))),onRight:(elem)=>zipRight5(write(elem),go(single2(op.f)))})}))}return match6(exit3,{onFailure:(cause3)=>onDecision(done9(failCause3(cause3))),onSuccess:match({onLeft:(z)=>onDecision(done9(succeed3(z))),onRight:(elem)=>succeed9(flatMap12(write(elem),()=>flatMap12(fromEffect5(forkIn2(interruptible4(pull),scope4)),(leftFiber)=>go(both2(leftFiber,fiber)))))})})}}function go(state){switch(state._tag){case OP_BOTH_RUNNING:{let leftJoin=interruptible4(join3(state.left)),rightJoin=interruptible4(join3(state.right));return unwrap(raceWith2(leftJoin,rightJoin,{onSelfDone:(leftExit,rf)=>zipRight4(interrupt6(rf),handleSide(leftExit,state.right,pullL)(options.onSelfDone,BothRunning,(f)=>LeftDone(f))),onOtherDone:(rightExit,lf)=>zipRight4(interrupt6(lf),handleSide(rightExit,state.left,pullR)(options.onOtherDone,(left3,right3)=>BothRunning(right3,left3),(f)=>RightDone(f)))}))}case OP_LEFT_DONE:return unwrap(map16(exit2(pullR),match6({onFailure:(cause3)=>fromEffect5(state.f(failCause3(cause3))),onSuccess:match({onLeft:(done9)=>fromEffect5(state.f(succeed3(done9))),onRight:(elem)=>flatMap12(write(elem),()=>go(LeftDone(state.f)))})})));case OP_RIGHT_DONE:return unwrap(map16(exit2(pullL),match6({onFailure:(cause3)=>fromEffect5(state.f(failCause3(cause3))),onSuccess:match({onLeft:(done9)=>fromEffect5(state.f(succeed3(done9))),onRight:(elem)=>flatMap12(write(elem),()=>go(RightDone(state.f)))})})))}}return fromEffect5(withFiberRuntime2((parent)=>{let inherit=withFiberRuntime2((state)=>{return state.transferChildren(parent.scope()),_void}),leftFiber=interruptible4(pullL).pipe(ensuring2(inherit),forkIn2(scope4)),rightFiber=interruptible4(pullR).pipe(ensuring2(inherit),forkIn2(scope4));return zipWith8(leftFiber,rightFiber,(left3,right3)=>BothRunning(left3,right3))})).pipe(flatMap12(go),embedInput(input))})}return unwrapScopedWith(merge9)});var orDieWith3=dual(2,(self,f)=>catchAll4(self,(e)=>failCauseSync4(()=>die4(f(e))))),orElse7=dual(2,(self,that)=>catchAll4(self,that)),pipeToOrFail=dual(2,(self,that)=>suspend4(()=>{let channelException=void 0,reader=readWith({onInput:(outElem)=>flatMap12(write(outElem),()=>reader),onFailure:(outErr)=>{return channelException=ChannelException(outErr),failCause10(die4(channelException))},onDone:succeedNow}),writer=readWithCause({onInput:(outElem)=>pipe(write(outElem),flatMap12(()=>writer)),onFailure:(cause3)=>isDieType2(cause3)&&isChannelException(cause3.defect)&&equals(cause3.defect,channelException)?fail11(cause3.defect.error):failCause10(cause3),onDone:succeedNow});return pipeTo(pipeTo(pipeTo(self,reader),that),writer)}));var repeated=(self)=>flatMap12(self,()=>repeated(self)),run=(self)=>scopedWith2((scope4)=>runIn(self,scope4));var runDrain=(self)=>run(drain(self)),runScoped=(self)=>scopeWith2((scope4)=>runIn(self,scope4)),scoped4=(effect2)=>unwrap(uninterruptibleMask3((restore)=>map16(make41(),(scope4)=>acquireReleaseOut(tapErrorCause2(restore(extend2(effect2,scope4)),(cause3)=>close(scope4,failCause3(cause3))),(_,exit3)=>close(scope4,exit3))))),scopedWith3=(f)=>unwrapScoped2(map16(scope2,(scope4)=>flatMap12(fromEffect5(f(scope4)),write)));var splitLines=()=>suspend4(()=>{let stringBuilder="",midCRLF=!1,splitLinesChunk=(chunk2)=>{let chunkBuilder=[];return map4(chunk2,(str)=>{if(str.length!==0){let from=0,indexOfCR=str.indexOf("\r"),indexOfLF=str.indexOf(`
|
|
31
|
+
`),endStackDef=stackDef.slice(2).join(`
|
|
32
|
+
`).trim();if(!endStackDef.includes("("))endStackDef=endStackDef.replace(/at (.*)/,"at ($1)");let endStackCall=stackCall.slice(2).join(`
|
|
33
|
+
`).trim();if(!endStackCall.includes("("))endStackCall=endStackCall.replace(/at (.*)/,"at ($1)");return cache=`${endStackDef}
|
|
34
|
+
${endStackCall}`,cache}},opts=options.spanOptions&&"captureStackTrace"in options.spanOptions?options.spanOptions:{captureStackTrace,...options.spanOptions};return withSpan2(effect,options.spanName,opts)}var fnUntraced2=fnUntraced;var get13=fiberRefGet;var getWith=fiberRefGetWith;var currentContext2=currentContext,currentSchedulingPriority2=currentSchedulingPriority;var currentScheduler2=currentScheduler;var currentTracerTimingEnabled2=currentTracerTimingEnabled;var buildWithScope2=buildWithScope;var context4=context2;var merge8=merge6;var EnqueueSymbolKey="effect/QueueEnqueue",EnqueueTypeId=Symbol.for(EnqueueSymbolKey),DequeueSymbolKey="effect/QueueDequeue",DequeueTypeId=Symbol.for(DequeueSymbolKey),QueueStrategySymbolKey="effect/QueueStrategy",QueueStrategyTypeId=Symbol.for(QueueStrategySymbolKey),BackingQueueSymbolKey="effect/BackingQueue",BackingQueueTypeId=Symbol.for(BackingQueueSymbolKey),queueStrategyVariance={_A:(_)=>_},backingQueueVariance={_A:(_)=>_},enqueueVariance={_In:(_)=>_},dequeueVariance={_Out:(_)=>_};class QueueImpl extends Class{queue;takers;shutdownHook;shutdownFlag;strategy;[EnqueueTypeId]=enqueueVariance;[DequeueTypeId]=dequeueVariance;constructor(queue,takers,shutdownHook,shutdownFlag,strategy){super();this.queue=queue,this.takers=takers,this.shutdownHook=shutdownHook,this.shutdownFlag=shutdownFlag,this.strategy=strategy}pipe(){return pipeArguments(this,arguments)}commit(){return this.take}capacity(){return this.queue.capacity()}get size(){return suspend(()=>catchAll(this.unsafeSize(),()=>interrupt2))}unsafeSize(){if(get6(this.shutdownFlag))return none2();return some2(this.queue.length()-length2(this.takers)+this.strategy.surplusSize())}get isEmpty(){return map10(this.size,(size11)=>size11<=0)}get isFull(){return map10(this.size,(size11)=>size11>=this.capacity())}get shutdown(){return uninterruptible(withFiberRuntime((state)=>{return pipe(this.shutdownFlag,set2(!0)),pipe(forEachConcurrentDiscard(unsafePollAll(this.takers),(d)=>deferredInterruptWith(d,state.id()),!1,!1),zipRight(this.strategy.shutdown),whenEffect(deferredSucceed(this.shutdownHook,void 0)),asVoid)}))}get isShutdown(){return sync(()=>get6(this.shutdownFlag))}get awaitShutdown(){return deferredAwait(this.shutdownHook)}isActive(){return!get6(this.shutdownFlag)}unsafeOffer(value){if(get6(this.shutdownFlag))return!1;let noRemaining;if(this.queue.length()===0){let taker=pipe(this.takers,poll2(EmptyMutableQueue));if(taker!==EmptyMutableQueue)unsafeCompleteDeferred(taker,value),noRemaining=!0;else noRemaining=!1}else noRemaining=!1;if(noRemaining)return!0;let succeeded=this.queue.offer(value);return unsafeCompleteTakers(this.strategy,this.queue,this.takers),succeeded}offer(value){return suspend(()=>{if(get6(this.shutdownFlag))return interrupt2;let noRemaining;if(this.queue.length()===0){let taker=pipe(this.takers,poll2(EmptyMutableQueue));if(taker!==EmptyMutableQueue)unsafeCompleteDeferred(taker,value),noRemaining=!0;else noRemaining=!1}else noRemaining=!1;if(noRemaining)return succeed(!0);let succeeded=this.queue.offer(value);return unsafeCompleteTakers(this.strategy,this.queue,this.takers),succeeded?succeed(!0):this.strategy.handleSurplus([value],this.queue,this.takers,this.shutdownFlag)})}offerAll(iterable){return suspend(()=>{if(get6(this.shutdownFlag))return interrupt2;let values3=fromIterable(iterable),pTakers=this.queue.length()===0?fromIterable(unsafePollN(this.takers,values3.length)):empty2,[forTakers,remaining]=pipe(values3,splitAt(pTakers.length));for(let i=0;i<pTakers.length;i++){let taker=pTakers[i],item=forTakers[i];unsafeCompleteDeferred(taker,item)}if(remaining.length===0)return succeed(!0);let surplus=this.queue.offerAll(remaining);return unsafeCompleteTakers(this.strategy,this.queue,this.takers),isEmpty(surplus)?succeed(!0):this.strategy.handleSurplus(surplus,this.queue,this.takers,this.shutdownFlag)})}get take(){return withFiberRuntime((state)=>{if(get6(this.shutdownFlag))return interrupt2;let item=this.queue.poll(EmptyMutableQueue);if(item!==EmptyMutableQueue)return this.strategy.unsafeOnQueueEmptySpace(this.queue,this.takers),succeed(item);else{let deferred=deferredUnsafeMake(state.id());return pipe(suspend(()=>{return pipe(this.takers,offer(deferred)),unsafeCompleteTakers(this.strategy,this.queue,this.takers),get6(this.shutdownFlag)?interrupt2:deferredAwait(deferred)}),onInterrupt(()=>{return sync(()=>unsafeRemove(this.takers,deferred))}))}})}get takeAll(){return suspend(()=>{return get6(this.shutdownFlag)?interrupt2:sync(()=>{let values3=this.queue.pollUpTo(Number.POSITIVE_INFINITY);return this.strategy.unsafeOnQueueEmptySpace(this.queue,this.takers),fromIterable2(values3)})})}takeUpTo(max6){return suspend(()=>get6(this.shutdownFlag)?interrupt2:sync(()=>{let values3=this.queue.pollUpTo(max6);return this.strategy.unsafeOnQueueEmptySpace(this.queue,this.takers),fromIterable2(values3)}))}takeBetween(min4,max6){return suspend(()=>takeRemainderLoop(this,min4,max6,empty5()))}}var takeRemainderLoop=(self,min4,max6,acc)=>{if(max6<min4)return succeed(acc);return pipe(takeUpTo(self,max6),flatMap8((bs)=>{let remaining=min4-bs.length;if(remaining===1)return pipe(take2(self),map10((b)=>pipe(acc,appendAll2(bs),append2(b))));if(remaining>1)return pipe(take2(self),flatMap8((b)=>takeRemainderLoop(self,remaining-1,max6-bs.length-1,pipe(acc,appendAll2(bs),append2(b)))));return succeed(pipe(acc,appendAll2(bs)))}))},isQueue=(u)=>isEnqueue(u)&&isDequeue(u),isEnqueue=(u)=>hasProperty(u,EnqueueTypeId),isDequeue=(u)=>hasProperty(u,DequeueTypeId),bounded2=(requestedCapacity)=>pipe(sync(()=>bounded(requestedCapacity)),flatMap8((queue)=>make43(backingQueueFromMutableQueue(queue),backPressureStrategy()))),dropping=(requestedCapacity)=>pipe(sync(()=>bounded(requestedCapacity)),flatMap8((queue)=>make43(backingQueueFromMutableQueue(queue),droppingStrategy()))),sliding=(requestedCapacity)=>pipe(sync(()=>bounded(requestedCapacity)),flatMap8((queue)=>make43(backingQueueFromMutableQueue(queue),slidingStrategy()))),unbounded2=()=>pipe(sync(()=>unbounded()),flatMap8((queue)=>make43(backingQueueFromMutableQueue(queue),droppingStrategy()))),unsafeMake9=(queue,takers,shutdownHook,shutdownFlag,strategy)=>{return new QueueImpl(queue,takers,shutdownHook,shutdownFlag,strategy)},make43=(queue,strategy)=>pipe(deferredMake(),map10((deferred)=>unsafeMake9(queue,unbounded(),deferred,make12(!1),strategy)));class BackingQueueFromMutableQueue{mutable;[BackingQueueTypeId]=backingQueueVariance;constructor(mutable){this.mutable=mutable}poll(def){return poll2(this.mutable,def)}pollUpTo(limit){return pollUpTo(this.mutable,limit)}offerAll(elements){return offerAll(this.mutable,elements)}offer(element){return offer(this.mutable,element)}capacity(){return capacity(this.mutable)}length(){return length2(this.mutable)}}var backingQueueFromMutableQueue=(mutable)=>new BackingQueueFromMutableQueue(mutable),capacity2=(self)=>self.capacity(),size11=(self)=>self.size,isFull=(self)=>self.isFull,isEmpty10=(self)=>self.isEmpty,isShutdown=(self)=>self.isShutdown,awaitShutdown=(self)=>self.awaitShutdown,shutdown=(self)=>self.shutdown,offer2=dual(2,(self,value)=>self.offer(value)),unsafeOffer=dual(2,(self,value)=>self.unsafeOffer(value)),offerAll2=dual(2,(self,iterable)=>self.offerAll(iterable)),poll5=(self)=>map10(self.takeUpTo(1),head2),take2=(self)=>self.take,takeAll=(self)=>self.takeAll,takeUpTo=dual(2,(self,max6)=>self.takeUpTo(max6)),takeBetween=dual(3,(self,min4,max6)=>self.takeBetween(min4,max6)),takeN=dual(2,(self,n)=>self.takeBetween(n,n)),backPressureStrategy=()=>new BackPressureStrategy,droppingStrategy=()=>new DroppingStrategy,slidingStrategy=()=>new SlidingStrategy;class BackPressureStrategy{[QueueStrategyTypeId]=queueStrategyVariance;putters=unbounded();surplusSize(){return length2(this.putters)}onCompleteTakersWithEmptyQueue(takers){while(!isEmpty7(this.putters)&&!isEmpty7(takers)){let taker=poll2(takers,void 0),putter=poll2(this.putters,void 0);if(putter[2])unsafeCompleteDeferred(putter[1],!0);unsafeCompleteDeferred(taker,putter[0])}}get shutdown(){return pipe(fiberId,flatMap8((fiberId3)=>pipe(sync(()=>unsafePollAll(this.putters)),flatMap8((putters)=>forEachConcurrentDiscard(putters,([_,deferred,isLastItem])=>isLastItem?pipe(deferredInterruptWith(deferred,fiberId3),asVoid):void_,!1,!1)))))}handleSurplus(iterable,queue,takers,isShutdown2){return withFiberRuntime((state)=>{let deferred=deferredUnsafeMake(state.id());return pipe(suspend(()=>{return this.unsafeOffer(iterable,deferred),this.unsafeOnQueueEmptySpace(queue,takers),unsafeCompleteTakers(this,queue,takers),get6(isShutdown2)?interrupt2:deferredAwait(deferred)}),onInterrupt(()=>sync(()=>this.unsafeRemove(deferred))))})}unsafeOnQueueEmptySpace(queue,takers){let keepPolling=!0;while(keepPolling&&(queue.capacity()===Number.POSITIVE_INFINITY||queue.length()<queue.capacity())){let putter=pipe(this.putters,poll2(EmptyMutableQueue));if(putter===EmptyMutableQueue)keepPolling=!1;else{let offered=queue.offer(putter[0]);if(offered&&putter[2])unsafeCompleteDeferred(putter[1],!0);else if(!offered)unsafeOfferAll(this.putters,pipe(unsafePollAll(this.putters),prepend2(putter)));unsafeCompleteTakers(this,queue,takers)}}}unsafeOffer(iterable,deferred){let stuff=fromIterable(iterable);for(let i=0;i<stuff.length;i++){let value=stuff[i];if(i===stuff.length-1)pipe(this.putters,offer([value,deferred,!0]));else pipe(this.putters,offer([value,deferred,!1]))}}unsafeRemove(deferred){unsafeOfferAll(this.putters,pipe(unsafePollAll(this.putters),filter3(([,_])=>_!==deferred)))}}class DroppingStrategy{[QueueStrategyTypeId]=queueStrategyVariance;surplusSize(){return 0}get shutdown(){return void_}onCompleteTakersWithEmptyQueue(){}handleSurplus(_iterable,_queue,_takers,_isShutdown){return succeed(!1)}unsafeOnQueueEmptySpace(_queue,_takers){}}class SlidingStrategy{[QueueStrategyTypeId]=queueStrategyVariance;surplusSize(){return 0}get shutdown(){return void_}onCompleteTakersWithEmptyQueue(){}handleSurplus(iterable,queue,takers,_isShutdown){return sync(()=>{return this.unsafeOffer(queue,iterable),unsafeCompleteTakers(this,queue,takers),!0})}unsafeOnQueueEmptySpace(_queue,_takers){}unsafeOffer(queue,iterable){let iterator=iterable[Symbol.iterator](),next4,offering=!0;while(!(next4=iterator.next()).done&&offering){if(queue.capacity()===0)return;queue.poll(EmptyMutableQueue),offering=queue.offer(next4.value)}}}var unsafeCompleteDeferred=(deferred,a)=>{return deferredUnsafeDone(deferred,succeed(a))},unsafeOfferAll=(queue,as4)=>{return pipe(queue,offerAll(as4))},unsafePollAll=(queue)=>{return pipe(queue,pollUpTo(Number.POSITIVE_INFINITY))},unsafePollN=(queue,max6)=>{return pipe(queue,pollUpTo(max6))},unsafeRemove=(queue,a)=>{unsafeOfferAll(queue,pipe(unsafePollAll(queue),filter3((b)=>a!==b)))},unsafeCompleteTakers=(strategy,queue,takers)=>{let keepPolling=!0;while(keepPolling&&queue.length()!==0){let taker=pipe(takers,poll2(EmptyMutableQueue));if(taker!==EmptyMutableQueue){let element=queue.poll(EmptyMutableQueue);if(element!==EmptyMutableQueue)unsafeCompleteDeferred(taker,element),strategy.unsafeOnQueueEmptySpace(queue,takers);else unsafeOfferAll(takers,pipe(unsafePollAll(takers),prepend2(taker)));keepPolling=!0}else keepPolling=!1}if(keepPolling&&queue.length()===0&&!isEmpty7(takers))strategy.onCompleteTakersWithEmptyQueue(takers)};var AbsentValue=Symbol.for("effect/PubSub/AbsentValue"),addSubscribers=(subscription,pollers)=>(subscribers)=>{if(!subscribers.has(subscription))subscribers.set(subscription,new Set);subscribers.get(subscription).add(pollers)},removeSubscribers=(subscription,pollers)=>(subscribers)=>{if(!subscribers.has(subscription))return;let set7=subscribers.get(subscription);if(set7.delete(pollers),set7.size===0)subscribers.delete(subscription)},bounded3=(capacity3)=>suspend(()=>{let pubsub=makeBoundedPubSub(capacity3);return makePubSub(pubsub,new BackPressureStrategy2)}),dropping2=(capacity3)=>suspend(()=>{let pubsub=makeBoundedPubSub(capacity3);return makePubSub(pubsub,new DroppingStrategy2)}),sliding2=(capacity3)=>suspend(()=>{let pubsub=makeBoundedPubSub(capacity3);return makePubSub(pubsub,new SlidingStrategy2)}),unbounded3=(options)=>suspend(()=>{let pubsub=makeUnboundedPubSub(options);return makePubSub(pubsub,new DroppingStrategy2)});var shutdown2=(self)=>self.shutdown;var subscribe=(self)=>self.subscribe,makeBoundedPubSub=(capacity3)=>{let options=typeof capacity3==="number"?{capacity:capacity3}:capacity3;ensureCapacity(options.capacity);let replayBuffer=options.replay&&options.replay>0?new ReplayBuffer(Math.ceil(options.replay)):void 0;if(options.capacity===1)return new BoundedPubSubSingle(replayBuffer);else if(nextPow2(options.capacity)===options.capacity)return new BoundedPubSubPow2(options.capacity,replayBuffer);else return new BoundedPubSubArb(options.capacity,replayBuffer)},makeUnboundedPubSub=(options)=>new UnboundedPubSub(options?.replay?new ReplayBuffer(options.replay):void 0),makeSubscription=(pubsub,subscribers,strategy)=>map10(deferredMake(),(deferred)=>unsafeMakeSubscription(pubsub,subscribers,pubsub.subscribe(),unbounded(),deferred,make12(!1),strategy)),unsafeMakeSubscription=(pubsub,subscribers,subscription,pollers,shutdownHook,shutdownFlag,strategy)=>new SubscriptionImpl(pubsub,subscribers,subscription,pollers,shutdownHook,shutdownFlag,strategy,pubsub.replayWindow());class BoundedPubSubArb{capacity;replayBuffer;array;publisherIndex=0;subscribers;subscriberCount=0;subscribersIndex=0;constructor(capacity3,replayBuffer){this.capacity=capacity3,this.replayBuffer=replayBuffer,this.array=Array.from({length:capacity3}),this.subscribers=Array.from({length:capacity3})}replayWindow(){return this.replayBuffer?new ReplayWindowImpl(this.replayBuffer):emptyReplayWindow}isEmpty(){return this.publisherIndex===this.subscribersIndex}isFull(){return this.publisherIndex===this.subscribersIndex+this.capacity}size(){return this.publisherIndex-this.subscribersIndex}publish(value){if(this.isFull())return!1;if(this.subscriberCount!==0){let index=this.publisherIndex%this.capacity;this.array[index]=value,this.subscribers[index]=this.subscriberCount,this.publisherIndex+=1}if(this.replayBuffer)this.replayBuffer.offer(value);return!0}publishAll(elements){if(this.subscriberCount===0){if(this.replayBuffer)this.replayBuffer.offerAll(elements);return empty5()}let chunk2=fromIterable2(elements),n=chunk2.length,size12=this.publisherIndex-this.subscribersIndex,available=this.capacity-size12,forPubSub=Math.min(n,available);if(forPubSub===0)return chunk2;let iteratorIndex=0,publishAllIndex=this.publisherIndex+forPubSub;while(this.publisherIndex!==publishAllIndex){let a=unsafeGet4(chunk2,iteratorIndex++),index=this.publisherIndex%this.capacity;if(this.array[index]=a,this.subscribers[index]=this.subscriberCount,this.publisherIndex+=1,this.replayBuffer)this.replayBuffer.offer(a)}return drop2(chunk2,iteratorIndex)}slide(){if(this.subscribersIndex!==this.publisherIndex){let index=this.subscribersIndex%this.capacity;this.array[index]=AbsentValue,this.subscribers[index]=0,this.subscribersIndex+=1}if(this.replayBuffer)this.replayBuffer.slide()}subscribe(){return this.subscriberCount+=1,new BoundedPubSubArbSubscription(this,this.publisherIndex,!1)}}class BoundedPubSubArbSubscription{self;subscriberIndex;unsubscribed;constructor(self,subscriberIndex,unsubscribed){this.self=self,this.subscriberIndex=subscriberIndex,this.unsubscribed=unsubscribed}isEmpty(){return this.unsubscribed||this.self.publisherIndex===this.subscriberIndex||this.self.publisherIndex===this.self.subscribersIndex}size(){if(this.unsubscribed)return 0;return this.self.publisherIndex-Math.max(this.subscriberIndex,this.self.subscribersIndex)}poll(default_){if(this.unsubscribed)return default_;if(this.subscriberIndex=Math.max(this.subscriberIndex,this.self.subscribersIndex),this.subscriberIndex!==this.self.publisherIndex){let index=this.subscriberIndex%this.self.capacity,elem=this.self.array[index];if(this.self.subscribers[index]-=1,this.self.subscribers[index]===0)this.self.array[index]=AbsentValue,this.self.subscribersIndex+=1;return this.subscriberIndex+=1,elem}return default_}pollUpTo(n){if(this.unsubscribed)return empty5();this.subscriberIndex=Math.max(this.subscriberIndex,this.self.subscribersIndex);let size12=this.self.publisherIndex-this.subscriberIndex,toPoll=Math.min(n,size12);if(toPoll<=0)return empty5();let builder=[],pollUpToIndex=this.subscriberIndex+toPoll;while(this.subscriberIndex!==pollUpToIndex){let index=this.subscriberIndex%this.self.capacity,a=this.self.array[index];if(this.self.subscribers[index]-=1,this.self.subscribers[index]===0)this.self.array[index]=AbsentValue,this.self.subscribersIndex+=1;builder.push(a),this.subscriberIndex+=1}return fromIterable2(builder)}unsubscribe(){if(!this.unsubscribed){this.unsubscribed=!0,this.self.subscriberCount-=1,this.subscriberIndex=Math.max(this.subscriberIndex,this.self.subscribersIndex);while(this.subscriberIndex!==this.self.publisherIndex){let index=this.subscriberIndex%this.self.capacity;if(this.self.subscribers[index]-=1,this.self.subscribers[index]===0)this.self.array[index]=AbsentValue,this.self.subscribersIndex+=1;this.subscriberIndex+=1}}}}class BoundedPubSubPow2{capacity;replayBuffer;array;mask;publisherIndex=0;subscribers;subscriberCount=0;subscribersIndex=0;constructor(capacity3,replayBuffer){this.capacity=capacity3,this.replayBuffer=replayBuffer,this.array=Array.from({length:capacity3}),this.mask=capacity3-1,this.subscribers=Array.from({length:capacity3})}replayWindow(){return this.replayBuffer?new ReplayWindowImpl(this.replayBuffer):emptyReplayWindow}isEmpty(){return this.publisherIndex===this.subscribersIndex}isFull(){return this.publisherIndex===this.subscribersIndex+this.capacity}size(){return this.publisherIndex-this.subscribersIndex}publish(value){if(this.isFull())return!1;if(this.subscriberCount!==0){let index=this.publisherIndex&this.mask;this.array[index]=value,this.subscribers[index]=this.subscriberCount,this.publisherIndex+=1}if(this.replayBuffer)this.replayBuffer.offer(value);return!0}publishAll(elements){if(this.subscriberCount===0){if(this.replayBuffer)this.replayBuffer.offerAll(elements);return empty5()}let chunk2=fromIterable2(elements),n=chunk2.length,size12=this.publisherIndex-this.subscribersIndex,available=this.capacity-size12,forPubSub=Math.min(n,available);if(forPubSub===0)return chunk2;let iteratorIndex=0,publishAllIndex=this.publisherIndex+forPubSub;while(this.publisherIndex!==publishAllIndex){let elem=unsafeGet4(chunk2,iteratorIndex++),index=this.publisherIndex&this.mask;if(this.array[index]=elem,this.subscribers[index]=this.subscriberCount,this.publisherIndex+=1,this.replayBuffer)this.replayBuffer.offer(elem)}return drop2(chunk2,iteratorIndex)}slide(){if(this.subscribersIndex!==this.publisherIndex){let index=this.subscribersIndex&this.mask;this.array[index]=AbsentValue,this.subscribers[index]=0,this.subscribersIndex+=1}if(this.replayBuffer)this.replayBuffer.slide()}subscribe(){return this.subscriberCount+=1,new BoundedPubSubPow2Subscription(this,this.publisherIndex,!1)}}class BoundedPubSubPow2Subscription{self;subscriberIndex;unsubscribed;constructor(self,subscriberIndex,unsubscribed){this.self=self,this.subscriberIndex=subscriberIndex,this.unsubscribed=unsubscribed}isEmpty(){return this.unsubscribed||this.self.publisherIndex===this.subscriberIndex||this.self.publisherIndex===this.self.subscribersIndex}size(){if(this.unsubscribed)return 0;return this.self.publisherIndex-Math.max(this.subscriberIndex,this.self.subscribersIndex)}poll(default_){if(this.unsubscribed)return default_;if(this.subscriberIndex=Math.max(this.subscriberIndex,this.self.subscribersIndex),this.subscriberIndex!==this.self.publisherIndex){let index=this.subscriberIndex&this.self.mask,elem=this.self.array[index];if(this.self.subscribers[index]-=1,this.self.subscribers[index]===0)this.self.array[index]=AbsentValue,this.self.subscribersIndex+=1;return this.subscriberIndex+=1,elem}return default_}pollUpTo(n){if(this.unsubscribed)return empty5();this.subscriberIndex=Math.max(this.subscriberIndex,this.self.subscribersIndex);let size12=this.self.publisherIndex-this.subscriberIndex,toPoll=Math.min(n,size12);if(toPoll<=0)return empty5();let builder=[],pollUpToIndex=this.subscriberIndex+toPoll;while(this.subscriberIndex!==pollUpToIndex){let index=this.subscriberIndex&this.self.mask,elem=this.self.array[index];if(this.self.subscribers[index]-=1,this.self.subscribers[index]===0)this.self.array[index]=AbsentValue,this.self.subscribersIndex+=1;builder.push(elem),this.subscriberIndex+=1}return fromIterable2(builder)}unsubscribe(){if(!this.unsubscribed){this.unsubscribed=!0,this.self.subscriberCount-=1,this.subscriberIndex=Math.max(this.subscriberIndex,this.self.subscribersIndex);while(this.subscriberIndex!==this.self.publisherIndex){let index=this.subscriberIndex&this.self.mask;if(this.self.subscribers[index]-=1,this.self.subscribers[index]===0)this.self.array[index]=AbsentValue,this.self.subscribersIndex+=1;this.subscriberIndex+=1}}}}class BoundedPubSubSingle{replayBuffer;publisherIndex=0;subscriberCount=0;subscribers=0;value=AbsentValue;capacity=1;constructor(replayBuffer){this.replayBuffer=replayBuffer}replayWindow(){return this.replayBuffer?new ReplayWindowImpl(this.replayBuffer):emptyReplayWindow}pipe(){return pipeArguments(this,arguments)}isEmpty(){return this.subscribers===0}isFull(){return!this.isEmpty()}size(){return this.isEmpty()?0:1}publish(value){if(this.isFull())return!1;if(this.subscriberCount!==0)this.value=value,this.subscribers=this.subscriberCount,this.publisherIndex+=1;if(this.replayBuffer)this.replayBuffer.offer(value);return!0}publishAll(elements){if(this.subscriberCount===0){if(this.replayBuffer)this.replayBuffer.offerAll(elements);return empty5()}let chunk2=fromIterable2(elements);if(isEmpty(chunk2))return chunk2;if(this.publish(unsafeHead2(chunk2)))return drop2(chunk2,1);else return chunk2}slide(){if(this.isFull())this.subscribers=0,this.value=AbsentValue;if(this.replayBuffer)this.replayBuffer.slide()}subscribe(){return this.subscriberCount+=1,new BoundedPubSubSingleSubscription(this,this.publisherIndex,!1)}}class BoundedPubSubSingleSubscription{self;subscriberIndex;unsubscribed;constructor(self,subscriberIndex,unsubscribed){this.self=self,this.subscriberIndex=subscriberIndex,this.unsubscribed=unsubscribed}isEmpty(){return this.unsubscribed||this.self.subscribers===0||this.subscriberIndex===this.self.publisherIndex}size(){return this.isEmpty()?0:1}poll(default_){if(this.isEmpty())return default_;let elem=this.self.value;if(this.self.subscribers-=1,this.self.subscribers===0)this.self.value=AbsentValue;return this.subscriberIndex+=1,elem}pollUpTo(n){if(this.isEmpty()||n<1)return empty5();let a=this.self.value;if(this.self.subscribers-=1,this.self.subscribers===0)this.self.value=AbsentValue;return this.subscriberIndex+=1,of2(a)}unsubscribe(){if(!this.unsubscribed){if(this.unsubscribed=!0,this.self.subscriberCount-=1,this.subscriberIndex!==this.self.publisherIndex){if(this.self.subscribers-=1,this.self.subscribers===0)this.self.value=AbsentValue}}}}class UnboundedPubSub{replayBuffer;publisherHead={value:AbsentValue,subscribers:0,next:null};publisherTail=this.publisherHead;publisherIndex=0;subscribersIndex=0;capacity=Number.MAX_SAFE_INTEGER;constructor(replayBuffer){this.replayBuffer=replayBuffer}replayWindow(){return this.replayBuffer?new ReplayWindowImpl(this.replayBuffer):emptyReplayWindow}isEmpty(){return this.publisherHead===this.publisherTail}isFull(){return!1}size(){return this.publisherIndex-this.subscribersIndex}publish(value){let subscribers=this.publisherTail.subscribers;if(subscribers!==0)this.publisherTail.next={value,subscribers,next:null},this.publisherTail=this.publisherTail.next,this.publisherIndex+=1;if(this.replayBuffer)this.replayBuffer.offer(value);return!0}publishAll(elements){if(this.publisherTail.subscribers!==0)for(let a of elements)this.publish(a);else if(this.replayBuffer)this.replayBuffer.offerAll(elements);return empty5()}slide(){if(this.publisherHead!==this.publisherTail)this.publisherHead=this.publisherHead.next,this.publisherHead.value=AbsentValue,this.subscribersIndex+=1;if(this.replayBuffer)this.replayBuffer.slide()}subscribe(){return this.publisherTail.subscribers+=1,new UnboundedPubSubSubscription(this,this.publisherTail,this.publisherIndex,!1)}}class UnboundedPubSubSubscription{self;subscriberHead;subscriberIndex;unsubscribed;constructor(self,subscriberHead,subscriberIndex,unsubscribed){this.self=self,this.subscriberHead=subscriberHead,this.subscriberIndex=subscriberIndex,this.unsubscribed=unsubscribed}isEmpty(){if(this.unsubscribed)return!0;let empty34=!0,loop3=!0;while(loop3)if(this.subscriberHead===this.self.publisherTail)loop3=!1;else if(this.subscriberHead.next.value!==AbsentValue)empty34=!1,loop3=!1;else this.subscriberHead=this.subscriberHead.next,this.subscriberIndex+=1;return empty34}size(){if(this.unsubscribed)return 0;return this.self.publisherIndex-Math.max(this.subscriberIndex,this.self.subscribersIndex)}poll(default_){if(this.unsubscribed)return default_;let loop3=!0,polled=default_;while(loop3)if(this.subscriberHead===this.self.publisherTail)loop3=!1;else{let elem=this.subscriberHead.next.value;if(elem!==AbsentValue){if(polled=elem,this.subscriberHead.subscribers-=1,this.subscriberHead.subscribers===0)this.self.publisherHead=this.self.publisherHead.next,this.self.publisherHead.value=AbsentValue,this.self.subscribersIndex+=1;loop3=!1}this.subscriberHead=this.subscriberHead.next,this.subscriberIndex+=1}return polled}pollUpTo(n){let builder=[],default_=AbsentValue,i=0;while(i!==n){let a=this.poll(default_);if(a===default_)i=n;else builder.push(a),i+=1}return fromIterable2(builder)}unsubscribe(){if(!this.unsubscribed){this.unsubscribed=!0,this.self.publisherTail.subscribers-=1;while(this.subscriberHead!==this.self.publisherTail){if(this.subscriberHead.next.value!==AbsentValue){if(this.subscriberHead.subscribers-=1,this.subscriberHead.subscribers===0)this.self.publisherHead=this.self.publisherHead.next,this.self.publisherHead.value=AbsentValue,this.self.subscribersIndex+=1}this.subscriberHead=this.subscriberHead.next}}}}class SubscriptionImpl extends Class{pubsub;subscribers;subscription;pollers;shutdownHook;shutdownFlag;strategy;replayWindow;[DequeueTypeId]=dequeueVariance;constructor(pubsub,subscribers,subscription,pollers,shutdownHook,shutdownFlag,strategy,replayWindow){super();this.pubsub=pubsub,this.subscribers=subscribers,this.subscription=subscription,this.pollers=pollers,this.shutdownHook=shutdownHook,this.shutdownFlag=shutdownFlag,this.strategy=strategy,this.replayWindow=replayWindow}commit(){return this.take}pipe(){return pipeArguments(this,arguments)}capacity(){return this.pubsub.capacity}isActive(){return!get6(this.shutdownFlag)}get size(){return suspend(()=>get6(this.shutdownFlag)?interrupt2:succeed(this.subscription.size()+this.replayWindow.remaining))}unsafeSize(){if(get6(this.shutdownFlag))return none2();return some2(this.subscription.size()+this.replayWindow.remaining)}get isFull(){return suspend(()=>get6(this.shutdownFlag)?interrupt2:succeed(this.subscription.size()===this.capacity()))}get isEmpty(){return map10(this.size,(size12)=>size12===0)}get shutdown(){return uninterruptible(withFiberRuntime((state)=>{return set2(this.shutdownFlag,!0),pipe(forEachParUnbounded(unsafePollAllQueue(this.pollers),(d)=>deferredInterruptWith(d,state.id()),!1),zipRight(sync(()=>{this.subscribers.delete(this.subscription),this.subscription.unsubscribe(),this.strategy.unsafeOnPubSubEmptySpace(this.pubsub,this.subscribers)})),whenEffect(deferredSucceed(this.shutdownHook,void 0)),asVoid)}))}get isShutdown(){return sync(()=>get6(this.shutdownFlag))}get awaitShutdown(){return deferredAwait(this.shutdownHook)}get take(){return withFiberRuntime((state)=>{if(get6(this.shutdownFlag))return interrupt2;if(this.replayWindow.remaining>0){let message2=this.replayWindow.take();return succeed(message2)}let message=isEmpty7(this.pollers)?this.subscription.poll(EmptyMutableQueue):EmptyMutableQueue;if(message===EmptyMutableQueue){let deferred=deferredUnsafeMake(state.id());return pipe(suspend(()=>{return pipe(this.pollers,offer(deferred)),pipe(this.subscribers,addSubscribers(this.subscription,this.pollers)),this.strategy.unsafeCompletePollers(this.pubsub,this.subscribers,this.subscription,this.pollers),get6(this.shutdownFlag)?interrupt2:deferredAwait(deferred)}),onInterrupt(()=>sync(()=>unsafeRemove2(this.pollers,deferred))))}else return this.strategy.unsafeOnPubSubEmptySpace(this.pubsub,this.subscribers),succeed(message)})}get takeAll(){return suspend(()=>{if(get6(this.shutdownFlag))return interrupt2;let as4=isEmpty7(this.pollers)?unsafePollAllSubscription(this.subscription):empty5();if(this.strategy.unsafeOnPubSubEmptySpace(this.pubsub,this.subscribers),this.replayWindow.remaining>0)return succeed(appendAll2(this.replayWindow.takeAll(),as4));return succeed(as4)})}takeUpTo(max6){return suspend(()=>{if(get6(this.shutdownFlag))return interrupt2;let replay=void 0;if(this.replayWindow.remaining>=max6){let as5=this.replayWindow.takeN(max6);return succeed(as5)}else if(this.replayWindow.remaining>0)replay=this.replayWindow.takeAll(),max6=max6-replay.length;let as4=isEmpty7(this.pollers)?unsafePollN2(this.subscription,max6):empty5();return this.strategy.unsafeOnPubSubEmptySpace(this.pubsub,this.subscribers),replay?succeed(appendAll2(replay,as4)):succeed(as4)})}takeBetween(min4,max6){return suspend(()=>takeRemainderLoop2(this,min4,max6,empty5()))}}var takeRemainderLoop2=(self,min4,max6,acc)=>{if(max6<min4)return succeed(acc);return pipe(self.takeUpTo(max6),flatMap8((bs)=>{let remaining=min4-bs.length;if(remaining===1)return pipe(self.take,map10((b)=>pipe(acc,appendAll2(bs),append2(b))));if(remaining>1)return pipe(self.take,flatMap8((b)=>takeRemainderLoop2(self,remaining-1,max6-bs.length-1,pipe(acc,appendAll2(bs),append2(b)))));return succeed(pipe(acc,appendAll2(bs)))}))};class PubSubImpl{pubsub;subscribers;scope;shutdownHook;shutdownFlag;strategy;[EnqueueTypeId]=enqueueVariance;[DequeueTypeId]=dequeueVariance;constructor(pubsub,subscribers,scope4,shutdownHook,shutdownFlag,strategy){this.pubsub=pubsub,this.subscribers=subscribers,this.scope=scope4,this.shutdownHook=shutdownHook,this.shutdownFlag=shutdownFlag,this.strategy=strategy}capacity(){return this.pubsub.capacity}get size(){return suspend(()=>get6(this.shutdownFlag)?interrupt2:sync(()=>this.pubsub.size()))}unsafeSize(){if(get6(this.shutdownFlag))return none2();return some2(this.pubsub.size())}get isFull(){return map10(this.size,(size12)=>size12===this.capacity())}get isEmpty(){return map10(this.size,(size12)=>size12===0)}get awaitShutdown(){return deferredAwait(this.shutdownHook)}get isShutdown(){return sync(()=>get6(this.shutdownFlag))}get shutdown(){return uninterruptible(withFiberRuntime((state)=>{return pipe(this.shutdownFlag,set2(!0)),pipe(this.scope.close(exitInterrupt(state.id())),zipRight(this.strategy.shutdown),whenEffect(deferredSucceed(this.shutdownHook,void 0)),asVoid)}))}publish(value){return suspend(()=>{if(get6(this.shutdownFlag))return interrupt2;if(this.pubsub.publish(value))return this.strategy.unsafeCompleteSubscribers(this.pubsub,this.subscribers),succeed(!0);return this.strategy.handleSurplus(this.pubsub,this.subscribers,of2(value),this.shutdownFlag)})}isActive(){return!get6(this.shutdownFlag)}unsafeOffer(value){if(get6(this.shutdownFlag))return!1;if(this.pubsub.publish(value))return this.strategy.unsafeCompleteSubscribers(this.pubsub,this.subscribers),!0;return!1}publishAll(elements){return suspend(()=>{if(get6(this.shutdownFlag))return interrupt2;let surplus=unsafePublishAll(this.pubsub,elements);if(this.strategy.unsafeCompleteSubscribers(this.pubsub,this.subscribers),isEmpty(surplus))return succeed(!0);return this.strategy.handleSurplus(this.pubsub,this.subscribers,surplus,this.shutdownFlag)})}get subscribe(){let acquire=tap(all4([this.scope.fork(sequential2),makeSubscription(this.pubsub,this.subscribers,this.strategy)]),(tuple3)=>tuple3[0].addFinalizer(()=>tuple3[1].shutdown));return map10(acquireRelease(acquire,(tuple3,exit3)=>tuple3[0].close(exit3)),(tuple3)=>tuple3[1])}offer(value){return this.publish(value)}offerAll(elements){return this.publishAll(elements)}pipe(){return pipeArguments(this,arguments)}}var makePubSub=(pubsub,strategy)=>flatMap8(scopeMake(),(scope4)=>map10(deferredMake(),(deferred)=>unsafeMakePubSub(pubsub,new Map,scope4,deferred,make12(!1),strategy))),unsafeMakePubSub=(pubsub,subscribers,scope4,shutdownHook,shutdownFlag,strategy)=>new PubSubImpl(pubsub,subscribers,scope4,shutdownHook,shutdownFlag,strategy),ensureCapacity=(capacity3)=>{if(capacity3<=0)throw new InvalidPubSubCapacityException(`Cannot construct PubSub with capacity of ${capacity3}`)},unsafeCompleteDeferred2=(deferred,a)=>{deferredUnsafeDone(deferred,succeed(a))},unsafeOfferAll2=(queue,as4)=>{return pipe(queue,offerAll(as4))},unsafePollAllQueue=(queue)=>{return pipe(queue,pollUpTo(Number.POSITIVE_INFINITY))},unsafePollAllSubscription=(subscription)=>{return subscription.pollUpTo(Number.POSITIVE_INFINITY)},unsafePollN2=(subscription,max6)=>{return subscription.pollUpTo(max6)},unsafePublishAll=(pubsub,as4)=>{return pubsub.publishAll(as4)},unsafeRemove2=(queue,value)=>{unsafeOfferAll2(queue,pipe(unsafePollAllQueue(queue),filter3((elem)=>elem!==value)))};class BackPressureStrategy2{publishers=unbounded();get shutdown(){return flatMap8(fiberId,(fiberId3)=>flatMap8(sync(()=>unsafePollAllQueue(this.publishers)),(publishers)=>forEachConcurrentDiscard(publishers,([_,deferred,last4])=>last4?pipe(deferredInterruptWith(deferred,fiberId3),asVoid):void_,!1,!1)))}handleSurplus(pubsub,subscribers,elements,isShutdown2){return withFiberRuntime((state)=>{let deferred=deferredUnsafeMake(state.id());return pipe(suspend(()=>{return this.unsafeOffer(elements,deferred),this.unsafeOnPubSubEmptySpace(pubsub,subscribers),this.unsafeCompleteSubscribers(pubsub,subscribers),get6(isShutdown2)?interrupt2:deferredAwait(deferred)}),onInterrupt(()=>sync(()=>this.unsafeRemove(deferred))))})}unsafeOnPubSubEmptySpace(pubsub,subscribers){let keepPolling=!0;while(keepPolling&&!pubsub.isFull()){let publisher=pipe(this.publishers,poll2(EmptyMutableQueue));if(publisher===EmptyMutableQueue)keepPolling=!1;else{let published=pubsub.publish(publisher[0]);if(published&&publisher[2])unsafeCompleteDeferred2(publisher[1],!0);else if(!published)unsafeOfferAll2(this.publishers,pipe(unsafePollAllQueue(this.publishers),prepend2(publisher)));this.unsafeCompleteSubscribers(pubsub,subscribers)}}}unsafeCompletePollers(pubsub,subscribers,subscription,pollers){return unsafeStrategyCompletePollers(this,pubsub,subscribers,subscription,pollers)}unsafeCompleteSubscribers(pubsub,subscribers){return unsafeStrategyCompleteSubscribers(this,pubsub,subscribers)}unsafeOffer(elements,deferred){let iterator=elements[Symbol.iterator](),next4=iterator.next();if(!next4.done)while(!0){let value=next4.value;if(next4=iterator.next(),next4.done){pipe(this.publishers,offer([value,deferred,!0]));break}pipe(this.publishers,offer([value,deferred,!1]))}}unsafeRemove(deferred){unsafeOfferAll2(this.publishers,pipe(unsafePollAllQueue(this.publishers),filter3(([_,a])=>a!==deferred)))}}class DroppingStrategy2{get shutdown(){return void_}handleSurplus(_pubsub,_subscribers,_elements,_isShutdown){return succeed(!1)}unsafeOnPubSubEmptySpace(_pubsub,_subscribers){}unsafeCompletePollers(pubsub,subscribers,subscription,pollers){return unsafeStrategyCompletePollers(this,pubsub,subscribers,subscription,pollers)}unsafeCompleteSubscribers(pubsub,subscribers){return unsafeStrategyCompleteSubscribers(this,pubsub,subscribers)}}class SlidingStrategy2{get shutdown(){return void_}handleSurplus(pubsub,subscribers,elements,_isShutdown){return sync(()=>{return this.unsafeSlidingPublish(pubsub,elements),this.unsafeCompleteSubscribers(pubsub,subscribers),!0})}unsafeOnPubSubEmptySpace(_pubsub,_subscribers){}unsafeCompletePollers(pubsub,subscribers,subscription,pollers){return unsafeStrategyCompletePollers(this,pubsub,subscribers,subscription,pollers)}unsafeCompleteSubscribers(pubsub,subscribers){return unsafeStrategyCompleteSubscribers(this,pubsub,subscribers)}unsafeSlidingPublish(pubsub,elements){let it=elements[Symbol.iterator](),next4=it.next();if(!next4.done&&pubsub.capacity>0){let a=next4.value,loop3=!0;while(loop3){pubsub.slide();let pub=pubsub.publish(a);if(pub&&(next4=it.next())&&!next4.done)a=next4.value;else if(pub)loop3=!1}}}}var unsafeStrategyCompletePollers=(strategy,pubsub,subscribers,subscription,pollers)=>{let keepPolling=!0;while(keepPolling&&!subscription.isEmpty()){let poller=pipe(pollers,poll2(EmptyMutableQueue));if(poller===EmptyMutableQueue)if(pipe(subscribers,removeSubscribers(subscription,pollers)),isEmpty7(pollers))keepPolling=!1;else pipe(subscribers,addSubscribers(subscription,pollers));else{let pollResult=subscription.poll(EmptyMutableQueue);if(pollResult===EmptyMutableQueue)unsafeOfferAll2(pollers,pipe(unsafePollAllQueue(pollers),prepend2(poller)));else unsafeCompleteDeferred2(poller,pollResult),strategy.unsafeOnPubSubEmptySpace(pubsub,subscribers)}}},unsafeStrategyCompleteSubscribers=(strategy,pubsub,subscribers)=>{for(let[subscription,pollersSet]of subscribers)for(let pollers of pollersSet)strategy.unsafeCompletePollers(pubsub,subscribers,subscription,pollers)};class ReplayBuffer{capacity;constructor(capacity3){this.capacity=capacity3}head={value:AbsentValue,next:null};tail=this.head;size=0;index=0;slide(){this.index++}offer(a){if(this.tail.value=a,this.tail.next={value:AbsentValue,next:null},this.tail=this.tail.next,this.size===this.capacity)this.head=this.head.next;else this.size+=1}offerAll(as4){for(let a of as4)this.offer(a)}}class ReplayWindowImpl{buffer;head;index;remaining;constructor(buffer){this.buffer=buffer,this.index=buffer.index,this.remaining=buffer.size,this.head=buffer.head}fastForward(){while(this.index<this.buffer.index)this.head=this.head.next,this.index++}take(){if(this.remaining===0)return;else if(this.index<this.buffer.index)this.fastForward();this.remaining--;let value=this.head.value;return this.head=this.head.next,value}takeN(n){if(this.remaining===0)return empty5();else if(this.index<this.buffer.index)this.fastForward();let len=Math.min(n,this.remaining),items=new Array(len);for(let i=0;i<len;i++){let value=this.head.value;this.head=this.head.next,items[i]=value}return this.remaining-=len,unsafeFromArray(items)}takeAll(){return this.takeN(this.remaining)}}var emptyReplayWindow={remaining:0,take:()=>{return},takeN:()=>empty5(),takeAll:()=>empty5()};var bounded4=bounded3,dropping3=dropping2,sliding3=sliding2,unbounded4=unbounded3;var shutdown3=shutdown2;var subscribe2=subscribe;var exports_Queue={};__export(exports_Queue,{unsafeOffer:()=>unsafeOffer2,unbounded:()=>unbounded5,takeUpTo:()=>takeUpTo2,takeN:()=>takeN2,takeBetween:()=>takeBetween2,takeAll:()=>takeAll2,take:()=>take3,slidingStrategy:()=>slidingStrategy2,sliding:()=>sliding4,size:()=>size13,shutdown:()=>shutdown4,poll:()=>poll6,offerAll:()=>offerAll3,offer:()=>offer3,make:()=>make44,isShutdown:()=>isShutdown3,isQueue:()=>isQueue2,isFull:()=>isFull3,isEnqueue:()=>isEnqueue2,isEmpty:()=>isEmpty12,isDequeue:()=>isDequeue2,droppingStrategy:()=>droppingStrategy2,dropping:()=>dropping4,capacity:()=>capacity4,bounded:()=>bounded5,backPressureStrategy:()=>backPressureStrategy2,awaitShutdown:()=>awaitShutdown3,QueueStrategyTypeId:()=>QueueStrategyTypeId2,EnqueueTypeId:()=>EnqueueTypeId2,DequeueTypeId:()=>DequeueTypeId2,BackingQueueTypeId:()=>BackingQueueTypeId2});var EnqueueTypeId2=EnqueueTypeId,DequeueTypeId2=DequeueTypeId,QueueStrategyTypeId2=QueueStrategyTypeId,BackingQueueTypeId2=BackingQueueTypeId,isQueue2=isQueue,isDequeue2=isDequeue,isEnqueue2=isEnqueue,backPressureStrategy2=backPressureStrategy,droppingStrategy2=droppingStrategy,slidingStrategy2=slidingStrategy,make44=make43,bounded5=bounded2,dropping4=dropping,sliding4=sliding,unbounded5=unbounded2,capacity4=capacity2,size13=size11,isEmpty12=isEmpty10,isFull3=isFull,isShutdown3=isShutdown,awaitShutdown3=awaitShutdown,shutdown4=shutdown,offer3=offer2,unsafeOffer2=unsafeOffer,offerAll3=offerAll2,poll6=poll5,take3=take2,takeAll2=takeAll,takeUpTo2=takeUpTo,takeBetween2=takeBetween,takeN2=takeN;var OP_CONTINUE2="Continue",OP_CLOSE="Close",OP_YIELD2="Yield";var ChildExecutorDecisionSymbolKey="effect/ChannelChildExecutorDecision",ChildExecutorDecisionTypeId=Symbol.for(ChildExecutorDecisionSymbolKey),proto4={[ChildExecutorDecisionTypeId]:ChildExecutorDecisionTypeId},Continue=(_)=>{let op=Object.create(proto4);return op._tag=OP_CONTINUE2,op};var OP_CONTINUATION_K="ContinuationK",OP_CONTINUATION_FINALIZER="ContinuationFinalizer";var ContinuationTypeId=Symbol.for("effect/ChannelContinuation"),continuationVariance={_Env:(_)=>_,_InErr:(_)=>_,_InElem:(_)=>_,_InDone:(_)=>_,_OutErr:(_)=>_,_OutDone:(_)=>_,_OutErr2:(_)=>_,_OutElem:(_)=>_,_OutDone2:(_)=>_};class ContinuationKImpl{onSuccess;onHalt;_tag=OP_CONTINUATION_K;[ContinuationTypeId]=continuationVariance;constructor(onSuccess,onHalt){this.onSuccess=onSuccess,this.onHalt=onHalt}onExit(exit3){return isFailure(exit3)?this.onHalt(exit3.cause):this.onSuccess(exit3.value)}}class ContinuationFinalizerImpl{finalizer;_tag=OP_CONTINUATION_FINALIZER;[ContinuationTypeId]=continuationVariance;constructor(finalizer){this.finalizer=finalizer}}var OP_PULL_AFTER_NEXT="PullAfterNext",OP_PULL_AFTER_ALL_ENQUEUED="PullAfterAllEnqueued";var UpstreamPullStrategySymbolKey="effect/ChannelUpstreamPullStrategy",UpstreamPullStrategyTypeId=Symbol.for(UpstreamPullStrategySymbolKey),upstreamPullStrategyVariance={_A:(_)=>_},proto5={[UpstreamPullStrategyTypeId]:upstreamPullStrategyVariance},PullAfterNext=(emitSeparator)=>{let op=Object.create(proto5);return op._tag=OP_PULL_AFTER_NEXT,op.emitSeparator=emitSeparator,op};var OP_BRACKET_OUT="BracketOut",OP_BRIDGE="Bridge",OP_CONCAT_ALL="ConcatAll",OP_EMIT="Emit",OP_ENSURING="Ensuring",OP_FAIL3="Fail",OP_FOLD2="Fold",OP_FROM_EFFECT2="FromEffect",OP_PIPE_TO="PipeTo",OP_PROVIDE2="Provide",OP_READ="Read",OP_SUCCEED="Succeed",OP_SUCCEED_NOW="SucceedNow",OP_SUSPEND2="Suspend";var ChannelSymbolKey="effect/Channel",ChannelTypeId2=Symbol.for(ChannelSymbolKey),channelVariance2={_Env:(_)=>_,_InErr:(_)=>_,_InElem:(_)=>_,_InDone:(_)=>_,_OutErr:(_)=>_,_OutElem:(_)=>_,_OutDone:(_)=>_},proto6={[ChannelTypeId2]:channelVariance2,pipe(){return pipeArguments(this,arguments)}},isChannel=(u)=>hasProperty(u,ChannelTypeId2)||isEffect2(u),acquireReleaseOut=dual(2,(self,release)=>{let op=Object.create(proto6);return op._tag=OP_BRACKET_OUT,op.acquire=()=>self,op.finalizer=release,op}),catchAllCause4=dual(2,(self,f)=>{let op=Object.create(proto6);return op._tag=OP_FOLD2,op.channel=self,op.k=new ContinuationKImpl(succeed10,f),op}),collectElements=(self)=>{return suspend4(()=>{let builder=[];return flatMap12(pipeTo(self,collectElementsReader(builder)),(value)=>sync4(()=>[fromIterable2(builder),value]))})},collectElementsReader=(builder)=>readWith({onInput:(outElem)=>flatMap12(sync4(()=>{builder.push(outElem)}),()=>collectElementsReader(builder)),onFailure:fail11,onDone:succeedNow});var concatAllWith=(channels,f,g)=>{let op=Object.create(proto6);return op._tag=OP_CONCAT_ALL,op.combineInners=f,op.combineAll=g,op.onPull=()=>PullAfterNext(none2()),op.onEmit=()=>Continue,op.value=()=>channels,op.k=identity,op},concatMapWith=dual(4,(self,f,g,h)=>{let op=Object.create(proto6);return op._tag=OP_CONCAT_ALL,op.combineInners=g,op.combineAll=h,op.onPull=()=>PullAfterNext(none2()),op.onEmit=()=>Continue,op.value=()=>self,op.k=f,op});var embedInput=dual(2,(self,input)=>{let op=Object.create(proto6);return op._tag=OP_BRIDGE,op.input=input,op.channel=self,op}),ensuringWith=dual(2,(self,finalizer)=>{let op=Object.create(proto6);return op._tag=OP_ENSURING,op.channel=self,op.finalizer=finalizer,op}),fail11=(error)=>failCause10(fail6(error));var failCause10=(cause3)=>failCauseSync4(()=>cause3),failCauseSync4=(evaluate2)=>{let op=Object.create(proto6);return op._tag=OP_FAIL3,op.error=evaluate2,op},flatMap12=dual(2,(self,f)=>{let op=Object.create(proto6);return op._tag=OP_FOLD2,op.channel=self,op.k=new ContinuationKImpl(f,failCause10),op}),foldCauseChannel=dual(2,(self,options)=>{let op=Object.create(proto6);return op._tag=OP_FOLD2,op.channel=self,op.k=new ContinuationKImpl(options.onSuccess,options.onFailure),op}),fromEffect5=(effect)=>{let op=Object.create(proto6);return op._tag=OP_FROM_EFFECT2,op.effect=()=>effect,op},pipeTo=dual(2,(self,that)=>{let op=Object.create(proto6);return op._tag=OP_PIPE_TO,op.left=()=>self,op.right=()=>that,op}),provideContext3=dual(2,(self,env)=>{let op=Object.create(proto6);return op._tag=OP_PROVIDE2,op.context=()=>env,op.inner=self,op});var readWith=(options)=>readWithCause({onInput:options.onInput,onFailure:(cause3)=>match(failureOrCause2(cause3),{onLeft:options.onFailure,onRight:failCause10}),onDone:options.onDone}),readWithCause=(options)=>{let op=Object.create(proto6);return op._tag=OP_READ,op.more=options.onInput,op.done=new ContinuationKImpl(options.onDone,options.onFailure),op},succeed10=(value)=>sync4(()=>value),succeedNow=(result)=>{let op=Object.create(proto6);return op._tag=OP_SUCCEED_NOW,op.terminal=result,op},suspend4=(evaluate2)=>{let op=Object.create(proto6);return op._tag=OP_SUSPEND2,op.channel=evaluate2,op},sync4=(evaluate2)=>{let op=Object.create(proto6);return op._tag=OP_SUCCEED,op.evaluate=evaluate2,op},void_6=succeedNow(void 0);var write=(out)=>{let op=Object.create(proto6);return op._tag=OP_EMIT,op.out=out,op};var OP_DONE3="Done",OP_EMIT2="Emit",OP_FROM_EFFECT3="FromEffect",OP_READ2="Read";var ChannelStateTypeId=Symbol.for("effect/ChannelState"),channelStateVariance={_E:(_)=>_,_R:(_)=>_},proto7={[ChannelStateTypeId]:channelStateVariance},Done2=()=>{let op=Object.create(proto7);return op._tag=OP_DONE3,op},Emit=()=>{let op=Object.create(proto7);return op._tag=OP_EMIT2,op},fromEffect6=(effect)=>{let op=Object.create(proto7);return op._tag=OP_FROM_EFFECT3,op.effect=effect,op},Read=(upstream,onEffect,onEmit,onDone)=>{let op=Object.create(proto7);return op._tag=OP_READ2,op.upstream=upstream,op.onEffect=onEffect,op.onEmit=onEmit,op.onDone=onDone,op};var isFromEffect=(self)=>self._tag===OP_FROM_EFFECT3;var effect=(self)=>isFromEffect(self)?self.effect:_void,effectOrUndefinedIgnored=(self)=>isFromEffect(self)?ignore2(self.effect):void 0;var OP_PULL_FROM_CHILD="PullFromChild",OP_PULL_FROM_UPSTREAM="PullFromUpstream",OP_DRAIN_CHILD_EXECUTORS="DrainChildExecutors",OP_EMIT3="Emit";class PullFromChild{childExecutor;parentSubexecutor;onEmit;_tag=OP_PULL_FROM_CHILD;constructor(childExecutor,parentSubexecutor,onEmit){this.childExecutor=childExecutor,this.parentSubexecutor=parentSubexecutor,this.onEmit=onEmit}close(exit3){let fin1=this.childExecutor.close(exit3),fin2=this.parentSubexecutor.close(exit3);if(fin1!==void 0&&fin2!==void 0)return zipWith8(exit2(fin1),exit2(fin2),(exit1,exit22)=>pipe(exit1,zipRight2(exit22)));else if(fin1!==void 0)return fin1;else if(fin2!==void 0)return fin2;else return}enqueuePullFromChild(_child){return this}}class PullFromUpstream{upstreamExecutor;createChild;lastDone;activeChildExecutors;combineChildResults;combineWithChildResult;onPull;onEmit;_tag=OP_PULL_FROM_UPSTREAM;constructor(upstreamExecutor,createChild,lastDone,activeChildExecutors,combineChildResults,combineWithChildResult,onPull,onEmit){this.upstreamExecutor=upstreamExecutor,this.createChild=createChild,this.lastDone=lastDone,this.activeChildExecutors=activeChildExecutors,this.combineChildResults=combineChildResults,this.combineWithChildResult=combineWithChildResult,this.onPull=onPull,this.onEmit=onEmit}close(exit3){let fin1=this.upstreamExecutor.close(exit3),result=[...this.activeChildExecutors.map((child)=>child!==void 0?child.childExecutor.close(exit3):void 0),fin1].reduce((acc,next4)=>{if(acc!==void 0&&next4!==void 0)return zipWith8(acc,exit2(next4),(exit1,exit22)=>zipRight2(exit1,exit22));else if(acc!==void 0)return acc;else if(next4!==void 0)return exit2(next4);else return},void 0);return result===void 0?result:result}enqueuePullFromChild(child){return new PullFromUpstream(this.upstreamExecutor,this.createChild,this.lastDone,[...this.activeChildExecutors,child],this.combineChildResults,this.combineWithChildResult,this.onPull,this.onEmit)}}class DrainChildExecutors{upstreamExecutor;lastDone;activeChildExecutors;upstreamDone;combineChildResults;combineWithChildResult;onPull;_tag=OP_DRAIN_CHILD_EXECUTORS;constructor(upstreamExecutor,lastDone,activeChildExecutors,upstreamDone,combineChildResults,combineWithChildResult,onPull){this.upstreamExecutor=upstreamExecutor,this.lastDone=lastDone,this.activeChildExecutors=activeChildExecutors,this.upstreamDone=upstreamDone,this.combineChildResults=combineChildResults,this.combineWithChildResult=combineWithChildResult,this.onPull=onPull}close(exit3){let fin1=this.upstreamExecutor.close(exit3),result=[...this.activeChildExecutors.map((child)=>child!==void 0?child.childExecutor.close(exit3):void 0),fin1].reduce((acc,next4)=>{if(acc!==void 0&&next4!==void 0)return zipWith8(acc,exit2(next4),(exit1,exit22)=>zipRight2(exit1,exit22));else if(acc!==void 0)return acc;else if(next4!==void 0)return exit2(next4);else return},void 0);return result===void 0?result:result}enqueuePullFromChild(child){return new DrainChildExecutors(this.upstreamExecutor,this.lastDone,[...this.activeChildExecutors,child],this.upstreamDone,this.combineChildResults,this.combineWithChildResult,this.onPull)}}class Emit2{value;next;_tag=OP_EMIT3;constructor(value,next4){this.value=value,this.next=next4}close(exit3){let result=this.next.close(exit3);return result===void 0?result:result}enqueuePullFromChild(_child){return this}}var OP_PULLED="Pulled",OP_NO_UPSTREAM="NoUpstream";var UpstreamPullRequestSymbolKey="effect/ChannelUpstreamPullRequest",UpstreamPullRequestTypeId=Symbol.for(UpstreamPullRequestSymbolKey),upstreamPullRequestVariance={_A:(_)=>_},proto8={[UpstreamPullRequestTypeId]:upstreamPullRequestVariance},Pulled=(value)=>{let op=Object.create(proto8);return op._tag=OP_PULLED,op.value=value,op},NoUpstream=(activeDownstreamCount)=>{let op=Object.create(proto8);return op._tag=OP_NO_UPSTREAM,op.activeDownstreamCount=activeDownstreamCount,op};class ChannelExecutor{_activeSubexecutor=void 0;_cancelled=void 0;_closeLastSubstream=void 0;_currentChannel;_done=void 0;_doneStack=[];_emitted=void 0;_executeCloseLastSubstream;_input=void 0;_inProgressFinalizer=void 0;_providedEnv;constructor(initialChannel,providedEnv,executeCloseLastSubstream){this._currentChannel=initialChannel,this._executeCloseLastSubstream=executeCloseLastSubstream,this._providedEnv=providedEnv}run(){let result=void 0;while(result===void 0)if(this._cancelled!==void 0)result=this.processCancellation();else if(this._activeSubexecutor!==void 0)result=this.runSubexecutor();else try{if(this._currentChannel===void 0)result=Done2();else{if(isEffect2(this._currentChannel))this._currentChannel=fromEffect5(this._currentChannel);switch(this._currentChannel._tag){case OP_BRACKET_OUT:{result=this.runBracketOut(this._currentChannel);break}case OP_BRIDGE:{let bridgeInput=this._currentChannel.input;if(this._currentChannel=this._currentChannel.channel,this._input!==void 0){let inputExecutor=this._input;this._input=void 0;let drainer=()=>flatMap10(bridgeInput.awaitRead(),()=>suspend3(()=>{let state=inputExecutor.run();switch(state._tag){case OP_DONE3:return match6(inputExecutor.getDone(),{onFailure:(cause3)=>bridgeInput.error(cause3),onSuccess:(value)=>bridgeInput.done(value)});case OP_EMIT2:return flatMap10(bridgeInput.emit(inputExecutor.getEmit()),()=>drainer());case OP_FROM_EFFECT3:return matchCauseEffect3(state.effect,{onFailure:(cause3)=>bridgeInput.error(cause3),onSuccess:()=>drainer()});case OP_READ2:return readUpstream(state,()=>drainer(),(cause3)=>bridgeInput.error(cause3))}}));result=fromEffect6(flatMap10(forkDaemon2(interruptible4(drainer())),(fiber)=>sync3(()=>this.addFinalizer((exit3)=>flatMap10(interrupt6(fiber),()=>suspend3(()=>{let effect2=this.restorePipe(exit3,inputExecutor);return effect2!==void 0?effect2:_void}))))))}break}case OP_CONCAT_ALL:{let executor=new ChannelExecutor(this._currentChannel.value(),this._providedEnv,(effect2)=>sync3(()=>{let prevLastClose=this._closeLastSubstream===void 0?_void:this._closeLastSubstream;this._closeLastSubstream=pipe(prevLastClose,zipRight4(effect2))}));executor._input=this._input;let channel=this._currentChannel;this._activeSubexecutor=new PullFromUpstream(executor,(value)=>channel.k(value),void 0,[],(x,y)=>channel.combineInners(x,y),(x,y)=>channel.combineAll(x,y),(request2)=>channel.onPull(request2),(value)=>channel.onEmit(value)),this._closeLastSubstream=void 0,this._currentChannel=void 0;break}case OP_EMIT:{this._emitted=this._currentChannel.out,this._currentChannel=this._activeSubexecutor!==void 0?void 0:void_6,result=Emit();break}case OP_ENSURING:{this.runEnsuring(this._currentChannel);break}case OP_FAIL3:{result=this.doneHalt(this._currentChannel.error());break}case OP_FOLD2:{this._doneStack.push(this._currentChannel.k),this._currentChannel=this._currentChannel.channel;break}case OP_FROM_EFFECT2:{let effect2=this._providedEnv===void 0?this._currentChannel.effect():pipe(this._currentChannel.effect(),provide2(this._providedEnv));result=fromEffect6(matchCauseEffect3(effect2,{onFailure:(cause3)=>{let state=this.doneHalt(cause3);return state!==void 0&&isFromEffect(state)?state.effect:_void},onSuccess:(value)=>{let state=this.doneSucceed(value);return state!==void 0&&isFromEffect(state)?state.effect:_void}}));break}case OP_PIPE_TO:{let previousInput=this._input,leftExec=new ChannelExecutor(this._currentChannel.left(),this._providedEnv,(effect2)=>this._executeCloseLastSubstream(effect2));leftExec._input=previousInput,this._input=leftExec,this.addFinalizer((exit3)=>{let effect2=this.restorePipe(exit3,previousInput);return effect2!==void 0?effect2:_void}),this._currentChannel=this._currentChannel.right();break}case OP_PROVIDE2:{let previousEnv=this._providedEnv;this._providedEnv=this._currentChannel.context(),this._currentChannel=this._currentChannel.inner,this.addFinalizer(()=>sync3(()=>{this._providedEnv=previousEnv}));break}case OP_READ:{let read=this._currentChannel;result=Read(this._input,identity,(emitted)=>{try{this._currentChannel=read.more(emitted)}catch(error){this._currentChannel=read.done.onExit(die3(error))}return},(exit3)=>{let onExit4=(exit4)=>{return read.done.onExit(exit4)};this._currentChannel=onExit4(exit3);return});break}case OP_SUCCEED:{result=this.doneSucceed(this._currentChannel.evaluate());break}case OP_SUCCEED_NOW:{result=this.doneSucceed(this._currentChannel.terminal);break}case OP_SUSPEND2:{this._currentChannel=this._currentChannel.channel();break}default:this._currentChannel._tag}}}catch(error){this._currentChannel=failCause10(die4(error))}return result}getDone(){return this._done}getEmit(){return this._emitted}cancelWith(exit3){this._cancelled=exit3}clearInProgressFinalizer(){this._inProgressFinalizer=void 0}storeInProgressFinalizer(finalizer){this._inProgressFinalizer=finalizer}popAllFinalizers(exit3){let finalizers=[],next4=this._doneStack.pop();while(next4){if(next4._tag==="ContinuationFinalizer")finalizers.push(next4.finalizer);next4=this._doneStack.pop()}let effect2=finalizers.length===0?_void:runFinalizers(finalizers,exit3);return this.storeInProgressFinalizer(effect2),effect2}popNextFinalizers(){let builder=[];while(this._doneStack.length!==0){let cont=this._doneStack[this._doneStack.length-1];if(cont._tag===OP_CONTINUATION_K)return builder;builder.push(cont),this._doneStack.pop()}return builder}restorePipe(exit3,prev){let currInput=this._input;if(this._input=prev,currInput!==void 0)return currInput.close(exit3);return _void}close(exit3){let runInProgressFinalizers=void 0,finalizer=this._inProgressFinalizer;if(finalizer!==void 0)runInProgressFinalizers=pipe(finalizer,ensuring2(sync3(()=>this.clearInProgressFinalizer())));let closeSelf=void 0,selfFinalizers=this.popAllFinalizers(exit3);if(selfFinalizers!==void 0)closeSelf=pipe(selfFinalizers,ensuring2(sync3(()=>this.clearInProgressFinalizer())));let closeSubexecutors=this._activeSubexecutor===void 0?void 0:this._activeSubexecutor.close(exit3);if(closeSubexecutors===void 0&&runInProgressFinalizers===void 0&&closeSelf===void 0)return;return pipe(exit2(ifNotNull(closeSubexecutors)),zip6(exit2(ifNotNull(runInProgressFinalizers))),zip6(exit2(ifNotNull(closeSelf))),map16(([[exit1,exit22],exit32])=>pipe(exit1,zipRight2(exit22),zipRight2(exit32))),uninterruptible2,flatMap10((exit4)=>suspend3(()=>exit4)))}doneSucceed(value){if(this._doneStack.length===0)return this._done=succeed3(value),this._currentChannel=void 0,Done2();let head5=this._doneStack[this._doneStack.length-1];if(head5._tag===OP_CONTINUATION_K){this._doneStack.pop(),this._currentChannel=head5.onSuccess(value);return}let finalizers=this.popNextFinalizers();if(this._doneStack.length===0)return this._doneStack=finalizers.reverse(),this._done=succeed3(value),this._currentChannel=void 0,Done2();let finalizerEffect=runFinalizers(finalizers.map((f)=>f.finalizer),succeed3(value));this.storeInProgressFinalizer(finalizerEffect);let effect2=pipe(finalizerEffect,ensuring2(sync3(()=>this.clearInProgressFinalizer())),uninterruptible2,flatMap10(()=>sync3(()=>this.doneSucceed(value))));return fromEffect6(effect2)}doneHalt(cause3){if(this._doneStack.length===0)return this._done=failCause3(cause3),this._currentChannel=void 0,Done2();let head5=this._doneStack[this._doneStack.length-1];if(head5._tag===OP_CONTINUATION_K){this._doneStack.pop();try{this._currentChannel=head5.onHalt(cause3)}catch(error){this._currentChannel=failCause10(die4(error))}return}let finalizers=this.popNextFinalizers();if(this._doneStack.length===0)return this._doneStack=finalizers.reverse(),this._done=failCause3(cause3),this._currentChannel=void 0,Done2();let finalizerEffect=runFinalizers(finalizers.map((f)=>f.finalizer),failCause3(cause3));this.storeInProgressFinalizer(finalizerEffect);let effect2=pipe(finalizerEffect,ensuring2(sync3(()=>this.clearInProgressFinalizer())),uninterruptible2,flatMap10(()=>sync3(()=>this.doneHalt(cause3))));return fromEffect6(effect2)}processCancellation(){return this._currentChannel=void 0,this._done=this._cancelled,this._cancelled=void 0,Done2()}runBracketOut(bracketOut){let effect2=uninterruptible2(matchCauseEffect3(this.provide(bracketOut.acquire()),{onFailure:(cause3)=>sync3(()=>{this._currentChannel=failCause10(cause3)}),onSuccess:(out)=>sync3(()=>{this.addFinalizer((exit3)=>this.provide(bracketOut.finalizer(out,exit3))),this._currentChannel=write(out)})}));return fromEffect6(effect2)}provide(effect2){if(this._providedEnv===void 0)return effect2;return pipe(effect2,provide2(this._providedEnv))}runEnsuring(ensuring3){this.addFinalizer(ensuring3.finalizer),this._currentChannel=ensuring3.channel}addFinalizer(f){this._doneStack.push(new ContinuationFinalizerImpl(f))}runSubexecutor(){let subexecutor=this._activeSubexecutor;switch(subexecutor._tag){case OP_PULL_FROM_CHILD:return this.pullFromChild(subexecutor.childExecutor,subexecutor.parentSubexecutor,subexecutor.onEmit,subexecutor);case OP_PULL_FROM_UPSTREAM:return this.pullFromUpstream(subexecutor);case OP_DRAIN_CHILD_EXECUTORS:return this.drainChildExecutors(subexecutor);case OP_EMIT3:return this._emitted=subexecutor.value,this._activeSubexecutor=subexecutor.next,Emit()}}replaceSubexecutor(nextSubExec){this._currentChannel=void 0,this._activeSubexecutor=nextSubExec}finishWithExit(exit3){let state=match6(exit3,{onFailure:(cause3)=>this.doneHalt(cause3),onSuccess:(value)=>this.doneSucceed(value)});return this._activeSubexecutor=void 0,state===void 0?_void:effect(state)}finishSubexecutorWithCloseEffect(subexecutorDone,...closeFuncs){this.addFinalizer(()=>pipe(closeFuncs,forEach8((closeFunc)=>pipe(sync3(()=>closeFunc(subexecutorDone)),flatMap10((closeEffect)=>closeEffect!==void 0?closeEffect:_void)),{discard:!0})));let state=pipe(subexecutorDone,match6({onFailure:(cause3)=>this.doneHalt(cause3),onSuccess:(value)=>this.doneSucceed(value)}));return this._activeSubexecutor=void 0,state}applyUpstreamPullStrategy(upstreamFinished,queue,strategy){switch(strategy._tag){case OP_PULL_AFTER_NEXT:{let shouldPrepend=!upstreamFinished||queue.some((subexecutor)=>subexecutor!==void 0);return[strategy.emitSeparator,shouldPrepend?[void 0,...queue]:queue]}case OP_PULL_AFTER_ALL_ENQUEUED:{let shouldEnqueue=!upstreamFinished||queue.some((subexecutor)=>subexecutor!==void 0);return[strategy.emitSeparator,shouldEnqueue?[...queue,void 0]:queue]}}}pullFromChild(childExecutor,parentSubexecutor,onEmitted,subexecutor){return Read(childExecutor,identity,(emitted)=>{let childExecutorDecision=onEmitted(emitted);switch(childExecutorDecision._tag){case OP_CONTINUE2:break;case OP_CLOSE:{this.finishWithDoneValue(childExecutor,parentSubexecutor,childExecutorDecision.value);break}case OP_YIELD2:{let modifiedParent=parentSubexecutor.enqueuePullFromChild(subexecutor);this.replaceSubexecutor(modifiedParent);break}}this._activeSubexecutor=new Emit2(emitted,this._activeSubexecutor);return},match6({onFailure:(cause3)=>{let state=this.handleSubexecutorFailure(childExecutor,parentSubexecutor,cause3);return state===void 0?void 0:effectOrUndefinedIgnored(state)},onSuccess:(doneValue)=>{this.finishWithDoneValue(childExecutor,parentSubexecutor,doneValue);return}}))}finishWithDoneValue(childExecutor,parentSubexecutor,doneValue){let subexecutor=parentSubexecutor;switch(subexecutor._tag){case OP_PULL_FROM_UPSTREAM:{let modifiedParent=new PullFromUpstream(subexecutor.upstreamExecutor,subexecutor.createChild,subexecutor.lastDone!==void 0?subexecutor.combineChildResults(subexecutor.lastDone,doneValue):doneValue,subexecutor.activeChildExecutors,subexecutor.combineChildResults,subexecutor.combineWithChildResult,subexecutor.onPull,subexecutor.onEmit);this._closeLastSubstream=childExecutor.close(succeed3(doneValue)),this.replaceSubexecutor(modifiedParent);break}case OP_DRAIN_CHILD_EXECUTORS:{let modifiedParent=new DrainChildExecutors(subexecutor.upstreamExecutor,subexecutor.lastDone!==void 0?subexecutor.combineChildResults(subexecutor.lastDone,doneValue):doneValue,subexecutor.activeChildExecutors,subexecutor.upstreamDone,subexecutor.combineChildResults,subexecutor.combineWithChildResult,subexecutor.onPull);this._closeLastSubstream=childExecutor.close(succeed3(doneValue)),this.replaceSubexecutor(modifiedParent);break}default:break}}handleSubexecutorFailure(childExecutor,parentSubexecutor,cause3){return this.finishSubexecutorWithCloseEffect(failCause3(cause3),(exit3)=>parentSubexecutor.close(exit3),(exit3)=>childExecutor.close(exit3))}pullFromUpstream(subexecutor){if(subexecutor.activeChildExecutors.length===0)return this.performPullFromUpstream(subexecutor);let activeChild=subexecutor.activeChildExecutors[0],parentSubexecutor=new PullFromUpstream(subexecutor.upstreamExecutor,subexecutor.createChild,subexecutor.lastDone,subexecutor.activeChildExecutors.slice(1),subexecutor.combineChildResults,subexecutor.combineWithChildResult,subexecutor.onPull,subexecutor.onEmit);if(activeChild===void 0)return this.performPullFromUpstream(parentSubexecutor);this.replaceSubexecutor(new PullFromChild(activeChild.childExecutor,parentSubexecutor,activeChild.onEmit));return}performPullFromUpstream(subexecutor){return Read(subexecutor.upstreamExecutor,(effect2)=>{let closeLastSubstream=this._closeLastSubstream===void 0?_void:this._closeLastSubstream;return this._closeLastSubstream=void 0,pipe(this._executeCloseLastSubstream(closeLastSubstream),zipRight4(effect2))},(emitted)=>{if(this._closeLastSubstream!==void 0){let closeLastSubstream=this._closeLastSubstream;return this._closeLastSubstream=void 0,pipe(this._executeCloseLastSubstream(closeLastSubstream),map16(()=>{let childExecutor2=new ChannelExecutor(subexecutor.createChild(emitted),this._providedEnv,this._executeCloseLastSubstream);childExecutor2._input=this._input;let[emitSeparator2,updatedChildExecutors2]=this.applyUpstreamPullStrategy(!1,subexecutor.activeChildExecutors,subexecutor.onPull(Pulled(emitted)));if(this._activeSubexecutor=new PullFromChild(childExecutor2,new PullFromUpstream(subexecutor.upstreamExecutor,subexecutor.createChild,subexecutor.lastDone,updatedChildExecutors2,subexecutor.combineChildResults,subexecutor.combineWithChildResult,subexecutor.onPull,subexecutor.onEmit),subexecutor.onEmit),isSome2(emitSeparator2))this._activeSubexecutor=new Emit2(emitSeparator2.value,this._activeSubexecutor);return}))}let childExecutor=new ChannelExecutor(subexecutor.createChild(emitted),this._providedEnv,this._executeCloseLastSubstream);childExecutor._input=this._input;let[emitSeparator,updatedChildExecutors]=this.applyUpstreamPullStrategy(!1,subexecutor.activeChildExecutors,subexecutor.onPull(Pulled(emitted)));if(this._activeSubexecutor=new PullFromChild(childExecutor,new PullFromUpstream(subexecutor.upstreamExecutor,subexecutor.createChild,subexecutor.lastDone,updatedChildExecutors,subexecutor.combineChildResults,subexecutor.combineWithChildResult,subexecutor.onPull,subexecutor.onEmit),subexecutor.onEmit),isSome2(emitSeparator))this._activeSubexecutor=new Emit2(emitSeparator.value,this._activeSubexecutor);return},(exit3)=>{if(subexecutor.activeChildExecutors.some((subexecutor2)=>subexecutor2!==void 0)){let drain=new DrainChildExecutors(subexecutor.upstreamExecutor,subexecutor.lastDone,[void 0,...subexecutor.activeChildExecutors],subexecutor.upstreamExecutor.getDone(),subexecutor.combineChildResults,subexecutor.combineWithChildResult,subexecutor.onPull);if(this._closeLastSubstream!==void 0){let closeLastSubstream2=this._closeLastSubstream;return this._closeLastSubstream=void 0,pipe(this._executeCloseLastSubstream(closeLastSubstream2),map16(()=>this.replaceSubexecutor(drain)))}this.replaceSubexecutor(drain);return}let closeLastSubstream=this._closeLastSubstream,state=this.finishSubexecutorWithCloseEffect(pipe(exit3,map11((a)=>subexecutor.combineWithChildResult(subexecutor.lastDone,a))),()=>closeLastSubstream,(exit4)=>subexecutor.upstreamExecutor.close(exit4));return state===void 0?void 0:effectOrUndefinedIgnored(state)})}drainChildExecutors(subexecutor){if(subexecutor.activeChildExecutors.length===0){let lastClose=this._closeLastSubstream;if(lastClose!==void 0)this.addFinalizer(()=>succeed9(lastClose));return this.finishSubexecutorWithCloseEffect(subexecutor.upstreamDone,()=>lastClose,(exit3)=>subexecutor.upstreamExecutor.close(exit3))}let activeChild=subexecutor.activeChildExecutors[0],rest=subexecutor.activeChildExecutors.slice(1);if(activeChild===void 0){let[emitSeparator,remainingExecutors]=this.applyUpstreamPullStrategy(!0,rest,subexecutor.onPull(NoUpstream(rest.reduce((n,curr)=>curr!==void 0?n+1:n,0))));if(this.replaceSubexecutor(new DrainChildExecutors(subexecutor.upstreamExecutor,subexecutor.lastDone,remainingExecutors,subexecutor.upstreamDone,subexecutor.combineChildResults,subexecutor.combineWithChildResult,subexecutor.onPull)),isSome2(emitSeparator))return this._emitted=emitSeparator.value,Emit();return}let parentSubexecutor=new DrainChildExecutors(subexecutor.upstreamExecutor,subexecutor.lastDone,rest,subexecutor.upstreamDone,subexecutor.combineChildResults,subexecutor.combineWithChildResult,subexecutor.onPull);this.replaceSubexecutor(new PullFromChild(activeChild.childExecutor,parentSubexecutor,activeChild.onEmit));return}}var ifNotNull=(effect2)=>effect2!==void 0?effect2:_void,runFinalizers=(finalizers,exit3)=>{return pipe(forEach8(finalizers,(fin)=>exit2(fin(exit3))),map16((exits)=>pipe(all2(exits),getOrElse(()=>void_2))),flatMap10((exit4)=>suspend3(()=>exit4)))},readUpstream=(r,onSuccess,onFailure)=>{let readStack=[r],read=()=>{let current=readStack.pop();if(current===void 0||current.upstream===void 0)return dieMessage2("Unexpected end of input for channel execution");let state=current.upstream.run();switch(state._tag){case OP_EMIT2:{let emitEffect=current.onEmit(current.upstream.getEmit());if(readStack.length===0){if(emitEffect===void 0)return suspend3(onSuccess);return pipe(emitEffect,matchCauseEffect3({onFailure,onSuccess}))}if(emitEffect===void 0)return suspend3(()=>read());return pipe(emitEffect,matchCauseEffect3({onFailure,onSuccess:()=>read()}))}case OP_DONE3:{let doneEffect=current.onDone(current.upstream.getDone());if(readStack.length===0){if(doneEffect===void 0)return suspend3(onSuccess);return pipe(doneEffect,matchCauseEffect3({onFailure,onSuccess}))}if(doneEffect===void 0)return suspend3(()=>read());return pipe(doneEffect,matchCauseEffect3({onFailure,onSuccess:()=>read()}))}case OP_FROM_EFFECT3:return readStack.push(current),pipe(current.onEffect(state.effect),catchAllCause2((cause3)=>suspend3(()=>{let doneEffect=current.onDone(failCause3(cause3));return doneEffect===void 0?_void:doneEffect})),matchCauseEffect3({onFailure,onSuccess:()=>read()}));case OP_READ2:return readStack.push(current),readStack.push(state),suspend3(()=>read())}};return read()},runIn=dual(2,(self,scope4)=>{let run=(channelDeferred,scopeDeferred,scope5)=>acquireUseRelease2(sync3(()=>new ChannelExecutor(self,void 0,identity)),(exec)=>suspend3(()=>runScopedInterpret(exec.run(),exec).pipe(intoDeferred2(channelDeferred),zipRight4(_await(channelDeferred)),zipLeft3(_await(scopeDeferred)))),(exec,exit3)=>{let finalize=exec.close(exit3);if(finalize===void 0)return _void;return tapErrorCause2(finalize,(cause3)=>addFinalizer2(scope5,failCause8(cause3)))});return uninterruptibleMask3((restore)=>all7([fork2(scope4,sequential3),make19(),make19()]).pipe(flatMap10(([child,channelDeferred,scopeDeferred])=>restore(run(channelDeferred,scopeDeferred,child)).pipe(forkIn2(scope4),flatMap10((fiber)=>scope4.addFinalizer((exit3)=>{let interruptors3=isFailure(exit3)?interruptors2(exit3.cause):void 0;return isDone(channelDeferred).pipe(flatMap10((isDone6)=>isDone6?succeed2(scopeDeferred,void 0).pipe(zipRight4(_await3(fiber)),zipRight4(inheritAll2(fiber))):succeed2(scopeDeferred,void 0).pipe(zipRight4(interruptors3&&size3(interruptors3)>0?interruptAs(fiber,combineAll3(interruptors3)):interrupt6(fiber)),zipRight4(inheritAll2(fiber)))))}).pipe(zipRight4(restore(_await(channelDeferred)))))))))}),runScopedInterpret=(channelState,exec)=>{let op=channelState;switch(op._tag){case OP_FROM_EFFECT3:return pipe(op.effect,flatMap10(()=>runScopedInterpret(exec.run(),exec)));case OP_EMIT2:return runScopedInterpret(exec.run(),exec);case OP_DONE3:return suspend3(()=>exec.getDone());case OP_READ2:return readUpstream(op,()=>runScopedInterpret(exec.run(),exec),failCause8)}};var OP_DONE4="Done",OP_AWAIT="Await";var MergeDecisionSymbolKey="effect/ChannelMergeDecision",MergeDecisionTypeId=Symbol.for(MergeDecisionSymbolKey),proto9={[MergeDecisionTypeId]:{_R:(_)=>_,_E0:(_)=>_,_Z0:(_)=>_,_E:(_)=>_,_Z:(_)=>_}},Done3=(effect2)=>{let op=Object.create(proto9);return op._tag=OP_DONE4,op.effect=effect2,op},Await=(f)=>{let op=Object.create(proto9);return op._tag=OP_AWAIT,op.f=f,op};var OP_BOTH_RUNNING="BothRunning",OP_LEFT_DONE="LeftDone",OP_RIGHT_DONE="RightDone";var MergeStateSymbolKey="effect/ChannelMergeState",MergeStateTypeId=Symbol.for(MergeStateSymbolKey),proto10={[MergeStateTypeId]:MergeStateTypeId},BothRunning=(left3,right3)=>{let op=Object.create(proto10);return op._tag=OP_BOTH_RUNNING,op.left=left3,op.right=right3,op},LeftDone=(f)=>{let op=Object.create(proto10);return op._tag=OP_LEFT_DONE,op.f=f,op},RightDone=(f)=>{let op=Object.create(proto10);return op._tag=OP_RIGHT_DONE,op.f=f,op};var OP_BACK_PRESSURE="BackPressure",OP_BUFFER_SLIDING="BufferSliding";var MergeStrategySymbolKey="effect/ChannelMergeStrategy",MergeStrategyTypeId=Symbol.for(MergeStrategySymbolKey),proto11={[MergeStrategyTypeId]:MergeStrategyTypeId},BackPressure=(_)=>{let op=Object.create(proto11);return op._tag=OP_BACK_PRESSURE,op},BufferSliding=(_)=>{let op=Object.create(proto11);return op._tag=OP_BUFFER_SLIDING,op};var match15=dual(2,(self,{onBackPressure,onBufferSliding})=>{switch(self._tag){case OP_BACK_PRESSURE:return onBackPressure();case OP_BUFFER_SLIDING:return onBufferSliding()}});var OP_STATE_EMPTY="Empty",OP_STATE_EMIT="Emit",OP_STATE_ERROR="Error",OP_STATE_DONE2="Done",stateEmpty=(notifyProducer)=>({_tag:OP_STATE_EMPTY,notifyProducer}),stateEmit=(notifyConsumers)=>({_tag:OP_STATE_EMIT,notifyConsumers}),stateError=(cause3)=>({_tag:OP_STATE_ERROR,cause:cause3}),stateDone=(done9)=>({_tag:OP_STATE_DONE2,done:done9});class SingleProducerAsyncInputImpl{ref;constructor(ref){this.ref=ref}awaitRead(){return flatten8(modify3(this.ref,(state)=>state._tag===OP_STATE_EMPTY?[_await(state.notifyProducer),state]:[_void,state]))}get close(){return fiberIdWith2((fiberId3)=>this.error(interrupt5(fiberId3)))}done(value){return flatten8(modify3(this.ref,(state)=>{switch(state._tag){case OP_STATE_EMPTY:return[_await(state.notifyProducer),state];case OP_STATE_EMIT:return[forEach8(state.notifyConsumers,(deferred)=>succeed2(deferred,left2(value)),{discard:!0}),stateDone(value)];case OP_STATE_ERROR:return[interrupt7,state];case OP_STATE_DONE2:return[interrupt7,state]}}))}emit(element){return flatMap10(make19(),(deferred)=>flatten8(modify3(this.ref,(state)=>{switch(state._tag){case OP_STATE_EMPTY:return[_await(state.notifyProducer),state];case OP_STATE_EMIT:{let notifyConsumer=state.notifyConsumers[0],notifyConsumers=state.notifyConsumers.slice(1);if(notifyConsumer!==void 0)return[succeed2(notifyConsumer,right2(element)),notifyConsumers.length===0?stateEmpty(deferred):stateEmit(notifyConsumers)];throw new Error("Bug: Channel.SingleProducerAsyncInput.emit - Queue was empty! please report an issue at https://github.com/Effect-TS/effect/issues")}case OP_STATE_ERROR:return[interrupt7,state];case OP_STATE_DONE2:return[interrupt7,state]}})))}error(cause3){return flatten8(modify3(this.ref,(state)=>{switch(state._tag){case OP_STATE_EMPTY:return[_await(state.notifyProducer),state];case OP_STATE_EMIT:return[forEach8(state.notifyConsumers,(deferred)=>failCause2(deferred,cause3),{discard:!0}),stateError(cause3)];case OP_STATE_ERROR:return[interrupt7,state];case OP_STATE_DONE2:return[interrupt7,state]}}))}get take(){return this.takeWith((cause3)=>failCause3(map13(cause3,left2)),(elem)=>succeed3(elem),(done9)=>fail4(right2(done9)))}takeWith(onError3,onElement,onDone){return flatMap10(make19(),(deferred)=>flatten8(modify3(this.ref,(state)=>{switch(state._tag){case OP_STATE_EMPTY:return[zipRight4(succeed2(state.notifyProducer,void 0),matchCause2(_await(deferred),{onFailure:onError3,onSuccess:match({onLeft:onDone,onRight:onElement})})),stateEmit([deferred])];case OP_STATE_EMIT:return[matchCause2(_await(deferred),{onFailure:onError3,onSuccess:match({onLeft:onDone,onRight:onElement})}),stateEmit([...state.notifyConsumers,deferred])];case OP_STATE_ERROR:return[succeed9(onError3(state.cause)),state];case OP_STATE_DONE2:return[succeed9(onDone(state.done)),state]}})))}}var make45=()=>pipe(make19(),flatMap10((deferred)=>make29(stateEmpty(deferred))),map16((ref)=>new SingleProducerAsyncInputImpl(ref)));var acquireUseRelease3=(acquire,use,release)=>flatMap12(fromEffect5(make29(()=>_void)),(ref)=>pipe(fromEffect5(uninterruptible2(tap2(acquire,(a)=>set6(ref,(exit3)=>release(a,exit3))))),flatMap12(use),ensuringWith((exit3)=>flatMap10(get12(ref),(f)=>f(exit3))))),as4=dual(2,(self,value)=>map18(self,()=>value));var catchAll4=dual(2,(self,f)=>catchAllCause4(self,(cause3)=>match(failureOrCause2(cause3),{onLeft:f,onRight:failCause10}))),concatMap=dual(2,(self,f)=>concatMapWith(self,f,()=>{return},()=>{return}));var drain=(self)=>{let drainer=readWithCause({onInput:()=>drainer,onFailure:failCause10,onDone:succeed10});return pipeTo(self,drainer)};var ensuring3=dual(2,(self,finalizer)=>ensuringWith(self,()=>finalizer));var flatten10=(self)=>flatMap12(self,identity),foldChannel=dual(2,(self,options)=>foldCauseChannel(self,{onFailure:(cause3)=>{let either4=failureOrCause2(cause3);switch(either4._tag){case"Left":return options.onFailure(either4.left);case"Right":return failCause10(either4.right)}},onSuccess:options.onSuccess}));var fromInput=(input)=>unwrap(input.takeWith(failCause10,(elem)=>flatMap12(write(elem),()=>fromInput(input)),succeed10));var fromQueue=(queue)=>suspend4(()=>fromQueueInternal(queue)),fromQueueInternal=(queue)=>pipe(fromEffect5(take3(queue)),flatMap12(match({onLeft:match6({onFailure:failCause10,onSuccess:succeedNow}),onRight:(elem)=>flatMap12(write(elem),()=>fromQueueInternal(queue))}))),identityChannel=()=>readWith({onInput:(input)=>flatMap12(write(input),()=>identityChannel()),onFailure:fail11,onDone:succeedNow}),interruptWhen=dual(2,(self,effect2)=>mergeWith2(self,{other:fromEffect5(effect2),onSelfDone:(selfDone)=>Done3(suspend3(()=>selfDone)),onOtherDone:(effectDone)=>Done3(suspend3(()=>effectDone))})),interruptWhenDeferred=dual(2,(self,deferred)=>interruptWhen(self,_await(deferred))),map18=dual(2,(self,f)=>flatMap12(self,(a)=>sync4(()=>f(a))));var mapError4=dual(2,(self,f)=>mapErrorCause3(self,map13(f))),mapErrorCause3=dual(2,(self,f)=>catchAllCause4(self,(cause3)=>failCause10(f(cause3)))),mapOut=dual(2,(self,f)=>{let reader=readWith({onInput:(outElem)=>flatMap12(write(f(outElem)),()=>reader),onFailure:fail11,onDone:succeedNow});return pipeTo(self,reader)}),mapOutEffect=dual(2,(self,f)=>{let reader=readWithCause({onInput:(outElem)=>pipe(fromEffect5(f(outElem)),flatMap12(write),flatMap12(()=>reader)),onFailure:failCause10,onDone:succeedNow});return pipeTo(self,reader)}),mapOutEffectPar=dual(3,(self,f,n)=>unwrapScopedWith((scope4)=>gen2(function*(){let input=yield*make45(),queueReader=fromInput(input),queue=yield*bounded5(n);yield*addFinalizer2(scope4,shutdown4(queue));let errorSignal=yield*make19(),withPermits=n===Number.POSITIVE_INFINITY?(_)=>identity:(yield*makeSemaphore2(n)).withPermits;yield*(yield*queueReader.pipe(pipeTo(self),toPullIn(scope4))).pipe(matchCauseEffect3({onFailure:(cause3)=>offer3(queue,failCause8(cause3)),onSuccess:match({onLeft:(outDone)=>zipRight4(interruptible4(withPermits(n)(_void)),asVoid2(offer3(queue,succeed9(left2(outDone))))),onRight:(outElem)=>gen2(function*(){let deferred=yield*make19(),latch=yield*make19();yield*offer3(queue,map16(_await(deferred),right2)),yield*succeed2(latch,void 0).pipe(zipRight4(uninterruptibleMask3((restore)=>exit2(restore(_await(errorSignal))).pipe(raceFirst2(exit2(restore(f(outElem)))),flatMap10(identity))).pipe(tapErrorCause2((cause3)=>failCause2(errorSignal,cause3)),intoDeferred2(deferred))),withPermits(1),forkIn2(scope4)),yield*_await(latch)})})}),forever3,interruptible4,forkIn2(scope4));let consumer=unwrap(matchCause2(flatten8(take3(queue)),{onFailure:failCause10,onSuccess:match({onLeft:succeedNow,onRight:(outElem)=>flatMap12(write(outElem),()=>consumer)})}));return embedInput(consumer,input)}))),mergeAll5=(options)=>{return(channels)=>mergeAllWith(options)(channels,constVoid)};var mergeAllWith=({bufferSize=16,concurrency,mergeStrategy=BackPressure()})=>(channels,f)=>unwrapScopedWith((scope4)=>gen2(function*(){let concurrencyN=concurrency==="unbounded"?Number.MAX_SAFE_INTEGER:concurrency,input=yield*make45(),queueReader=fromInput(input),queue=yield*bounded5(bufferSize);yield*addFinalizer2(scope4,shutdown4(queue));let cancelers=yield*unbounded5();yield*addFinalizer2(scope4,shutdown4(cancelers));let lastDone=yield*make29(none2()),errorSignal=yield*make19(),withPermits=(yield*makeSemaphore2(concurrencyN)).withPermits,pull=yield*toPullIn(pipeTo(queueReader,channels),scope4);function evaluatePull(pull2){return pull2.pipe(flatMap10(match({onLeft:(done9)=>succeed9(some2(done9)),onRight:(outElem)=>as3(offer3(queue,succeed9(right2(outElem))),none2())})),repeat({until:(_)=>isSome2(_)}),flatMap10((outDone)=>update3(lastDone,match2({onNone:()=>some2(outDone.value),onSome:(lastDone2)=>some2(f(lastDone2,outDone.value))}))),catchAllCause2((cause3)=>isInterrupted2(cause3)?failCause8(cause3):offer3(queue,failCause8(cause3)).pipe(zipRight4(succeed2(errorSignal,void 0)),asVoid2)))}yield*pull.pipe(matchCauseEffect3({onFailure:(cause3)=>offer3(queue,failCause8(cause3)).pipe(zipRight4(succeed9(!1))),onSuccess:match({onLeft:(outDone)=>raceWith2(interruptible4(_await(errorSignal)),interruptible4(withPermits(concurrencyN)(_void)),{onSelfDone:(_,permitAcquisition)=>as3(interrupt6(permitAcquisition),!1),onOtherDone:(_,failureAwait)=>zipRight4(interrupt6(failureAwait),get12(lastDone).pipe(flatMap10(match2({onNone:()=>offer3(queue,succeed9(left2(outDone))),onSome:(lastDone2)=>offer3(queue,succeed9(left2(f(lastDone2,outDone))))})),as3(!1)))}),onRight:(channel)=>match15(mergeStrategy,{onBackPressure:()=>gen2(function*(){let latch=yield*make19(),raceEffects=scopedWith2((scope5)=>toPullIn(pipeTo(queueReader,channel),scope5).pipe(flatMap10((pull2)=>race2(exit2(evaluatePull(pull2)),exit2(interruptible4(_await(errorSignal))))),flatMap10(identity)));return yield*succeed2(latch,void 0).pipe(zipRight4(raceEffects),withPermits(1),forkIn2(scope4)),yield*_await(latch),!(yield*isDone(errorSignal))}),onBufferSliding:()=>gen2(function*(){let canceler=yield*make19(),latch=yield*make19(),size14=yield*size13(cancelers);yield*take3(cancelers).pipe(flatMap10((canceler2)=>succeed2(canceler2,void 0)),when2(()=>size14>=concurrencyN)),yield*offer3(cancelers,canceler);let raceEffects=scopedWith2((scope5)=>toPullIn(pipeTo(queueReader,channel),scope5).pipe(flatMap10((pull2)=>exit2(evaluatePull(pull2)).pipe(race2(exit2(interruptible4(_await(errorSignal)))),race2(exit2(interruptible4(_await(canceler)))))),flatMap10(identity)));return yield*succeed2(latch,void 0).pipe(zipRight4(raceEffects),withPermits(1),forkIn2(scope4)),yield*_await(latch),!(yield*isDone(errorSignal))})})})}),repeat({while:(_)=>_}),forkIn2(scope4));let consumer=pipe(take3(queue),flatten8,matchCause2({onFailure:failCause10,onSuccess:match({onLeft:succeedNow,onRight:(outElem)=>flatMap12(write(outElem),()=>consumer)})}),unwrap);return embedInput(consumer,input)})),mergeMap=dual(3,(self,f,options)=>mergeAll5(options)(mapOut(self,f)));var mergeWith2=dual(2,(self,options)=>{function merge9(scope4){return gen2(function*(){let input=yield*make45(),queueReader=fromInput(input),pullL=yield*toPullIn(pipeTo(queueReader,self),scope4),pullR=yield*toPullIn(pipeTo(queueReader,options.other),scope4);function handleSide(exit3,fiber,pull){return(done9,both2,single2)=>{function onDecision(decision){let op=decision;if(op._tag===OP_DONE4)return succeed9(fromEffect5(zipRight4(interrupt6(fiber),op.effect)));return map16(_await3(fiber),match6({onFailure:(cause3)=>fromEffect5(op.f(failCause3(cause3))),onSuccess:match({onLeft:(done10)=>fromEffect5(op.f(succeed3(done10))),onRight:(elem)=>zipRight5(write(elem),go(single2(op.f)))})}))}return match6(exit3,{onFailure:(cause3)=>onDecision(done9(failCause3(cause3))),onSuccess:match({onLeft:(z)=>onDecision(done9(succeed3(z))),onRight:(elem)=>succeed9(flatMap12(write(elem),()=>flatMap12(fromEffect5(forkIn2(interruptible4(pull),scope4)),(leftFiber)=>go(both2(leftFiber,fiber)))))})})}}function go(state){switch(state._tag){case OP_BOTH_RUNNING:{let leftJoin=interruptible4(join3(state.left)),rightJoin=interruptible4(join3(state.right));return unwrap(raceWith2(leftJoin,rightJoin,{onSelfDone:(leftExit,rf)=>zipRight4(interrupt6(rf),handleSide(leftExit,state.right,pullL)(options.onSelfDone,BothRunning,(f)=>LeftDone(f))),onOtherDone:(rightExit,lf)=>zipRight4(interrupt6(lf),handleSide(rightExit,state.left,pullR)(options.onOtherDone,(left3,right3)=>BothRunning(right3,left3),(f)=>RightDone(f)))}))}case OP_LEFT_DONE:return unwrap(map16(exit2(pullR),match6({onFailure:(cause3)=>fromEffect5(state.f(failCause3(cause3))),onSuccess:match({onLeft:(done9)=>fromEffect5(state.f(succeed3(done9))),onRight:(elem)=>flatMap12(write(elem),()=>go(LeftDone(state.f)))})})));case OP_RIGHT_DONE:return unwrap(map16(exit2(pullL),match6({onFailure:(cause3)=>fromEffect5(state.f(failCause3(cause3))),onSuccess:match({onLeft:(done9)=>fromEffect5(state.f(succeed3(done9))),onRight:(elem)=>flatMap12(write(elem),()=>go(RightDone(state.f)))})})))}}return fromEffect5(withFiberRuntime2((parent)=>{let inherit=withFiberRuntime2((state)=>{return state.transferChildren(parent.scope()),_void}),leftFiber=interruptible4(pullL).pipe(ensuring2(inherit),forkIn2(scope4)),rightFiber=interruptible4(pullR).pipe(ensuring2(inherit),forkIn2(scope4));return zipWith8(leftFiber,rightFiber,(left3,right3)=>BothRunning(left3,right3))})).pipe(flatMap12(go),embedInput(input))})}return unwrapScopedWith(merge9)});var orDieWith3=dual(2,(self,f)=>catchAll4(self,(e)=>failCauseSync4(()=>die4(f(e))))),orElse7=dual(2,(self,that)=>catchAll4(self,that)),pipeToOrFail=dual(2,(self,that)=>suspend4(()=>{let channelException=void 0,reader=readWith({onInput:(outElem)=>flatMap12(write(outElem),()=>reader),onFailure:(outErr)=>{return channelException=ChannelException(outErr),failCause10(die4(channelException))},onDone:succeedNow}),writer=readWithCause({onInput:(outElem)=>pipe(write(outElem),flatMap12(()=>writer)),onFailure:(cause3)=>isDieType2(cause3)&&isChannelException(cause3.defect)&&equals(cause3.defect,channelException)?fail11(cause3.defect.error):failCause10(cause3),onDone:succeedNow});return pipeTo(pipeTo(pipeTo(self,reader),that),writer)}));var repeated=(self)=>flatMap12(self,()=>repeated(self)),run=(self)=>scopedWith2((scope4)=>runIn(self,scope4));var runDrain=(self)=>run(drain(self)),runScoped=(self)=>scopeWith2((scope4)=>runIn(self,scope4)),scoped4=(effect2)=>unwrap(uninterruptibleMask3((restore)=>map16(make41(),(scope4)=>acquireReleaseOut(tapErrorCause2(restore(extend2(effect2,scope4)),(cause3)=>close(scope4,failCause3(cause3))),(_,exit3)=>close(scope4,exit3))))),scopedWith3=(f)=>unwrapScoped2(map16(scope2,(scope4)=>flatMap12(fromEffect5(f(scope4)),write)));var splitLines=()=>suspend4(()=>{let stringBuilder="",midCRLF=!1,splitLinesChunk=(chunk2)=>{let chunkBuilder=[];return map4(chunk2,(str)=>{if(str.length!==0){let from=0,indexOfCR=str.indexOf("\r"),indexOfLF=str.indexOf(`
|
|
35
35
|
`);if(midCRLF){if(indexOfLF===0)chunkBuilder.push(stringBuilder),stringBuilder="",from=1,indexOfLF=str.indexOf(`
|
|
36
36
|
`,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(`
|
|
37
37
|
`,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(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@6qat/tcp-connection",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.4",
|
|
4
4
|
"description": "TCP connection library with Effect.js integration",
|
|
5
5
|
"module": "dist/index.js",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -19,13 +19,14 @@
|
|
|
19
19
|
"keywords": ["tcp", "connection", "effect", "bun"],
|
|
20
20
|
"author": "Your Name",
|
|
21
21
|
"license": "MIT",
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"effect": "^3.14.21"
|
|
24
|
+
},
|
|
22
25
|
"devDependencies": {
|
|
23
26
|
"@types/bun": "^1.2.11",
|
|
24
27
|
"typescript": "^5.8.3"
|
|
25
28
|
},
|
|
26
|
-
"peerDependencies": {
|
|
27
|
-
"effect": "^3.14.21"
|
|
28
|
-
},
|
|
29
|
+
"peerDependencies": {},
|
|
29
30
|
"publishConfig": {
|
|
30
31
|
"access": "public"
|
|
31
32
|
}
|