@ceschiatti/redistail 0.0.3 → 0.0.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.
@@ -1,10 +1,10 @@
1
- import{createRequire}from"node:module";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 __require=createRequire(import.meta.url);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 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))));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)=>({...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)=>({...a,[name]:b}))));var globalStore,globalValue=(id,compute)=>{if(!globalStore)globalThis["effect/GlobalValue"]??=new Map,globalStore=globalThis["effect/GlobalValue"];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;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;var isDate=(input)=>input instanceof Date,isIterable=(input)=>typeof input==="string"||hasProperty(input,Symbol.iterator);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 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(()=>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 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)},CIRCULAR="[Circular]";function formatDate(date){try{return date.toISOString()}catch{return"Invalid Date"}}function safeToString(input){try{let s=input.toString();return typeof s==="string"?s:String(s)}catch{return"[toString threw]"}}function formatPropertyKey(name){return isString(name)?JSON.stringify(name):String(name)}function formatUnknown(input,options){let space=options?.space??0,seen=new WeakSet,gap=!space?"":isNumber(space)?" ".repeat(space):space,ind=(d)=>gap.repeat(d),wrap=(v,body)=>{let ctor=v?.constructor;return ctor&&ctor!==Object.prototype.constructor&&ctor.name?`${ctor.name}(${body})`:body},ownKeys=(o)=>{try{return Reflect.ownKeys(o)}catch{return["[ownKeys threw]"]}};function go(v,d=0){if(Array.isArray(v)){if(seen.has(v))return CIRCULAR;if(seen.add(v),!gap||v.length<=1)return`[${v.map((x)=>go(x,d)).join(",")}]`;let inner=v.map((x)=>go(x,d+1)).join(`,
1
+ import{createRequire}from"node:module";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 __require=createRequire(import.meta.url);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 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))));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)=>({...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)=>({...a,[name]:b}))));var globalStore,globalValue=(id,compute)=>{if(!globalStore)globalThis["effect/GlobalValue"]??=new Map,globalStore=globalThis["effect/GlobalValue"];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;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;var isDate=(input)=>input instanceof Date,isIterable=(input)=>typeof input==="string"||hasProperty(input,Symbol.iterator);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 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(()=>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){if(Number.isNaN(self.getTime()))return string("Invalid 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 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){let t1=self.getTime(),t2=that.getTime();return t1===t2||Number.isNaN(t1)&&Number.isNaN(t2)}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)},CIRCULAR="[Circular]";function formatDate(date){try{return date.toISOString()}catch{return"Invalid Date"}}function safeToString(input){try{let s=input.toString();return typeof s==="string"?s:String(s)}catch{return"[toString threw]"}}function formatPropertyKey(name){return isString(name)?JSON.stringify(name):String(name)}function formatUnknown(input,options){let space=options?.space??0,seen=new WeakSet,gap=!space?"":isNumber(space)?" ".repeat(space):space,ind=(d)=>gap.repeat(d),wrap=(v,body)=>{let ctor=v?.constructor;return ctor&&ctor!==Object.prototype.constructor&&ctor.name?`${ctor.name}(${body})`:body},ownKeys=(o)=>{try{return Reflect.ownKeys(o)}catch{return["[ownKeys threw]"]}};function go(v,d=0){if(Array.isArray(v)){if(seen.has(v))return CIRCULAR;if(seen.add(v),!gap||v.length<=1)return`[${v.map((x)=>go(x,d)).join(",")}]`;let inner=v.map((x)=>go(x,d+1)).join(`,
2
2
  `+ind(d+1));return`[
3
3
  ${ind(d+1)}${inner}
4
4
  ${ind(d)}]`}if(isDate(v))return formatDate(v);if(!options?.ignoreToString&&hasProperty(v,"toString")&&isFunction2(v.toString)&&v.toString!==Object.prototype.toString&&v.toString!==Array.prototype.toString){let s=safeToString(v);if(v instanceof Error&&v.cause)return`${s} (cause: ${go(v.cause,d)})`;return s}if(isString(v))return JSON.stringify(v);if(isNumber(v)||v==null||isBoolean(v)||isSymbol(v))return String(v);if(isBigInt(v))return String(v)+"n";if(v instanceof Set||v instanceof Map){if(seen.has(v))return CIRCULAR;return seen.add(v),`${v.constructor.name}(${go(Array.from(v),d)})`}if(isObject(v)){if(seen.has(v))return CIRCULAR;seen.add(v);let keys=ownKeys(v);if(!gap||keys.length<=1){let body2=`{${keys.map((k)=>`${formatPropertyKey(k)}:${go(v[k],d)}`).join(",")}}`;return wrap(v,body2)}let body=`{
5
5
  ${keys.map((k)=>`${ind(d+1)}${formatPropertyKey(k)}: ${go(v[k],d+1)}`).join(`,
6
6
  `)}
7
- ${ind(d)}}`;return wrap(v,body)}return String(v)}return go(input,0)}var 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 moduleVersion="3.19.9",getCurrentVersion=()=>moduleVersion;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 fromOption=dual(2,(self,onNone)=>isNone(self)?left(onNone()):right(self.value));var right2=right;var left2=left;var fromOption2=fromOption,try_=(evaluate)=>{if(isFunction2(evaluate))try{return right2(evaluate())}catch(e){return left2(e)}else try{return right2(evaluate.try())}catch(e){return left2(evaluate.catch(e))}};var 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)),liftPredicate=dual(3,(a,predicate,orLeftWith)=>predicate(a)?right2(a):left2(orLeftWith(a)));var merge=match({onLeft:identity,onRight:identity});var all=(input)=>{if(Symbol.iterator in input){let out2=[];for(let e of input){if(isLeft2(e))return e;out2.push(e.right)}return right2(out2)}let out={};for(let key of Object.keys(input)){let e=input[key];if(isLeft2(e))return e;out[key]=e.right}return right2(out)};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 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{return none2()}},getOrThrowWith=dual(2,(self,onNone)=>{if(isSome2(self))return self.value;throw onNone()}),getOrThrow=getOrThrowWith(()=>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 containsWith=(isEquivalent)=>dual(2,(self,a)=>isNone2(self)?!1:isEquivalent(self.value,a)),_equivalence=equivalence(),contains=containsWith(_equivalence);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 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}}};var allocate=(n)=>Array(n),makeBy=dual(2,(n,f)=>{let max2=Math.max(1,Math.floor(n)),out=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 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 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 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 empty=()=>[],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 TypeId3=Symbol.for("effect/Chunk");function copy2(src,srcPos,dest,destPos,len){for(let i=srcPos;i<Math.min(src.length,srcPos+len);i++)dest[destPos+i-srcPos]=src[i];return dest}var emptyArray=[],getEquivalence2=(isEquivalent)=>make((self,that)=>self.length===that.length&&toReadonlyArray(self).every((value,i)=>isEquivalent(value,unsafeGet2(that,i)))),_equivalence3=getEquivalence2(equals),ChunkProto={[TypeId3]:{_A:(_)=>_},toString(){return format(this.toJSON())},toJSON(){return{_id:"Chunk",values:toReadonlyArray(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},[symbol2](that){return isChunk(that)&&_equivalence3(this,that)},[symbol](){return cached(this,array2(toReadonlyArray(this)))},[Symbol.iterator](){switch(this.backing._tag){case"IArray":return this.backing.array[Symbol.iterator]();case"IEmpty":return emptyArray[Symbol.iterator]();default:return toReadonlyArray(this)[Symbol.iterator]()}},pipe(){return pipeArguments(this,arguments)}},makeChunk=(backing)=>{let chunk=Object.create(ChunkProto);switch(chunk.backing=backing,backing._tag){case"IEmpty":{chunk.length=0,chunk.depth=0,chunk.left=chunk,chunk.right=chunk;break}case"IConcat":{chunk.length=backing.left.length+backing.right.length,chunk.depth=1+Math.max(backing.left.depth,backing.right.depth),chunk.left=backing.left,chunk.right=backing.right;break}case"IArray":{chunk.length=backing.array.length,chunk.depth=0,chunk.left=_empty,chunk.right=_empty;break}case"ISingleton":{chunk.length=1,chunk.depth=0,chunk.left=_empty,chunk.right=_empty;break}case"ISlice":{chunk.length=backing.length,chunk.depth=backing.chunk.depth+1,chunk.left=_empty,chunk.right=_empty;break}}return chunk},isChunk=(u)=>hasProperty(u,TypeId3),_empty=makeChunk({_tag:"IEmpty"}),empty2=()=>_empty,make4=(...as)=>unsafeFromNonEmptyArray(as),of2=(a)=>makeChunk({_tag:"ISingleton",a}),fromIterable2=(self)=>isChunk(self)?self:unsafeFromArray(fromIterable(self)),copyToArray=(self,array3,initial)=>{switch(self.backing._tag){case"IArray":{copy2(self.backing.array,0,array3,initial,self.length);break}case"IConcat":{copyToArray(self.left,array3,initial),copyToArray(self.right,array3,initial+self.left.length);break}case"ISingleton":{array3[initial]=self.backing.a;break}case"ISlice":{let i=0,j=initial;while(i<self.length)array3[j]=unsafeGet2(self,i),i+=1,j+=1;break}}},toArray_=(self)=>toReadonlyArray(self).slice(),toArray2=toArray_,toReadonlyArray_=(self)=>{switch(self.backing._tag){case"IEmpty":return emptyArray;case"IArray":return self.backing.array;default:{let arr=Array(self.length);return copyToArray(self,arr,0),self.backing={_tag:"IArray",array:arr},self.left=_empty,self.right=_empty,self.depth=0,arr}}},toReadonlyArray=toReadonlyArray_,reverseChunk=(self)=>{switch(self.backing._tag){case"IEmpty":case"ISingleton":return self;case"IArray":return makeChunk({_tag:"IArray",array:reverse(self.backing.array)});case"IConcat":return makeChunk({_tag:"IConcat",left:reverse2(self.backing.right),right:reverse2(self.backing.left)});case"ISlice":return unsafeFromArray(reverse(toReadonlyArray(self)))}},reverse2=reverseChunk,get2=dual(2,(self,index)=>index<0||index>=self.length?none2():some2(unsafeGet2(self,index))),unsafeFromArray=(self)=>self.length===0?empty2():self.length===1?of2(self[0]):makeChunk({_tag:"IArray",array:self}),unsafeFromNonEmptyArray=(self)=>unsafeFromArray(self),unsafeGet2=dual(2,(self,index)=>{switch(self.backing._tag){case"IEmpty":throw Error("Index out of bounds");case"ISingleton":{if(index!==0)throw Error("Index out of bounds");return self.backing.a}case"IArray":{if(index>=self.length||index<0)throw Error("Index out of bounds");return self.backing.array[index]}case"IConcat":return index<self.left.length?unsafeGet2(self.left,index):unsafeGet2(self.right,index-self.left.length);case"ISlice":return unsafeGet2(self.backing.chunk,index+self.backing.offset)}}),append2=dual(2,(self,a)=>appendAll2(self,of2(a))),prepend2=dual(2,(self,elem)=>appendAll2(of2(elem),self)),take=dual(2,(self,n)=>{if(n<=0)return _empty;else if(n>=self.length)return self;else switch(self.backing._tag){case"ISlice":return makeChunk({_tag:"ISlice",chunk:self.backing.chunk,length:n,offset:self.backing.offset});case"IConcat":{if(n>self.left.length)return makeChunk({_tag:"IConcat",left:self.left,right:take(self.right,n-self.left.length)});return take(self.left,n)}default:return makeChunk({_tag:"ISlice",chunk:self,offset:0,length:n})}}),drop2=dual(2,(self,n)=>{if(n<=0)return self;else if(n>=self.length)return _empty;else switch(self.backing._tag){case"ISlice":return makeChunk({_tag:"ISlice",chunk:self.backing.chunk,offset:self.backing.offset+n,length:self.backing.length-n});case"IConcat":{if(n>self.left.length)return drop2(self.right,n-self.left.length);return makeChunk({_tag:"IConcat",left:drop2(self.left,n),right:self.right})}default:return makeChunk({_tag:"ISlice",chunk:self,offset:n,length:self.length-n})}});var dropWhile=dual(2,(self,predicate)=>{let arr=toReadonlyArray(self),len=arr.length,i=0;while(i<len&&predicate(arr[i]))i++;return drop2(self,i)});var appendAll2=dual(2,(self,that)=>{if(self.backing._tag==="IEmpty")return that;if(that.backing._tag==="IEmpty")return self;let diff=that.depth-self.depth;if(Math.abs(diff)<=1)return makeChunk({_tag:"IConcat",left:self,right:that});else if(diff<-1)if(self.left.depth>=self.right.depth){let nr=appendAll2(self.right,that);return makeChunk({_tag:"IConcat",left:self.left,right:nr})}else{let nrr=appendAll2(self.right.right,that);if(nrr.depth===self.depth-3){let nr=makeChunk({_tag:"IConcat",left:self.right.left,right:nrr});return makeChunk({_tag:"IConcat",left:self.left,right:nr})}else{let nl=makeChunk({_tag:"IConcat",left:self.left,right:self.right.left});return makeChunk({_tag:"IConcat",left:nl,right:nrr})}}else if(that.right.depth>=that.left.depth){let nl=appendAll2(self,that.left);return makeChunk({_tag:"IConcat",left:nl,right:that.right})}else{let nll=appendAll2(self,that.left.left);if(nll.depth===that.depth-3){let nl=makeChunk({_tag:"IConcat",left:nll,right:that.left.right});return makeChunk({_tag:"IConcat",left:nl,right:that.right})}else{let nr=makeChunk({_tag:"IConcat",left:that.left.right,right:that.right});return makeChunk({_tag:"IConcat",left:nll,right:nr})}}}),filterMap2=dual(2,(self,f)=>unsafeFromArray(filterMap(self,f))),filter2=dual(2,(self,predicate)=>unsafeFromArray(filter(self,predicate))),filterMapWhile2=dual(2,(self,f)=>unsafeFromArray(filterMapWhile(self,f)));var flatMap3=dual(2,(self,f)=>{if(self.backing._tag==="ISingleton")return f(self.backing.a,0);let out=_empty,i=0;for(let k of self)out=appendAll2(out,f(k,i++));return out});var flatten2=flatMap3(identity);var isEmpty=(self)=>self.length===0,isNonEmpty=(self)=>self.length>0,head2=get2(0),unsafeHead=(self)=>unsafeGet2(self,0),headNonEmpty2=unsafeHead,last2=(self)=>get2(self,self.length-1),unsafeLast=(self)=>unsafeGet2(self,self.length-1);var map4=dual(2,(self,f)=>self.backing._tag==="ISingleton"?of2(f(self.backing.a,0)):unsafeFromArray(pipe(toReadonlyArray(self),map3((a,i)=>f(a,i))))),mapAccum2=dual(3,(self,s,f)=>{let[s1,as]=mapAccum(self,s,f);return[s1,unsafeFromArray(as)]});var splitAt2=dual(2,(self,n)=>[take(self,n),drop2(self,n)]);var splitWhere=dual(2,(self,predicate)=>{let i=0;for(let a of toReadonlyArray(self))if(predicate(a))break;else i++;return splitAt2(self,i)});var tailNonEmpty2=(self)=>drop2(self,1),takeRight=dual(2,(self,n)=>drop2(self,self.length-n)),takeWhile=dual(2,(self,predicate)=>{let out=[];for(let a of toReadonlyArray(self))if(predicate(a))out.push(a);else break;return unsafeFromArray(out)});var zipWith2=dual(3,(self,that,f)=>unsafeFromArray(zipWith(self,that,f)));var makeBy2=dual(2,(n,f)=>fromIterable2(makeBy(n,f))),range=(start,end)=>start<=end?makeBy2(end-start+1,(i)=>start+i):of2(start);var findFirst3=findFirst2;var reduce2=reduce,reduceRight2=reduceRight;var SIZE=5,BUCKET_SIZE=Math.pow(2,5),MASK=BUCKET_SIZE-1,MAX_INDEX_NODE=BUCKET_SIZE/2,MIN_ARRAY_NODE=BUCKET_SIZE/4;function popcount(x){return x-=x>>1&1431655765,x=(x&858993459)+(x>>2&858993459),x=x+(x>>4)&252645135,x+=x>>8,x+=x>>16,x&127}function hashFragment(shift,h){return h>>>shift&MASK}function toBitmap(x){return 1<<x}function fromBitmap(bitmap,bit){return popcount(bitmap&bit-1)}var make5=(value,previous)=>({value,previous});function arrayUpdate(mutate,at,v,arr){let out=arr;if(!mutate){let len=arr.length;out=Array(len);for(let i=0;i<len;++i)out[i]=arr[i]}return out[at]=v,out}function arraySpliceOut(mutate,at,arr){let newLen=arr.length-1,i=0,g=0,out=arr;if(mutate)i=g=at;else{out=Array(newLen);while(i<at)out[g++]=arr[i++]}++i;while(i<=newLen)out[g++]=arr[i++];if(mutate)out.length=newLen;return out}function arraySpliceIn(mutate,at,v,arr){let len=arr.length;if(mutate){let i2=len;while(i2>=at)arr[i2--]=arr[i2];return arr[at]=v,arr}let i=0,g=0,out=Array(len+1);while(i<at)out[g++]=arr[i++];out[at]=v;while(i<len)out[++g]=arr[i++];return out}class EmptyNode{_tag="EmptyNode";modify(edit,_shift,f,hash2,key,size){let v=f(none2());if(isNone2(v))return new EmptyNode;return++size.value,new LeafNode(edit,hash2,key,v)}}function isEmptyNode(a){return isTagged(a,"EmptyNode")}function isLeafNode(node){return isEmptyNode(node)||node._tag==="LeafNode"||node._tag==="CollisionNode"}function canEditNode(node,edit){return isEmptyNode(node)?!1:edit===node.edit}class LeafNode{edit;hash;key;value;_tag="LeafNode";constructor(edit,hash2,key,value){this.edit=edit,this.hash=hash2,this.key=key,this.value=value}modify(edit,shift,f,hash2,key,size){if(equals(key,this.key)){let v2=f(this.value);if(v2===this.value)return this;else if(isNone2(v2))return--size.value,new EmptyNode;if(canEditNode(this,edit))return this.value=v2,this;return new LeafNode(edit,hash2,key,v2)}let v=f(none2());if(isNone2(v))return this;return++size.value,mergeLeaves(edit,shift,this.hash,this,hash2,new LeafNode(edit,hash2,key,v))}}class CollisionNode{edit;hash;children;_tag="CollisionNode";constructor(edit,hash2,children){this.edit=edit,this.hash=hash2,this.children=children}modify(edit,shift,f,hash2,key,size){if(hash2===this.hash){let canEdit=canEditNode(this,edit),list=this.updateCollisionList(canEdit,edit,this.hash,this.children,f,key,size);if(list===this.children)return this;return list.length>1?new CollisionNode(edit,this.hash,list):list[0]}let v=f(none2());if(isNone2(v))return this;return++size.value,mergeLeaves(edit,shift,this.hash,this,hash2,new LeafNode(edit,hash2,key,v))}updateCollisionList(mutate,edit,hash2,list,f,key,size){let len=list.length;for(let i=0;i<len;++i){let child=list[i];if("key"in child&&equals(key,child.key)){let value=child.value,newValue2=f(value);if(newValue2===value)return list;if(isNone2(newValue2))return--size.value,arraySpliceOut(mutate,i,list);return arrayUpdate(mutate,i,new LeafNode(edit,hash2,key,newValue2),list)}}let newValue=f(none2());if(isNone2(newValue))return list;return++size.value,arrayUpdate(mutate,len,new LeafNode(edit,hash2,key,newValue),list)}}class IndexedNode{edit;mask;children;_tag="IndexedNode";constructor(edit,mask,children){this.edit=edit,this.mask=mask,this.children=children}modify(edit,shift,f,hash2,key,size){let mask=this.mask,children=this.children,frag=hashFragment(shift,hash2),bit=toBitmap(frag),indx=fromBitmap(mask,bit),exists=mask&bit,canEdit=canEditNode(this,edit);if(!exists){let _newChild=new EmptyNode().modify(edit,shift+SIZE,f,hash2,key,size);if(!_newChild)return this;return children.length>=MAX_INDEX_NODE?expand(edit,frag,_newChild,mask,children):new IndexedNode(edit,mask|bit,arraySpliceIn(canEdit,indx,_newChild,children))}let current=children[indx],child=current.modify(edit,shift+SIZE,f,hash2,key,size);if(current===child)return this;let bitmap=mask,newChildren;if(isEmptyNode(child)){if(bitmap&=~bit,!bitmap)return new EmptyNode;if(children.length<=2&&isLeafNode(children[indx^1]))return children[indx^1];newChildren=arraySpliceOut(canEdit,indx,children)}else newChildren=arrayUpdate(canEdit,indx,child,children);if(canEdit)return this.mask=bitmap,this.children=newChildren,this;return new IndexedNode(edit,bitmap,newChildren)}}class ArrayNode{edit;size;children;_tag="ArrayNode";constructor(edit,size,children){this.edit=edit,this.size=size,this.children=children}modify(edit,shift,f,hash2,key,size){let count=this.size,children=this.children,frag=hashFragment(shift,hash2),child=children[frag],newChild=(child||new EmptyNode).modify(edit,shift+SIZE,f,hash2,key,size);if(child===newChild)return this;let canEdit=canEditNode(this,edit),newChildren;if(isEmptyNode(child)&&!isEmptyNode(newChild))++count,newChildren=arrayUpdate(canEdit,frag,newChild,children);else if(!isEmptyNode(child)&&isEmptyNode(newChild)){if(--count,count<=MIN_ARRAY_NODE)return pack(edit,count,frag,children);newChildren=arrayUpdate(canEdit,frag,new EmptyNode,children)}else newChildren=arrayUpdate(canEdit,frag,newChild,children);if(canEdit)return this.size=count,this.children=newChildren,this;return new ArrayNode(edit,count,newChildren)}}function pack(edit,count,removed,elements){let children=Array(count-1),g=0,bitmap=0;for(let i=0,len=elements.length;i<len;++i)if(i!==removed){let elem=elements[i];if(elem&&!isEmptyNode(elem))children[g++]=elem,bitmap|=1<<i}return new IndexedNode(edit,bitmap,children)}function expand(edit,frag,child,bitmap,subNodes){let arr=[],bit=bitmap,count=0;for(let i=0;bit;++i){if(bit&1)arr[i]=subNodes[count++];bit>>>=1}return arr[frag]=child,new ArrayNode(edit,count+1,arr)}function mergeLeavesInner(edit,shift,h1,n1,h2,n2){if(h1===h2)return new CollisionNode(edit,h1,[n2,n1]);let subH1=hashFragment(shift,h1),subH2=hashFragment(shift,h2);if(subH1===subH2)return(child)=>new IndexedNode(edit,toBitmap(subH1)|toBitmap(subH2),[child]);else{let children=subH1<subH2?[n1,n2]:[n2,n1];return new IndexedNode(edit,toBitmap(subH1)|toBitmap(subH2),children)}}function mergeLeaves(edit,shift,h1,n1,h2,n2){let stack=void 0,currentShift=shift;while(!0){let res=mergeLeavesInner(edit,currentShift,h1,n1,h2,n2);if(typeof res==="function")stack=make5(res,stack),currentShift=currentShift+SIZE;else{let final=res;while(stack!=null)final=stack.value(final),stack=stack.previous;return final}}}var HashMapSymbolKey="effect/HashMap",HashMapTypeId=Symbol.for(HashMapSymbolKey),HashMapProto={[HashMapTypeId]:HashMapTypeId,[Symbol.iterator](){return new HashMapIterator(this,(k,v)=>[k,v])},[symbol](){let hash2=hash(HashMapSymbolKey);for(let item of this)hash2^=pipe(hash(item[0]),combine(hash(item[1])));return cached(this,hash2)},[symbol2](that){if(isHashMap(that)){if(that._size!==this._size)return!1;for(let item of this){let elem=pipe(that,getHash(item[0],hash(item[0])));if(isNone2(elem))return!1;else if(!equals(item[1],elem.value))return!1}return!0}return!1},toString(){return format(this.toJSON())},toJSON(){return{_id:"HashMap",values:Array.from(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}},makeImpl=(editable,edit,root,size)=>{let map5=Object.create(HashMapProto);return map5._editable=editable,map5._edit=edit,map5._root=root,map5._size=size,map5};class HashMapIterator{map;f;v;constructor(map5,f){this.map=map5,this.f=f,this.v=visitLazy(this.map._root,this.f,void 0)}next(){if(isNone2(this.v))return{done:!0,value:void 0};let v0=this.v.value;return this.v=applyCont(v0.cont),{done:!1,value:v0.value}}[Symbol.iterator](){return new HashMapIterator(this.map,this.f)}}var applyCont=(cont)=>cont?visitLazyChildren(cont[0],cont[1],cont[2],cont[3],cont[4]):none2(),visitLazy=(node,f,cont=void 0)=>{switch(node._tag){case"LeafNode":{if(isSome2(node.value))return some2({value:f(node.key,node.value.value),cont});return applyCont(cont)}case"CollisionNode":case"ArrayNode":case"IndexedNode":{let children=node.children;return visitLazyChildren(children.length,children,0,f,cont)}default:return applyCont(cont)}},visitLazyChildren=(len,children,i,f,cont)=>{while(i<len){let child=children[i++];if(child&&!isEmptyNode(child))return visitLazy(child,f,[len,children,i,f,cont])}return applyCont(cont)},_empty2=makeImpl(!1,0,new EmptyNode,0),empty3=()=>_empty2;var fromIterable3=(entries)=>{let map5=beginMutation(empty3());for(let entry of entries)set(map5,entry[0],entry[1]);return endMutation(map5)},isHashMap=(u)=>hasProperty(u,HashMapTypeId),isEmpty2=(self)=>self&&isEmptyNode(self._root),get3=dual(2,(self,key)=>getHash(self,key,hash(key))),getHash=dual(3,(self,key,hash2)=>{let node=self._root,shift=0;while(!0)switch(node._tag){case"LeafNode":return equals(key,node.key)?node.value:none2();case"CollisionNode":{if(hash2===node.hash){let children=node.children;for(let i=0,len=children.length;i<len;++i){let child=children[i];if("key"in child&&equals(key,child.key))return child.value}}return none2()}case"IndexedNode":{let frag=hashFragment(shift,hash2),bit=toBitmap(frag);if(node.mask&bit){node=node.children[fromBitmap(node.mask,bit)],shift+=SIZE;break}return none2()}case"ArrayNode":{if(node=node.children[hashFragment(shift,hash2)],node){shift+=SIZE;break}return none2()}default:return none2()}});var has=dual(2,(self,key)=>isSome2(getHash(self,key,hash(key))));var set=dual(3,(self,key,value)=>modifyAt(self,key,()=>some2(value))),setTree=dual(3,(self,newRoot,newSize)=>{if(self._editable)return self._root=newRoot,self._size=newSize,self;return newRoot===self._root?self:makeImpl(self._editable,self._edit,newRoot,newSize)}),keys=(self)=>new HashMapIterator(self,(key)=>key);var size=(self)=>self._size;var beginMutation=(self)=>makeImpl(!0,self._edit+1,self._root,self._size),endMutation=(self)=>{return self._editable=!1,self},mutate=dual(2,(self,f)=>{let transient=beginMutation(self);return f(transient),endMutation(transient)}),modifyAt=dual(3,(self,key,f)=>modifyHash(self,key,hash(key),f)),modifyHash=dual(4,(self,key,hash2,f)=>{let size2={value:self._size},newRoot=self._root.modify(self._editable?self._edit:NaN,0,f,hash2,key,size2);return pipe(self,setTree(newRoot,size2.value))});var remove2=dual(2,(self,key)=>modifyAt(self,key,none2));var map5=dual(2,(self,f)=>reduce3(self,empty3(),(map6,value,key)=>set(map6,key,f(value,key))));var forEach=dual(2,(self,f)=>reduce3(self,void 0,(_,value,key)=>f(value,key))),reduce3=dual(3,(self,zero,f)=>{let root=self._root;if(root._tag==="LeafNode")return isSome2(root.value)?f(zero,root.value.value,root.key):zero;if(root._tag==="EmptyNode")return zero;let toVisit=[root.children],children;while(children=toVisit.pop())for(let i=0,len=children.length;i<len;){let child=children[i++];if(child&&!isEmptyNode(child))if(child._tag==="LeafNode"){if(isSome2(child.value))zero=f(zero,child.value.value,child.key)}else toVisit.push(child.children)}return zero});var HashSetSymbolKey="effect/HashSet",HashSetTypeId=Symbol.for(HashSetSymbolKey),HashSetProto={[HashSetTypeId]:HashSetTypeId,[Symbol.iterator](){return keys(this._keyMap)},[symbol](){return cached(this,combine(hash(this._keyMap))(hash(HashSetSymbolKey)))},[symbol2](that){if(isHashSet(that))return size(this._keyMap)===size(that._keyMap)&&equals(this._keyMap,that._keyMap);return!1},toString(){return format(this.toJSON())},toJSON(){return{_id:"HashSet",values:Array.from(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}},makeImpl2=(keyMap)=>{let set2=Object.create(HashSetProto);return set2._keyMap=keyMap,set2},isHashSet=(u)=>hasProperty(u,HashSetTypeId),_empty3=makeImpl2(empty3()),empty4=()=>_empty3,fromIterable4=(elements)=>{let set2=beginMutation2(empty4());for(let value of elements)add(set2,value);return endMutation2(set2)},make6=(...elements)=>{let set2=beginMutation2(empty4());for(let value of elements)add(set2,value);return endMutation2(set2)},has2=dual(2,(self,value)=>has(self._keyMap,value));var size2=(self)=>size(self._keyMap),beginMutation2=(self)=>makeImpl2(beginMutation(self._keyMap)),endMutation2=(self)=>{return self._keyMap._editable=!1,self},mutate2=dual(2,(self,f)=>{let transient=beginMutation2(self);return f(transient),endMutation2(transient)}),add=dual(2,(self,value)=>self._keyMap._editable?(set(value,!0)(self._keyMap),self):makeImpl2(set(value,!0)(self._keyMap))),remove3=dual(2,(self,value)=>self._keyMap._editable?(remove2(value)(self._keyMap),self):makeImpl2(remove2(value)(self._keyMap))),difference2=dual(2,(self,that)=>mutate2(self,(set2)=>{for(let value of that)remove3(set2,value)}));var union2=dual(2,(self,that)=>mutate2(empty4(),(set2)=>{forEach2(self,(value)=>add(set2,value));for(let value of that)add(set2,value)}));var forEach2=dual(2,(self,f)=>forEach(self._keyMap,(_,k)=>f(k))),reduce4=dual(3,(self,zero,f)=>reduce3(self._keyMap,zero,(z,_,a)=>f(z,a)));var empty5=empty4,fromIterable5=fromIterable4,make7=make6,has3=has2;var size3=size2;var add2=add,remove4=remove3,difference3=difference2;var union3=union2;var forEach3=forEach2,reduce5=reduce4;var OP_DIE="Die",OP_EMPTY="Empty",OP_FAIL="Fail",OP_INTERRUPT="Interrupt",OP_PARALLEL="Parallel",OP_SEQUENTIAL="Sequential";var CauseSymbolKey="effect/Cause",CauseTypeId=Symbol.for(CauseSymbolKey),variance={_E:(_)=>_},proto={[CauseTypeId]:variance,[symbol](){return pipe(hash(CauseSymbolKey),combine(hash(flattenCause(this))),cached(this))},[symbol2](that){return isCause(that)&&causeEquals(this,that)},pipe(){return pipeArguments(this,arguments)},toJSON(){switch(this._tag){case"Empty":return{_id:"Cause",_tag:this._tag};case"Die":return{_id:"Cause",_tag:this._tag,defect:toJSON(this.defect)};case"Interrupt":return{_id:"Cause",_tag:this._tag,fiberId:this.fiberId.toJSON()};case"Fail":return{_id:"Cause",_tag:this._tag,failure:toJSON(this.error)};case"Sequential":case"Parallel":return{_id:"Cause",_tag:this._tag,left:toJSON(this.left),right:toJSON(this.right)}}},toString(){return pretty(this)},[NodeInspectSymbol](){return this.toJSON()}},empty6=(()=>{let o=Object.create(proto);return o._tag=OP_EMPTY,o})(),fail=(error)=>{let o=Object.create(proto);return o._tag=OP_FAIL,o.error=error,o},die=(defect)=>{let o=Object.create(proto);return o._tag=OP_DIE,o.defect=defect,o},interrupt=(fiberId)=>{let o=Object.create(proto);return o._tag=OP_INTERRUPT,o.fiberId=fiberId,o},parallel=(left3,right3)=>{let o=Object.create(proto);return o._tag=OP_PARALLEL,o.left=left3,o.right=right3,o},sequential=(left3,right3)=>{let o=Object.create(proto);return o._tag=OP_SEQUENTIAL,o.left=left3,o.right=right3,o},isCause=(u)=>hasProperty(u,CauseTypeId),isEmptyType=(self)=>self._tag===OP_EMPTY;var isDieType=(self)=>self._tag===OP_DIE;var isEmpty3=(self)=>{if(self._tag===OP_EMPTY)return!0;return reduce6(self,!0,(acc,cause)=>{switch(cause._tag){case OP_EMPTY:return some2(acc);case OP_DIE:case OP_FAIL:case OP_INTERRUPT:return some2(!1);default:return none2()}})};var isInterrupted=(self)=>isSome2(interruptOption(self)),isInterruptedOnly=(self)=>reduceWithContext(void 0,IsInterruptedOnlyCauseReducer)(self),failures=(self)=>reverse2(reduce6(self,empty2(),(list,cause)=>cause._tag===OP_FAIL?some2(pipe(list,prepend2(cause.error))):none2())),defects=(self)=>reverse2(reduce6(self,empty2(),(list,cause)=>cause._tag===OP_DIE?some2(pipe(list,prepend2(cause.defect))):none2())),interruptors=(self)=>reduce6(self,empty5(),(set2,cause)=>cause._tag===OP_INTERRUPT?some2(pipe(set2,add2(cause.fiberId))):none2()),failureOption=(self)=>find(self,(cause)=>cause._tag===OP_FAIL?some2(cause.error):none2()),failureOrCause=(self)=>{let option=failureOption(self);switch(option._tag){case"None":return right2(self);case"Some":return left2(option.value)}};var flipCauseOption=(self)=>match3(self,{onEmpty:some2(empty6),onFail:map2(fail),onDie:(defect)=>some2(die(defect)),onInterrupt:(fiberId)=>some2(interrupt(fiberId)),onSequential:mergeWith(sequential),onParallel:mergeWith(parallel)}),interruptOption=(self)=>find(self,(cause)=>cause._tag===OP_INTERRUPT?some2(cause.fiberId):none2()),keepDefects=(self)=>match3(self,{onEmpty:none2(),onFail:()=>none2(),onDie:(defect)=>some2(die(defect)),onInterrupt:()=>none2(),onSequential:mergeWith(sequential),onParallel:mergeWith(parallel)}),keepDefectsAndElectFailures=(self)=>match3(self,{onEmpty:none2(),onFail:(failure)=>some2(die(failure)),onDie:(defect)=>some2(die(defect)),onInterrupt:()=>none2(),onSequential:mergeWith(sequential),onParallel:mergeWith(parallel)});var stripFailures=(self)=>match3(self,{onEmpty:empty6,onFail:()=>empty6,onDie:die,onInterrupt:interrupt,onSequential:sequential,onParallel:parallel}),electFailures=(self)=>match3(self,{onEmpty:empty6,onFail:die,onDie:die,onInterrupt:interrupt,onSequential:sequential,onParallel:parallel});var map8=dual(2,(self,f)=>flatMap6(self,(e)=>fail(f(e)))),flatMap6=dual(2,(self,f)=>match3(self,{onEmpty:empty6,onFail:(error)=>f(error),onDie:(defect)=>die(defect),onInterrupt:(fiberId)=>interrupt(fiberId),onSequential:(left3,right3)=>sequential(left3,right3),onParallel:(left3,right3)=>parallel(left3,right3)})),flatten3=(self)=>flatMap6(self,identity);var causeEquals=(left3,right3)=>{let leftStack=of2(left3),rightStack=of2(right3);while(isNonEmpty(leftStack)&&isNonEmpty(rightStack)){let[leftParallel,leftSequential]=pipe(headNonEmpty2(leftStack),reduce6([empty5(),empty2()],([parallel2,sequential2],cause)=>{let[par,seq]=evaluateCause(cause);return some2([pipe(parallel2,union3(par)),pipe(sequential2,appendAll2(seq))])})),[rightParallel,rightSequential]=pipe(headNonEmpty2(rightStack),reduce6([empty5(),empty2()],([parallel2,sequential2],cause)=>{let[par,seq]=evaluateCause(cause);return some2([pipe(parallel2,union3(par)),pipe(sequential2,appendAll2(seq))])}));if(!equals(leftParallel,rightParallel))return!1;leftStack=leftSequential,rightStack=rightSequential}return!0},flattenCause=(cause)=>{return flattenCauseLoop(of2(cause),empty2())},flattenCauseLoop=(causes,flattened)=>{while(!0){let[parallel2,sequential2]=pipe(causes,reduce([empty5(),empty2()],([parallel3,sequential3],cause)=>{let[par,seq]=evaluateCause(cause);return[pipe(parallel3,union3(par)),pipe(sequential3,appendAll2(seq))]})),updated=size3(parallel2)>0?pipe(flattened,prepend2(parallel2)):flattened;if(isEmpty(sequential2))return reverse2(updated);causes=sequential2,flattened=updated}throw Error(getBugErrorMessage("Cause.flattenCauseLoop"))},find=dual(2,(self,pf)=>{let stack=[self];while(stack.length>0){let item=stack.pop(),option=pf(item);switch(option._tag){case"None":{switch(item._tag){case OP_SEQUENTIAL:case OP_PARALLEL:{stack.push(item.right),stack.push(item.left);break}}break}case"Some":return option}}return none2()});var evaluateCause=(self)=>{let cause=self,stack=[],_parallel=empty5(),_sequential=empty2();while(cause!==void 0)switch(cause._tag){case OP_EMPTY:{if(stack.length===0)return[_parallel,_sequential];cause=stack.pop();break}case OP_FAIL:{if(_parallel=add2(_parallel,make4(cause._tag,cause.error)),stack.length===0)return[_parallel,_sequential];cause=stack.pop();break}case OP_DIE:{if(_parallel=add2(_parallel,make4(cause._tag,cause.defect)),stack.length===0)return[_parallel,_sequential];cause=stack.pop();break}case OP_INTERRUPT:{if(_parallel=add2(_parallel,make4(cause._tag,cause.fiberId)),stack.length===0)return[_parallel,_sequential];cause=stack.pop();break}case OP_SEQUENTIAL:{switch(cause.left._tag){case OP_EMPTY:{cause=cause.right;break}case OP_SEQUENTIAL:{cause=sequential(cause.left.left,sequential(cause.left.right,cause.right));break}case OP_PARALLEL:{cause=parallel(sequential(cause.left.left,cause.right),sequential(cause.left.right,cause.right));break}default:{_sequential=prepend2(_sequential,cause.right),cause=cause.left;break}}break}case OP_PARALLEL:{stack.push(cause.right),cause=cause.left;break}}throw Error(getBugErrorMessage("Cause.evaluateCauseLoop"))};var IsInterruptedOnlyCauseReducer={emptyCase:constTrue,failCase:constFalse,dieCase:constFalse,interruptCase:constTrue,sequentialCase:(_,left3,right3)=>left3&&right3,parallelCase:(_,left3,right3)=>left3&&right3};var OP_SEQUENTIAL_CASE="SequentialCase",OP_PARALLEL_CASE="ParallelCase",match3=dual(2,(self,{onDie,onEmpty,onFail,onInterrupt,onParallel,onSequential})=>{return reduceWithContext(self,void 0,{emptyCase:()=>onEmpty,failCase:(_,error)=>onFail(error),dieCase:(_,defect)=>onDie(defect),interruptCase:(_,fiberId)=>onInterrupt(fiberId),sequentialCase:(_,left3,right3)=>onSequential(left3,right3),parallelCase:(_,left3,right3)=>onParallel(left3,right3)})}),reduce6=dual(3,(self,zero,pf)=>{let accumulator=zero,cause=self,causes=[];while(cause!==void 0){let option=pf(accumulator,cause);switch(accumulator=isSome2(option)?option.value:accumulator,cause._tag){case OP_SEQUENTIAL:{causes.push(cause.right),cause=cause.left;break}case OP_PARALLEL:{causes.push(cause.right),cause=cause.left;break}default:{cause=void 0;break}}if(cause===void 0&&causes.length>0)cause=causes.pop()}return accumulator}),reduceWithContext=dual(3,(self,context,reducer)=>{let input=[self],output=[];while(input.length>0){let cause=input.pop();switch(cause._tag){case OP_EMPTY:{output.push(right2(reducer.emptyCase(context)));break}case OP_FAIL:{output.push(right2(reducer.failCase(context,cause.error)));break}case OP_DIE:{output.push(right2(reducer.dieCase(context,cause.defect)));break}case OP_INTERRUPT:{output.push(right2(reducer.interruptCase(context,cause.fiberId)));break}case OP_SEQUENTIAL:{input.push(cause.right),input.push(cause.left),output.push(left2({_tag:OP_SEQUENTIAL_CASE}));break}case OP_PARALLEL:{input.push(cause.right),input.push(cause.left),output.push(left2({_tag:OP_PARALLEL_CASE}));break}}}let accumulator=[];while(output.length>0){let either=output.pop();switch(either._tag){case"Left":{switch(either.left._tag){case OP_SEQUENTIAL_CASE:{let left3=accumulator.pop(),right3=accumulator.pop(),value=reducer.sequentialCase(context,left3,right3);accumulator.push(value);break}case OP_PARALLEL_CASE:{let left3=accumulator.pop(),right3=accumulator.pop(),value=reducer.parallelCase(context,left3,right3);accumulator.push(value);break}}break}case"Right":{accumulator.push(either.right);break}}}if(accumulator.length===0)throw Error("BUG: Cause.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues");return accumulator.pop()}),pretty=(cause,options)=>{if(isInterruptedOnly(cause))return"All fibers interrupted without errors.";return prettyErrors(cause).map(function(e){if(options?.renderErrorCause!==!0||e.cause===void 0)return e.stack;return`${e.stack} {
7
+ ${ind(d)}}`;return wrap(v,body)}return String(v)}return go(input,0)}var 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 moduleVersion="3.19.14",getCurrentVersion=()=>moduleVersion;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 fromOption=dual(2,(self,onNone)=>isNone(self)?left(onNone()):right(self.value));var right2=right;var left2=left;var fromOption2=fromOption,try_=(evaluate)=>{if(isFunction2(evaluate))try{return right2(evaluate())}catch(e){return left2(e)}else try{return right2(evaluate.try())}catch(e){return left2(evaluate.catch(e))}};var 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)),liftPredicate=dual(3,(a,predicate,orLeftWith)=>predicate(a)?right2(a):left2(orLeftWith(a)));var merge=match({onLeft:identity,onRight:identity});var all=(input)=>{if(Symbol.iterator in input){let out2=[];for(let e of input){if(isLeft2(e))return e;out2.push(e.right)}return right2(out2)}let out={};for(let key of Object.keys(input)){let e=input[key];if(isLeft2(e))return e;out[key]=e.right}return right2(out)};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 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{return none2()}},getOrThrowWith=dual(2,(self,onNone)=>{if(isSome2(self))return self.value;throw onNone()}),getOrThrow=getOrThrowWith(()=>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 containsWith=(isEquivalent)=>dual(2,(self,a)=>isNone2(self)?!1:isEquivalent(self.value,a)),_equivalence=equivalence(),contains=containsWith(_equivalence);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 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}}};var allocate=(n)=>Array(n),makeBy=dual(2,(n,f)=>{let max2=Math.max(1,Math.floor(n)),out=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 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 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 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 empty=()=>[],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 TypeId3=Symbol.for("effect/Chunk");function copy2(src,srcPos,dest,destPos,len){for(let i=srcPos;i<Math.min(src.length,srcPos+len);i++)dest[destPos+i-srcPos]=src[i];return dest}var emptyArray=[],getEquivalence2=(isEquivalent)=>make((self,that)=>self.length===that.length&&toReadonlyArray(self).every((value,i)=>isEquivalent(value,unsafeGet2(that,i)))),_equivalence3=getEquivalence2(equals),ChunkProto={[TypeId3]:{_A:(_)=>_},toString(){return format(this.toJSON())},toJSON(){return{_id:"Chunk",values:toReadonlyArray(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},[symbol2](that){return isChunk(that)&&_equivalence3(this,that)},[symbol](){return cached(this,array2(toReadonlyArray(this)))},[Symbol.iterator](){switch(this.backing._tag){case"IArray":return this.backing.array[Symbol.iterator]();case"IEmpty":return emptyArray[Symbol.iterator]();default:return toReadonlyArray(this)[Symbol.iterator]()}},pipe(){return pipeArguments(this,arguments)}},makeChunk=(backing)=>{let chunk=Object.create(ChunkProto);switch(chunk.backing=backing,backing._tag){case"IEmpty":{chunk.length=0,chunk.depth=0,chunk.left=chunk,chunk.right=chunk;break}case"IConcat":{chunk.length=backing.left.length+backing.right.length,chunk.depth=1+Math.max(backing.left.depth,backing.right.depth),chunk.left=backing.left,chunk.right=backing.right;break}case"IArray":{chunk.length=backing.array.length,chunk.depth=0,chunk.left=_empty,chunk.right=_empty;break}case"ISingleton":{chunk.length=1,chunk.depth=0,chunk.left=_empty,chunk.right=_empty;break}case"ISlice":{chunk.length=backing.length,chunk.depth=backing.chunk.depth+1,chunk.left=_empty,chunk.right=_empty;break}}return chunk},isChunk=(u)=>hasProperty(u,TypeId3),_empty=makeChunk({_tag:"IEmpty"}),empty2=()=>_empty,make4=(...as)=>unsafeFromNonEmptyArray(as),of2=(a)=>makeChunk({_tag:"ISingleton",a}),fromIterable2=(self)=>isChunk(self)?self:unsafeFromArray(fromIterable(self)),copyToArray=(self,array3,initial)=>{switch(self.backing._tag){case"IArray":{copy2(self.backing.array,0,array3,initial,self.length);break}case"IConcat":{copyToArray(self.left,array3,initial),copyToArray(self.right,array3,initial+self.left.length);break}case"ISingleton":{array3[initial]=self.backing.a;break}case"ISlice":{let i=0,j=initial;while(i<self.length)array3[j]=unsafeGet2(self,i),i+=1,j+=1;break}}},toArray_=(self)=>toReadonlyArray(self).slice(),toArray2=toArray_,toReadonlyArray_=(self)=>{switch(self.backing._tag){case"IEmpty":return emptyArray;case"IArray":return self.backing.array;default:{let arr=Array(self.length);return copyToArray(self,arr,0),self.backing={_tag:"IArray",array:arr},self.left=_empty,self.right=_empty,self.depth=0,arr}}},toReadonlyArray=toReadonlyArray_,reverseChunk=(self)=>{switch(self.backing._tag){case"IEmpty":case"ISingleton":return self;case"IArray":return makeChunk({_tag:"IArray",array:reverse(self.backing.array)});case"IConcat":return makeChunk({_tag:"IConcat",left:reverse2(self.backing.right),right:reverse2(self.backing.left)});case"ISlice":return unsafeFromArray(reverse(toReadonlyArray(self)))}},reverse2=reverseChunk,get2=dual(2,(self,index)=>index<0||index>=self.length?none2():some2(unsafeGet2(self,index))),unsafeFromArray=(self)=>self.length===0?empty2():self.length===1?of2(self[0]):makeChunk({_tag:"IArray",array:self}),unsafeFromNonEmptyArray=(self)=>unsafeFromArray(self),unsafeGet2=dual(2,(self,index)=>{switch(self.backing._tag){case"IEmpty":throw Error("Index out of bounds");case"ISingleton":{if(index!==0)throw Error("Index out of bounds");return self.backing.a}case"IArray":{if(index>=self.length||index<0)throw Error("Index out of bounds");return self.backing.array[index]}case"IConcat":return index<self.left.length?unsafeGet2(self.left,index):unsafeGet2(self.right,index-self.left.length);case"ISlice":return unsafeGet2(self.backing.chunk,index+self.backing.offset)}}),append2=dual(2,(self,a)=>appendAll2(self,of2(a))),prepend2=dual(2,(self,elem)=>appendAll2(of2(elem),self)),take=dual(2,(self,n)=>{if(n<=0)return _empty;else if(n>=self.length)return self;else switch(self.backing._tag){case"ISlice":return makeChunk({_tag:"ISlice",chunk:self.backing.chunk,length:n,offset:self.backing.offset});case"IConcat":{if(n>self.left.length)return makeChunk({_tag:"IConcat",left:self.left,right:take(self.right,n-self.left.length)});return take(self.left,n)}default:return makeChunk({_tag:"ISlice",chunk:self,offset:0,length:n})}}),drop2=dual(2,(self,n)=>{if(n<=0)return self;else if(n>=self.length)return _empty;else switch(self.backing._tag){case"ISlice":return makeChunk({_tag:"ISlice",chunk:self.backing.chunk,offset:self.backing.offset+n,length:self.backing.length-n});case"IConcat":{if(n>self.left.length)return drop2(self.right,n-self.left.length);return makeChunk({_tag:"IConcat",left:drop2(self.left,n),right:self.right})}default:return makeChunk({_tag:"ISlice",chunk:self,offset:n,length:self.length-n})}});var dropWhile=dual(2,(self,predicate)=>{let arr=toReadonlyArray(self),len=arr.length,i=0;while(i<len&&predicate(arr[i]))i++;return drop2(self,i)});var appendAll2=dual(2,(self,that)=>{if(self.backing._tag==="IEmpty")return that;if(that.backing._tag==="IEmpty")return self;let diff=that.depth-self.depth;if(Math.abs(diff)<=1)return makeChunk({_tag:"IConcat",left:self,right:that});else if(diff<-1)if(self.left.depth>=self.right.depth){let nr=appendAll2(self.right,that);return makeChunk({_tag:"IConcat",left:self.left,right:nr})}else{let nrr=appendAll2(self.right.right,that);if(nrr.depth===self.depth-3){let nr=makeChunk({_tag:"IConcat",left:self.right.left,right:nrr});return makeChunk({_tag:"IConcat",left:self.left,right:nr})}else{let nl=makeChunk({_tag:"IConcat",left:self.left,right:self.right.left});return makeChunk({_tag:"IConcat",left:nl,right:nrr})}}else if(that.right.depth>=that.left.depth){let nl=appendAll2(self,that.left);return makeChunk({_tag:"IConcat",left:nl,right:that.right})}else{let nll=appendAll2(self,that.left.left);if(nll.depth===that.depth-3){let nl=makeChunk({_tag:"IConcat",left:nll,right:that.left.right});return makeChunk({_tag:"IConcat",left:nl,right:that.right})}else{let nr=makeChunk({_tag:"IConcat",left:that.left.right,right:that.right});return makeChunk({_tag:"IConcat",left:nll,right:nr})}}}),filterMap2=dual(2,(self,f)=>unsafeFromArray(filterMap(self,f))),filter2=dual(2,(self,predicate)=>unsafeFromArray(filter(self,predicate))),filterMapWhile2=dual(2,(self,f)=>unsafeFromArray(filterMapWhile(self,f)));var flatMap3=dual(2,(self,f)=>{if(self.backing._tag==="ISingleton")return f(self.backing.a,0);let out=_empty,i=0;for(let k of self)out=appendAll2(out,f(k,i++));return out});var flatten2=flatMap3(identity);var isEmpty=(self)=>self.length===0,isNonEmpty=(self)=>self.length>0,head2=get2(0),unsafeHead=(self)=>unsafeGet2(self,0),headNonEmpty2=unsafeHead,last2=(self)=>get2(self,self.length-1),unsafeLast=(self)=>unsafeGet2(self,self.length-1);var map4=dual(2,(self,f)=>self.backing._tag==="ISingleton"?of2(f(self.backing.a,0)):unsafeFromArray(pipe(toReadonlyArray(self),map3((a,i)=>f(a,i))))),mapAccum2=dual(3,(self,s,f)=>{let[s1,as]=mapAccum(self,s,f);return[s1,unsafeFromArray(as)]});var splitAt2=dual(2,(self,n)=>[take(self,n),drop2(self,n)]);var splitWhere=dual(2,(self,predicate)=>{let i=0;for(let a of toReadonlyArray(self))if(predicate(a))break;else i++;return splitAt2(self,i)});var tailNonEmpty2=(self)=>drop2(self,1),takeRight=dual(2,(self,n)=>drop2(self,self.length-n)),takeWhile=dual(2,(self,predicate)=>{let out=[];for(let a of toReadonlyArray(self))if(predicate(a))out.push(a);else break;return unsafeFromArray(out)});var zipWith2=dual(3,(self,that,f)=>unsafeFromArray(zipWith(self,that,f)));var makeBy2=dual(2,(n,f)=>fromIterable2(makeBy(n,f))),range=(start,end)=>start<=end?makeBy2(end-start+1,(i)=>start+i):of2(start);var findFirst3=findFirst2;var reduce2=reduce,reduceRight2=reduceRight;var SIZE=5,BUCKET_SIZE=Math.pow(2,5),MASK=BUCKET_SIZE-1,MAX_INDEX_NODE=BUCKET_SIZE/2,MIN_ARRAY_NODE=BUCKET_SIZE/4;function popcount(x){return x-=x>>1&1431655765,x=(x&858993459)+(x>>2&858993459),x=x+(x>>4)&252645135,x+=x>>8,x+=x>>16,x&127}function hashFragment(shift,h){return h>>>shift&MASK}function toBitmap(x){return 1<<x}function fromBitmap(bitmap,bit){return popcount(bitmap&bit-1)}var make5=(value,previous)=>({value,previous});function arrayUpdate(mutate,at,v,arr){let out=arr;if(!mutate){let len=arr.length;out=Array(len);for(let i=0;i<len;++i)out[i]=arr[i]}return out[at]=v,out}function arraySpliceOut(mutate,at,arr){let newLen=arr.length-1,i=0,g=0,out=arr;if(mutate)i=g=at;else{out=Array(newLen);while(i<at)out[g++]=arr[i++]}++i;while(i<=newLen)out[g++]=arr[i++];if(mutate)out.length=newLen;return out}function arraySpliceIn(mutate,at,v,arr){let len=arr.length;if(mutate){let i2=len;while(i2>=at)arr[i2--]=arr[i2];return arr[at]=v,arr}let i=0,g=0,out=Array(len+1);while(i<at)out[g++]=arr[i++];out[at]=v;while(i<len)out[++g]=arr[i++];return out}class EmptyNode{_tag="EmptyNode";modify(edit,_shift,f,hash2,key,size){let v=f(none2());if(isNone2(v))return new EmptyNode;return++size.value,new LeafNode(edit,hash2,key,v)}}function isEmptyNode(a){return isTagged(a,"EmptyNode")}function isLeafNode(node){return isEmptyNode(node)||node._tag==="LeafNode"||node._tag==="CollisionNode"}function canEditNode(node,edit){return isEmptyNode(node)?!1:edit===node.edit}class LeafNode{edit;hash;key;value;_tag="LeafNode";constructor(edit,hash2,key,value){this.edit=edit,this.hash=hash2,this.key=key,this.value=value}modify(edit,shift,f,hash2,key,size){if(equals(key,this.key)){let v2=f(this.value);if(v2===this.value)return this;else if(isNone2(v2))return--size.value,new EmptyNode;if(canEditNode(this,edit))return this.value=v2,this;return new LeafNode(edit,hash2,key,v2)}let v=f(none2());if(isNone2(v))return this;return++size.value,mergeLeaves(edit,shift,this.hash,this,hash2,new LeafNode(edit,hash2,key,v))}}class CollisionNode{edit;hash;children;_tag="CollisionNode";constructor(edit,hash2,children){this.edit=edit,this.hash=hash2,this.children=children}modify(edit,shift,f,hash2,key,size){if(hash2===this.hash){let canEdit=canEditNode(this,edit),list=this.updateCollisionList(canEdit,edit,this.hash,this.children,f,key,size);if(list===this.children)return this;return list.length>1?new CollisionNode(edit,this.hash,list):list[0]}let v=f(none2());if(isNone2(v))return this;return++size.value,mergeLeaves(edit,shift,this.hash,this,hash2,new LeafNode(edit,hash2,key,v))}updateCollisionList(mutate,edit,hash2,list,f,key,size){let len=list.length;for(let i=0;i<len;++i){let child=list[i];if("key"in child&&equals(key,child.key)){let value=child.value,newValue2=f(value);if(newValue2===value)return list;if(isNone2(newValue2))return--size.value,arraySpliceOut(mutate,i,list);return arrayUpdate(mutate,i,new LeafNode(edit,hash2,key,newValue2),list)}}let newValue=f(none2());if(isNone2(newValue))return list;return++size.value,arrayUpdate(mutate,len,new LeafNode(edit,hash2,key,newValue),list)}}class IndexedNode{edit;mask;children;_tag="IndexedNode";constructor(edit,mask,children){this.edit=edit,this.mask=mask,this.children=children}modify(edit,shift,f,hash2,key,size){let mask=this.mask,children=this.children,frag=hashFragment(shift,hash2),bit=toBitmap(frag),indx=fromBitmap(mask,bit),exists=mask&bit,canEdit=canEditNode(this,edit);if(!exists){let _newChild=new EmptyNode().modify(edit,shift+SIZE,f,hash2,key,size);if(!_newChild)return this;return children.length>=MAX_INDEX_NODE?expand(edit,frag,_newChild,mask,children):new IndexedNode(edit,mask|bit,arraySpliceIn(canEdit,indx,_newChild,children))}let current=children[indx],child=current.modify(edit,shift+SIZE,f,hash2,key,size);if(current===child)return this;let bitmap=mask,newChildren;if(isEmptyNode(child)){if(bitmap&=~bit,!bitmap)return new EmptyNode;if(children.length<=2&&isLeafNode(children[indx^1]))return children[indx^1];newChildren=arraySpliceOut(canEdit,indx,children)}else newChildren=arrayUpdate(canEdit,indx,child,children);if(canEdit)return this.mask=bitmap,this.children=newChildren,this;return new IndexedNode(edit,bitmap,newChildren)}}class ArrayNode{edit;size;children;_tag="ArrayNode";constructor(edit,size,children){this.edit=edit,this.size=size,this.children=children}modify(edit,shift,f,hash2,key,size){let count=this.size,children=this.children,frag=hashFragment(shift,hash2),child=children[frag],newChild=(child||new EmptyNode).modify(edit,shift+SIZE,f,hash2,key,size);if(child===newChild)return this;let canEdit=canEditNode(this,edit),newChildren;if(isEmptyNode(child)&&!isEmptyNode(newChild))++count,newChildren=arrayUpdate(canEdit,frag,newChild,children);else if(!isEmptyNode(child)&&isEmptyNode(newChild)){if(--count,count<=MIN_ARRAY_NODE)return pack(edit,count,frag,children);newChildren=arrayUpdate(canEdit,frag,new EmptyNode,children)}else newChildren=arrayUpdate(canEdit,frag,newChild,children);if(canEdit)return this.size=count,this.children=newChildren,this;return new ArrayNode(edit,count,newChildren)}}function pack(edit,count,removed,elements){let children=Array(count-1),g=0,bitmap=0;for(let i=0,len=elements.length;i<len;++i)if(i!==removed){let elem=elements[i];if(elem&&!isEmptyNode(elem))children[g++]=elem,bitmap|=1<<i}return new IndexedNode(edit,bitmap,children)}function expand(edit,frag,child,bitmap,subNodes){let arr=[],bit=bitmap,count=0;for(let i=0;bit;++i){if(bit&1)arr[i]=subNodes[count++];bit>>>=1}return arr[frag]=child,new ArrayNode(edit,count+1,arr)}function mergeLeavesInner(edit,shift,h1,n1,h2,n2){if(h1===h2)return new CollisionNode(edit,h1,[n2,n1]);let subH1=hashFragment(shift,h1),subH2=hashFragment(shift,h2);if(subH1===subH2)return(child)=>new IndexedNode(edit,toBitmap(subH1)|toBitmap(subH2),[child]);else{let children=subH1<subH2?[n1,n2]:[n2,n1];return new IndexedNode(edit,toBitmap(subH1)|toBitmap(subH2),children)}}function mergeLeaves(edit,shift,h1,n1,h2,n2){let stack=void 0,currentShift=shift;while(!0){let res=mergeLeavesInner(edit,currentShift,h1,n1,h2,n2);if(typeof res==="function")stack=make5(res,stack),currentShift=currentShift+SIZE;else{let final=res;while(stack!=null)final=stack.value(final),stack=stack.previous;return final}}}var HashMapSymbolKey="effect/HashMap",HashMapTypeId=Symbol.for(HashMapSymbolKey),HashMapProto={[HashMapTypeId]:HashMapTypeId,[Symbol.iterator](){return new HashMapIterator(this,(k,v)=>[k,v])},[symbol](){let hash2=hash(HashMapSymbolKey);for(let item of this)hash2^=pipe(hash(item[0]),combine(hash(item[1])));return cached(this,hash2)},[symbol2](that){if(isHashMap(that)){if(that._size!==this._size)return!1;for(let item of this){let elem=pipe(that,getHash(item[0],hash(item[0])));if(isNone2(elem))return!1;else if(!equals(item[1],elem.value))return!1}return!0}return!1},toString(){return format(this.toJSON())},toJSON(){return{_id:"HashMap",values:Array.from(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}},makeImpl=(editable,edit,root,size)=>{let map5=Object.create(HashMapProto);return map5._editable=editable,map5._edit=edit,map5._root=root,map5._size=size,map5};class HashMapIterator{map;f;v;constructor(map5,f){this.map=map5,this.f=f,this.v=visitLazy(this.map._root,this.f,void 0)}next(){if(isNone2(this.v))return{done:!0,value:void 0};let v0=this.v.value;return this.v=applyCont(v0.cont),{done:!1,value:v0.value}}[Symbol.iterator](){return new HashMapIterator(this.map,this.f)}}var applyCont=(cont)=>cont?visitLazyChildren(cont[0],cont[1],cont[2],cont[3],cont[4]):none2(),visitLazy=(node,f,cont=void 0)=>{switch(node._tag){case"LeafNode":{if(isSome2(node.value))return some2({value:f(node.key,node.value.value),cont});return applyCont(cont)}case"CollisionNode":case"ArrayNode":case"IndexedNode":{let children=node.children;return visitLazyChildren(children.length,children,0,f,cont)}default:return applyCont(cont)}},visitLazyChildren=(len,children,i,f,cont)=>{while(i<len){let child=children[i++];if(child&&!isEmptyNode(child))return visitLazy(child,f,[len,children,i,f,cont])}return applyCont(cont)},_empty2=makeImpl(!1,0,new EmptyNode,0),empty3=()=>_empty2;var fromIterable3=(entries)=>{let map5=beginMutation(empty3());for(let entry of entries)set(map5,entry[0],entry[1]);return endMutation(map5)},isHashMap=(u)=>hasProperty(u,HashMapTypeId),isEmpty2=(self)=>self&&isEmptyNode(self._root),get3=dual(2,(self,key)=>getHash(self,key,hash(key))),getHash=dual(3,(self,key,hash2)=>{let node=self._root,shift=0;while(!0)switch(node._tag){case"LeafNode":return equals(key,node.key)?node.value:none2();case"CollisionNode":{if(hash2===node.hash){let children=node.children;for(let i=0,len=children.length;i<len;++i){let child=children[i];if("key"in child&&equals(key,child.key))return child.value}}return none2()}case"IndexedNode":{let frag=hashFragment(shift,hash2),bit=toBitmap(frag);if(node.mask&bit){node=node.children[fromBitmap(node.mask,bit)],shift+=SIZE;break}return none2()}case"ArrayNode":{if(node=node.children[hashFragment(shift,hash2)],node){shift+=SIZE;break}return none2()}default:return none2()}});var has=dual(2,(self,key)=>isSome2(getHash(self,key,hash(key))));var set=dual(3,(self,key,value)=>modifyAt(self,key,()=>some2(value))),setTree=dual(3,(self,newRoot,newSize)=>{if(self._editable)return self._root=newRoot,self._size=newSize,self;return newRoot===self._root?self:makeImpl(self._editable,self._edit,newRoot,newSize)}),keys=(self)=>new HashMapIterator(self,(key)=>key);var size=(self)=>self._size;var beginMutation=(self)=>makeImpl(!0,self._edit+1,self._root,self._size),endMutation=(self)=>{return self._editable=!1,self},mutate=dual(2,(self,f)=>{let transient=beginMutation(self);return f(transient),endMutation(transient)}),modifyAt=dual(3,(self,key,f)=>modifyHash(self,key,hash(key),f)),modifyHash=dual(4,(self,key,hash2,f)=>{let size2={value:self._size},newRoot=self._root.modify(self._editable?self._edit:NaN,0,f,hash2,key,size2);return pipe(self,setTree(newRoot,size2.value))});var remove2=dual(2,(self,key)=>modifyAt(self,key,none2));var map5=dual(2,(self,f)=>reduce3(self,empty3(),(map6,value,key)=>set(map6,key,f(value,key))));var forEach=dual(2,(self,f)=>reduce3(self,void 0,(_,value,key)=>f(value,key))),reduce3=dual(3,(self,zero,f)=>{let root=self._root;if(root._tag==="LeafNode")return isSome2(root.value)?f(zero,root.value.value,root.key):zero;if(root._tag==="EmptyNode")return zero;let toVisit=[root.children],children;while(children=toVisit.pop())for(let i=0,len=children.length;i<len;){let child=children[i++];if(child&&!isEmptyNode(child))if(child._tag==="LeafNode"){if(isSome2(child.value))zero=f(zero,child.value.value,child.key)}else toVisit.push(child.children)}return zero});var HashSetSymbolKey="effect/HashSet",HashSetTypeId=Symbol.for(HashSetSymbolKey),HashSetProto={[HashSetTypeId]:HashSetTypeId,[Symbol.iterator](){return keys(this._keyMap)},[symbol](){return cached(this,combine(hash(this._keyMap))(hash(HashSetSymbolKey)))},[symbol2](that){if(isHashSet(that))return size(this._keyMap)===size(that._keyMap)&&equals(this._keyMap,that._keyMap);return!1},toString(){return format(this.toJSON())},toJSON(){return{_id:"HashSet",values:Array.from(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}},makeImpl2=(keyMap)=>{let set2=Object.create(HashSetProto);return set2._keyMap=keyMap,set2},isHashSet=(u)=>hasProperty(u,HashSetTypeId),_empty3=makeImpl2(empty3()),empty4=()=>_empty3,fromIterable4=(elements)=>{let set2=beginMutation2(empty4());for(let value of elements)add(set2,value);return endMutation2(set2)},make6=(...elements)=>{let set2=beginMutation2(empty4());for(let value of elements)add(set2,value);return endMutation2(set2)},has2=dual(2,(self,value)=>has(self._keyMap,value));var size2=(self)=>size(self._keyMap),beginMutation2=(self)=>makeImpl2(beginMutation(self._keyMap)),endMutation2=(self)=>{return self._keyMap._editable=!1,self},mutate2=dual(2,(self,f)=>{let transient=beginMutation2(self);return f(transient),endMutation2(transient)}),add=dual(2,(self,value)=>self._keyMap._editable?(set(value,!0)(self._keyMap),self):makeImpl2(set(value,!0)(self._keyMap))),remove3=dual(2,(self,value)=>self._keyMap._editable?(remove2(value)(self._keyMap),self):makeImpl2(remove2(value)(self._keyMap))),difference2=dual(2,(self,that)=>mutate2(self,(set2)=>{for(let value of that)remove3(set2,value)}));var union2=dual(2,(self,that)=>mutate2(empty4(),(set2)=>{forEach2(self,(value)=>add(set2,value));for(let value of that)add(set2,value)}));var forEach2=dual(2,(self,f)=>forEach(self._keyMap,(_,k)=>f(k))),reduce4=dual(3,(self,zero,f)=>reduce3(self._keyMap,zero,(z,_,a)=>f(z,a)));var empty5=empty4,fromIterable5=fromIterable4,make7=make6,has3=has2;var size3=size2;var add2=add,remove4=remove3,difference3=difference2;var union3=union2;var forEach3=forEach2,reduce5=reduce4;var OP_DIE="Die",OP_EMPTY="Empty",OP_FAIL="Fail",OP_INTERRUPT="Interrupt",OP_PARALLEL="Parallel",OP_SEQUENTIAL="Sequential";var CauseSymbolKey="effect/Cause",CauseTypeId=Symbol.for(CauseSymbolKey),variance={_E:(_)=>_},proto={[CauseTypeId]:variance,[symbol](){return pipe(hash(CauseSymbolKey),combine(hash(flattenCause(this))),cached(this))},[symbol2](that){return isCause(that)&&causeEquals(this,that)},pipe(){return pipeArguments(this,arguments)},toJSON(){switch(this._tag){case"Empty":return{_id:"Cause",_tag:this._tag};case"Die":return{_id:"Cause",_tag:this._tag,defect:toJSON(this.defect)};case"Interrupt":return{_id:"Cause",_tag:this._tag,fiberId:this.fiberId.toJSON()};case"Fail":return{_id:"Cause",_tag:this._tag,failure:toJSON(this.error)};case"Sequential":case"Parallel":return{_id:"Cause",_tag:this._tag,left:toJSON(this.left),right:toJSON(this.right)}}},toString(){return pretty(this)},[NodeInspectSymbol](){return this.toJSON()}},empty6=(()=>{let o=Object.create(proto);return o._tag=OP_EMPTY,o})(),fail=(error)=>{let o=Object.create(proto);return o._tag=OP_FAIL,o.error=error,o},die=(defect)=>{let o=Object.create(proto);return o._tag=OP_DIE,o.defect=defect,o},interrupt=(fiberId)=>{let o=Object.create(proto);return o._tag=OP_INTERRUPT,o.fiberId=fiberId,o},parallel=(left3,right3)=>{let o=Object.create(proto);return o._tag=OP_PARALLEL,o.left=left3,o.right=right3,o},sequential=(left3,right3)=>{let o=Object.create(proto);return o._tag=OP_SEQUENTIAL,o.left=left3,o.right=right3,o},isCause=(u)=>hasProperty(u,CauseTypeId),isEmptyType=(self)=>self._tag===OP_EMPTY;var isDieType=(self)=>self._tag===OP_DIE;var isEmpty3=(self)=>{if(self._tag===OP_EMPTY)return!0;return reduce6(self,!0,(acc,cause)=>{switch(cause._tag){case OP_EMPTY:return some2(acc);case OP_DIE:case OP_FAIL:case OP_INTERRUPT:return some2(!1);default:return none2()}})};var isInterrupted=(self)=>isSome2(interruptOption(self)),isInterruptedOnly=(self)=>reduceWithContext(void 0,IsInterruptedOnlyCauseReducer)(self),failures=(self)=>reverse2(reduce6(self,empty2(),(list,cause)=>cause._tag===OP_FAIL?some2(pipe(list,prepend2(cause.error))):none2())),defects=(self)=>reverse2(reduce6(self,empty2(),(list,cause)=>cause._tag===OP_DIE?some2(pipe(list,prepend2(cause.defect))):none2())),interruptors=(self)=>reduce6(self,empty5(),(set2,cause)=>cause._tag===OP_INTERRUPT?some2(pipe(set2,add2(cause.fiberId))):none2()),failureOption=(self)=>find(self,(cause)=>cause._tag===OP_FAIL?some2(cause.error):none2()),failureOrCause=(self)=>{let option=failureOption(self);switch(option._tag){case"None":return right2(self);case"Some":return left2(option.value)}};var flipCauseOption=(self)=>match3(self,{onEmpty:some2(empty6),onFail:map2(fail),onDie:(defect)=>some2(die(defect)),onInterrupt:(fiberId)=>some2(interrupt(fiberId)),onSequential:mergeWith(sequential),onParallel:mergeWith(parallel)}),interruptOption=(self)=>find(self,(cause)=>cause._tag===OP_INTERRUPT?some2(cause.fiberId):none2()),keepDefects=(self)=>match3(self,{onEmpty:none2(),onFail:()=>none2(),onDie:(defect)=>some2(die(defect)),onInterrupt:()=>none2(),onSequential:mergeWith(sequential),onParallel:mergeWith(parallel)}),keepDefectsAndElectFailures=(self)=>match3(self,{onEmpty:none2(),onFail:(failure)=>some2(die(failure)),onDie:(defect)=>some2(die(defect)),onInterrupt:()=>none2(),onSequential:mergeWith(sequential),onParallel:mergeWith(parallel)});var stripFailures=(self)=>match3(self,{onEmpty:empty6,onFail:()=>empty6,onDie:die,onInterrupt:interrupt,onSequential:sequential,onParallel:parallel}),electFailures=(self)=>match3(self,{onEmpty:empty6,onFail:die,onDie:die,onInterrupt:interrupt,onSequential:sequential,onParallel:parallel});var map8=dual(2,(self,f)=>flatMap6(self,(e)=>fail(f(e)))),flatMap6=dual(2,(self,f)=>match3(self,{onEmpty:empty6,onFail:(error)=>f(error),onDie:(defect)=>die(defect),onInterrupt:(fiberId)=>interrupt(fiberId),onSequential:(left3,right3)=>sequential(left3,right3),onParallel:(left3,right3)=>parallel(left3,right3)})),flatten3=(self)=>flatMap6(self,identity);var causeEquals=(left3,right3)=>{let leftStack=of2(left3),rightStack=of2(right3);while(isNonEmpty(leftStack)&&isNonEmpty(rightStack)){let[leftParallel,leftSequential]=pipe(headNonEmpty2(leftStack),reduce6([empty5(),empty2()],([parallel2,sequential2],cause)=>{let[par,seq]=evaluateCause(cause);return some2([pipe(parallel2,union3(par)),pipe(sequential2,appendAll2(seq))])})),[rightParallel,rightSequential]=pipe(headNonEmpty2(rightStack),reduce6([empty5(),empty2()],([parallel2,sequential2],cause)=>{let[par,seq]=evaluateCause(cause);return some2([pipe(parallel2,union3(par)),pipe(sequential2,appendAll2(seq))])}));if(!equals(leftParallel,rightParallel))return!1;leftStack=leftSequential,rightStack=rightSequential}return!0},flattenCause=(cause)=>{return flattenCauseLoop(of2(cause),empty2())},flattenCauseLoop=(causes,flattened)=>{while(!0){let[parallel2,sequential2]=pipe(causes,reduce([empty5(),empty2()],([parallel3,sequential3],cause)=>{let[par,seq]=evaluateCause(cause);return[pipe(parallel3,union3(par)),pipe(sequential3,appendAll2(seq))]})),updated=size3(parallel2)>0?pipe(flattened,prepend2(parallel2)):flattened;if(isEmpty(sequential2))return reverse2(updated);causes=sequential2,flattened=updated}throw Error(getBugErrorMessage("Cause.flattenCauseLoop"))},find=dual(2,(self,pf)=>{let stack=[self];while(stack.length>0){let item=stack.pop(),option=pf(item);switch(option._tag){case"None":{switch(item._tag){case OP_SEQUENTIAL:case OP_PARALLEL:{stack.push(item.right),stack.push(item.left);break}}break}case"Some":return option}}return none2()});var evaluateCause=(self)=>{let cause=self,stack=[],_parallel=empty5(),_sequential=empty2();while(cause!==void 0)switch(cause._tag){case OP_EMPTY:{if(stack.length===0)return[_parallel,_sequential];cause=stack.pop();break}case OP_FAIL:{if(_parallel=add2(_parallel,make4(cause._tag,cause.error)),stack.length===0)return[_parallel,_sequential];cause=stack.pop();break}case OP_DIE:{if(_parallel=add2(_parallel,make4(cause._tag,cause.defect)),stack.length===0)return[_parallel,_sequential];cause=stack.pop();break}case OP_INTERRUPT:{if(_parallel=add2(_parallel,make4(cause._tag,cause.fiberId)),stack.length===0)return[_parallel,_sequential];cause=stack.pop();break}case OP_SEQUENTIAL:{switch(cause.left._tag){case OP_EMPTY:{cause=cause.right;break}case OP_SEQUENTIAL:{cause=sequential(cause.left.left,sequential(cause.left.right,cause.right));break}case OP_PARALLEL:{cause=parallel(sequential(cause.left.left,cause.right),sequential(cause.left.right,cause.right));break}default:{_sequential=prepend2(_sequential,cause.right),cause=cause.left;break}}break}case OP_PARALLEL:{stack.push(cause.right),cause=cause.left;break}}throw Error(getBugErrorMessage("Cause.evaluateCauseLoop"))};var IsInterruptedOnlyCauseReducer={emptyCase:constTrue,failCase:constFalse,dieCase:constFalse,interruptCase:constTrue,sequentialCase:(_,left3,right3)=>left3&&right3,parallelCase:(_,left3,right3)=>left3&&right3};var OP_SEQUENTIAL_CASE="SequentialCase",OP_PARALLEL_CASE="ParallelCase",match3=dual(2,(self,{onDie,onEmpty,onFail,onInterrupt,onParallel,onSequential})=>{return reduceWithContext(self,void 0,{emptyCase:()=>onEmpty,failCase:(_,error)=>onFail(error),dieCase:(_,defect)=>onDie(defect),interruptCase:(_,fiberId)=>onInterrupt(fiberId),sequentialCase:(_,left3,right3)=>onSequential(left3,right3),parallelCase:(_,left3,right3)=>onParallel(left3,right3)})}),reduce6=dual(3,(self,zero,pf)=>{let accumulator=zero,cause=self,causes=[];while(cause!==void 0){let option=pf(accumulator,cause);switch(accumulator=isSome2(option)?option.value:accumulator,cause._tag){case OP_SEQUENTIAL:{causes.push(cause.right),cause=cause.left;break}case OP_PARALLEL:{causes.push(cause.right),cause=cause.left;break}default:{cause=void 0;break}}if(cause===void 0&&causes.length>0)cause=causes.pop()}return accumulator}),reduceWithContext=dual(3,(self,context,reducer)=>{let input=[self],output=[];while(input.length>0){let cause=input.pop();switch(cause._tag){case OP_EMPTY:{output.push(right2(reducer.emptyCase(context)));break}case OP_FAIL:{output.push(right2(reducer.failCase(context,cause.error)));break}case OP_DIE:{output.push(right2(reducer.dieCase(context,cause.defect)));break}case OP_INTERRUPT:{output.push(right2(reducer.interruptCase(context,cause.fiberId)));break}case OP_SEQUENTIAL:{input.push(cause.right),input.push(cause.left),output.push(left2({_tag:OP_SEQUENTIAL_CASE}));break}case OP_PARALLEL:{input.push(cause.right),input.push(cause.left),output.push(left2({_tag:OP_PARALLEL_CASE}));break}}}let accumulator=[];while(output.length>0){let either=output.pop();switch(either._tag){case"Left":{switch(either.left._tag){case OP_SEQUENTIAL_CASE:{let left3=accumulator.pop(),right3=accumulator.pop(),value=reducer.sequentialCase(context,left3,right3);accumulator.push(value);break}case OP_PARALLEL_CASE:{let left3=accumulator.pop(),right3=accumulator.pop(),value=reducer.parallelCase(context,left3,right3);accumulator.push(value);break}}break}case"Right":{accumulator.push(either.right);break}}}if(accumulator.length===0)throw Error("BUG: Cause.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues");return accumulator.pop()}),pretty=(cause,options)=>{if(isInterruptedOnly(cause))return"All fibers interrupted without errors.";return prettyErrors(cause).map(function(e){if(options?.renderErrorCause!==!0||e.cause===void 0)return e.stack;return`${e.stack} {
8
8
  ${renderErrorCause(e.cause," ")}
9
9
  }`}).join(`
10
10
  `)},renderErrorCause=(cause,prefix)=>{let lines=cause.stack.split(`
@@ -20,7 +20,7 @@ ${prefix}}`;return stack};class PrettyError extends globalThis.Error{span=void 0
20
20
  `)}return error},isContext=(u)=>hasProperty(u,TypeId4),isTag=(u)=>hasProperty(u,TagTypeId),isReference=(u)=>hasProperty(u,ReferenceTypeId),_empty4=makeContext(new Map),empty7=()=>_empty4,make8=(tag,service)=>makeContext(new Map([[tag.key,service]])),add3=dual(3,(self,tag,service)=>{let map9=new Map(self.unsafeMap);return map9.set(tag.key,service),makeContext(map9)}),defaultValueCache=globalValue("effect/Context/defaultValueCache",()=>new Map),getDefaultValue=(tag)=>{if(defaultValueCache.has(tag.key))return defaultValueCache.get(tag.key);let value=tag.defaultValue();return defaultValueCache.set(tag.key,value),value},unsafeGetReference=(self,tag)=>{return self.unsafeMap.has(tag.key)?self.unsafeMap.get(tag.key):getDefaultValue(tag)},unsafeGet3=dual(2,(self,tag)=>{if(!self.unsafeMap.has(tag.key)){if(ReferenceTypeId in tag)return getDefaultValue(tag);throw serviceNotFoundError(tag)}return self.unsafeMap.get(tag.key)}),get4=unsafeGet3,getOrElse2=dual(3,(self,tag,orElse2)=>{if(!self.unsafeMap.has(tag.key))return isReference(tag)?getDefaultValue(tag):orElse2();return self.unsafeMap.get(tag.key)}),getOption=dual(2,(self,tag)=>{if(!self.unsafeMap.has(tag.key))return isReference(tag)?some(getDefaultValue(tag)):none;return some(self.unsafeMap.get(tag.key))}),merge2=dual(2,(self,that)=>{let map9=new Map(self.unsafeMap);for(let[tag,s]of that.unsafeMap)map9.set(tag,s);return makeContext(map9)}),mergeAll=(...ctxs)=>{let map9=new Map;for(let i=0;i<ctxs.length;i++)ctxs[i].unsafeMap.forEach((value,key)=>{map9.set(key,value)});return makeContext(map9)},pick=(...tags)=>(self)=>{let tagSet=new Set(tags.map((_)=>_.key)),newEnv=new Map;for(let[tag,s]of self.unsafeMap.entries())if(tagSet.has(tag))newEnv.set(tag,s);return makeContext(newEnv)},omit=(...tags)=>(self)=>{let newEnv=new Map(self.unsafeMap);for(let tag of tags)newEnv.delete(tag.key);return makeContext(newEnv)};var TagTypeId2=TagTypeId,ReferenceTypeId2=ReferenceTypeId,GenericTag=makeGenericTag;var unsafeMake=makeContext,isContext2=isContext,isTag2=isTag,isReference2=isReference,empty8=empty7,make9=make8,add4=add3,get5=get4,getOrElse3=getOrElse2,unsafeGet4=unsafeGet3,getOption2=getOption,merge3=merge2,mergeAll2=mergeAll,pick2=pick,omit2=omit,Tag2=Tag,Reference2=Reference;var exports_Duration={};__export(exports_Duration,{zero:()=>zero,weeks:()=>weeks,unsafeToNanos:()=>unsafeToNanos,unsafeFormatIso:()=>unsafeFormatIso,unsafeDivide:()=>unsafeDivide,toWeeks:()=>toWeeks,toSeconds:()=>toSeconds,toNanos:()=>toNanos,toMinutes:()=>toMinutes,toMillis:()=>toMillis,toHrTime:()=>toHrTime,toHours:()=>toHours,toDays:()=>toDays,times:()=>times,sum:()=>sum,subtract:()=>subtract,seconds:()=>seconds,parts:()=>parts,nanos:()=>nanos,minutes:()=>minutes,min:()=>min2,millis:()=>millis,micros:()=>micros,max:()=>max2,matchWith:()=>matchWith,match:()=>match4,lessThanOrEqualTo:()=>lessThanOrEqualTo,lessThan:()=>lessThan2,isZero:()=>isZero,isFinite:()=>isFinite,isDuration:()=>isDuration,infinity:()=>infinity,hours:()=>hours,greaterThanOrEqualTo:()=>greaterThanOrEqualTo,greaterThan:()=>greaterThan2,fromIso:()=>fromIso,formatIso:()=>formatIso,format:()=>format2,equals:()=>equals2,divide:()=>divide,decodeUnknown:()=>decodeUnknown,decode:()=>decode,days:()=>days,clamp:()=>clamp3,between:()=>between2,Order:()=>Order,Equivalence:()=>Equivalence});var TypeId5=Symbol.for("effect/Duration"),bigint0=BigInt(0),bigint24=BigInt(24),bigint60=BigInt(60),bigint1e3=BigInt(1000),bigint1e6=BigInt(1e6),bigint1e9=BigInt(1e9),DURATION_REGEX=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,decode=(input)=>{if(isDuration(input))return input;else if(isNumber(input))return millis(input);else if(isBigInt(input))return nanos(input);else if(Array.isArray(input)&&input.length===2&&input.every(isNumber)){if(input[0]===-1/0||input[1]===-1/0||Number.isNaN(input[0])||Number.isNaN(input[1]))return zero;if(input[0]===1/0||input[1]===1/0)return infinity;return nanos(BigInt(Math.round(input[0]*1e9))+BigInt(Math.round(input[1])))}else if(isString(input)){let match4=DURATION_REGEX.exec(input);if(match4){let[_,valueStr,unit]=match4,value=Number(valueStr);switch(unit){case"nano":case"nanos":return nanos(BigInt(valueStr));case"micro":case"micros":return micros(BigInt(valueStr));case"milli":case"millis":return millis(value);case"second":case"seconds":return seconds(value);case"minute":case"minutes":return minutes(value);case"hour":case"hours":return hours(value);case"day":case"days":return days(value);case"week":case"weeks":return weeks(value)}}}throw Error("Invalid DurationInput")},decodeUnknown=liftThrowable(decode),zeroValue={_tag:"Millis",millis:0},infinityValue={_tag:"Infinity"},DurationProto={[TypeId5]:TypeId5,[symbol](){return cached(this,structure(this.value))},[symbol2](that){return isDuration(that)&&equals2(this,that)},toString(){return`Duration(${format2(this)})`},toJSON(){switch(this.value._tag){case"Millis":return{_id:"Duration",_tag:"Millis",millis:this.value.millis};case"Nanos":return{_id:"Duration",_tag:"Nanos",hrtime:toHrTime(this)};case"Infinity":return{_id:"Duration",_tag:"Infinity"}}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}},make10=(input)=>{let duration=Object.create(DurationProto);if(isNumber(input))if(isNaN(input)||input<=0)duration.value=zeroValue;else if(!Number.isFinite(input))duration.value=infinityValue;else if(!Number.isInteger(input))duration.value={_tag:"Nanos",nanos:BigInt(Math.round(input*1e6))};else duration.value={_tag:"Millis",millis:input};else if(input<=bigint0)duration.value=zeroValue;else duration.value={_tag:"Nanos",nanos:input};return duration},isDuration=(u)=>hasProperty(u,TypeId5),isFinite=(self)=>self.value._tag!=="Infinity",isZero=(self)=>{switch(self.value._tag){case"Millis":return self.value.millis===0;case"Nanos":return self.value.nanos===bigint0;case"Infinity":return!1}},zero=make10(0),infinity=make10(1/0),nanos=(nanos2)=>make10(nanos2),micros=(micros2)=>make10(micros2*bigint1e3),millis=(millis2)=>make10(millis2),seconds=(seconds2)=>make10(seconds2*1000),minutes=(minutes2)=>make10(minutes2*60000),hours=(hours2)=>make10(hours2*3600000),days=(days2)=>make10(days2*86400000),weeks=(weeks2)=>make10(weeks2*604800000),toMillis=(self)=>match4(self,{onMillis:(millis2)=>millis2,onNanos:(nanos2)=>Number(nanos2)/1e6}),toSeconds=(self)=>match4(self,{onMillis:(millis2)=>millis2/1000,onNanos:(nanos2)=>Number(nanos2)/1e9}),toMinutes=(self)=>match4(self,{onMillis:(millis2)=>millis2/60000,onNanos:(nanos2)=>Number(nanos2)/60000000000}),toHours=(self)=>match4(self,{onMillis:(millis2)=>millis2/3600000,onNanos:(nanos2)=>Number(nanos2)/3600000000000}),toDays=(self)=>match4(self,{onMillis:(millis2)=>millis2/86400000,onNanos:(nanos2)=>Number(nanos2)/86400000000000}),toWeeks=(self)=>match4(self,{onMillis:(millis2)=>millis2/604800000,onNanos:(nanos2)=>Number(nanos2)/604800000000000}),toNanos=(self)=>{let _self=decode(self);switch(_self.value._tag){case"Infinity":return none2();case"Nanos":return some2(_self.value.nanos);case"Millis":return some2(BigInt(Math.round(_self.value.millis*1e6)))}},unsafeToNanos=(self)=>{let _self=decode(self);switch(_self.value._tag){case"Infinity":throw Error("Cannot convert infinite duration to nanos");case"Nanos":return _self.value.nanos;case"Millis":return BigInt(Math.round(_self.value.millis*1e6))}},toHrTime=(self)=>{let _self=decode(self);switch(_self.value._tag){case"Infinity":return[1/0,0];case"Nanos":return[Number(_self.value.nanos/bigint1e9),Number(_self.value.nanos%bigint1e9)];case"Millis":return[Math.floor(_self.value.millis/1000),Math.round(_self.value.millis%1000*1e6)]}},match4=dual(2,(self,options)=>{let _self=decode(self);switch(_self.value._tag){case"Nanos":return options.onNanos(_self.value.nanos);case"Infinity":return options.onMillis(1/0);case"Millis":return options.onMillis(_self.value.millis)}}),matchWith=dual(3,(self,that,options)=>{let _self=decode(self),_that=decode(that);if(_self.value._tag==="Infinity"||_that.value._tag==="Infinity")return options.onMillis(toMillis(_self),toMillis(_that));else if(_self.value._tag==="Nanos"||_that.value._tag==="Nanos"){let selfNanos=_self.value._tag==="Nanos"?_self.value.nanos:BigInt(Math.round(_self.value.millis*1e6)),thatNanos=_that.value._tag==="Nanos"?_that.value.nanos:BigInt(Math.round(_that.value.millis*1e6));return options.onNanos(selfNanos,thatNanos)}return options.onMillis(_self.value.millis,_that.value.millis)}),Order=make2((self,that)=>matchWith(self,that,{onMillis:(self2,that2)=>self2<that2?-1:self2>that2?1:0,onNanos:(self2,that2)=>self2<that2?-1:self2>that2?1:0})),between2=between(mapInput2(Order,decode)),Equivalence=(self,that)=>matchWith(self,that,{onMillis:(self2,that2)=>self2===that2,onNanos:(self2,that2)=>self2===that2}),_min=min(Order),min2=dual(2,(self,that)=>_min(decode(self),decode(that))),_max=max(Order),max2=dual(2,(self,that)=>_max(decode(self),decode(that))),_clamp=clamp(Order),clamp3=dual(2,(self,options)=>_clamp(decode(self),{minimum:decode(options.minimum),maximum:decode(options.maximum)})),divide=dual(2,(self,by)=>match4(self,{onMillis:(millis2)=>{if(by===0||isNaN(by)||!Number.isFinite(by))return none2();return some2(make10(millis2/by))},onNanos:(nanos2)=>{if(isNaN(by)||by<=0||!Number.isFinite(by))return none2();try{return some2(make10(nanos2/BigInt(by)))}catch{return none2()}}})),unsafeDivide=dual(2,(self,by)=>match4(self,{onMillis:(millis2)=>make10(millis2/by),onNanos:(nanos2)=>{if(isNaN(by)||by<0||Object.is(by,-0))return zero;else if(Object.is(by,0)||!Number.isFinite(by))return infinity;return make10(nanos2/BigInt(by))}})),times=dual(2,(self,times2)=>match4(self,{onMillis:(millis2)=>make10(millis2*times2),onNanos:(nanos2)=>make10(nanos2*BigInt(times2))})),subtract=dual(2,(self,that)=>matchWith(self,that,{onMillis:(self2,that2)=>make10(self2-that2),onNanos:(self2,that2)=>make10(self2-that2)})),sum=dual(2,(self,that)=>matchWith(self,that,{onMillis:(self2,that2)=>make10(self2+that2),onNanos:(self2,that2)=>make10(self2+that2)})),lessThan2=dual(2,(self,that)=>matchWith(self,that,{onMillis:(self2,that2)=>self2<that2,onNanos:(self2,that2)=>self2<that2})),lessThanOrEqualTo=dual(2,(self,that)=>matchWith(self,that,{onMillis:(self2,that2)=>self2<=that2,onNanos:(self2,that2)=>self2<=that2})),greaterThan2=dual(2,(self,that)=>matchWith(self,that,{onMillis:(self2,that2)=>self2>that2,onNanos:(self2,that2)=>self2>that2})),greaterThanOrEqualTo=dual(2,(self,that)=>matchWith(self,that,{onMillis:(self2,that2)=>self2>=that2,onNanos:(self2,that2)=>self2>=that2})),equals2=dual(2,(self,that)=>Equivalence(decode(self),decode(that))),parts=(self)=>{let duration=decode(self);if(duration.value._tag==="Infinity")return{days:1/0,hours:1/0,minutes:1/0,seconds:1/0,millis:1/0,nanos:1/0};let nanos2=unsafeToNanos(duration),ms=nanos2/bigint1e6,sec=ms/bigint1e3,min3=sec/bigint60,hr=min3/bigint60,days2=hr/bigint24;return{days:Number(days2),hours:Number(hr%bigint24),minutes:Number(min3%bigint60),seconds:Number(sec%bigint60),millis:Number(ms%bigint1e3),nanos:Number(nanos2%bigint1e6)}},format2=(self)=>{let duration=decode(self);if(duration.value._tag==="Infinity")return"Infinity";if(isZero(duration))return"0";let fragments=parts(duration),pieces=[];if(fragments.days!==0)pieces.push(`${fragments.days}d`);if(fragments.hours!==0)pieces.push(`${fragments.hours}h`);if(fragments.minutes!==0)pieces.push(`${fragments.minutes}m`);if(fragments.seconds!==0)pieces.push(`${fragments.seconds}s`);if(fragments.millis!==0)pieces.push(`${fragments.millis}ms`);if(fragments.nanos!==0)pieces.push(`${fragments.nanos}ns`);return pieces.join(" ")},unsafeFormatIso=(self)=>{let duration=decode(self);if(!isFinite(duration))throw RangeError("Cannot format infinite duration");let fragments=[],{days:days2,hours:hours2,millis:millis2,minutes:minutes2,nanos:nanos2,seconds:seconds2}=parts(duration),rest=days2;if(rest>=365){let years=Math.floor(rest/365);rest%=365,fragments.push(`${years}Y`)}if(rest>=30){let months=Math.floor(rest/30);rest%=30,fragments.push(`${months}M`)}if(rest>=7){let weeks2=Math.floor(rest/7);rest%=7,fragments.push(`${weeks2}W`)}if(rest>0)fragments.push(`${rest}D`);if(hours2!==0||minutes2!==0||seconds2!==0||millis2!==0||nanos2!==0){if(fragments.push("T"),hours2!==0)fragments.push(`${hours2}H`);if(minutes2!==0)fragments.push(`${minutes2}M`);if(seconds2!==0||millis2!==0||nanos2!==0){let total=BigInt(seconds2)*bigint1e9+BigInt(millis2)*bigint1e6+BigInt(nanos2),str=(Number(total)/1e9).toFixed(9).replace(/\.?0+$/,"");fragments.push(`${str}S`)}}return`P${fragments.join("")||"T0S"}`},formatIso=(self)=>{let duration=decode(self);return isFinite(duration)?some2(unsafeFormatIso(duration)):none2()},fromIso=(iso)=>{let result=DURATION_ISO_REGEX.exec(iso);if(result==null)return none2();let[years,months,weeks2,days2,hours2,mins,secs]=result.slice(1,8).map((_)=>_?Number(_):0),value=years*365*24*60*60+months*30*24*60*60+weeks2*7*24*60*60+days2*24*60*60+hours2*60*60+mins*60+secs;return some2(seconds(value))},DURATION_ISO_REGEX=/^P(?!$)(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?(?:T(?!$)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$/;var TypeId6=Symbol.for("effect/MutableRef"),MutableRefProto={[TypeId6]:TypeId6,toString(){return format(this.toJSON())},toJSON(){return{_id:"MutableRef",current:toJSON(this.current)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}},make11=(value)=>{let ref=Object.create(MutableRefProto);return ref.current=value,ref},compareAndSet=dual(3,(self,oldValue,newValue)=>{if(equals(oldValue,self.current))return self.current=newValue,!0;return!1});var get6=(self)=>self.current;var set2=dual(2,(self,value)=>{return self.current=value,self});var FiberIdSymbolKey="effect/FiberId",FiberIdTypeId=Symbol.for(FiberIdSymbolKey),OP_NONE="None",OP_RUNTIME="Runtime",OP_COMPOSITE="Composite",emptyHash=string(`${FiberIdSymbolKey}-${OP_NONE}`);class None{[FiberIdTypeId]=FiberIdTypeId;_tag=OP_NONE;id=-1;startTimeMillis=-1;[symbol](){return emptyHash}[symbol2](that){return isFiberId(that)&&that._tag===OP_NONE}toString(){return format(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag}}[NodeInspectSymbol](){return this.toJSON()}}class Runtime{id;startTimeMillis;[FiberIdTypeId]=FiberIdTypeId;_tag=OP_RUNTIME;constructor(id,startTimeMillis){this.id=id,this.startTimeMillis=startTimeMillis}[symbol](){return cached(this,string(`${FiberIdSymbolKey}-${this._tag}-${this.id}-${this.startTimeMillis}`))}[symbol2](that){return isFiberId(that)&&that._tag===OP_RUNTIME&&this.id===that.id&&this.startTimeMillis===that.startTimeMillis}toString(){return format(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag,id:this.id,startTimeMillis:this.startTimeMillis}}[NodeInspectSymbol](){return this.toJSON()}}class Composite{left;right;[FiberIdTypeId]=FiberIdTypeId;_tag=OP_COMPOSITE;constructor(left3,right3){this.left=left3,this.right=right3}_hash;[symbol](){return pipe(string(`${FiberIdSymbolKey}-${this._tag}`),combine(hash(this.left)),combine(hash(this.right)),cached(this))}[symbol2](that){return isFiberId(that)&&that._tag===OP_COMPOSITE&&equals(this.left,that.left)&&equals(this.right,that.right)}toString(){return format(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag,left:toJSON(this.left),right:toJSON(this.right)}}[NodeInspectSymbol](){return this.toJSON()}}var none3=new None;var isFiberId=(self)=>hasProperty(self,FiberIdTypeId);var combine2=dual(2,(self,that)=>{if(self._tag===OP_NONE)return that;if(that._tag===OP_NONE)return self;return new Composite(self,that)}),combineAll=(fiberIds)=>{return pipe(fiberIds,reduce5(none3,(a,b)=>combine2(b)(a)))};var ids=(self)=>{switch(self._tag){case OP_NONE:return empty5();case OP_RUNTIME:return make7(self.id);case OP_COMPOSITE:return pipe(ids(self.left),union3(ids(self.right)))}},_fiberCounter=globalValue(Symbol.for("effect/Fiber/Id/_fiberCounter"),()=>make11(0));var threadName=(self)=>{return Array.from(ids(self)).map((n)=>`#${n}`).join(",")};var unsafeMake2=()=>{let id=get6(_fiberCounter);return pipe(_fiberCounter,set2(id+1)),new Runtime(id,Date.now())};var none4=none3;var combine3=combine2,combineAll2=combineAll;var ids2=ids;var threadName2=threadName;var unsafeMake3=unsafeMake2;var empty9=empty3;var fromIterable6=fromIterable3,isEmpty4=isEmpty2,get7=get3;var set3=set,keys2=keys;var size4=size;var mutate3=mutate,modifyAt2=modifyAt;var map9=map5;var forEach4=forEach,reduce7=reduce3;var TypeId7=Symbol.for("effect/List"),toArray3=(self)=>fromIterable(self),getEquivalence3=(isEquivalent)=>mapInput(getEquivalence(isEquivalent),toArray3),_equivalence4=getEquivalence3(equals),ConsProto={[TypeId7]:TypeId7,_tag:"Cons",toString(){return format(this.toJSON())},toJSON(){return{_id:"List",_tag:"Cons",values:toArray3(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},[symbol2](that){return isList(that)&&this._tag===that._tag&&_equivalence4(this,that)},[symbol](){return cached(this,array2(toArray3(this)))},[Symbol.iterator](){let done=!1,self=this;return{next(){if(done)return this.return();if(self._tag==="Nil")return done=!0,this.return();let value=self.head;return self=self.tail,{done,value}},return(value){if(!done)done=!0;return{done:!0,value}}}},pipe(){return pipeArguments(this,arguments)}},makeCons=(head3,tail)=>{let cons=Object.create(ConsProto);return cons.head=head3,cons.tail=tail,cons},NilHash=string("Nil"),NilProto={[TypeId7]:TypeId7,_tag:"Nil",toString(){return format(this.toJSON())},toJSON(){return{_id:"List",_tag:"Nil"}},[NodeInspectSymbol](){return this.toJSON()},[symbol](){return NilHash},[symbol2](that){return isList(that)&&this._tag===that._tag},[Symbol.iterator](){return{next(){return{done:!0,value:void 0}}}},pipe(){return pipeArguments(this,arguments)}},_Nil=Object.create(NilProto),isList=(u)=>hasProperty(u,TypeId7),isNil=(self)=>self._tag==="Nil",isCons=(self)=>self._tag==="Cons";var nil=()=>_Nil,cons=(head3,tail)=>makeCons(head3,tail),empty10=nil,of3=(value)=>makeCons(value,_Nil);var appendAll3=dual(2,(self,that)=>prependAll(that,self)),prepend3=dual(2,(self,element)=>cons(element,self)),prependAll=dual(2,(self,prefix)=>{if(isNil(self))return prefix;else if(isNil(prefix))return self;else{let result=makeCons(prefix.head,self),curr=result,that=prefix.tail;while(!isNil(that)){let temp=makeCons(that.head,self);curr.tail=temp,curr=temp,that=that.tail}return result}});var reduce8=dual(3,(self,zero2,f)=>{let acc=zero2,these=self;while(!isNil(these))acc=f(acc,these.head),these=these.tail;return acc});var reverse3=(self)=>{let result=empty10(),these=self;while(!isNil(these))result=prepend3(result,these.head),these=these.tail;return result};var ArrayProto=Object.assign(Object.create(Array.prototype),{[symbol](){return cached(this,array2(this))},[symbol2](that){if(Array.isArray(that)&&this.length===that.length)return this.every((v,i)=>equals(v,that[i]));else return!1}}),Structural=function(){function Structural2(args){if(args)Object.assign(this,args)}return Structural2.prototype=StructuralPrototype,Structural2}(),struct=(as)=>Object.assign(Object.create(StructuralPrototype),as);var ContextPatchTypeId=Symbol.for("effect/DifferContextPatch");function variance2(a){return a}var PatchProto={...Structural.prototype,[ContextPatchTypeId]:{_Value:variance2,_Patch:variance2}},EmptyProto=Object.assign(Object.create(PatchProto),{_tag:"Empty"}),_empty5=Object.create(EmptyProto),empty11=()=>_empty5,AndThenProto=Object.assign(Object.create(PatchProto),{_tag:"AndThen"}),makeAndThen=(first,second)=>{let o=Object.create(AndThenProto);return o.first=first,o.second=second,o},AddServiceProto=Object.assign(Object.create(PatchProto),{_tag:"AddService"}),makeAddService=(key,service)=>{let o=Object.create(AddServiceProto);return o.key=key,o.service=service,o},RemoveServiceProto=Object.assign(Object.create(PatchProto),{_tag:"RemoveService"}),makeRemoveService=(key)=>{let o=Object.create(RemoveServiceProto);return o.key=key,o},UpdateServiceProto=Object.assign(Object.create(PatchProto),{_tag:"UpdateService"}),makeUpdateService=(key,update)=>{let o=Object.create(UpdateServiceProto);return o.key=key,o.update=update,o},diff=(oldValue,newValue)=>{let missingServices=new Map(oldValue.unsafeMap),patch=empty11();for(let[tag,newService]of newValue.unsafeMap.entries())if(missingServices.has(tag)){let old=missingServices.get(tag);if(missingServices.delete(tag),!equals(old,newService))patch=combine4(makeUpdateService(tag,()=>newService))(patch)}else missingServices.delete(tag),patch=combine4(makeAddService(tag,newService))(patch);for(let[tag]of missingServices.entries())patch=combine4(makeRemoveService(tag))(patch);return patch},combine4=dual(2,(self,that)=>makeAndThen(self,that)),patch=dual(2,(self,context)=>{if(self._tag==="Empty")return context;let wasServiceUpdated=!1,patches=of2(self),updatedContext=new Map(context.unsafeMap);while(isNonEmpty(patches)){let head3=headNonEmpty2(patches),tail=tailNonEmpty2(patches);switch(head3._tag){case"Empty":{patches=tail;break}case"AddService":{updatedContext.set(head3.key,head3.service),patches=tail;break}case"AndThen":{patches=prepend2(prepend2(tail,head3.second),head3.first);break}case"RemoveService":{updatedContext.delete(head3.key),patches=tail;break}case"UpdateService":{updatedContext.set(head3.key,head3.update(updatedContext.get(head3.key))),wasServiceUpdated=!0,patches=tail;break}}}if(!wasServiceUpdated)return makeContext(updatedContext);let map10=new Map;for(let[tag]of context.unsafeMap)if(updatedContext.has(tag))map10.set(tag,updatedContext.get(tag)),updatedContext.delete(tag);for(let[tag,s]of updatedContext)map10.set(tag,s);return makeContext(map10)});var HashSetPatchTypeId=Symbol.for("effect/DifferHashSetPatch");function variance3(a){return a}var PatchProto2={...Structural.prototype,[HashSetPatchTypeId]:{_Value:variance3,_Key:variance3,_Patch:variance3}},EmptyProto2=Object.assign(Object.create(PatchProto2),{_tag:"Empty"}),_empty6=Object.create(EmptyProto2),empty12=()=>_empty6,AndThenProto2=Object.assign(Object.create(PatchProto2),{_tag:"AndThen"}),makeAndThen2=(first,second)=>{let o=Object.create(AndThenProto2);return o.first=first,o.second=second,o},AddProto=Object.assign(Object.create(PatchProto2),{_tag:"Add"}),makeAdd=(value)=>{let o=Object.create(AddProto);return o.value=value,o},RemoveProto=Object.assign(Object.create(PatchProto2),{_tag:"Remove"}),makeRemove=(value)=>{let o=Object.create(RemoveProto);return o.value=value,o},diff2=(oldValue,newValue)=>{let[removed,patch2]=reduce5([oldValue,empty12()],([set4,patch3],value)=>{if(has3(value)(set4))return[remove4(value)(set4),patch3];return[set4,combine5(makeAdd(value))(patch3)]})(newValue);return reduce5(patch2,(patch3,value)=>combine5(makeRemove(value))(patch3))(removed)},combine5=dual(2,(self,that)=>makeAndThen2(self,that)),patch2=dual(2,(self,oldValue)=>{if(self._tag==="Empty")return oldValue;let set4=oldValue,patches=of2(self);while(isNonEmpty(patches)){let head3=headNonEmpty2(patches),tail=tailNonEmpty2(patches);switch(head3._tag){case"Empty":{patches=tail;break}case"AndThen":{patches=prepend2(head3.first)(prepend2(head3.second)(tail));break}case"Add":{set4=add2(head3.value)(set4),patches=tail;break}case"Remove":set4=remove4(head3.value)(set4),patches=tail}}return set4});var ReadonlyArrayPatchTypeId=Symbol.for("effect/DifferReadonlyArrayPatch");function variance4(a){return a}var PatchProto3={...Structural.prototype,[ReadonlyArrayPatchTypeId]:{_Value:variance4,_Patch:variance4}},EmptyProto3=Object.assign(Object.create(PatchProto3),{_tag:"Empty"}),_empty7=Object.create(EmptyProto3),empty13=()=>_empty7,AndThenProto3=Object.assign(Object.create(PatchProto3),{_tag:"AndThen"}),makeAndThen3=(first,second)=>{let o=Object.create(AndThenProto3);return o.first=first,o.second=second,o},AppendProto=Object.assign(Object.create(PatchProto3),{_tag:"Append"}),makeAppend=(values3)=>{let o=Object.create(AppendProto);return o.values=values3,o},SliceProto=Object.assign(Object.create(PatchProto3),{_tag:"Slice"}),makeSlice=(from,until)=>{let o=Object.create(SliceProto);return o.from=from,o.until=until,o},UpdateProto=Object.assign(Object.create(PatchProto3),{_tag:"Update"}),makeUpdate=(index,patch3)=>{let o=Object.create(UpdateProto);return o.index=index,o.patch=patch3,o},diff3=(options)=>{let i=0,patch3=empty13();while(i<options.oldValue.length&&i<options.newValue.length){let oldElement=options.oldValue[i],newElement=options.newValue[i],valuePatch=options.differ.diff(oldElement,newElement);if(!equals(valuePatch,options.differ.empty))patch3=combine6(patch3,makeUpdate(i,valuePatch));i=i+1}if(i<options.oldValue.length)patch3=combine6(patch3,makeSlice(0,i));if(i<options.newValue.length)patch3=combine6(patch3,makeAppend(drop(i)(options.newValue)));return patch3},combine6=dual(2,(self,that)=>makeAndThen3(self,that)),patch3=dual(3,(self,oldValue,differ)=>{if(self._tag==="Empty")return oldValue;let readonlyArray=oldValue.slice(),patches=of(self);while(isNonEmptyArray2(patches)){let head3=headNonEmpty(patches),tail=tailNonEmpty(patches);switch(head3._tag){case"Empty":{patches=tail;break}case"AndThen":{tail.unshift(head3.first,head3.second),patches=tail;break}case"Append":{for(let value of head3.values)readonlyArray.push(value);patches=tail;break}case"Slice":{readonlyArray=readonlyArray.slice(head3.from,head3.until),patches=tail;break}case"Update":{readonlyArray[head3.index]=differ.patch(head3.patch,readonlyArray[head3.index]),patches=tail;break}}}return readonlyArray});var DifferTypeId=Symbol.for("effect/Differ"),DifferProto={[DifferTypeId]:{_P:identity,_V:identity},pipe(){return pipeArguments(this,arguments)}},make14=(params)=>{let differ=Object.create(DifferProto);return differ.empty=params.empty,differ.diff=params.diff,differ.combine=params.combine,differ.patch=params.patch,differ},environment=()=>make14({empty:empty11(),combine:(first,second)=>combine4(second)(first),diff:(oldValue,newValue)=>diff(oldValue,newValue),patch:(patch4,oldValue)=>patch(oldValue)(patch4)});var hashSet=()=>make14({empty:empty12(),combine:(first,second)=>combine5(second)(first),diff:(oldValue,newValue)=>diff2(oldValue,newValue),patch:(patch4,oldValue)=>patch2(oldValue)(patch4)});var readonlyArray=(differ)=>make14({empty:empty13(),combine:(first,second)=>combine6(first,second),diff:(oldValue,newValue)=>diff3({oldValue,newValue,differ}),patch:(patch4,oldValue)=>patch3(patch4,oldValue,differ)});var update=()=>updateWith((_,a)=>a),updateWith=(f)=>make14({empty:identity,combine:(first,second)=>{if(first===identity)return second;if(second===identity)return first;return(a)=>second(first(a))},diff:(oldValue,newValue)=>{if(equals(oldValue,newValue))return identity;return constant(newValue)},patch:(patch4,oldValue)=>f(oldValue,patch4(oldValue))});var BIT_MASK=255,BIT_SHIFT=8,active=(patch4)=>patch4&BIT_MASK,enabled=(patch4)=>patch4>>BIT_SHIFT&BIT_MASK,make15=(active2,enabled2)=>(active2&BIT_MASK)+((enabled2&active2&BIT_MASK)<<BIT_SHIFT),empty14=make15(0,0),enable=(flag)=>make15(flag,flag),disable=(flag)=>make15(flag,0);var exclude=dual(2,(self,flag)=>make15(active(self)&~flag,enabled(self)));var andThen=dual(2,(self,that)=>self|that);var invert=(n)=>~n>>>0&BIT_MASK;var None2=0,Interruption=1,OpSupervision=2,RuntimeMetrics=4,WindDown=16,CooperativeYielding=32;var cooperativeYielding=(self)=>isEnabled(self,CooperativeYielding),disable2=dual(2,(self,flag)=>self&~flag);var enable2=dual(2,(self,flag)=>self|flag);var interruptible=(self)=>interruption(self)&&!windDown(self),interruption=(self)=>isEnabled(self,Interruption);var isEnabled=dual(2,(self,flag)=>(self&flag)!==0),make16=(...flags)=>flags.reduce((a,b)=>a|b,0),none5=make16(None2);var runtimeMetrics=(self)=>isEnabled(self,RuntimeMetrics);var windDown=(self)=>isEnabled(self,WindDown);var diff4=dual(2,(self,that)=>make15(self^that,that)),patch4=dual(2,(self,patch5)=>self&(invert(active(patch5))|enabled(patch5))|active(patch5)&enabled(patch5));var differ=make14({empty:empty14,diff:(oldValue,newValue)=>diff4(oldValue,newValue),combine:(first,second)=>andThen(second)(first),patch:(_patch,oldValue)=>patch4(oldValue,_patch)});var empty15=empty14;var enable3=enable,disable3=disable;var exclude2=exclude;var empty16={_tag:"Empty"},par=(self,that)=>({_tag:"Par",left:self,right:that}),seq=(self,that)=>({_tag:"Seq",left:self,right:that}),single=(dataSource,blockedRequest)=>({_tag:"Single",dataSource,blockedRequest});var flatten4=(self)=>{let current=of3(self),updated=empty10();while(!0){let[parallel2,sequential2]=reduce8(current,[parallelCollectionEmpty(),empty10()],([parallel3,sequential3],blockedRequest)=>{let[par2,seq2]=step(blockedRequest);return[parallelCollectionCombine(parallel3,par2),appendAll3(sequential3,seq2)]});if(updated=merge4(updated,parallel2),isNil(sequential2))return reverse3(updated);current=sequential2}throw Error("BUG: BlockedRequests.flatten - please report an issue at https://github.com/Effect-TS/effect/issues")},step=(requests)=>{let current=requests,parallel2=parallelCollectionEmpty(),stack=empty10(),sequential2=empty10();while(!0)switch(current._tag){case"Empty":{if(isNil(stack))return[parallel2,sequential2];current=stack.head,stack=stack.tail;break}case"Par":{stack=cons(current.right,stack),current=current.left;break}case"Seq":{let{left:left3,right:right3}=current;switch(left3._tag){case"Empty":{current=right3;break}case"Par":{let{left:l,right:r}=left3;current=par(seq(l,right3),seq(r,right3));break}case"Seq":{let{left:l,right:r}=left3;current=seq(l,seq(r,right3));break}case"Single":{current=left3,sequential2=cons(right3,sequential2);break}}break}case"Single":{if(parallel2=parallelCollectionAdd(parallel2,current),isNil(stack))return[parallel2,sequential2];current=stack.head,stack=stack.tail;break}}throw Error("BUG: BlockedRequests.step - please report an issue at https://github.com/Effect-TS/effect/issues")},merge4=(sequential2,parallel2)=>{if(isNil(sequential2))return of3(parallelCollectionToSequentialCollection(parallel2));if(parallelCollectionIsEmpty(parallel2))return sequential2;let seqHeadKeys=sequentialCollectionKeys(sequential2.head),parKeys=parallelCollectionKeys(parallel2);if(seqHeadKeys.length===1&&parKeys.length===1&&equals(seqHeadKeys[0],parKeys[0]))return cons(sequentialCollectionCombine(sequential2.head,parallelCollectionToSequentialCollection(parallel2)),sequential2.tail);return cons(parallelCollectionToSequentialCollection(parallel2),sequential2)},EntryTypeId=Symbol.for("effect/RequestBlock/Entry");class EntryImpl{request;result;listeners;ownerId;state;[EntryTypeId]=blockedRequestVariance;constructor(request,result,listeners,ownerId,state){this.request=request,this.result=result,this.listeners=listeners,this.ownerId=ownerId,this.state=state}}var blockedRequestVariance={_R:(_)=>_};var makeEntry=(options)=>new EntryImpl(options.request,options.result,options.listeners,options.ownerId,options.state),RequestBlockParallelTypeId=Symbol.for("effect/RequestBlock/RequestBlockParallel"),parallelVariance={_R:(_)=>_};class ParallelImpl{map;[RequestBlockParallelTypeId]=parallelVariance;constructor(map10){this.map=map10}}var parallelCollectionEmpty=()=>new ParallelImpl(empty9());var parallelCollectionAdd=(self,blockedRequest)=>new ParallelImpl(modifyAt2(self.map,blockedRequest.dataSource,(_)=>orElseSome(map2(_,append2(blockedRequest.blockedRequest)),()=>of2(blockedRequest.blockedRequest)))),parallelCollectionCombine=(self,that)=>new ParallelImpl(reduce7(self.map,that.map,(map10,value,key)=>set3(map10,key,match2(get7(map10,key),{onNone:()=>value,onSome:(other)=>appendAll2(value,other)})))),parallelCollectionIsEmpty=(self)=>isEmpty4(self.map),parallelCollectionKeys=(self)=>Array.from(keys2(self.map)),parallelCollectionToSequentialCollection=(self)=>sequentialCollectionMake(map9(self.map,(x)=>of2(x))),SequentialCollectionTypeId=Symbol.for("effect/RequestBlock/RequestBlockSequential"),sequentialVariance={_R:(_)=>_};class SequentialImpl{map;[SequentialCollectionTypeId]=sequentialVariance;constructor(map10){this.map=map10}}var sequentialCollectionMake=(map10)=>new SequentialImpl(map10),sequentialCollectionCombine=(self,that)=>new SequentialImpl(reduce7(that.map,self.map,(map10,value,key)=>set3(map10,key,match2(get7(map10,key),{onNone:()=>empty2(),onSome:(a)=>appendAll2(a,value)}))));var sequentialCollectionKeys=(self)=>Array.from(keys2(self.map)),sequentialCollectionToChunk=(self)=>Array.from(self.map);var OP_STATE_PENDING="Pending",OP_STATE_DONE="Done";var DeferredSymbolKey="effect/Deferred",DeferredTypeId=Symbol.for(DeferredSymbolKey),deferredVariance={_E:(_)=>_,_A:(_)=>_},pending=(joiners)=>{return{_tag:OP_STATE_PENDING,joiners}},done=(effect)=>{return{_tag:OP_STATE_DONE,effect}};class SingleShotGen2{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 SingleShotGen2(this.self)}}var blocked=(blockedRequests,_continue)=>{let effect=new EffectPrimitive("Blocked");return effect.effect_instruction_i0=blockedRequests,effect.effect_instruction_i1=_continue,effect},runRequestBlock=(blockedRequests)=>{let effect=new EffectPrimitive("RunBlocked");return effect.effect_instruction_i0=blockedRequests,effect},EffectTypeId2=Symbol.for("effect/Effect");class RevertFlags{patch;op;_op=OP_REVERT_FLAGS;constructor(patch5,op){this.patch=patch5,this.op=op}}class EffectPrimitive{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[EffectTypeId2]=effectVariance;constructor(_op){this._op=_op}[symbol2](that){return this===that}[symbol](){return cached(this,random(this))}pipe(){return pipeArguments(this,arguments)}toJSON(){return{_id:"Effect",_op:this._op,effect_instruction_i0:toJSON(this.effect_instruction_i0),effect_instruction_i1:toJSON(this.effect_instruction_i1),effect_instruction_i2:toJSON(this.effect_instruction_i2)}}toString(){return format(this.toJSON())}[NodeInspectSymbol](){return this.toJSON()}[Symbol.iterator](){return new SingleShotGen2(new YieldWrap(this))}}class EffectPrimitiveFailure{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[EffectTypeId2]=effectVariance;constructor(_op){this._op=_op,this._tag=_op}[symbol2](that){return exitIsExit(that)&&that._op==="Failure"&&equals(this.effect_instruction_i0,that.effect_instruction_i0)}[symbol](){return pipe(string(this._tag),combine(hash(this.effect_instruction_i0)),cached(this))}get cause(){return this.effect_instruction_i0}pipe(){return pipeArguments(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,cause:this.cause.toJSON()}}toString(){return format(this.toJSON())}[NodeInspectSymbol](){return this.toJSON()}[Symbol.iterator](){return new SingleShotGen2(new YieldWrap(this))}}class EffectPrimitiveSuccess{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[EffectTypeId2]=effectVariance;constructor(_op){this._op=_op,this._tag=_op}[symbol2](that){return exitIsExit(that)&&that._op==="Success"&&equals(this.effect_instruction_i0,that.effect_instruction_i0)}[symbol](){return pipe(string(this._tag),combine(hash(this.effect_instruction_i0)),cached(this))}get value(){return this.effect_instruction_i0}pipe(){return pipeArguments(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,value:toJSON(this.value)}}toString(){return format(this.toJSON())}[NodeInspectSymbol](){return this.toJSON()}[Symbol.iterator](){return new SingleShotGen2(new YieldWrap(this))}}var isEffect=(u)=>hasProperty(u,EffectTypeId2),withFiberRuntime=(withRuntime)=>{let effect=new EffectPrimitive(OP_WITH_RUNTIME);return effect.effect_instruction_i0=withRuntime,effect},acquireUseRelease=dual(3,(acquire,use,release)=>uninterruptibleMask((restore)=>flatMap8(acquire,(a)=>flatMap8(exit(suspend(()=>restore(use(a)))),(exit)=>{return suspend(()=>release(a,exit)).pipe(matchCauseEffect({onFailure:(cause)=>{switch(exit._tag){case OP_FAILURE:return failCause(sequential(exit.effect_instruction_i0,cause));case OP_SUCCESS:return failCause(cause)}},onSuccess:()=>exit}))})))),as=dual(2,(self,value)=>flatMap8(self,()=>succeed(value))),asVoid=(self)=>as(self,void 0),custom=function(){let wrapper=new EffectPrimitive(OP_COMMIT);switch(arguments.length){case 2:{wrapper.effect_instruction_i0=arguments[0],wrapper.commit=arguments[1];break}case 3:{wrapper.effect_instruction_i0=arguments[0],wrapper.effect_instruction_i1=arguments[1],wrapper.commit=arguments[2];break}case 4:{wrapper.effect_instruction_i0=arguments[0],wrapper.effect_instruction_i1=arguments[1],wrapper.effect_instruction_i2=arguments[2],wrapper.commit=arguments[3];break}default:throw Error(getBugErrorMessage("you're not supposed to end up here"))}return wrapper},unsafeAsync=(register,blockingOn=none4)=>{let effect=new EffectPrimitive(OP_ASYNC),cancelerRef=void 0;return effect.effect_instruction_i0=(resume)=>{cancelerRef=register(resume)},effect.effect_instruction_i1=blockingOn,onInterrupt(effect,(_)=>isEffect(cancelerRef)?cancelerRef:void_)},asyncInterrupt=(register,blockingOn=none4)=>suspend(()=>unsafeAsync(register,blockingOn)),async_=(resume,blockingOn=none4)=>{return custom(resume,function(){let backingResume=void 0,pendingEffect=void 0;function proxyResume(effect2){if(backingResume)backingResume(effect2);else if(pendingEffect===void 0)pendingEffect=effect2}let effect=new EffectPrimitive(OP_ASYNC);effect.effect_instruction_i0=(resume2)=>{if(backingResume=resume2,pendingEffect)resume2(pendingEffect)},effect.effect_instruction_i1=blockingOn;let cancelerRef=void 0,controllerRef=void 0;if(this.effect_instruction_i0.length!==1)controllerRef=new AbortController,cancelerRef=internalCall(()=>this.effect_instruction_i0(proxyResume,controllerRef.signal));else cancelerRef=internalCall(()=>this.effect_instruction_i0(proxyResume));return cancelerRef||controllerRef?onInterrupt(effect,(_)=>{if(controllerRef)controllerRef.abort();return cancelerRef??void_}):effect})};var catchAllCause=dual(2,(self,f)=>{let effect=new EffectPrimitive(OP_ON_FAILURE);return effect.effect_instruction_i0=self,effect.effect_instruction_i1=f,effect}),catchAll=dual(2,(self,f)=>matchEffect(self,{onFailure:f,onSuccess:succeed})),catchIf=dual(3,(self,predicate,f)=>catchAllCause(self,(cause)=>{let either2=failureOrCause(cause);switch(either2._tag){case"Left":return predicate(either2.left)?f(either2.left):failCause(cause);case"Right":return failCause(either2.right)}})),catchSome=dual(2,(self,pf)=>catchAllCause(self,(cause)=>{let either2=failureOrCause(cause);switch(either2._tag){case"Left":return pipe(pf(either2.left),getOrElse(()=>failCause(cause)));case"Right":return failCause(either2.right)}})),checkInterruptible=(f)=>withFiberRuntime((_,status)=>f(interruption(status.runtimeFlags))),originalSymbol=Symbol.for("effect/OriginalAnnotation");var capture=(obj,span2)=>{if(isSome2(span2))return new Proxy(obj,{has(target,p){return p===spanSymbol||p===originalSymbol||p in target},get(target,p){if(p===spanSymbol)return span2.value;if(p===originalSymbol)return obj;return target[p]}});return obj},die2=(defect)=>isObject(defect)&&!(spanSymbol in defect)?withFiberRuntime((fiber)=>failCause(die(capture(defect,currentSpanFromFiber(fiber))))):failCause(die(defect)),dieMessage=(message)=>failCauseSync(()=>die(new RuntimeException(message))),dieSync=(evaluate)=>flatMap8(sync(evaluate),die2),either2=(self)=>matchEffect(self,{onFailure:(e)=>succeed(left2(e)),onSuccess:(a)=>succeed(right2(a))}),exit=(self)=>matchCause(self,{onFailure:exitFailCause,onSuccess:exitSucceed}),fail2=(error)=>isObject(error)&&!(spanSymbol in error)?withFiberRuntime((fiber)=>failCause(fail(capture(error,currentSpanFromFiber(fiber))))):failCause(fail(error)),failSync=(evaluate)=>flatMap8(sync(evaluate),fail2),failCause=(cause)=>{let effect=new EffectPrimitiveFailure(OP_FAILURE);return effect.effect_instruction_i0=cause,effect},failCauseSync=(evaluate)=>flatMap8(sync(evaluate),failCause),fiberId=withFiberRuntime((state)=>succeed(state.id())),fiberIdWith=(f)=>withFiberRuntime((state)=>f(state.id())),flatMap8=dual(2,(self,f)=>{let effect=new EffectPrimitive(OP_ON_SUCCESS);return effect.effect_instruction_i0=self,effect.effect_instruction_i1=f,effect}),andThen2=dual(2,(self,f)=>flatMap8(self,(a)=>{let b=typeof f==="function"?f(a):f;if(isEffect(b))return b;else if(isPromiseLike(b))return unsafeAsync((resume)=>{b.then((a2)=>resume(succeed(a2)),(e)=>resume(fail2(new UnknownException(e,"An unknown error occurred in Effect.andThen"))))});return succeed(b)})),step2=(self)=>{let effect=new EffectPrimitive("OnStep");return effect.effect_instruction_i0=self,effect},flatten5=(self)=>flatMap8(self,identity),flip=(self)=>matchEffect(self,{onFailure:succeed,onSuccess:fail2}),matchCause=dual(2,(self,options)=>matchCauseEffect(self,{onFailure:(cause)=>succeed(options.onFailure(cause)),onSuccess:(a)=>succeed(options.onSuccess(a))})),matchCauseEffect=dual(2,(self,options)=>{let effect=new EffectPrimitive(OP_ON_SUCCESS_AND_FAILURE);return effect.effect_instruction_i0=self,effect.effect_instruction_i1=options.onFailure,effect.effect_instruction_i2=options.onSuccess,effect}),matchEffect=dual(2,(self,options)=>matchCauseEffect(self,{onFailure:(cause)=>{if(defects(cause).length>0)return failCause(electFailures(cause));let failures2=failures(cause);if(failures2.length>0)return options.onFailure(unsafeHead(failures2));return failCause(cause)},onSuccess:options.onSuccess})),forEachSequential=dual(2,(self,f)=>suspend(()=>{let arr=fromIterable(self),ret=allocate(arr.length),i=0;return as(whileLoop({while:()=>i<arr.length,body:()=>f(arr[i],i),step:(b)=>{ret[i++]=b}}),ret)})),forEachSequentialDiscard=dual(2,(self,f)=>suspend(()=>{let arr=fromIterable(self),i=0;return whileLoop({while:()=>i<arr.length,body:()=>f(arr[i],i),step:()=>{i++}})})),if_=dual((args)=>typeof args[0]==="boolean"||isEffect(args[0]),(self,options)=>isEffect(self)?flatMap8(self,(b)=>b?options.onTrue():options.onFalse()):self?options.onTrue():options.onFalse()),interrupt2=flatMap8(fiberId,(fiberId2)=>interruptWith(fiberId2)),interruptWith=(fiberId2)=>failCause(interrupt(fiberId2)),interruptible2=(self)=>{let effect=new EffectPrimitive(OP_UPDATE_RUNTIME_FLAGS);return effect.effect_instruction_i0=enable3(Interruption),effect.effect_instruction_i1=()=>self,effect},interruptibleMask=(f)=>custom(f,function(){let effect=new EffectPrimitive(OP_UPDATE_RUNTIME_FLAGS);return effect.effect_instruction_i0=enable3(Interruption),effect.effect_instruction_i1=(oldFlags)=>interruption(oldFlags)?internalCall(()=>this.effect_instruction_i0(interruptible2)):internalCall(()=>this.effect_instruction_i0(uninterruptible)),effect}),intoDeferred=dual(2,(self,deferred)=>uninterruptibleMask((restore)=>flatMap8(exit(restore(self)),(exit2)=>deferredDone(deferred,exit2)))),map10=dual(2,(self,f)=>flatMap8(self,(a)=>sync(()=>f(a)))),mapBoth=dual(2,(self,options)=>matchEffect(self,{onFailure:(e)=>failSync(()=>options.onFailure(e)),onSuccess:(a)=>sync(()=>options.onSuccess(a))})),mapError=dual(2,(self,f)=>matchCauseEffect(self,{onFailure:(cause)=>{let either3=failureOrCause(cause);switch(either3._tag){case"Left":return failSync(()=>f(either3.left));case"Right":return failCause(either3.right)}},onSuccess:succeed})),onError=dual(2,(self,cleanup)=>onExit(self,(exit2)=>exitIsSuccess(exit2)?void_:cleanup(exit2.effect_instruction_i0))),onExit=dual(2,(self,cleanup)=>uninterruptibleMask((restore)=>matchCauseEffect(restore(self),{onFailure:(cause1)=>{let result=exitFailCause(cause1);return matchCauseEffect(cleanup(result),{onFailure:(cause2)=>exitFailCause(sequential(cause1,cause2)),onSuccess:()=>result})},onSuccess:(success)=>{let result=exitSucceed(success);return zipRight(cleanup(result),result)}}))),onInterrupt=dual(2,(self,cleanup)=>onExit(self,exitMatch({onFailure:(cause)=>isInterruptedOnly(cause)?asVoid(cleanup(interruptors(cause))):void_,onSuccess:()=>void_}))),orElse2=dual(2,(self,that)=>attemptOrElse(self,that,succeed)),orDie=(self)=>orDieWith(self,identity),orDieWith=dual(2,(self,f)=>matchEffect(self,{onFailure:(e)=>die2(f(e)),onSuccess:succeed})),partitionMap2=partitionMap,runtimeFlags=withFiberRuntime((_,status)=>succeed(status.runtimeFlags)),succeed=(value)=>{let effect=new EffectPrimitiveSuccess(OP_SUCCESS);return effect.effect_instruction_i0=value,effect},suspend=(evaluate)=>{let effect=new EffectPrimitive(OP_COMMIT);return effect.commit=evaluate,effect},sync=(thunk)=>{let effect=new EffectPrimitive(OP_SYNC);return effect.effect_instruction_i0=thunk,effect},tap=dual((args)=>args.length===3||args.length===2&&!(isObject(args[1])&&("onlyEffect"in args[1])),(self,f)=>flatMap8(self,(a)=>{let b=typeof f==="function"?f(a):f;if(isEffect(b))return as(b,a);else if(isPromiseLike(b))return unsafeAsync((resume)=>{b.then((_)=>resume(succeed(a)),(e)=>resume(fail2(new UnknownException(e,"An unknown error occurred in Effect.tap"))))});return succeed(a)})),transplant=(f)=>withFiberRuntime((state)=>{let scopeOverride=state.getFiberRef(currentForkScopeOverride),scope=pipe(scopeOverride,getOrElse(()=>state.scope()));return f(fiberRefLocally(currentForkScopeOverride,some2(scope)))}),attemptOrElse=dual(3,(self,that,onSuccess)=>matchCauseEffect(self,{onFailure:(cause)=>{if(defects(cause).length>0)return failCause(getOrThrow(keepDefectsAndElectFailures(cause)));return that()},onSuccess})),uninterruptible=(self)=>{let effect=new EffectPrimitive(OP_UPDATE_RUNTIME_FLAGS);return effect.effect_instruction_i0=disable3(Interruption),effect.effect_instruction_i1=()=>self,effect},uninterruptibleMask=(f)=>custom(f,function(){let effect=new EffectPrimitive(OP_UPDATE_RUNTIME_FLAGS);return effect.effect_instruction_i0=disable3(Interruption),effect.effect_instruction_i1=(oldFlags)=>interruption(oldFlags)?internalCall(()=>this.effect_instruction_i0(interruptible2)):internalCall(()=>this.effect_instruction_i0(uninterruptible)),effect}),void_=succeed(void 0);var updateRuntimeFlags=(patch5)=>{let effect=new EffectPrimitive(OP_UPDATE_RUNTIME_FLAGS);return effect.effect_instruction_i0=patch5,effect.effect_instruction_i1=void 0,effect},whenEffect=dual(2,(self,condition)=>flatMap8(condition,(b)=>{if(b)return pipe(self,map10(some2));return succeed(none2())})),whileLoop=(options)=>{let effect=new EffectPrimitive(OP_WHILE);return effect.effect_instruction_i0=options.while,effect.effect_instruction_i1=options.body,effect.effect_instruction_i2=options.step,effect},fromIterator=(iterator)=>suspend(()=>{let effect=new EffectPrimitive(OP_ITERATOR);return effect.effect_instruction_i0=iterator(),effect}),gen=function(){let f=arguments.length===1?arguments[0]:arguments[1].bind(arguments[0]);return fromIterator(()=>f(pipe))},fnUntraced=(body,...pipeables)=>Object.defineProperty(pipeables.length===0?function(...args){return fromIterator(()=>body.apply(this,args))}:function(...args){let effect=fromIterator(()=>body.apply(this,args));for(let x of pipeables)effect=x(effect,...args);return effect},"length",{value:body.length,configurable:!0}),withConcurrency=dual(2,(self,concurrency)=>fiberRefLocally(self,currentConcurrency,concurrency)),withRequestBatching=dual(2,(self,requestBatching)=>fiberRefLocally(self,currentRequestBatching,requestBatching)),withRuntimeFlags=dual(2,(self,update2)=>{let effect=new EffectPrimitive(OP_UPDATE_RUNTIME_FLAGS);return effect.effect_instruction_i0=update2,effect.effect_instruction_i1=()=>self,effect}),withTracerEnabled=dual(2,(effect,enabled2)=>fiberRefLocally(effect,currentTracerEnabled,enabled2)),withTracerTiming=dual(2,(effect,enabled2)=>fiberRefLocally(effect,currentTracerTimingEnabled,enabled2)),yieldNow=(options)=>{let effect=new EffectPrimitive(OP_YIELD);return typeof options?.priority<"u"?withSchedulingPriority(effect,options.priority):effect},zip2=dual(2,(self,that)=>flatMap8(self,(a)=>map10(that,(b)=>[a,b])));var zipLeft=dual(2,(self,that)=>flatMap8(self,(a)=>as(that,a))),zipRight=dual(2,(self,that)=>flatMap8(self,()=>that)),zipWith3=dual(3,(self,that,f)=>flatMap8(self,(a)=>map10(that,(b)=>f(a,b)))),never=asyncInterrupt(()=>{let interval=setInterval(()=>{},2147483647);return sync(()=>clearInterval(interval))}),interruptFiber=(self)=>flatMap8(fiberId,(fiberId2)=>pipe(self,interruptAsFiber(fiberId2))),interruptAsFiber=dual(2,(self,fiberId2)=>flatMap8(self.interruptAsFork(fiberId2),()=>self.await)),logLevelAll={_tag:"All",syslog:0,label:"ALL",ordinal:Number.MIN_SAFE_INTEGER,pipe(){return pipeArguments(this,arguments)}},logLevelFatal={_tag:"Fatal",syslog:2,label:"FATAL",ordinal:50000,pipe(){return pipeArguments(this,arguments)}},logLevelError={_tag:"Error",syslog:3,label:"ERROR",ordinal:40000,pipe(){return pipeArguments(this,arguments)}},logLevelWarning={_tag:"Warning",syslog:4,label:"WARN",ordinal:30000,pipe(){return pipeArguments(this,arguments)}},logLevelInfo={_tag:"Info",syslog:6,label:"INFO",ordinal:20000,pipe(){return pipeArguments(this,arguments)}},logLevelDebug={_tag:"Debug",syslog:7,label:"DEBUG",ordinal:1e4,pipe(){return pipeArguments(this,arguments)}},logLevelTrace={_tag:"Trace",syslog:7,label:"TRACE",ordinal:0,pipe(){return pipeArguments(this,arguments)}},logLevelNone={_tag:"None",syslog:7,label:"OFF",ordinal:Number.MAX_SAFE_INTEGER,pipe(){return pipeArguments(this,arguments)}},allLogLevels=[logLevelAll,logLevelTrace,logLevelDebug,logLevelInfo,logLevelWarning,logLevelError,logLevelFatal,logLevelNone],FiberRefSymbolKey="effect/FiberRef",FiberRefTypeId=Symbol.for(FiberRefSymbolKey),fiberRefVariance={_A:(_)=>_},fiberRefGet=(self)=>withFiberRuntime((fiber)=>exitSucceed(fiber.getFiberRef(self)));var fiberRefGetWith=dual(2,(self,f)=>flatMap8(fiberRefGet(self),f)),fiberRefSet=dual(2,(self,value)=>fiberRefModify(self,()=>[void 0,value]));var fiberRefModify=dual(2,(self,f)=>withFiberRuntime((state)=>{let[b,a]=f(state.getFiberRef(self));return state.setFiberRef(self,a),succeed(b)}));var fiberRefLocally=dual(3,(use,self,value)=>acquireUseRelease(zipLeft(fiberRefGet(self),fiberRefSet(self,value)),()=>use,(oldValue)=>fiberRefSet(self,oldValue))),fiberRefLocallyWith=dual(3,(use,self,f)=>fiberRefGetWith(self,(a)=>fiberRefLocally(use,self,f(a)))),fiberRefUnsafeMake=(initial,options)=>fiberRefUnsafeMakePatch(initial,{differ:update(),fork:options?.fork??identity,join:options?.join}),fiberRefUnsafeMakeHashSet=(initial)=>{let differ2=hashSet();return fiberRefUnsafeMakePatch(initial,{differ:differ2,fork:differ2.empty})},fiberRefUnsafeMakeReadonlyArray=(initial)=>{let differ2=readonlyArray(update());return fiberRefUnsafeMakePatch(initial,{differ:differ2,fork:differ2.empty})},fiberRefUnsafeMakeContext=(initial)=>{let differ2=environment();return fiberRefUnsafeMakePatch(initial,{differ:differ2,fork:differ2.empty})},fiberRefUnsafeMakePatch=(initial,options)=>{return{...CommitPrototype,[FiberRefTypeId]:fiberRefVariance,initial,commit(){return fiberRefGet(this)},diff:(oldValue,newValue)=>options.differ.diff(oldValue,newValue),combine:(first,second)=>options.differ.combine(first,second),patch:(patch5)=>(oldValue)=>options.differ.patch(patch5,oldValue),fork:options.fork,join:options.join??((_,n)=>n)}},fiberRefUnsafeMakeRuntimeFlags=(initial)=>fiberRefUnsafeMakePatch(initial,{differ,fork:differ.empty}),currentContext=globalValue(Symbol.for("effect/FiberRef/currentContext"),()=>fiberRefUnsafeMakeContext(empty8())),currentSchedulingPriority=globalValue(Symbol.for("effect/FiberRef/currentSchedulingPriority"),()=>fiberRefUnsafeMake(0)),currentMaxOpsBeforeYield=globalValue(Symbol.for("effect/FiberRef/currentMaxOpsBeforeYield"),()=>fiberRefUnsafeMake(2048)),currentLogAnnotations=globalValue(Symbol.for("effect/FiberRef/currentLogAnnotation"),()=>fiberRefUnsafeMake(empty9())),currentLogLevel=globalValue(Symbol.for("effect/FiberRef/currentLogLevel"),()=>fiberRefUnsafeMake(logLevelInfo)),currentLogSpan=globalValue(Symbol.for("effect/FiberRef/currentLogSpan"),()=>fiberRefUnsafeMake(empty10())),withSchedulingPriority=dual(2,(self,scheduler)=>fiberRefLocally(self,currentSchedulingPriority,scheduler)),withMaxOpsBeforeYield=dual(2,(self,scheduler)=>fiberRefLocally(self,currentMaxOpsBeforeYield,scheduler)),currentConcurrency=globalValue(Symbol.for("effect/FiberRef/currentConcurrency"),()=>fiberRefUnsafeMake("unbounded")),currentRequestBatching=globalValue(Symbol.for("effect/FiberRef/currentRequestBatching"),()=>fiberRefUnsafeMake(!0)),currentUnhandledErrorLogLevel=globalValue(Symbol.for("effect/FiberRef/currentUnhandledErrorLogLevel"),()=>fiberRefUnsafeMake(some2(logLevelDebug))),currentVersionMismatchErrorLogLevel=globalValue(Symbol.for("effect/FiberRef/versionMismatchErrorLogLevel"),()=>fiberRefUnsafeMake(some2(logLevelWarning))),withUnhandledErrorLogLevel=dual(2,(self,level)=>fiberRefLocally(self,currentUnhandledErrorLogLevel,level)),currentMetricLabels=globalValue(Symbol.for("effect/FiberRef/currentMetricLabels"),()=>fiberRefUnsafeMakeReadonlyArray(empty())),metricLabels=fiberRefGet(currentMetricLabels),currentForkScopeOverride=globalValue(Symbol.for("effect/FiberRef/currentForkScopeOverride"),()=>fiberRefUnsafeMake(none2(),{fork:()=>none2(),join:(parent,_)=>parent})),currentInterruptedCause=globalValue(Symbol.for("effect/FiberRef/currentInterruptedCause"),()=>fiberRefUnsafeMake(empty6,{fork:()=>empty6,join:(parent,_)=>parent})),currentTracerEnabled=globalValue(Symbol.for("effect/FiberRef/currentTracerEnabled"),()=>fiberRefUnsafeMake(!0)),currentTracerTimingEnabled=globalValue(Symbol.for("effect/FiberRef/currentTracerTiming"),()=>fiberRefUnsafeMake(!0)),currentTracerSpanAnnotations=globalValue(Symbol.for("effect/FiberRef/currentTracerSpanAnnotations"),()=>fiberRefUnsafeMake(empty9())),currentTracerSpanLinks=globalValue(Symbol.for("effect/FiberRef/currentTracerSpanLinks"),()=>fiberRefUnsafeMake(empty2())),ScopeTypeId=Symbol.for("effect/Scope"),CloseableScopeTypeId=Symbol.for("effect/CloseableScope"),scopeAddFinalizer=(self,finalizer)=>self.addFinalizer(()=>asVoid(finalizer)),scopeAddFinalizerExit=(self,finalizer)=>self.addFinalizer(finalizer),scopeClose=(self,exit2)=>self.close(exit2),scopeFork=(self,strategy)=>self.fork(strategy),causeSquash=(self)=>{return causeSquashWith(identity)(self)},causeSquashWith=dual(2,(self,f)=>{let option=pipe(self,failureOption,map2(f));switch(option._tag){case"None":return pipe(defects(self),head2,match2({onNone:()=>{let interrupts=fromIterable(interruptors(self)).flatMap((fiberId2)=>fromIterable(ids2(fiberId2)).map((id)=>`#${id}`));return new InterruptedException(interrupts?`Interrupted by fibers: ${interrupts.join(", ")}`:void 0)},onSome:identity}));case"Some":return option.value}}),YieldableError=function(){class YieldableError2 extends globalThis.Error{commit(){return fail2(this)}toJSON(){let obj={...this};if(this.message)obj.message=this.message;if(this.cause)obj.cause=this.cause;return obj}[NodeInspectSymbol](){if(this.toString!==globalThis.Error.prototype.toString)return this.stack?`${this.toString()}
21
21
  ${this.stack.split(`
22
22
  `).slice(1).join(`
23
- `)}`:this.toString();else if("Bun"in globalThis)return pretty(fail(this),{renderErrorCause:!0});return this}}return Object.assign(YieldableError2.prototype,StructuralCommitPrototype),YieldableError2}(),makeException=(proto2,tag)=>{class Base2 extends YieldableError{_tag=tag}return Object.assign(Base2.prototype,proto2),Base2.prototype.name=tag,Base2},RuntimeExceptionTypeId=Symbol.for("effect/Cause/errors/RuntimeException"),RuntimeException=makeException({[RuntimeExceptionTypeId]:RuntimeExceptionTypeId},"RuntimeException"),isRuntimeException=(u)=>hasProperty(u,RuntimeExceptionTypeId),InterruptedExceptionTypeId=Symbol.for("effect/Cause/errors/InterruptedException"),InterruptedException=makeException({[InterruptedExceptionTypeId]:InterruptedExceptionTypeId},"InterruptedException"),isInterruptedException=(u)=>hasProperty(u,InterruptedExceptionTypeId),IllegalArgumentExceptionTypeId=Symbol.for("effect/Cause/errors/IllegalArgument"),IllegalArgumentException=makeException({[IllegalArgumentExceptionTypeId]:IllegalArgumentExceptionTypeId},"IllegalArgumentException");var NoSuchElementExceptionTypeId=Symbol.for("effect/Cause/errors/NoSuchElement"),NoSuchElementException=makeException({[NoSuchElementExceptionTypeId]:NoSuchElementExceptionTypeId},"NoSuchElementException"),isNoSuchElementException=(u)=>hasProperty(u,NoSuchElementExceptionTypeId),InvalidPubSubCapacityExceptionTypeId=Symbol.for("effect/Cause/errors/InvalidPubSubCapacityException"),InvalidPubSubCapacityException=makeException({[InvalidPubSubCapacityExceptionTypeId]:InvalidPubSubCapacityExceptionTypeId},"InvalidPubSubCapacityException"),ExceededCapacityExceptionTypeId=Symbol.for("effect/Cause/errors/ExceededCapacityException"),ExceededCapacityException=makeException({[ExceededCapacityExceptionTypeId]:ExceededCapacityExceptionTypeId},"ExceededCapacityException");var TimeoutExceptionTypeId=Symbol.for("effect/Cause/errors/Timeout"),TimeoutException=makeException({[TimeoutExceptionTypeId]:TimeoutExceptionTypeId},"TimeoutException"),timeoutExceptionFromDuration=(duration)=>new TimeoutException(`Operation timed out after '${format2(duration)}'`);var UnknownExceptionTypeId=Symbol.for("effect/Cause/errors/UnknownException"),UnknownException=function(){class UnknownException2 extends YieldableError{_tag="UnknownException";error;constructor(cause,message){super(message??"An unknown error occurred",{cause});this.error=cause}}return Object.assign(UnknownException2.prototype,{[UnknownExceptionTypeId]:UnknownExceptionTypeId,name:"UnknownException"}),UnknownException2}();var exitIsExit=(u)=>isEffect(u)&&("_tag"in u)&&(u._tag==="Success"||u._tag==="Failure"),exitIsFailure=(self)=>self._tag==="Failure",exitIsSuccess=(self)=>self._tag==="Success";var exitAs=dual(2,(self,value)=>{switch(self._tag){case OP_FAILURE:return exitFailCause(self.effect_instruction_i0);case OP_SUCCESS:return exitSucceed(value)}}),exitAsVoid=(self)=>exitAs(self,void 0);var exitCollectAll=(exits,options)=>exitCollectAllInternal(exits,options?.parallel?parallel:sequential),exitDie=(defect)=>exitFailCause(die(defect));var exitFail=(error)=>exitFailCause(fail(error)),exitFailCause=(cause)=>{let effect=new EffectPrimitiveFailure(OP_FAILURE);return effect.effect_instruction_i0=cause,effect},exitFlatMap=dual(2,(self,f)=>{switch(self._tag){case OP_FAILURE:return exitFailCause(self.effect_instruction_i0);case OP_SUCCESS:return f(self.effect_instruction_i0)}});var exitFlatten=(self)=>pipe(self,exitFlatMap(identity));var exitInterrupt=(fiberId2)=>exitFailCause(interrupt(fiberId2)),exitMap=dual(2,(self,f)=>{switch(self._tag){case OP_FAILURE:return exitFailCause(self.effect_instruction_i0);case OP_SUCCESS:return exitSucceed(f(self.effect_instruction_i0))}}),exitMapBoth=dual(2,(self,{onFailure,onSuccess})=>{switch(self._tag){case OP_FAILURE:return exitFailCause(pipe(self.effect_instruction_i0,map8(onFailure)));case OP_SUCCESS:return exitSucceed(onSuccess(self.effect_instruction_i0))}});var exitMatch=dual(2,(self,{onFailure,onSuccess})=>{switch(self._tag){case OP_FAILURE:return onFailure(self.effect_instruction_i0);case OP_SUCCESS:return onSuccess(self.effect_instruction_i0)}}),exitMatchEffect=dual(2,(self,{onFailure,onSuccess})=>{switch(self._tag){case OP_FAILURE:return onFailure(self.effect_instruction_i0);case OP_SUCCESS:return onSuccess(self.effect_instruction_i0)}}),exitSucceed=(value)=>{let effect=new EffectPrimitiveSuccess(OP_SUCCESS);return effect.effect_instruction_i0=value,effect},exitVoid=exitSucceed(void 0),exitZip=dual(2,(self,that)=>exitZipWith(self,that,{onSuccess:(a,a2)=>[a,a2],onFailure:sequential}));var exitZipRight=dual(2,(self,that)=>exitZipWith(self,that,{onSuccess:(_,a2)=>a2,onFailure:sequential}));var exitZipWith=dual(3,(self,that,{onFailure,onSuccess})=>{switch(self._tag){case OP_FAILURE:switch(that._tag){case OP_SUCCESS:return exitFailCause(self.effect_instruction_i0);case OP_FAILURE:return exitFailCause(onFailure(self.effect_instruction_i0,that.effect_instruction_i0))}case OP_SUCCESS:switch(that._tag){case OP_SUCCESS:return exitSucceed(onSuccess(self.effect_instruction_i0,that.effect_instruction_i0));case OP_FAILURE:return exitFailCause(that.effect_instruction_i0)}}}),exitCollectAllInternal=(exits,combineCauses)=>{let list=fromIterable2(exits);if(!isNonEmpty(list))return none2();return pipe(tailNonEmpty2(list),reduce(pipe(headNonEmpty2(list),exitMap(of2)),(accumulator,current)=>pipe(accumulator,exitZipWith(current,{onSuccess:(list2,value)=>pipe(list2,prepend2(value)),onFailure:combineCauses}))),exitMap(reverse2),exitMap((chunk)=>toReadonlyArray(chunk)),some2)},deferredUnsafeMake=(fiberId2)=>{return{...CommitPrototype,[DeferredTypeId]:deferredVariance,state:make11(pending([])),commit(){return deferredAwait(this)},blockingOn:fiberId2}},deferredMake=()=>flatMap8(fiberId,(id)=>deferredMakeAs(id)),deferredMakeAs=(fiberId2)=>sync(()=>deferredUnsafeMake(fiberId2)),deferredAwait=(self)=>asyncInterrupt((resume)=>{let state=get6(self.state);switch(state._tag){case OP_STATE_DONE:return resume(state.effect);case OP_STATE_PENDING:return state.joiners.push(resume),deferredInterruptJoiner(self,resume)}},self.blockingOn),deferredComplete=dual(2,(self,effect)=>intoDeferred(effect,self)),deferredCompleteWith=dual(2,(self,effect)=>sync(()=>{let state=get6(self.state);switch(state._tag){case OP_STATE_DONE:return!1;case OP_STATE_PENDING:{set2(self.state,done(effect));for(let i=0,len=state.joiners.length;i<len;i++)state.joiners[i](effect);return!0}}})),deferredDone=dual(2,(self,exit2)=>deferredCompleteWith(self,exit2)),deferredFail=dual(2,(self,error)=>deferredCompleteWith(self,fail2(error)));var deferredFailCause=dual(2,(self,cause)=>deferredCompleteWith(self,failCause(cause)));var deferredInterrupt=(self)=>flatMap8(fiberId,(fiberId2)=>deferredCompleteWith(self,interruptWith(fiberId2))),deferredInterruptWith=dual(2,(self,fiberId2)=>deferredCompleteWith(self,interruptWith(fiberId2))),deferredIsDone=(self)=>sync(()=>get6(self.state)._tag===OP_STATE_DONE),deferredPoll=(self)=>sync(()=>{let state=get6(self.state);switch(state._tag){case OP_STATE_DONE:return some2(state.effect);case OP_STATE_PENDING:return none2()}}),deferredSucceed=dual(2,(self,value)=>deferredCompleteWith(self,succeed(value)));var deferredUnsafeDone=(self,effect)=>{let state=get6(self.state);if(state._tag===OP_STATE_PENDING){set2(self.state,done(effect));for(let i=0,len=state.joiners.length;i<len;i++)state.joiners[i](effect)}},deferredInterruptJoiner=(self,joiner)=>sync(()=>{let state=get6(self.state);if(state._tag===OP_STATE_PENDING){let index=state.joiners.indexOf(joiner);if(index>=0)state.joiners.splice(index,1)}}),constContext=withFiberRuntime((fiber)=>exitSucceed(fiber.currentContext)),context=()=>constContext;var contextWithEffect=(f)=>flatMap8(context(),f),provideContext=dual(2,(self,context2)=>fiberRefLocally(currentContext,context2)(self)),provideSomeContext=dual(2,(self,context2)=>fiberRefLocallyWith(currentContext,(parent)=>merge3(parent,context2))(self)),mapInputContext=dual(2,(self,f)=>contextWithEffect((context2)=>provideContext(self,f(context2)))),filterEffectOrElse=dual(2,(self,options)=>flatMap8(self,(a)=>flatMap8(options.predicate(a),(pass)=>pass?succeed(a):options.orElse(a)))),filterEffectOrFail=dual(2,(self,options)=>filterEffectOrElse(self,{predicate:options.predicate,orElse:(a)=>fail2(options.orFailWith(a))})),currentSpanFromFiber=(fiber)=>{let span2=fiber.currentSpan;return span2!==void 0&&span2._tag==="Span"?some2(span2):none2()},NoopSpanProto={_tag:"Span",spanId:"noop",traceId:"noop",sampled:!1,status:{_tag:"Ended",startTime:BigInt(0),endTime:BigInt(0),exit:exitVoid},attributes:new Map,links:[],kind:"internal",attribute(){},event(){},end(){},addLinks(){}},noopSpan=(options)=>Object.assign(Object.create(NoopSpanProto),options);var fail3=fail,die3=die,interrupt3=interrupt;var isDieType2=isDieType;var isInterrupted2=isInterrupted,isInterruptedOnly2=isInterruptedOnly;var interruptors2=interruptors;var failureOrCause2=failureOrCause,flipCauseOption2=flipCauseOption;var map11=map8;var squash=causeSquash;var IllegalArgumentException2=IllegalArgumentException;var NoSuchElementException2=NoSuchElementException;var RuntimeException2=RuntimeException,isRuntimeException2=isRuntimeException;var exports_Effect={};__export(exports_Effect,{zipWith:()=>zipWith6,zipRight:()=>zipRight4,zipLeft:()=>zipLeft3,zip:()=>zip5,yieldNow:()=>yieldNow4,withUnhandledErrorLogLevel:()=>withUnhandledErrorLogLevel2,withTracerTiming:()=>withTracerTiming2,withTracerScoped:()=>withTracerScoped2,withTracerEnabled:()=>withTracerEnabled2,withTracer:()=>withTracer2,withSpanScoped:()=>withSpanScoped2,withSpan:()=>withSpan3,withSchedulingPriority:()=>withSchedulingPriority2,withScheduler:()=>withScheduler2,withRuntimeFlagsPatchScoped:()=>withRuntimeFlagsPatchScoped,withRuntimeFlagsPatch:()=>withRuntimeFlagsPatch,withRequestCaching:()=>withRequestCaching2,withRequestCache:()=>withRequestCache2,withRequestBatching:()=>withRequestBatching2,withRandomScoped:()=>withRandomScoped2,withRandomFixed:()=>withRandomFixed,withRandom:()=>withRandom2,withParentSpan:()=>withParentSpan3,withMetric:()=>withMetric2,withMaxOpsBeforeYield:()=>withMaxOpsBeforeYield2,withLogSpan:()=>withLogSpan2,withFiberRuntime:()=>withFiberRuntime2,withExecutionPlan:()=>withExecutionPlan2,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_3,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:()=>tapErrorCause3,tapError:()=>tapError3,tapDefect:()=>tapDefect2,tapBoth:()=>tapBoth2,tap:()=>tap3,takeWhile:()=>takeWhile3,takeUntil:()=>takeUntil2,tagMetricsScoped:()=>tagMetricsScoped2,tagMetrics:()=>tagMetrics2,sync:()=>sync4,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:()=>scoped2,scopeWith:()=>scopeWith2,scope:()=>scope3,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:()=>retry2,request:()=>request,replicateEffect:()=>replicateEffect2,replicate:()=>replicate2,repeatOrElse:()=>repeatOrElse,repeatN:()=>repeatN2,repeat:()=>repeat,reduceWhile:()=>reduceWhile2,reduceRight:()=>reduceRight4,reduceEffect:()=>reduceEffect3,reduce:()=>reduce11,randomWith:()=>randomWith2,random:()=>random3,raceWith:()=>raceWith2,raceFirst:()=>raceFirst2,raceAll:()=>raceAll2,race:()=>race2,provideServiceEffect:()=>provideServiceEffect2,provideService:()=>provideService3,provide:()=>provide2,promise:()=>promise2,patchRuntimeFlags:()=>patchRuntimeFlags,patchFiberRefs:()=>patchFiberRefs2,partition:()=>partition4,parallelFinalizers:()=>parallelFinalizers2,parallelErrors:()=>parallelErrors2,orElseSucceed:()=>orElseSucceed2,orElseFail:()=>orElseFail2,orElse:()=>orElse5,orDieWith:()=>orDieWith2,orDie:()=>orDie3,optionFromOptional:()=>optionFromOptional2,option:()=>option2,once:()=>once3,onInterrupt:()=>onInterrupt2,onExit:()=>onExit3,onError:()=>onError2,none:()=>none9,never:()=>never3,negate:()=>negate2,metricLabels:()=>metricLabels2,mergeAll:()=>mergeAll5,merge:()=>merge7,matchEffect:()=>matchEffect2,matchCauseEffect:()=>matchCauseEffect3,matchCause:()=>matchCause3,match:()=>match13,mapInputContext:()=>mapInputContext3,mapErrorCause:()=>mapErrorCause2,mapError:()=>mapError3,mapBoth:()=>mapBoth4,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:()=>log3,locallyWith:()=>locallyWith,locallyScopedWith:()=>locallyScopedWith,locallyScoped:()=>locallyScoped,locally:()=>locally,linkSpans:()=>linkSpans2,linkSpanCurrent:()=>linkSpanCurrent2,liftPredicate:()=>liftPredicate3,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:()=>forEach6,fnUntraced:()=>fnUntraced2,fn:()=>fn,flipWith:()=>flipWith2,flip:()=>flip2,flatten:()=>flatten8,flatMap:()=>flatMap11,firstSuccessOf:()=>firstSuccessOf2,findFirst:()=>findFirst6,finalizersMask:()=>finalizersMask2,filterOrFail:()=>filterOrFail2,filterOrElse:()=>filterOrElse2,filterOrDieMessage:()=>filterOrDieMessage2,filterOrDie:()=>filterOrDie2,filterMap:()=>filterMap5,filterEffectOrFail:()=>filterEffectOrFail2,filterEffectOrElse:()=>filterEffectOrElse2,filter:()=>filter7,fiberIdWith:()=>fiberIdWith2,fiberId:()=>fiberId2,failSync:()=>failSync3,failCauseSync:()=>failCauseSync3,failCause:()=>failCause8,fail:()=>fail9,exit:()=>exit2,exists:()=>exists2,every:()=>every6,eventually:()=>eventually2,ensuringChildren:()=>ensuringChildren2,ensuringChild:()=>ensuringChild2,ensuring:()=>ensuring3,ensureSuccessType:()=>ensureSuccessType,ensureRequirementsType:()=>ensureRequirementsType,ensureErrorType:()=>ensureErrorType,either:()=>either4,dropWhile:()=>dropWhile3,dropUntil:()=>dropUntil2,disconnect:()=>disconnect2,diffFiberRefs:()=>diffFiberRefs2,dieSync:()=>dieSync3,dieMessage:()=>dieMessage2,die:()=>die6,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:()=>catchAllCause3,catchAll:()=>catchAll3,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:()=>asVoid3,asSomeError:()=>asSomeError2,asSome:()=>asSome2,as:()=>as4,ap:()=>ap,annotateSpans:()=>annotateSpans3,annotateLogsScoped:()=>annotateLogsScoped2,annotateLogs:()=>annotateLogs3,annotateCurrentSpan:()=>annotateCurrentSpan2,andThen:()=>andThen5,allowInterrupt:()=>allowInterrupt2,allWith:()=>allWith2,allSuccesses:()=>allSuccesses2,all:()=>all5,addFinalizer:()=>addFinalizer3,acquireUseRelease:()=>acquireUseRelease2,acquireReleaseInterruptible:()=>acquireReleaseInterruptible2,acquireRelease:()=>acquireRelease2,Tag:()=>Tag3,Service:()=>Service,EffectTypeId:()=>EffectTypeId3,Do:()=>Do2});var ClockSymbolKey="effect/Clock",ClockTypeId=Symbol.for(ClockSymbolKey),clockTag=GenericTag("effect/Clock"),MAX_TIMER_MILLIS=2147483647,globalClockScheduler={unsafeSchedule(task,duration){let millis2=toMillis(duration);if(millis2>MAX_TIMER_MILLIS)return constFalse;let completed=!1,handle=setTimeout(()=>{completed=!0,task()},millis2);return()=>{return clearTimeout(handle),!completed}}},performanceNowNanos=function(){let bigint1e62=BigInt(1e6);if(typeof performance>"u")return()=>BigInt(Date.now())*bigint1e62;let origin;return()=>{if(origin===void 0)origin=BigInt(Date.now())*bigint1e62-BigInt(Math.round(performance.now()*1e6));return origin+BigInt(Math.round(performance.now()*1e6))}}(),processOrPerformanceNow=function(){let processHrtime=typeof process==="object"&&"hrtime"in process&&typeof process.hrtime.bigint==="function"?process.hrtime:void 0;if(!processHrtime)return performanceNowNanos;let origin=performanceNowNanos()-processHrtime.bigint();return()=>origin+processHrtime.bigint()}();class ClockImpl{[ClockTypeId]=ClockTypeId;unsafeCurrentTimeMillis(){return Date.now()}unsafeCurrentTimeNanos(){return processOrPerformanceNow()}currentTimeMillis=sync(()=>this.unsafeCurrentTimeMillis());currentTimeNanos=sync(()=>this.unsafeCurrentTimeNanos());scheduler(){return succeed(globalClockScheduler)}sleep(duration){return async_((resume)=>{let canceler=globalClockScheduler.unsafeSchedule(()=>resume(void_),duration);return asVoid(sync(canceler))})}}var make18=()=>new ClockImpl;var Order2=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 OP_AND="And",OP_OR="Or",OP_INVALID_DATA="InvalidData",OP_MISSING_DATA="MissingData",OP_SOURCE_UNAVAILABLE="SourceUnavailable",OP_UNSUPPORTED="Unsupported";var ConfigErrorSymbolKey="effect/ConfigError",ConfigErrorTypeId=Symbol.for(ConfigErrorSymbolKey),proto2={_tag:"ConfigError",[ConfigErrorTypeId]:ConfigErrorTypeId},And=(self,that)=>{let error=Object.create(proto2);return error._op=OP_AND,error.left=self,error.right=that,Object.defineProperty(error,"toString",{enumerable:!1,value(){return`${this.left} and ${this.right}`}}),Object.defineProperty(error,"message",{enumerable:!1,get(){return this.toString()}}),error},Or=(self,that)=>{let error=Object.create(proto2);return error._op=OP_OR,error.left=self,error.right=that,Object.defineProperty(error,"toString",{enumerable:!1,value(){return`${this.left} or ${this.right}`}}),Object.defineProperty(error,"message",{enumerable:!1,get(){return this.toString()}}),error},InvalidData=(path,message,options={pathDelim:"."})=>{let error=Object.create(proto2);return error._op=OP_INVALID_DATA,error.path=path,error.message=message,Object.defineProperty(error,"toString",{enumerable:!1,value(){return`(Invalid data at ${pipe(this.path,join(options.pathDelim))}: "${this.message}")`}}),error},MissingData=(path,message,options={pathDelim:"."})=>{let error=Object.create(proto2);return error._op=OP_MISSING_DATA,error.path=path,error.message=message,Object.defineProperty(error,"toString",{enumerable:!1,value(){return`(Missing data at ${pipe(this.path,join(options.pathDelim))}: "${this.message}")`}}),error},SourceUnavailable=(path,message,cause,options={pathDelim:"."})=>{let error=Object.create(proto2);return error._op=OP_SOURCE_UNAVAILABLE,error.path=path,error.message=message,error.cause=cause,Object.defineProperty(error,"toString",{enumerable:!1,value(){return`(Source unavailable at ${pipe(this.path,join(options.pathDelim))}: "${this.message}")`}}),error},Unsupported=(path,message,options={pathDelim:"."})=>{let error=Object.create(proto2);return error._op=OP_UNSUPPORTED,error.path=path,error.message=message,Object.defineProperty(error,"toString",{enumerable:!1,value(){return`(Unsupported operation at ${pipe(this.path,join(options.pathDelim))}: "${this.message}")`}}),error};var prefixed=dual(2,(self,prefix)=>{switch(self._op){case OP_AND:return And(prefixed(self.left,prefix),prefixed(self.right,prefix));case OP_OR:return Or(prefixed(self.left,prefix),prefixed(self.right,prefix));case OP_INVALID_DATA:return InvalidData([...prefix,...self.path],self.message);case OP_MISSING_DATA:return MissingData([...prefix,...self.path],self.message);case OP_SOURCE_UNAVAILABLE:return SourceUnavailable([...prefix,...self.path],self.message,self.cause);case OP_UNSUPPORTED:return Unsupported([...prefix,...self.path],self.message)}}),IsMissingDataOnlyReducer={andCase:(_,left3,right3)=>left3&&right3,orCase:(_,left3,right3)=>left3&&right3,invalidDataCase:constFalse,missingDataCase:constTrue,sourceUnavailableCase:constFalse,unsupportedCase:constFalse},reduceWithContext2=dual(3,(self,context2,reducer)=>{let input=[self],output=[];while(input.length>0){let error=input.pop();switch(error._op){case OP_AND:{input.push(error.right),input.push(error.left),output.push(left2({_op:"AndCase"}));break}case OP_OR:{input.push(error.right),input.push(error.left),output.push(left2({_op:"OrCase"}));break}case OP_INVALID_DATA:{output.push(right2(reducer.invalidDataCase(context2,error.path,error.message)));break}case OP_MISSING_DATA:{output.push(right2(reducer.missingDataCase(context2,error.path,error.message)));break}case OP_SOURCE_UNAVAILABLE:{output.push(right2(reducer.sourceUnavailableCase(context2,error.path,error.message,error.cause)));break}case OP_UNSUPPORTED:{output.push(right2(reducer.unsupportedCase(context2,error.path,error.message)));break}}}let accumulator=[];while(output.length>0){let either3=output.pop();switch(either3._op){case"Left":{switch(either3.left._op){case"AndCase":{let left3=accumulator.pop(),right3=accumulator.pop(),value=reducer.andCase(context2,left3,right3);accumulator.push(value);break}case"OrCase":{let left3=accumulator.pop(),right3=accumulator.pop(),value=reducer.orCase(context2,left3,right3);accumulator.push(value);break}}break}case"Right":{accumulator.push(either3.right);break}}}if(accumulator.length===0)throw Error("BUG: ConfigError.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues");return accumulator.pop()}),isMissingDataOnly=(self)=>reduceWithContext2(self,void 0,IsMissingDataOnlyReducer);var empty17={_tag:"Empty"};var patch5=dual(2,(path,patch6)=>{let input=of3(patch6),output=path;while(isCons(input)){let patch7=input.head;switch(patch7._tag){case"Empty":{input=input.tail;break}case"AndThen":{input=cons(patch7.first,cons(patch7.second,input.tail));break}case"MapName":{output=map3(output,patch7.f),input=input.tail;break}case"Nested":{output=prepend(output,patch7.name),input=input.tail;break}case"Unnested":{if(pipe(head(output),contains(patch7.name)))output=tailNonEmpty(output),input=input.tail;else return left2(MissingData(output,`Expected ${patch7.name} to be in path in ConfigProvider#unnested`));break}}}return right2(output)});var OP_CONSTANT="Constant",OP_FAIL2="Fail",OP_FALLBACK="Fallback",OP_DESCRIBED="Described",OP_LAZY="Lazy",OP_MAP_OR_FAIL="MapOrFail",OP_NESTED="Nested",OP_PRIMITIVE="Primitive",OP_SEQUENCE="Sequence",OP_HASHMAP="HashMap",OP_ZIP_WITH="ZipWith";var concat=(l,r)=>[...l,...r],ConfigProviderSymbolKey="effect/ConfigProvider",ConfigProviderTypeId=Symbol.for(ConfigProviderSymbolKey),configProviderTag=GenericTag("effect/ConfigProvider"),FlatConfigProviderSymbolKey="effect/ConfigProviderFlat",FlatConfigProviderTypeId=Symbol.for(FlatConfigProviderSymbolKey),make20=(options)=>({[ConfigProviderTypeId]:ConfigProviderTypeId,pipe(){return pipeArguments(this,arguments)},...options}),makeFlat=(options)=>({[FlatConfigProviderTypeId]:FlatConfigProviderTypeId,patch:options.patch,load:(path,config,split=!0)=>options.load(path,config,split),enumerateChildren:options.enumerateChildren}),fromFlat=(flat)=>make20({load:(config)=>flatMap8(fromFlatLoop(flat,empty(),config,!1),(chunk)=>match2(head(chunk),{onNone:()=>fail2(MissingData(empty(),`Expected a single value having structure: ${config}`)),onSome:succeed})),flattened:flat}),fromEnv=(options)=>{let{pathDelim,seqDelim}=Object.assign({},{pathDelim:"_",seqDelim:","},options),makePathString=(path)=>pipe(path,join(pathDelim)),unmakePathString=(pathString)=>pathString.split(pathDelim),getEnv=()=>typeof process<"u"&&("env"in process)&&typeof process.env==="object"?process.env:{};return fromFlat(makeFlat({load:(path,primitive,split=!0)=>{let pathString=makePathString(path),current=getEnv(),valueOpt=pathString in current?some2(current[pathString]):none2();return pipe(valueOpt,mapError(()=>MissingData(path,`Expected ${pathString} to exist in the process context`)),flatMap8((value)=>parsePrimitive(value,path,primitive,seqDelim,split)))},enumerateChildren:(path)=>sync(()=>{let current=getEnv(),filteredKeyPaths=Object.keys(current).map((value)=>unmakePathString(value.toUpperCase())).filter((keyPath)=>{for(let i=0;i<path.length;i++){let pathComponent=pipe(path,unsafeGet(i)),currentElement=keyPath[i];if(currentElement===void 0||pathComponent!==currentElement)return!1}return!0}).flatMap((keyPath)=>keyPath.slice(path.length,path.length+1));return fromIterable5(filteredKeyPaths)}),patch:empty17}))};var extend=(leftDef,rightDef,left3,right3)=>{let leftPad=unfold(left3.length,(index)=>index>=right3.length?none2():some2([leftDef(index),index+1])),rightPad=unfold(right3.length,(index)=>index>=left3.length?none2():some2([rightDef(index),index+1])),leftExtension=concat(left3,leftPad),rightExtension=concat(right3,rightPad);return[leftExtension,rightExtension]},appendConfigPath=(path,config)=>{let op=config;if(op._tag==="Nested"){let out=path.slice();while(op._tag==="Nested")out.push(op.name),op=op.config;return out}return path},fromFlatLoop=(flat,prefix,config,split)=>{let op=config;switch(op._tag){case OP_CONSTANT:return succeed(of(op.value));case OP_DESCRIBED:return suspend(()=>fromFlatLoop(flat,prefix,op.config,split));case OP_FAIL2:return fail2(MissingData(prefix,op.message));case OP_FALLBACK:return pipe(suspend(()=>fromFlatLoop(flat,prefix,op.first,split)),catchAll((error1)=>{if(op.condition(error1))return pipe(fromFlatLoop(flat,prefix,op.second,split),catchAll((error2)=>fail2(Or(error1,error2))));return fail2(error1)}));case OP_LAZY:return suspend(()=>fromFlatLoop(flat,prefix,op.config(),split));case OP_MAP_OR_FAIL:return suspend(()=>pipe(fromFlatLoop(flat,prefix,op.original,split),flatMap8(forEachSequential((a)=>pipe(op.mapOrFail(a),mapError(prefixed(appendConfigPath(prefix,op.original))))))));case OP_NESTED:return suspend(()=>fromFlatLoop(flat,concat(prefix,of(op.name)),op.config,split));case OP_PRIMITIVE:return pipe(patch5(prefix,flat.patch),flatMap8((prefix2)=>pipe(flat.load(prefix2,op,split),flatMap8((values3)=>{if(values3.length===0){let name=pipe(last(prefix2),getOrElse(()=>"<n/a>"));return fail2(MissingData([],`Expected ${op.description} with name ${name}`))}return succeed(values3)}))));case OP_SEQUENCE:return pipe(patch5(prefix,flat.patch),flatMap8((patchedPrefix)=>pipe(flat.enumerateChildren(patchedPrefix),flatMap8(indicesFrom),flatMap8((indices)=>{if(indices.length===0)return suspend(()=>map10(fromFlatLoop(flat,prefix,op.config,!0),of));return pipe(forEachSequential(indices,(index)=>fromFlatLoop(flat,append(prefix,`[${index}]`),op.config,!0)),map10((chunkChunk)=>{let flattened=flatten(chunkChunk);if(flattened.length===0)return of(empty());return of(flattened)}))}))));case OP_HASHMAP:return suspend(()=>pipe(patch5(prefix,flat.patch),flatMap8((prefix2)=>pipe(flat.enumerateChildren(prefix2),flatMap8((keys3)=>{return pipe(keys3,forEachSequential((key)=>fromFlatLoop(flat,concat(prefix2,of(key)),op.valueConfig,split)),map10((matrix)=>{if(matrix.length===0)return of(empty9());return pipe(transpose(matrix),map3((values3)=>fromIterable6(zip(fromIterable(keys3),values3))))}))})))));case OP_ZIP_WITH:return suspend(()=>pipe(fromFlatLoop(flat,prefix,op.left,split),either2,flatMap8((left3)=>pipe(fromFlatLoop(flat,prefix,op.right,split),either2,flatMap8((right3)=>{if(isLeft2(left3)&&isLeft2(right3))return fail2(And(left3.left,right3.left));if(isLeft2(left3)&&isRight2(right3))return fail2(left3.left);if(isRight2(left3)&&isLeft2(right3))return fail2(right3.left);if(isRight2(left3)&&isRight2(right3)){let path=pipe(prefix,join(".")),fail4=fromFlatLoopFail(prefix,path),[lefts,rights]=extend(fail4,fail4,pipe(left3.right,map3(right2)),pipe(right3.right,map3(right2)));return pipe(lefts,zip(rights),forEachSequential(([left4,right4])=>pipe(zip2(left4,right4),map10(([left5,right5])=>op.zip(left5,right5)))))}throw Error("BUG: ConfigProvider.fromFlatLoop - please report an issue at https://github.com/Effect-TS/effect/issues")})))))}},fromFlatLoopFail=(prefix,path)=>(index)=>left2(MissingData(prefix,`The element at index ${index} in a sequence at path "${path}" was missing`));var splitPathString=(text,delim)=>{return text.split(new RegExp(`\\s*${escape(delim)}\\s*`))},parsePrimitive=(text,path,primitive,delimiter,split)=>{if(!split)return pipe(primitive.parse(text),mapBoth({onFailure:prefixed(path),onSuccess:of}));return pipe(splitPathString(text,delimiter),forEachSequential((char)=>primitive.parse(char.trim())),mapError(prefixed(path)))},transpose=(array3)=>{return Object.keys(array3[0]).map((column)=>array3.map((row)=>row[column]))},indicesFrom=(quotedIndices)=>pipe(forEachSequential(quotedIndices,parseQuotedIndex),mapBoth({onFailure:()=>empty(),onSuccess:sort(Order2)}),either2,map10(merge));var QUOTED_INDEX_REGEX=/^(\[(\d+)\])$/,parseQuotedIndex=(str)=>{let match6=str.match(QUOTED_INDEX_REGEX);if(match6!==null){let matchedIndex=match6[2];return pipe(matchedIndex!==void 0&&matchedIndex.length>0?some2(matchedIndex):none2(),flatMap(parseInteger))}return none2()};var parseInteger=(str)=>{let parsedIndex=Number.parseInt(str);return Number.isNaN(parsedIndex)?none2():some2(parsedIndex)};var TypeId8=Symbol.for("effect/Console"),consoleTag=GenericTag("effect/Console"),defaultConsole={[TypeId8]:TypeId8,assert(condition,...args){return sync(()=>{console.assert(condition,...args)})},clear:sync(()=>{console.clear()}),count(label){return sync(()=>{console.count(label)})},countReset(label){return sync(()=>{console.countReset(label)})},debug(...args){return sync(()=>{console.debug(...args)})},dir(item,options){return sync(()=>{console.dir(item,options)})},dirxml(...args){return sync(()=>{console.dirxml(...args)})},error(...args){return sync(()=>{console.error(...args)})},group(options){return options?.collapsed?sync(()=>console.groupCollapsed(options?.label)):sync(()=>console.group(options?.label))},groupEnd:sync(()=>{console.groupEnd()}),info(...args){return sync(()=>{console.info(...args)})},log(...args){return sync(()=>{console.log(...args)})},table(tabularData,properties){return sync(()=>{console.table(tabularData,properties)})},time(label){return sync(()=>console.time(label))},timeEnd(label){return sync(()=>console.timeEnd(label))},timeLog(label,...args){return sync(()=>{console.timeLog(label,...args)})},trace(...args){return sync(()=>{console.trace(...args)})},warn(...args){return sync(()=>{console.warn(...args)})},unsafe:console};var RandomSymbolKey="effect/Random",RandomTypeId=Symbol.for(RandomSymbolKey),randomTag=GenericTag("effect/Random");class RandomImpl{seed;[RandomTypeId]=RandomTypeId;PRNG;constructor(seed){this.seed=seed,this.PRNG=new PCGRandom(seed)}get next(){return sync(()=>this.PRNG.number())}get nextBoolean(){return map10(this.next,(n)=>n>0.5)}get nextInt(){return sync(()=>this.PRNG.integer(Number.MAX_SAFE_INTEGER))}nextRange(min3,max3){return map10(this.next,(n)=>(max3-min3)*n+min3)}nextIntBetween(min3,max3){return sync(()=>this.PRNG.integer(max3-min3)+min3)}shuffle(elements){return shuffleWith(elements,(n)=>this.nextIntBetween(0,n))}}var shuffleWith=(elements,nextIntBounded)=>{return suspend(()=>pipe(sync(()=>Array.from(elements)),flatMap8((buffer)=>{let numbers=[];for(let i=buffer.length;i>=2;i=i-1)numbers.push(i);return pipe(numbers,forEachSequentialDiscard((n)=>pipe(nextIntBounded(n),map10((k)=>swap(buffer,n-1,k)))),as(fromIterable2(buffer)))})))},swap=(buffer,index1,index2)=>{let tmp=buffer[index1];return buffer[index1]=buffer[index2],buffer[index2]=tmp,buffer},make21=(seed)=>new RandomImpl(hash(seed));class FixedRandomImpl{values;[RandomTypeId]=RandomTypeId;index=0;constructor(values3){if(this.values=values3,values3.length===0)throw Error("Requires at least one value")}getNextValue(){let value=this.values[this.index];return this.index=(this.index+1)%this.values.length,value}get next(){return sync(()=>{let value=this.getNextValue();if(typeof value==="number")return Math.max(0,Math.min(1,value));return hash(value)/2147483647})}get nextBoolean(){return sync(()=>{let value=this.getNextValue();if(typeof value==="boolean")return value;return hash(value)%2===0})}get nextInt(){return sync(()=>{let value=this.getNextValue();if(typeof value==="number"&&Number.isFinite(value))return Math.round(value);return Math.abs(hash(value))})}nextRange(min3,max3){return map10(this.next,(n)=>(max3-min3)*n+min3)}nextIntBetween(min3,max3){return sync(()=>{let value=this.getNextValue();if(typeof value==="number"&&Number.isFinite(value))return Math.max(min3,Math.min(max3-1,Math.round(value)));let hash2=Math.abs(hash(value));return min3+hash2%(max3-min3)})}shuffle(elements){return shuffleWith(elements,(n)=>this.nextIntBetween(0,n))}}var fixed=(values3)=>new FixedRandomImpl(values3);var TracerTypeId=Symbol.for("effect/Tracer"),make22=(options)=>({[TracerTypeId]:TracerTypeId,...options}),tracerTag=GenericTag("effect/Tracer"),spanTag=GenericTag("effect/ParentSpan"),randomHexString=function(){return function(length){let result="";for(let i=0;i<length;i++)result+="abcdef0123456789".charAt(Math.floor(Math.random()*16));return result}}();class NativeSpan{name;parent;context;startTime;kind;_tag="Span";spanId;traceId="native";sampled=!0;status;attributes;events=[];links;constructor(name,parent,context2,links,startTime,kind){this.name=name,this.parent=parent,this.context=context2,this.startTime=startTime,this.kind=kind,this.status={_tag:"Started",startTime},this.attributes=new Map,this.traceId=parent._tag==="Some"?parent.value.traceId:randomHexString(32),this.spanId=randomHexString(16),this.links=Array.from(links)}end(endTime,exit2){this.status={_tag:"Ended",endTime,exit:exit2,startTime:this.status.startTime}}attribute(key,value){this.attributes.set(key,value)}event(name,startTime,attributes){this.events.push([name,startTime,attributes??{}])}addLinks(links){this.links.push(...links)}}var nativeTracer=make22({span:(name,parent,context2,links,startTime,kind)=>new NativeSpan(name,parent,context2,links,startTime,kind),context:(f)=>f()});var addSpanStackTrace=(options)=>{if(options?.captureStackTrace===!1)return options;else if(options?.captureStackTrace!==void 0&&typeof options.captureStackTrace!=="boolean")return options;let limit=Error.stackTraceLimit;Error.stackTraceLimit=3;let traceError=Error();Error.stackTraceLimit=limit;let cache=!1;return{...options,captureStackTrace:()=>{if(cache!==!1)return cache;if(traceError.stack!==void 0){let stack=traceError.stack.split(`
23
+ `)}`:this.toString();else if("Bun"in globalThis)return pretty(fail(this),{renderErrorCause:!0});return this}}return Object.assign(YieldableError2.prototype,StructuralCommitPrototype),YieldableError2}(),makeException=(proto2,tag)=>{class Base2 extends YieldableError{_tag=tag}return Object.assign(Base2.prototype,proto2),Base2.prototype.name=tag,Base2},RuntimeExceptionTypeId=Symbol.for("effect/Cause/errors/RuntimeException"),RuntimeException=makeException({[RuntimeExceptionTypeId]:RuntimeExceptionTypeId},"RuntimeException"),isRuntimeException=(u)=>hasProperty(u,RuntimeExceptionTypeId),InterruptedExceptionTypeId=Symbol.for("effect/Cause/errors/InterruptedException"),InterruptedException=makeException({[InterruptedExceptionTypeId]:InterruptedExceptionTypeId},"InterruptedException"),isInterruptedException=(u)=>hasProperty(u,InterruptedExceptionTypeId),IllegalArgumentExceptionTypeId=Symbol.for("effect/Cause/errors/IllegalArgument"),IllegalArgumentException=makeException({[IllegalArgumentExceptionTypeId]:IllegalArgumentExceptionTypeId},"IllegalArgumentException");var NoSuchElementExceptionTypeId=Symbol.for("effect/Cause/errors/NoSuchElement"),NoSuchElementException=makeException({[NoSuchElementExceptionTypeId]:NoSuchElementExceptionTypeId},"NoSuchElementException"),isNoSuchElementException=(u)=>hasProperty(u,NoSuchElementExceptionTypeId),InvalidPubSubCapacityExceptionTypeId=Symbol.for("effect/Cause/errors/InvalidPubSubCapacityException"),InvalidPubSubCapacityException=makeException({[InvalidPubSubCapacityExceptionTypeId]:InvalidPubSubCapacityExceptionTypeId},"InvalidPubSubCapacityException"),ExceededCapacityExceptionTypeId=Symbol.for("effect/Cause/errors/ExceededCapacityException"),ExceededCapacityException=makeException({[ExceededCapacityExceptionTypeId]:ExceededCapacityExceptionTypeId},"ExceededCapacityException");var TimeoutExceptionTypeId=Symbol.for("effect/Cause/errors/Timeout"),TimeoutException=makeException({[TimeoutExceptionTypeId]:TimeoutExceptionTypeId},"TimeoutException"),timeoutExceptionFromDuration=(duration)=>new TimeoutException(`Operation timed out after '${format2(duration)}'`);var UnknownExceptionTypeId=Symbol.for("effect/Cause/errors/UnknownException"),UnknownException=function(){class UnknownException2 extends YieldableError{_tag="UnknownException";error;constructor(cause,message){super(message??"An unknown error occurred",{cause});this.error=cause}}return Object.assign(UnknownException2.prototype,{[UnknownExceptionTypeId]:UnknownExceptionTypeId,name:"UnknownException"}),UnknownException2}();var exitIsExit=(u)=>isEffect(u)&&("_tag"in u)&&(u._tag==="Success"||u._tag==="Failure"),exitIsFailure=(self)=>self._tag==="Failure",exitIsSuccess=(self)=>self._tag==="Success";var exitAs=dual(2,(self,value)=>{switch(self._tag){case OP_FAILURE:return exitFailCause(self.effect_instruction_i0);case OP_SUCCESS:return exitSucceed(value)}}),exitAsVoid=(self)=>exitAs(self,void 0);var exitCollectAll=(exits,options)=>exitCollectAllInternal(exits,options?.parallel?parallel:sequential),exitDie=(defect)=>exitFailCause(die(defect));var exitFail=(error)=>exitFailCause(fail(error)),exitFailCause=(cause)=>{let effect=new EffectPrimitiveFailure(OP_FAILURE);return effect.effect_instruction_i0=cause,effect},exitFlatMap=dual(2,(self,f)=>{switch(self._tag){case OP_FAILURE:return exitFailCause(self.effect_instruction_i0);case OP_SUCCESS:return f(self.effect_instruction_i0)}});var exitFlatten=(self)=>pipe(self,exitFlatMap(identity));var exitInterrupt=(fiberId2)=>exitFailCause(interrupt(fiberId2)),exitMap=dual(2,(self,f)=>{switch(self._tag){case OP_FAILURE:return exitFailCause(self.effect_instruction_i0);case OP_SUCCESS:return exitSucceed(f(self.effect_instruction_i0))}}),exitMapBoth=dual(2,(self,{onFailure,onSuccess})=>{switch(self._tag){case OP_FAILURE:return exitFailCause(pipe(self.effect_instruction_i0,map8(onFailure)));case OP_SUCCESS:return exitSucceed(onSuccess(self.effect_instruction_i0))}});var exitMatch=dual(2,(self,{onFailure,onSuccess})=>{switch(self._tag){case OP_FAILURE:return onFailure(self.effect_instruction_i0);case OP_SUCCESS:return onSuccess(self.effect_instruction_i0)}}),exitMatchEffect=dual(2,(self,{onFailure,onSuccess})=>{switch(self._tag){case OP_FAILURE:return onFailure(self.effect_instruction_i0);case OP_SUCCESS:return onSuccess(self.effect_instruction_i0)}}),exitSucceed=(value)=>{let effect=new EffectPrimitiveSuccess(OP_SUCCESS);return effect.effect_instruction_i0=value,effect},exitVoid=exitSucceed(void 0),exitZip=dual(2,(self,that)=>exitZipWith(self,that,{onSuccess:(a,a2)=>[a,a2],onFailure:sequential}));var exitZipRight=dual(2,(self,that)=>exitZipWith(self,that,{onSuccess:(_,a2)=>a2,onFailure:sequential}));var exitZipWith=dual(3,(self,that,{onFailure,onSuccess})=>{switch(self._tag){case OP_FAILURE:switch(that._tag){case OP_SUCCESS:return exitFailCause(self.effect_instruction_i0);case OP_FAILURE:return exitFailCause(onFailure(self.effect_instruction_i0,that.effect_instruction_i0))}case OP_SUCCESS:switch(that._tag){case OP_SUCCESS:return exitSucceed(onSuccess(self.effect_instruction_i0,that.effect_instruction_i0));case OP_FAILURE:return exitFailCause(that.effect_instruction_i0)}}}),exitCollectAllInternal=(exits,combineCauses)=>{let list=fromIterable2(exits);if(!isNonEmpty(list))return none2();return pipe(tailNonEmpty2(list),reduce(pipe(headNonEmpty2(list),exitMap(of2)),(accumulator,current)=>pipe(accumulator,exitZipWith(current,{onSuccess:(list2,value)=>pipe(list2,prepend2(value)),onFailure:combineCauses}))),exitMap(reverse2),exitMap((chunk)=>toReadonlyArray(chunk)),some2)},deferredUnsafeMake=(fiberId2)=>{return{...CommitPrototype,[DeferredTypeId]:deferredVariance,state:make11(pending([])),commit(){return deferredAwait(this)},blockingOn:fiberId2}},deferredMake=()=>flatMap8(fiberId,(id)=>deferredMakeAs(id)),deferredMakeAs=(fiberId2)=>sync(()=>deferredUnsafeMake(fiberId2)),deferredAwait=(self)=>asyncInterrupt((resume)=>{let state=get6(self.state);switch(state._tag){case OP_STATE_DONE:return resume(state.effect);case OP_STATE_PENDING:return state.joiners.push(resume),deferredInterruptJoiner(self,resume)}},self.blockingOn),deferredComplete=dual(2,(self,effect)=>intoDeferred(effect,self)),deferredCompleteWith=dual(2,(self,effect)=>sync(()=>{let state=get6(self.state);switch(state._tag){case OP_STATE_DONE:return!1;case OP_STATE_PENDING:{set2(self.state,done(effect));for(let i=0,len=state.joiners.length;i<len;i++)state.joiners[i](effect);return!0}}})),deferredDone=dual(2,(self,exit2)=>deferredCompleteWith(self,exit2)),deferredFail=dual(2,(self,error)=>deferredCompleteWith(self,fail2(error)));var deferredFailCause=dual(2,(self,cause)=>deferredCompleteWith(self,failCause(cause)));var deferredInterrupt=(self)=>flatMap8(fiberId,(fiberId2)=>deferredCompleteWith(self,interruptWith(fiberId2))),deferredInterruptWith=dual(2,(self,fiberId2)=>deferredCompleteWith(self,interruptWith(fiberId2))),deferredIsDone=(self)=>sync(()=>get6(self.state)._tag===OP_STATE_DONE),deferredPoll=(self)=>sync(()=>{let state=get6(self.state);switch(state._tag){case OP_STATE_DONE:return some2(state.effect);case OP_STATE_PENDING:return none2()}}),deferredSucceed=dual(2,(self,value)=>deferredCompleteWith(self,succeed(value)));var deferredUnsafeDone=(self,effect)=>{let state=get6(self.state);if(state._tag===OP_STATE_PENDING){set2(self.state,done(effect));for(let i=0,len=state.joiners.length;i<len;i++)state.joiners[i](effect)}},deferredInterruptJoiner=(self,joiner)=>sync(()=>{let state=get6(self.state);if(state._tag===OP_STATE_PENDING){let index=state.joiners.indexOf(joiner);if(index>=0)state.joiners.splice(index,1)}}),constContext=withFiberRuntime((fiber)=>exitSucceed(fiber.currentContext)),context=()=>constContext;var contextWithEffect=(f)=>flatMap8(context(),f),provideContext=dual(2,(self,context2)=>fiberRefLocally(currentContext,context2)(self)),provideSomeContext=dual(2,(self,context2)=>fiberRefLocallyWith(currentContext,(parent)=>merge3(parent,context2))(self)),mapInputContext=dual(2,(self,f)=>contextWithEffect((context2)=>provideContext(self,f(context2)))),filterEffectOrElse=dual(2,(self,options)=>flatMap8(self,(a)=>flatMap8(options.predicate(a),(pass)=>pass?succeed(a):options.orElse(a)))),filterEffectOrFail=dual(2,(self,options)=>filterEffectOrElse(self,{predicate:options.predicate,orElse:(a)=>fail2(options.orFailWith(a))})),currentSpanFromFiber=(fiber)=>{let span2=fiber.currentSpan;return span2!==void 0&&span2._tag==="Span"?some2(span2):none2()},NoopSpanProto={_tag:"Span",spanId:"noop",traceId:"noop",sampled:!1,status:{_tag:"Ended",startTime:BigInt(0),endTime:BigInt(0),exit:exitVoid},attributes:new Map,links:[],kind:"internal",attribute(){},event(){},end(){},addLinks(){}},noopSpan=(options)=>Object.assign(Object.create(NoopSpanProto),options);var fail3=fail,die3=die,interrupt3=interrupt;var isDieType2=isDieType;var isInterrupted2=isInterrupted,isInterruptedOnly2=isInterruptedOnly;var interruptors2=interruptors;var failureOrCause2=failureOrCause,flipCauseOption2=flipCauseOption;var map11=map8;var squash=causeSquash;var IllegalArgumentException2=IllegalArgumentException;var NoSuchElementException2=NoSuchElementException;var RuntimeException2=RuntimeException,isRuntimeException2=isRuntimeException;var exports_Effect={};__export(exports_Effect,{zipWith:()=>zipWith6,zipRight:()=>zipRight4,zipLeft:()=>zipLeft3,zip:()=>zip5,yieldNow:()=>yieldNow4,withUnhandledErrorLogLevel:()=>withUnhandledErrorLogLevel2,withTracerTiming:()=>withTracerTiming2,withTracerScoped:()=>withTracerScoped2,withTracerEnabled:()=>withTracerEnabled2,withTracer:()=>withTracer2,withSpanScoped:()=>withSpanScoped2,withSpan:()=>withSpan3,withSchedulingPriority:()=>withSchedulingPriority2,withScheduler:()=>withScheduler2,withRuntimeFlagsPatchScoped:()=>withRuntimeFlagsPatchScoped,withRuntimeFlagsPatch:()=>withRuntimeFlagsPatch,withRequestCaching:()=>withRequestCaching2,withRequestCache:()=>withRequestCache2,withRequestBatching:()=>withRequestBatching2,withRandomScoped:()=>withRandomScoped2,withRandomFixed:()=>withRandomFixed,withRandom:()=>withRandom2,withParentSpan:()=>withParentSpan3,withMetric:()=>withMetric2,withMaxOpsBeforeYield:()=>withMaxOpsBeforeYield2,withLogSpan:()=>withLogSpan2,withFiberRuntime:()=>withFiberRuntime2,withExecutionPlan:()=>withExecutionPlan2,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_3,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:()=>tapErrorCause3,tapError:()=>tapError3,tapDefect:()=>tapDefect2,tapBoth:()=>tapBoth2,tap:()=>tap3,takeWhile:()=>takeWhile3,takeUntil:()=>takeUntil2,tagMetricsScoped:()=>tagMetricsScoped2,tagMetrics:()=>tagMetrics2,sync:()=>sync4,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:()=>scoped2,scopeWith:()=>scopeWith2,scope:()=>scope3,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:()=>retry2,request:()=>request,replicateEffect:()=>replicateEffect2,replicate:()=>replicate2,repeatOrElse:()=>repeatOrElse,repeatN:()=>repeatN2,repeat:()=>repeat,reduceWhile:()=>reduceWhile2,reduceRight:()=>reduceRight4,reduceEffect:()=>reduceEffect3,reduce:()=>reduce11,randomWith:()=>randomWith2,random:()=>random3,raceWith:()=>raceWith2,raceFirst:()=>raceFirst2,raceAll:()=>raceAll2,race:()=>race2,provideServiceEffect:()=>provideServiceEffect2,provideService:()=>provideService3,provide:()=>provide2,promise:()=>promise2,patchRuntimeFlags:()=>patchRuntimeFlags,patchFiberRefs:()=>patchFiberRefs2,partition:()=>partition4,parallelFinalizers:()=>parallelFinalizers2,parallelErrors:()=>parallelErrors2,orElseSucceed:()=>orElseSucceed2,orElseFail:()=>orElseFail2,orElse:()=>orElse5,orDieWith:()=>orDieWith2,orDie:()=>orDie3,optionFromOptional:()=>optionFromOptional2,option:()=>option2,once:()=>once3,onInterrupt:()=>onInterrupt2,onExit:()=>onExit3,onError:()=>onError2,none:()=>none9,never:()=>never3,negate:()=>negate2,metricLabels:()=>metricLabels2,mergeAll:()=>mergeAll5,merge:()=>merge7,matchEffect:()=>matchEffect2,matchCauseEffect:()=>matchCauseEffect3,matchCause:()=>matchCause3,match:()=>match13,mapInputContext:()=>mapInputContext3,mapErrorCause:()=>mapErrorCause2,mapError:()=>mapError3,mapBoth:()=>mapBoth4,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:()=>log3,locallyWith:()=>locallyWith,locallyScopedWith:()=>locallyScopedWith,locallyScoped:()=>locallyScoped,locally:()=>locally,linkSpans:()=>linkSpans2,linkSpanCurrent:()=>linkSpanCurrent2,liftPredicate:()=>liftPredicate3,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:()=>forEach6,fnUntraced:()=>fnUntraced2,fn:()=>fn,flipWith:()=>flipWith2,flip:()=>flip2,flatten:()=>flatten8,flatMap:()=>flatMap11,firstSuccessOf:()=>firstSuccessOf2,findFirst:()=>findFirst6,finalizersMask:()=>finalizersMask2,filterOrFail:()=>filterOrFail2,filterOrElse:()=>filterOrElse2,filterOrDieMessage:()=>filterOrDieMessage2,filterOrDie:()=>filterOrDie2,filterMap:()=>filterMap5,filterEffectOrFail:()=>filterEffectOrFail2,filterEffectOrElse:()=>filterEffectOrElse2,filter:()=>filter7,fiberIdWith:()=>fiberIdWith2,fiberId:()=>fiberId2,failSync:()=>failSync3,failCauseSync:()=>failCauseSync3,failCause:()=>failCause8,fail:()=>fail9,exit:()=>exit2,exists:()=>exists2,every:()=>every6,eventually:()=>eventually2,ensuringChildren:()=>ensuringChildren2,ensuringChild:()=>ensuringChild2,ensuring:()=>ensuring3,ensureSuccessType:()=>ensureSuccessType,ensureRequirementsType:()=>ensureRequirementsType,ensureErrorType:()=>ensureErrorType,either:()=>either4,dropWhile:()=>dropWhile3,dropUntil:()=>dropUntil2,disconnect:()=>disconnect2,diffFiberRefs:()=>diffFiberRefs2,dieSync:()=>dieSync3,dieMessage:()=>dieMessage2,die:()=>die6,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:()=>catchAllCause3,catchAll:()=>catchAll3,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:()=>asVoid3,asSomeError:()=>asSomeError2,asSome:()=>asSome2,as:()=>as4,ap:()=>ap,annotateSpans:()=>annotateSpans3,annotateLogsScoped:()=>annotateLogsScoped2,annotateLogs:()=>annotateLogs3,annotateCurrentSpan:()=>annotateCurrentSpan2,andThen:()=>andThen5,allowInterrupt:()=>allowInterrupt2,allWith:()=>allWith2,allSuccesses:()=>allSuccesses2,all:()=>all5,addFinalizer:()=>addFinalizer3,acquireUseRelease:()=>acquireUseRelease2,acquireReleaseInterruptible:()=>acquireReleaseInterruptible2,acquireRelease:()=>acquireRelease2,Tag:()=>Tag3,Service:()=>Service,EffectTypeId:()=>EffectTypeId3,Do:()=>Do2});var ClockSymbolKey="effect/Clock",ClockTypeId=Symbol.for(ClockSymbolKey),clockTag=GenericTag("effect/Clock"),MAX_TIMER_MILLIS=2147483647,globalClockScheduler={unsafeSchedule(task,duration){let millis2=toMillis(duration);if(millis2>MAX_TIMER_MILLIS)return constFalse;let completed=!1,handle=setTimeout(()=>{completed=!0,task()},millis2);return()=>{return clearTimeout(handle),!completed}}},performanceNowNanos=function(){let bigint1e62=BigInt(1e6);if(typeof performance>"u"||typeof performance.now!=="function")return()=>BigInt(Date.now())*bigint1e62;let origin;return()=>{if(origin===void 0)origin=BigInt(Date.now())*bigint1e62-BigInt(Math.round(performance.now()*1e6));return origin+BigInt(Math.round(performance.now()*1e6))}}(),processOrPerformanceNow=function(){let processHrtime=typeof process==="object"&&"hrtime"in process&&typeof process.hrtime.bigint==="function"?process.hrtime:void 0;if(!processHrtime)return performanceNowNanos;let origin=performanceNowNanos()-processHrtime.bigint();return()=>origin+processHrtime.bigint()}();class ClockImpl{[ClockTypeId]=ClockTypeId;unsafeCurrentTimeMillis(){return Date.now()}unsafeCurrentTimeNanos(){return processOrPerformanceNow()}currentTimeMillis=sync(()=>this.unsafeCurrentTimeMillis());currentTimeNanos=sync(()=>this.unsafeCurrentTimeNanos());scheduler(){return succeed(globalClockScheduler)}sleep(duration){return async_((resume)=>{let canceler=globalClockScheduler.unsafeSchedule(()=>resume(void_),duration);return asVoid(sync(canceler))})}}var make18=()=>new ClockImpl;var Order2=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 OP_AND="And",OP_OR="Or",OP_INVALID_DATA="InvalidData",OP_MISSING_DATA="MissingData",OP_SOURCE_UNAVAILABLE="SourceUnavailable",OP_UNSUPPORTED="Unsupported";var ConfigErrorSymbolKey="effect/ConfigError",ConfigErrorTypeId=Symbol.for(ConfigErrorSymbolKey),proto2={_tag:"ConfigError",[ConfigErrorTypeId]:ConfigErrorTypeId},And=(self,that)=>{let error=Object.create(proto2);return error._op=OP_AND,error.left=self,error.right=that,Object.defineProperty(error,"toString",{enumerable:!1,value(){return`${this.left} and ${this.right}`}}),Object.defineProperty(error,"message",{enumerable:!1,get(){return this.toString()}}),error},Or=(self,that)=>{let error=Object.create(proto2);return error._op=OP_OR,error.left=self,error.right=that,Object.defineProperty(error,"toString",{enumerable:!1,value(){return`${this.left} or ${this.right}`}}),Object.defineProperty(error,"message",{enumerable:!1,get(){return this.toString()}}),error},InvalidData=(path,message,options={pathDelim:"."})=>{let error=Object.create(proto2);return error._op=OP_INVALID_DATA,error.path=path,error.message=message,Object.defineProperty(error,"toString",{enumerable:!1,value(){return`(Invalid data at ${pipe(this.path,join(options.pathDelim))}: "${this.message}")`}}),error},MissingData=(path,message,options={pathDelim:"."})=>{let error=Object.create(proto2);return error._op=OP_MISSING_DATA,error.path=path,error.message=message,Object.defineProperty(error,"toString",{enumerable:!1,value(){return`(Missing data at ${pipe(this.path,join(options.pathDelim))}: "${this.message}")`}}),error},SourceUnavailable=(path,message,cause,options={pathDelim:"."})=>{let error=Object.create(proto2);return error._op=OP_SOURCE_UNAVAILABLE,error.path=path,error.message=message,error.cause=cause,Object.defineProperty(error,"toString",{enumerable:!1,value(){return`(Source unavailable at ${pipe(this.path,join(options.pathDelim))}: "${this.message}")`}}),error},Unsupported=(path,message,options={pathDelim:"."})=>{let error=Object.create(proto2);return error._op=OP_UNSUPPORTED,error.path=path,error.message=message,Object.defineProperty(error,"toString",{enumerable:!1,value(){return`(Unsupported operation at ${pipe(this.path,join(options.pathDelim))}: "${this.message}")`}}),error};var prefixed=dual(2,(self,prefix)=>{switch(self._op){case OP_AND:return And(prefixed(self.left,prefix),prefixed(self.right,prefix));case OP_OR:return Or(prefixed(self.left,prefix),prefixed(self.right,prefix));case OP_INVALID_DATA:return InvalidData([...prefix,...self.path],self.message);case OP_MISSING_DATA:return MissingData([...prefix,...self.path],self.message);case OP_SOURCE_UNAVAILABLE:return SourceUnavailable([...prefix,...self.path],self.message,self.cause);case OP_UNSUPPORTED:return Unsupported([...prefix,...self.path],self.message)}}),IsMissingDataOnlyReducer={andCase:(_,left3,right3)=>left3&&right3,orCase:(_,left3,right3)=>left3&&right3,invalidDataCase:constFalse,missingDataCase:constTrue,sourceUnavailableCase:constFalse,unsupportedCase:constFalse},reduceWithContext2=dual(3,(self,context2,reducer)=>{let input=[self],output=[];while(input.length>0){let error=input.pop();switch(error._op){case OP_AND:{input.push(error.right),input.push(error.left),output.push(left2({_op:"AndCase"}));break}case OP_OR:{input.push(error.right),input.push(error.left),output.push(left2({_op:"OrCase"}));break}case OP_INVALID_DATA:{output.push(right2(reducer.invalidDataCase(context2,error.path,error.message)));break}case OP_MISSING_DATA:{output.push(right2(reducer.missingDataCase(context2,error.path,error.message)));break}case OP_SOURCE_UNAVAILABLE:{output.push(right2(reducer.sourceUnavailableCase(context2,error.path,error.message,error.cause)));break}case OP_UNSUPPORTED:{output.push(right2(reducer.unsupportedCase(context2,error.path,error.message)));break}}}let accumulator=[];while(output.length>0){let either3=output.pop();switch(either3._op){case"Left":{switch(either3.left._op){case"AndCase":{let left3=accumulator.pop(),right3=accumulator.pop(),value=reducer.andCase(context2,left3,right3);accumulator.push(value);break}case"OrCase":{let left3=accumulator.pop(),right3=accumulator.pop(),value=reducer.orCase(context2,left3,right3);accumulator.push(value);break}}break}case"Right":{accumulator.push(either3.right);break}}}if(accumulator.length===0)throw Error("BUG: ConfigError.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues");return accumulator.pop()}),isMissingDataOnly=(self)=>reduceWithContext2(self,void 0,IsMissingDataOnlyReducer);var empty17={_tag:"Empty"};var patch5=dual(2,(path,patch6)=>{let input=of3(patch6),output=path;while(isCons(input)){let patch7=input.head;switch(patch7._tag){case"Empty":{input=input.tail;break}case"AndThen":{input=cons(patch7.first,cons(patch7.second,input.tail));break}case"MapName":{output=map3(output,patch7.f),input=input.tail;break}case"Nested":{output=prepend(output,patch7.name),input=input.tail;break}case"Unnested":{if(pipe(head(output),contains(patch7.name)))output=tailNonEmpty(output),input=input.tail;else return left2(MissingData(output,`Expected ${patch7.name} to be in path in ConfigProvider#unnested`));break}}}return right2(output)});var OP_CONSTANT="Constant",OP_FAIL2="Fail",OP_FALLBACK="Fallback",OP_DESCRIBED="Described",OP_LAZY="Lazy",OP_MAP_OR_FAIL="MapOrFail",OP_NESTED="Nested",OP_PRIMITIVE="Primitive",OP_SEQUENCE="Sequence",OP_HASHMAP="HashMap",OP_ZIP_WITH="ZipWith";var concat=(l,r)=>[...l,...r],ConfigProviderSymbolKey="effect/ConfigProvider",ConfigProviderTypeId=Symbol.for(ConfigProviderSymbolKey),configProviderTag=GenericTag("effect/ConfigProvider"),FlatConfigProviderSymbolKey="effect/ConfigProviderFlat",FlatConfigProviderTypeId=Symbol.for(FlatConfigProviderSymbolKey),make20=(options)=>({[ConfigProviderTypeId]:ConfigProviderTypeId,pipe(){return pipeArguments(this,arguments)},...options}),makeFlat=(options)=>({[FlatConfigProviderTypeId]:FlatConfigProviderTypeId,patch:options.patch,load:(path,config,split=!0)=>options.load(path,config,split),enumerateChildren:options.enumerateChildren}),fromFlat=(flat)=>make20({load:(config)=>flatMap8(fromFlatLoop(flat,empty(),config,!1),(chunk)=>match2(head(chunk),{onNone:()=>fail2(MissingData(empty(),`Expected a single value having structure: ${config}`)),onSome:succeed})),flattened:flat}),fromEnv=(options)=>{let{pathDelim,seqDelim}=Object.assign({},{pathDelim:"_",seqDelim:","},options),makePathString=(path)=>pipe(path,join(pathDelim)),unmakePathString=(pathString)=>pathString.split(pathDelim),getEnv=()=>typeof process<"u"&&("env"in process)&&typeof process.env==="object"?process.env:{};return fromFlat(makeFlat({load:(path,primitive,split=!0)=>{let pathString=makePathString(path),current=getEnv(),valueOpt=pathString in current?some2(current[pathString]):none2();return pipe(valueOpt,mapError(()=>MissingData(path,`Expected ${pathString} to exist in the process context`)),flatMap8((value)=>parsePrimitive(value,path,primitive,seqDelim,split)))},enumerateChildren:(path)=>sync(()=>{let current=getEnv(),filteredKeyPaths=Object.keys(current).map((value)=>unmakePathString(value.toUpperCase())).filter((keyPath)=>{for(let i=0;i<path.length;i++){let pathComponent=pipe(path,unsafeGet(i)),currentElement=keyPath[i];if(currentElement===void 0||pathComponent!==currentElement)return!1}return!0}).flatMap((keyPath)=>keyPath.slice(path.length,path.length+1));return fromIterable5(filteredKeyPaths)}),patch:empty17}))};var extend=(leftDef,rightDef,left3,right3)=>{let leftPad=unfold(left3.length,(index)=>index>=right3.length?none2():some2([leftDef(index),index+1])),rightPad=unfold(right3.length,(index)=>index>=left3.length?none2():some2([rightDef(index),index+1])),leftExtension=concat(left3,leftPad),rightExtension=concat(right3,rightPad);return[leftExtension,rightExtension]},appendConfigPath=(path,config)=>{let op=config;if(op._tag==="Nested"){let out=path.slice();while(op._tag==="Nested")out.push(op.name),op=op.config;return out}return path},fromFlatLoop=(flat,prefix,config,split)=>{let op=config;switch(op._tag){case OP_CONSTANT:return succeed(of(op.value));case OP_DESCRIBED:return suspend(()=>fromFlatLoop(flat,prefix,op.config,split));case OP_FAIL2:return fail2(MissingData(prefix,op.message));case OP_FALLBACK:return pipe(suspend(()=>fromFlatLoop(flat,prefix,op.first,split)),catchAll((error1)=>{if(op.condition(error1))return pipe(fromFlatLoop(flat,prefix,op.second,split),catchAll((error2)=>fail2(Or(error1,error2))));return fail2(error1)}));case OP_LAZY:return suspend(()=>fromFlatLoop(flat,prefix,op.config(),split));case OP_MAP_OR_FAIL:return suspend(()=>pipe(fromFlatLoop(flat,prefix,op.original,split),flatMap8(forEachSequential((a)=>pipe(op.mapOrFail(a),mapError(prefixed(appendConfigPath(prefix,op.original))))))));case OP_NESTED:return suspend(()=>fromFlatLoop(flat,concat(prefix,of(op.name)),op.config,split));case OP_PRIMITIVE:return pipe(patch5(prefix,flat.patch),flatMap8((prefix2)=>pipe(flat.load(prefix2,op,split),flatMap8((values3)=>{if(values3.length===0){let name=pipe(last(prefix2),getOrElse(()=>"<n/a>"));return fail2(MissingData([],`Expected ${op.description} with name ${name}`))}return succeed(values3)}))));case OP_SEQUENCE:return pipe(patch5(prefix,flat.patch),flatMap8((patchedPrefix)=>pipe(flat.enumerateChildren(patchedPrefix),flatMap8(indicesFrom),flatMap8((indices)=>{if(indices.length===0)return suspend(()=>map10(fromFlatLoop(flat,prefix,op.config,!0),of));return pipe(forEachSequential(indices,(index)=>fromFlatLoop(flat,append(prefix,`[${index}]`),op.config,!0)),map10((chunkChunk)=>{let flattened=flatten(chunkChunk);if(flattened.length===0)return of(empty());return of(flattened)}))}))));case OP_HASHMAP:return suspend(()=>pipe(patch5(prefix,flat.patch),flatMap8((prefix2)=>pipe(flat.enumerateChildren(prefix2),flatMap8((keys3)=>{return pipe(keys3,forEachSequential((key)=>fromFlatLoop(flat,concat(prefix2,of(key)),op.valueConfig,split)),map10((matrix)=>{if(matrix.length===0)return of(empty9());return pipe(transpose(matrix),map3((values3)=>fromIterable6(zip(fromIterable(keys3),values3))))}))})))));case OP_ZIP_WITH:return suspend(()=>pipe(fromFlatLoop(flat,prefix,op.left,split),either2,flatMap8((left3)=>pipe(fromFlatLoop(flat,prefix,op.right,split),either2,flatMap8((right3)=>{if(isLeft2(left3)&&isLeft2(right3))return fail2(And(left3.left,right3.left));if(isLeft2(left3)&&isRight2(right3))return fail2(left3.left);if(isRight2(left3)&&isLeft2(right3))return fail2(right3.left);if(isRight2(left3)&&isRight2(right3)){let path=pipe(prefix,join(".")),fail4=fromFlatLoopFail(prefix,path),[lefts,rights]=extend(fail4,fail4,pipe(left3.right,map3(right2)),pipe(right3.right,map3(right2)));return pipe(lefts,zip(rights),forEachSequential(([left4,right4])=>pipe(zip2(left4,right4),map10(([left5,right5])=>op.zip(left5,right5)))))}throw Error("BUG: ConfigProvider.fromFlatLoop - please report an issue at https://github.com/Effect-TS/effect/issues")})))))}},fromFlatLoopFail=(prefix,path)=>(index)=>left2(MissingData(prefix,`The element at index ${index} in a sequence at path "${path}" was missing`));var splitPathString=(text,delim)=>{return text.split(new RegExp(`\\s*${escape(delim)}\\s*`))},parsePrimitive=(text,path,primitive,delimiter,split)=>{if(!split)return pipe(primitive.parse(text),mapBoth({onFailure:prefixed(path),onSuccess:of}));return pipe(splitPathString(text,delimiter),forEachSequential((char)=>primitive.parse(char.trim())),mapError(prefixed(path)))},transpose=(array3)=>{return Object.keys(array3[0]).map((column)=>array3.map((row)=>row[column]))},indicesFrom=(quotedIndices)=>pipe(forEachSequential(quotedIndices,parseQuotedIndex),mapBoth({onFailure:()=>empty(),onSuccess:sort(Order2)}),either2,map10(merge));var QUOTED_INDEX_REGEX=/^(\[(\d+)\])$/,parseQuotedIndex=(str)=>{let match6=str.match(QUOTED_INDEX_REGEX);if(match6!==null){let matchedIndex=match6[2];return pipe(matchedIndex!==void 0&&matchedIndex.length>0?some2(matchedIndex):none2(),flatMap(parseInteger))}return none2()};var parseInteger=(str)=>{let parsedIndex=Number.parseInt(str);return Number.isNaN(parsedIndex)?none2():some2(parsedIndex)};var TypeId8=Symbol.for("effect/Console"),consoleTag=GenericTag("effect/Console"),defaultConsole={[TypeId8]:TypeId8,assert(condition,...args){return sync(()=>{console.assert(condition,...args)})},clear:sync(()=>{console.clear()}),count(label){return sync(()=>{console.count(label)})},countReset(label){return sync(()=>{console.countReset(label)})},debug(...args){return sync(()=>{console.debug(...args)})},dir(item,options){return sync(()=>{console.dir(item,options)})},dirxml(...args){return sync(()=>{console.dirxml(...args)})},error(...args){return sync(()=>{console.error(...args)})},group(options){return options?.collapsed?sync(()=>console.groupCollapsed(options?.label)):sync(()=>console.group(options?.label))},groupEnd:sync(()=>{console.groupEnd()}),info(...args){return sync(()=>{console.info(...args)})},log(...args){return sync(()=>{console.log(...args)})},table(tabularData,properties){return sync(()=>{console.table(tabularData,properties)})},time(label){return sync(()=>console.time(label))},timeEnd(label){return sync(()=>console.timeEnd(label))},timeLog(label,...args){return sync(()=>{console.timeLog(label,...args)})},trace(...args){return sync(()=>{console.trace(...args)})},warn(...args){return sync(()=>{console.warn(...args)})},unsafe:console};var RandomSymbolKey="effect/Random",RandomTypeId=Symbol.for(RandomSymbolKey),randomTag=GenericTag("effect/Random");class RandomImpl{seed;[RandomTypeId]=RandomTypeId;PRNG;constructor(seed){this.seed=seed,this.PRNG=new PCGRandom(seed)}get next(){return sync(()=>this.PRNG.number())}get nextBoolean(){return map10(this.next,(n)=>n>0.5)}get nextInt(){return sync(()=>this.PRNG.integer(Number.MAX_SAFE_INTEGER))}nextRange(min3,max3){return map10(this.next,(n)=>(max3-min3)*n+min3)}nextIntBetween(min3,max3){return sync(()=>this.PRNG.integer(max3-min3)+min3)}shuffle(elements){return shuffleWith(elements,(n)=>this.nextIntBetween(0,n))}}var shuffleWith=(elements,nextIntBounded)=>{return suspend(()=>pipe(sync(()=>Array.from(elements)),flatMap8((buffer)=>{let numbers=[];for(let i=buffer.length;i>=2;i=i-1)numbers.push(i);return pipe(numbers,forEachSequentialDiscard((n)=>pipe(nextIntBounded(n),map10((k)=>swap(buffer,n-1,k)))),as(fromIterable2(buffer)))})))},swap=(buffer,index1,index2)=>{let tmp=buffer[index1];return buffer[index1]=buffer[index2],buffer[index2]=tmp,buffer},make21=(seed)=>new RandomImpl(hash(seed));class FixedRandomImpl{values;[RandomTypeId]=RandomTypeId;index=0;constructor(values3){if(this.values=values3,values3.length===0)throw Error("Requires at least one value")}getNextValue(){let value=this.values[this.index];return this.index=(this.index+1)%this.values.length,value}get next(){return sync(()=>{let value=this.getNextValue();if(typeof value==="number")return Math.max(0,Math.min(1,value));return hash(value)/2147483647})}get nextBoolean(){return sync(()=>{let value=this.getNextValue();if(typeof value==="boolean")return value;return hash(value)%2===0})}get nextInt(){return sync(()=>{let value=this.getNextValue();if(typeof value==="number"&&Number.isFinite(value))return Math.round(value);return Math.abs(hash(value))})}nextRange(min3,max3){return map10(this.next,(n)=>(max3-min3)*n+min3)}nextIntBetween(min3,max3){return sync(()=>{let value=this.getNextValue();if(typeof value==="number"&&Number.isFinite(value))return Math.max(min3,Math.min(max3-1,Math.round(value)));let hash2=Math.abs(hash(value));return min3+hash2%(max3-min3)})}shuffle(elements){return shuffleWith(elements,(n)=>this.nextIntBetween(0,n))}}var fixed=(values3)=>new FixedRandomImpl(values3);var TracerTypeId=Symbol.for("effect/Tracer"),make22=(options)=>({[TracerTypeId]:TracerTypeId,...options}),tracerTag=GenericTag("effect/Tracer"),spanTag=GenericTag("effect/ParentSpan"),randomHexString=function(){return function(length){let result="";for(let i=0;i<length;i++)result+="abcdef0123456789".charAt(Math.floor(Math.random()*16));return result}}();class NativeSpan{name;parent;context;startTime;kind;_tag="Span";spanId;traceId="native";sampled=!0;status;attributes;events=[];links;constructor(name,parent,context2,links,startTime,kind){this.name=name,this.parent=parent,this.context=context2,this.startTime=startTime,this.kind=kind,this.status={_tag:"Started",startTime},this.attributes=new Map,this.traceId=parent._tag==="Some"?parent.value.traceId:randomHexString(32),this.spanId=randomHexString(16),this.links=Array.from(links)}end(endTime,exit2){this.status={_tag:"Ended",endTime,exit:exit2,startTime:this.status.startTime}}attribute(key,value){this.attributes.set(key,value)}event(name,startTime,attributes){this.events.push([name,startTime,attributes??{}])}addLinks(links){this.links.push(...links)}}var nativeTracer=make22({span:(name,parent,context2,links,startTime,kind)=>new NativeSpan(name,parent,context2,links,startTime,kind),context:(f)=>f()});var addSpanStackTrace=(options)=>{if(options?.captureStackTrace===!1)return options;else if(options?.captureStackTrace!==void 0&&typeof options.captureStackTrace!=="boolean")return options;let limit=Error.stackTraceLimit;Error.stackTraceLimit=3;let traceError=Error();Error.stackTraceLimit=limit;let cache=!1;return{...options,captureStackTrace:()=>{if(cache!==!1)return cache;if(traceError.stack!==void 0){let stack=traceError.stack.split(`
24
24
  `);if(stack[3]!==void 0)return cache=stack[3].trim(),cache}}}},DisablePropagation=Reference2()("effect/Tracer/DisablePropagation",{defaultValue:constFalse});var liveServices=pipe(empty8(),add4(clockTag,make18()),add4(consoleTag,defaultConsole),add4(randomTag,make21(Math.random())),add4(configProviderTag,fromEnv()),add4(tracerTag,nativeTracer)),currentServices=globalValue(Symbol.for("effect/DefaultServices/currentServices"),()=>fiberRefUnsafeMakeContext(liveServices)),sleep=(duration)=>{let decodedDuration=decode(duration);return clockWith((clock)=>clock.sleep(decodedDuration))},defaultServicesWith=(f)=>withFiberRuntime((fiber)=>f(fiber.currentDefaultServices)),clockWith=(f)=>defaultServicesWith((services)=>f(services.unsafeMap.get(clockTag.key))),currentTimeMillis=clockWith((clock)=>clock.currentTimeMillis),currentTimeNanos=clockWith((clock)=>clock.currentTimeNanos),withClock=dual(2,(effect,c)=>fiberRefLocallyWith(currentServices,add4(clockTag,c))(effect)),withConfigProvider=dual(2,(self,provider)=>fiberRefLocallyWith(currentServices,add4(configProviderTag,provider))(self)),configProviderWith=(f)=>defaultServicesWith((services)=>f(services.unsafeMap.get(configProviderTag.key))),config=(config2)=>configProviderWith((_)=>_.load(config2));var randomWith=(f)=>defaultServicesWith((services)=>f(services.unsafeMap.get(randomTag.key))),withRandom=dual(2,(effect,value)=>fiberRefLocallyWith(currentServices,add4(randomTag,value))(effect)),next=randomWith((random2)=>random2.next);var tracerWith=(f)=>defaultServicesWith((services)=>f(services.unsafeMap.get(tracerTag.key))),withTracer=dual(2,(effect,value)=>fiberRefLocallyWith(currentServices,add4(tracerTag,value))(effect));var not=(self)=>!self;var EffectPrototype2=EffectPrototype,CommitPrototype2=CommitPrototype;var Base2=Base;class Class extends Base2{}var OP_SEQUENTIAL2="Sequential",OP_PARALLEL2="Parallel",OP_PARALLEL_N="ParallelN",sequential2={_tag:OP_SEQUENTIAL2},parallel2={_tag:OP_PARALLEL2},parallelN=(parallelism)=>({_tag:OP_PARALLEL_N,parallelism}),isSequential=(self)=>self._tag===OP_SEQUENTIAL2,isParallel=(self)=>self._tag===OP_PARALLEL2;var sequential3=sequential2,parallel3=parallel2,parallelN2=parallelN;function unsafeMake4(fiberRefLocals){return new FiberRefsImpl(fiberRefLocals)}function empty18(){return unsafeMake4(new Map)}var FiberRefsSym=Symbol.for("effect/FiberRefs");class FiberRefsImpl{locals;[FiberRefsSym]=FiberRefsSym;constructor(locals){this.locals=locals}pipe(){return pipeArguments(this,arguments)}}var findAncestor=(_ref,_parentStack,_childStack,_childModified=!1)=>{let ref=_ref,parentStack=_parentStack,childStack=_childStack,childModified=_childModified,ret=void 0;while(ret===void 0)if(isNonEmptyReadonlyArray(parentStack)&&isNonEmptyReadonlyArray(childStack)){let parentFiberId=headNonEmpty(parentStack)[0],parentAncestors=tailNonEmpty(parentStack),childFiberId=headNonEmpty(childStack)[0],childRefValue=headNonEmpty(childStack)[1],childAncestors=tailNonEmpty(childStack);if(parentFiberId.startTimeMillis<childFiberId.startTimeMillis)childStack=childAncestors,childModified=!0;else if(parentFiberId.startTimeMillis>childFiberId.startTimeMillis)parentStack=parentAncestors;else if(parentFiberId.id<childFiberId.id)childStack=childAncestors,childModified=!0;else if(parentFiberId.id>childFiberId.id)parentStack=parentAncestors;else ret=[childRefValue,childModified]}else ret=[ref.initial,!0];return ret},joinAs=dual(3,(self,fiberId2,that)=>{let parentFiberRefs=new Map(self.locals);return that.locals.forEach((childStack,fiberRef)=>{let childValue=childStack[0][1];if(!childStack[0][0][symbol2](fiberId2)){if(!parentFiberRefs.has(fiberRef)){if(equals(childValue,fiberRef.initial))return;parentFiberRefs.set(fiberRef,[[fiberId2,fiberRef.join(fiberRef.initial,childValue)]]);return}let parentStack=parentFiberRefs.get(fiberRef),[ancestor,wasModified]=findAncestor(fiberRef,parentStack,childStack);if(wasModified){let patch6=fiberRef.diff(ancestor,childValue),oldValue=parentStack[0][1],newValue=fiberRef.join(oldValue,fiberRef.patch(patch6)(oldValue));if(!equals(oldValue,newValue)){let newStack,parentFiberId=parentStack[0][0];if(parentFiberId[symbol2](fiberId2))newStack=[[parentFiberId,newValue],...parentStack.slice(1)];else newStack=[[fiberId2,newValue],...parentStack];parentFiberRefs.set(fiberRef,newStack)}}}}),new FiberRefsImpl(parentFiberRefs)}),forkAs=dual(2,(self,childId)=>{let map12=new Map;return unsafeForkAs(self,map12,childId),new FiberRefsImpl(map12)}),unsafeForkAs=(self,map12,fiberId2)=>{self.locals.forEach((stack,fiberRef)=>{let oldValue=stack[0][1],newValue=fiberRef.patch(fiberRef.fork)(oldValue);if(equals(oldValue,newValue))map12.set(fiberRef,stack);else map12.set(fiberRef,[[fiberId2,newValue],...stack])})},fiberRefs=(self)=>fromIterable5(self.locals.keys()),setAll=(self)=>forEachSequentialDiscard(fiberRefs(self),(fiberRef)=>fiberRefSet(fiberRef,getOrDefault(self,fiberRef))),delete_=dual(2,(self,fiberRef)=>{let locals=new Map(self.locals);return locals.delete(fiberRef),new FiberRefsImpl(locals)}),get8=dual(2,(self,fiberRef)=>{if(!self.locals.has(fiberRef))return none2();return some2(headNonEmpty(self.locals.get(fiberRef))[1])}),getOrDefault=dual(2,(self,fiberRef)=>pipe(get8(self,fiberRef),getOrElse(()=>fiberRef.initial))),updateAs=dual(2,(self,{fiberId:fiberId2,fiberRef,value})=>{if(self.locals.size===0)return new FiberRefsImpl(new Map([[fiberRef,[[fiberId2,value]]]]));let locals=new Map(self.locals);return unsafeUpdateAs(locals,fiberId2,fiberRef,value),new FiberRefsImpl(locals)}),unsafeUpdateAs=(locals,fiberId2,fiberRef,value)=>{let oldStack=locals.get(fiberRef)??[],newStack;if(isNonEmptyReadonlyArray(oldStack)){let[currentId,currentValue]=headNonEmpty(oldStack);if(currentId[symbol2](fiberId2))if(equals(currentValue,value))return;else newStack=[[fiberId2,value],...oldStack.slice(1)];else newStack=[[fiberId2,value],...oldStack]}else newStack=[[fiberId2,value]];locals.set(fiberRef,newStack)},updateManyAs=dual(2,(self,{entries:entries2,forkAs:forkAs2})=>{if(self.locals.size===0)return new FiberRefsImpl(new Map(entries2));let locals=new Map(self.locals);if(forkAs2!==void 0)unsafeForkAs(self,locals,forkAs2);return entries2.forEach(([fiberRef,values3])=>{if(values3.length===1)unsafeUpdateAs(locals,values3[0][0],fiberRef,values3[0][1]);else values3.forEach(([fiberId2,value])=>{unsafeUpdateAs(locals,fiberId2,fiberRef,value)})}),new FiberRefsImpl(locals)});var get9=get8,getOrDefault2=getOrDefault,joinAs2=joinAs,setAll2=setAll,updateAs2=updateAs,updateManyAs2=updateManyAs;var empty19=empty18;var OP_EMPTY2="Empty",OP_ADD="Add",OP_REMOVE="Remove",OP_UPDATE="Update",OP_AND_THEN="AndThen",empty20={_tag:OP_EMPTY2},diff5=(oldValue,newValue)=>{let missingLocals=new Map(oldValue.locals),patch6=empty20;for(let[fiberRef,pairs]of newValue.locals.entries()){let newValue2=headNonEmpty(pairs)[1],old=missingLocals.get(fiberRef);if(old!==void 0){let oldValue2=headNonEmpty(old)[1];if(!equals(oldValue2,newValue2))patch6=combine7({_tag:OP_UPDATE,fiberRef,patch:fiberRef.diff(oldValue2,newValue2)})(patch6)}else patch6=combine7({_tag:OP_ADD,fiberRef,value:newValue2})(patch6);missingLocals.delete(fiberRef)}for(let[fiberRef]of missingLocals.entries())patch6=combine7({_tag:OP_REMOVE,fiberRef})(patch6);return patch6},combine7=dual(2,(self,that)=>({_tag:OP_AND_THEN,first:self,second:that})),patch6=dual(3,(self,fiberId2,oldValue)=>{let fiberRefs2=oldValue,patches=of(self);while(isNonEmptyReadonlyArray(patches)){let head3=headNonEmpty(patches),tail=tailNonEmpty(patches);switch(head3._tag){case OP_EMPTY2:{patches=tail;break}case OP_ADD:{fiberRefs2=updateAs(fiberRefs2,{fiberId:fiberId2,fiberRef:head3.fiberRef,value:head3.value}),patches=tail;break}case OP_REMOVE:{fiberRefs2=delete_(fiberRefs2,head3.fiberRef),patches=tail;break}case OP_UPDATE:{let value=getOrDefault(fiberRefs2,head3.fiberRef);fiberRefs2=updateAs(fiberRefs2,{fiberId:fiberId2,fiberRef:head3.fiberRef,value:head3.fiberRef.patch(head3.patch)(value)}),patches=tail;break}case OP_AND_THEN:{patches=prepend(head3.first)(prepend(head3.second)(tail));break}}}return fiberRefs2});var diff6=diff5;var patch7=patch6;var FiberStatusSymbolKey="effect/FiberStatus",FiberStatusTypeId=Symbol.for(FiberStatusSymbolKey),OP_DONE="Done",OP_RUNNING="Running",OP_SUSPENDED="Suspended",DoneHash=string(`${FiberStatusSymbolKey}-${OP_DONE}`);class Done{[FiberStatusTypeId]=FiberStatusTypeId;_tag=OP_DONE;[symbol](){return DoneHash}[symbol2](that){return isFiberStatus(that)&&that._tag===OP_DONE}}class Running{runtimeFlags;[FiberStatusTypeId]=FiberStatusTypeId;_tag=OP_RUNNING;constructor(runtimeFlags2){this.runtimeFlags=runtimeFlags2}[symbol](){return pipe(hash(FiberStatusSymbolKey),combine(hash(this._tag)),combine(hash(this.runtimeFlags)),cached(this))}[symbol2](that){return isFiberStatus(that)&&that._tag===OP_RUNNING&&this.runtimeFlags===that.runtimeFlags}}class Suspended{runtimeFlags;blockingOn;[FiberStatusTypeId]=FiberStatusTypeId;_tag=OP_SUSPENDED;constructor(runtimeFlags2,blockingOn){this.runtimeFlags=runtimeFlags2,this.blockingOn=blockingOn}[symbol](){return pipe(hash(FiberStatusSymbolKey),combine(hash(this._tag)),combine(hash(this.runtimeFlags)),combine(hash(this.blockingOn)),cached(this))}[symbol2](that){return isFiberStatus(that)&&that._tag===OP_SUSPENDED&&this.runtimeFlags===that.runtimeFlags&&equals(this.blockingOn,that.blockingOn)}}var done2=new Done,running=(runtimeFlags2)=>new Running(runtimeFlags2),suspended=(runtimeFlags2,blockingOn)=>new Suspended(runtimeFlags2,blockingOn),isFiberStatus=(u)=>hasProperty(u,FiberStatusTypeId),isDone=(self)=>self._tag===OP_DONE;var done3=done2,running2=running,suspended2=suspended;var isDone2=isDone;var All=logLevelAll,Fatal=logLevelFatal,Error2=logLevelError,Warning=logLevelWarning,Info=logLevelInfo,Debug=logLevelDebug,Trace=logLevelTrace,None3=logLevelNone;var Order3=pipe(Order2,mapInput2((level)=>level.ordinal));var greaterThan3=greaterThan(Order3);var fromLiteral=(literal)=>{switch(literal){case"All":return All;case"Debug":return Debug;case"Error":return Error2;case"Fatal":return Fatal;case"Info":return Info;case"Trace":return Trace;case"None":return None3;case"Warning":return Warning}};var TypeId9=Symbol.for("effect/Micro"),MicroExitTypeId=Symbol.for("effect/Micro/MicroExit");var MicroCauseTypeId=Symbol.for("effect/Micro/MicroCause");var microCauseVariance={_E:identity};class MicroCauseImpl extends globalThis.Error{_tag;traces;[MicroCauseTypeId];constructor(_tag,originalError,traces){let causeName=`MicroCause.${_tag}`,name,message,stack;if(originalError instanceof globalThis.Error){name=`(${causeName}) ${originalError.name}`,message=originalError.message;let messageLines=message.split(`
25
25
  `).length;stack=originalError.stack?`(${causeName}) ${originalError.stack.split(`
26
26
  `).slice(0,messageLines+3).join(`
@@ -28,7 +28,7 @@ ${this.stack.split(`
28
28
  ${traces.join(`
29
29
  `)}`;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",[TypeId9]: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 Proto=makePrimitiveProto(options);return function(){let self=Object.create(Proto);return self[args]=options.single===!1?arguments:arguments[0],self}},makeExit=(options)=>{let Proto={...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(Proto);return self[args]=value,self[successCont]=void 0,self[failureCont]=void 0,self[ensureCont]=void 0,self}},succeed2=makeExit({op:"Success",prop:"value",eval(fiber){let cont=fiber.getCont(successCont);return cont?cont[successCont](this[args],fiber):fiber.yieldWith(this)}}),failCause2=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_2=succeed2(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=succeed2,exitFailCause2=failCause2,exitInterrupt2=exitFailCause2(causeInterrupt());var exitDie2=(defect)=>exitFailCause2(causeDie(defect));var exitVoid2=exitSucceed2(void 0);var setImmediate2="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,setImmediate2(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_2})}));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:(cause)=>flatMap9(f(exitFailCause2(cause)),()=>failCause2(cause)),onSuccess:(a)=>flatMap9(f(exitSucceed2(a)),()=>succeed2(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};var TypeId10=Symbol.for("effect/Readable");var Proto={[TypeId10]:TypeId10,pipe(){return pipeArguments(this,arguments)}};var RefTypeId=Symbol.for("effect/Ref"),refVariance={_A:(_)=>_};class RefImpl extends Class{ref;commit(){return this.get}[RefTypeId]=refVariance;[TypeId10]=TypeId10;constructor(ref){super();this.ref=ref,this.get=sync(()=>get6(this.ref))}get;modify(f){return sync(()=>{let current=get6(this.ref),[b,a]=f(current);if(current!==a)set2(a)(this.ref);return b})}}var unsafeMake5=(value)=>new RefImpl(make11(value)),make23=(value)=>sync(()=>unsafeMake5(value)),get10=(self)=>self.get,set4=dual(2,(self,value)=>self.modify(()=>[void 0,value])),getAndSet=dual(2,(self,value)=>self.modify((a)=>[a,value]));var modify3=dual(2,(self,f)=>self.modify(f));var update2=dual(2,(self,f)=>self.modify((a)=>[void 0,f(a)]));var make24=make23,get11=get10,getAndSet2=getAndSet;var modify4=modify3;var set5=set4;var update3=update2;class PriorityBuckets{buckets=[];scheduleTask(task,priority){let length=this.buckets.length,bucket=void 0,index=0;for(;index<length;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===length)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 match7=(concurrency,sequential4,unbounded,bounded)=>{switch(concurrency){case void 0:return sequential4();case"unbounded":return unbounded();case"inherit":return fiberRefGetWith(currentConcurrency,(concurrency2)=>concurrency2==="unbounded"?unbounded():concurrency2>1?bounded(concurrency2):sequential4());default:return concurrency>1?bounded(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 sleep2=sleep,currentTimeMillis2=currentTimeMillis,currentTimeNanos2=currentTimeNanos,clockWith2=clockWith,Clock=clockTag;var make25=(label,startTime)=>({label,startTime}),formatLabel=(key)=>key.replace(/[\s="]/g,"_"),render=(now)=>(self)=>{return`${formatLabel(self.label)}=${now-self.startTime}ms`};var make26=make25;var tracerWith2=tracerWith;var MetricLabelSymbolKey="effect/MetricLabel",MetricLabelTypeId=Symbol.for(MetricLabelSymbolKey);class MetricLabelImpl{key;value;[MetricLabelTypeId]=MetricLabelTypeId;_hash;constructor(key,value){this.key=key,this.value=value,this._hash=string(MetricLabelSymbolKey+this.key+this.value)}[symbol](){return this._hash}[symbol2](that){return isMetricLabel(that)&&this.key===that.key&&this.value===that.value}pipe(){return pipeArguments(this,arguments)}}var make27=(key,value)=>{return new MetricLabelImpl(key,value)},isMetricLabel=(u)=>hasProperty(u,MetricLabelTypeId);var annotateLogs=dual((args2)=>isEffect(args2[0]),function(){let args2=arguments;return fiberRefLocallyWith(args2[0],currentLogAnnotations,typeof args2[1]==="string"?set3(args2[1],args2[2]):(annotations)=>Object.entries(args2[1]).reduce((acc,[key,value])=>set3(acc,key,value),annotations))}),asSome=(self)=>map10(self,some2),asSomeError=(self)=>mapError(self,some2),try_2=(arg)=>{let evaluate2,onFailure=void 0;if(typeof arg==="function")evaluate2=arg;else evaluate2=arg.try,onFailure=arg.catch;return suspend(()=>{try{return succeed(internalCall(evaluate2))}catch(error){return fail2(onFailure?internalCall(()=>onFailure(error)):new UnknownException(error,"An unknown error occurred in Effect.try"))}})},_catch=dual(3,(self,tag,options)=>catchAll(self,(e)=>{if(hasProperty(e,tag)&&e[tag]===options.failure)return options.onFailure(e);return fail2(e)})),catchAllDefect=dual(2,(self,f)=>catchAllCause(self,(cause)=>{let option=find(cause,(_)=>isDieType(_)?some2(_):none2());switch(option._tag){case"None":return failCause(cause);case"Some":return f(option.value.defect)}})),catchSomeCause=dual(2,(self,f)=>matchCauseEffect(self,{onFailure:(cause)=>{let option=f(cause);switch(option._tag){case"None":return failCause(cause);case"Some":return option.value}},onSuccess:succeed})),catchSomeDefect=dual(2,(self,pf)=>catchAllCause(self,(cause)=>{let option=find(cause,(_)=>isDieType(_)?some2(_):none2());switch(option._tag){case"None":return failCause(cause);case"Some":{let optionEffect=pf(option.value.defect);return optionEffect._tag==="Some"?optionEffect.value:failCause(cause)}}})),catchTag=dual((args2)=>isEffect(args2[0]),(self,...args2)=>{let f=args2[args2.length-1],predicate;if(args2.length===2)predicate=isTagged(args2[0]);else predicate=(e)=>{let tag=hasProperty(e,"_tag")?e._tag:void 0;if(!tag)return!1;for(let i=0;i<args2.length-1;i++)if(args2[i]===tag)return!0;return!1};return catchIf(self,predicate,f)}),catchTags=dual(2,(self,cases)=>{let keys3;return catchIf(self,(e)=>{return keys3??=Object.keys(cases),hasProperty(e,"_tag")&&isString(e._tag)&&keys3.includes(e._tag)},(e)=>cases[e._tag](e))}),cause=(self)=>matchCause(self,{onFailure:identity,onSuccess:()=>empty6}),clockWith3=clockWith2,clock=clockWith3(succeed),delay=dual(2,(self,duration)=>zipRight(sleep2(duration),self)),descriptorWith=(f)=>withFiberRuntime((state,status)=>f({id:state.id(),status,interruptors:interruptors(state.getFiberRef(currentInterruptedCause))})),allowInterrupt=descriptorWith((descriptor)=>size3(descriptor.interruptors)>0?interrupt2:void_),descriptor=descriptorWith(succeed),diffFiberRefs=(self)=>summarized(self,fiberRefs2,diff5),diffFiberRefsAndRuntimeFlags=(self)=>summarized(self,zip2(fiberRefs2,runtimeFlags),([refs,flags],[refsNew,flagsNew])=>[diff5(refs,refsNew),diff4(flags,flagsNew)]),Do=succeed({}),bind2=bind(map10,flatMap8),bindTo2=bindTo(map10),let_2=let_(map10),dropUntil=dual(2,(elements,predicate)=>suspend(()=>{let iterator=elements[Symbol.iterator](),builder=[],next2,dropping=succeed(!1),i=0;while((next2=iterator.next())&&!next2.done){let a=next2.value,index=i++;dropping=flatMap8(dropping,(bool)=>{if(bool)return builder.push(a),succeed(!0);return predicate(a,index)})}return map10(dropping,()=>builder)})),dropWhile2=dual(2,(elements,predicate)=>suspend(()=>{let iterator=elements[Symbol.iterator](),builder=[],next2,dropping=succeed(!0),i=0;while((next2=iterator.next())&&!next2.done){let a=next2.value,index=i++;dropping=flatMap8(dropping,(d)=>map10(d?predicate(a,index):succeed(!1),(b)=>{if(!b)builder.push(a);return b}))}return map10(dropping,()=>builder)})),contextWith=(f)=>map10(context(),f),eventually=(self)=>orElse2(self,()=>flatMap8(yieldNow(),()=>eventually(self))),filterMap4=dual(2,(elements,pf)=>map10(forEachSequential(elements,identity),filterMap(pf))),filterOrDie=dual(3,(self,predicate,orDieWith2)=>filterOrElse(self,predicate,(a)=>dieSync(()=>orDieWith2(a)))),filterOrDieMessage=dual(3,(self,predicate,message)=>filterOrElse(self,predicate,()=>dieMessage(message))),filterOrElse=dual(3,(self,predicate,orElse3)=>flatMap8(self,(a)=>predicate(a)?succeed(a):orElse3(a))),liftPredicate2=dual(3,(self,predicate,orFailWith)=>suspend(()=>predicate(self)?succeed(self):fail2(orFailWith(self)))),filterOrFail=dual((args2)=>isEffect(args2[0]),(self,predicate,orFailWith)=>filterOrElse(self,predicate,(a)=>orFailWith===void 0?fail2(new NoSuchElementException):failSync(()=>orFailWith(a)))),findFirst5=dual(2,(elements,predicate)=>suspend(()=>{let iterator=elements[Symbol.iterator](),next2=iterator.next();if(!next2.done)return findLoop(iterator,0,predicate,next2.value);return succeed(none2())})),findLoop=(iterator,index,f,value)=>flatMap8(f(value,index),(result)=>{if(result)return succeed(some2(value));let next2=iterator.next();if(!next2.done)return findLoop(iterator,index+1,f,next2.value);return succeed(none2())}),firstSuccessOf=(effects)=>suspend(()=>{let list=fromIterable2(effects);if(!isNonEmpty(list))return dieSync(()=>new IllegalArgumentException("Received an empty collection of effects"));return pipe(tailNonEmpty2(list),reduce(headNonEmpty2(list),(left3,right3)=>orElse2(left3,()=>right3)))}),flipWith=dual(2,(self,f)=>flip(f(flip(self)))),match8=dual(2,(self,options)=>matchEffect(self,{onFailure:(e)=>succeed(options.onFailure(e)),onSuccess:(a)=>succeed(options.onSuccess(a))})),every5=dual(2,(elements,predicate)=>suspend(()=>forAllLoop(elements[Symbol.iterator](),0,predicate))),forAllLoop=(iterator,index,f)=>{let next2=iterator.next();return next2.done?succeed(!0):flatMap8(f(next2.value,index),(b)=>b?forAllLoop(iterator,index+1,f):succeed(b))},forever=(self)=>{let loop=flatMap8(flatMap8(self,()=>yieldNow()),()=>loop);return loop},fiberRefs2=withFiberRuntime((state)=>succeed(state.getFiberRefs())),head3=(self)=>flatMap8(self,(as3)=>{let next2=as3[Symbol.iterator]().next();if(next2.done)return fail2(new NoSuchElementException);return succeed(next2.value)}),ignore=(self)=>match8(self,{onFailure:constVoid,onSuccess:constVoid}),ignoreLogged=(self)=>matchCauseEffect(self,{onFailure:(cause2)=>logDebug(cause2,"An error was silently ignored because it is not anticipated to be useful"),onSuccess:()=>void_}),inheritFiberRefs=(childFiberRefs)=>updateFiberRefs((parentFiberId,parentFiberRefs)=>joinAs2(parentFiberRefs,parentFiberId,childFiberRefs)),isFailure2=(self)=>match8(self,{onFailure:constTrue,onSuccess:constFalse}),isSuccess=(self)=>match8(self,{onFailure:constFalse,onSuccess:constTrue}),iterate=(initial,options)=>suspend(()=>{if(options.while(initial))return flatMap8(options.body(initial),(z2)=>iterate(z2,options));return succeed(initial)}),logWithLevel=(level)=>(...message)=>{let levelOption=fromNullable(level),cause2=void 0;for(let i=0,len=message.length;i<len;i++){let msg=message[i];if(isCause(msg)){if(cause2!==void 0)cause2=sequential(cause2,msg);else cause2=msg;message=[...message.slice(0,i),...message.slice(i+1)],i--}}if(cause2===void 0)cause2=empty6;return withFiberRuntime((fiberState)=>{return fiberState.log(message,cause2,levelOption),void_})},log=logWithLevel(),logTrace=logWithLevel(Trace),logDebug=logWithLevel(Debug),logInfo=logWithLevel(Info),logWarning=logWithLevel(Warning),logError=logWithLevel(Error2),logFatal=logWithLevel(Fatal),withLogSpan=dual(2,(effect,label)=>flatMap8(currentTimeMillis2,(now)=>fiberRefLocallyWith(effect,currentLogSpan,prepend3(make26(label,now))))),logAnnotations=fiberRefGet(currentLogAnnotations),loop=(initial,options)=>options.discard?loopDiscard(initial,options.while,options.step,options.body):map10(loopInternal(initial,options.while,options.step,options.body),fromIterable),loopInternal=(initial,cont,inc,body)=>suspend(()=>cont(initial)?flatMap8(body(initial),(a)=>map10(loopInternal(inc(initial),cont,inc,body),prepend3(a))):sync(()=>empty10())),loopDiscard=(initial,cont,inc,body)=>suspend(()=>cont(initial)?flatMap8(body(initial),()=>loopDiscard(inc(initial),cont,inc,body)):void_),mapAccum3=dual(3,(elements,initial,f)=>suspend(()=>{let iterator=elements[Symbol.iterator](),builder=[],result=succeed(initial),next2,i=0;while(!(next2=iterator.next()).done){let index=i++,value=next2.value;result=flatMap8(result,(state)=>map10(f(state,value,index),([z,b])=>{return builder.push(b),z}))}return map10(result,(z)=>[z,builder])})),mapErrorCause=dual(2,(self,f)=>matchCauseEffect(self,{onFailure:(c)=>failCauseSync(()=>f(c)),onSuccess:succeed})),memoize=(self)=>pipe(deferredMake(),flatMap8((deferred)=>pipe(diffFiberRefsAndRuntimeFlags(self),intoDeferred(deferred),once,map10((complete)=>zipRight(complete,pipe(deferredAwait(deferred),flatMap8(([patch8,a])=>as(zip2(patchFiberRefs(patch8[0]),updateRuntimeFlags(patch8[1])),a)))))))),merge5=(self)=>matchEffect(self,{onFailure:(e)=>succeed(e),onSuccess:succeed}),negate=(self)=>map10(self,(b)=>!b),none6=(self)=>flatMap8(self,(option)=>{switch(option._tag){case"None":return void_;case"Some":return fail2(new NoSuchElementException)}}),once=(self)=>map10(make24(!0),(ref)=>asVoid(whenEffect(self,getAndSet2(ref,!1)))),option=(self)=>matchEffect(self,{onFailure:()=>succeed(none2()),onSuccess:(a)=>succeed(some2(a))}),orElseFail=dual(2,(self,evaluate2)=>orElse2(self,()=>failSync(evaluate2))),orElseSucceed=dual(2,(self,evaluate2)=>orElse2(self,()=>sync(evaluate2))),parallelErrors=(self)=>matchCauseEffect(self,{onFailure:(cause2)=>{let errors=fromIterable(failures(cause2));return errors.length===0?failCause(cause2):fail2(errors)},onSuccess:succeed}),patchFiberRefs=(patch8)=>updateFiberRefs((fiberId2,fiberRefs3)=>pipe(patch8,patch6(fiberId2,fiberRefs3))),promise=(evaluate2)=>evaluate2.length>=1?async_((resolve,signal)=>{try{evaluate2(signal).then((a)=>resolve(succeed(a)),(e)=>resolve(die2(e)))}catch(e){resolve(die2(e))}}):async_((resolve)=>{try{evaluate2().then((a)=>resolve(succeed(a)),(e)=>resolve(die2(e)))}catch(e){resolve(die2(e))}}),provideService=dual(3,(self,tag,service)=>contextWithEffect((env)=>provideContext(self,add4(env,tag,service)))),provideServiceEffect=dual(3,(self,tag,effect)=>contextWithEffect((env)=>flatMap8(effect,(service)=>provideContext(self,pipe(env,add4(tag,service)))))),random2=randomWith(succeed),reduce9=dual(3,(elements,zero2,f)=>fromIterable(elements).reduce((acc,el,i)=>flatMap8(acc,(a)=>f(a,el,i)),succeed(zero2))),reduceRight3=dual(3,(elements,zero2,f)=>fromIterable(elements).reduceRight((acc,el,i)=>flatMap8(acc,(a)=>f(el,a,i)),succeed(zero2))),reduceWhile=dual(3,(elements,zero2,options)=>flatMap8(sync(()=>elements[Symbol.iterator]()),(iterator)=>reduceWhileLoop(iterator,0,zero2,options.while,options.body))),reduceWhileLoop=(iterator,index,state,predicate,f)=>{let next2=iterator.next();if(!next2.done&&predicate(state))return flatMap8(f(state,next2.value,index),(nextState)=>reduceWhileLoop(iterator,index+1,nextState,predicate,f));return succeed(state)},repeatN=dual(2,(self,n)=>suspend(()=>repeatNLoop(self,n))),repeatNLoop=(self,n)=>flatMap8(self,(a)=>n<=0?succeed(a):zipRight(yieldNow(),repeatNLoop(self,n-1))),sandbox=(self)=>matchCauseEffect(self,{onFailure:fail2,onSuccess:succeed}),setFiberRefs=(fiberRefs3)=>suspend(()=>setAll2(fiberRefs3)),sleep3=sleep2,succeedNone=succeed(none2()),succeedSome=(value)=>succeed(some2(value)),summarized=dual(3,(self,summary,f)=>flatMap8(summary,(start)=>flatMap8(self,(value)=>map10(summary,(end)=>[f(start,end),value])))),tagMetrics=dual((args2)=>isEffect(args2[0]),function(){return labelMetrics(arguments[0],typeof arguments[1]==="string"?[make27(arguments[1],arguments[2])]:Object.entries(arguments[1]).map(([k,v])=>make27(k,v)))}),labelMetrics=dual(2,(self,labels)=>fiberRefLocallyWith(self,currentMetricLabels,(old)=>union(old,labels))),takeUntil=dual(2,(elements,predicate)=>suspend(()=>{let iterator=elements[Symbol.iterator](),builder=[],next2,effect=succeed(!1),i=0;while((next2=iterator.next())&&!next2.done){let a=next2.value,index=i++;effect=flatMap8(effect,(bool)=>{if(bool)return succeed(!0);return builder.push(a),predicate(a,index)})}return map10(effect,()=>builder)})),takeWhile2=dual(2,(elements,predicate)=>suspend(()=>{let iterator=elements[Symbol.iterator](),builder=[],next2,taking=succeed(!0),i=0;while((next2=iterator.next())&&!next2.done){let a=next2.value,index=i++;taking=flatMap8(taking,(taking2)=>pipe(taking2?predicate(a,index):succeed(!1),map10((bool)=>{if(bool)builder.push(a);return bool})))}return map10(taking,()=>builder)})),tapBoth=dual(2,(self,{onFailure,onSuccess})=>matchCauseEffect(self,{onFailure:(cause2)=>{let either3=failureOrCause(cause2);switch(either3._tag){case"Left":return zipRight(onFailure(either3.left),failCause(cause2));case"Right":return failCause(cause2)}},onSuccess:(a)=>as(onSuccess(a),a)})),tapDefect=dual(2,(self,f)=>catchAllCause(self,(cause2)=>match2(keepDefects(cause2),{onNone:()=>failCause(cause2),onSome:(a)=>zipRight(f(a),failCause(cause2))}))),tapError=dual(2,(self,f)=>matchCauseEffect(self,{onFailure:(cause2)=>{let either3=failureOrCause(cause2);switch(either3._tag){case"Left":return zipRight(f(either3.left),failCause(cause2));case"Right":return failCause(cause2)}},onSuccess:succeed})),tapErrorTag=dual(3,(self,k,f)=>tapError(self,(e)=>{if(isTagged(e,k))return f(e);return void_})),tapErrorCause=dual(2,(self,f)=>matchCauseEffect(self,{onFailure:(cause2)=>zipRight(f(cause2),failCause(cause2)),onSuccess:succeed})),timed=(self)=>timedWith(self,currentTimeNanos2),timedWith=dual(2,(self,nanos2)=>summarized(self,nanos2,(start,end)=>nanos(end-start))),tracerWith3=tracerWith2,tracer=tracerWith3(succeed),tryPromise=(arg)=>{let evaluate2,catcher=void 0;if(typeof arg==="function")evaluate2=arg;else evaluate2=arg.try,catcher=arg.catch;let fail4=(e)=>catcher?failSync(()=>catcher(e)):fail2(new UnknownException(e,"An unknown error occurred in Effect.tryPromise"));if(evaluate2.length>=1)return async_((resolve,signal)=>{try{evaluate2(signal).then((a)=>resolve(succeed(a)),(e)=>resolve(fail4(e)))}catch(e){resolve(fail4(e))}});return async_((resolve)=>{try{evaluate2().then((a)=>resolve(succeed(a)),(e)=>resolve(fail4(e)))}catch(e){resolve(fail4(e))}})},tryMap=dual(2,(self,options)=>flatMap8(self,(a)=>try_2({try:()=>options.try(a),catch:options.catch}))),tryMapPromise=dual(2,(self,options)=>flatMap8(self,(a)=>tryPromise({try:options.try.length>=1?(signal)=>options.try(a,signal):()=>options.try(a),catch:options.catch}))),unless=dual(2,(self,condition)=>suspend(()=>condition()?succeedNone:asSome(self))),unlessEffect=dual(2,(self,condition)=>flatMap8(condition,(b)=>b?succeedNone:asSome(self))),unsandbox=(self)=>mapErrorCause(self,flatten3),updateFiberRefs=(f)=>withFiberRuntime((state)=>{return state.setFiberRefs(f(state.id(),state.getFiberRefs())),void_}),updateService=dual(3,(self,tag,f)=>mapInputContext(self,(context2)=>add4(context2,tag,f(unsafeGet4(context2,tag))))),when=dual(2,(self,condition)=>suspend(()=>condition()?map10(self,some2):succeed(none2()))),whenFiberRef=dual(3,(self,fiberRef,predicate)=>flatMap8(fiberRefGet(fiberRef),(s)=>predicate(s)?map10(self,(a)=>[s,some2(a)]):succeed([s,none2()]))),whenRef=dual(3,(self,ref,predicate)=>flatMap8(get11(ref),(s)=>predicate(s)?map10(self,(a)=>[s,some2(a)]):succeed([s,none2()]))),withMetric=dual(2,(self,metric)=>metric(self)),serviceFunctionEffect=(getService,f)=>(...args2)=>flatMap8(getService,(a)=>f(a)(...args2)),serviceFunction=(getService,f)=>(...args2)=>map10(getService,(a)=>f(a)(...args2)),serviceFunctions=(getService)=>new Proxy({},{get(_target,prop,_receiver){return(...args2)=>flatMap8(getService,(s)=>s[prop](...args2))}}),serviceConstants=(getService)=>new Proxy({},{get(_target,prop,_receiver){return flatMap8(getService,(s)=>isEffect(s[prop])?s[prop]:succeed(s[prop]))}}),serviceMembers=(getService)=>({functions:serviceFunctions(getService),constants:serviceConstants(getService)}),serviceOption=(tag)=>map10(context(),getOption2(tag)),serviceOptional=(tag)=>flatMap8(context(),getOption2(tag)),annotateCurrentSpan=function(){let args2=arguments;return ignore(flatMap8(currentSpan,(span2)=>sync(()=>{if(typeof args2[0]==="string")span2.attribute(args2[0],args2[1]);else for(let key in args2[0])span2.attribute(key,args2[0][key])})))},linkSpanCurrent=function(){let args2=arguments,links=Array.isArray(args2[0])?args2[0]:[{_tag:"SpanLink",span:args2[0],attributes:args2[1]??{}}];return ignore(flatMap8(currentSpan,(span2)=>sync(()=>span2.addLinks(links))))},annotateSpans=dual((args2)=>isEffect(args2[0]),function(){let args2=arguments;return fiberRefLocallyWith(args2[0],currentTracerSpanAnnotations,typeof args2[1]==="string"?set3(args2[1],args2[2]):(annotations)=>Object.entries(args2[1]).reduce((acc,[key,value])=>set3(acc,key,value),annotations))}),currentParentSpan=serviceOptional(spanTag),currentSpan=flatMap8(context(),(context2)=>{let span2=context2.unsafeMap.get(spanTag.key);return span2!==void 0&&span2._tag==="Span"?succeed(span2):fail2(new NoSuchElementException)}),linkSpans=dual((args2)=>isEffect(args2[0]),(self,span2,attributes)=>fiberRefLocallyWith(self,currentTracerSpanLinks,append2({_tag:"SpanLink",span:span2,attributes:attributes??{}}))),bigint02=BigInt(0),filterDisablePropagation=flatMap((span2)=>get5(span2.context,DisablePropagation)?span2._tag==="Span"?filterDisablePropagation(span2.parent):none2():some2(span2)),unsafeMakeSpan=(fiber,name,options)=>{let disablePropagation=!fiber.getFiberRef(currentTracerEnabled)||options.context&&get5(options.context,DisablePropagation),context2=fiber.getFiberRef(currentContext),parent=options.parent?some2(options.parent):options.root?none2():filterDisablePropagation(getOption2(context2,spanTag)),span2;if(disablePropagation)span2=noopSpan({name,parent,context:add4(options.context??empty8(),DisablePropagation,!0)});else{let services=fiber.getFiberRef(currentServices),tracer2=get5(services,tracerTag),clock2=get5(services,Clock),timingEnabled=fiber.getFiberRef(currentTracerTimingEnabled),fiberRefs3=fiber.getFiberRefs(),annotationsFromEnv=get9(fiberRefs3,currentTracerSpanAnnotations),linksFromEnv=get9(fiberRefs3,currentTracerSpanLinks),links=linksFromEnv._tag==="Some"?options.links!==void 0?[...toReadonlyArray(linksFromEnv.value),...options.links??[]]:toReadonlyArray(linksFromEnv.value):options.links??empty();if(span2=tracer2.span(name,parent,options.context??empty8(),links,timingEnabled?clock2.unsafeCurrentTimeNanos():bigint02,options.kind??"internal",options),annotationsFromEnv._tag==="Some")forEach4(annotationsFromEnv.value,(value,key)=>span2.attribute(key,value));if(options.attributes!==void 0)Object.entries(options.attributes).forEach(([k,v])=>span2.attribute(k,v))}if(typeof options.captureStackTrace==="function")spanToTrace.set(span2,options.captureStackTrace);return span2},makeSpan=(name,options)=>{return options=addSpanStackTrace(options),withFiberRuntime((fiber)=>succeed(unsafeMakeSpan(fiber,name,options)))},spanAnnotations=fiberRefGet(currentTracerSpanAnnotations),spanLinks=fiberRefGet(currentTracerSpanLinks),endSpan=(span2,exit2,clock2,timingEnabled)=>sync(()=>{if(span2.status._tag==="Ended")return;if(exitIsFailure(exit2)&&spanToTrace.has(span2))span2.attribute("code.stacktrace",spanToTrace.get(span2)());span2.end(timingEnabled?clock2.unsafeCurrentTimeNanos():bigint02,exit2)}),useSpan=(name,...args2)=>{let options=addSpanStackTrace(args2.length===1?void 0:args2[0]),evaluate2=args2[args2.length-1];return withFiberRuntime((fiber)=>{let span2=unsafeMakeSpan(fiber,name,options),timingEnabled=fiber.getFiberRef(currentTracerTimingEnabled),clock2=get5(fiber.getFiberRef(currentServices),clockTag);return onExit(evaluate2(span2),(exit2)=>endSpan(span2,exit2,clock2,timingEnabled))})},withParentSpan=dual(2,(self,span2)=>provideService(self,spanTag,span2)),withSpan=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 useSpan(name,options,(span2)=>withParentSpan(self,span2))}return(self)=>useSpan(name,options,(span2)=>withParentSpan(self,span2))},functionWithSpan=(options)=>function(){let captureStackTrace=options.captureStackTrace??!1;if(options.captureStackTrace!==!1){let limit=Error.stackTraceLimit;Error.stackTraceLimit=2;let error=Error();Error.stackTraceLimit=limit;let cache=!1;captureStackTrace=()=>{if(cache!==!1)return cache;if(error.stack)return cache=error.stack.trim().split(`
30
30
  `).slice(2).join(`
31
- `).trim(),cache}}return suspend(()=>{let opts=typeof options.options==="function"?options.options.apply(null,arguments):options.options;return withSpan(suspend(()=>internalCall(()=>options.body.apply(this,arguments))),opts.name,{...opts,captureStackTrace})})},fromNullable2=(value)=>value==null?fail2(new NoSuchElementException):succeed(value),optionFromOptional=(self)=>catchAll(map10(self,some2),(error)=>isNoSuchElementException(error)?succeedNone:fail2(error));var isExit=exitIsExit,isFailure3=exitIsFailure,isSuccess2=exitIsSuccess;var all3=exitCollectAll,die4=exitDie;var fail4=exitFail,failCause3=exitFailCause;var flatten6=exitFlatten;var interrupt4=exitInterrupt,map12=exitMap,mapBoth2=exitMapBoth;var match9=exitMatch;var succeed3=exitSucceed,void_3=exitVoid;var zip3=exitZip;var zipRight2=exitZipRight;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 unsafeMake6=(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);var isRuntimeFiber=(self)=>(RuntimeFiberTypeId in self),_await=(self)=>self.await;var inheritAll=(self)=>self.inheritAll;var interruptAllAs=dual(2,fnUntraced(function*(fibers,fiberId2){for(let fiber of fibers){if(isRuntimeFiber(fiber)){fiber.unsafeInterruptAsFork(fiberId2);continue}yield*fiber.interruptAsFork(fiberId2)}for(let fiber of fibers){if(isRuntimeFiber(fiber)&&fiber.unsafePoll())continue;yield*fiber.await}})),interruptAsFork=dual(2,(self,fiberId2)=>self.interruptAsFork(fiberId2)),join2=(self)=>zipLeft(flatten5(self.await),self.inheritAll);var _never={...CommitPrototype,commit(){return join2(this)},...fiberProto,id:()=>none4,await:never,children:succeed([]),inheritAll:never,poll:succeed(none2()),interruptAsFork:()=>never};var poll=(self)=>self.poll;var currentFiberURI="effect/FiberCurrent";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"=]*$/,format3=(quoteValue,whitespace)=>({annotations,cause:cause2,date,fiberId:fiberId2,logLevel,message,spans})=>{let formatValue=(value)=>value.match(textOnly)?value:quoteValue(value),format4=(label,value)=>`${formatLabel(label)}=${formatValue(value)}`,append3=(label,value)=>" "+format4(label,value),out=format4("timestamp",date.toISOString());out+=append3("level",logLevel.label),out+=append3("fiber",threadName(fiberId2));let messages=ensure(message);for(let i=0;i<messages.length;i++)out+=append3("message",toStringUnknown(messages[i],whitespace));if(!isEmptyType(cause2))out+=append3("cause",pretty(cause2,{renderErrorCause:!0}));for(let span2 of spans)out+=" "+render(date.getTime())(span2);for(let[label,value]of annotations)out+=append3(label,toStringUnknown(value,whitespace));return out},escapeDoubleQuotes=(s)=>`"${s.replace(/\\([\s\S])|(")/g,"\\$1$2")}"`,stringLogger=makeLogger(format3(escapeDoubleQuotes));var structuredMessage=(u)=>{switch(typeof u){case"bigint":case"function":case"symbol":return String(u);default:return toJSON(u)}};var withColor=(text,...colors)=>{let out="";for(let i=0;i<colors.length;i++)out+=`\x1B[${colors[i]}m`;return out+text+"\x1B[0m"},withColorNoop=(text,..._colors)=>text,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]},logLevelStyle={None:"",All:"",Trace:"color:gray",Debug:"color:blue",Info:"color:green",Warning:"color:orange",Error:"color:red",Fatal:"background-color:red;color:white"},defaultDateFormat=(date)=>`${date.getHours().toString().padStart(2,"0")}:${date.getMinutes().toString().padStart(2,"0")}:${date.getSeconds().toString().padStart(2,"0")}.${date.getMilliseconds().toString().padStart(3,"0")}`,hasProcessStdout=typeof process==="object"&&process!==null&&typeof process.stdout==="object"&&process.stdout!==null,processStdoutIsTTY=hasProcessStdout&&process.stdout.isTTY===!0,hasProcessStdoutOrDeno=hasProcessStdout||"Deno"in globalThis,prettyLogger=(options)=>{let mode_=options?.mode??"auto",isBrowser=(mode_==="auto"?hasProcessStdoutOrDeno?"tty":"browser":mode_)==="browser",showColors=typeof options?.colors==="boolean"?options.colors:processStdoutIsTTY||isBrowser,formatDate2=options?.formatDate??defaultDateFormat;return isBrowser?prettyLoggerBrowser({colors:showColors,formatDate:formatDate2}):prettyLoggerTty({colors:showColors,formatDate:formatDate2,stderr:options?.stderr===!0})},prettyLoggerTty=(options)=>{let color=options.colors?withColor:withColorNoop;return makeLogger(({annotations,cause:cause2,context:context2,date,fiberId:fiberId2,logLevel,message:message_,spans})=>{let services=getOrDefault2(context2,currentServices),console2=get5(services,consoleTag).unsafe,log2=options.stderr===!0?console2.error:console2.log,message=ensure(message_),firstLine=color(`[${options.formatDate(date)}]`,colors.white)+` ${color(logLevel.label,...logLevelColors[logLevel._tag])} (${threadName(fiberId2)})`;if(isCons(spans)){let now=date.getTime(),render2=render(now);for(let span2 of spans)firstLine+=" "+render2(span2)}firstLine+=":";let messageIndex=0;if(message.length>0){let firstMaybeString=structuredMessage(message[0]);if(typeof firstMaybeString==="string")firstLine+=" "+color(firstMaybeString,colors.bold,colors.cyan),messageIndex++}if(log2(firstLine),console2.group(),!isEmpty3(cause2))log2(pretty(cause2,{renderErrorCause:!0}));if(messageIndex<message.length)for(;messageIndex<message.length;messageIndex++)log2(redact(message[messageIndex]));if(size4(annotations)>0)for(let[key,value]of annotations)log2(color(`${key}:`,colors.bold,colors.white),redact(value));console2.groupEnd()})},prettyLoggerBrowser=(options)=>{let color=options.colors?"%c":"";return makeLogger(({annotations,cause:cause2,context:context2,date,fiberId:fiberId2,logLevel,message:message_,spans})=>{let services=getOrDefault2(context2,currentServices),console2=get5(services,consoleTag).unsafe,message=ensure(message_),firstLine=`${color}[${options.formatDate(date)}]`,firstParams=[];if(options.colors)firstParams.push("color:gray");if(firstLine+=` ${color}${logLevel.label}${color} (${threadName(fiberId2)})`,options.colors)firstParams.push(logLevelStyle[logLevel._tag],"");if(isCons(spans)){let now=date.getTime(),render2=render(now);for(let span2 of spans)firstLine+=" "+render2(span2)}firstLine+=":";let messageIndex=0;if(message.length>0){let firstMaybeString=structuredMessage(message[0]);if(typeof firstMaybeString==="string"){if(firstLine+=` ${color}${firstMaybeString}`,options.colors)firstParams.push("color:deepskyblue");messageIndex++}}if(console2.groupCollapsed(firstLine,...firstParams),!isEmpty3(cause2))console2.error(pretty(cause2,{renderErrorCause:!0}));if(messageIndex<message.length)for(;messageIndex<message.length;messageIndex++)console2.log(redact(message[messageIndex]));if(size4(annotations)>0)for(let[key,value]of annotations){let redacted=redact(value);if(options.colors)console2.log(`%c${key}:`,"color:gray",redacted);else console2.log(`${key}:`,redacted)}console2.groupEnd()})},prettyLoggerDefault=globalValue("effect/Logger/prettyLoggerDefault",()=>prettyLogger());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,bigint){this.incremental=incremental,this.bigint=bigint,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 TypeId11=Symbol.for("effect/MutableHashMap"),MutableHashMapProto={[TypeId11]:TypeId11,[Symbol.iterator](){return new MutableHashMapIterator(this)},toString(){return format(this.toJSON())},toJSON(){return{_id:"MutableHashMap",values:Array.from(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}};class MutableHashMapIterator{self;referentialIterator;bucketIterator;constructor(self){this.self=self,this.referentialIterator=self.referential[Symbol.iterator]()}next(){if(this.bucketIterator!==void 0)return this.bucketIterator.next();let result=this.referentialIterator.next();if(result.done)return this.bucketIterator=new BucketIterator(this.self.buckets.values()),this.next();return result}[Symbol.iterator](){return new MutableHashMapIterator(this.self)}}class BucketIterator{backing;constructor(backing){this.backing=backing}currentBucket;next(){if(this.currentBucket===void 0){let result2=this.backing.next();if(result2.done)return result2;this.currentBucket=result2.value[Symbol.iterator]()}let result=this.currentBucket.next();if(result.done)return this.currentBucket=void 0,this.next();return result}}var empty21=()=>{let self=Object.create(MutableHashMapProto);return self.referential=new Map,self.buckets=new Map,self.bucketsSize=0,self};var get12=dual(2,(self,key)=>{if(isEqual(key)===!1)return self.referential.has(key)?some2(self.referential.get(key)):none2();let hash2=key[symbol](),bucket=self.buckets.get(hash2);if(bucket===void 0)return none2();return getFromBucket(self,bucket,key)});var getFromBucket=(self,bucket,key,remove5=!1)=>{for(let i=0,len=bucket.length;i<len;i++)if(key[symbol2](bucket[i][0])){let value=bucket[i][1];if(remove5)bucket.splice(i,1),self.bucketsSize--;return some2(value)}return none2()},has4=dual(2,(self,key)=>isSome2(get12(self,key))),set6=dual(3,(self,key,value)=>{if(isEqual(key)===!1)return self.referential.set(key,value),self;let hash2=key[symbol](),bucket=self.buckets.get(hash2);if(bucket===void 0)return self.buckets.set(hash2,[[key,value]]),self.bucketsSize++,self;return removeFromBucket(self,bucket,key),bucket.push([key,value]),self.bucketsSize++,self}),removeFromBucket=(self,bucket,key)=>{for(let i=0,len=bucket.length;i<len;i++)if(key[symbol2](bucket[i][0])){bucket.splice(i,1),self.bucketsSize--;return}};var remove5=dual(2,(self,key)=>{if(isEqual(key)===!1)return self.referential.delete(key),self;let hash2=key[symbol](),bucket=self.buckets.get(hash2);if(bucket===void 0)return self;if(removeFromBucket(self,bucket,key),bucket.length===0)self.buckets.delete(hash2);return self});var size6=(self)=>{return self.referential.size+self.bucketsSize};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:(_)=>_},make28=(options)=>({[MetricHookTypeId]:metricHookVariance,pipe(){return pipeArguments(this,arguments)},...options});var bigint03=BigInt(0),counter4=(key)=>{let sum2=key.keyType.bigint?bigint03:0,canUpdate=key.keyType.incremental?key.keyType.bigint?(value)=>value>=bigint03:(value)=>value>=0:(_value)=>!0,update4=(value)=>{if(canUpdate(value))sum2=sum2+value};return make28({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 make28({get:()=>frequency2(values3),update:update4,modify:update4})},gauge3=(_key,startAt)=>{let value=startAt;return make28({get:()=>gauge2(value),update:(v)=>{value=v},modify:(v)=>{value=value+v}})},histogram4=(key)=>{let bounds=key.keyType.boundaries.values,size7=bounds.length,values3=new Uint32Array(size7+1),boundaries=new Float64Array(size7),count=0,sum2=0,min3=Number.MAX_VALUE,max3=Number.MIN_VALUE;pipe(bounds,sort(Order2),map3((n,i)=>{boundaries[i]=n}));let update4=(value)=>{let from=0,to=size7;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(size7),cumulated=0;for(let i=0;i<size7;i++){let boundary=boundaries[i],value=values3[i];cumulated=cumulated+value,builder[i]=[boundary,cumulated]}return builder};return make28({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(Order2)),values3=allocate(maxSize),head4=0,count=0,sum2=0,min3=0,max3=0,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(greaterThanOrEqualTo(age,zero)&&lessThanOrEqualTo(age,maxAge))builder.push(v)}i=i+1}return calculateQuantiles(error,sortedQuantiles,sort(builder,Order2))},observe=(value,timestamp)=>{if(maxSize>0){head4=head4+1;let target=head4%maxSize;values3[target]=[timestamp,value]}min3=count===0?value:Math.min(min3,value),max3=count===0?value:Math.max(max3,value),count=count+1,sum2=sum2+value};return make28({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 empty();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 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 unsafeMake7=(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(unsafeMake7(key,hook.get()));return result}get(key){let hook=pipe(this.map,get12(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 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,get12(key),getOrUndefined);if(value==null){let counter5=counter4(key);if(!pipe(this.map,has4(key)))pipe(this.map,set6(key,counter5));value=counter5}return value}getFrequency(key){let value=pipe(this.map,get12(key),getOrUndefined);if(value==null){let frequency4=frequency3(key);if(!pipe(this.map,has4(key)))pipe(this.map,set6(key,frequency4));value=frequency4}return value}getGauge(key){let value=pipe(this.map,get12(key),getOrUndefined);if(value==null){let gauge4=gauge3(key,key.keyType.bigint?BigInt(0):0);if(!pipe(this.map,has4(key)))pipe(this.map,set6(key,gauge4));value=gauge4}return value}getHistogram(key){let value=pipe(this.map,get12(key),getOrUndefined);if(value==null){let histogram5=histogram4(key);if(!pipe(this.map,has4(key)))pipe(this.map,set6(key,histogram5));value=histogram5}return value}getSummary(key){let value=pipe(this.map,get12(key),getOrUndefined);if(value==null){let summary4=summary3(key);if(!pipe(this.map,has4(key)))pipe(this.map,set6(key,summary4));value=summary4}return value}}var make29=()=>{return new MetricRegistryImpl};var MetricSymbolKey="effect/Metric",MetricTypeId=Symbol.for(MetricSymbolKey),metricVariance={_Type:(_)=>_,_In:(_)=>_,_Out:(_)=>_},globalMetricRegistry=globalValue(Symbol.for("effect/Metric/globalMetricRegistry"),()=>make29()),make30=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 make30(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,[make27(key,value)]));var taggedWithLabels2=dual(2,(self,extraTags)=>{return make30(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 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),fromEffect=(effect)=>{return new Const(effect)},none8=globalValue("effect/Supervisor/none",()=>fromEffect(void_));var make31=make14;var OP_EMPTY3="Empty",OP_ADD_SUPERVISOR="AddSupervisor",OP_REMOVE_SUPERVISOR="RemoveSupervisor",OP_AND_THEN2="AndThen",empty22={_tag:OP_EMPTY3},combine8=(self,that)=>{return{_tag:OP_AND_THEN2,first:self,second:that}},patch8=(self,supervisor)=>{return patchLoop(supervisor,of2(self))},patchLoop=(_supervisor,_patches)=>{let supervisor=_supervisor,patches=_patches;while(isNonEmpty(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 empty5();else if(isZip(self))return pipe(toSet2(self.left),union3(toSet2(self.right)));else return make7(self)},diff7=(oldValue,newValue)=>{if(equals(oldValue,newValue))return empty22;let oldSupervisors=toSet2(oldValue),newSupervisors=toSet2(newValue),added=pipe(newSupervisors,difference3(oldSupervisors),reduce5(empty22,(patch9,supervisor)=>combine8(patch9,{_tag:OP_ADD_SUPERVISOR,supervisor}))),removed=pipe(oldSupervisors,difference3(newSupervisors),reduce5(empty22,(patch9,supervisor)=>combine8(patch9,{_tag:OP_REMOVE_SUPERVISOR,supervisor})));return combine8(added,removed)},differ2=make31({empty:empty22,patch:patch8,combine:combine8,diff:diff7});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 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)=>{while(!0){let state=internalCall(()=>cont.effect_instruction_i0.next(value));if(state.done)return exitSucceed(state.value);let primitive=yieldWrapGet(state.value);if(!exitIsExit(primitive))return self.pushStack(cont),primitive;else if(primitive._tag==="Failure")return primitive;value=primitive.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 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=[];_children=null;_observers=[];_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((_,status)=>status)}get runtimeFlags(){return this.ask((state,status)=>{if(isDone2(status))return state.currentRuntimeFlags;return status.runtimeFlags})}scope(){return unsafeMake6(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,status)=>{deferredUnsafeDone(deferred,sync(()=>f(fiber,status)))})),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),patch9=pipe(diff4(parentRuntimeFlags,updatedRuntimeFlags),exclude2(Interruption),exclude2(WindDown));return updateRuntimeFlags(patch9)})}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 children=this._children;if(this._children=null,children!==null&&children.size>0){for(let child of children)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!isEmpty3(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 isDone3=!1;return whileLoop({while:()=>!isDone3,body:()=>{let next2=it.next();if(!next2.done)return asVoid(next2.value.await);else return sync(()=>{isDone3=!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),annotations=this.getFiberRef(currentLogAnnotations),loggers=this.getLoggers(),contextMap=this.getFiberRefs();if(size3(loggers)>0){let clockService=get5(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,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?done3: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,patch9){let newRuntimeFlags=patch4(oldRuntimeFlags,patch9);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(()=>unsafeGet4(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=diff6(snap.refs,refs),patchFlags=diff4(snap.flags,flags);return exitSucceed(blocked(op.effect_instruction_i0,withFiberRuntime((newFiber)=>{while(frames.length>0)newFiber.pushStack(frames.pop());return newFiber.setFiberRefs(patch7(newFiber.id(),newFiber.getFiberRefs())(patchRefs)),newFiber.currentRuntimeFlags=patch4(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=patch4(oldRuntimeFlags,updateFlags);if(interruptible(newRuntimeFlags)&&this.isInterrupted())return exitFailCause(this.getInterruptedCause());else if(this.patchRuntimeFlags(this.currentRuntimeFlags,updateFlags),op.effect_instruction_i1){let revertFlags=diff4(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){let level=this.getFiberRef(currentVersionMismatchErrorLogLevel);if(level._tag==="Some"){let effectVersion=cur[EffectTypeId2]._V;this.log(`Executing an Effect versioned ${effectVersion} with a Runtime of version ${getCurrentVersion()}, you may want to dedupe the effect dependencies, you can use the language service plugin to detect this at compile time: https://github.com/Effect-TS/language-service`,empty6,level)}}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);get5(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,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=unsafeGet4(getOrDefault(context2,currentServices),clockTag),attributes={};for(let[key,value]of annotations)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.length===1?message[0]:message),clockService.unsafeCurrentTimeNanos(),attributes)}));var currentLoggers=globalValue(Symbol.for("effect/FiberRef/currentLoggers"),()=>fiberRefUnsafeMakeHashSet(make7(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((annotations)=>{for(let i=0;i<entries2.length;i++){let[key,value]=entries2[i];set3(annotations,key,value)}return annotations}))},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=disable2(runtime2.currentRuntimeFlags,Interruption);return flatMap8(scope,(scope)=>scopeAddFinalizerExit(scope,(exit2)=>withFiberRuntime((runtimeFinalizer)=>{let preRefs=runtimeFinalizer.getFiberRefs(),preFlags=runtimeFinalizer.currentRuntimeFlags,patchRefs=diff6(preRefs,acquireRefs),patchFlags=diff4(preFlags,acquireFlags),inverseRefs=diff6(acquireRefs,preRefs);return runtimeFinalizer.setFiberRefs(patch7(patchRefs,runtimeFinalizer.id(),acquireRefs)),ensuring(withRuntimeFlags(finalizer(exit2),patchFlags),sync(()=>{runtimeFinalizer.setFiberRefs(patch7(inverseRefs,runtimeFinalizer.id(),runtimeFinalizer.getFiberRefs()))}))})))}),daemonChildren=(self)=>{return fiberRefLocally(currentForkScopeOverride,some2(globalScope))(self)},_existsParFound=Symbol.for("effect/Effect/existsPar/found"),exists=dual((args2)=>isIterable(args2[0])&&!isEffect(args2[0]),(elements,predicate,options)=>matchSimple(options?.concurrency,()=>suspend(()=>existsLoop(elements[Symbol.iterator](),0,predicate)),()=>matchEffect(forEach5(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 next2=iterator.next();if(next2.done)return succeed(!1);return flatMap8(f(next2.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(()=>[]))),()=>map10(forEach5(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 keys3=Object.keys(input),size7=keys3.length;return[keys3.map((k)=>input[k]),some2((values3)=>{let res={};for(let i=0;i<size7;i++)res[keys3[i]]=values3[i];return res})]},allValidate=(effects,reconcile,options)=>{let eitherEffects=[];for(let effect of effects)eitherEffects.push(either2(effect));return flatMap8(forEach5(eitherEffects,identity,{concurrency:options?.concurrency,batching:options?.batching,concurrentFinalizers:options?.concurrentFinalizers}),(eithers)=>{let none9=none2(),size7=eithers.length,errors=Array(size7),successes=Array(size7),errored=!1;for(let i=0;i<size7;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 forEach5(eitherEffects,identity,{concurrency:options?.concurrency,batching:options?.batching,discard:!0,concurrentFinalizers:options?.concurrentFinalizers});return map10(forEach5(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(forEach5(effects,identity,options),reconcile.value):forEach5(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)),forEach5=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 match7(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 match7(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 as3=fromIterable(self),array3=Array(as3.length);return zipRight(forEachConcurrentDiscard(as3,(a,i)=>flatMap8(f(a,i),(b)=>sync(()=>array3[i]=b)),batching,!1),succeed(array3))}),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,interrupted=!1,fibersCount=n?Math.min(todos.length,n):todos.length,fibers=new Set,results=[],interruptAll=()=>fibers.forEach((fiber)=>{fiber.currentScheduler.scheduleTask(()=>{fiber.unsafeInterruptAsFork(parent.id())},0)}),startOrder=[],joinOrder=[],residual=[],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=[];interrupted=!0,interruptAll()},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"&&!interrupted)onInterruptSignal()},next2=()=>{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),interrupted)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 next2()})}};for(let i=0;i<fibersCount;i++)next2()}));return asVoid(onExit(flatten5(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)next2()},next2=()=>{runFiber(toPop.pop(),!0).addObserver(check(index,!0)),index++};processingFiber.addObserver(check(index,!1)),index++;for(let i=0;i<concurrency;i++)next2()})},onSuccess:()=>forEachSequential(joinOrder,(f2)=>f2.inheritAll)})))}))),forEachParN=(self,n,f,batching)=>suspend(()=>{let as3=fromIterable(self),array3=Array(as3.length);return zipRight(forEachConcurrentDiscard(as3,(a,i)=>map10(f(a,i),(b)=>array3[i]=b),batching,!1,n),succeed(array3))}),fork=(self)=>withFiberRuntime((state,status)=>succeed(unsafeFork(self,state,status.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=unsafeMake3(),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))),mergeAll3=dual((args2)=>isFunction2(args2[2]),(elements,zero2,f,options)=>matchSimple(options?.concurrency,()=>fromIterable(elements).reduce((acc,a,i)=>zipWith3(acc,a,(acc2,a2)=>f(acc2,a2,i)),succeed(zero2)),()=>flatMap8(make24(zero2),(acc)=>flatMap8(forEach5(elements,(effect,i)=>flatMap8(effect,(a)=>update3(acc,(b)=>f(b,a,i))),options),()=>get11(acc))))),partition3=dual((args2)=>isIterable(args2[0]),(elements,f,options)=>pipe(forEach5(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)=>withFiberRuntime((state,status)=>async_((resume2)=>{let fibers=new Set,winner,failures2=empty6,interruptAll=()=>{for(let fiber of fibers)fiber.unsafeInterruptAsFork(state.id())},latch=!1,empty23=!0;for(let self of all5){empty23=!1;let fiber=unsafeFork(interruptible2(self),state,status.runtimeFlags);if(fibers.add(fiber),fiber.addObserver((exit2)=>{if(fibers.delete(fiber),!winner)if(exit2._tag==="Success")latch=!0,winner=fiber,failures2=empty6,interruptAll();else failures2=parallel(exit2.cause,failures2);if(latch&&fibers.size===0)resume2(winner?zipRight(inheritAll(winner),winner.unsafePoll()):failCause(failures2))}),winner)break}if(empty23)return resume2(dieSync(()=>new IllegalArgumentException("Received an empty collection of effects")));return latch=!0,interruptAllAs(fibers,state.id())})),reduceEffect=dual((args2)=>isIterable(args2[0])&&!isEffect(args2[0]),(elements,zero2,f,options)=>matchSimple(options?.concurrency,()=>fromIterable(elements).reduce((acc,a,i)=>zipWith3(acc,a,(acc2,a2)=>f(acc2,a2,i)),zero2),()=>suspend(()=>pipe(mergeAll3([zero2,...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 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 patch9=strategy._tag==="Parallel"?parallelFinalizers:strategy._tag==="Sequential"?sequentialFinalizers:parallelNFinalizers(strategy.parallelism);switch(scope.strategy._tag){case"Parallel":return patch9(self(parallelFinalizers));case"Sequential":return patch9(self(sequentialFinalizers));case"ParallelN":return patch9(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([make27(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)=>flatten5(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(forEach5(elements,(a,i)=>flip(f(a,i)),options))),withClockScoped=(c)=>fiberRefLocallyScopedWith(currentServices,add4(clockTag,c)),withRandomScoped=(value)=>fiberRefLocallyScopedWith(currentServices,add4(randomTag,value)),withConfigProviderScoped=(provider)=>fiberRefLocallyScopedWith(currentServices,add4(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===empty15)return void_;return pipe(runtimeFlags,flatMap8((runtimeFlags2)=>{let updatedRuntimeFlags=patch4(runtimeFlags2,update5),revertRuntimeFlags=diff4(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(make9(scopeTag,scope2)))),scopeUse=dual(2,(effect,scope2)=>pipe(effect,scopeExtend(scope2),onExit((exit2)=>scope2.close(exit2)))),fiberRefUnsafeMakeSupervisor=(initial)=>fiberRefUnsafeMakePatch(initial,{differ:differ2,fork:empty22}),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)=>forEach5(fibers,_await),fiberAll=(fibers)=>{return{...CommitPrototype2,commit(){return join2(this)},[FiberTypeId]:fiberVariance2,id:()=>fromIterable(fibers).reduce((id,fiber)=>combine3(id,fiber.id()),none4),await:exit(forEachParUnbounded(fibers,(fiber)=>flatten5(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([])),(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))}};var 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=make11(!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((id)=>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(id)))})));var makeSpanScoped=(name,options)=>{return options=addSpanStackTrace(options),uninterruptible(withFiberRuntime((fiber)=>{let scope2=unsafeGet4(fiber.getFiberRef(currentContext),scopeTag),span2=unsafeMakeSpan(fiber,name,options),timingEnabled=fiber.getFiberRef(currentTracerTimingEnabled),clock_=get5(fiber.getFiberRef(currentServices),clockTag);return as(scopeAddFinalizerExit(scope2,(exit2)=>endSpan(span2,exit2,clock_,timingEnabled)),span2)}))},withTracerScoped=(value)=>fiberRefLocallyScopedWith(currentServices,add4(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 IntervalSymbolKey="effect/ScheduleInterval",IntervalTypeId=Symbol.for(IntervalSymbolKey),empty23={[IntervalTypeId]:IntervalTypeId,startMillis:0,endMillis:0},make32=(startMillis,endMillis)=>{if(startMillis>endMillis)return empty23;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 isEmpty6=(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 make32(start,end)}),size7=(self)=>{return millis(self.endMillis-self.startMillis)};var after=(startMilliseconds)=>{return make32(startMilliseconds,Number.POSITIVE_INFINITY)};var make33=make32,empty24=empty23,lessThan4=lessThan3;var isEmpty7=isEmpty6;var intersect2=intersect,size8=size7;var after2=after;var IntervalsSymbolKey="effect/ScheduleIntervals",IntervalsTypeId=Symbol.for(IntervalsSymbolKey),make34=(intervals)=>{return{[IntervalsTypeId]:IntervalsTypeId,intervals}};var union6=dual(2,(self,that)=>{if(!isNonEmpty(that.intervals))return self;if(!isNonEmpty(self.intervals))return that;if(headNonEmpty2(self.intervals).startMillis<headNonEmpty2(that.intervals).startMillis)return unionLoop(tailNonEmpty2(self.intervals),that.intervals,headNonEmpty2(self.intervals),empty2());return unionLoop(self.intervals,tailNonEmpty2(that.intervals),headNonEmpty2(that.intervals),empty2())}),unionLoop=(_self,_that,_interval,_acc)=>{let self=_self,that=_that,interval=_interval,acc=_acc;while(isNonEmpty(self)||isNonEmpty(that))if(!isNonEmpty(self)&&isNonEmpty(that))if(interval.endMillis<headNonEmpty2(that).startMillis)acc=pipe(acc,prepend2(interval)),interval=headNonEmpty2(that),that=tailNonEmpty2(that),self=empty2();else interval=make33(interval.startMillis,headNonEmpty2(that).endMillis),that=tailNonEmpty2(that),self=empty2();else if(isNonEmpty(self)&&isEmpty(that))if(interval.endMillis<headNonEmpty2(self).startMillis)acc=pipe(acc,prepend2(interval)),interval=headNonEmpty2(self),that=empty2(),self=tailNonEmpty2(self);else interval=make33(interval.startMillis,headNonEmpty2(self).endMillis),that=empty2(),self=tailNonEmpty2(self);else if(isNonEmpty(self)&&isNonEmpty(that))if(headNonEmpty2(self).startMillis<headNonEmpty2(that).startMillis)if(interval.endMillis<headNonEmpty2(self).startMillis)acc=pipe(acc,prepend2(interval)),interval=headNonEmpty2(self),self=tailNonEmpty2(self);else interval=make33(interval.startMillis,headNonEmpty2(self).endMillis),self=tailNonEmpty2(self);else if(interval.endMillis<headNonEmpty2(that).startMillis)acc=pipe(acc,prepend2(interval)),interval=headNonEmpty2(that),that=tailNonEmpty2(that);else interval=make33(interval.startMillis,headNonEmpty2(that).endMillis),that=tailNonEmpty2(that);else throw Error(getBugErrorMessage("Intervals.unionLoop"));return make34(pipe(acc,prepend2(interval),reverse2))},intersect3=dual(2,(self,that)=>intersectLoop(self.intervals,that.intervals,empty2())),intersectLoop=(_left,_right,_acc)=>{let left3=_left,right3=_right,acc=_acc;while(isNonEmpty(left3)&&isNonEmpty(right3)){let interval=pipe(headNonEmpty2(left3),intersect2(headNonEmpty2(right3))),intervals=isEmpty7(interval)?acc:pipe(acc,prepend2(interval));if(pipe(headNonEmpty2(left3),lessThan4(headNonEmpty2(right3))))left3=tailNonEmpty2(left3);else right3=tailNonEmpty2(right3);acc=intervals}return make34(reverse2(acc))},start=(self)=>{return pipe(self.intervals,head2,getOrElse(()=>empty24)).startMillis},end=(self)=>{return pipe(self.intervals,head2,getOrElse(()=>empty24)).endMillis},lessThan5=dual(2,(self,that)=>start(self)<start(that)),isNonEmpty3=(self)=>{return isNonEmpty(self.intervals)},max4=dual(2,(self,that)=>lessThan5(self,that)?that:self);var make35=make34;var union7=union6,intersect4=intersect3,start2=start,end2=end,lessThan6=lessThan5,isNonEmpty4=isNonEmpty3,max5=max4;var OP_CONTINUE="Continue",OP_DONE2="Done",_continue=(intervals)=>{return{_tag:OP_CONTINUE,intervals}},continueWith=(interval)=>{return{_tag:OP_CONTINUE,intervals:make35(of2(interval))}},done4={_tag:OP_DONE2},isContinue=(self)=>{return self._tag===OP_CONTINUE},isDone3=(self)=>{return self._tag===OP_DONE2};var _continue2=_continue;var continueWith2=continueWith,done5=done4,isContinue2=isContinue,isDone4=isDone3;var Scope=scopeTag,addFinalizer2=scopeAddFinalizer,addFinalizerExit=scopeAddFinalizerExit,close=scopeClose,extend2=scopeExtend,fork2=scopeFork;var make36=scopeMake;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))});updateTakenUnsafe(fiber,f){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)}updateTaken(f){return withFiberRuntime((fiber)=>this.updateTakenUnsafe(fiber,f))}resize=(permits)=>asVoid(withFiberRuntime((fiber)=>{if(this.permits=permits,this.free<0)return void_;return this.updateTakenUnsafe(fiber,(taken)=>taken)}));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),(tuple)=>tuple[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)=>set4(cache,none2()),ensuringChild=dual(2,(self,f)=>ensuringChildren(self,(children)=>f(fiberAll(children)))),ensuringChildren=dual(2,(self,children)=>flatMap8(track,(supervisor)=>pipe(supervised(self,supervisor),ensuring(flatMap8(supervisor.value,children))))),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((map13)=>{let result=pipe(map13,get12(new Key(a,eq)));if(isNone2(result))return pipe(deferredMake(),tap((deferred)=>pipe(diffFiberRefs(f(a)),intoDeferred(deferred),fork)),map10((deferred)=>[deferred,pipe(map13,set6(new Key(a,eq),deferred))]));return succeed([result.value,map13])}),flatMap8(deferredAwait),flatMap8(([patch9,b])=>pipe(patchFiberRefs(patch9),as(b))))))},raceFirst=dual(2,(self,that)=>pipe(exit(self),race(exit(that)),(effect)=>flatten5(effect))),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})=>flatten5(timeoutTo(self,{onTimeout:()=>failSync(onTimeout),onSuccess:succeed,duration}))),timeoutFailCause=dual(2,(self,{duration,onTimeout})=>flatten5(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;[TypeId10]=TypeId10;constructor(ref,withLock){super();this.ref=ref,this.withLock=withLock,this.get=get10(this.ref)}get;commit(){return this.get}modify(f){return this.modifyEffect((a)=>succeed(f(a)))}modifyEffect(f){return this.withLock(pipe(flatMap8(get10(this.ref),f),flatMap8(([b,a])=>as(set4(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])}}));var bindAll=dual((args2)=>isEffect(args2[0]),(self,f,options)=>flatMap8(self,(a)=>all4(f(a),options).pipe(map10((record)=>Object.assign({},a,record)))));var TypeId12=Symbol.for("effect/ManagedRuntime");var OP_EXTEND_SCOPE="ExtendScope",OP_FOLD="Fold",OP_FRESH="Fresh",OP_FROM_EFFECT="FromEffect",OP_SCOPED="Scoped",OP_SUSPEND="Suspend",OP_PROVIDE="Provide",OP_PROVIDE_MERGE="ProvideMerge",OP_MERGE_ALL="MergeAll",OP_ZIP_WITH2="ZipWith";var _await2=_await;var inheritAll2=inheritAll,interrupt5=interruptFiber;var interruptAs=interruptAsFiber;var join3=join2;var poll2=poll;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=unsafeMake3(),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((id2)=>equals(id2,fiberRuntime.id())?void_:interruptAsFiber(fiberRuntime,id2))),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(id2,cancelOptions)=>unsafeRunCallback(runtime2)(pipe(fiberRuntime,interruptAs(id2??none4)),{...cancelOptions,onExit:cancelOptions?.onExit?(exit2)=>cancelOptions.onExit(flatten6(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 make37=(options)=>new RuntimeImpl(options.context,options.runtimeFlags,options.fiberRefs),runtime2=()=>withFiberRuntime((state,status2)=>succeed(new RuntimeImpl(state.getFiberRef(currentContext),status2.runtimeFlags,state.getFiberRefs()))),defaultRuntimeFlags=make16(Interruption,CooperativeYielding,RuntimeMetrics),defaultRuntime=make37({context:empty8(),runtimeFlags:defaultRuntimeFlags,fiberRefs:empty19()});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,(map14)=>{let inMap=map14.get(layer);if(inMap!==void 0){let[acquire,release]=inMap,cached3=pipe(acquire,flatMap8(([patch9,b])=>pipe(patchFiberRefs(patch9),as(b))),onExit(exitMatch({onFailure:()=>void_,onSuccess:()=>scopeAddFinalizerExit(scope2,release)})));return succeed([cached3,map14])}return pipe(make23(0),flatMap8((observers)=>pipe(deferredMake(),flatMap8((deferred)=>pipe(make23(()=>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(set4(finalizerRef,(exit3)=>pipe(scopeClose(innerScope,exit3),whenEffect(modify3(observers,(n)=>[n===1,n-1])),asVoid)),zipRight(update2(observers,(n)=>n+1)),zipRight(scopeAddFinalizerExit(scope2,(exit3)=>pipe(sync(()=>map14.delete(layer)),zipRight(get10(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(get10(finalizerRef),flatMap8((finalizer)=>finalizer(exit2)))];return[resource,isFresh(layer)?map14:map14.set(layer,memoized)]}))))))}),flatten5)}}var makeMemoMap=suspend(()=>map10(makeSynchronized(new Map),(ref)=>new MemoMapImpl(ref))),unsafeMakeMemoMap=()=>new MemoMapImpl(unsafeMakeSynchronized(new Map)),build=(self)=>scopeWith((scope2)=>buildWithScope(self,scope2)),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 gen(function*(){let parallelScope=yield*scopeFork(scope2,parallel2),firstScope=yield*scopeFork(parallelScope,sequential2),secondScope=yield*scopeFork(parallelScope,sequential2);return(memoMap)=>pipe(memoMap.getOrElseMemoize(op.first,firstScope),zipWithOptions(memoMap.getOrElseMemoize(op.second,secondScope),op.zipK,{concurrent:!0}))});case"MergeAll":{let layers=op.layers;return map10(scopeFork(scope2,parallel2),(parallelScope)=>(memoMap)=>{let contexts=Array(layers.length);return map10(forEachConcurrentDiscard(layers,fnUntraced(function*(layer,i){let scope3=yield*scopeFork(parallelScope,sequential2),context2=yield*memoMap.getOrElseMemoize(layer,scope3);contexts[i]=context2}),!1,!1),()=>mergeAll2(...contexts))})}}},catchAll2=dual(2,(self,onFailure)=>match11(self,{onFailure,onSuccess:succeedContext})),catchAllCause2=dual(2,(self,onFailure)=>matchCause2(self,{onFailure,onSuccess:succeedContext})),die5=(defect)=>failCause5(die3(defect)),dieSync2=(evaluate2)=>failCauseSync2(()=>die3(evaluate2())),discard=(self)=>map14(self,()=>empty8()),context2=()=>fromEffectContext(context()),extendScope=(self)=>{let extendScope2=Object.create(proto3);return extendScope2._op_layer=OP_EXTEND_SCOPE,extendScope2.layer=self,extendScope2},fail6=(error)=>failCause5(fail3(error)),failSync2=(evaluate2)=>failCauseSync2(()=>fail3(evaluate2())),failCause5=(cause2)=>fromEffectContext(failCause(cause2)),failCauseSync2=(evaluate2)=>fromEffectContext(failCauseSync(evaluate2)),flatMap10=dual(2,(self,f)=>match11(self,{onFailure:fail6,onSuccess:f})),flatten7=dual(2,(self,tag)=>flatMap10(self,get5(tag))),fresh=(self)=>{let fresh2=Object.create(proto3);return fresh2._op_layer=OP_FRESH,fresh2.layer=self,fresh2},fromEffect3=dual(2,(a,b)=>{let tagFirst=isTag2(a),tag=tagFirst?a:b;return fromEffectContext(map10(tagFirst?b:a,(service)=>make9(tag,service)))}),fromEffectDiscard=(effect)=>fromEffectContext(map10(effect,()=>empty8()));function fromEffectContext(effect){let fromEffect4=Object.create(proto3);return fromEffect4._op_layer=OP_FROM_EFFECT,fromEffect4.effect=effect,fromEffect4}var fiberRefLocally2=dual(3,(self,ref,value)=>locallyEffect(self,fiberRefLocally(ref,value))),locallyEffect=dual(2,(self,f)=>{let locally=Object.create(proto3);return locally._op_layer="Locally",locally.self=self,locally.f=f,locally}),fiberRefLocallyWith2=dual(3,(self,ref,value)=>locallyEffect(self,fiberRefLocallyWith(ref,value))),fiberRefLocallyScoped2=(self,value)=>scopedDiscard(fiberRefLocallyScoped(self,value)),fiberRefLocallyScopedWith2=(self,value)=>scopedDiscard(fiberRefLocallyScopedWith(self,value)),fromFunction=(tagA,tagB,f)=>fromEffectContext(map10(tagA,(a)=>make9(tagB,f(a)))),launch=(self)=>scopedEffect(zipRight(scopeWith((scope2)=>pipe(self,buildWithScope(scope2))),never)),mock=function(){if(arguments.length===1)return(service)=>mockImpl(arguments[0],service);return mockImpl(arguments[0],arguments[1])},mockImpl=(tag,service)=>succeed5(tag,new Proxy({...service},{get(target,prop,_receiver){if(prop in target)return target[prop];let prevLimit=Error.stackTraceLimit;Error.stackTraceLimit=2;let error=Error(`${tag.key}: Unimplemented method "${prop.toString()}"`);return Error.stackTraceLimit=prevLimit,error.name="UnimplementedError",makeUnimplemented(error)},has:constTrue})),makeUnimplemented=(error)=>{let dead=die2(error);function unimplemented(){return dead}return Object.assign(unimplemented,dead),Object.setPrototypeOf(unimplemented,Object.getPrototypeOf(dead)),unimplemented},map14=dual(2,(self,f)=>flatMap10(self,(context3)=>succeedContext(f(context3)))),mapError2=dual(2,(self,f)=>catchAll2(self,(error)=>failSync2(()=>f(error)))),matchCause2=dual(2,(self,{onFailure,onSuccess})=>{let fold=Object.create(proto3);return fold._op_layer=OP_FOLD,fold.layer=self,fold.failureK=onFailure,fold.successK=onSuccess,fold}),match11=dual(2,(self,{onFailure,onSuccess})=>matchCause2(self,{onFailure:(cause2)=>{let failureOrCause3=failureOrCause2(cause2);switch(failureOrCause3._tag){case"Left":return onFailure(failureOrCause3.left);case"Right":return failCause5(failureOrCause3.right)}},onSuccess})),memoize2=(self)=>scopeWith((scope2)=>map10(memoize(buildWithScope(self,scope2)),fromEffectContext)),merge6=dual(2,(self,that)=>zipWith4(self,that,(a,b)=>merge3(a,b))),mergeAll4=(...layers)=>{let mergeAll5=Object.create(proto3);return mergeAll5._op_layer=OP_MERGE_ALL,mergeAll5.layers=layers,mergeAll5},orDie2=(self)=>catchAll2(self,(defect)=>die5(defect)),orElse4=dual(2,(self,that)=>catchAll2(self,that)),passthrough=(self)=>merge6(context2(),self),project=dual(4,(self,tagA,tagB,f)=>map14(self,(context3)=>make9(tagB,f(unsafeGet4(context3,tagA))))),retry=dual(2,(self,schedule)=>suspend2(()=>{let stateTag=GenericTag("effect/Layer/retry/{ state: unknown }");return pipe(succeed5(stateTag,{state:schedule.initial}),flatMap10((env)=>retryLoop(self,schedule,stateTag,pipe(env,get5(stateTag)).state)))})),retryLoop=(self,schedule,stateTag,state)=>{return pipe(self,catchAll2((error)=>pipe(retryUpdate(schedule,stateTag,error,state),flatMap10((env)=>fresh(retryLoop(self,schedule,stateTag,pipe(env,get5(stateTag)).state))))))},retryUpdate=(schedule,stateTag,error,state)=>{return fromEffect3(stateTag,pipe(currentTimeMillis2,flatMap8((now)=>pipe(schedule.step(now,error,state),flatMap8(([state2,_,decision])=>isDone4(decision)?fail2(error):pipe(sleep2(millis(start2(decision.intervals)-now)),as({state:state2})))))))},scoped=dual(2,(a,b)=>{let tagFirst=isTag2(a),tag=tagFirst?a:b;return scopedContext(map10(tagFirst?b:a,(service)=>make9(tag,service)))}),scopedDiscard=(effect)=>scopedContext(pipe(effect,as(empty8()))),scopedContext=(effect)=>{let scoped2=Object.create(proto3);return scoped2._op_layer=OP_SCOPED,scoped2.effect=effect,scoped2},scope2=scopedContext(map10(acquireRelease(scopeMake(),(scope3,exit2)=>scope3.close(exit2)),(scope3)=>make9(Scope,scope3))),service=(tag)=>fromEffect3(tag,tag),succeed5=dual(2,(a,b)=>{let tagFirst=isTag2(a);return fromEffectContext(succeed(make9(tagFirst?a:b,tagFirst?b:a)))}),succeedContext=(context3)=>{return fromEffectContext(succeed(context3))},empty26=succeedContext(empty8()),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(()=>make9(tag,evaluate2())))}),syncContext=(evaluate2)=>{return fromEffectContext(sync(evaluate2))},tap2=dual(2,(self,f)=>flatMap10(self,(context3)=>fromEffectContext(as(f(context3),context3)))),tapError2=dual(2,(self,f)=>catchAll2(self,(e)=>fromEffectContext(flatMap8(f(e),()=>fail2(e))))),tapErrorCause2=dual(2,(self,f)=>catchAllCause2(self,(cause2)=>fromEffectContext(flatMap8(f(cause2),()=>failCause(cause2))))),toRuntime=(self)=>pipe(scopeWith((scope3)=>buildWithScope(self,scope3)),flatMap8((context3)=>pipe(runtime2(),provideContext(context3)))),toRuntimeWithMemoMap=dual(2,(self,memoMap)=>flatMap8(scopeWith((scope3)=>buildWithMemoMap(self,memoMap,scope3)),(context3)=>pipe(runtime2(),provideContext(context3)))),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)?mergeAll4(...that):that},zipK:{value:(a,b)=>pipe(a,merge3(b))}}),provideTo.second=self,provideTo})),provideMerge=dual(2,(that,self)=>{let zipWith4=Object.create(proto3);return zipWith4._op_layer=OP_PROVIDE_MERGE,zipWith4.first=self,zipWith4.second=provide(that,self),zipWith4.zipK=(a,b)=>{return pipe(a,merge3(b))},zipWith4}),zipWith4=dual(3,(self,that,f)=>suspend2(()=>{let zipWith5=Object.create(proto3);return zipWith5._op_layer=OP_ZIP_WITH2,zipWith5.first=self,zipWith5.second=that,zipWith5.zipK=f,zipWith5})),unwrapEffect=(self)=>{let tag=GenericTag("effect/Layer/unwrapEffect/Layer.Layer<R1, E1, A>");return flatMap10(fromEffect3(tag,self),(context3)=>get5(context3,tag))},unwrapScoped=(self)=>{let tag=GenericTag("effect/Layer/unwrapScoped/Layer.Layer<R1, E1, A>");return flatMap10(scoped(tag,self),(context3)=>get5(context3,tag))},annotateLogs2=dual((args2)=>isLayer(args2[0]),function(){let args2=arguments;return fiberRefLocallyWith2(args2[0],currentLogAnnotations,typeof args2[1]==="string"?set3(args2[1],args2[2]):(annotations)=>Object.entries(args2[1]).reduce((acc,[key,value])=>set3(acc,key,value),annotations))}),annotateSpans2=dual((args2)=>isLayer(args2[0]),function(){let args2=arguments;return fiberRefLocallyWith2(args2[0],currentTracerSpanAnnotations,typeof args2[1]==="string"?set3(args2[1],args2[2]):(annotations)=>Object.entries(args2[1]).reduce((acc,[key,value])=>set3(acc,key,value),annotations))}),withSpan2=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 unwrapScoped(map10(options?.onEnd?tap(makeSpanScoped(name,options),(span2)=>addFinalizer((exit2)=>options.onEnd(span2,exit2))):makeSpanScoped(name,options),(span2)=>withParentSpan2(self,span2)))}return(self)=>unwrapScoped(map10(options?.onEnd?tap(makeSpanScoped(name,options),(span2)=>addFinalizer((exit2)=>options.onEnd(span2,exit2))):makeSpanScoped(name,options),(span2)=>withParentSpan2(self,span2)))},withParentSpan2=dual(2,(self,span2)=>provide(self,succeedContext(make9(spanTag,span2)))),provideSomeLayer=dual(2,(self,layer)=>scopedWith((scope3)=>flatMap8(buildWithScope(layer,scope3),(context3)=>provideSomeContext(self,context3)))),provideSomeRuntime=dual(2,(self,rt)=>{let patchRefs=diff6(defaultRuntime.fiberRefs,rt.fiberRefs),patchFlags=diff4(defaultRuntime.runtimeFlags,rt.runtimeFlags);return uninterruptibleMask((restore)=>withFiberRuntime((fiber)=>{let oldContext=fiber.getFiberRef(currentContext),oldRefs=fiber.getFiberRefs(),newRefs=patch7(fiber.id(),oldRefs)(patchRefs),oldFlags=fiber.currentRuntimeFlags,newFlags=patch4(patchFlags)(oldFlags),rollbackRefs=diff6(newRefs,oldRefs),rollbackFlags=diff4(newFlags,oldFlags);return fiber.setFiberRefs(newRefs),fiber.currentRuntimeFlags=newFlags,ensuring(provideSomeContext(restore(self),merge3(oldContext,rt.context)),withFiberRuntime((fiber2)=>{return fiber2.setFiberRefs(patch7(fiber2.id(),fiber2.getFiberRefs())(rollbackRefs)),fiber2.currentRuntimeFlags=patch4(rollbackFlags)(fiber2.currentRuntimeFlags),void_}))}))}),effect_provide=dual(2,(self,source)=>{if(Array.isArray(source))return provideSomeLayer(self,mergeAll4(...source));else if(isLayer(source))return provideSomeLayer(self,source);else if(isContext2(source))return provideSomeContext(self,source);else if(TypeId12 in source)return flatMap8(source.runtimeEffect,(rt)=>provideSomeRuntime(self,rt));else return provideSomeRuntime(self,source)});var console2=map10(fiberRefGet(currentServices),get5(consoleTag)),consoleWith=(f)=>fiberRefGetWith(currentServices,(services)=>f(get5(services,consoleTag))),withConsole=dual(2,(effect,value)=>fiberRefLocallyWith(effect,currentServices,add4(consoleTag,value))),withConsoleScoped=(console3)=>fiberRefLocallyScopedWith(currentServices,add4(consoleTag,console3)),setConsole=(console3)=>scopedDiscard(fiberRefLocallyScopedWith(currentServices,add4(consoleTag,console3))),assert=(condition,...args2)=>consoleWith((_)=>_.assert(condition,...args2)),clear=consoleWith((_)=>_.clear),count=(label)=>consoleWith((_)=>_.count(label)),countReset=(label)=>consoleWith((_)=>_.countReset(label)),debug=(...args2)=>consoleWith((_)=>_.debug(...args2)),dir=(item,options)=>consoleWith((_)=>_.dir(item,options)),dirxml=(...args2)=>consoleWith((_)=>_.dirxml(...args2)),error=(...args2)=>consoleWith((_)=>_.error(...args2)),group=(options)=>consoleWith((_)=>acquireRelease(_.group(options),()=>_.groupEnd)),info=(...args2)=>consoleWith((_)=>_.info(...args2)),log2=(...args2)=>consoleWith((_)=>_.log(...args2)),table=(tabularData,properties)=>consoleWith((_)=>_.table(tabularData,properties)),time=(label)=>consoleWith((_)=>acquireRelease(_.time(label),()=>_.timeEnd(label))),timeLog=(label,...args2)=>consoleWith((_)=>_.timeLog(label,...args2)),trace=(...args2)=>consoleWith((_)=>_.trace(...args2)),warn=(...args2)=>consoleWith((_)=>_.warn(...args2)),withGroup=dual((args2)=>isEffect(args2[0]),(self,options)=>consoleWith((_)=>acquireUseRelease(_.group(options),()=>self,()=>_.groupEnd))),withTime=dual((args2)=>isEffect(args2[0]),(self,label)=>consoleWith((_)=>acquireUseRelease(_.time(label),()=>self,()=>_.timeEnd(label))));var exports_Data={};__export(exports_Data,{unsafeStruct:()=>unsafeStruct,unsafeArray:()=>unsafeArray,tuple:()=>tuple,taggedEnum:()=>taggedEnum,tagged:()=>tagged2,struct:()=>struct2,case:()=>_case,array:()=>array3,TaggedError:()=>TaggedError,TaggedClass:()=>TaggedClass,Structural:()=>Structural2,Error:()=>Error3,Class:()=>Class2});var struct2=struct,unsafeStruct=(as3)=>Object.setPrototypeOf(as3,StructuralPrototype),tuple=(...as3)=>unsafeArray(as3),array3=(as3)=>unsafeArray(as3.slice(0)),unsafeArray=(as3)=>Object.setPrototypeOf(as3,ArrayProto),_case=()=>(args2)=>args2===void 0?Object.create(StructuralPrototype):struct2(args2);var tagged2=(tag)=>(args2)=>{let value=args2===void 0?Object.create(StructuralPrototype):struct2(args2);return value._tag=tag,value},Class2=Structural,TaggedClass=(tag)=>{class Base3 extends Class2{_tag=tag}return Base3},Structural2=Structural,taggedEnum=()=>new Proxy({},{get(_target,tag,_receiver){if(tag==="$is")return isTagged;else if(tag==="$match")return taggedMatch;return tagged2(tag)}});function taggedMatch(){if(arguments.length===1){let cases2=arguments[0];return function(value2){return cases2[value2._tag](value2)}}let value=arguments[0];return arguments[1][value._tag](value)}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 TypeId13=Symbol.for("effect/DateTime"),TimeZoneTypeId=Symbol.for("effect/DateTime/TimeZone"),Proto2={[TypeId13]:TypeId13,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}}},makeZonedProto=(epochMillis,zone,partsUtc)=>{let self=Object.create(ProtoZoned);return self.epochMillis=epochMillis,self.zone=zone,Object.defineProperty(self,"partsUtc",{value:partsUtc,enumerable:!1,writable:!0}),Object.defineProperty(self,"adjustedEpochMillis",{value:void 0,enumerable:!1,writable:!0}),Object.defineProperty(self,"partsAdjusted",{value:void 0,enumerable:!1,writable:!0}),self},isDateTime=(u)=>hasProperty(u,TypeId13),isDateTimeArgs=(args2)=>isDateTime(args2[0]),isTimeZone=(u)=>hasProperty(u,TimeZoneTypeId);var isTimeZoneNamed=(u)=>isTimeZone(u)&&u._tag==="Named";var isZoned=(self)=>self._tag==="Zoned";var makeUtc=(epochMillis)=>{let self=Object.create(ProtoUtc);return self.epochMillis=epochMillis,Object.defineProperty(self,"partsUtc",{value:void 0,enumerable:!1,writable:!0}),self},unsafeFromDate=(date)=>{let epochMillis=date.getTime();if(Number.isNaN(epochMillis))throw new IllegalArgumentException2("Invalid date");return makeUtc(epochMillis)},unsafeMake8=(input)=>{if(isDateTime(input))return input;else if(input instanceof Date)return unsafeFromDate(input);else if(typeof input==="object"){let date=new Date(0);return setPartsDate(date,input),unsafeFromDate(date)}else if(typeof input==="string"&&!hasZone(input))return unsafeFromDate(new Date(input+"Z"));return unsafeFromDate(new Date(input))},hasZone=(input)=>/Z|[+-]\d{2}$|[+-]\d{2}:?\d{2}$|\]$/.test(input),minEpochMillis=-8639999956800000,maxEpochMillis=8639999949600000,unsafeMakeZoned=(input,options)=>{if(options?.timeZone===void 0&&isDateTime(input)&&isZoned(input))return input;let self=unsafeMake8(input);if(self.epochMillis<minEpochMillis||self.epochMillis>maxEpochMillis)throw RangeError(`Epoch millis out of range: ${self.epochMillis}`);let zone;if(options?.timeZone===void 0){let offset=new Date(self.epochMillis).getTimezoneOffset()*-60*1000;zone=zoneMakeOffset(offset)}else if(isTimeZone(options?.timeZone))zone=options.timeZone;else if(typeof options?.timeZone==="number")zone=zoneMakeOffset(options.timeZone);else{let parsedZone=zoneFromString(options.timeZone);if(isNone2(parsedZone))throw new IllegalArgumentException2(`Invalid time zone: ${options.timeZone}`);zone=parsedZone.value}if(options?.adjustForTimeZone!==!0)return makeZonedProto(self.epochMillis,zone,self.partsUtc);return makeZonedFromAdjusted(self.epochMillis,zone,options?.disambiguation??"compatible")};var validZoneCache=globalValue("effect/DateTime/validZoneCache",()=>new Map),formatOptions={day:"numeric",month:"numeric",year:"numeric",hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"longOffset",fractionalSecondDigits:3,hourCycle:"h23"},zoneMakeIntl=(format4)=>{let zoneId=format4.resolvedOptions().timeZone;if(validZoneCache.has(zoneId))return validZoneCache.get(zoneId);let zone=Object.create(ProtoTimeZoneNamed);return zone.id=zoneId,zone.format=format4,validZoneCache.set(zoneId,zone),zone},zoneUnsafeMakeNamed=(zoneId)=>{if(validZoneCache.has(zoneId))return validZoneCache.get(zoneId);try{return zoneMakeIntl(new Intl.DateTimeFormat("en-US",{...formatOptions,timeZone:zoneId}))}catch{throw new IllegalArgumentException2(`Invalid time zone: ${zoneId}`)}},zoneMakeOffset=(offset)=>{let zone=Object.create(ProtoTimeZoneOffset);return zone.offset=offset,zone},zoneMakeNamed=liftThrowable(zoneUnsafeMakeNamed);var offsetZoneRegex=/^(?:GMT|[+-])/,zoneFromString=(zone)=>{if(offsetZoneRegex.test(zone)){let offset=parseOffset(zone);return offset===null?none2():some2(zoneMakeOffset(offset))}return zoneMakeNamed(zone)};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 abs=Math.abs(offset),hours2=Math.floor(abs/3600000),minutes2=Math.round(abs%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 dateToParts=(date)=>({millis:date.getUTCMilliseconds(),seconds:date.getUTCSeconds(),minutes:date.getUTCMinutes(),hours:date.getUTCHours(),day:date.getUTCDate(),weekDay:date.getUTCDay(),month:date.getUTCMonth()+1,year:date.getUTCFullYear()}),toParts=(self)=>{if(self._tag==="Utc")return toPartsUtc(self);else if(self.partsAdjusted!==void 0)return self.partsAdjusted;return self.partsAdjusted=withDate(self,dateToParts),self.partsAdjusted},toPartsUtc=(self)=>{if(self.partsUtc!==void 0)return self.partsUtc;return self.partsUtc=withDateUtc(self,dateToParts),self.partsUtc};var setPartsDate=(date,parts2)=>{if(parts2.year!==void 0)date.setUTCFullYear(parts2.year);if(parts2.month!==void 0)date.setUTCMonth(parts2.month-1);if(parts2.day!==void 0)date.setUTCDate(parts2.day);if(parts2.weekDay!==void 0){let diff8=parts2.weekDay-date.getUTCDay();date.setUTCDate(date.getUTCDate()+diff8)}if(parts2.hours!==void 0)date.setUTCHours(parts2.hours);if(parts2.minutes!==void 0)date.setUTCMinutes(parts2.minutes);if(parts2.seconds!==void 0)date.setUTCSeconds(parts2.seconds);if(parts2.millis!==void 0)date.setUTCMilliseconds(parts2.millis)};var constDayMillis=86400000,makeZonedFromAdjusted=(adjustedMillis,zone,disambiguation)=>{if(zone._tag==="Offset")return makeZonedProto(adjustedMillis-zone.offset,zone);let beforeOffset=calculateNamedOffset(adjustedMillis-constDayMillis,adjustedMillis,zone),afterOffset=calculateNamedOffset(adjustedMillis+constDayMillis,adjustedMillis,zone);if(beforeOffset===afterOffset)return makeZonedProto(adjustedMillis-beforeOffset,zone);let isForwards=beforeOffset<afterOffset,transitionMillis=beforeOffset-afterOffset;if(isForwards){if(calculateNamedOffset(adjustedMillis-afterOffset,adjustedMillis,zone)===afterOffset)return makeZonedProto(adjustedMillis-afterOffset,zone);let before2=makeZonedProto(adjustedMillis-beforeOffset,zone),beforeAdjustedMillis=toDate(before2).getTime();if(adjustedMillis!==beforeAdjustedMillis)switch(disambiguation){case"reject":{let formatted=new Date(adjustedMillis).toISOString();throw RangeError(`Gap time: ${formatted} does not exist in time zone ${zone.id}`)}case"earlier":return makeZonedProto(adjustedMillis-afterOffset,zone);case"compatible":case"later":return before2}return before2}if(calculateNamedOffset(adjustedMillis-beforeOffset,adjustedMillis,zone)===beforeOffset){if(disambiguation==="earlier"||disambiguation==="compatible")return makeZonedProto(adjustedMillis-beforeOffset,zone);if(calculateNamedOffset(adjustedMillis-beforeOffset+transitionMillis,adjustedMillis+transitionMillis,zone)===beforeOffset)return makeZonedProto(adjustedMillis-beforeOffset,zone);if(disambiguation==="reject"){let formatted=new Date(adjustedMillis).toISOString();throw RangeError(`Ambiguous time: ${formatted} occurs twice in time zone ${zone.id}`)}}return makeZonedProto(adjustedMillis-afterOffset,zone)},offsetRegex=/([+-])(\d{2}):(\d{2})$/,parseOffset=(offset)=>{let match12=offsetRegex.exec(offset);if(match12===null)return null;let[,sign,hours2,minutes2]=match12;return(sign==="+"?1:-1)*(Number(hours2)*60+Number(minutes2))*60*1000},calculateNamedOffset=(utcMillis,adjustedMillis,zone)=>{let offset=zone.format.formatToParts(utcMillis).find((_)=>_.type==="timeZoneName")?.value??"";if(offset==="GMT")return 0;let result=parseOffset(offset);if(result===null)return zonedOffset(makeZonedProto(adjustedMillis,zone));return result},mutate4=dual(isDateTimeArgs,(self,f,options)=>{if(self._tag==="Utc"){let date=toDateUtc(self);return f(date),makeUtc(date.getTime())}let adjustedDate=toDate(self),newAdjustedDate=new Date(adjustedDate.getTime());return f(newAdjustedDate),makeZonedFromAdjusted(newAdjustedDate.getTime(),self.zone,options?.disambiguation??"compatible")});var withDate=dual(2,(self,f)=>f(toDate(self))),withDateUtc=dual(2,(self,f)=>f(toDateUtc(self)));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 isNonEmpty5=(self)=>self.length>0;var TypeId14=Symbol.for("effect/Cron"),CronProto={[TypeId14]:TypeId14,[symbol2](that){return isCron(that)&&equals3(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,TypeId14),make38=(values3)=>{let o=Object.create(CronProto);o.seconds=new Set(sort(values3.seconds??[0],Order2)),o.minutes=new Set(sort(values3.minutes,Order2)),o.hours=new Set(sort(values3.hours,Order2)),o.days=new Set(sort(values3.days,Order2)),o.months=new Set(sort(values3.months,Order2)),o.weekdays=new Set(sort(values3.weekdays,Order2)),o.tz=fromNullable(values3.tz);let seconds2=Array.from(o.seconds),minutes2=Array.from(o.minutes),hours2=Array.from(o.hours),days2=Array.from(o.days),months=Array.from(o.months),weekdays=Array.from(o.weekdays);return o.first={second:seconds2[0]??0,minute:minutes2[0]??0,hour:hours2[0]??0,day:days2[0]??1,month:(months[0]??1)-1,weekday:weekdays[0]??0},o.next={second:nextLookupTable(seconds2,60),minute:nextLookupTable(minutes2,60),hour:nextLookupTable(hours2,24),day:nextLookupTable(days2,32),month:nextLookupTable(months,13),weekday:nextLookupTable(weekdays,7)},o},nextLookupTable=(values3,size9)=>{let result=Array(size9).fill(void 0);if(values3.length===0)return result;let current=void 0,index=values3.length-1;for(let i=size9-1;i>=0;i--){while(index>=0&&values3[index]>=i)current=values3[index--];result[i]=current}return result},ParseErrorTypeId=Symbol.for("effect/Cron/errors/ParseError");class ParseError extends TaggedError("CronParseError"){[ParseErrorTypeId]=ParseErrorTypeId}var parse=(cron,tz)=>{let segments=cron.split(" ").filter(isNonEmpty5);if(segments.length!==5&&segments.length!==6)return left2(new ParseError({message:"Invalid number of segments in cron expression",input:cron}));if(segments.length===5)segments.unshift("0");let[seconds2,minutes2,hours2,days2,months,weekdays]=segments,zone=tz===void 0||isTimeZone(tz)?right2(tz):fromOption2(zoneFromString(tz),()=>new ParseError({message:"Invalid time zone in cron expression",input:tz}));return all({tz:zone,seconds:parseSegment(seconds2,secondOptions),minutes:parseSegment(minutes2,minuteOptions),hours:parseSegment(hours2,hourOptions),days:parseSegment(days2,dayOptions),months:parseSegment(months,monthOptions),weekdays:parseSegment(weekdays,weekdayOptions)}).pipe(map(make38))};var match12=(cron,date)=>{let parts2=unsafeMakeZoned(date,{timeZone:getOrUndefined(cron.tz)}).pipe(toParts);if(cron.seconds.size!==0&&!cron.seconds.has(parts2.seconds))return!1;if(cron.minutes.size!==0&&!cron.minutes.has(parts2.minutes))return!1;if(cron.hours.size!==0&&!cron.hours.has(parts2.hours))return!1;if(cron.months.size!==0&&!cron.months.has(parts2.month))return!1;if(cron.days.size===0&&cron.weekdays.size===0)return!0;if(cron.weekdays.size===0)return cron.days.has(parts2.day);if(cron.days.size===0)return cron.weekdays.has(parts2.weekDay);return cron.days.has(parts2.day)||cron.weekdays.has(parts2.weekDay)},daysInMonth=(date)=>new Date(Date.UTC(date.getUTCFullYear(),date.getUTCMonth()+1,0)).getUTCDate(),next2=(cron,startFrom)=>{let tz=getOrUndefined(cron.tz),zoned=unsafeMakeZoned(startFrom??new Date,{timeZone:tz}),adjustDst=tz!==void 0&&isTimeZoneNamed(tz)&&tz.id==="UTC"?constVoid:(current)=>{let adjusted=unsafeMakeZoned(current,{timeZone:zoned.zone,adjustForTimeZone:!0}).pipe(toDate),drift=current.getTime()-adjusted.getTime();if(drift>0)current.setTime(current.getTime()+drift)},result=mutate4(zoned,(current)=>{current.setUTCSeconds(current.getUTCSeconds()+1,0);for(let i=0;i<1e4;i++){if(cron.seconds.size!==0){let currentSecond=current.getUTCSeconds(),nextSecond=cron.next.second[currentSecond];if(nextSecond===void 0){current.setUTCMinutes(current.getUTCMinutes()+1,cron.first.second),adjustDst(current);continue}if(nextSecond>currentSecond){current.setUTCSeconds(nextSecond),adjustDst(current);continue}}if(cron.minutes.size!==0){let currentMinute=current.getUTCMinutes(),nextMinute=cron.next.minute[currentMinute];if(nextMinute===void 0){current.setUTCHours(current.getUTCHours()+1,cron.first.minute,cron.first.second),adjustDst(current);continue}if(nextMinute>currentMinute){current.setUTCMinutes(nextMinute,cron.first.second),adjustDst(current);continue}}if(cron.hours.size!==0){let currentHour=current.getUTCHours(),nextHour=cron.next.hour[currentHour];if(nextHour===void 0){current.setUTCDate(current.getUTCDate()+1),current.setUTCHours(cron.first.hour,cron.first.minute,cron.first.second),adjustDst(current);continue}if(nextHour>currentHour){current.setUTCHours(nextHour,cron.first.minute,cron.first.second),adjustDst(current);continue}}if(cron.weekdays.size!==0||cron.days.size!==0){let a=1/0,b=1/0;if(cron.weekdays.size!==0){let currentWeekday=current.getUTCDay(),nextWeekday=cron.next.weekday[currentWeekday];a=nextWeekday===void 0?7-currentWeekday+cron.first.weekday:nextWeekday-currentWeekday}if(cron.days.size!==0&&a!==0){let currentDay=current.getUTCDate(),nextDay=cron.next.day[currentDay];b=nextDay===void 0?daysInMonth(current)-currentDay+cron.first.day:nextDay-currentDay}let addDays=Math.min(a,b);if(addDays!==0){current.setUTCDate(current.getUTCDate()+addDays),current.setUTCHours(cron.first.hour,cron.first.minute,cron.first.second),adjustDst(current);continue}}if(cron.months.size!==0){let currentMonth=current.getUTCMonth()+1,nextMonth=cron.next.month[currentMonth];if(nextMonth===void 0){current.setUTCFullYear(current.getUTCFullYear()+1),current.setUTCMonth(cron.first.month,cron.first.day),current.setUTCHours(cron.first.hour,cron.first.minute,cron.first.second),adjustDst(current);continue}if(nextMonth>currentMonth){current.setUTCMonth(nextMonth-1,cron.first.day),current.setUTCHours(cron.first.hour,cron.first.minute,cron.first.second),adjustDst(current);continue}}return}throw Error("Unable to find next cron date")});return toDateUtc(result)};var Equivalence2=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)),equals3=dual(2,(self,that)=>Equivalence2(self,that)),secondOptions={min:0,max:59},minuteOptions={min:0,max:59},hourOptions={min:0,max:23},dayOptions={min:1,max:31},monthOptions={min:1,max:12,aliases:{jan:1,feb:2,mar:3,apr:4,may:5,jun:6,jul:7,aug:8,sep:9,oct:10,nov:11,dec:12}},weekdayOptions={min:0,max:6,aliases:{sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6}},parseSegment=(input,options)=>{let capacity=options.max-options.min+1,values3=new Set,fields=input.split(",");for(let field of fields){let[raw,step3]=splitStep(field);if(raw==="*"&&step3===void 0)return right2(new Set);if(step3!==void 0){if(!Number.isInteger(step3))return left2(new ParseError({message:"Expected step value to be a positive integer",input}));if(step3<1)return left2(new ParseError({message:"Expected step value to be greater than 0",input}));if(step3>options.max)return left2(new ParseError({message:`Expected step value to be less than ${options.max}`,input}))}if(raw==="*")for(let i=options.min;i<=options.max;i+=step3??1)values3.add(i);else{let[left3,right3]=splitRange(raw,options.aliases);if(!Number.isInteger(left3))return left2(new ParseError({message:"Expected a positive integer",input}));if(left3<options.min||left3>options.max)return left2(new ParseError({message:`Expected a value between ${options.min} and ${options.max}`,input}));if(right3===void 0)values3.add(left3);else{if(!Number.isInteger(right3))return left2(new ParseError({message:"Expected a positive integer",input}));if(right3<options.min||right3>options.max)return left2(new ParseError({message:`Expected a value between ${options.min} and ${options.max}`,input}));if(left3>right3)return left2(new ParseError({message:"Invalid value range",input}));for(let i=left3;i<=right3;i+=step3??1)values3.add(i)}}if(values3.size>=capacity)return right2(new Set)}return right2(values3)},splitStep=(input)=>{let seperator=input.indexOf("/");if(seperator!==-1)return[input.slice(0,seperator),Number(input.slice(seperator+1))];return[input,void 0]},splitRange=(input,aliases)=>{let seperator=input.indexOf("-");if(seperator!==-1)return[aliasOrValue(input.slice(0,seperator),aliases),aliasOrValue(input.slice(seperator+1),aliases)];return[aliasOrValue(input,aliases),void 0]};function aliasOrValue(field,aliases){return aliases?.[field.toLocaleLowerCase()]??Number(field)}var next3=next;var fixed2=fixed;var ScheduleSymbolKey="effect/Schedule",ScheduleTypeId=Symbol.for(ScheduleSymbolKey),isSchedule=(u)=>hasProperty(u,ScheduleTypeId),ScheduleDriverSymbolKey="effect/ScheduleDriver",ScheduleDriverTypeId=Symbol.for(ScheduleDriverSymbolKey),defaultIterationMetadata={start:0,now:0,input:void 0,output:void 0,elapsed:zero,elapsedSincePrevious:zero,recurrence:0},CurrentIterationMetadata=Reference2()("effect/Schedule/CurrentIterationMetadata",{defaultValue:()=>defaultIterationMetadata}),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)}}var updateInfo=(iterationMetaRef,now,input,output)=>update2(iterationMetaRef,(prev)=>prev.recurrence===0?{now,input,output,recurrence:prev.recurrence+1,elapsed:zero,elapsedSincePrevious:zero,start:now}:{now,input,output,recurrence:prev.recurrence+1,elapsed:millis(now-prev.start),elapsedSincePrevious:millis(now-prev.now),start:prev.start});class ScheduleDriverImpl{schedule;ref;[ScheduleDriverTypeId]=scheduleDriverVariance;constructor(schedule,ref){this.schedule=schedule,this.ref=ref}get state(){return map10(get10(this.ref),(tuple2)=>tuple2[1])}get last(){return flatMap8(get10(this.ref),([element,_])=>{switch(element._tag){case"None":return failSync(()=>new NoSuchElementException);case"Some":return succeed(element.value)}})}iterationMeta=unsafeMake5(defaultIterationMetadata);get reset(){return set4(this.ref,[none2(),this.schedule.initial]).pipe(zipLeft(set4(this.iterationMeta,defaultIterationMetadata)))}next(input){return pipe(map10(get10(this.ref),(tuple2)=>tuple2[1]),flatMap8((state)=>pipe(currentTimeMillis2,flatMap8((now)=>pipe(suspend(()=>this.schedule.step(now,input,state)),flatMap8(([state2,out,decision])=>{let setState=set4(this.ref,[some2(out),state2]);if(isDone4(decision))return setState.pipe(zipRight(fail2(none2())));let millis2=start2(decision.intervals)-now;if(millis2<=0)return setState.pipe(zipRight(updateInfo(this.iterationMeta,now,input,out)),as(out));let duration=millis(millis2);return pipe(setState,zipRight(updateInfo(this.iterationMeta,now,input,out)),zipRight(sleep3(duration)),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))))),andThen4=dual(2,(self,that)=>map15(andThenEither(self,that),merge)),andThenEither=dual(2,(self,that)=>makeWithState([self.initial,that.initial,!0],(now,input,state)=>state[2]?flatMap8(self.step(now,input,state[0]),([lState,out,decision])=>{if(isDone4(decision))return map10(that.step(now,input,state[1]),([rState,out2,decision2])=>[[lState,rState,!1],right2(out2),decision2]);return succeed([[lState,state[1],!0],left2(out),decision])}):map10(that.step(now,input,state[1]),([rState,out,decision])=>[[state[0],rState,!1],right2(out),decision]))),as3=dual(2,(self,out)=>map15(self,()=>out)),asVoid2=(self)=>map15(self,constVoid),bothInOut=dual(2,(self,that)=>makeWithState([self.initial,that.initial],(now,[in1,in2],state)=>zipWith3(self.step(now,in1,state[0]),that.step(now,in2,state[1]),([lState,out,lDecision],[rState,out2,rDecision])=>{if(isContinue2(lDecision)&&isContinue2(rDecision)){let interval=pipe(lDecision.intervals,union7(rDecision.intervals));return[[lState,rState],[out,out2],_continue2(interval)]}return[[lState,rState],[out,out2],done5]}))),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(isDone4(decision))return succeed([state2,out,done5]);return map10(test(input,out),(cont)=>cont?[state2,out,decision]:[state2,out,done5])}))),collectAllInputs=()=>collectAllOutputs(identity2()),collectAllOutputs=(self)=>reduce10(self,empty2(),(outs,out)=>pipe(outs,append2(out))),collectUntil=(f)=>collectAllOutputs(recurUntil(f)),collectUntilEffect=(f)=>collectAllOutputs(recurUntilEffect(f)),collectWhile=(f)=>collectAllOutputs(recurWhile(f)),collectWhileEffect=(f)=>collectAllOutputs(recurWhileEffect(f)),compose=dual(2,(self,that)=>makeWithState([self.initial,that.initial],(now,input,state)=>flatMap8(self.step(now,input,state[0]),([lState,out,lDecision])=>map10(that.step(now,out,state[1]),([rState,out2,rDecision])=>isDone4(lDecision)?[[lState,rState],out2,done5]:isDone4(rDecision)?[[lState,rState],out2,done5]:[[lState,rState],out2,_continue2(pipe(lDecision.intervals,max5(rDecision.intervals)))])))),mapInput3=dual(2,(self,f)=>mapInputEffect(self,(input2)=>sync(()=>f(input2)))),mapInputContext2=dual(2,(self,f)=>makeWithState(self.initial,(now,input,state)=>mapInputContext(self.step(now,input,state),f))),mapInputEffect=dual(2,(self,f)=>makeWithState(self.initial,(now,input2,state)=>flatMap8(f(input2),(input)=>self.step(now,input,state)))),cron=(expression,tz)=>{let parsed=isCron(expression)?right2(expression):parse(expression,tz);return makeWithState([!0,[Number.MIN_SAFE_INTEGER,0,0]],(now,_,[initial,previous])=>{if(now<previous[0])return succeed([[!1,previous],[previous[1],previous[2]],continueWith2(make33(previous[1],previous[2]))]);if(isLeft2(parsed))return die2(parsed.left);let cron2=parsed.right,date=new Date(now),next4;if(initial&&match12(cron2,date))next4=now;next4=next2(cron2,date).getTime();let start3=beginningOfSecond(next4),end3=endOfSecond(next4);return succeed([[!1,[next4,start3,end3]],[start3,end3],continueWith2(make33(start3,end3))])})},dayOfMonth=(day)=>{return makeWithState([Number.NEGATIVE_INFINITY,0],(now,_,state)=>{if(!Number.isInteger(day)||day<1||31<day)return dieSync(()=>new IllegalArgumentException(`Invalid argument in: dayOfMonth(${day}). Must be in range 1...31`));let n=state[1],day0=nextDayOfMonth(now,day,n===0),start3=beginningOfDay(day0),end3=endOfDay(day0),interval=make33(start3,end3);return succeed([[end3,n+1],n,continueWith2(interval)])})},dayOfWeek=(day)=>{return makeWithState([Number.MIN_SAFE_INTEGER,0],(now,_,state)=>{if(!Number.isInteger(day)||day<1||7<day)return dieSync(()=>new IllegalArgumentException(`Invalid argument in: dayOfWeek(${day}). Must be in range 1 (Monday)...7 (Sunday)`));let n=state[1],day0=nextDay(now,day,n===0),start3=beginningOfDay(day0),end3=endOfDay(day0),interval=make33(start3,end3);return succeed([[end3,n+1],n,continueWith2(interval)])})},delayed=dual(2,(self,f)=>delayedEffect(self,(duration)=>sync(()=>f(duration)))),delayedEffect=dual(2,(self,f)=>modifyDelayEffect(self,(_,delay2)=>f(delay2))),delayedSchedule=(schedule)=>addDelay(schedule,(x)=>x),delays=(self)=>makeWithState(self.initial,(now,input,state)=>pipe(self.step(now,input,state),flatMap8(([state2,_,decision])=>{if(isDone4(decision))return succeed([state2,zero,decision]);return succeed([state2,millis(start2(decision.intervals)-now),decision])}))),mapBoth3=dual(2,(self,{onInput,onOutput})=>map15(mapInput3(self,onInput),onOutput)),mapBothEffect=dual(2,(self,{onInput,onOutput})=>mapEffect2(mapInputEffect(self,onInput),onOutput)),driver=(self)=>pipe(make23([none2(),self.initial]),map10((ref)=>new ScheduleDriverImpl(self,ref))),duration=(durationInput)=>{let duration2=decode(durationInput),durationMillis=toMillis(duration2);return makeWithState(!0,(now,_,state)=>succeed(state?[!1,duration2,continueWith2(after2(now+durationMillis))]:[!1,zero,done5]))},either3=dual(2,(self,that)=>union8(self,that)),eitherWith=dual(3,(self,that,f)=>unionWith2(self,that,f)),ensuring2=dual(2,(self,finalizer)=>makeWithState(self.initial,(now,input,state)=>flatMap8(self.step(now,input,state),([state2,out,decision])=>isDone4(decision)?as(finalizer,[state2,out,decision]):succeed([state2,out,decision])))),exponential2=(baseInput,factor=2)=>{let base=decode(baseInput);return delayedSchedule(map15(forever2,(i)=>times(base,Math.pow(factor,i))))},fibonacci=(oneInput)=>{let one=decode(oneInput);return delayedSchedule(pipe(unfold2([one,one],([a,b])=>[b,sum(a,b)]),map15((out)=>out[0])))},fixed3=(intervalInput)=>{let interval=decode(intervalInput),intervalMillis=toMillis(interval);return makeWithState([none2(),0],(now,_,[option2,n])=>sync(()=>{switch(option2._tag){case"None":return[[some2([now,now+intervalMillis]),n+1],n,continueWith2(after2(now+intervalMillis))];case"Some":{let[startMillis,lastRun]=option2.value,runningBehind=now>lastRun+intervalMillis,boundary=equals(interval,zero)?interval:millis(intervalMillis-(now-startMillis)%intervalMillis),sleepTime=equals(boundary,zero)?interval:boundary,nextRun=runningBehind?now:now+toMillis(sleepTime);return[[some2([startMillis,nextRun]),n+1],n,continueWith2(after2(nextRun))]}}}))},fromDelay=(delay2)=>duration(delay2),fromDelays=(delay2,...delays2)=>makeWithState([[delay2,...delays2].map((_)=>decode(_)),!0],(now,_,[durations,cont])=>sync(()=>{if(cont){let x=durations[0],interval=after2(now+toMillis(x));if(durations.length>=2)return[[durations.slice(1),!0],x,continueWith2(interval)];let y=durations.slice(1);return[[[x,...y],!1],x,continueWith2(interval)]}return[[durations,!1],zero,done5]})),fromFunction2=(f)=>map15(identity2(),f),hourOfDay=(hour)=>makeWithState([Number.NEGATIVE_INFINITY,0],(now,_,state)=>{if(!Number.isInteger(hour)||hour<0||23<hour)return dieSync(()=>new IllegalArgumentException(`Invalid argument in: hourOfDay(${hour}). Must be in range 0...23`));let n=state[1],hour0=nextHour(now,hour,n===0),start3=beginningOfHour(hour0),end3=endOfHour(hour0),interval=make33(start3,end3);return succeed([[end3,n+1],n,continueWith2(interval)])}),identity2=()=>makeWithState(void 0,(now,input,state)=>succeed([state,input,continueWith2(after2(now))])),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],done5])})))),intersectWithLoop=(self,that,input,lState,out,lInterval,rState,out2,rInterval,f)=>{let combined=f(lInterval,rInterval);if(isNonEmpty4(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(isDone4(decision))return succeed([[lState2,rState],[out3,out2],done5]);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(isDone4(decision))return succeed([[lState,rState2],[out,out22],done5]);return intersectWithLoop(self,that,input,lState,out,lInterval,rState2,out22,decision.intervals,f)})},jittered=(self)=>jitteredWith(self,{min:0.8,max:1.2}),jitteredWith=dual(2,(self,options)=>{let{max:max6,min:min4}=Object.assign({min:0.8,max:1.2},options);return delayedEffect(self,(duration2)=>map10(next3,(random3)=>{let d=toMillis(duration2),jittered2=d*min4*(1-random3)+d*max6*random3;return millis(jittered2)}))}),linear=(baseInput)=>{let base=decode(baseInput);return delayedSchedule(map15(forever2,(i)=>times(base,i+1)))},map15=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])))),minuteOfHour=(minute)=>makeWithState([Number.MIN_SAFE_INTEGER,0],(now,_,state)=>{if(!Number.isInteger(minute)||minute<0||59<minute)return dieSync(()=>new IllegalArgumentException(`Invalid argument in: minuteOfHour(${minute}). Must be in range 0...59`));let n=state[1],minute0=nextMinute(now,minute,n===0),start3=beginningOfMinute(minute0),end3=endOfMinute(minute0),interval=make33(start3,end3);return succeed([[end3,n+1],n,continueWith2(interval)])}),modifyDelay=dual(2,(self,f)=>modifyDelayEffect(self,(out,duration2)=>sync(()=>f(out,duration2)))),modifyDelayEffect=dual(2,(self,f)=>makeWithState(self.initial,(now,input,state)=>flatMap8(self.step(now,input,state),([state2,out,decision])=>{if(isDone4(decision))return succeed([state2,out,decision]);let intervals=decision.intervals,delay2=size8(make33(now,start2(intervals)));return map10(f(out,delay2),(durationInput)=>{let duration2=decode(durationInput),oldStart=start2(intervals),newStart=now+toMillis(duration2),delta=newStart-oldStart,newEnd=Math.max(0,end2(intervals)+delta),newInterval=make33(newStart,newEnd);return[state2,out,continueWith2(newInterval)]})}))),onDecision=dual(2,(self,f)=>makeWithState(self.initial,(now,input,state)=>flatMap8(self.step(now,input,state),([state2,out,decision])=>as(f(out,decision),[state2,out,decision])))),passthrough2=(self)=>makeWithState(self.initial,(now,input,state)=>pipe(self.step(now,input,state),map10(([state2,_,decision])=>[state2,input,decision]))),provideContext3=dual(2,(self,context3)=>makeWithState(self.initial,(now,input,state)=>provideContext(self.step(now,input,state),context3))),provideService2=dual(3,(self,tag,service2)=>makeWithState(self.initial,(now,input,state)=>contextWithEffect((env)=>provideContext(self.step(now,input,state),add4(env,tag,service2))))),recurUntil=(f)=>untilInput(identity2(),f),recurUntilEffect=(f)=>untilInputEffect(identity2(),f),recurUntilOption=(pf)=>untilOutput(map15(identity2(),pf),isSome2),recurUpTo=(durationInput)=>{let duration2=decode(durationInput);return whileOutput(elapsed,(elapsed)=>lessThan2(elapsed,duration2))},recurWhile=(f)=>whileInput(identity2(),f),recurWhileEffect=(f)=>whileInputEffect(identity2(),f),recurs=(n)=>whileOutput(forever2,(out)=>out<n),reduce10=dual(3,(self,zero2,f)=>reduceEffect2(self,zero2,(z,out)=>sync(()=>f(z,out)))),reduceEffect2=dual(3,(self,zero2,f)=>makeWithState([self.initial,zero2],(now,input,[s,z])=>flatMap8(self.step(now,input,s),([s2,out,decision])=>isDone4(decision)?succeed([[s2,z],z,decision]):map10(f(z,out),(z2)=>[[s2,z2],z,decision]))));var repetitions=(self)=>reduce10(self,0,(n,_)=>n+1),resetAfter=dual(2,(self,durationInput)=>{let duration2=decode(durationInput);return pipe(self,intersect5(elapsed),resetWhen(([,time2])=>greaterThanOrEqualTo(time2,duration2)),map15((out)=>out[0]))}),resetWhen=dual(2,(self,f)=>makeWithState(self.initial,(now,input,state)=>flatMap8(self.step(now,input,state),([state2,out,decision])=>f(out)?self.step(now,input,self.initial):succeed([state2,out,decision])))),run=dual(3,(self,now,input)=>pipe(runLoop(self,now,fromIterable2(input),self.initial,empty2()),map10((list)=>reverse2(list)))),runLoop=(self,now,inputs,state,acc)=>{if(!isNonEmpty(inputs))return succeed(acc);let input=headNonEmpty2(inputs),nextInputs=tailNonEmpty2(inputs);return flatMap8(self.step(now,input,state),([state2,out,decision])=>{if(isDone4(decision))return sync(()=>pipe(acc,prepend2(out)));return runLoop(self,start2(decision.intervals),nextInputs,state2,prepend2(acc,out))})},secondOfMinute=(second)=>makeWithState([Number.NEGATIVE_INFINITY,0],(now,_,state)=>{if(!Number.isInteger(second)||second<0||59<second)return dieSync(()=>new IllegalArgumentException(`Invalid argument in: secondOfMinute(${second}). Must be in range 0...59`));let n=state[1],second0=nextSecond(now,second,n===0),start3=beginningOfSecond(second0),end3=endOfSecond(second0),interval=make33(start3,end3);return succeed([[end3,n+1],n,continueWith2(interval)])}),spaced=(duration2)=>addDelay(forever2,()=>duration2),succeed6=(value)=>map15(forever2,()=>value),sync3=(evaluate2)=>map15(forever2,evaluate2),tapInput=dual(2,(self,f)=>makeWithState(self.initial,(now,input,state)=>zipRight(f(input),self.step(now,input,state)))),tapOutput=dual(2,(self,f)=>makeWithState(self.initial,(now,input,state)=>tap(self.step(now,input,state),([,out])=>f(out)))),unfold2=(initial,f)=>makeWithState(initial,(now,_,state)=>sync(()=>[f(state),state,continueWith2(after2(now))])),union8=dual(2,(self,that)=>unionWith2(self,that,union7)),unionWith2=dual(3,(self,that,f)=>makeWithState([self.initial,that.initial],(now,input,state)=>zipWith3(self.step(now,input,state[0]),that.step(now,input,state[1]),([lState,l,lDecision],[rState,r,rDecision])=>{if(isDone4(lDecision)&&isDone4(rDecision))return[[lState,rState],[l,r],done5];if(isDone4(lDecision)&&isContinue2(rDecision))return[[lState,rState],[l,r],_continue2(rDecision.intervals)];if(isContinue2(lDecision)&&isDone4(rDecision))return[[lState,rState],[l,r],_continue2(lDecision.intervals)];if(isContinue2(lDecision)&&isContinue2(rDecision)){let combined=f(lDecision.intervals,rDecision.intervals);return[[lState,rState],[l,r],_continue2(combined)]}throw Error("BUG: Schedule.unionWith - please report an issue at https://github.com/Effect-TS/effect/issues")}))),untilInput=dual(2,(self,f)=>check(self,(input,_)=>!f(input))),untilInputEffect=dual(2,(self,f)=>checkEffect(self,(input,_)=>negate(f(input)))),untilOutput=dual(2,(self,f)=>check(self,(_,out)=>!f(out))),untilOutputEffect=dual(2,(self,f)=>checkEffect(self,(_,out)=>negate(f(out)))),upTo=dual(2,(self,duration2)=>zipLeft2(self,recurUpTo(duration2))),whileInput=dual(2,(self,f)=>check(self,(input,_)=>f(input))),whileInputEffect=dual(2,(self,f)=>checkEffect(self,(input,_)=>f(input))),whileOutput=dual(2,(self,f)=>check(self,(_,out)=>f(out))),whileOutputEffect=dual(2,(self,f)=>checkEffect(self,(_,out)=>f(out))),windowed=(intervalInput)=>{let interval=decode(intervalInput),millis2=toMillis(interval);return makeWithState([none2(),0],(now,_,[option2,n])=>{switch(option2._tag){case"None":return succeed([[some2(now),n+1],n,continueWith2(after2(now+millis2))]);case"Some":return succeed([[some2(option2.value),n+1],n,continueWith2(after2(now+(millis2-(now-option2.value)%millis2)))])}})},zipLeft2=dual(2,(self,that)=>map15(intersect5(self,that),(out)=>out[0])),zipRight3=dual(2,(self,that)=>map15(intersect5(self,that),(out)=>out[1])),zipWith5=dual(3,(self,that,f)=>map15(intersect5(self,that),([out,out2])=>f(out,out2))),beginningOfSecond=(now)=>{let date=new Date(now);return new Date(date.getFullYear(),date.getMonth(),date.getDate(),date.getHours(),date.getMinutes(),date.getSeconds(),0).getTime()},endOfSecond=(now)=>{let date=new Date(beginningOfSecond(now));return date.setSeconds(date.getSeconds()+1)},nextSecond=(now,second,initial)=>{let date=new Date(now);if(date.getSeconds()===second&&initial)return now;if(date.getSeconds()<second)return date.setSeconds(second);let newDate=new Date(date.setSeconds(second));return newDate.setTime(newDate.getTime()+60000)},beginningOfMinute=(now)=>{let date=new Date(now);return new Date(date.getFullYear(),date.getMonth(),date.getDate(),date.getHours(),date.getMinutes(),0,0).getTime()},endOfMinute=(now)=>{let date=new Date(beginningOfMinute(now));return date.setMinutes(date.getMinutes()+1)},nextMinute=(now,minute,initial)=>{let date=new Date(now);if(date.getMinutes()===minute&&initial)return now;if(date.getMinutes()<minute)return date.setMinutes(minute);let newDate=new Date(date.setMinutes(minute));return newDate.setTime(newDate.getTime()+3600000)},beginningOfHour=(now)=>{let date=new Date(now);return new Date(date.getFullYear(),date.getMonth(),date.getDate(),date.getHours(),0,0,0).getTime()},endOfHour=(now)=>{let date=new Date(beginningOfHour(now));return date.setHours(date.getHours()+1)},nextHour=(now,hour,initial)=>{let date=new Date(now);if(date.getHours()===hour&&initial)return now;if(date.getHours()<hour)return date.setHours(hour);let newDate=new Date(date.setHours(hour));return newDate.setTime(newDate.getTime()+86400000)},beginningOfDay=(now)=>{let date=new Date(now);return new Date(date.getFullYear(),date.getMonth(),date.getDate(),0,0,0,0).getTime()},endOfDay=(now)=>{let date=new Date(beginningOfDay(now));return date.setDate(date.getDate()+1)},nextDay=(now,dayOfWeek2,initial)=>{let date=new Date(now);if(date.getDay()===dayOfWeek2&&initial)return now;let nextDayOfWeek=(7+dayOfWeek2-date.getDay())%7;return date.setDate(date.getDate()+(nextDayOfWeek===0?7:nextDayOfWeek))},nextDayOfMonth=(now,day,initial)=>{let date=new Date(now);if(date.getDate()===day&&initial)return now;if(date.getDate()<day)return date.setDate(day);return findNextMonth(now,day,1)},findNextMonth=(now,day,months)=>{let d=new Date(now),tmp1=new Date(d.setDate(day));if(new Date(tmp1.setMonth(tmp1.getMonth()+months)).getDate()===day){let d2=new Date(now),tmp3=new Date(d2.setDate(day));return tmp3.setMonth(tmp3.getMonth()+months)}return findNextMonth(now,day,months+1)},ScheduleDefectTypeId=Symbol.for("effect/Schedule/ScheduleDefect");class ScheduleDefect{error;[ScheduleDefectTypeId];constructor(error2){this.error=error2,this[ScheduleDefectTypeId]=ScheduleDefectTypeId}}var isScheduleDefect=(u)=>hasProperty(u,ScheduleDefectTypeId),scheduleDefectWrap=(self)=>catchAll(self,(e)=>die2(new ScheduleDefect(e))),scheduleDefectRefailCause=(cause2)=>match2(find(cause2,(_)=>isDieType(_)&&isScheduleDefect(_.defect)?some2(_.defect):none2()),{onNone:()=>cause2,onSome:(error2)=>fail(error2.error)}),scheduleDefectRefail=(effect)=>catchAllCause(effect,(cause2)=>failCause(scheduleDefectRefailCause(cause2))),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??passthrough2(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(map15((intersectionPair)=>intersectionPair[0])):withUntil;return scheduleDefectRefail(repeat_Effect(self,withTimes))}),repeatOrElse_Effect=dual(3,(self,schedule,orElse5)=>flatMap8(driver(schedule),(driver2)=>matchEffect(self,{onFailure:(error2)=>orElse5(error2,none2()),onSuccess:(value)=>repeatOrElseEffectLoop(provideServiceEffect(self,CurrentIterationMetadata,get10(driver2.iterationMeta)),driver2,(error2,option2)=>provideServiceEffect(orElse5(error2,option2),CurrentIterationMetadata,get10(driver2.iterationMeta)),value)}))),repeatOrElseEffectLoop=(self,driver2,orElse5,value)=>matchEffect(driver2.next(value),{onFailure:()=>orDie(driver2.last),onSuccess:(b)=>matchEffect(self,{onFailure:(error2)=>orElse5(error2,some2(b)),onSuccess:(value2)=>repeatOrElseEffectLoop(self,driver2,orElse5,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);return scheduleDefectRefail(retry_Effect(self,fromRetryOptions(options)))}),fromRetryOptions=(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;return options.times?intersect5(withUntil,recurs(options.times)):withUntil},retryOrElse_Effect=dual(3,(self,policy,orElse5)=>flatMap8(driver(policy),(driver2)=>retryOrElse_EffectLoop(provideServiceEffect(self,CurrentIterationMetadata,get10(driver2.iterationMeta)),driver2,(e,out)=>provideServiceEffect(orElse5(e,out),CurrentIterationMetadata,get10(driver2.iterationMeta))))),retryOrElse_EffectLoop=(self,driver2,orElse5)=>{return catchAll(self,(e)=>matchEffect(driver2.next(e),{onFailure:()=>pipe(driver2.last,orDie,flatMap8((out)=>orElse5(e,out))),onSuccess:()=>retryOrElse_EffectLoop(self,driver2,orElse5)}))},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(provideServiceEffect(self,CurrentIterationMetadata,get10(driver2.iterationMeta)),initial,driver2))),scheduleFrom_EffectLoop=(self,initial,driver2)=>matchEffect(driver2.next(initial),{onFailure:()=>orDie(driver2.last),onSuccess:()=>flatMap8(self,(a)=>scheduleFrom_EffectLoop(self,a,driver2))}),count2=unfold2(0,(n)=>n+1),elapsed=makeWithState(none2(),(now,_,state)=>{switch(state._tag){case"None":return succeed([some2(now),zero,continueWith2(after2(now))]);case"Some":return succeed([some2(state.value),millis(now-state.value),continueWith2(after2(now))])}}),forever2=unfold2(0,(n)=>n+1),once2=asVoid2(recurs(1)),stop=asVoid2(recurs(0)),scheduleForked=dual(2,(self,schedule)=>forkScoped(schedule_Effect(self,schedule)));var withExecutionPlan=dual(2,(effect,plan)=>suspend(()=>{let i=0,result;return flatMap8(whileLoop({while:()=>i<plan.steps.length&&(result===void 0||isLeft2(result)),body:()=>{let step3=plan.steps[i],nextEffect=effect_provide(effect,step3.provide);if(result){let attempted=!1,wrapped=nextEffect;nextEffect=suspend(()=>{if(attempted)return wrapped;return attempted=!0,result}),nextEffect=scheduleDefectRefail(retry_Effect(nextEffect,scheduleFromStep(step3,!1)))}else{let schedule=scheduleFromStep(step3,!0);nextEffect=schedule?scheduleDefectRefail(retry_Effect(nextEffect,schedule)):nextEffect}return either2(nextEffect)},step:(either4)=>{result=either4,i++}}),()=>result)})),scheduleFromStep=(step3,first)=>{if(!first)return fromRetryOptions({schedule:step3.schedule?step3.schedule:step3.attempts?void 0:once2,times:step3.attempts,while:step3.while});else if(step3.attempts===1||!(step3.schedule||step3.attempts))return;return fromRetryOptions({schedule:step3.schedule,while:step3.while,times:step3.attempts?step3.attempts-1:void 0})};var make39=deferredMake;var _await3=deferredAwait;var done7=deferredDone,fail7=deferredFail;var failCause6=deferredFailCause;var interrupt6=deferredInterrupt;var isDone5=deferredIsDone,poll3=deferredPoll,succeed7=deferredSucceed;var unsafeMake9=deferredUnsafeMake,unsafeDone=deferredUnsafeDone;var TypeId15=Symbol.for("effect/MutableList"),MutableListProto={[TypeId15]:TypeId15,[Symbol.iterator](){let done8=!1,head4=this.head;return{next(){if(done8)return this.return();if(head4==null)return done8=!0,this.return();let value=head4.value;return head4=head4.next,{done:done8,value}},return(value){if(!done8)done8=!0;return{done:!0,value}}}},toString(){return format(this.toJSON())},toJSON(){return{_id:"MutableList",values:Array.from(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}},makeNode=(value)=>({value,removed:!1,prev:void 0,next:void 0}),empty27=()=>{let list=Object.create(MutableListProto);return list.head=void 0,list.tail=void 0,list._length=0,list};var isEmpty8=(self)=>length(self)===0,length=(self)=>self._length;var append3=dual(2,(self,value)=>{let node=makeNode(value);if(self.head===void 0)self.head=node;if(self.tail===void 0)self.tail=node;else self.tail.next=node,node.prev=self.tail,self.tail=node;return self._length+=1,self}),shift=(self)=>{let head4=self.head;if(head4!==void 0)return remove6(self,head4),head4.value;return};var remove6=(self,node)=>{if(node.removed)return;if(node.removed=!0,node.prev!==void 0&&node.next!==void 0)node.prev.next=node.next,node.next.prev=node.prev;else if(node.prev!==void 0)self.tail=node.prev,node.prev.next=void 0;else if(node.next!==void 0)self.head=node.next,node.next.prev=void 0;else self.tail=void 0,self.head=void 0;if(self._length>0)self._length-=1};var TypeId16=Symbol.for("effect/MutableQueue"),EmptyMutableQueue=Symbol.for("effect/mutable/MutableQueue/Empty"),MutableQueueProto={[TypeId16]:TypeId16,[Symbol.iterator](){return Array.from(this.queue)[Symbol.iterator]()},toString(){return format(this.toJSON())},toJSON(){return{_id:"MutableQueue",values:Array.from(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}},make40=(capacity)=>{let queue=Object.create(MutableQueueProto);return queue.queue=empty27(),queue.capacity=capacity,queue},bounded=(capacity)=>make40(capacity),unbounded=()=>make40(void 0),length2=(self)=>length(self.queue),isEmpty9=(self)=>isEmpty8(self.queue);var capacity=(self)=>self.capacity===void 0?1/0:self.capacity,offer=dual(2,(self,value)=>{let queueLength=length(self.queue);if(self.capacity!==void 0&&queueLength===self.capacity)return!1;return append3(value)(self.queue),!0}),offerAll=dual(2,(self,values3)=>{let iterator=values3[Symbol.iterator](),next4,remainder=empty2(),offering=!0;while(offering&&(next4=iterator.next())&&!next4.done)offering=offer(next4.value)(self);while(next4!=null&&!next4.done)remainder=prepend2(next4.value)(remainder),next4=iterator.next();return reverse2(remainder)}),poll4=dual(2,(self,def)=>{if(isEmpty8(self.queue))return def;return shift(self.queue)}),pollUpTo=dual(2,(self,n)=>{let result=empty2(),count3=0;while(count3<n){let element=poll4(EmptyMutableQueue)(self);if(element===EmptyMutableQueue)break;result=prepend2(element)(result),count3+=1}return reverse2(result)});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:next4}=key;if(next4!==void 0)if(key.next=void 0,previous!==void 0)previous.next=next4,next4.previous=previous;else this.head=next4,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 next4=key.next;if(next4!==void 0)key.next=void 0,this.head=next4,this.head.previous=void 0;else this.head=void 0,this.tail=void 0}return key}}var makeKeySet=()=>new KeySetImpl,makeCacheState=(map16,keys3,accesses,updating,hits,misses)=>({map:map16,keys:keys3,accesses,updating,hits,misses}),initialCacheState=()=>makeCacheState(empty21(),makeKeySet(),unbounded(),make11(!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,context3,fiberId2,lookup,timeToLive){this.capacity=capacity2,this.context=context3,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:size6(this.cacheState.map)}))}getOption(key){return suspend(()=>match2(get12(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(get12(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=get12(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(get12(this.cacheState.map,k));if(value===void 0)if(deferred=unsafeMake9(this.fiberId),mapKey=makeMapKey(k),has4(this.cacheState.map,k))value=getOrUndefined(get12(this.cacheState.map,k));else set6(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(()=>{remove5(this.cacheState.map,key)})}invalidateWhen(key,when2){return sync(()=>{let value=get12(this.cacheState.map,key);if(isSome2(value)&&value.value._tag==="Complete"){if(value.value.exit._tag==="Success"){if(when2(value.value.exit.value))remove5(this.cacheState.map,key)}}})}get invalidateAll(){return sync(()=>{this.cacheState.map=empty21()})}refresh(key){return clockWith3((clock2)=>suspend(()=>{let k=key,deferred=unsafeMake9(this.fiberId),value=getOrUndefined(get12(this.cacheState.map,k));if(value===void 0)if(has4(this.cacheState.map,k))value=getOrUndefined(get12(this.cacheState.map,k));else set6(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(get12(this.cacheState.map,k));if(equals(found,value))remove5(this.cacheState.map,k);return asVoid(this.get(key))}return pipe(this.lookupValueOf(key,deferred),when(()=>{let current=getOrUndefined(get12(this.cacheState.map,k));if(equals(current,value)){let mapValue=refreshing(deferred,value);return set6(this.cacheState.map,k,mapValue),!0}return!1}),asVoid)}case"Pending":return _await3(value.deferred);case"Refreshing":return _await3(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))));set6(this.cacheState.map,k,mapValue)}))}get size(){return sync(()=>{return size6(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 keys3=[];for(let entry of this.cacheState.map)if(entry[1]._tag==="Complete"&&entry[1].exit._tag==="Success")keys3.push(entry[0]);return keys3})}resolveMapValue(value,ignorePending=!1){return clockWith3((clock2)=>{switch(value._tag){case"Complete":{if(this.trackAccess(value.key),this.hasExpired(clock2,value.timeToLiveMillis))return remove5(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(_await3(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(_await3(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=poll4(this.cacheState.accesses,EmptyMutableQueue);if(key2===EmptyMutableQueue)loop2=!1;else this.cacheState.keys.add(key2)}let size9=size6(this.cacheState.map);loop2=size9>this.capacity;while(loop2){let key2=this.cacheState.keys.remove();if(key2!==void 0){if(has4(this.cacheState.map,key2.current))remove5(this.cacheState.map,key2.current),size9=size9-1,loop2=size9>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 set6(this.cacheState.map,key,value),zipRight(done7(deferred,exit2),exit2)}),onInterrupt(()=>zipRight(interrupt6(deferred),sync(()=>{remove5(this.cacheState.map,key)}))))}))}}var unsafeMakeWith=(capacity2,lookup,timeToLive)=>new CacheImpl(capacity2,empty8(),none3,lookup,(exit2)=>decode(timeToLive(exit2)));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((id2)=>{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(empty16,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:id2,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:id2,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,once3=once,all5=all4,allWith2=allWith,allSuccesses2=allSuccesses,dropUntil2=dropUntil,dropWhile3=dropWhile2,takeUntil2=takeUntil,takeWhile3=takeWhile2,every6=every5,exists2=exists,filter7=filter6,filterMap5=filterMap4,findFirst6=findFirst5,forEach6=forEach5,head4=head3,mergeAll5=mergeAll3,partition4=partition3,reduce11=reduce9,reduceWhile2=reduceWhile,reduceRight4=reduceRight3,reduceEffect3=reduceEffect,replicate2=replicate,replicateEffect2=replicateEffect,validateAll2=validateAll,validateFirst2=validateFirst,async=async_,asyncEffect2=asyncEffect,custom2=custom,withFiberRuntime2=withFiberRuntime,fail9=fail2,failSync3=failSync,failCause8=failCause,failCauseSync3=failCauseSync,die6=die2,dieMessage2=dieMessage,dieSync3=dieSync,gen2=gen,never3=never,none9=none6,promise2=promise,succeed9=succeed,succeedNone2=succeedNone,succeedSome2=succeedSome,suspend3=suspend,sync4=sync,_void=void_;var yieldNow4=yieldNow,_catch2=_catch;var catchAll3=catchAll,catchAllCause3=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,retry2=retry_combined,withExecutionPlan2=withExecutionPlan,retryOrElse=retryOrElse_Effect,try_3=try_2;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,liftPredicate3=liftPredicate2,as4=as,asSome2=asSome,asSomeError2=asSomeError,asVoid3=asVoid,flip2=flip,flipWith2=flipWith,map16=map10,mapAccum4=mapAccum3,mapBoth4=mapBoth,mapError3=mapError,mapErrorCause2=mapErrorCause,merge7=merge5,negate2=negate,acquireRelease2=acquireRelease,acquireReleaseInterruptible2=acquireReleaseInterruptible,acquireUseRelease2=acquireUseRelease,addFinalizer3=addFinalizer,ensuring3=ensuring,onError2=onError,onExit3=onExit,parallelFinalizers2=parallelFinalizers,sequentialFinalizers2=sequentialFinalizers,finalizersMask2=finalizersMask,scope3=scope,scopeWith2=scopeWith,scopedWith2=scopedWith,scoped2=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,mapInputContext3=mapInputContext,provide2=effect_provide,provideService3=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,either4=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,flatMap11=flatMap8,andThen5=andThen2,flatten8=flatten5,race2=race,raceAll2=raceAll,raceFirst2=raceFirst,raceWith2=raceWith,summarized2=summarized,tap3=tap,tapBoth2=tapBoth,tapDefect2=tapDefect,tapError3=tapError,tapErrorTag2=tapErrorTag,tapErrorCause3=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=isSuccess,match13=match8,matchCause3=matchCause,matchCauseEffect3=matchCauseEffect,matchEffect2=matchEffect,log3=log,logWithLevel2=(level,...message)=>logWithLevel(level)(...message),logTrace2=logTrace,logDebug2=logDebug,logInfo2=logInfo,logWarning2=logWarning,logError2=logError,logFatal2=logFatal,withLogSpan2=withLogSpan,annotateLogs3=annotateLogs,annotateLogsScoped2=annotateLogsScoped,logAnnotations2=logAnnotations,withUnhandledErrorLogLevel2=withUnhandledErrorLogLevel,whenLogLevel2=whenLogLevel,orDie3=orDie,orDieWith2=orDieWith,orElse5=orElse2,orElseFail2=orElseFail,orElseSucceed2=orElseSucceed,firstSuccessOf2=firstSuccessOf,random3=random2,randomWith2=randomWith,withRandom2=withRandom,withRandomFixed=dual(2,(effect,values3)=>withRandom2(effect,fixed2(values3))),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,zip5=zipOptions,zipLeft3=zipLeftOptions,zipRight4=zipRightOptions,zipWith6=zipWithOptions,ap=dual(2,(self,that)=>zipWith6(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,annotateSpans3=annotateSpans,annotateCurrentSpan2=annotateCurrentSpan,currentSpan2=currentSpan,currentParentSpan2=currentParentSpan,spanAnnotations2=spanAnnotations,spanLinks2=spanLinks,linkSpans2=linkSpans,linkSpanCurrent2=linkSpanCurrent,makeSpan2=makeSpan,makeSpanScoped2=makeSpanScoped,useSpan2=useSpan,withSpan3=withSpan,functionWithSpan2=functionWithSpan,withSpanScoped2=withSpanScoped,withParentSpan3=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]);Object.assign(fn,cn);let{apply,bind:bind4,call}=fn,proto4=Object.setPrototypeOf({},Object.getPrototypeOf(cn));return proto4.apply=apply,proto4.bind=bind4,proto4.call=call,Object.setPrototypeOf(fn,proto4),cache.set(prop,fn),fn}})},Tag3=(id2)=>()=>{let limit=Error.stackTraceLimit;Error.stackTraceLimit=2;let creationError=Error();Error.stackTraceLimit=limit;function TagClass(){}return Object.setPrototypeOf(TagClass,TagProto),TagClass.key=id2,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[id2,maker]=arguments,proxy="accessors"in maker?maker.accessors:!1,limit=Error.stackTraceLimit;Error.stackTraceLimit=2;let creationError=Error();Error.stackTraceLimit=limit;let patchState="unchecked",TagClass=function(service2){if(patchState==="unchecked"){let proto4=Object.getPrototypeOf(service2);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,service2);else if(patchState==="patched")return Object.setPrototypeOf(service2,Object.getPrototypeOf(this)),service2};TagClass.prototype._tag=id2,Object.defineProperty(TagClass,"make",{get(){return(service2)=>new this(service2)}}),Object.defineProperty(TagClass,"use",{get(){return(body)=>andThen2(this,body)}}),TagClass.key=id2,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,isFunction3=!1;if("effect"in maker)isFunction3=typeof maker.effect==="function",Object.defineProperty(TagClass,layerName,{get(){if(isFunction3)return function(){return fromEffect3(TagClass,map16(maker.effect.apply(null,arguments),(_)=>new this(_)))}.bind(this);return layerCache??=fromEffect3(TagClass,map16(maker.effect,(_)=>new this(_)))}});else if("scoped"in maker)isFunction3=typeof maker.scoped==="function",Object.defineProperty(TagClass,layerName,{get(){if(isFunction3)return function(){return scoped(TagClass,map16(maker.scoped.apply(null,arguments),(_)=>new this(_)))}.bind(this);return layerCache??=scoped(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??=succeed5(TagClass,new this(maker.succeed))}});if(hasDeps){let layerWithDepsCache;Object.defineProperty(TagClass,"Default",{get(){if(isFunction3)return function(){return provide(this.DefaultWithoutDependencies.apply(null,arguments),maker.dependencies)};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=Error();if(Error.stackTraceLimit=limit,typeof nameOrBody!=="string")return defineLength(nameOrBody.length,function(...args2){let limit2=Error.stackTraceLimit;Error.stackTraceLimit=2;let errorCall=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,{[name](...args2){let limit2=Error.stackTraceLimit;Error.stackTraceLimit=2;let errorCall=Error();return Error.stackTraceLimit=limit2,fnApply({self:this,body,args:args2,pipeables:pipeables2,spanName:name,spanOptions:options,errorDef,errorCall})}}[name])};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(error2){fnError=error2,effect=die6(error2)}if(options.pipeables.length>0)try{for(let x of options.pipeables)effect=x(effect,...options.args)}catch(error2){effect=fnError?failCause8(sequential(die(fnError),die(error2))):die6(error2)}let cache=!1,captureStackTrace=()=>{if(cache!==!1)return cache;if(options.errorCall.stack){let stackDef=options.errorDef.stack.trim().split(`
31
+ `).trim(),cache}}return suspend(()=>{let opts=typeof options.options==="function"?options.options.apply(null,arguments):options.options;return withSpan(suspend(()=>internalCall(()=>options.body.apply(this,arguments))),opts.name,{...opts,captureStackTrace})})},fromNullable2=(value)=>value==null?fail2(new NoSuchElementException):succeed(value),optionFromOptional=(self)=>catchAll(map10(self,some2),(error)=>isNoSuchElementException(error)?succeedNone:fail2(error));var isExit=exitIsExit,isFailure3=exitIsFailure,isSuccess2=exitIsSuccess;var all3=exitCollectAll,die4=exitDie;var fail4=exitFail,failCause3=exitFailCause;var flatten6=exitFlatten;var interrupt4=exitInterrupt,map12=exitMap,mapBoth2=exitMapBoth;var match9=exitMatch;var succeed3=exitSucceed,void_3=exitVoid;var zip3=exitZip;var zipRight2=exitZipRight;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 unsafeMake6=(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);var isRuntimeFiber=(self)=>(RuntimeFiberTypeId in self),_await=(self)=>self.await;var inheritAll=(self)=>self.inheritAll;var interruptAllAs=dual(2,fnUntraced(function*(fibers,fiberId2){for(let fiber of fibers){if(isRuntimeFiber(fiber)){fiber.unsafeInterruptAsFork(fiberId2);continue}yield*fiber.interruptAsFork(fiberId2)}for(let fiber of fibers){if(isRuntimeFiber(fiber)&&fiber.unsafePoll())continue;yield*fiber.await}})),interruptAsFork=dual(2,(self,fiberId2)=>self.interruptAsFork(fiberId2)),join2=(self)=>zipLeft(flatten5(self.await),self.inheritAll);var _never={...CommitPrototype,commit(){return join2(this)},...fiberProto,id:()=>none4,await:never,children:succeed([]),inheritAll:never,poll:succeed(none2()),interruptAsFork:()=>never};var poll=(self)=>self.poll;var currentFiberURI="effect/FiberCurrent";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"=]*$/,format3=(quoteValue,whitespace)=>({annotations,cause:cause2,date,fiberId:fiberId2,logLevel,message,spans})=>{let formatValue=(value)=>value.match(textOnly)?value:quoteValue(value),format4=(label,value)=>`${formatLabel(label)}=${formatValue(value)}`,append3=(label,value)=>" "+format4(label,value),out=format4("timestamp",date.toISOString());out+=append3("level",logLevel.label),out+=append3("fiber",threadName(fiberId2));let messages=ensure(message);for(let i=0;i<messages.length;i++)out+=append3("message",toStringUnknown(messages[i],whitespace));if(!isEmptyType(cause2))out+=append3("cause",pretty(cause2,{renderErrorCause:!0}));for(let span2 of spans)out+=" "+render(date.getTime())(span2);for(let[label,value]of annotations)out+=append3(label,toStringUnknown(value,whitespace));return out},escapeDoubleQuotes=(s)=>`"${s.replace(/\\([\s\S])|(")/g,"\\$1$2")}"`,stringLogger=makeLogger(format3(escapeDoubleQuotes));var structuredMessage=(u)=>{switch(typeof u){case"bigint":case"function":case"symbol":return String(u);default:return toJSON(u)}};var withColor=(text,...colors)=>{let out="";for(let i=0;i<colors.length;i++)out+=`\x1B[${colors[i]}m`;return out+text+"\x1B[0m"},withColorNoop=(text,..._colors)=>text,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]},logLevelStyle={None:"",All:"",Trace:"color:gray",Debug:"color:blue",Info:"color:green",Warning:"color:orange",Error:"color:red",Fatal:"background-color:red;color:white"},defaultDateFormat=(date)=>`${date.getHours().toString().padStart(2,"0")}:${date.getMinutes().toString().padStart(2,"0")}:${date.getSeconds().toString().padStart(2,"0")}.${date.getMilliseconds().toString().padStart(3,"0")}`,hasProcessStdout=typeof process==="object"&&process!==null&&typeof process.stdout==="object"&&process.stdout!==null,processStdoutIsTTY=hasProcessStdout&&process.stdout.isTTY===!0,hasProcessStdoutOrDeno=hasProcessStdout||"Deno"in globalThis,prettyLogger=(options)=>{let mode_=options?.mode??"auto",isBrowser=(mode_==="auto"?hasProcessStdoutOrDeno?"tty":"browser":mode_)==="browser",showColors=typeof options?.colors==="boolean"?options.colors:processStdoutIsTTY||isBrowser,formatDate2=options?.formatDate??defaultDateFormat;return isBrowser?prettyLoggerBrowser({colors:showColors,formatDate:formatDate2}):prettyLoggerTty({colors:showColors,formatDate:formatDate2,stderr:options?.stderr===!0})},prettyLoggerTty=(options)=>{let color=options.colors?withColor:withColorNoop;return makeLogger(({annotations,cause:cause2,context:context2,date,fiberId:fiberId2,logLevel,message:message_,spans})=>{let services=getOrDefault2(context2,currentServices),console2=get5(services,consoleTag).unsafe,log2=options.stderr===!0?console2.error:console2.log,message=ensure(message_),firstLine=color(`[${options.formatDate(date)}]`,colors.white)+` ${color(logLevel.label,...logLevelColors[logLevel._tag])} (${threadName(fiberId2)})`;if(isCons(spans)){let now=date.getTime(),render2=render(now);for(let span2 of spans)firstLine+=" "+render2(span2)}firstLine+=":";let messageIndex=0;if(message.length>0){let firstMaybeString=structuredMessage(message[0]);if(typeof firstMaybeString==="string")firstLine+=" "+color(firstMaybeString,colors.bold,colors.cyan),messageIndex++}if(log2(firstLine),console2.group(),!isEmpty3(cause2))log2(pretty(cause2,{renderErrorCause:!0}));if(messageIndex<message.length)for(;messageIndex<message.length;messageIndex++)log2(redact(message[messageIndex]));if(size4(annotations)>0)for(let[key,value]of annotations)log2(color(`${key}:`,colors.bold,colors.white),redact(value));console2.groupEnd()})},prettyLoggerBrowser=(options)=>{let color=options.colors?"%c":"";return makeLogger(({annotations,cause:cause2,context:context2,date,fiberId:fiberId2,logLevel,message:message_,spans})=>{let services=getOrDefault2(context2,currentServices),console2=get5(services,consoleTag).unsafe,message=ensure(message_),firstLine=`${color}[${options.formatDate(date)}]`,firstParams=[];if(options.colors)firstParams.push("color:gray");if(firstLine+=` ${color}${logLevel.label}${color} (${threadName(fiberId2)})`,options.colors)firstParams.push(logLevelStyle[logLevel._tag],"");if(isCons(spans)){let now=date.getTime(),render2=render(now);for(let span2 of spans)firstLine+=" "+render2(span2)}firstLine+=":";let messageIndex=0;if(message.length>0){let firstMaybeString=structuredMessage(message[0]);if(typeof firstMaybeString==="string"){if(firstLine+=` ${color}${firstMaybeString}`,options.colors)firstParams.push("color:deepskyblue");messageIndex++}}if(console2.groupCollapsed(firstLine,...firstParams),!isEmpty3(cause2))console2.error(pretty(cause2,{renderErrorCause:!0}));if(messageIndex<message.length)for(;messageIndex<message.length;messageIndex++)console2.log(redact(message[messageIndex]));if(size4(annotations)>0)for(let[key,value]of annotations){let redacted=redact(value);if(options.colors)console2.log(`%c${key}:`,"color:gray",redacted);else console2.log(`${key}:`,redacted)}console2.groupEnd()})},prettyLoggerDefault=globalValue("effect/Logger/prettyLoggerDefault",()=>prettyLogger());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,bigint){this.incremental=incremental,this.bigint=bigint,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 TypeId11=Symbol.for("effect/MutableHashMap"),MutableHashMapProto={[TypeId11]:TypeId11,[Symbol.iterator](){return new MutableHashMapIterator(this)},toString(){return format(this.toJSON())},toJSON(){return{_id:"MutableHashMap",values:Array.from(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}};class MutableHashMapIterator{self;referentialIterator;bucketIterator;constructor(self){this.self=self,this.referentialIterator=self.referential[Symbol.iterator]()}next(){if(this.bucketIterator!==void 0)return this.bucketIterator.next();let result=this.referentialIterator.next();if(result.done)return this.bucketIterator=new BucketIterator(this.self.buckets.values()),this.next();return result}[Symbol.iterator](){return new MutableHashMapIterator(this.self)}}class BucketIterator{backing;constructor(backing){this.backing=backing}currentBucket;next(){if(this.currentBucket===void 0){let result2=this.backing.next();if(result2.done)return result2;this.currentBucket=result2.value[Symbol.iterator]()}let result=this.currentBucket.next();if(result.done)return this.currentBucket=void 0,this.next();return result}}var empty21=()=>{let self=Object.create(MutableHashMapProto);return self.referential=new Map,self.buckets=new Map,self.bucketsSize=0,self};var get12=dual(2,(self,key)=>{if(isEqual(key)===!1)return self.referential.has(key)?some2(self.referential.get(key)):none2();let hash2=key[symbol](),bucket=self.buckets.get(hash2);if(bucket===void 0)return none2();return getFromBucket(self,bucket,key)});var getFromBucket=(self,bucket,key,remove5=!1)=>{for(let i=0,len=bucket.length;i<len;i++)if(key[symbol2](bucket[i][0])){let value=bucket[i][1];if(remove5)bucket.splice(i,1),self.bucketsSize--;return some2(value)}return none2()},has4=dual(2,(self,key)=>isSome2(get12(self,key))),set6=dual(3,(self,key,value)=>{if(isEqual(key)===!1)return self.referential.set(key,value),self;let hash2=key[symbol](),bucket=self.buckets.get(hash2);if(bucket===void 0)return self.buckets.set(hash2,[[key,value]]),self.bucketsSize++,self;return removeFromBucket(self,bucket,key),bucket.push([key,value]),self.bucketsSize++,self}),removeFromBucket=(self,bucket,key)=>{for(let i=0,len=bucket.length;i<len;i++)if(key[symbol2](bucket[i][0])){bucket.splice(i,1),self.bucketsSize--;return}};var remove5=dual(2,(self,key)=>{if(isEqual(key)===!1)return self.referential.delete(key),self;let hash2=key[symbol](),bucket=self.buckets.get(hash2);if(bucket===void 0)return self;if(removeFromBucket(self,bucket,key),bucket.length===0)self.buckets.delete(hash2);return self});var size6=(self)=>{return self.referential.size+self.bucketsSize};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:(_)=>_},make28=(options)=>({[MetricHookTypeId]:metricHookVariance,pipe(){return pipeArguments(this,arguments)},...options});var bigint03=BigInt(0),counter4=(key)=>{let sum2=key.keyType.bigint?bigint03:0,canUpdate=key.keyType.incremental?key.keyType.bigint?(value)=>value>=bigint03:(value)=>value>=0:(_value)=>!0,update4=(value)=>{if(canUpdate(value))sum2=sum2+value};return make28({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 make28({get:()=>frequency2(values3),update:update4,modify:update4})},gauge3=(_key,startAt)=>{let value=startAt;return make28({get:()=>gauge2(value),update:(v)=>{value=v},modify:(v)=>{value=value+v}})},histogram4=(key)=>{let bounds=key.keyType.boundaries.values,size7=bounds.length,values3=new Uint32Array(size7+1),boundaries=new Float64Array(size7),count=0,sum2=0,min3=Number.MAX_VALUE,max3=Number.MIN_VALUE;pipe(bounds,sort(Order2),map3((n,i)=>{boundaries[i]=n}));let update4=(value)=>{let from=0,to=size7;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(size7),cumulated=0;for(let i=0;i<size7;i++){let boundary=boundaries[i],value=values3[i];cumulated=cumulated+value,builder[i]=[boundary,cumulated]}return builder};return make28({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(Order2)),values3=allocate(maxSize),head4=0,count=0,sum2=0,min3=0,max3=0,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(greaterThanOrEqualTo(age,zero)&&lessThanOrEqualTo(age,maxAge))builder.push(v)}i=i+1}return calculateQuantiles(error,sortedQuantiles,sort(builder,Order2))},observe=(value,timestamp)=>{if(maxSize>0){head4=head4+1;let target=head4%maxSize;values3[target]=[timestamp,value]}min3=count===0?value:Math.min(min3,value),max3=count===0?value:Math.max(max3,value),count=count+1,sum2=sum2+value};return make28({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 empty();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 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 unsafeMake7=(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(unsafeMake7(key,hook.get()));return result}get(key){let hook=pipe(this.map,get12(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 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,get12(key),getOrUndefined);if(value==null){let counter5=counter4(key);if(!pipe(this.map,has4(key)))pipe(this.map,set6(key,counter5));value=counter5}return value}getFrequency(key){let value=pipe(this.map,get12(key),getOrUndefined);if(value==null){let frequency4=frequency3(key);if(!pipe(this.map,has4(key)))pipe(this.map,set6(key,frequency4));value=frequency4}return value}getGauge(key){let value=pipe(this.map,get12(key),getOrUndefined);if(value==null){let gauge4=gauge3(key,key.keyType.bigint?BigInt(0):0);if(!pipe(this.map,has4(key)))pipe(this.map,set6(key,gauge4));value=gauge4}return value}getHistogram(key){let value=pipe(this.map,get12(key),getOrUndefined);if(value==null){let histogram5=histogram4(key);if(!pipe(this.map,has4(key)))pipe(this.map,set6(key,histogram5));value=histogram5}return value}getSummary(key){let value=pipe(this.map,get12(key),getOrUndefined);if(value==null){let summary4=summary3(key);if(!pipe(this.map,has4(key)))pipe(this.map,set6(key,summary4));value=summary4}return value}}var make29=()=>{return new MetricRegistryImpl};var MetricSymbolKey="effect/Metric",MetricTypeId=Symbol.for(MetricSymbolKey),metricVariance={_Type:(_)=>_,_In:(_)=>_,_Out:(_)=>_},globalMetricRegistry=globalValue(Symbol.for("effect/Metric/globalMetricRegistry"),()=>make29()),make30=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 make30(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,[make27(key,value)]));var taggedWithLabels2=dual(2,(self,extraTags)=>{return make30(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 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),fromEffect=(effect)=>{return new Const(effect)},none8=globalValue("effect/Supervisor/none",()=>fromEffect(void_));var make31=make14;var OP_EMPTY3="Empty",OP_ADD_SUPERVISOR="AddSupervisor",OP_REMOVE_SUPERVISOR="RemoveSupervisor",OP_AND_THEN2="AndThen",empty22={_tag:OP_EMPTY3},combine8=(self,that)=>{return{_tag:OP_AND_THEN2,first:self,second:that}},patch8=(self,supervisor)=>{return patchLoop(supervisor,of2(self))},patchLoop=(_supervisor,_patches)=>{let supervisor=_supervisor,patches=_patches;while(isNonEmpty(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 empty5();else if(isZip(self))return pipe(toSet2(self.left),union3(toSet2(self.right)));else return make7(self)},diff7=(oldValue,newValue)=>{if(equals(oldValue,newValue))return empty22;let oldSupervisors=toSet2(oldValue),newSupervisors=toSet2(newValue),added=pipe(newSupervisors,difference3(oldSupervisors),reduce5(empty22,(patch9,supervisor)=>combine8(patch9,{_tag:OP_ADD_SUPERVISOR,supervisor}))),removed=pipe(oldSupervisors,difference3(newSupervisors),reduce5(empty22,(patch9,supervisor)=>combine8(patch9,{_tag:OP_REMOVE_SUPERVISOR,supervisor})));return combine8(added,removed)},differ2=make31({empty:empty22,patch:patch8,combine:combine8,diff:diff7});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 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)=>{while(!0){let state=internalCall(()=>cont.effect_instruction_i0.next(value));if(state.done)return exitSucceed(state.value);let primitive=yieldWrapGet(state.value);if(!exitIsExit(primitive))return self.pushStack(cont),primitive;else if(primitive._tag==="Failure")return primitive;value=primitive.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 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=[];_children=null;_observers=[];_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((_,status)=>status)}get runtimeFlags(){return this.ask((state,status)=>{if(isDone2(status))return state.currentRuntimeFlags;return status.runtimeFlags})}scope(){return unsafeMake6(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,status)=>{deferredUnsafeDone(deferred,sync(()=>f(fiber,status)))})),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),patch9=pipe(diff4(parentRuntimeFlags,updatedRuntimeFlags),exclude2(Interruption),exclude2(WindDown));return updateRuntimeFlags(patch9)})}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 children=this._children;if(this._children=null,children!==null&&children.size>0){for(let child of children)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!isEmpty3(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 isDone3=!1;return whileLoop({while:()=>!isDone3,body:()=>{let next2=it.next();if(!next2.done)return asVoid(next2.value.await);else return sync(()=>{isDone3=!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),annotations=this.getFiberRef(currentLogAnnotations),loggers=this.getLoggers(),contextMap=this.getFiberRefs();if(size3(loggers)>0){let clockService=get5(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,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?done3: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,patch9){let newRuntimeFlags=patch4(oldRuntimeFlags,patch9);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(()=>unsafeGet4(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=diff6(snap.refs,refs),patchFlags=diff4(snap.flags,flags);return exitSucceed(blocked(op.effect_instruction_i0,withFiberRuntime((newFiber)=>{while(frames.length>0)newFiber.pushStack(frames.pop());return newFiber.setFiberRefs(patch7(newFiber.id(),newFiber.getFiberRefs())(patchRefs)),newFiber.currentRuntimeFlags=patch4(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=patch4(oldRuntimeFlags,updateFlags);if(interruptible(newRuntimeFlags)&&this.isInterrupted())return exitFailCause(this.getInterruptedCause());else if(this.patchRuntimeFlags(this.currentRuntimeFlags,updateFlags),op.effect_instruction_i1){let revertFlags=diff4(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){let level=this.getFiberRef(currentVersionMismatchErrorLogLevel);if(level._tag==="Some"){let effectVersion=cur[EffectTypeId2]._V;this.log(`Executing an Effect versioned ${effectVersion} with a Runtime of version ${getCurrentVersion()}, you may want to dedupe the effect dependencies, you can use the language service plugin to detect this at compile time: https://github.com/Effect-TS/language-service`,empty6,level)}}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);get5(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,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=unsafeGet4(getOrDefault(context2,currentServices),clockTag),attributes={};for(let[key,value]of annotations)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.length===1?message[0]:message),clockService.unsafeCurrentTimeNanos(),attributes)}));var currentLoggers=globalValue(Symbol.for("effect/FiberRef/currentLoggers"),()=>fiberRefUnsafeMakeHashSet(make7(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((annotations)=>{for(let i=0;i<entries2.length;i++){let[key,value]=entries2[i];set3(annotations,key,value)}return annotations}))},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=disable2(runtime2.currentRuntimeFlags,Interruption);return flatMap8(scope,(scope)=>scopeAddFinalizerExit(scope,(exit2)=>withFiberRuntime((runtimeFinalizer)=>{let preRefs=runtimeFinalizer.getFiberRefs(),preFlags=runtimeFinalizer.currentRuntimeFlags,patchRefs=diff6(preRefs,acquireRefs),patchFlags=diff4(preFlags,acquireFlags),inverseRefs=diff6(acquireRefs,preRefs);return runtimeFinalizer.setFiberRefs(patch7(patchRefs,runtimeFinalizer.id(),acquireRefs)),ensuring(withRuntimeFlags(finalizer(exit2),patchFlags),sync(()=>{runtimeFinalizer.setFiberRefs(patch7(inverseRefs,runtimeFinalizer.id(),runtimeFinalizer.getFiberRefs()))}))})))}),daemonChildren=(self)=>{return fiberRefLocally(currentForkScopeOverride,some2(globalScope))(self)},_existsParFound=Symbol.for("effect/Effect/existsPar/found"),exists=dual((args2)=>isIterable(args2[0])&&!isEffect(args2[0]),(elements,predicate,options)=>matchSimple(options?.concurrency,()=>suspend(()=>existsLoop(elements[Symbol.iterator](),0,predicate)),()=>matchEffect(forEach5(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 next2=iterator.next();if(next2.done)return succeed(!1);return flatMap8(f(next2.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(()=>[]))),()=>map10(forEach5(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 keys3=Object.keys(input),size7=keys3.length;return[keys3.map((k)=>input[k]),some2((values3)=>{let res={};for(let i=0;i<size7;i++)res[keys3[i]]=values3[i];return res})]},allValidate=(effects,reconcile,options)=>{let eitherEffects=[];for(let effect of effects)eitherEffects.push(either2(effect));return flatMap8(forEach5(eitherEffects,identity,{concurrency:options?.concurrency,batching:options?.batching,concurrentFinalizers:options?.concurrentFinalizers}),(eithers)=>{let none9=none2(),size7=eithers.length,errors=Array(size7),successes=Array(size7),errored=!1;for(let i=0;i<size7;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 forEach5(eitherEffects,identity,{concurrency:options?.concurrency,batching:options?.batching,discard:!0,concurrentFinalizers:options?.concurrentFinalizers});return map10(forEach5(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(forEach5(effects,identity,options),reconcile.value):forEach5(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)),forEach5=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 match7(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 match7(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 as3=fromIterable(self),array3=Array(as3.length);return zipRight(forEachConcurrentDiscard(as3,(a,i)=>flatMap8(f(a,i),(b)=>sync(()=>array3[i]=b)),batching,!1),succeed(array3))}),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,interrupted=!1,fibersCount=n?Math.min(todos.length,n):todos.length,fibers=new Set,results=[],interruptAll=()=>fibers.forEach((fiber)=>{fiber.currentScheduler.scheduleTask(()=>{fiber.unsafeInterruptAsFork(parent.id())},0)}),startOrder=[],joinOrder=[],residual=[],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=[];interrupted=!0,interruptAll()},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"&&!interrupted)onInterruptSignal()},next2=()=>{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),interrupted)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 next2()})}};for(let i=0;i<fibersCount;i++)next2()}));return asVoid(onExit(flatten5(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)next2()},next2=()=>{runFiber(toPop.pop(),!0).addObserver(check(index,!0)),index++};processingFiber.addObserver(check(index,!1)),index++;for(let i=0;i<concurrency;i++)next2()})},onSuccess:()=>forEachSequential(joinOrder,(f2)=>f2.inheritAll)})))}))),forEachParN=(self,n,f,batching)=>suspend(()=>{let as3=fromIterable(self),array3=Array(as3.length);return zipRight(forEachConcurrentDiscard(as3,(a,i)=>map10(f(a,i),(b)=>array3[i]=b),batching,!1,n),succeed(array3))}),fork=(self)=>withFiberRuntime((state,status)=>succeed(unsafeFork(self,state,status.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=unsafeMake3(),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))),mergeAll3=dual((args2)=>isFunction2(args2[2]),(elements,zero2,f,options)=>matchSimple(options?.concurrency,()=>fromIterable(elements).reduce((acc,a,i)=>zipWith3(acc,a,(acc2,a2)=>f(acc2,a2,i)),succeed(zero2)),()=>flatMap8(make24(zero2),(acc)=>flatMap8(forEach5(elements,(effect,i)=>flatMap8(effect,(a)=>update3(acc,(b)=>f(b,a,i))),options),()=>get11(acc))))),partition3=dual((args2)=>isIterable(args2[0]),(elements,f,options)=>pipe(forEach5(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)=>withFiberRuntime((state,status)=>async_((resume2)=>{let fibers=new Set,winner,failures2=empty6,interruptAll=()=>{for(let fiber of fibers)fiber.unsafeInterruptAsFork(state.id())},latch=!1,empty23=!0;for(let self of all5){empty23=!1;let fiber=unsafeFork(interruptible2(self),state,status.runtimeFlags);if(fibers.add(fiber),fiber.addObserver((exit2)=>{if(fibers.delete(fiber),!winner)if(exit2._tag==="Success")latch=!0,winner=fiber,failures2=empty6,interruptAll();else failures2=parallel(exit2.cause,failures2);if(latch&&fibers.size===0)resume2(winner?zipRight(inheritAll(winner),winner.unsafePoll()):failCause(failures2))}),winner)break}if(empty23)return resume2(dieSync(()=>new IllegalArgumentException("Received an empty collection of effects")));return latch=!0,interruptAllAs(fibers,state.id())})),reduceEffect=dual((args2)=>isIterable(args2[0])&&!isEffect(args2[0]),(elements,zero2,f,options)=>matchSimple(options?.concurrency,()=>fromIterable(elements).reduce((acc,a,i)=>zipWith3(acc,a,(acc2,a2)=>f(acc2,a2,i)),zero2),()=>suspend(()=>pipe(mergeAll3([zero2,...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 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 patch9=strategy._tag==="Parallel"?parallelFinalizers:strategy._tag==="Sequential"?sequentialFinalizers:parallelNFinalizers(strategy.parallelism);switch(scope.strategy._tag){case"Parallel":return patch9(self(parallelFinalizers));case"Sequential":return patch9(self(sequentialFinalizers));case"ParallelN":return patch9(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([make27(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)=>flatten5(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(forEach5(elements,(a,i)=>flip(f(a,i)),options))),withClockScoped=(c)=>fiberRefLocallyScopedWith(currentServices,add4(clockTag,c)),withRandomScoped=(value)=>fiberRefLocallyScopedWith(currentServices,add4(randomTag,value)),withConfigProviderScoped=(provider)=>fiberRefLocallyScopedWith(currentServices,add4(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===empty15)return void_;return pipe(runtimeFlags,flatMap8((runtimeFlags2)=>{let updatedRuntimeFlags=patch4(runtimeFlags2,update5),revertRuntimeFlags=diff4(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(make9(scopeTag,scope2)))),scopeUse=dual(2,(effect,scope2)=>pipe(effect,scopeExtend(scope2),onExit((exit2)=>scope2.close(exit2)))),fiberRefUnsafeMakeSupervisor=(initial)=>fiberRefUnsafeMakePatch(initial,{differ:differ2,fork:empty22}),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)=>forEach5(fibers,_await),fiberAll=(fibers)=>{return{...CommitPrototype2,commit(){return join2(this)},[FiberTypeId]:fiberVariance2,id:()=>fromIterable(fibers).reduce((id,fiber)=>combine3(id,fiber.id()),none4),await:exit(forEachParUnbounded(fibers,(fiber)=>flatten5(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([])),(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))}};var 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=make11(!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((id)=>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(id)))})));var makeSpanScoped=(name,options)=>{return options=addSpanStackTrace(options),uninterruptible(withFiberRuntime((fiber)=>{let scope2=unsafeGet4(fiber.getFiberRef(currentContext),scopeTag),span2=unsafeMakeSpan(fiber,name,options),timingEnabled=fiber.getFiberRef(currentTracerTimingEnabled),clock_=get5(fiber.getFiberRef(currentServices),clockTag);return as(scopeAddFinalizerExit(scope2,(exit2)=>endSpan(span2,exit2,clock_,timingEnabled)),span2)}))},withTracerScoped=(value)=>fiberRefLocallyScopedWith(currentServices,add4(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 IntervalSymbolKey="effect/ScheduleInterval",IntervalTypeId=Symbol.for(IntervalSymbolKey),empty23={[IntervalTypeId]:IntervalTypeId,startMillis:0,endMillis:0},make32=(startMillis,endMillis)=>{if(startMillis>endMillis)return empty23;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 isEmpty6=(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 make32(start,end)}),size7=(self)=>{return millis(self.endMillis-self.startMillis)};var after=(startMilliseconds)=>{return make32(startMilliseconds,Number.POSITIVE_INFINITY)};var make33=make32,empty24=empty23,lessThan4=lessThan3;var isEmpty7=isEmpty6;var intersect2=intersect,size8=size7;var after2=after;var IntervalsSymbolKey="effect/ScheduleIntervals",IntervalsTypeId=Symbol.for(IntervalsSymbolKey),make34=(intervals)=>{return{[IntervalsTypeId]:IntervalsTypeId,intervals}};var union6=dual(2,(self,that)=>{if(!isNonEmpty(that.intervals))return self;if(!isNonEmpty(self.intervals))return that;if(headNonEmpty2(self.intervals).startMillis<headNonEmpty2(that.intervals).startMillis)return unionLoop(tailNonEmpty2(self.intervals),that.intervals,headNonEmpty2(self.intervals),empty2());return unionLoop(self.intervals,tailNonEmpty2(that.intervals),headNonEmpty2(that.intervals),empty2())}),unionLoop=(_self,_that,_interval,_acc)=>{let self=_self,that=_that,interval=_interval,acc=_acc;while(isNonEmpty(self)||isNonEmpty(that))if(!isNonEmpty(self)&&isNonEmpty(that))if(interval.endMillis<headNonEmpty2(that).startMillis)acc=pipe(acc,prepend2(interval)),interval=headNonEmpty2(that),that=tailNonEmpty2(that),self=empty2();else interval=make33(interval.startMillis,headNonEmpty2(that).endMillis),that=tailNonEmpty2(that),self=empty2();else if(isNonEmpty(self)&&isEmpty(that))if(interval.endMillis<headNonEmpty2(self).startMillis)acc=pipe(acc,prepend2(interval)),interval=headNonEmpty2(self),that=empty2(),self=tailNonEmpty2(self);else interval=make33(interval.startMillis,headNonEmpty2(self).endMillis),that=empty2(),self=tailNonEmpty2(self);else if(isNonEmpty(self)&&isNonEmpty(that))if(headNonEmpty2(self).startMillis<headNonEmpty2(that).startMillis)if(interval.endMillis<headNonEmpty2(self).startMillis)acc=pipe(acc,prepend2(interval)),interval=headNonEmpty2(self),self=tailNonEmpty2(self);else interval=make33(interval.startMillis,headNonEmpty2(self).endMillis),self=tailNonEmpty2(self);else if(interval.endMillis<headNonEmpty2(that).startMillis)acc=pipe(acc,prepend2(interval)),interval=headNonEmpty2(that),that=tailNonEmpty2(that);else interval=make33(interval.startMillis,headNonEmpty2(that).endMillis),that=tailNonEmpty2(that);else throw Error(getBugErrorMessage("Intervals.unionLoop"));return make34(pipe(acc,prepend2(interval),reverse2))},intersect3=dual(2,(self,that)=>intersectLoop(self.intervals,that.intervals,empty2())),intersectLoop=(_left,_right,_acc)=>{let left3=_left,right3=_right,acc=_acc;while(isNonEmpty(left3)&&isNonEmpty(right3)){let interval=pipe(headNonEmpty2(left3),intersect2(headNonEmpty2(right3))),intervals=isEmpty7(interval)?acc:pipe(acc,prepend2(interval));if(pipe(headNonEmpty2(left3),lessThan4(headNonEmpty2(right3))))left3=tailNonEmpty2(left3);else right3=tailNonEmpty2(right3);acc=intervals}return make34(reverse2(acc))},start=(self)=>{return pipe(self.intervals,head2,getOrElse(()=>empty24)).startMillis},end=(self)=>{return pipe(self.intervals,head2,getOrElse(()=>empty24)).endMillis},lessThan5=dual(2,(self,that)=>start(self)<start(that)),isNonEmpty3=(self)=>{return isNonEmpty(self.intervals)},max4=dual(2,(self,that)=>lessThan5(self,that)?that:self);var make35=make34;var union7=union6,intersect4=intersect3,start2=start,end2=end,lessThan6=lessThan5,isNonEmpty4=isNonEmpty3,max5=max4;var OP_CONTINUE="Continue",OP_DONE2="Done",_continue=(intervals)=>{return{_tag:OP_CONTINUE,intervals}},continueWith=(interval)=>{return{_tag:OP_CONTINUE,intervals:make35(of2(interval))}},done4={_tag:OP_DONE2},isContinue=(self)=>{return self._tag===OP_CONTINUE},isDone3=(self)=>{return self._tag===OP_DONE2};var _continue2=_continue;var continueWith2=continueWith,done5=done4,isContinue2=isContinue,isDone4=isDone3;var Scope=scopeTag,addFinalizer2=scopeAddFinalizer,addFinalizerExit=scopeAddFinalizerExit,close=scopeClose,extend2=scopeExtend,fork2=scopeFork;var make36=scopeMake;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))});updateTakenUnsafe(fiber,f){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)}updateTaken(f){return withFiberRuntime((fiber)=>this.updateTakenUnsafe(fiber,f))}resize=(permits)=>asVoid(withFiberRuntime((fiber)=>{if(this.permits=permits,this.free<0)return void_;return this.updateTakenUnsafe(fiber,(taken)=>taken)}));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),(tuple)=>tuple[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)=>set4(cache,none2()),ensuringChild=dual(2,(self,f)=>ensuringChildren(self,(children)=>f(fiberAll(children)))),ensuringChildren=dual(2,(self,children)=>flatMap8(track,(supervisor)=>pipe(supervised(self,supervisor),ensuring(flatMap8(supervisor.value,children))))),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((map13)=>{let result=pipe(map13,get12(new Key(a,eq)));if(isNone2(result))return pipe(deferredMake(),tap((deferred)=>pipe(diffFiberRefs(f(a)),intoDeferred(deferred),fork)),map10((deferred)=>[deferred,pipe(map13,set6(new Key(a,eq),deferred))]));return succeed([result.value,map13])}),flatMap8(deferredAwait),flatMap8(([patch9,b])=>pipe(patchFiberRefs(patch9),as(b))))))},raceFirst=dual(2,(self,that)=>pipe(exit(self),race(exit(that)),(effect)=>flatten5(effect))),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})=>flatten5(timeoutTo(self,{onTimeout:()=>failSync(onTimeout),onSuccess:succeed,duration}))),timeoutFailCause=dual(2,(self,{duration,onTimeout})=>flatten5(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;[TypeId10]=TypeId10;constructor(ref,withLock){super();this.ref=ref,this.withLock=withLock,this.get=get10(this.ref)}get;commit(){return this.get}modify(f){return this.modifyEffect((a)=>succeed(f(a)))}modifyEffect(f){return this.withLock(pipe(flatMap8(get10(this.ref),f),flatMap8(([b,a])=>as(set4(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])}}));var bindAll=dual((args2)=>isEffect(args2[0]),(self,f,options)=>flatMap8(self,(a)=>all4(f(a),options).pipe(map10((record)=>Object.assign({},a,record)))));var TypeId12=Symbol.for("effect/ManagedRuntime");var OP_EXTEND_SCOPE="ExtendScope",OP_FOLD="Fold",OP_FRESH="Fresh",OP_FROM_EFFECT="FromEffect",OP_SCOPED="Scoped",OP_SUSPEND="Suspend",OP_PROVIDE="Provide",OP_PROVIDE_MERGE="ProvideMerge",OP_MERGE_ALL="MergeAll",OP_ZIP_WITH2="ZipWith";var _await2=_await;var inheritAll2=inheritAll,interrupt5=interruptFiber;var interruptAs=interruptAsFiber;var join3=join2;var poll2=poll;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=unsafeMake3(),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((id2)=>equals(id2,fiberRuntime.id())?void_:interruptAsFiber(fiberRuntime,id2))),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(id2,cancelOptions)=>unsafeRunCallback(runtime2)(pipe(fiberRuntime,interruptAs(id2??none4)),{...cancelOptions,onExit:cancelOptions?.onExit?(exit2)=>cancelOptions.onExit(flatten6(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(new 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 make37=(options)=>new RuntimeImpl(options.context,options.runtimeFlags,options.fiberRefs),runtime2=()=>withFiberRuntime((state,status2)=>succeed(new RuntimeImpl(state.getFiberRef(currentContext),status2.runtimeFlags,state.getFiberRefs()))),defaultRuntimeFlags=make16(Interruption,CooperativeYielding,RuntimeMetrics),defaultRuntime=make37({context:empty8(),runtimeFlags:defaultRuntimeFlags,fiberRefs:empty19()});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,(map14)=>{let inMap=map14.get(layer);if(inMap!==void 0){let[acquire,release]=inMap,cached3=pipe(acquire,flatMap8(([patch9,b])=>pipe(patchFiberRefs(patch9),as(b))),onExit(exitMatch({onFailure:()=>void_,onSuccess:()=>scopeAddFinalizerExit(scope2,release)})));return succeed([cached3,map14])}return pipe(make23(0),flatMap8((observers)=>pipe(deferredMake(),flatMap8((deferred)=>pipe(make23(()=>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(set4(finalizerRef,(exit3)=>pipe(scopeClose(innerScope,exit3),whenEffect(modify3(observers,(n)=>[n===1,n-1])),asVoid)),zipRight(update2(observers,(n)=>n+1)),zipRight(scopeAddFinalizerExit(scope2,(exit3)=>pipe(sync(()=>map14.delete(layer)),zipRight(get10(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(get10(finalizerRef),flatMap8((finalizer)=>finalizer(exit2)))];return[resource,isFresh(layer)?map14:map14.set(layer,memoized)]}))))))}),flatten5)}}var makeMemoMap=suspend(()=>map10(makeSynchronized(new Map),(ref)=>new MemoMapImpl(ref))),unsafeMakeMemoMap=()=>new MemoMapImpl(unsafeMakeSynchronized(new Map)),build=(self)=>scopeWith((scope2)=>buildWithScope(self,scope2)),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 gen(function*(){let parallelScope=yield*scopeFork(scope2,parallel2),firstScope=yield*scopeFork(parallelScope,sequential2),secondScope=yield*scopeFork(parallelScope,sequential2);return(memoMap)=>pipe(memoMap.getOrElseMemoize(op.first,firstScope),zipWithOptions(memoMap.getOrElseMemoize(op.second,secondScope),op.zipK,{concurrent:!0}))});case"MergeAll":{let layers=op.layers;return map10(scopeFork(scope2,parallel2),(parallelScope)=>(memoMap)=>{let contexts=Array(layers.length);return map10(forEachConcurrentDiscard(layers,fnUntraced(function*(layer,i){let scope3=yield*scopeFork(parallelScope,sequential2),context2=yield*memoMap.getOrElseMemoize(layer,scope3);contexts[i]=context2}),!1,!1),()=>mergeAll2(...contexts))})}}},catchAll2=dual(2,(self,onFailure)=>match11(self,{onFailure,onSuccess:succeedContext})),catchAllCause2=dual(2,(self,onFailure)=>matchCause2(self,{onFailure,onSuccess:succeedContext})),die5=(defect)=>failCause5(die3(defect)),dieSync2=(evaluate2)=>failCauseSync2(()=>die3(evaluate2())),discard=(self)=>map14(self,()=>empty8()),context2=()=>fromEffectContext(context()),extendScope=(self)=>{let extendScope2=Object.create(proto3);return extendScope2._op_layer=OP_EXTEND_SCOPE,extendScope2.layer=self,extendScope2},fail6=(error)=>failCause5(fail3(error)),failSync2=(evaluate2)=>failCauseSync2(()=>fail3(evaluate2())),failCause5=(cause2)=>fromEffectContext(failCause(cause2)),failCauseSync2=(evaluate2)=>fromEffectContext(failCauseSync(evaluate2)),flatMap10=dual(2,(self,f)=>match11(self,{onFailure:fail6,onSuccess:f})),flatten7=dual(2,(self,tag)=>flatMap10(self,get5(tag))),fresh=(self)=>{let fresh2=Object.create(proto3);return fresh2._op_layer=OP_FRESH,fresh2.layer=self,fresh2},fromEffect3=dual(2,(a,b)=>{let tagFirst=isTag2(a),tag=tagFirst?a:b;return fromEffectContext(map10(tagFirst?b:a,(service)=>make9(tag,service)))}),fromEffectDiscard=(effect)=>fromEffectContext(map10(effect,()=>empty8()));function fromEffectContext(effect){let fromEffect4=Object.create(proto3);return fromEffect4._op_layer=OP_FROM_EFFECT,fromEffect4.effect=effect,fromEffect4}var fiberRefLocally2=dual(3,(self,ref,value)=>locallyEffect(self,fiberRefLocally(ref,value))),locallyEffect=dual(2,(self,f)=>{let locally=Object.create(proto3);return locally._op_layer="Locally",locally.self=self,locally.f=f,locally}),fiberRefLocallyWith2=dual(3,(self,ref,value)=>locallyEffect(self,fiberRefLocallyWith(ref,value))),fiberRefLocallyScoped2=(self,value)=>scopedDiscard(fiberRefLocallyScoped(self,value)),fiberRefLocallyScopedWith2=(self,value)=>scopedDiscard(fiberRefLocallyScopedWith(self,value)),fromFunction=(tagA,tagB,f)=>fromEffectContext(map10(tagA,(a)=>make9(tagB,f(a)))),launch=(self)=>scopedEffect(zipRight(scopeWith((scope2)=>pipe(self,buildWithScope(scope2))),never)),mock=function(){if(arguments.length===1)return(service)=>mockImpl(arguments[0],service);return mockImpl(arguments[0],arguments[1])},mockImpl=(tag,service)=>succeed5(tag,new Proxy({...service},{get(target,prop,_receiver){if(prop in target)return target[prop];let prevLimit=Error.stackTraceLimit;Error.stackTraceLimit=2;let error=Error(`${tag.key}: Unimplemented method "${prop.toString()}"`);return Error.stackTraceLimit=prevLimit,error.name="UnimplementedError",makeUnimplemented(error)},has:constTrue})),makeUnimplemented=(error)=>{let dead=die2(error);function unimplemented(){return dead}return Object.assign(unimplemented,dead),Object.setPrototypeOf(unimplemented,Object.getPrototypeOf(dead)),unimplemented},map14=dual(2,(self,f)=>flatMap10(self,(context3)=>succeedContext(f(context3)))),mapError2=dual(2,(self,f)=>catchAll2(self,(error)=>failSync2(()=>f(error)))),matchCause2=dual(2,(self,{onFailure,onSuccess})=>{let fold=Object.create(proto3);return fold._op_layer=OP_FOLD,fold.layer=self,fold.failureK=onFailure,fold.successK=onSuccess,fold}),match11=dual(2,(self,{onFailure,onSuccess})=>matchCause2(self,{onFailure:(cause2)=>{let failureOrCause3=failureOrCause2(cause2);switch(failureOrCause3._tag){case"Left":return onFailure(failureOrCause3.left);case"Right":return failCause5(failureOrCause3.right)}},onSuccess})),memoize2=(self)=>scopeWith((scope2)=>map10(memoize(buildWithScope(self,scope2)),fromEffectContext)),merge6=dual(2,(self,that)=>zipWith4(self,that,(a,b)=>merge3(a,b))),mergeAll4=(...layers)=>{let mergeAll5=Object.create(proto3);return mergeAll5._op_layer=OP_MERGE_ALL,mergeAll5.layers=layers,mergeAll5},orDie2=(self)=>catchAll2(self,(defect)=>die5(defect)),orElse4=dual(2,(self,that)=>catchAll2(self,that)),passthrough=(self)=>merge6(context2(),self),project=dual(4,(self,tagA,tagB,f)=>map14(self,(context3)=>make9(tagB,f(unsafeGet4(context3,tagA))))),retry=dual(2,(self,schedule)=>suspend2(()=>{let stateTag=GenericTag("effect/Layer/retry/{ state: unknown }");return pipe(succeed5(stateTag,{state:schedule.initial}),flatMap10((env)=>retryLoop(self,schedule,stateTag,pipe(env,get5(stateTag)).state)))})),retryLoop=(self,schedule,stateTag,state)=>{return pipe(self,catchAll2((error)=>pipe(retryUpdate(schedule,stateTag,error,state),flatMap10((env)=>fresh(retryLoop(self,schedule,stateTag,pipe(env,get5(stateTag)).state))))))},retryUpdate=(schedule,stateTag,error,state)=>{return fromEffect3(stateTag,pipe(currentTimeMillis2,flatMap8((now)=>pipe(schedule.step(now,error,state),flatMap8(([state2,_,decision])=>isDone4(decision)?fail2(error):pipe(sleep2(millis(start2(decision.intervals)-now)),as({state:state2})))))))},scoped=dual(2,(a,b)=>{let tagFirst=isTag2(a),tag=tagFirst?a:b;return scopedContext(map10(tagFirst?b:a,(service)=>make9(tag,service)))}),scopedDiscard=(effect)=>scopedContext(pipe(effect,as(empty8()))),scopedContext=(effect)=>{let scoped2=Object.create(proto3);return scoped2._op_layer=OP_SCOPED,scoped2.effect=effect,scoped2},scope2=scopedContext(map10(acquireRelease(scopeMake(),(scope3,exit2)=>scope3.close(exit2)),(scope3)=>make9(Scope,scope3))),service=(tag)=>fromEffect3(tag,tag),succeed5=dual(2,(a,b)=>{let tagFirst=isTag2(a);return fromEffectContext(succeed(make9(tagFirst?a:b,tagFirst?b:a)))}),succeedContext=(context3)=>{return fromEffectContext(succeed(context3))},empty26=succeedContext(empty8()),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(()=>make9(tag,evaluate2())))}),syncContext=(evaluate2)=>{return fromEffectContext(sync(evaluate2))},tap2=dual(2,(self,f)=>flatMap10(self,(context3)=>fromEffectContext(as(f(context3),context3)))),tapError2=dual(2,(self,f)=>catchAll2(self,(e)=>fromEffectContext(flatMap8(f(e),()=>fail2(e))))),tapErrorCause2=dual(2,(self,f)=>catchAllCause2(self,(cause2)=>fromEffectContext(flatMap8(f(cause2),()=>failCause(cause2))))),toRuntime=(self)=>pipe(scopeWith((scope3)=>buildWithScope(self,scope3)),flatMap8((context3)=>pipe(runtime2(),provideContext(context3)))),toRuntimeWithMemoMap=dual(2,(self,memoMap)=>flatMap8(scopeWith((scope3)=>buildWithMemoMap(self,memoMap,scope3)),(context3)=>pipe(runtime2(),provideContext(context3)))),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)?mergeAll4(...that):that},zipK:{value:(a,b)=>pipe(a,merge3(b))}}),provideTo.second=self,provideTo})),provideMerge=dual(2,(that,self)=>{let zipWith4=Object.create(proto3);return zipWith4._op_layer=OP_PROVIDE_MERGE,zipWith4.first=self,zipWith4.second=provide(that,self),zipWith4.zipK=(a,b)=>{return pipe(a,merge3(b))},zipWith4}),zipWith4=dual(3,(self,that,f)=>suspend2(()=>{let zipWith5=Object.create(proto3);return zipWith5._op_layer=OP_ZIP_WITH2,zipWith5.first=self,zipWith5.second=that,zipWith5.zipK=f,zipWith5})),unwrapEffect=(self)=>{let tag=GenericTag("effect/Layer/unwrapEffect/Layer.Layer<R1, E1, A>");return flatMap10(fromEffect3(tag,self),(context3)=>get5(context3,tag))},unwrapScoped=(self)=>{let tag=GenericTag("effect/Layer/unwrapScoped/Layer.Layer<R1, E1, A>");return flatMap10(scoped(tag,self),(context3)=>get5(context3,tag))},annotateLogs2=dual((args2)=>isLayer(args2[0]),function(){let args2=arguments;return fiberRefLocallyWith2(args2[0],currentLogAnnotations,typeof args2[1]==="string"?set3(args2[1],args2[2]):(annotations)=>Object.entries(args2[1]).reduce((acc,[key,value])=>set3(acc,key,value),annotations))}),annotateSpans2=dual((args2)=>isLayer(args2[0]),function(){let args2=arguments;return fiberRefLocallyWith2(args2[0],currentTracerSpanAnnotations,typeof args2[1]==="string"?set3(args2[1],args2[2]):(annotations)=>Object.entries(args2[1]).reduce((acc,[key,value])=>set3(acc,key,value),annotations))}),withSpan2=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 unwrapScoped(map10(options?.onEnd?tap(makeSpanScoped(name,options),(span2)=>addFinalizer((exit2)=>options.onEnd(span2,exit2))):makeSpanScoped(name,options),(span2)=>withParentSpan2(self,span2)))}return(self)=>unwrapScoped(map10(options?.onEnd?tap(makeSpanScoped(name,options),(span2)=>addFinalizer((exit2)=>options.onEnd(span2,exit2))):makeSpanScoped(name,options),(span2)=>withParentSpan2(self,span2)))},withParentSpan2=dual(2,(self,span2)=>provide(self,succeedContext(make9(spanTag,span2)))),provideSomeLayer=dual(2,(self,layer)=>scopedWith((scope3)=>flatMap8(buildWithScope(layer,scope3),(context3)=>provideSomeContext(self,context3)))),provideSomeRuntime=dual(2,(self,rt)=>{let patchRefs=diff6(defaultRuntime.fiberRefs,rt.fiberRefs),patchFlags=diff4(defaultRuntime.runtimeFlags,rt.runtimeFlags);return uninterruptibleMask((restore)=>withFiberRuntime((fiber)=>{let oldContext=fiber.getFiberRef(currentContext),oldRefs=fiber.getFiberRefs(),newRefs=patch7(fiber.id(),oldRefs)(patchRefs),oldFlags=fiber.currentRuntimeFlags,newFlags=patch4(patchFlags)(oldFlags),rollbackRefs=diff6(newRefs,oldRefs),rollbackFlags=diff4(newFlags,oldFlags);return fiber.setFiberRefs(newRefs),fiber.currentRuntimeFlags=newFlags,ensuring(provideSomeContext(restore(self),merge3(oldContext,rt.context)),withFiberRuntime((fiber2)=>{return fiber2.setFiberRefs(patch7(fiber2.id(),fiber2.getFiberRefs())(rollbackRefs)),fiber2.currentRuntimeFlags=patch4(rollbackFlags)(fiber2.currentRuntimeFlags),void_}))}))}),effect_provide=dual(2,(self,source)=>{if(Array.isArray(source))return provideSomeLayer(self,mergeAll4(...source));else if(isLayer(source))return provideSomeLayer(self,source);else if(isContext2(source))return provideSomeContext(self,source);else if(TypeId12 in source)return flatMap8(source.runtimeEffect,(rt)=>provideSomeRuntime(self,rt));else return provideSomeRuntime(self,source)});var console2=map10(fiberRefGet(currentServices),get5(consoleTag)),consoleWith=(f)=>fiberRefGetWith(currentServices,(services)=>f(get5(services,consoleTag))),withConsole=dual(2,(effect,value)=>fiberRefLocallyWith(effect,currentServices,add4(consoleTag,value))),withConsoleScoped=(console3)=>fiberRefLocallyScopedWith(currentServices,add4(consoleTag,console3)),setConsole=(console3)=>scopedDiscard(fiberRefLocallyScopedWith(currentServices,add4(consoleTag,console3))),assert=(condition,...args2)=>consoleWith((_)=>_.assert(condition,...args2)),clear=consoleWith((_)=>_.clear),count=(label)=>consoleWith((_)=>_.count(label)),countReset=(label)=>consoleWith((_)=>_.countReset(label)),debug=(...args2)=>consoleWith((_)=>_.debug(...args2)),dir=(item,options)=>consoleWith((_)=>_.dir(item,options)),dirxml=(...args2)=>consoleWith((_)=>_.dirxml(...args2)),error=(...args2)=>consoleWith((_)=>_.error(...args2)),group=(options)=>consoleWith((_)=>acquireRelease(_.group(options),()=>_.groupEnd)),info=(...args2)=>consoleWith((_)=>_.info(...args2)),log2=(...args2)=>consoleWith((_)=>_.log(...args2)),table=(tabularData,properties)=>consoleWith((_)=>_.table(tabularData,properties)),time=(label)=>consoleWith((_)=>acquireRelease(_.time(label),()=>_.timeEnd(label))),timeLog=(label,...args2)=>consoleWith((_)=>_.timeLog(label,...args2)),trace=(...args2)=>consoleWith((_)=>_.trace(...args2)),warn=(...args2)=>consoleWith((_)=>_.warn(...args2)),withGroup=dual((args2)=>isEffect(args2[0]),(self,options)=>consoleWith((_)=>acquireUseRelease(_.group(options),()=>self,()=>_.groupEnd))),withTime=dual((args2)=>isEffect(args2[0]),(self,label)=>consoleWith((_)=>acquireUseRelease(_.time(label),()=>self,()=>_.timeEnd(label))));var exports_Data={};__export(exports_Data,{unsafeStruct:()=>unsafeStruct,unsafeArray:()=>unsafeArray,tuple:()=>tuple,taggedEnum:()=>taggedEnum,tagged:()=>tagged2,struct:()=>struct2,case:()=>_case,array:()=>array3,TaggedError:()=>TaggedError,TaggedClass:()=>TaggedClass,Structural:()=>Structural2,Error:()=>Error3,Class:()=>Class2});var struct2=struct,unsafeStruct=(as3)=>Object.setPrototypeOf(as3,StructuralPrototype),tuple=(...as3)=>unsafeArray(as3),array3=(as3)=>unsafeArray(as3.slice(0)),unsafeArray=(as3)=>Object.setPrototypeOf(as3,ArrayProto),_case=()=>(args2)=>args2===void 0?Object.create(StructuralPrototype):struct2(args2);var tagged2=(tag)=>(args2)=>{let value=args2===void 0?Object.create(StructuralPrototype):struct2(args2);return value._tag=tag,value},Class2=Structural,TaggedClass=(tag)=>{class Base3 extends Class2{_tag=tag}return Base3},Structural2=Structural,taggedEnum=()=>new Proxy({},{get(_target,tag,_receiver){if(tag==="$is")return isTagged;else if(tag==="$match")return taggedMatch;return tagged2(tag)}});function taggedMatch(){if(arguments.length===1){let cases2=arguments[0];return function(value2){return cases2[value2._tag](value2)}}let value=arguments[0];return arguments[1][value._tag](value)}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 TypeId13=Symbol.for("effect/DateTime"),TimeZoneTypeId=Symbol.for("effect/DateTime/TimeZone"),Proto2={[TypeId13]:TypeId13,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}}},makeZonedProto=(epochMillis,zone,partsUtc)=>{let self=Object.create(ProtoZoned);return self.epochMillis=epochMillis,self.zone=zone,Object.defineProperty(self,"partsUtc",{value:partsUtc,enumerable:!1,writable:!0}),Object.defineProperty(self,"adjustedEpochMillis",{value:void 0,enumerable:!1,writable:!0}),Object.defineProperty(self,"partsAdjusted",{value:void 0,enumerable:!1,writable:!0}),self},isDateTime=(u)=>hasProperty(u,TypeId13),isDateTimeArgs=(args2)=>isDateTime(args2[0]),isTimeZone=(u)=>hasProperty(u,TimeZoneTypeId);var isTimeZoneNamed=(u)=>isTimeZone(u)&&u._tag==="Named";var isZoned=(self)=>self._tag==="Zoned";var makeUtc=(epochMillis)=>{let self=Object.create(ProtoUtc);return self.epochMillis=epochMillis,Object.defineProperty(self,"partsUtc",{value:void 0,enumerable:!1,writable:!0}),self},unsafeFromDate=(date)=>{let epochMillis=date.getTime();if(Number.isNaN(epochMillis))throw new IllegalArgumentException2("Invalid date");return makeUtc(epochMillis)},unsafeMake8=(input)=>{if(isDateTime(input))return input;else if(input instanceof Date)return unsafeFromDate(input);else if(typeof input==="object"){let date=new Date(0);return setPartsDate(date,input),unsafeFromDate(date)}else if(typeof input==="string"&&!hasZone(input))return unsafeFromDate(new Date(input+"Z"));return unsafeFromDate(new Date(input))},hasZone=(input)=>/Z|[+-]\d{2}$|[+-]\d{2}:?\d{2}$|\]$/.test(input),minEpochMillis=-8639999956800000,maxEpochMillis=8639999949600000,unsafeMakeZoned=(input,options)=>{if(options?.timeZone===void 0&&isDateTime(input)&&isZoned(input))return input;let self=unsafeMake8(input);if(self.epochMillis<minEpochMillis||self.epochMillis>maxEpochMillis)throw RangeError(`Epoch millis out of range: ${self.epochMillis}`);let zone;if(options?.timeZone===void 0){let offset=new Date(self.epochMillis).getTimezoneOffset()*-60*1000;zone=zoneMakeOffset(offset)}else if(isTimeZone(options?.timeZone))zone=options.timeZone;else if(typeof options?.timeZone==="number")zone=zoneMakeOffset(options.timeZone);else{let parsedZone=zoneFromString(options.timeZone);if(isNone2(parsedZone))throw new IllegalArgumentException2(`Invalid time zone: ${options.timeZone}`);zone=parsedZone.value}if(options?.adjustForTimeZone!==!0)return makeZonedProto(self.epochMillis,zone,self.partsUtc);return makeZonedFromAdjusted(self.epochMillis,zone,options?.disambiguation??"compatible")};var validZoneCache=globalValue("effect/DateTime/validZoneCache",()=>new Map),formatOptions={day:"numeric",month:"numeric",year:"numeric",hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"longOffset",fractionalSecondDigits:3,hourCycle:"h23"},zoneMakeIntl=(format4)=>{let zoneId=format4.resolvedOptions().timeZone;if(validZoneCache.has(zoneId))return validZoneCache.get(zoneId);let zone=Object.create(ProtoTimeZoneNamed);return zone.id=zoneId,zone.format=format4,validZoneCache.set(zoneId,zone),zone},zoneUnsafeMakeNamed=(zoneId)=>{if(validZoneCache.has(zoneId))return validZoneCache.get(zoneId);try{return zoneMakeIntl(new Intl.DateTimeFormat("en-US",{...formatOptions,timeZone:zoneId}))}catch{throw new IllegalArgumentException2(`Invalid time zone: ${zoneId}`)}},zoneMakeOffset=(offset)=>{let zone=Object.create(ProtoTimeZoneOffset);return zone.offset=offset,zone},zoneMakeNamed=liftThrowable(zoneUnsafeMakeNamed);var offsetZoneRegex=/^(?:GMT|[+-])/,zoneFromString=(zone)=>{if(offsetZoneRegex.test(zone)){let offset=parseOffset(zone);return offset===null?none2():some2(zoneMakeOffset(offset))}return zoneMakeNamed(zone)};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 abs=Math.abs(offset),hours2=Math.floor(abs/3600000),minutes2=Math.round(abs%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 dateToParts=(date)=>({millis:date.getUTCMilliseconds(),seconds:date.getUTCSeconds(),minutes:date.getUTCMinutes(),hours:date.getUTCHours(),day:date.getUTCDate(),weekDay:date.getUTCDay(),month:date.getUTCMonth()+1,year:date.getUTCFullYear()}),toParts=(self)=>{if(self._tag==="Utc")return toPartsUtc(self);else if(self.partsAdjusted!==void 0)return self.partsAdjusted;return self.partsAdjusted=withDate(self,dateToParts),self.partsAdjusted},toPartsUtc=(self)=>{if(self.partsUtc!==void 0)return self.partsUtc;return self.partsUtc=withDateUtc(self,dateToParts),self.partsUtc};var setPartsDate=(date,parts2)=>{if(parts2.year!==void 0)date.setUTCFullYear(parts2.year);if(parts2.month!==void 0)date.setUTCMonth(parts2.month-1);if(parts2.day!==void 0)date.setUTCDate(parts2.day);if(parts2.weekDay!==void 0){let diff8=parts2.weekDay-date.getUTCDay();date.setUTCDate(date.getUTCDate()+diff8)}if(parts2.hours!==void 0)date.setUTCHours(parts2.hours);if(parts2.minutes!==void 0)date.setUTCMinutes(parts2.minutes);if(parts2.seconds!==void 0)date.setUTCSeconds(parts2.seconds);if(parts2.millis!==void 0)date.setUTCMilliseconds(parts2.millis)};var constDayMillis=86400000,makeZonedFromAdjusted=(adjustedMillis,zone,disambiguation)=>{if(zone._tag==="Offset")return makeZonedProto(adjustedMillis-zone.offset,zone);let beforeOffset=calculateNamedOffset(adjustedMillis-constDayMillis,adjustedMillis,zone),afterOffset=calculateNamedOffset(adjustedMillis+constDayMillis,adjustedMillis,zone);if(beforeOffset===afterOffset)return makeZonedProto(adjustedMillis-beforeOffset,zone);let isForwards=beforeOffset<afterOffset,transitionMillis=beforeOffset-afterOffset;if(isForwards){if(calculateNamedOffset(adjustedMillis-afterOffset,adjustedMillis,zone)===afterOffset)return makeZonedProto(adjustedMillis-afterOffset,zone);let before2=makeZonedProto(adjustedMillis-beforeOffset,zone),beforeAdjustedMillis=toDate(before2).getTime();if(adjustedMillis!==beforeAdjustedMillis)switch(disambiguation){case"reject":{let formatted=new Date(adjustedMillis).toISOString();throw RangeError(`Gap time: ${formatted} does not exist in time zone ${zone.id}`)}case"earlier":return makeZonedProto(adjustedMillis-afterOffset,zone);case"compatible":case"later":return before2}return before2}if(calculateNamedOffset(adjustedMillis-beforeOffset,adjustedMillis,zone)===beforeOffset){if(disambiguation==="earlier"||disambiguation==="compatible")return makeZonedProto(adjustedMillis-beforeOffset,zone);if(calculateNamedOffset(adjustedMillis-beforeOffset+transitionMillis,adjustedMillis+transitionMillis,zone)===beforeOffset)return makeZonedProto(adjustedMillis-beforeOffset,zone);if(disambiguation==="reject"){let formatted=new Date(adjustedMillis).toISOString();throw RangeError(`Ambiguous time: ${formatted} occurs twice in time zone ${zone.id}`)}}return makeZonedProto(adjustedMillis-afterOffset,zone)},offsetRegex=/([+-])(\d{2}):(\d{2})$/,parseOffset=(offset)=>{let match12=offsetRegex.exec(offset);if(match12===null)return null;let[,sign,hours2,minutes2]=match12;return(sign==="+"?1:-1)*(Number(hours2)*60+Number(minutes2))*60*1000},calculateNamedOffset=(utcMillis,adjustedMillis,zone)=>{let offset=zone.format.formatToParts(utcMillis).find((_)=>_.type==="timeZoneName")?.value??"";if(offset==="GMT")return 0;let result=parseOffset(offset);if(result===null)return zonedOffset(makeZonedProto(adjustedMillis,zone));return result},mutate4=dual(isDateTimeArgs,(self,f,options)=>{if(self._tag==="Utc"){let date=toDateUtc(self);return f(date),makeUtc(date.getTime())}let adjustedDate=toDate(self),newAdjustedDate=new Date(adjustedDate.getTime());return f(newAdjustedDate),makeZonedFromAdjusted(newAdjustedDate.getTime(),self.zone,options?.disambiguation??"compatible")});var withDate=dual(2,(self,f)=>f(toDate(self))),withDateUtc=dual(2,(self,f)=>f(toDateUtc(self)));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 isNonEmpty5=(self)=>self.length>0;var TypeId14=Symbol.for("effect/Cron"),CronProto={[TypeId14]:TypeId14,[symbol2](that){return isCron(that)&&equals3(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,TypeId14),make38=(values3)=>{let o=Object.create(CronProto);o.seconds=new Set(sort(values3.seconds??[0],Order2)),o.minutes=new Set(sort(values3.minutes,Order2)),o.hours=new Set(sort(values3.hours,Order2)),o.days=new Set(sort(values3.days,Order2)),o.months=new Set(sort(values3.months,Order2)),o.weekdays=new Set(sort(values3.weekdays,Order2)),o.tz=fromNullable(values3.tz);let seconds2=Array.from(o.seconds),minutes2=Array.from(o.minutes),hours2=Array.from(o.hours),days2=Array.from(o.days),months=Array.from(o.months),weekdays=Array.from(o.weekdays);return o.first={second:seconds2[0]??0,minute:minutes2[0]??0,hour:hours2[0]??0,day:days2[0]??1,month:(months[0]??1)-1,weekday:weekdays[0]??0},o.next={second:nextLookupTable(seconds2,60),minute:nextLookupTable(minutes2,60),hour:nextLookupTable(hours2,24),day:nextLookupTable(days2,32),month:nextLookupTable(months,13),weekday:nextLookupTable(weekdays,7)},o},nextLookupTable=(values3,size9)=>{let result=Array(size9).fill(void 0);if(values3.length===0)return result;let current=void 0,index=values3.length-1;for(let i=size9-1;i>=0;i--){while(index>=0&&values3[index]>=i)current=values3[index--];result[i]=current}return result},ParseErrorTypeId=Symbol.for("effect/Cron/errors/ParseError");class ParseError extends TaggedError("CronParseError"){[ParseErrorTypeId]=ParseErrorTypeId}var parse=(cron,tz)=>{let segments=cron.split(" ").filter(isNonEmpty5);if(segments.length!==5&&segments.length!==6)return left2(new ParseError({message:"Invalid number of segments in cron expression",input:cron}));if(segments.length===5)segments.unshift("0");let[seconds2,minutes2,hours2,days2,months,weekdays]=segments,zone=tz===void 0||isTimeZone(tz)?right2(tz):fromOption2(zoneFromString(tz),()=>new ParseError({message:"Invalid time zone in cron expression",input:tz}));return all({tz:zone,seconds:parseSegment(seconds2,secondOptions),minutes:parseSegment(minutes2,minuteOptions),hours:parseSegment(hours2,hourOptions),days:parseSegment(days2,dayOptions),months:parseSegment(months,monthOptions),weekdays:parseSegment(weekdays,weekdayOptions)}).pipe(map(make38))};var match12=(cron,date)=>{let parts2=unsafeMakeZoned(date,{timeZone:getOrUndefined(cron.tz)}).pipe(toParts);if(cron.seconds.size!==0&&!cron.seconds.has(parts2.seconds))return!1;if(cron.minutes.size!==0&&!cron.minutes.has(parts2.minutes))return!1;if(cron.hours.size!==0&&!cron.hours.has(parts2.hours))return!1;if(cron.months.size!==0&&!cron.months.has(parts2.month))return!1;if(cron.days.size===0&&cron.weekdays.size===0)return!0;if(cron.weekdays.size===0)return cron.days.has(parts2.day);if(cron.days.size===0)return cron.weekdays.has(parts2.weekDay);return cron.days.has(parts2.day)||cron.weekdays.has(parts2.weekDay)},daysInMonth=(date)=>new Date(Date.UTC(date.getUTCFullYear(),date.getUTCMonth()+1,0)).getUTCDate(),next2=(cron,startFrom)=>{let tz=getOrUndefined(cron.tz),zoned=unsafeMakeZoned(startFrom??new Date,{timeZone:tz}),adjustDst=tz!==void 0&&isTimeZoneNamed(tz)&&tz.id==="UTC"?constVoid:(current)=>{let adjusted=unsafeMakeZoned(current,{timeZone:zoned.zone,adjustForTimeZone:!0}).pipe(toDate),drift=current.getTime()-adjusted.getTime();if(drift>0)current.setTime(current.getTime()+drift)},result=mutate4(zoned,(current)=>{current.setUTCSeconds(current.getUTCSeconds()+1,0);for(let i=0;i<1e4;i++){if(cron.seconds.size!==0){let currentSecond=current.getUTCSeconds(),nextSecond=cron.next.second[currentSecond];if(nextSecond===void 0){current.setUTCMinutes(current.getUTCMinutes()+1,cron.first.second),adjustDst(current);continue}if(nextSecond>currentSecond){current.setUTCSeconds(nextSecond),adjustDst(current);continue}}if(cron.minutes.size!==0){let currentMinute=current.getUTCMinutes(),nextMinute=cron.next.minute[currentMinute];if(nextMinute===void 0){current.setUTCHours(current.getUTCHours()+1,cron.first.minute,cron.first.second),adjustDst(current);continue}if(nextMinute>currentMinute){current.setUTCMinutes(nextMinute,cron.first.second),adjustDst(current);continue}}if(cron.hours.size!==0){let currentHour=current.getUTCHours(),nextHour=cron.next.hour[currentHour];if(nextHour===void 0){current.setUTCDate(current.getUTCDate()+1),current.setUTCHours(cron.first.hour,cron.first.minute,cron.first.second),adjustDst(current);continue}if(nextHour>currentHour){current.setUTCHours(nextHour,cron.first.minute,cron.first.second),adjustDst(current);continue}}if(cron.weekdays.size!==0||cron.days.size!==0){let a=1/0,b=1/0;if(cron.weekdays.size!==0){let currentWeekday=current.getUTCDay(),nextWeekday=cron.next.weekday[currentWeekday];a=nextWeekday===void 0?7-currentWeekday+cron.first.weekday:nextWeekday-currentWeekday}if(cron.days.size!==0&&a!==0){let currentDay=current.getUTCDate(),nextDay=cron.next.day[currentDay];b=nextDay===void 0?daysInMonth(current)-currentDay+cron.first.day:nextDay-currentDay}let addDays=Math.min(a,b);if(addDays!==0){current.setUTCDate(current.getUTCDate()+addDays),current.setUTCHours(cron.first.hour,cron.first.minute,cron.first.second),adjustDst(current);continue}}if(cron.months.size!==0){let currentMonth=current.getUTCMonth()+1,nextMonth=cron.next.month[currentMonth];if(nextMonth===void 0){current.setUTCFullYear(current.getUTCFullYear()+1),current.setUTCMonth(cron.first.month,cron.first.day),current.setUTCHours(cron.first.hour,cron.first.minute,cron.first.second),adjustDst(current);continue}if(nextMonth>currentMonth){current.setUTCMonth(nextMonth-1,cron.first.day),current.setUTCHours(cron.first.hour,cron.first.minute,cron.first.second),adjustDst(current);continue}}return}throw Error("Unable to find next cron date")});return toDateUtc(result)};var Equivalence2=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)),equals3=dual(2,(self,that)=>Equivalence2(self,that)),secondOptions={min:0,max:59},minuteOptions={min:0,max:59},hourOptions={min:0,max:23},dayOptions={min:1,max:31},monthOptions={min:1,max:12,aliases:{jan:1,feb:2,mar:3,apr:4,may:5,jun:6,jul:7,aug:8,sep:9,oct:10,nov:11,dec:12}},weekdayOptions={min:0,max:6,aliases:{sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6}},parseSegment=(input,options)=>{let capacity=options.max-options.min+1,values3=new Set,fields=input.split(",");for(let field of fields){let[raw,step3]=splitStep(field);if(raw==="*"&&step3===void 0)return right2(new Set);if(step3!==void 0){if(!Number.isInteger(step3))return left2(new ParseError({message:"Expected step value to be a positive integer",input}));if(step3<1)return left2(new ParseError({message:"Expected step value to be greater than 0",input}));if(step3>options.max)return left2(new ParseError({message:`Expected step value to be less than ${options.max}`,input}))}if(raw==="*")for(let i=options.min;i<=options.max;i+=step3??1)values3.add(i);else{let[left3,right3]=splitRange(raw,options.aliases);if(!Number.isInteger(left3))return left2(new ParseError({message:"Expected a positive integer",input}));if(left3<options.min||left3>options.max)return left2(new ParseError({message:`Expected a value between ${options.min} and ${options.max}`,input}));if(right3===void 0)values3.add(left3);else{if(!Number.isInteger(right3))return left2(new ParseError({message:"Expected a positive integer",input}));if(right3<options.min||right3>options.max)return left2(new ParseError({message:`Expected a value between ${options.min} and ${options.max}`,input}));if(left3>right3)return left2(new ParseError({message:"Invalid value range",input}));for(let i=left3;i<=right3;i+=step3??1)values3.add(i)}}if(values3.size>=capacity)return right2(new Set)}return right2(values3)},splitStep=(input)=>{let seperator=input.indexOf("/");if(seperator!==-1)return[input.slice(0,seperator),Number(input.slice(seperator+1))];return[input,void 0]},splitRange=(input,aliases)=>{let seperator=input.indexOf("-");if(seperator!==-1)return[aliasOrValue(input.slice(0,seperator),aliases),aliasOrValue(input.slice(seperator+1),aliases)];return[aliasOrValue(input,aliases),void 0]};function aliasOrValue(field,aliases){return aliases?.[field.toLocaleLowerCase()]??Number(field)}var next3=next;var fixed2=fixed;var ScheduleSymbolKey="effect/Schedule",ScheduleTypeId=Symbol.for(ScheduleSymbolKey),isSchedule=(u)=>hasProperty(u,ScheduleTypeId),ScheduleDriverSymbolKey="effect/ScheduleDriver",ScheduleDriverTypeId=Symbol.for(ScheduleDriverSymbolKey),defaultIterationMetadata={start:0,now:0,input:void 0,output:void 0,elapsed:zero,elapsedSincePrevious:zero,recurrence:0},CurrentIterationMetadata=Reference2()("effect/Schedule/CurrentIterationMetadata",{defaultValue:()=>defaultIterationMetadata}),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)}}var updateInfo=(iterationMetaRef,now,input,output)=>update2(iterationMetaRef,(prev)=>prev.recurrence===0?{now,input,output,recurrence:prev.recurrence+1,elapsed:zero,elapsedSincePrevious:zero,start:now}:{now,input,output,recurrence:prev.recurrence+1,elapsed:millis(now-prev.start),elapsedSincePrevious:millis(now-prev.now),start:prev.start});class ScheduleDriverImpl{schedule;ref;[ScheduleDriverTypeId]=scheduleDriverVariance;constructor(schedule,ref){this.schedule=schedule,this.ref=ref}get state(){return map10(get10(this.ref),(tuple2)=>tuple2[1])}get last(){return flatMap8(get10(this.ref),([element,_])=>{switch(element._tag){case"None":return failSync(()=>new NoSuchElementException);case"Some":return succeed(element.value)}})}iterationMeta=unsafeMake5(defaultIterationMetadata);get reset(){return set4(this.ref,[none2(),this.schedule.initial]).pipe(zipLeft(set4(this.iterationMeta,defaultIterationMetadata)))}next(input){return pipe(map10(get10(this.ref),(tuple2)=>tuple2[1]),flatMap8((state)=>pipe(currentTimeMillis2,flatMap8((now)=>pipe(suspend(()=>this.schedule.step(now,input,state)),flatMap8(([state2,out,decision])=>{let setState=set4(this.ref,[some2(out),state2]);if(isDone4(decision))return setState.pipe(zipRight(fail2(none2())));let millis2=start2(decision.intervals)-now;if(millis2<=0)return setState.pipe(zipRight(updateInfo(this.iterationMeta,now,input,out)),as(out));let duration=millis(millis2);return pipe(setState,zipRight(updateInfo(this.iterationMeta,now,input,out)),zipRight(sleep3(duration)),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))))),andThen4=dual(2,(self,that)=>map15(andThenEither(self,that),merge)),andThenEither=dual(2,(self,that)=>makeWithState([self.initial,that.initial,!0],(now,input,state)=>state[2]?flatMap8(self.step(now,input,state[0]),([lState,out,decision])=>{if(isDone4(decision))return map10(that.step(now,input,state[1]),([rState,out2,decision2])=>[[lState,rState,!1],right2(out2),decision2]);return succeed([[lState,state[1],!0],left2(out),decision])}):map10(that.step(now,input,state[1]),([rState,out,decision])=>[[state[0],rState,!1],right2(out),decision]))),as3=dual(2,(self,out)=>map15(self,()=>out)),asVoid2=(self)=>map15(self,constVoid),bothInOut=dual(2,(self,that)=>makeWithState([self.initial,that.initial],(now,[in1,in2],state)=>zipWith3(self.step(now,in1,state[0]),that.step(now,in2,state[1]),([lState,out,lDecision],[rState,out2,rDecision])=>{if(isContinue2(lDecision)&&isContinue2(rDecision)){let interval=pipe(lDecision.intervals,union7(rDecision.intervals));return[[lState,rState],[out,out2],_continue2(interval)]}return[[lState,rState],[out,out2],done5]}))),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(isDone4(decision))return succeed([state2,out,done5]);return map10(test(input,out),(cont)=>cont?[state2,out,decision]:[state2,out,done5])}))),collectAllInputs=()=>collectAllOutputs(identity2()),collectAllOutputs=(self)=>reduce10(self,empty2(),(outs,out)=>pipe(outs,append2(out))),collectUntil=(f)=>collectAllOutputs(recurUntil(f)),collectUntilEffect=(f)=>collectAllOutputs(recurUntilEffect(f)),collectWhile=(f)=>collectAllOutputs(recurWhile(f)),collectWhileEffect=(f)=>collectAllOutputs(recurWhileEffect(f)),compose=dual(2,(self,that)=>makeWithState([self.initial,that.initial],(now,input,state)=>flatMap8(self.step(now,input,state[0]),([lState,out,lDecision])=>map10(that.step(now,out,state[1]),([rState,out2,rDecision])=>isDone4(lDecision)?[[lState,rState],out2,done5]:isDone4(rDecision)?[[lState,rState],out2,done5]:[[lState,rState],out2,_continue2(pipe(lDecision.intervals,max5(rDecision.intervals)))])))),mapInput3=dual(2,(self,f)=>mapInputEffect(self,(input2)=>sync(()=>f(input2)))),mapInputContext2=dual(2,(self,f)=>makeWithState(self.initial,(now,input,state)=>mapInputContext(self.step(now,input,state),f))),mapInputEffect=dual(2,(self,f)=>makeWithState(self.initial,(now,input2,state)=>flatMap8(f(input2),(input)=>self.step(now,input,state)))),cron=(expression,tz)=>{let parsed=isCron(expression)?right2(expression):parse(expression,tz);return makeWithState([!0,[Number.MIN_SAFE_INTEGER,0,0]],(now,_,[initial,previous])=>{if(now<previous[0])return succeed([[!1,previous],[previous[1],previous[2]],continueWith2(make33(previous[1],previous[2]))]);if(isLeft2(parsed))return die2(parsed.left);let cron2=parsed.right,date=new Date(now),next4;if(initial&&match12(cron2,date))next4=now;next4=next2(cron2,date).getTime();let start3=beginningOfSecond(next4),end3=endOfSecond(next4);return succeed([[!1,[next4,start3,end3]],[start3,end3],continueWith2(make33(start3,end3))])})},dayOfMonth=(day)=>{return makeWithState([Number.NEGATIVE_INFINITY,0],(now,_,state)=>{if(!Number.isInteger(day)||day<1||31<day)return dieSync(()=>new IllegalArgumentException(`Invalid argument in: dayOfMonth(${day}). Must be in range 1...31`));let n=state[1],day0=nextDayOfMonth(now,day,n===0),start3=beginningOfDay(day0),end3=endOfDay(day0),interval=make33(start3,end3);return succeed([[end3,n+1],n,continueWith2(interval)])})},dayOfWeek=(day)=>{return makeWithState([Number.MIN_SAFE_INTEGER,0],(now,_,state)=>{if(!Number.isInteger(day)||day<1||7<day)return dieSync(()=>new IllegalArgumentException(`Invalid argument in: dayOfWeek(${day}). Must be in range 1 (Monday)...7 (Sunday)`));let n=state[1],day0=nextDay(now,day,n===0),start3=beginningOfDay(day0),end3=endOfDay(day0),interval=make33(start3,end3);return succeed([[end3,n+1],n,continueWith2(interval)])})},delayed=dual(2,(self,f)=>delayedEffect(self,(duration)=>sync(()=>f(duration)))),delayedEffect=dual(2,(self,f)=>modifyDelayEffect(self,(_,delay2)=>f(delay2))),delayedSchedule=(schedule)=>addDelay(schedule,(x)=>x),delays=(self)=>makeWithState(self.initial,(now,input,state)=>pipe(self.step(now,input,state),flatMap8(([state2,_,decision])=>{if(isDone4(decision))return succeed([state2,zero,decision]);return succeed([state2,millis(start2(decision.intervals)-now),decision])}))),mapBoth3=dual(2,(self,{onInput,onOutput})=>map15(mapInput3(self,onInput),onOutput)),mapBothEffect=dual(2,(self,{onInput,onOutput})=>mapEffect2(mapInputEffect(self,onInput),onOutput)),driver=(self)=>pipe(make23([none2(),self.initial]),map10((ref)=>new ScheduleDriverImpl(self,ref))),duration=(durationInput)=>{let duration2=decode(durationInput),durationMillis=toMillis(duration2);return makeWithState(!0,(now,_,state)=>succeed(state?[!1,duration2,continueWith2(after2(now+durationMillis))]:[!1,zero,done5]))},either3=dual(2,(self,that)=>union8(self,that)),eitherWith=dual(3,(self,that,f)=>unionWith2(self,that,f)),ensuring2=dual(2,(self,finalizer)=>makeWithState(self.initial,(now,input,state)=>flatMap8(self.step(now,input,state),([state2,out,decision])=>isDone4(decision)?as(finalizer,[state2,out,decision]):succeed([state2,out,decision])))),exponential2=(baseInput,factor=2)=>{let base=decode(baseInput);return delayedSchedule(map15(forever2,(i)=>times(base,Math.pow(factor,i))))},fibonacci=(oneInput)=>{let one=decode(oneInput);return delayedSchedule(pipe(unfold2([one,one],([a,b])=>[b,sum(a,b)]),map15((out)=>out[0])))},fixed3=(intervalInput)=>{let interval=decode(intervalInput),intervalMillis=toMillis(interval);return makeWithState([none2(),0],(now,_,[option2,n])=>sync(()=>{switch(option2._tag){case"None":return[[some2([now,now+intervalMillis]),n+1],n,continueWith2(after2(now+intervalMillis))];case"Some":{let[startMillis,lastRun]=option2.value,runningBehind=now>lastRun+intervalMillis,boundary=equals(interval,zero)?interval:millis(intervalMillis-(now-startMillis)%intervalMillis),sleepTime=equals(boundary,zero)?interval:boundary,nextRun=runningBehind?now:now+toMillis(sleepTime);return[[some2([startMillis,nextRun]),n+1],n,continueWith2(after2(nextRun))]}}}))},fromDelay=(delay2)=>duration(delay2),fromDelays=(delay2,...delays2)=>makeWithState([[delay2,...delays2].map((_)=>decode(_)),!0],(now,_,[durations,cont])=>sync(()=>{if(cont){let x=durations[0],interval=after2(now+toMillis(x));if(durations.length>=2)return[[durations.slice(1),!0],x,continueWith2(interval)];let y=durations.slice(1);return[[[x,...y],!1],x,continueWith2(interval)]}return[[durations,!1],zero,done5]})),fromFunction2=(f)=>map15(identity2(),f),hourOfDay=(hour)=>makeWithState([Number.NEGATIVE_INFINITY,0],(now,_,state)=>{if(!Number.isInteger(hour)||hour<0||23<hour)return dieSync(()=>new IllegalArgumentException(`Invalid argument in: hourOfDay(${hour}). Must be in range 0...23`));let n=state[1],hour0=nextHour(now,hour,n===0),start3=beginningOfHour(hour0),end3=endOfHour(hour0),interval=make33(start3,end3);return succeed([[end3,n+1],n,continueWith2(interval)])}),identity2=()=>makeWithState(void 0,(now,input,state)=>succeed([state,input,continueWith2(after2(now))])),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],done5])})))),intersectWithLoop=(self,that,input,lState,out,lInterval,rState,out2,rInterval,f)=>{let combined=f(lInterval,rInterval);if(isNonEmpty4(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(isDone4(decision))return succeed([[lState2,rState],[out3,out2],done5]);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(isDone4(decision))return succeed([[lState,rState2],[out,out22],done5]);return intersectWithLoop(self,that,input,lState,out,lInterval,rState2,out22,decision.intervals,f)})},jittered=(self)=>jitteredWith(self,{min:0.8,max:1.2}),jitteredWith=dual(2,(self,options)=>{let{max:max6,min:min4}=Object.assign({min:0.8,max:1.2},options);return delayedEffect(self,(duration2)=>map10(next3,(random3)=>{let d=toMillis(duration2),jittered2=d*min4*(1-random3)+d*max6*random3;return millis(jittered2)}))}),linear=(baseInput)=>{let base=decode(baseInput);return delayedSchedule(map15(forever2,(i)=>times(base,i+1)))},map15=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])))),minuteOfHour=(minute)=>makeWithState([Number.MIN_SAFE_INTEGER,0],(now,_,state)=>{if(!Number.isInteger(minute)||minute<0||59<minute)return dieSync(()=>new IllegalArgumentException(`Invalid argument in: minuteOfHour(${minute}). Must be in range 0...59`));let n=state[1],minute0=nextMinute(now,minute,n===0),start3=beginningOfMinute(minute0),end3=endOfMinute(minute0),interval=make33(start3,end3);return succeed([[end3,n+1],n,continueWith2(interval)])}),modifyDelay=dual(2,(self,f)=>modifyDelayEffect(self,(out,duration2)=>sync(()=>f(out,duration2)))),modifyDelayEffect=dual(2,(self,f)=>makeWithState(self.initial,(now,input,state)=>flatMap8(self.step(now,input,state),([state2,out,decision])=>{if(isDone4(decision))return succeed([state2,out,decision]);let intervals=decision.intervals,delay2=size8(make33(now,start2(intervals)));return map10(f(out,delay2),(durationInput)=>{let duration2=decode(durationInput),oldStart=start2(intervals),newStart=now+toMillis(duration2),delta=newStart-oldStart,newEnd=Math.max(0,end2(intervals)+delta),newInterval=make33(newStart,newEnd);return[state2,out,continueWith2(newInterval)]})}))),onDecision=dual(2,(self,f)=>makeWithState(self.initial,(now,input,state)=>flatMap8(self.step(now,input,state),([state2,out,decision])=>as(f(out,decision),[state2,out,decision])))),passthrough2=(self)=>makeWithState(self.initial,(now,input,state)=>pipe(self.step(now,input,state),map10(([state2,_,decision])=>[state2,input,decision]))),provideContext3=dual(2,(self,context3)=>makeWithState(self.initial,(now,input,state)=>provideContext(self.step(now,input,state),context3))),provideService2=dual(3,(self,tag,service2)=>makeWithState(self.initial,(now,input,state)=>contextWithEffect((env)=>provideContext(self.step(now,input,state),add4(env,tag,service2))))),recurUntil=(f)=>untilInput(identity2(),f),recurUntilEffect=(f)=>untilInputEffect(identity2(),f),recurUntilOption=(pf)=>untilOutput(map15(identity2(),pf),isSome2),recurUpTo=(durationInput)=>{let duration2=decode(durationInput);return whileOutput(elapsed,(elapsed)=>lessThan2(elapsed,duration2))},recurWhile=(f)=>whileInput(identity2(),f),recurWhileEffect=(f)=>whileInputEffect(identity2(),f),recurs=(n)=>whileOutput(forever2,(out)=>out<n),reduce10=dual(3,(self,zero2,f)=>reduceEffect2(self,zero2,(z,out)=>sync(()=>f(z,out)))),reduceEffect2=dual(3,(self,zero2,f)=>makeWithState([self.initial,zero2],(now,input,[s,z])=>flatMap8(self.step(now,input,s),([s2,out,decision])=>isDone4(decision)?succeed([[s2,z],z,decision]):map10(f(z,out),(z2)=>[[s2,z2],z,decision]))));var repetitions=(self)=>reduce10(self,0,(n,_)=>n+1),resetAfter=dual(2,(self,durationInput)=>{let duration2=decode(durationInput);return pipe(self,intersect5(elapsed),resetWhen(([,time2])=>greaterThanOrEqualTo(time2,duration2)),map15((out)=>out[0]))}),resetWhen=dual(2,(self,f)=>makeWithState(self.initial,(now,input,state)=>flatMap8(self.step(now,input,state),([state2,out,decision])=>f(out)?self.step(now,input,self.initial):succeed([state2,out,decision])))),run=dual(3,(self,now,input)=>pipe(runLoop(self,now,fromIterable2(input),self.initial,empty2()),map10((list)=>reverse2(list)))),runLoop=(self,now,inputs,state,acc)=>{if(!isNonEmpty(inputs))return succeed(acc);let input=headNonEmpty2(inputs),nextInputs=tailNonEmpty2(inputs);return flatMap8(self.step(now,input,state),([state2,out,decision])=>{if(isDone4(decision))return sync(()=>pipe(acc,prepend2(out)));return runLoop(self,start2(decision.intervals),nextInputs,state2,prepend2(acc,out))})},secondOfMinute=(second)=>makeWithState([Number.NEGATIVE_INFINITY,0],(now,_,state)=>{if(!Number.isInteger(second)||second<0||59<second)return dieSync(()=>new IllegalArgumentException(`Invalid argument in: secondOfMinute(${second}). Must be in range 0...59`));let n=state[1],second0=nextSecond(now,second,n===0),start3=beginningOfSecond(second0),end3=endOfSecond(second0),interval=make33(start3,end3);return succeed([[end3,n+1],n,continueWith2(interval)])}),spaced=(duration2)=>addDelay(forever2,()=>duration2),succeed6=(value)=>map15(forever2,()=>value),sync3=(evaluate2)=>map15(forever2,evaluate2),tapInput=dual(2,(self,f)=>makeWithState(self.initial,(now,input,state)=>zipRight(f(input),self.step(now,input,state)))),tapOutput=dual(2,(self,f)=>makeWithState(self.initial,(now,input,state)=>tap(self.step(now,input,state),([,out])=>f(out)))),unfold2=(initial,f)=>makeWithState(initial,(now,_,state)=>sync(()=>[f(state),state,continueWith2(after2(now))])),union8=dual(2,(self,that)=>unionWith2(self,that,union7)),unionWith2=dual(3,(self,that,f)=>makeWithState([self.initial,that.initial],(now,input,state)=>zipWith3(self.step(now,input,state[0]),that.step(now,input,state[1]),([lState,l,lDecision],[rState,r,rDecision])=>{if(isDone4(lDecision)&&isDone4(rDecision))return[[lState,rState],[l,r],done5];if(isDone4(lDecision)&&isContinue2(rDecision))return[[lState,rState],[l,r],_continue2(rDecision.intervals)];if(isContinue2(lDecision)&&isDone4(rDecision))return[[lState,rState],[l,r],_continue2(lDecision.intervals)];if(isContinue2(lDecision)&&isContinue2(rDecision)){let combined=f(lDecision.intervals,rDecision.intervals);return[[lState,rState],[l,r],_continue2(combined)]}throw Error("BUG: Schedule.unionWith - please report an issue at https://github.com/Effect-TS/effect/issues")}))),untilInput=dual(2,(self,f)=>check(self,(input,_)=>!f(input))),untilInputEffect=dual(2,(self,f)=>checkEffect(self,(input,_)=>negate(f(input)))),untilOutput=dual(2,(self,f)=>check(self,(_,out)=>!f(out))),untilOutputEffect=dual(2,(self,f)=>checkEffect(self,(_,out)=>negate(f(out)))),upTo=dual(2,(self,duration2)=>zipLeft2(self,recurUpTo(duration2))),whileInput=dual(2,(self,f)=>check(self,(input,_)=>f(input))),whileInputEffect=dual(2,(self,f)=>checkEffect(self,(input,_)=>f(input))),whileOutput=dual(2,(self,f)=>check(self,(_,out)=>f(out))),whileOutputEffect=dual(2,(self,f)=>checkEffect(self,(_,out)=>f(out))),windowed=(intervalInput)=>{let interval=decode(intervalInput),millis2=toMillis(interval);return makeWithState([none2(),0],(now,_,[option2,n])=>{switch(option2._tag){case"None":return succeed([[some2(now),n+1],n,continueWith2(after2(now+millis2))]);case"Some":return succeed([[some2(option2.value),n+1],n,continueWith2(after2(now+(millis2-(now-option2.value)%millis2)))])}})},zipLeft2=dual(2,(self,that)=>map15(intersect5(self,that),(out)=>out[0])),zipRight3=dual(2,(self,that)=>map15(intersect5(self,that),(out)=>out[1])),zipWith5=dual(3,(self,that,f)=>map15(intersect5(self,that),([out,out2])=>f(out,out2))),beginningOfSecond=(now)=>{let date=new Date(now);return new Date(date.getFullYear(),date.getMonth(),date.getDate(),date.getHours(),date.getMinutes(),date.getSeconds(),0).getTime()},endOfSecond=(now)=>{let date=new Date(beginningOfSecond(now));return date.setSeconds(date.getSeconds()+1)},nextSecond=(now,second,initial)=>{let date=new Date(now);if(date.getSeconds()===second&&initial)return now;if(date.getSeconds()<second)return date.setSeconds(second);let newDate=new Date(date.setSeconds(second));return newDate.setTime(newDate.getTime()+60000)},beginningOfMinute=(now)=>{let date=new Date(now);return new Date(date.getFullYear(),date.getMonth(),date.getDate(),date.getHours(),date.getMinutes(),0,0).getTime()},endOfMinute=(now)=>{let date=new Date(beginningOfMinute(now));return date.setMinutes(date.getMinutes()+1)},nextMinute=(now,minute,initial)=>{let date=new Date(now);if(date.getMinutes()===minute&&initial)return now;if(date.getMinutes()<minute)return date.setMinutes(minute);let newDate=new Date(date.setMinutes(minute));return newDate.setTime(newDate.getTime()+3600000)},beginningOfHour=(now)=>{let date=new Date(now);return new Date(date.getFullYear(),date.getMonth(),date.getDate(),date.getHours(),0,0,0).getTime()},endOfHour=(now)=>{let date=new Date(beginningOfHour(now));return date.setHours(date.getHours()+1)},nextHour=(now,hour,initial)=>{let date=new Date(now);if(date.getHours()===hour&&initial)return now;if(date.getHours()<hour)return date.setHours(hour);let newDate=new Date(date.setHours(hour));return newDate.setTime(newDate.getTime()+86400000)},beginningOfDay=(now)=>{let date=new Date(now);return new Date(date.getFullYear(),date.getMonth(),date.getDate(),0,0,0,0).getTime()},endOfDay=(now)=>{let date=new Date(beginningOfDay(now));return date.setDate(date.getDate()+1)},nextDay=(now,dayOfWeek2,initial)=>{let date=new Date(now);if(date.getDay()===dayOfWeek2&&initial)return now;let nextDayOfWeek=(7+dayOfWeek2-date.getDay())%7;return date.setDate(date.getDate()+(nextDayOfWeek===0?7:nextDayOfWeek))},nextDayOfMonth=(now,day,initial)=>{let date=new Date(now);if(date.getDate()===day&&initial)return now;if(date.getDate()<day)return date.setDate(day);return findNextMonth(now,day,1)},findNextMonth=(now,day,months)=>{let d=new Date(now),tmp1=new Date(d.setDate(day));if(new Date(tmp1.setMonth(tmp1.getMonth()+months)).getDate()===day){let d2=new Date(now),tmp3=new Date(d2.setDate(day));return tmp3.setMonth(tmp3.getMonth()+months)}return findNextMonth(now,day,months+1)},ScheduleDefectTypeId=Symbol.for("effect/Schedule/ScheduleDefect");class ScheduleDefect{error;[ScheduleDefectTypeId];constructor(error2){this.error=error2,this[ScheduleDefectTypeId]=ScheduleDefectTypeId}}var isScheduleDefect=(u)=>hasProperty(u,ScheduleDefectTypeId),scheduleDefectWrap=(self)=>catchAll(self,(e)=>die2(new ScheduleDefect(e))),scheduleDefectRefailCause=(cause2)=>match2(find(cause2,(_)=>isDieType(_)&&isScheduleDefect(_.defect)?some2(_.defect):none2()),{onNone:()=>cause2,onSome:(error2)=>fail(error2.error)}),scheduleDefectRefail=(effect)=>catchAllCause(effect,(cause2)=>failCause(scheduleDefectRefailCause(cause2))),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??passthrough2(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(map15((intersectionPair)=>intersectionPair[0])):withUntil;return scheduleDefectRefail(repeat_Effect(self,withTimes))}),repeatOrElse_Effect=dual(3,(self,schedule,orElse5)=>flatMap8(driver(schedule),(driver2)=>matchEffect(self,{onFailure:(error2)=>orElse5(error2,none2()),onSuccess:(value)=>repeatOrElseEffectLoop(provideServiceEffect(self,CurrentIterationMetadata,get10(driver2.iterationMeta)),driver2,(error2,option2)=>provideServiceEffect(orElse5(error2,option2),CurrentIterationMetadata,get10(driver2.iterationMeta)),value)}))),repeatOrElseEffectLoop=(self,driver2,orElse5,value)=>matchEffect(driver2.next(value),{onFailure:()=>orDie(driver2.last),onSuccess:(b)=>matchEffect(self,{onFailure:(error2)=>orElse5(error2,some2(b)),onSuccess:(value2)=>repeatOrElseEffectLoop(self,driver2,orElse5,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);return scheduleDefectRefail(retry_Effect(self,fromRetryOptions(options)))}),fromRetryOptions=(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;return options.times!==void 0?intersect5(withUntil,recurs(options.times)):withUntil},retryOrElse_Effect=dual(3,(self,policy,orElse5)=>flatMap8(driver(policy),(driver2)=>retryOrElse_EffectLoop(provideServiceEffect(self,CurrentIterationMetadata,get10(driver2.iterationMeta)),driver2,(e,out)=>provideServiceEffect(orElse5(e,out),CurrentIterationMetadata,get10(driver2.iterationMeta))))),retryOrElse_EffectLoop=(self,driver2,orElse5)=>{return catchAll(self,(e)=>matchEffect(driver2.next(e),{onFailure:()=>pipe(driver2.last,orDie,flatMap8((out)=>orElse5(e,out))),onSuccess:()=>retryOrElse_EffectLoop(self,driver2,orElse5)}))},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(provideServiceEffect(self,CurrentIterationMetadata,get10(driver2.iterationMeta)),initial,driver2))),scheduleFrom_EffectLoop=(self,initial,driver2)=>matchEffect(driver2.next(initial),{onFailure:()=>orDie(driver2.last),onSuccess:()=>flatMap8(self,(a)=>scheduleFrom_EffectLoop(self,a,driver2))}),count2=unfold2(0,(n)=>n+1),elapsed=makeWithState(none2(),(now,_,state)=>{switch(state._tag){case"None":return succeed([some2(now),zero,continueWith2(after2(now))]);case"Some":return succeed([some2(state.value),millis(now-state.value),continueWith2(after2(now))])}}),forever2=unfold2(0,(n)=>n+1),once2=asVoid2(recurs(1)),stop=asVoid2(recurs(0)),scheduleForked=dual(2,(self,schedule)=>forkScoped(schedule_Effect(self,schedule)));var withExecutionPlan=dual(2,(effect,plan)=>suspend(()=>{let i=0,result;return flatMap8(whileLoop({while:()=>i<plan.steps.length&&(result===void 0||isLeft2(result)),body:()=>{let step3=plan.steps[i],nextEffect=effect_provide(effect,step3.provide);if(result){let attempted=!1,wrapped=nextEffect;nextEffect=suspend(()=>{if(attempted)return wrapped;return attempted=!0,result}),nextEffect=scheduleDefectRefail(retry_Effect(nextEffect,scheduleFromStep(step3,!1)))}else{let schedule=scheduleFromStep(step3,!0);nextEffect=schedule?scheduleDefectRefail(retry_Effect(nextEffect,schedule)):nextEffect}return either2(nextEffect)},step:(either4)=>{result=either4,i++}}),()=>result)})),scheduleFromStep=(step3,first)=>{if(!first)return fromRetryOptions({schedule:step3.schedule?step3.schedule:step3.attempts?void 0:once2,times:step3.attempts,while:step3.while});else if(step3.attempts===1||!(step3.schedule||step3.attempts))return;return fromRetryOptions({schedule:step3.schedule,while:step3.while,times:step3.attempts?step3.attempts-1:void 0})};var make39=deferredMake;var _await3=deferredAwait;var done7=deferredDone,fail7=deferredFail;var failCause6=deferredFailCause;var interrupt6=deferredInterrupt;var isDone5=deferredIsDone,poll3=deferredPoll,succeed7=deferredSucceed;var unsafeMake9=deferredUnsafeMake,unsafeDone=deferredUnsafeDone;var TypeId15=Symbol.for("effect/MutableList"),MutableListProto={[TypeId15]:TypeId15,[Symbol.iterator](){let done8=!1,head4=this.head;return{next(){if(done8)return this.return();if(head4==null)return done8=!0,this.return();let value=head4.value;return head4=head4.next,{done:done8,value}},return(value){if(!done8)done8=!0;return{done:!0,value}}}},toString(){return format(this.toJSON())},toJSON(){return{_id:"MutableList",values:Array.from(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}},makeNode=(value)=>({value,removed:!1,prev:void 0,next:void 0}),empty27=()=>{let list=Object.create(MutableListProto);return list.head=void 0,list.tail=void 0,list._length=0,list};var isEmpty8=(self)=>length(self)===0,length=(self)=>self._length;var append3=dual(2,(self,value)=>{let node=makeNode(value);if(self.head===void 0)self.head=node;if(self.tail===void 0)self.tail=node;else self.tail.next=node,node.prev=self.tail,self.tail=node;return self._length+=1,self}),shift=(self)=>{let head4=self.head;if(head4!==void 0)return remove6(self,head4),head4.value;return};var remove6=(self,node)=>{if(node.removed)return;if(node.removed=!0,node.prev!==void 0&&node.next!==void 0)node.prev.next=node.next,node.next.prev=node.prev;else if(node.prev!==void 0)self.tail=node.prev,node.prev.next=void 0;else if(node.next!==void 0)self.head=node.next,node.next.prev=void 0;else self.tail=void 0,self.head=void 0;if(self._length>0)self._length-=1};var TypeId16=Symbol.for("effect/MutableQueue"),EmptyMutableQueue=Symbol.for("effect/mutable/MutableQueue/Empty"),MutableQueueProto={[TypeId16]:TypeId16,[Symbol.iterator](){return Array.from(this.queue)[Symbol.iterator]()},toString(){return format(this.toJSON())},toJSON(){return{_id:"MutableQueue",values:Array.from(this).map(toJSON)}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}},make40=(capacity)=>{let queue=Object.create(MutableQueueProto);return queue.queue=empty27(),queue.capacity=capacity,queue},bounded=(capacity)=>make40(capacity),unbounded=()=>make40(void 0),length2=(self)=>length(self.queue),isEmpty9=(self)=>isEmpty8(self.queue);var capacity=(self)=>self.capacity===void 0?1/0:self.capacity,offer=dual(2,(self,value)=>{let queueLength=length(self.queue);if(self.capacity!==void 0&&queueLength===self.capacity)return!1;return append3(value)(self.queue),!0}),offerAll=dual(2,(self,values3)=>{let iterator=values3[Symbol.iterator](),next4,remainder=empty2(),offering=!0;while(offering&&(next4=iterator.next())&&!next4.done)offering=offer(next4.value)(self);while(next4!=null&&!next4.done)remainder=prepend2(next4.value)(remainder),next4=iterator.next();return reverse2(remainder)}),poll4=dual(2,(self,def)=>{if(isEmpty8(self.queue))return def;return shift(self.queue)}),pollUpTo=dual(2,(self,n)=>{let result=empty2(),count3=0;while(count3<n){let element=poll4(EmptyMutableQueue)(self);if(element===EmptyMutableQueue)break;result=prepend2(element)(result),count3+=1}return reverse2(result)});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:next4}=key;if(next4!==void 0)if(key.next=void 0,previous!==void 0)previous.next=next4,next4.previous=previous;else this.head=next4,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 next4=key.next;if(next4!==void 0)key.next=void 0,this.head=next4,this.head.previous=void 0;else this.head=void 0,this.tail=void 0}return key}}var makeKeySet=()=>new KeySetImpl,makeCacheState=(map16,keys3,accesses,updating,hits,misses)=>({map:map16,keys:keys3,accesses,updating,hits,misses}),initialCacheState=()=>makeCacheState(empty21(),makeKeySet(),unbounded(),make11(!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,context3,fiberId2,lookup,timeToLive){this.capacity=capacity2,this.context=context3,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:size6(this.cacheState.map)}))}getOption(key){return suspend(()=>match2(get12(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(get12(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=get12(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(get12(this.cacheState.map,k));if(value===void 0)if(deferred=unsafeMake9(this.fiberId),mapKey=makeMapKey(k),has4(this.cacheState.map,k))value=getOrUndefined(get12(this.cacheState.map,k));else set6(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(()=>{remove5(this.cacheState.map,key)})}invalidateWhen(key,when2){return sync(()=>{let value=get12(this.cacheState.map,key);if(isSome2(value)&&value.value._tag==="Complete"){if(value.value.exit._tag==="Success"){if(when2(value.value.exit.value))remove5(this.cacheState.map,key)}}})}get invalidateAll(){return sync(()=>{this.cacheState.map=empty21()})}refresh(key){return clockWith3((clock2)=>suspend(()=>{let k=key,deferred=unsafeMake9(this.fiberId),value=getOrUndefined(get12(this.cacheState.map,k));if(value===void 0)if(has4(this.cacheState.map,k))value=getOrUndefined(get12(this.cacheState.map,k));else set6(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(get12(this.cacheState.map,k));if(equals(found,value))remove5(this.cacheState.map,k);return asVoid(this.get(key))}return pipe(this.lookupValueOf(key,deferred),when(()=>{let current=getOrUndefined(get12(this.cacheState.map,k));if(equals(current,value)){let mapValue=refreshing(deferred,value);return set6(this.cacheState.map,k,mapValue),!0}return!1}),asVoid)}case"Pending":return _await3(value.deferred);case"Refreshing":return _await3(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))));set6(this.cacheState.map,k,mapValue)}))}get size(){return sync(()=>{return size6(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 keys3=[];for(let entry of this.cacheState.map)if(entry[1]._tag==="Complete"&&entry[1].exit._tag==="Success")keys3.push(entry[0]);return keys3})}resolveMapValue(value,ignorePending=!1){return clockWith3((clock2)=>{switch(value._tag){case"Complete":{if(this.trackAccess(value.key),this.hasExpired(clock2,value.timeToLiveMillis))return remove5(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(_await3(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(_await3(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=poll4(this.cacheState.accesses,EmptyMutableQueue);if(key2===EmptyMutableQueue)loop2=!1;else this.cacheState.keys.add(key2)}let size9=size6(this.cacheState.map);loop2=size9>this.capacity;while(loop2){let key2=this.cacheState.keys.remove();if(key2!==void 0){if(has4(this.cacheState.map,key2.current))remove5(this.cacheState.map,key2.current),size9=size9-1,loop2=size9>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 set6(this.cacheState.map,key,value),zipRight(done7(deferred,exit2),exit2)}),onInterrupt(()=>zipRight(interrupt6(deferred),sync(()=>{remove5(this.cacheState.map,key)}))))}))}}var unsafeMakeWith=(capacity2,lookup,timeToLive)=>new CacheImpl(capacity2,empty8(),none3,lookup,(exit2)=>decode(timeToLive(exit2)));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((id2)=>{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(empty16,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:id2,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:id2,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,once3=once,all5=all4,allWith2=allWith,allSuccesses2=allSuccesses,dropUntil2=dropUntil,dropWhile3=dropWhile2,takeUntil2=takeUntil,takeWhile3=takeWhile2,every6=every5,exists2=exists,filter7=filter6,filterMap5=filterMap4,findFirst6=findFirst5,forEach6=forEach5,head4=head3,mergeAll5=mergeAll3,partition4=partition3,reduce11=reduce9,reduceWhile2=reduceWhile,reduceRight4=reduceRight3,reduceEffect3=reduceEffect,replicate2=replicate,replicateEffect2=replicateEffect,validateAll2=validateAll,validateFirst2=validateFirst,async=async_,asyncEffect2=asyncEffect,custom2=custom,withFiberRuntime2=withFiberRuntime,fail9=fail2,failSync3=failSync,failCause8=failCause,failCauseSync3=failCauseSync,die6=die2,dieMessage2=dieMessage,dieSync3=dieSync,gen2=gen,never3=never,none9=none6,promise2=promise,succeed9=succeed,succeedNone2=succeedNone,succeedSome2=succeedSome,suspend3=suspend,sync4=sync,_void=void_;var yieldNow4=yieldNow,_catch2=_catch;var catchAll3=catchAll,catchAllCause3=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,retry2=retry_combined,withExecutionPlan2=withExecutionPlan,retryOrElse=retryOrElse_Effect,try_3=try_2;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,liftPredicate3=liftPredicate2,as4=as,asSome2=asSome,asSomeError2=asSomeError,asVoid3=asVoid,flip2=flip,flipWith2=flipWith,map16=map10,mapAccum4=mapAccum3,mapBoth4=mapBoth,mapError3=mapError,mapErrorCause2=mapErrorCause,merge7=merge5,negate2=negate,acquireRelease2=acquireRelease,acquireReleaseInterruptible2=acquireReleaseInterruptible,acquireUseRelease2=acquireUseRelease,addFinalizer3=addFinalizer,ensuring3=ensuring,onError2=onError,onExit3=onExit,parallelFinalizers2=parallelFinalizers,sequentialFinalizers2=sequentialFinalizers,finalizersMask2=finalizersMask,scope3=scope,scopeWith2=scopeWith,scopedWith2=scopedWith,scoped2=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,mapInputContext3=mapInputContext,provide2=effect_provide,provideService3=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,either4=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,flatMap11=flatMap8,andThen5=andThen2,flatten8=flatten5,race2=race,raceAll2=raceAll,raceFirst2=raceFirst,raceWith2=raceWith,summarized2=summarized,tap3=tap,tapBoth2=tapBoth,tapDefect2=tapDefect,tapError3=tapError,tapErrorTag2=tapErrorTag,tapErrorCause3=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=isSuccess,match13=match8,matchCause3=matchCause,matchCauseEffect3=matchCauseEffect,matchEffect2=matchEffect,log3=log,logWithLevel2=(level,...message)=>logWithLevel(level)(...message),logTrace2=logTrace,logDebug2=logDebug,logInfo2=logInfo,logWarning2=logWarning,logError2=logError,logFatal2=logFatal,withLogSpan2=withLogSpan,annotateLogs3=annotateLogs,annotateLogsScoped2=annotateLogsScoped,logAnnotations2=logAnnotations,withUnhandledErrorLogLevel2=withUnhandledErrorLogLevel,whenLogLevel2=whenLogLevel,orDie3=orDie,orDieWith2=orDieWith,orElse5=orElse2,orElseFail2=orElseFail,orElseSucceed2=orElseSucceed,firstSuccessOf2=firstSuccessOf,random3=random2,randomWith2=randomWith,withRandom2=withRandom,withRandomFixed=dual(2,(effect,values3)=>withRandom2(effect,fixed2(values3))),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,zip5=zipOptions,zipLeft3=zipLeftOptions,zipRight4=zipRightOptions,zipWith6=zipWithOptions,ap=dual(2,(self,that)=>zipWith6(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,annotateSpans3=annotateSpans,annotateCurrentSpan2=annotateCurrentSpan,currentSpan2=currentSpan,currentParentSpan2=currentParentSpan,spanAnnotations2=spanAnnotations,spanLinks2=spanLinks,linkSpans2=linkSpans,linkSpanCurrent2=linkSpanCurrent,makeSpan2=makeSpan,makeSpanScoped2=makeSpanScoped,useSpan2=useSpan,withSpan3=withSpan,functionWithSpan2=functionWithSpan,withSpanScoped2=withSpanScoped,withParentSpan3=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]);Object.assign(fn,cn);let{apply,bind:bind4,call}=fn,proto4=Object.setPrototypeOf({},Object.getPrototypeOf(cn));return proto4.apply=apply,proto4.bind=bind4,proto4.call=call,Object.setPrototypeOf(fn,proto4),cache.set(prop,fn),fn}})},Tag3=(id2)=>()=>{let limit=Error.stackTraceLimit;Error.stackTraceLimit=2;let creationError=Error();Error.stackTraceLimit=limit;function TagClass(){}return Object.setPrototypeOf(TagClass,TagProto),TagClass.key=id2,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[id2,maker]=arguments,proxy="accessors"in maker?maker.accessors:!1,limit=Error.stackTraceLimit;Error.stackTraceLimit=2;let creationError=Error();Error.stackTraceLimit=limit;let patchState="unchecked",TagClass=function(service2){if(patchState==="unchecked"){let proto4=Object.getPrototypeOf(service2);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,service2);else if(patchState==="patched")return Object.setPrototypeOf(service2,Object.getPrototypeOf(this)),service2};TagClass.prototype._tag=id2,Object.defineProperty(TagClass,"make",{get(){return(service2)=>new this(service2)}}),Object.defineProperty(TagClass,"use",{get(){return(body)=>andThen2(this,body)}}),TagClass.key=id2,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,isFunction3=!1;if("effect"in maker)isFunction3=typeof maker.effect==="function",Object.defineProperty(TagClass,layerName,{get(){if(isFunction3)return function(){return fromEffect3(TagClass,map16(maker.effect.apply(null,arguments),(_)=>new this(_)))}.bind(this);return layerCache??=fromEffect3(TagClass,map16(maker.effect,(_)=>new this(_)))}});else if("scoped"in maker)isFunction3=typeof maker.scoped==="function",Object.defineProperty(TagClass,layerName,{get(){if(isFunction3)return function(){return scoped(TagClass,map16(maker.scoped.apply(null,arguments),(_)=>new this(_)))}.bind(this);return layerCache??=scoped(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??=succeed5(TagClass,new this(maker.succeed))}});if(hasDeps){let layerWithDepsCache;Object.defineProperty(TagClass,"Default",{get(){if(isFunction3)return function(){return provide(this.DefaultWithoutDependencies.apply(null,arguments),maker.dependencies)};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=Error();if(Error.stackTraceLimit=limit,typeof nameOrBody!=="string")return defineLength(nameOrBody.length,function(...args2){let limit2=Error.stackTraceLimit;Error.stackTraceLimit=2;let errorCall=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,{[name](...args2){let limit2=Error.stackTraceLimit;Error.stackTraceLimit=2;let errorCall=Error();return Error.stackTraceLimit=limit2,fnApply({self:this,body,args:args2,pipeables:pipeables2,spanName:name,spanOptions:options,errorDef,errorCall})}}[name])};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(error2){fnError=error2,effect=die6(error2)}if(options.pipeables.length>0)try{for(let x of options.pipeables)effect=x(effect,...options.args)}catch(error2){effect=fnError?failCause8(sequential(die(fnError),die(error2))):die6(error2)}let cache=!1,captureStackTrace=()=>{if(cache!==!1)return cache;if(options.errorCall.stack){let stackDef=options.errorDef.stack.trim().split(`
32
32
  `),stackCall=options.errorCall.stack.trim().split(`
33
33
  `),endStackDef=stackDef.slice(2).join(`
34
34
  `).trim();if(!endStackDef.includes("("))endStackDef=endStackDef.replace(/at (.*)/,"at ($1)");let endStackCall=stackCall.slice(2).join(`
@@ -38,7 +38,7 @@ ${endStackCall}`,cache}},opts=options.spanOptions&&"captureStackTrace"in options
38
38
  `,from);else stringBuilder=stringBuilder+"\r";midCRLF=!1}while(indexOfCR!==-1||indexOfLF!==-1)if(indexOfCR===-1||indexOfLF!==-1&&indexOfLF<indexOfCR){if(stringBuilder.length===0)chunkBuilder.push(str.substring(from,indexOfLF));else chunkBuilder.push(stringBuilder+str.substring(from,indexOfLF)),stringBuilder="";from=indexOfLF+1,indexOfLF=str.indexOf(`
39
39
  `,from)}else if(str.length===indexOfCR+1)midCRLF=!0,indexOfCR=-1;else if(indexOfLF===indexOfCR+1){if(stringBuilder.length===0)chunkBuilder.push(str.substring(from,indexOfCR));else stringBuilder=stringBuilder+str.substring(from,indexOfCR),chunkBuilder.push(stringBuilder),stringBuilder="";from=indexOfCR+2,indexOfCR=str.indexOf("\r",from),indexOfLF=str.indexOf(`
40
40
  `,from)}else indexOfCR=str.indexOf("\r",indexOfCR+1);if(midCRLF)stringBuilder=stringBuilder+str.substring(from,str.length-1);else stringBuilder=stringBuilder+str.substring(from,str.length)}}),unsafeFromArray(chunkBuilder)},loop3=readWithCause({onInput:(input)=>{let out=splitLinesChunk(input);return isEmpty(out)?loop3:flatMap13(write(out),()=>loop3)},onFailure:(cause3)=>stringBuilder.length===0?failCause10(cause3):flatMap13(write(of2(stringBuilder)),()=>failCause10(cause3)),onDone:(done8)=>stringBuilder.length===0?succeed12(done8):flatMap13(write(of2(stringBuilder)),()=>succeed12(done8))});return loop3}),toPubSub=(pubsub)=>toQueue(pubsub),toPull=(self)=>flatMap11(scope3,(scope5)=>toPullIn(self,scope5)),toPullIn=dual(2,(self,scope5)=>zip5(sync4(()=>new ChannelExecutor(self,void 0,identity)),runtime3()).pipe(tap3(([executor,runtime4])=>addFinalizerExit(scope5,(exit3)=>{let finalizer=executor.close(exit3);return finalizer!==void 0?provide2(finalizer,runtime4):_void})),uninterruptible2,map16(([executor])=>suspend3(()=>interpretToPull(executor.run(),executor))))),interpretToPull=(channelState,exec)=>{let state=channelState;switch(state._tag){case OP_DONE3:return match9(exec.getDone(),{onFailure:failCause8,onSuccess:(done8)=>succeed9(left2(done8))});case OP_EMIT2:return succeed9(right2(exec.getEmit()));case OP_FROM_EFFECT3:return pipe(state.effect,flatMap11(()=>interpretToPull(exec.run(),exec)));case OP_READ2:return readUpstream(state,()=>interpretToPull(exec.run(),exec),(cause3)=>failCause8(cause3))}},toQueue=(queue)=>suspend5(()=>toQueueInternal(queue)),toQueueInternal=(queue)=>{return readWithCause({onInput:(elem)=>flatMap13(fromEffect4(offer3(queue,right2(elem))),()=>toQueueInternal(queue)),onFailure:(cause3)=>fromEffect4(offer3(queue,left2(failCause3(cause3)))),onDone:(done8)=>fromEffect4(offer3(queue,left2(succeed3(done8))))})},unwrap=(channel)=>flatten10(fromEffect4(channel)),unwrapScoped3=(self)=>concatAllWith(scoped4(self),(d,_)=>d,(d,_)=>d),unwrapScopedWith=(f)=>concatAllWith(scopedWith3(f),(d,_)=>d,(d,_)=>d);var withSpan5=function(){let dataFirst=typeof arguments[0]!=="string",name=dataFirst?arguments[1]:arguments[0],options=addSpanStackTrace(dataFirst?arguments[2]:arguments[1]),acquire=all5([makeSpan2(name,options),context3(),clock2,get13(currentTracerTimingEnabled2)]);if(dataFirst){let self=arguments[0];return acquireUseRelease3(acquire,([span4,context5])=>provideContext5(self,add4(context5,spanTag,span4)),([span4,,clock3,timingEnabled],exit3)=>endSpan(span4,exit3,clock3,timingEnabled))}return(self)=>acquireUseRelease3(acquire,([span4,context5])=>provideContext5(self,add4(context5,spanTag,span4)),([span4,,clock3,timingEnabled],exit3)=>endSpan(span4,exit3,clock3,timingEnabled))},writeAll=(...outs)=>writeChunk(fromIterable2(outs)),writeChunk=(outs)=>writeChunkWriter(0,outs.length,outs),writeChunkWriter=(idx,len,chunk2)=>{return idx===len?void_5:pipe(write(pipe(chunk2,unsafeGet2(idx))),flatMap13(()=>writeChunkWriter(idx+1,len,chunk2)))},zip6=dual((args2)=>isChannel(args2[1]),(self,that,options)=>options?.concurrent?mergeWith2(self,{other:that,onSelfDone:(exit1)=>Await((exit22)=>suspend3(()=>zip3(exit1,exit22))),onOtherDone:(exit22)=>Await((exit1)=>suspend3(()=>zip3(exit1,exit22)))}):flatMap13(self,(a)=>map19(that,(b)=>[a,b]))),zipLeft5=dual((args2)=>isChannel(args2[1]),(self,that,options)=>options?.concurrent?map19(zip6(self,that,{concurrent:!0}),(tuple2)=>tuple2[0]):flatMap13(self,(z)=>as6(that,z))),zipRight6=dual((args2)=>isChannel(args2[1]),(self,that,options)=>options?.concurrent?map19(zip6(self,that,{concurrent:!0}),(tuple2)=>tuple2[1]):flatMap13(self,()=>that)),ChannelExceptionTypeId=Symbol.for("effect/Channel/ChannelException"),ChannelException=(error2)=>({_tag:"ChannelException",[ChannelExceptionTypeId]:ChannelExceptionTypeId,error:error2}),isChannelException=(u)=>hasProperty(u,ChannelExceptionTypeId);var Done4=Done3,Await2=Await;var TypeId17=Symbol.for("effect/RcRef"),stateEmpty2={_tag:"Empty"},stateClosed={_tag:"Closed"},variance5={_A:identity,_E:identity};class RcRefImpl extends Class{acquire;context;scope;idleTimeToLive;[TypeId17]=variance5;[TypeId10]=TypeId10;state=stateEmpty2;semaphore=unsafeMakeSemaphore(1);constructor(acquire,context5,scope5,idleTimeToLive){super();this.acquire=acquire,this.context=context5,this.scope=scope5,this.idleTimeToLive=idleTimeToLive,this.get=get14(this)}get;commit(){return this.get}}var make43=(options)=>withFiberRuntime((fiber)=>{let context5=fiber.getFiberRef(currentContext),scope5=get5(context5,scopeTag),ref=new RcRefImpl(options.acquire,context5,scope5,options.idleTimeToLive?decode(options.idleTimeToLive):void 0);return as(scope5.addFinalizer(()=>ref.semaphore.withPermits(1)(suspend(()=>{let close2=ref.state._tag==="Acquired"?scopeClose(ref.state.scope,exitVoid):void_;return ref.state=stateClosed,close2}))),ref)}),get14=(self_)=>{let self=self_,isInfinite=self.idleTimeToLive&&!isFinite(self.idleTimeToLive);return uninterruptibleMask((restore)=>suspend(()=>{switch(self.state._tag){case"Closed":return interrupt2;case"Acquired":return self.state.refCount++,self.state.fiber?as(interruptFiber(self.state.fiber),self.state):succeed(self.state);case"Empty":return scopeMake().pipe(bindTo2("scope"),bind2("value",({scope:scope5})=>restore(fiberRefLocally(self.acquire,currentContext,add4(self.context,scopeTag,scope5)))),map10(({scope:scope5,value})=>{let state={_tag:"Acquired",value,scope:scope5,fiber:void 0,refCount:1};return self.state=state,state}))}})).pipe(self.semaphore.withPermits(1),bindTo2("state"),bind2("scope",()=>scopeTag),tap(({scope:scope5,state})=>scope5.addFinalizer(()=>suspend(()=>{if(state.refCount--,state.refCount>0||isInfinite)return void_;if(self.idleTimeToLive===void 0)return self.state=stateEmpty2,scopeClose(state.scope,exitVoid);return sleep3(self.idleTimeToLive).pipe(interruptible2,zipRight(suspend(()=>{if(self.state._tag==="Acquired"&&self.state.refCount===0)return self.state=stateEmpty2,scopeClose(state.scope,exitVoid);return void_})),ensuring(sync(()=>{state.fiber=void 0})),forkIn(self.scope),tap((fiber)=>{state.fiber=fiber}),self.semaphore.withPermits(1))}))),map10(({state})=>state.value))};var make44=make43,get15=get14;var runFork3=unsafeFork2;var runPromiseExit2=unsafeRunPromiseExit,defaultRuntime2=defaultRuntime;var OP_LEFT="Left",OP_RIGHT="Right",OP_BOTH="Both",OP_EITHER="Either";var Left={_tag:OP_LEFT},Right={_tag:OP_RIGHT},Both={_tag:OP_BOTH},Either={_tag:OP_EITHER},fromInput2=(input)=>{switch(input){case"left":return Left;case"right":return Right;case"both":return Both;case"either":return Either;default:return input}};var Both2=Both;var SinkTypeId2=Symbol.for("effect/Sink"),sinkVariance2={_A:(_)=>_,_In:(_)=>_,_L:(_)=>_,_E:(_)=>_,_R:(_)=>_};class SinkImpl{channel;[SinkTypeId2]=sinkVariance2;constructor(channel){this.channel=channel}pipe(){return pipeArguments(this,arguments)}}var isSink=(u)=>hasProperty(u,SinkTypeId2),suspend6=(evaluate2)=>new SinkImpl(suspend5(()=>toChannel(evaluate2())));var collectAll=()=>new SinkImpl(collectAllLoop(empty2())),collectAllLoop=(acc)=>readWithCause({onInput:(chunk2)=>collectAllLoop(pipe(acc,appendAll2(chunk2))),onFailure:failCause10,onDone:()=>succeed12(acc)}),collectAllN=(n)=>suspend6(()=>fromChannel(collectAllNLoop(n,empty2()))),collectAllNLoop=(n,acc)=>readWithCause({onInput:(chunk2)=>{let[collected,leftovers]=splitAt2(chunk2,n);if(collected.length<n)return collectAllNLoop(n-collected.length,appendAll2(acc,collected));if(isEmpty(leftovers))return succeed12(appendAll2(acc,collected));return flatMap13(write(leftovers),()=>succeed12(appendAll2(acc,collected)))},onFailure:failCause10,onDone:()=>succeed12(acc)});var collectLeftover=(self)=>new SinkImpl(pipe(collectElements(toChannel(self)),map19(([chunks,z])=>[z,flatten2(chunks)])));var drain2=new SinkImpl(drain(identityChannel()));var fail12=(e)=>new SinkImpl(fail11(e));var fold=(s,contFn,f)=>suspend6(()=>new SinkImpl(foldReader(s,contFn,f))),foldReader=(s,contFn,f)=>{if(!contFn(s))return succeedNow(s);return readWith({onInput:(input)=>{let[nextS,leftovers]=foldChunkSplit(s,input,contFn,f,0,input.length);if(isNonEmpty(leftovers))return pipe(write(leftovers),as6(nextS));return foldReader(nextS,contFn,f)},onFailure:fail11,onDone:()=>succeedNow(s)})},foldChunkSplit=(s,chunk2,contFn,f,index,length3)=>{if(index===length3)return[s,empty2()];let s1=f(s,pipe(chunk2,unsafeGet2(index)));if(contFn(s1))return foldChunkSplit(s1,chunk2,contFn,f,index+1,length3);return[s1,pipe(chunk2,drop2(index+1))]},foldSink=dual(2,(self,options)=>{let newChannel=pipe(toChannel(self),collectElements,foldChannel({onFailure:(error2)=>toChannel(options.onFailure(error2)),onSuccess:([leftovers,z])=>suspend5(()=>{let leftoversRef={ref:pipe(leftovers,filter2(isNonEmpty))},refReader=pipe(sync7(()=>{let ref=leftoversRef.ref;return leftoversRef.ref=empty2(),ref}),flatMap13((chunk2)=>writeChunk(chunk2))),passthrough5=identityChannel(),continuationSink=pipe(refReader,zipRight6(passthrough5),pipeTo(toChannel(options.onSuccess(z))));return flatMap13(collectElements(continuationSink),([newLeftovers,z1])=>pipe(succeed12(leftoversRef.ref),flatMap13(writeChunk),zipRight6(writeChunk(newLeftovers)),as6(z1)))})}));return new SinkImpl(newChannel)}),foldChunks=(s,contFn,f)=>suspend6(()=>new SinkImpl(foldChunksReader(s,contFn,f))),foldChunksReader=(s,contFn,f)=>{if(!contFn(s))return succeedNow(s);return readWith({onInput:(input)=>foldChunksReader(f(s,input),contFn,f),onFailure:fail11,onDone:()=>succeedNow(s)})};var foldEffect=(s,contFn,f)=>suspend6(()=>new SinkImpl(foldEffectReader(s,contFn,f))),foldEffectReader=(s,contFn,f)=>{if(!contFn(s))return succeedNow(s);return readWith({onInput:(input)=>pipe(fromEffect4(foldChunkSplitEffect(s,input,contFn,f)),flatMap13(([nextS,leftovers])=>pipe(leftovers,match2({onNone:()=>foldEffectReader(nextS,contFn,f),onSome:(leftover)=>pipe(write(leftover),as6(nextS))})))),onFailure:fail11,onDone:()=>succeedNow(s)})},foldChunkSplitEffect=(s,chunk2,contFn,f)=>foldChunkSplitEffectInternal(s,chunk2,0,chunk2.length,contFn,f),foldChunkSplitEffectInternal=(s,chunk2,index,length3,contFn,f)=>{if(index===length3)return succeed9([s,none2()]);return pipe(f(s,pipe(chunk2,unsafeGet2(index))),flatMap11((s1)=>contFn(s1)?foldChunkSplitEffectInternal(s1,chunk2,index+1,length3,contFn,f):succeed9([s1,some2(pipe(chunk2,drop2(index+1)))])))};var foldLeftChunks=(s,f)=>foldChunks(s,constTrue,f);var flatMap14=dual(2,(self,f)=>foldSink(self,{onFailure:fail12,onSuccess:f})),forEach7=(f)=>{let process2=readWithCause({onInput:(input)=>pipe(fromEffect4(forEach6(input,(v)=>f(v),{discard:!0})),flatMap13(()=>process2)),onFailure:failCause10,onDone:()=>void_5});return new SinkImpl(process2)},forEachChunk=(f)=>{let process2=readWithCause({onInput:(input)=>pipe(fromEffect4(f(input)),flatMap13(()=>process2)),onFailure:failCause10,onDone:()=>void_5});return new SinkImpl(process2)},forEachWhile=(f)=>{let process2=readWithCause({onInput:(input)=>forEachWhileReader(f,input,0,input.length,process2),onFailure:failCause10,onDone:()=>void_5});return new SinkImpl(process2)},forEachWhileReader=(f,input,index,length3,cont)=>{if(index===length3)return cont;return pipe(fromEffect4(f(pipe(input,unsafeGet2(index)))),flatMap13((bool)=>bool?forEachWhileReader(f,input,index+1,length3,cont):write(pipe(input,drop2(index)))),catchAll5((error2)=>pipe(write(pipe(input,drop2(index))),zipRight6(fail11(error2)))))};var fromChannel=(channel)=>new SinkImpl(channel),fromEffect6=(effect3)=>new SinkImpl(fromEffect4(effect3));var head5=()=>fold(none2(),isNone2,(option3,input)=>match2(option3,{onNone:()=>some2(input),onSome:()=>option3}));var last3=()=>foldLeftChunks(none2(),(s,input)=>orElse(last2(input),()=>s));var map20=dual(2,(self,f)=>{return new SinkImpl(pipe(toChannel(self),map19(f)))});var raceWith3=dual(2,(self,options)=>{function race3(scope5){return gen2(function*(){let pubsub=yield*bounded5(options?.capacity??16),subscription1=yield*extend2(subscribe2(pubsub),scope5),subscription2=yield*extend2(subscribe2(pubsub),scope5),reader=toPubSub(pubsub),writer=fromQueue(subscription1).pipe(pipeTo(toChannel(self)),zipLeft5(fromEffect4(shutdown2(subscription1))),mergeWith2({other:fromQueue(subscription2).pipe(pipeTo(toChannel(options.other)),zipLeft5(fromEffect4(shutdown2(subscription2)))),onSelfDone:options.onSelfDone,onOtherDone:options.onOtherDone})),racedChannel=mergeWith2(reader,{other:writer,onSelfDone:()=>Await(identity),onOtherDone:(exit3)=>Done3(exit3)});return new SinkImpl(racedChannel)})}return unwrapScopedWith2(race3)});var sum2=foldLeftChunks(0,(acc,chunk2)=>acc+reduce2(chunk2,0,(s,a)=>s+a));var toChannel=(self)=>isEffect2(self)?toChannel(fromEffect6(self)):self.channel;var unwrapScopedWith2=(f)=>new SinkImpl(unwrapScopedWith((scope5)=>f(scope5).pipe(map16((sink)=>toChannel(sink)))));var zipRight7=dual((args2)=>isSink(args2[1]),(self,that,options)=>zipWith9(self,that,(_,z2)=>z2,options)),zipWith9=dual((args2)=>isSink(args2[1]),(self,that,f,options)=>options?.concurrent?raceWith3(self,{other:that,onSelfDone:match9({onFailure:(cause3)=>Done3(failCause8(cause3)),onSuccess:(leftZ)=>Await(match9({onFailure:failCause8,onSuccess:(rightZ)=>succeed9(f(leftZ,rightZ))}))}),onOtherDone:match9({onFailure:(cause3)=>Done3(failCause8(cause3)),onSuccess:(rightZ)=>Await(match9({onFailure:failCause8,onSuccess:(leftZ)=>succeed9(f(leftZ,rightZ))}))})}):flatMap14(self,(z)=>map20(that,(z2)=>f(z,z2))));var count4=foldLeftChunks(0,(acc,chunk2)=>acc+chunk2.length),mkString=suspend6(()=>{let strings=[];return pipe(foldLeftChunks(void 0,(_,elems)=>map4(elems,(elem)=>{strings.push(String(elem))})),map20(()=>strings.join("")))});class Versioned{value;constructor(value){this.value=value}}var make45=(ref,isNew)=>({ref,isNew,isChanged:!1,expected:ref.versioned,newValue:ref.versioned.value}),unsafeGet6=(self)=>{return self.newValue},unsafeSet=(self,value)=>{self.isChanged=!0,self.newValue=value},commit=(self)=>{self.ref.versioned=new Versioned(self.newValue)};var isInvalid=(self)=>{return self.ref.versioned!==self.expected},isChanged=(self)=>{return self.isChanged};var JournalAnalysisInvalid="Invalid",JournalAnalysisReadWrite="ReadWrite",JournalAnalysisReadOnly="ReadOnly",commitJournal=(journal)=>{for(let entry of journal)commit(entry[1])},analyzeJournal=(journal)=>{let val=JournalAnalysisReadOnly;for(let[,entry]of journal)if(val=isInvalid(entry)?JournalAnalysisInvalid:isChanged(entry)?JournalAnalysisReadWrite:val,val===JournalAnalysisInvalid)return val;return val};var collectTodos=(journal)=>{let allTodos=new Map;for(let[,entry]of journal){for(let todo of entry.ref.todos)allTodos.set(todo[0],todo[1]);entry.ref.todos=new Map}return allTodos},execTodos=(todos)=>{let todosSorted=Array.from(todos.entries()).sort((x,y)=>x[0]-y[0]);for(let[_,todo]of todosSorted)todo()},addTodo=(txnId,journal,todoEffect)=>{let added=!1;for(let[,entry]of journal)if(!entry.ref.todos.has(txnId))entry.ref.todos.set(txnId,todoEffect),added=!0;return added};var OP_WITH_STM_RUNTIME="WithSTMRuntime",OP_ON_FAILURE2="OnFailure",OP_ON_RETRY="OnRetry",OP_ON_SUCCESS2="OnSuccess",OP_PROVIDE3="Provide",OP_SYNC2="Sync",OP_SUCCEED2="Succeed",OP_RETRY="Retry",OP_FAIL4="Fail",OP_DIE2="Die",OP_INTERRUPT2="Interrupt";var OP_FAIL5="Fail",OP_DIE3="Die",OP_INTERRUPT3="Interrupt",OP_SUCCEED3="Succeed",OP_RETRY2="Retry";var OP_DONE5="Done",OP_SUSPEND3="Suspend";var OP_DONE6="Done",OP_INTERRUPTED="Interrupted",OP_RUNNING2="Running";var STMStateSymbolKey="effect/STM/State",STMStateTypeId=Symbol.for(STMStateSymbolKey),isSTMState=(u)=>hasProperty(u,STMStateTypeId),isRunning2=(self)=>{return self._tag===OP_RUNNING2},isDone6=(self)=>{return self._tag===OP_DONE6};var done8=(exit3)=>{return{[STMStateTypeId]:STMStateTypeId,_tag:OP_DONE6,exit:exit3,[symbol](){return pipe(hash(STMStateSymbolKey),combine(hash(OP_DONE6)),combine(hash(exit3)),cached(this))},[symbol2](that){return isSTMState(that)&&that._tag===OP_DONE6&&equals(exit3,that.exit)}}},interruptedHash=pipe(hash(STMStateSymbolKey),combine(hash(OP_INTERRUPTED)),combine(hash("interrupted"))),interrupted2={[STMStateTypeId]:STMStateTypeId,_tag:OP_INTERRUPTED,[symbol](){return interruptedHash},[symbol2](that){return isSTMState(that)&&that._tag===OP_INTERRUPTED}},runningHash=pipe(hash(STMStateSymbolKey),combine(hash(OP_RUNNING2)),combine(hash("running"))),running3={[STMStateTypeId]:STMStateTypeId,_tag:OP_RUNNING2,[symbol](){return runningHash},[symbol2](that){return isSTMState(that)&&that._tag===OP_RUNNING2}},fromTExit=(tExit)=>{switch(tExit._tag){case OP_FAIL5:return done8(fail4(tExit.error));case OP_DIE3:return done8(die4(tExit.defect));case OP_INTERRUPT3:return done8(interrupt4(tExit.fiberId));case OP_SUCCEED3:return done8(succeed3(tExit.value));case OP_RETRY2:throw Error("BUG: STM.STMState.fromTExit - please report an issue at https://github.com/Effect-TS/effect/issues")}};var TExitSymbolKey="effect/TExit",TExitTypeId=Symbol.for(TExitSymbolKey),variance6={_A:(_)=>_,_E:(_)=>_},isExit2=(u)=>hasProperty(u,TExitTypeId);var isSuccess4=(self)=>{return self._tag===OP_SUCCEED3},isRetry=(self)=>{return self._tag===OP_RETRY2},fail13=(error2)=>({[TExitTypeId]:variance6,_tag:OP_FAIL5,error:error2,[symbol](){return pipe(hash(TExitSymbolKey),combine(hash(OP_FAIL5)),combine(hash(error2)),cached(this))},[symbol2](that){return isExit2(that)&&that._tag===OP_FAIL5&&equals(error2,that.error)}}),die8=(defect)=>({[TExitTypeId]:variance6,_tag:OP_DIE3,defect,[symbol](){return pipe(hash(TExitSymbolKey),combine(hash(OP_DIE3)),combine(hash(defect)),cached(this))},[symbol2](that){return isExit2(that)&&that._tag===OP_DIE3&&equals(defect,that.defect)}}),interrupt8=(fiberId3)=>({[TExitTypeId]:variance6,_tag:OP_INTERRUPT3,fiberId:fiberId3,[symbol](){return pipe(hash(TExitSymbolKey),combine(hash(OP_INTERRUPT3)),combine(hash(fiberId3)),cached(this))},[symbol2](that){return isExit2(that)&&that._tag===OP_INTERRUPT3&&equals(fiberId3,that.fiberId)}}),succeed13=(value)=>({[TExitTypeId]:variance6,_tag:OP_SUCCEED3,value,[symbol](){return pipe(hash(TExitSymbolKey),combine(hash(OP_SUCCEED3)),combine(hash(value)),cached(this))},[symbol2](that){return isExit2(that)&&that._tag===OP_SUCCEED3&&equals(value,that.value)}}),retryHash=pipe(hash(TExitSymbolKey),combine(hash(OP_RETRY2)),combine(hash("retry"))),retry4={[TExitTypeId]:variance6,_tag:OP_RETRY2,[symbol](){return retryHash},[symbol2](that){return isExit2(that)&&isRetry(that)}};var done9=(exit3)=>{return{_tag:OP_DONE5,exit:exit3}},suspend7=(journal)=>{return{_tag:OP_SUSPEND3,journal}};var txnCounter={ref:0},make46=()=>{let newId=txnCounter.ref+1;return txnCounter.ref=newId,newId};var STMSymbolKey2="effect/STM",STMTypeId2=Symbol.for(STMSymbolKey2),stmVariance={_R:(_)=>_,_E:(_)=>_,_A:(_)=>_};class STMPrimitive{effect_instruction_i0;_op=OP_COMMIT;effect_instruction_i1=void 0;effect_instruction_i2=void 0;[EffectTypeId3];[StreamTypeId];[SinkTypeId2];[ChannelTypeId2];get[STMTypeId2](){return stmVariance}constructor(effect_instruction_i0){this.effect_instruction_i0=effect_instruction_i0,this[EffectTypeId3]=effectVariance,this[StreamTypeId]=stmVariance,this[SinkTypeId2]=stmVariance,this[ChannelTypeId2]=stmVariance}[symbol2](that){return this===that}[symbol](){return cached(this,random(this))}[Symbol.iterator](){return new SingleShotGen2(new YieldWrap(this))}commit(){return unsafeAtomically(this,constVoid,constVoid)}pipe(){return pipeArguments(this,arguments)}}var unsafeAtomically=(self,onDone,onInterrupt3)=>withFiberRuntime((state)=>{let fiberId3=state.id(),env=state.getFiberRef(currentContext2),scheduler=state.getFiberRef(currentScheduler2),priority=state.getFiberRef(currentSchedulingPriority2),commitResult=tryCommitSync(fiberId3,self,env,scheduler,priority);switch(commitResult._tag){case OP_DONE5:return onDone(commitResult.exit),commitResult.exit;case OP_SUSPEND3:{let txnId=make46(),state2={value:running3},effect3=async((k)=>tryCommitAsync(fiberId3,self,txnId,state2,env,scheduler,priority,k));return uninterruptibleMask3((restore)=>pipe(restore(effect3),catchAllCause3((cause3)=>{let currentState=state2.value;if(isRunning2(currentState))state2.value=interrupted2;if(currentState=state2.value,isDone6(currentState))return onDone(currentState.exit),currentState.exit;return onInterrupt3(),failCause8(cause3)})))}}}),tryCommit=(fiberId3,stm,state,env,scheduler,priority)=>{let journal=new Map,tExit=new STMDriver(stm,journal,fiberId3,env).run(),analysis=analyzeJournal(journal);if(analysis===JournalAnalysisReadWrite)commitJournal(journal);else if(analysis===JournalAnalysisInvalid)throw Error("BUG: STM.TryCommit.tryCommit - please report an issue at https://github.com/Effect-TS/effect/issues");switch(tExit._tag){case OP_SUCCEED3:return state.value=fromTExit(tExit),completeTodos(succeed3(tExit.value),journal,scheduler,priority);case OP_FAIL5:{state.value=fromTExit(tExit);let cause3=fail3(tExit.error);return completeTodos(failCause3(cause3),journal,scheduler,priority)}case OP_DIE3:{state.value=fromTExit(tExit);let cause3=die3(tExit.defect);return completeTodos(failCause3(cause3),journal,scheduler,priority)}case OP_INTERRUPT3:{state.value=fromTExit(tExit);let cause3=interrupt3(fiberId3);return completeTodos(failCause3(cause3),journal,scheduler,priority)}case OP_RETRY2:return suspend7(journal)}},tryCommitSync=(fiberId3,stm,env,scheduler,priority)=>{let journal=new Map,tExit=new STMDriver(stm,journal,fiberId3,env).run(),analysis=analyzeJournal(journal);if(analysis===JournalAnalysisReadWrite&&isSuccess4(tExit))commitJournal(journal);else if(analysis===JournalAnalysisInvalid)throw Error("BUG: STM.TryCommit.tryCommitSync - please report an issue at https://github.com/Effect-TS/effect/issues");switch(tExit._tag){case OP_SUCCEED3:return completeTodos(succeed3(tExit.value),journal,scheduler,priority);case OP_FAIL5:{let cause3=fail3(tExit.error);return completeTodos(failCause3(cause3),journal,scheduler,priority)}case OP_DIE3:{let cause3=die3(tExit.defect);return completeTodos(failCause3(cause3),journal,scheduler,priority)}case OP_INTERRUPT3:{let cause3=interrupt3(fiberId3);return completeTodos(failCause3(cause3),journal,scheduler,priority)}case OP_RETRY2:return suspend7(journal)}},tryCommitAsync=(fiberId3,self,txnId,state,context5,scheduler,priority,k)=>{if(isRunning2(state.value)){let result=tryCommit(fiberId3,self,state,context5,scheduler,priority);switch(result._tag){case OP_DONE5:{completeTryCommit(result.exit,k);break}case OP_SUSPEND3:{addTodo(txnId,result.journal,()=>tryCommitAsync(fiberId3,self,txnId,state,context5,scheduler,priority,k));break}}}},completeTodos=(exit3,journal,scheduler,priority)=>{let todos=collectTodos(journal);if(todos.size>0)scheduler.scheduleTask(()=>execTodos(todos),priority);return done9(exit3)},completeTryCommit=(exit3,k)=>{k(exit3)};class STMDriver{self;journal;fiberId;contStack=[];env;constructor(self,journal,fiberId3,r0){this.self=self,this.journal=journal,this.fiberId=fiberId3,this.env=r0}getEnv(){return this.env}pushStack(cont){this.contStack.push(cont)}popStack(){return this.contStack.pop()}nextSuccess(){let current=this.popStack();while(current!==void 0&&current.effect_instruction_i0!==OP_ON_SUCCESS2)current=this.popStack();return current}nextFailure(){let current=this.popStack();while(current!==void 0&&current.effect_instruction_i0!==OP_ON_FAILURE2)current=this.popStack();return current}nextRetry(){let current=this.popStack();while(current!==void 0&&current.effect_instruction_i0!==OP_ON_RETRY)current=this.popStack();return current}run(){let curr=this.self,exit3=void 0;while(exit3===void 0&&curr!==void 0)try{let current=curr;if(current)switch(current._op){case"Tag":{curr=effect3((_,__,env)=>unsafeGet4(env,current));break}case"Left":{curr=fail14(current.left);break}case"None":{curr=fail14(new NoSuchElementException2);break}case"Right":{curr=succeed14(current.right);break}case"Some":{curr=succeed14(current.value);break}case"Commit":{switch(current.effect_instruction_i0){case OP_DIE2:{exit3=die8(internalCall(()=>current.effect_instruction_i1()));break}case OP_FAIL4:{let cont=this.nextFailure();if(cont===void 0)exit3=fail13(internalCall(()=>current.effect_instruction_i1()));else curr=internalCall(()=>cont.effect_instruction_i2(internalCall(()=>current.effect_instruction_i1())));break}case OP_RETRY:{let cont=this.nextRetry();if(cont===void 0)exit3=retry4;else curr=internalCall(()=>cont.effect_instruction_i2());break}case OP_INTERRUPT2:{exit3=interrupt8(this.fiberId);break}case OP_WITH_STM_RUNTIME:{curr=internalCall(()=>current.effect_instruction_i1(this));break}case OP_ON_SUCCESS2:case OP_ON_FAILURE2:case OP_ON_RETRY:{this.pushStack(current),curr=current.effect_instruction_i1;break}case OP_PROVIDE3:{let env=this.env;this.env=internalCall(()=>current.effect_instruction_i2(env)),curr=pipe(current.effect_instruction_i1,ensuring6(sync8(()=>this.env=env)));break}case OP_SUCCEED2:{let value=current.effect_instruction_i1,cont=this.nextSuccess();if(cont===void 0)exit3=succeed13(value);else curr=internalCall(()=>cont.effect_instruction_i2(value));break}case OP_SYNC2:{let value=internalCall(()=>current.effect_instruction_i1()),cont=this.nextSuccess();if(cont===void 0)exit3=succeed13(value);else curr=internalCall(()=>cont.effect_instruction_i2(value));break}}break}}}catch(e){curr=die9(e)}return exit3}}var catchAll6=dual(2,(self,f)=>{let stm=new STMPrimitive(OP_ON_FAILURE2);return stm.effect_instruction_i1=self,stm.effect_instruction_i2=f,stm});var die9=(defect)=>dieSync5(()=>defect);var dieSync5=(evaluate2)=>{let stm=new STMPrimitive(OP_DIE2);return stm.effect_instruction_i1=evaluate2,stm},effect3=(f)=>withSTMRuntime((_)=>succeed14(f(_.journal,_.fiberId,_.getEnv()))),ensuring6=dual(2,(self,finalizer)=>matchSTM(self,{onFailure:(e)=>zipRight8(finalizer,fail14(e)),onSuccess:(a)=>zipRight8(finalizer,succeed14(a))})),fail14=(error2)=>failSync6(()=>error2),failSync6=(evaluate2)=>{let stm=new STMPrimitive(OP_FAIL4);return stm.effect_instruction_i1=evaluate2,stm},flatMap15=dual(2,(self,f)=>{let stm=new STMPrimitive(OP_ON_SUCCESS2);return stm.effect_instruction_i1=self,stm.effect_instruction_i2=f,stm}),matchSTM=dual(2,(self,{onFailure,onSuccess})=>pipe(self,map21(right2),catchAll6((e)=>pipe(onFailure(e),map21(left2))),flatMap15((either6)=>{switch(either6._tag){case"Left":return succeed14(either6.left);case"Right":return onSuccess(either6.right)}}))),withSTMRuntime=(f)=>{let stm=new STMPrimitive(OP_WITH_STM_RUNTIME);return stm.effect_instruction_i1=f,stm};var interruptAs2=(fiberId3)=>{let stm=new STMPrimitive(OP_INTERRUPT2);return stm.effect_instruction_i1=fiberId3,stm},map21=dual(2,(self,f)=>pipe(self,flatMap15((a)=>sync8(()=>f(a)))));var retry5=new STMPrimitive(OP_RETRY),succeed14=(value)=>{let stm=new STMPrimitive(OP_SUCCEED2);return stm.effect_instruction_i1=value,stm},sync8=(evaluate2)=>{let stm=new STMPrimitive(OP_SYNC2);return stm.effect_instruction_i1=evaluate2,stm};var zipRight8=dual(2,(self,that)=>pipe(self,flatMap15(()=>that))),zipWith10=dual(3,(self,that,f)=>pipe(self,flatMap15((a)=>pipe(that,map21((b)=>f(a,b))))));var OP_BACKPRESSURE_STRATEGY="BackPressure",OP_DROPPING_STRATEGY="Dropping",OP_SLIDING_STRATEGY="Sliding";var as7=dual(2,(self,value)=>pipe(self,map21(()=>value)));var flatten11=(self)=>flatMap15(self,identity);var forEach8=dual((args2)=>isIterable(args2[0]),(iterable,f,options)=>{if(options?.discard)return pipe(sync8(()=>iterable[Symbol.iterator]()),flatMap15((iterator)=>{let loop3=suspend8(()=>{let next4=iterator.next();if(next4.done)return void_6;return pipe(f(next4.value),flatMap15(()=>loop3))});return loop3}));return suspend8(()=>fromIterable(iterable).reduce((acc,curr)=>zipWith10(acc,f(curr),(array4,elem)=>{return array4.push(elem),array4}),succeed14([])))});var all6=(input,options)=>{if(Symbol.iterator in input)return forEach8(input,identity,options);else if(options?.discard)return forEach8(Object.values(input),identity,options);return map21(forEach8(Object.entries(input),([_,e])=>map21(e,(a)=>[_,a])),(values3)=>{let res={};for(let[k,v]of values3)res[k]=v;return res})};var suspend8=(evaluate2)=>flatten11(sync8(evaluate2)),tap5=dual(2,(self,f)=>flatMap15(self,(a)=>as7(f(a),a)));var void_6=succeed14(void 0);var TRefSymbolKey="effect/TRef",TRefTypeId=Symbol.for(TRefSymbolKey),tRefVariance={_A:(_)=>_};class TRefImpl{[TRefTypeId]=tRefVariance;todos;versioned;constructor(value){this.versioned=new Versioned(value),this.todos=new Map}modify(f){return effect3((journal)=>{let entry=getOrMakeEntry(this,journal),[retValue,newValue]=f(unsafeGet6(entry));return unsafeSet(entry,newValue),retValue})}pipe(){return pipeArguments(this,arguments)}}var make47=(value)=>effect3((journal)=>{let ref=new TRefImpl(value);return journal.set(ref,make45(ref,!0)),ref}),get16=(self)=>self.modify((a)=>[a,a]),set7=dual(2,(self,value)=>self.modify(()=>[void 0,value]));var getOrMakeEntry=(self,journal)=>{if(journal.has(self))return journal.get(self);let entry=make45(self,!1);return journal.set(self,entry),entry},unsafeGet7=dual(2,(self,journal)=>unsafeGet6(getOrMakeEntry(self,journal))),unsafeSet2=dual(3,(self,value,journal)=>{let entry=getOrMakeEntry(self,journal);unsafeSet(entry,value);return});var TEnqueueSymbolKey="effect/TQueue/TEnqueue",TEnqueueTypeId=Symbol.for(TEnqueueSymbolKey),TDequeueSymbolKey="effect/TQueue/TDequeue",TDequeueTypeId=Symbol.for(TDequeueSymbolKey);var tDequeueVariance={_Out:(_)=>_},tEnqueueVariance={_In:(_)=>_};class TQueueImpl{ref;requestedCapacity;strategy;[TDequeueTypeId]=tDequeueVariance;[TEnqueueTypeId]=tEnqueueVariance;constructor(ref,requestedCapacity,strategy){this.ref=ref,this.requestedCapacity=requestedCapacity,this.strategy=strategy}capacity(){return this.requestedCapacity}size=withSTMRuntime((runtime4)=>{let queue=unsafeGet7(this.ref,runtime4.journal);if(queue===void 0)return interruptAs2(runtime4.fiberId);return succeed14(queue.length)});isFull=map21(this.size,(size12)=>size12===this.requestedCapacity);isEmpty=map21(this.size,(size12)=>size12===0);shutdown=withSTMRuntime((runtime4)=>{return unsafeSet2(this.ref,void 0,runtime4.journal),void_6});isShutdown=effect3((journal)=>{return unsafeGet7(this.ref,journal)===void 0});awaitShutdown=flatMap15(this.isShutdown,(isShutdown4)=>isShutdown4?void_6:retry5);offer(value){return withSTMRuntime((runtime4)=>{let queue=pipe(this.ref,unsafeGet7(runtime4.journal));if(queue===void 0)return interruptAs2(runtime4.fiberId);if(queue.length<this.requestedCapacity)return queue.push(value),unsafeSet2(this.ref,queue,runtime4.journal),succeed14(!0);switch(this.strategy._tag){case OP_BACKPRESSURE_STRATEGY:return retry5;case OP_DROPPING_STRATEGY:return succeed14(!1);case OP_SLIDING_STRATEGY:{if(queue.length===0)return succeed14(!0);return queue.shift(),queue.push(value),unsafeSet2(this.ref,queue,runtime4.journal),succeed14(!0)}}})}offerAll(iterable){return withSTMRuntime((runtime4)=>{let as8=Array.from(iterable),queue=unsafeGet7(this.ref,runtime4.journal);if(queue===void 0)return interruptAs2(runtime4.fiberId);if(queue.length+as8.length<=this.requestedCapacity)return unsafeSet2(this.ref,[...queue,...as8],runtime4.journal),succeed14(!0);switch(this.strategy._tag){case OP_BACKPRESSURE_STRATEGY:return retry5;case OP_DROPPING_STRATEGY:{let forQueue=as8.slice(0,this.requestedCapacity-queue.length);return unsafeSet2(this.ref,[...queue,...forQueue],runtime4.journal),succeed14(!1)}case OP_SLIDING_STRATEGY:{let forQueue=as8.slice(0,this.requestedCapacity-queue.length),toDrop=queue.length+forQueue.length-this.requestedCapacity,newQueue=queue.slice(toDrop);return unsafeSet2(this.ref,[...newQueue,...forQueue],runtime4.journal),succeed14(!0)}}})}peek=withSTMRuntime((runtime4)=>{let queue=unsafeGet7(this.ref,runtime4.journal);if(queue===void 0)return interruptAs2(runtime4.fiberId);if(queue.length===0)return retry5;return succeed14(queue[0])});peekOption=withSTMRuntime((runtime4)=>{let queue=unsafeGet7(this.ref,runtime4.journal);if(queue===void 0)return interruptAs2(runtime4.fiberId);return succeed14(fromNullable(queue[0]))});take=withSTMRuntime((runtime4)=>{let queue=unsafeGet7(this.ref,runtime4.journal);if(queue===void 0)return interruptAs2(runtime4.fiberId);if(queue.length===0)return retry5;let dequeued=queue.shift();return unsafeSet2(this.ref,queue,runtime4.journal),succeed14(dequeued)});takeAll=withSTMRuntime((runtime4)=>{let queue=unsafeGet7(this.ref,runtime4.journal);if(queue===void 0)return interruptAs2(runtime4.fiberId);return unsafeSet2(this.ref,[],runtime4.journal),succeed14(queue)});takeUpTo(max6){return withSTMRuntime((runtime4)=>{let queue=unsafeGet7(this.ref,runtime4.journal);if(queue===void 0)return interruptAs2(runtime4.fiberId);let[toTake,remaining]=splitAt2(unsafeFromArray(queue),max6);return unsafeSet2(this.ref,Array.from(remaining),runtime4.journal),succeed14(Array.from(toTake))})}}var isShutdown4=(self)=>self.isShutdown;var shutdown5=(self)=>self.shutdown;var take4=(self)=>self.take;var TPubSubSymbolKey="effect/TPubSub",TPubSubTypeId=Symbol.for(TPubSubSymbolKey),AbsentValue2=Symbol.for("effect/TPubSub/AbsentValue"),makeNode2=(head6,subscribers,tail)=>({head:head6,subscribers,tail});class TPubSubImpl{pubsubSize;publisherHead;publisherTail;requestedCapacity;strategy;subscriberCount;subscribers;[TPubSubTypeId]={_A:(_)=>_};[TEnqueueTypeId]=tEnqueueVariance;constructor(pubsubSize,publisherHead,publisherTail,requestedCapacity,strategy,subscriberCount,subscribers){this.pubsubSize=pubsubSize,this.publisherHead=publisherHead,this.publisherTail=publisherTail,this.requestedCapacity=requestedCapacity,this.strategy=strategy,this.subscriberCount=subscriberCount,this.subscribers=subscribers}isShutdown=effect3((journal)=>{return unsafeGet7(this.publisherTail,journal)===void 0});awaitShutdown=flatMap15(this.isShutdown,(isShutdown5)=>isShutdown5?void_6:retry5);capacity(){return this.requestedCapacity}size=withSTMRuntime((runtime4)=>{if(unsafeGet7(this.publisherTail,runtime4.journal)===void 0)return interruptAs2(runtime4.fiberId);return succeed14(unsafeGet7(this.pubsubSize,runtime4.journal))});isEmpty=map21(this.size,(size12)=>size12===0);isFull=map21(this.size,(size12)=>size12===this.capacity());offer(value){return withSTMRuntime((runtime4)=>{let currentPublisherTail=unsafeGet7(this.publisherTail,runtime4.journal);if(currentPublisherTail===void 0)return interruptAs2(runtime4.fiberId);let currentSubscriberCount=unsafeGet7(this.subscriberCount,runtime4.journal);if(currentSubscriberCount===0)return succeed14(!0);let currentPubSubSize=unsafeGet7(this.pubsubSize,runtime4.journal);if(currentPubSubSize<this.requestedCapacity){let updatedPublisherTail=new TRefImpl(void 0),updatedNode=makeNode2(value,currentSubscriberCount,updatedPublisherTail);return unsafeSet2(currentPublisherTail,updatedNode,runtime4.journal),unsafeSet2(this.publisherTail,updatedPublisherTail,runtime4.journal),unsafeSet2(this.pubsubSize,currentPubSubSize+1,runtime4.journal),succeed14(!0)}switch(this.strategy._tag){case OP_BACKPRESSURE_STRATEGY:return retry5;case OP_DROPPING_STRATEGY:return succeed14(!1);case OP_SLIDING_STRATEGY:{if(this.requestedCapacity>0){let currentPublisherHead=unsafeGet7(this.publisherHead,runtime4.journal),loop3=!0;while(loop3){let node=unsafeGet7(currentPublisherHead,runtime4.journal);if(node===void 0)return retry5;let{head:head6,tail}=node;if(head6!==AbsentValue2){let updatedNode2=makeNode2(AbsentValue2,node.subscribers,node.tail);unsafeSet2(currentPublisherHead,updatedNode2,runtime4.journal),unsafeSet2(this.publisherHead,tail,runtime4.journal),loop3=!1}else currentPublisherHead=tail}}let updatedPublisherTail=new TRefImpl(void 0),updatedNode=makeNode2(value,currentSubscriberCount,updatedPublisherTail);return unsafeSet2(currentPublisherTail,updatedNode,runtime4.journal),unsafeSet2(this.publisherTail,updatedPublisherTail,runtime4.journal),succeed14(!0)}}})}offerAll(iterable){return map21(forEach8(iterable,(a)=>this.offer(a)),every(identity))}shutdown=effect3((journal)=>{if(unsafeGet7(this.publisherTail,journal)!==void 0){unsafeSet2(this.publisherTail,void 0,journal);let currentSubscribers=unsafeGet7(this.subscribers,journal);forEach3(currentSubscribers,(subscriber)=>{unsafeSet2(subscriber,void 0,journal)}),unsafeSet2(this.subscribers,empty5(),journal)}})}class TPubSubSubscriptionImpl{pubsubSize;publisherHead;requestedCapacity;subscriberHead;subscriberCount;subscribers;[TPubSubTypeId]=TPubSubTypeId;[TDequeueTypeId]=tDequeueVariance;constructor(pubsubSize,publisherHead,requestedCapacity,subscriberHead,subscriberCount,subscribers){this.pubsubSize=pubsubSize,this.publisherHead=publisherHead,this.requestedCapacity=requestedCapacity,this.subscriberHead=subscriberHead,this.subscriberCount=subscriberCount,this.subscribers=subscribers}isShutdown=effect3((journal)=>{return unsafeGet7(this.subscriberHead,journal)===void 0});awaitShutdown=flatMap15(this.isShutdown,(isShutdown5)=>isShutdown5?void_6:retry5);capacity(){return this.requestedCapacity}size=withSTMRuntime((runtime4)=>{let currentSubscriberHead=unsafeGet7(this.subscriberHead,runtime4.journal);if(currentSubscriberHead===void 0)return interruptAs2(runtime4.fiberId);let loop3=!0,size12=0;while(loop3){let node=unsafeGet7(currentSubscriberHead,runtime4.journal);if(node===void 0)loop3=!1;else{let{head:head6,tail}=node;if(head6!==AbsentValue2){if(size12=size12+1,size12>=Number.MAX_SAFE_INTEGER)loop3=!1}currentSubscriberHead=tail}}return succeed14(size12)});isEmpty=map21(this.size,(size12)=>size12===0);isFull=map21(this.size,(size12)=>size12===this.capacity());peek=withSTMRuntime((runtime4)=>{let currentSubscriberHead=unsafeGet7(this.subscriberHead,runtime4.journal);if(currentSubscriberHead===void 0)return interruptAs2(runtime4.fiberId);let value=AbsentValue2,loop3=!0;while(loop3){let node=unsafeGet7(currentSubscriberHead,runtime4.journal);if(node===void 0)return retry5;let{head:head6,tail}=node;if(head6!==AbsentValue2)value=head6,loop3=!1;else currentSubscriberHead=tail}return succeed14(value)});peekOption=withSTMRuntime((runtime4)=>{let currentSubscriberHead=unsafeGet7(this.subscriberHead,runtime4.journal);if(currentSubscriberHead===void 0)return interruptAs2(runtime4.fiberId);let value=none2(),loop3=!0;while(loop3){let node=unsafeGet7(currentSubscriberHead,runtime4.journal);if(node===void 0)value=none2(),loop3=!1;else{let{head:head6,tail}=node;if(head6!==AbsentValue2)value=some2(head6),loop3=!1;else currentSubscriberHead=tail}}return succeed14(value)});shutdown=effect3((journal)=>{let currentSubscriberHead=unsafeGet7(this.subscriberHead,journal);if(currentSubscriberHead!==void 0){unsafeSet2(this.subscriberHead,void 0,journal);let loop3=!0;while(loop3){let node=unsafeGet7(currentSubscriberHead,journal);if(node===void 0)loop3=!1;else{let{head:head6,tail}=node;if(head6!==AbsentValue2){let subscribers=node.subscribers;if(subscribers===1){let size12=unsafeGet7(this.pubsubSize,journal),updatedNode=makeNode2(AbsentValue2,0,tail);unsafeSet2(currentSubscriberHead,updatedNode,journal),unsafeSet2(this.publisherHead,tail,journal),unsafeSet2(this.pubsubSize,size12-1,journal)}else{let updatedNode=makeNode2(head6,subscribers-1,tail);unsafeSet2(currentSubscriberHead,updatedNode,journal)}}currentSubscriberHead=tail}}let currentSubscriberCount=unsafeGet7(this.subscriberCount,journal);unsafeSet2(this.subscriberCount,currentSubscriberCount-1,journal),unsafeSet2(this.subscribers,remove4(unsafeGet7(this.subscribers,journal),this.subscriberHead),journal)}});take=withSTMRuntime((runtime4)=>{let currentSubscriberHead=unsafeGet7(this.subscriberHead,runtime4.journal);if(currentSubscriberHead===void 0)return interruptAs2(runtime4.fiberId);let value=AbsentValue2,loop3=!0;while(loop3){let node=unsafeGet7(currentSubscriberHead,runtime4.journal);if(node===void 0)return retry5;let{head:head6,tail}=node;if(head6!==AbsentValue2){let subscribers=node.subscribers;if(subscribers===1){let size12=unsafeGet7(this.pubsubSize,runtime4.journal),updatedNode=makeNode2(AbsentValue2,0,tail);unsafeSet2(currentSubscriberHead,updatedNode,runtime4.journal),unsafeSet2(this.publisherHead,tail,runtime4.journal),unsafeSet2(this.pubsubSize,size12-1,runtime4.journal)}else{let updatedNode=makeNode2(head6,subscribers-1,tail);unsafeSet2(currentSubscriberHead,updatedNode,runtime4.journal)}unsafeSet2(this.subscriberHead,tail,runtime4.journal),value=head6,loop3=!1}else currentSubscriberHead=tail}return succeed14(value)});takeAll=this.takeUpTo(Number.POSITIVE_INFINITY);takeUpTo(max6){return withSTMRuntime((runtime4)=>{let currentSubscriberHead=unsafeGet7(this.subscriberHead,runtime4.journal);if(currentSubscriberHead===void 0)return interruptAs2(runtime4.fiberId);let builder=[],n=0;while(n!==max6){let node=unsafeGet7(currentSubscriberHead,runtime4.journal);if(node===void 0)n=max6;else{let{head:head6,tail}=node;if(head6!==AbsentValue2){let subscribers=node.subscribers;if(subscribers===1){let size12=unsafeGet7(this.pubsubSize,runtime4.journal),updatedNode=makeNode2(AbsentValue2,0,tail);unsafeSet2(currentSubscriberHead,updatedNode,runtime4.journal),unsafeSet2(this.publisherHead,tail,runtime4.journal),unsafeSet2(this.pubsubSize,size12-1,runtime4.journal)}else{let updatedNode=makeNode2(head6,subscribers-1,tail);unsafeSet2(currentSubscriberHead,updatedNode,runtime4.journal)}builder.push(head6),n=n+1}currentSubscriberHead=tail}}return unsafeSet2(this.subscriberHead,currentSubscriberHead,runtime4.journal),succeed14(builder)})}}var makeSubscription2=(pubsubSize,publisherHead,publisherTail,requestedCapacity,subscriberCount,subscribers)=>pipe(get16(publisherTail),flatMap15((currentPublisherTail)=>pipe(all6([make47(currentPublisherTail),get16(subscriberCount),get16(subscribers)]),tap5(([_,currentSubscriberCount])=>pipe(subscriberCount,set7(currentSubscriberCount+1))),tap5(([subscriberHead,_,currentSubscribers])=>pipe(subscribers,set7(pipe(currentSubscribers,add2(subscriberHead))))),map21(([subscriberHead])=>new TPubSubSubscriptionImpl(pubsubSize,publisherHead,requestedCapacity,subscriberHead,subscriberCount,subscribers)))));var subscribe3=(self)=>makeSubscription2(self.pubsubSize,self.publisherHead,self.publisherTail,self.requestedCapacity,self.subscriberCount,self.subscribers),subscribeScoped=(self)=>acquireRelease2(subscribe3(self),(dequeue)=>shutdown5(dequeue));var subscribeScoped2=subscribeScoped;var isShutdown6=isShutdown4;var take5=take4;class RingBuffer{capacity;array;size=0;current=0;constructor(capacity7){this.capacity=capacity7,this.array=Array.from({length:capacity7},constUndefined)}head(){return fromNullable(this.array[this.current])}lastOrNull(){if(this.size===0)return;let index=this.current===0?this.array.length-1:this.current-1;return this.array[index]??void 0}put(value){this.array[this.current]=value,this.increment()}dropLast(){if(this.size>0)this.decrement(),this.array[this.current]=void 0}toChunk(){let begin=this.current-this.size,newArray=begin<0?[...this.array.slice(this.capacity+begin,this.capacity),...this.array.slice(0,this.current)]:this.array.slice(begin,this.current);return fromIterable2(newArray)}increment(){if(this.size<this.capacity)this.size+=1;this.current=(this.current+1)%this.capacity}decrement(){if(this.size-=1,this.current>0)this.current-=1;else this.current=this.capacity-1}}var OP_NOT_STARTED="NotStarted",OP_PREVIOUS="Previous",OP_CURRENT="Current",notStarted={_tag:"NotStarted"},previous=(fiber)=>({_tag:"Previous",fiber}),current=(fiber)=>({_tag:"Current",fiber});var make48=(emit)=>{return Object.assign(emit,{chunk(as8){return this(succeed9(as8))},die(defect){return this(die6(defect))},dieMessage(message){return this(dieMessage2(message))},done(exit3){return this(suspend3(()=>mapBoth2(exit3,{onFailure:some2,onSuccess:of2})))},end(){return this(fail9(none2()))},fail(e){return this(fail9(some2(e)))},fromEffect(effect4){return this(mapBoth4(effect4,{onFailure:some2,onSuccess:of2}))},fromEffectChunk(effect4){return this(pipe(effect4,mapError3(some2)))},halt(cause3){return this(failCause8(pipe(cause3,map11(some2))))},single(value){return this(succeed9(of2(value)))}})},makePush=(queue,scheduler)=>{let finished=!1,buffer=[],running4=!1;function array4(items){if(finished)return!1;if(items.length<=50000)buffer.push.apply(buffer,items);else for(let i=0;i<items.length;i++)buffer.push(items[0]);if(!running4)running4=!0,scheduler.scheduleTask(flush,0);return!0}function flush(){if(running4=!1,buffer.length>0)queue.unsafeOffer(buffer),buffer=[]}function done10(exit3){if(finished)return;if(finished=!0,exit3._tag==="Success")buffer.push(exit3.value);flush(),queue.unsafeOffer(exit3._tag==="Success"?void_3:exit3)}return{single(value){if(finished)return!1;if(buffer.push(value),!running4)running4=!0,scheduler.scheduleTask(flush,0);return!0},array:array4,chunk(chunk2){return array4(toReadonlyArray(chunk2))},done:done10,end(){if(finished)return;finished=!0,flush(),queue.unsafeOffer(void_3)},halt(cause3){return done10(failCause3(cause3))},fail(error2){return done10(fail4(error2))},die(defect){return done10(die4(defect))},dieMessage(message){return done10(die4(Error(message)))}}};var HandoffTypeId=Symbol.for("effect/Stream/Handoff"),OP_HANDOFF_STATE_EMPTY="Empty",OP_HANDOFF_STATE_FULL="Full",handoffStateEmpty=(notifyConsumer)=>({_tag:OP_HANDOFF_STATE_EMPTY,notifyConsumer}),handoffStateFull=(value,notifyProducer)=>({_tag:OP_HANDOFF_STATE_FULL,value,notifyProducer}),handoffStateMatch=(onEmpty,onFull)=>{return(self)=>{switch(self._tag){case OP_HANDOFF_STATE_EMPTY:return onEmpty(self.notifyConsumer);case OP_HANDOFF_STATE_FULL:return onFull(self.value,self.notifyProducer)}}},handoffVariance={_A:(_)=>_},make49=()=>pipe(make39(),flatMap11((deferred)=>make24(handoffStateEmpty(deferred))),map16((ref)=>({[HandoffTypeId]:handoffVariance,ref}))),offer5=dual(2,(self,value)=>{return flatMap11(make39(),(deferred)=>flatten8(modify4(self.ref,(state)=>pipe(state,handoffStateMatch((notifyConsumer)=>[zipRight4(succeed7(notifyConsumer,void 0),_await3(deferred)),handoffStateFull(value,deferred)],(_,notifyProducer)=>[flatMap11(_await3(notifyProducer),()=>pipe(self,offer5(value))),state])))))}),take6=(self)=>flatMap11(make39(),(deferred)=>flatten8(modify4(self.ref,(state)=>pipe(state,handoffStateMatch((notifyConsumer)=>[flatMap11(_await3(notifyConsumer),()=>take6(self)),state],(value,notifyProducer)=>[as4(succeed7(notifyProducer,void 0),value),handoffStateEmpty(deferred)])))));var OP_EMIT4="Emit",OP_HALT="Halt",OP_END="End",emit=(elements)=>({_tag:"Emit",elements}),halt=(cause3)=>({_tag:"Halt",cause:cause3}),end3=(reason)=>({_tag:"End",reason});var TakeSymbolKey="effect/Take",TakeTypeId=Symbol.for(TakeSymbolKey),takeVariance={_A:(_)=>_,_E:(_)=>_};class TakeImpl{exit;[TakeTypeId]=takeVariance;constructor(exit3){this.exit=exit3}pipe(){return pipeArguments(this,arguments)}}var chunk2=(chunk3)=>new TakeImpl(succeed3(chunk3));var done10=(self)=>suspend3(()=>self.exit),end4=new TakeImpl(fail4(none2()));var failCause11=(cause3)=>new TakeImpl(failCause3(pipe(cause3,map11(some2))));var fromPull=(pull)=>matchCause3(pull,{onFailure:(cause3)=>match2(flipCauseOption2(cause3),{onNone:()=>end4,onSome:failCause11}),onSuccess:chunk2});var match18=dual(2,(self,{onEnd,onFailure,onSuccess})=>match9(self.exit,{onFailure:(cause3)=>match2(flipCauseOption2(cause3),{onNone:onEnd,onSome:onFailure}),onSuccess}));var of5=(value)=>new TakeImpl(succeed3(of2(value)));var end5=()=>fail9(none2());var failCause12=(cause3)=>mapError3(failCause8(cause3),some2);var OP_SCHEDULE_END="ScheduleEnd",OP_UPSTREAM_END="UpstreamEnd",ScheduleEnd={_tag:"ScheduleEnd"},UpstreamEnd={_tag:"UpstreamEnd"};var OP_DRAIN_LEFT="DrainLeft",OP_DRAIN_RIGHT="DrainRight",OP_PULL_BOTH="PullBoth",OP_PULL_LEFT="PullLeft",OP_PULL_RIGHT="PullRight",DrainLeft={_tag:"DrainLeft"},DrainRight={_tag:"DrainRight"},PullBoth={_tag:"PullBoth"},PullLeft=(rightChunk)=>({_tag:"PullLeft",rightChunk}),PullRight=(leftChunk)=>({_tag:"PullRight",leftChunk});var OP_PULL_BOTH2="PullBoth",OP_PULL_LEFT2="PullLet",OP_PULL_RIGHT2="PullRight",PullBoth2={_tag:"PullBoth"},PullLeft2=(rightChunk)=>({_tag:"PullLet",rightChunk}),PullRight2=(leftChunk)=>({_tag:"PullRight",leftChunk});var StreamSymbolKey="effect/Stream",StreamTypeId2=Symbol.for(StreamSymbolKey),streamVariance={_R:(_)=>_,_E:(_)=>_,_A:(_)=>_};class StreamImpl{channel;[StreamTypeId2]=streamVariance;constructor(channel){this.channel=channel}pipe(){return pipeArguments(this,arguments)}}var isStream=(u)=>hasProperty(u,StreamTypeId2)||isEffect2(u),DefaultChunkSize=4096,accumulate=(self)=>chunks(accumulateChunks(self)),accumulateChunks=(self)=>{let accumulator=(s)=>readWith({onInput:(input)=>{let next4=appendAll2(s,input);return flatMap13(write(next4),()=>accumulator(next4))},onFailure:fail11,onDone:()=>void_5});return new StreamImpl(pipeTo(toChannel2(self),accumulator(empty2())))},acquireRelease3=(acquire,release)=>scoped5(acquireRelease2(acquire,release)),aggregate=dual(2,(self,sink)=>aggregateWithin(self,sink,forever4)),aggregateWithin=dual(3,(self,sink,schedule2)=>filterMap6(aggregateWithinEither(self,sink,schedule2),(_)=>match(_,{onLeft:none2,onRight:some2}))),aggregateWithinEither=dual(3,(self,sink,schedule2)=>{let layer=all5([make49(),make24(ScheduleEnd),make24(empty2()),driver2(schedule2),make24(!1),make24(!1)]);return fromEffect7(layer).pipe(flatMap16(([handoff,sinkEndReason,sinkLeftovers,scheduleDriver,consumed,endAfterEmit])=>{let handoffProducer=readWithCause({onInput:(input)=>flatMap13(fromEffect4(pipe(handoff,offer5(emit(input)),when2(()=>isNonEmpty(input)))),()=>handoffProducer),onFailure:(cause3)=>fromEffect4(offer5(handoff,halt(cause3))),onDone:()=>fromEffect4(offer5(handoff,end3(UpstreamEnd)))}),handoffConsumer=pipe(getAndSet2(sinkLeftovers,empty2()),flatMap11((leftovers)=>{if(isNonEmpty(leftovers))return pipe(set5(consumed,!0),zipRight4(succeed9(pipe(write(leftovers),flatMap13(()=>handoffConsumer)))));return pipe(take6(handoff),map16((signal)=>{switch(signal._tag){case OP_EMIT4:return pipe(fromEffect4(set5(consumed,!0)),zipRight6(write(signal.elements)),zipRight6(fromEffect4(get11(endAfterEmit))),flatMap13((bool)=>bool?void_5:handoffConsumer));case OP_HALT:return failCause10(signal.cause);case OP_END:{if(signal.reason._tag===OP_SCHEDULE_END)return pipe(get11(consumed),map16((bool)=>bool?fromEffect4(pipe(set5(sinkEndReason,ScheduleEnd),zipRight4(set5(endAfterEmit,!0)))):pipe(fromEffect4(pipe(set5(sinkEndReason,ScheduleEnd),zipRight4(set5(endAfterEmit,!0)))),flatMap13(()=>handoffConsumer))),unwrap);return pipe(set5(sinkEndReason,signal.reason),zipRight4(set5(endAfterEmit,!0)),fromEffect4)}}}))}),unwrap),timeout3=(lastB)=>scheduleDriver.next(lastB),scheduledAggregator=(sinkFiber,scheduleFiber,scope5)=>{let forkSink=pipe(set5(consumed,!1),zipRight4(set5(endAfterEmit,!1)),zipRight4(pipe(handoffConsumer,pipeToOrFail(toChannel(sink)),collectElements,run3,forkIn2(scope5)))),handleSide=(leftovers,b,c)=>pipe(set5(sinkLeftovers,flatten2(leftovers)),zipRight4(map16(get11(sinkEndReason),(reason)=>{switch(reason._tag){case OP_SCHEDULE_END:return pipe(all5([get11(consumed),forkSink,pipe(timeout3(some2(b)),forkIn2(scope5))]),map16(([wasConsumed,sinkFiber2,scheduleFiber2])=>{let toWrite=pipe(c,match2({onNone:()=>of2(right2(b)),onSome:(c2)=>make4(right2(b),left2(c2))}));if(wasConsumed)return pipe(write(toWrite),flatMap13(()=>scheduledAggregator(sinkFiber2,scheduleFiber2,scope5)));return scheduledAggregator(sinkFiber2,scheduleFiber2,scope5)}),unwrap);case OP_UPSTREAM_END:return pipe(get11(consumed),map16((wasConsumed)=>wasConsumed?write(of2(right2(b))):void_5),unwrap)}})),unwrap);return unwrap(raceWith2(join3(sinkFiber),join3(scheduleFiber),{onSelfDone:(sinkExit,_)=>pipe(interrupt5(scheduleFiber),zipRight4(pipe(suspend3(()=>sinkExit),map16(([leftovers,b])=>handleSide(leftovers,b,none2()))))),onOtherDone:(scheduleExit,_)=>matchCauseEffect3(suspend3(()=>scheduleExit),{onFailure:(cause3)=>match(failureOrCause2(cause3),{onLeft:()=>pipe(handoff,offer5(end3(ScheduleEnd)),forkDaemon2,zipRight4(pipe(join3(sinkFiber),map16(([leftovers,b])=>handleSide(leftovers,b,none2()))))),onRight:(cause4)=>pipe(handoff,offer5(halt(cause4)),forkDaemon2,zipRight4(pipe(join3(sinkFiber),map16(([leftovers,b])=>handleSide(leftovers,b,none2())))))}),onSuccess:(c)=>pipe(handoff,offer5(end3(ScheduleEnd)),forkDaemon2,zipRight4(pipe(join3(sinkFiber),map16(([leftovers,b])=>handleSide(leftovers,b,some2(c))))))})}))};return unwrapScopedWith3((scope5)=>pipeTo(toChannel2(self),handoffProducer).pipe(run3,forkIn2(scope5),zipRight4(pipeToOrFail(handoffConsumer,toChannel(sink)).pipe(collectElements,run3,forkIn2(scope5),flatMap11((sinkFiber)=>timeout3(none2()).pipe(forkIn2(scope5),map16((scheduleFiber)=>new StreamImpl(scheduledAggregator(sinkFiber,scheduleFiber,scope5)))))))))}))}),as8=dual(2,(self,value)=>map22(self,()=>value)),queueFromBufferOptions=(bufferSize)=>{if(bufferSize==="unbounded")return unbounded3();else if(typeof bufferSize==="number"||bufferSize===void 0)return bounded3(bufferSize??16);switch(bufferSize.strategy){case"dropping":return dropping2(bufferSize.bufferSize??16);case"sliding":return sliding2(bufferSize.bufferSize??16);default:return bounded3(bufferSize.bufferSize??16)}},_async=(register,bufferSize)=>acquireRelease2(queueFromBufferOptions(bufferSize),(queue)=>shutdown2(queue)).pipe(flatMap11((output)=>runtime3().pipe(flatMap11((runtime4)=>sync4(()=>{let runPromiseExit3=runPromiseExit2(runtime4);return register(make48((resume2)=>fromPull(resume2).pipe(flatMap11((take7)=>offer3(output,take7)),asVoid3,runPromiseExit3).then((exit3)=>{if(isFailure3(exit3)){if(!isInterrupted2(exit3.cause))throw squash(exit3.cause)}})))})),map16((value)=>{let loop3=take3(output).pipe(flatMap11((take7)=>done10(take7)),match13({onFailure:(maybeError)=>fromEffect4(shutdown2(output)).pipe(zipRight6(match2(maybeError,{onNone:()=>void_5,onSome:(error2)=>fail11(error2)}))),onSuccess:(chunk3)=>write(chunk3).pipe(flatMap13(()=>loop3))}),unwrap);return fromChannel2(loop3).pipe(ensuring7(value??_void))}))),unwrapScoped4),asyncEffect3=(register,bufferSize)=>pipe(acquireRelease2(queueFromBufferOptions(bufferSize),(queue)=>shutdown2(queue)),flatMap11((output)=>pipe(runtime3(),flatMap11((runtime4)=>pipe(register(make48((k)=>pipe(fromPull(k),flatMap11((take7)=>offer3(output,take7)),asVoid3,runPromiseExit2(runtime4)).then((exit3)=>{if(isFailure3(exit3)){if(!isInterrupted2(exit3.cause))throw squash(exit3.cause)}}))),map16(()=>{let loop3=pipe(take3(output),flatMap11(done10),match13({onFailure:(maybeError)=>pipe(fromEffect4(shutdown2(output)),zipRight6(match2(maybeError,{onNone:()=>void_5,onSome:fail11}))),onSuccess:(chunk3)=>pipe(write(chunk3),flatMap13(()=>loop3))}),unwrap);return loop3}))))),unwrapScoped3,fromChannel2),queueFromBufferOptionsPush=(options)=>{if(options?.bufferSize==="unbounded"||options?.bufferSize===void 0&&options?.strategy===void 0)return unbounded3();switch(options?.strategy){case"sliding":return sliding2(options.bufferSize??16);default:return dropping2(options?.bufferSize??16)}},asyncPush=(register,options)=>acquireRelease2(queueFromBufferOptionsPush(options),shutdown2).pipe(tap3((queue)=>getWith(currentScheduler2,(scheduler)=>register(makePush(queue,scheduler)))),map16((queue)=>{let loop3=flatMap13(take3(queue),(item)=>isExit(item)?isSuccess2(item)?void_5:failCause10(item.cause):zipRight6(write(unsafeFromArray(item)),loop3));return loop3}),unwrapScoped3,fromChannel2),asyncScoped=(register,bufferSize)=>pipe(acquireRelease2(queueFromBufferOptions(bufferSize),(queue)=>shutdown2(queue)),flatMap11((output)=>pipe(runtime3(),flatMap11((runtime4)=>pipe(register(make48((k)=>pipe(fromPull(k),flatMap11((take7)=>offer3(output,take7)),asVoid3,runPromiseExit2(runtime4)).then((exit3)=>{if(isFailure3(exit3)){if(!isInterrupted2(exit3.cause))throw squash(exit3.cause)}}))),zipRight4(make24(!1)),flatMap11((ref)=>pipe(get11(ref),map16((isDone7)=>isDone7?end5():pipe(take3(output),flatMap11(done10),onError2(()=>pipe(set5(ref,!0),zipRight4(shutdown2(output)))))))))))),scoped5,flatMap16(repeatEffectChunkOption)),branchAfter=dual(3,(self,n,f)=>suspend9(()=>{let buffering=(acc)=>readWith({onInput:(input)=>{if(acc.length+input.length>=n){let[b1,b2]=pipe(input,splitAt2(n-acc.length));return running4(pipe(acc,appendAll2(b1)),b2)}return buffering(pipe(acc,appendAll2(input)))},onFailure:fail11,onDone:()=>running4(acc,empty2())}),running4=(prefix,leftover)=>pipeTo(zipRight6(write(leftover),identityChannel()),toChannel2(f(prefix)));return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(buffering(empty2()))))})),broadcast=dual(3,(self,n,maximumLag)=>pipe(self,broadcastedQueues(n,maximumLag),map16((tuple2)=>tuple2.map((queue)=>flattenTake(fromQueue2(queue,{shutdown:!0})))))),broadcastDynamic=dual(2,(self,maximumLag)=>map16(toPubSub2(self,maximumLag),(pubsub)=>flattenTake(fromPubSub(pubsub)))),share=dual(2,(self,options)=>map16(make44({acquire:broadcastDynamic(self,options),idleTimeToLive:options.idleTimeToLive}),(rcRef)=>unwrapScoped4(get15(rcRef)))),broadcastedQueues=dual(3,(self,n,maximumLag)=>flatMap11(pubsubFromOptions(maximumLag),(pubsub)=>pipe(all5(Array.from({length:n},()=>subscribe2(pubsub))),tap3(()=>forkScoped2(runIntoPubSubScoped(self,pubsub)))))),broadcastedQueuesDynamic=dual(2,(self,maximumLag)=>map16(toPubSub2(self,maximumLag),subscribe2)),buffer=dual(2,(self,options)=>{if(options.capacity==="unbounded")return bufferUnbounded(self);else if(options.strategy==="dropping")return bufferDropping(self,options.capacity);else if(options.strategy==="sliding")return bufferSliding(self,options.capacity);let queue=toQueueOfElements(self,options);return new StreamImpl(unwrapScoped3(map16(queue,(queue2)=>{let process2=pipe(fromEffect4(take3(queue2)),flatMap13(match9({onFailure:(cause3)=>pipe(flipCauseOption2(cause3),match2({onNone:()=>void_5,onSome:failCause10})),onSuccess:(value)=>flatMap13(write(of2(value)),()=>process2)})));return process2})))}),bufferChunks=dual(2,(self,options)=>{if(options.strategy==="dropping")return bufferChunksDropping(self,options.capacity);else if(options.strategy==="sliding")return bufferChunksSliding(self,options.capacity);let queue=toQueue2(self,options);return new StreamImpl(unwrapScoped3(map16(queue,(queue2)=>{let process2=pipe(fromEffect4(take3(queue2)),flatMap13(match18({onEnd:()=>void_5,onFailure:failCause10,onSuccess:(value)=>pipe(write(value),flatMap13(()=>process2))})));return process2})))}),bufferChunksDropping=dual(2,(self,capacity7)=>{let queue=acquireRelease2(dropping2(capacity7),(queue2)=>shutdown2(queue2));return new StreamImpl(bufferSignal(queue,toChannel2(self)))}),bufferChunksSliding=dual(2,(self,capacity7)=>{let queue=acquireRelease2(sliding2(capacity7),(queue2)=>shutdown2(queue2));return new StreamImpl(bufferSignal(queue,toChannel2(self)))}),bufferDropping=dual(2,(self,capacity7)=>{let queue=acquireRelease2(dropping2(capacity7),(queue2)=>shutdown2(queue2));return new StreamImpl(bufferSignal(queue,toChannel2(rechunk(1)(self))))}),bufferSliding=dual(2,(self,capacity7)=>{let queue=acquireRelease2(sliding2(capacity7),(queue2)=>shutdown2(queue2));return new StreamImpl(bufferSignal(queue,toChannel2(pipe(self,rechunk(1)))))}),bufferUnbounded=(self)=>{let queue=toQueue2(self,{strategy:"unbounded"});return new StreamImpl(unwrapScoped3(map16(queue,(queue2)=>{let process2=pipe(fromEffect4(take3(queue2)),flatMap13(match18({onEnd:()=>void_5,onFailure:failCause10,onSuccess:(value)=>flatMap13(write(value),()=>process2)})));return process2})))},bufferSignal=(scoped5,bufferChannel)=>{let producer=(queue,ref)=>{let terminate=(take7)=>pipe(get11(ref),tap3(_await3),zipRight4(make39()),flatMap11((deferred)=>pipe(offer3(queue,[take7,deferred]),zipRight4(set5(ref,deferred)),zipRight4(_await3(deferred)))),asVoid3,fromEffect4);return readWithCause({onInput:(input)=>pipe(make39(),flatMap11((deferred)=>pipe(offer3(queue,[chunk2(input),deferred]),flatMap11((added)=>pipe(set5(ref,deferred),when2(()=>added))))),asVoid3,fromEffect4,flatMap13(()=>producer(queue,ref))),onFailure:(error2)=>terminate(failCause11(error2)),onDone:()=>terminate(end4)})},consumer=(queue)=>{let process2=pipe(fromEffect4(take3(queue)),flatMap13(([take7,deferred])=>zipRight6(fromEffect4(succeed7(deferred,void 0)),match18(take7,{onEnd:()=>void_5,onFailure:failCause10,onSuccess:(value)=>pipe(write(value),flatMap13(()=>process2))}))));return process2};return unwrapScoped3(pipe(scoped5,flatMap11((queue)=>pipe(make39(),tap3((start3)=>succeed7(start3,void 0)),flatMap11((start3)=>pipe(make24(start3),flatMap11((ref)=>pipe(bufferChannel,pipeTo(producer(queue,ref)),runScoped,forkScoped2)),as4(consumer(queue))))))))},catchAll7=dual(2,(self,f)=>catchAllCause6(self,(cause3)=>match(failureOrCause2(cause3),{onLeft:f,onRight:failCause13}))),catchAllCause6=dual(2,(self,f)=>new StreamImpl(pipe(toChannel2(self),catchAllCause5((cause3)=>toChannel2(f(cause3)))))),catchSome3=dual(2,(self,pf)=>pipe(self,catchAll7((error2)=>pipe(pf(error2),getOrElse(()=>fail15(error2)))))),catchSomeCause3=dual(2,(self,pf)=>pipe(self,catchAllCause6((cause3)=>pipe(pf(cause3),getOrElse(()=>failCause13(cause3)))))),catchTag3=dual(3,(self,k,f)=>catchAll7(self,(e)=>{if("_tag"in e&&e._tag===k)return f(e);return fail15(e)})),catchTags3=dual(2,(self,cases)=>catchAll7(self,(e)=>{let keys3=Object.keys(cases);if("_tag"in e&&keys3.includes(e._tag))return cases[e._tag](e);return fail15(e)})),changes=(self)=>pipe(self,changesWith((x,y)=>equals(y)(x))),changesWith=dual(2,(self,f)=>{let writer=(last4)=>readWithCause({onInput:(input)=>{let[newLast,newChunk]=reduce2(input,[last4,empty2()],([option3,outputs],output)=>{if(isSome2(option3)&&f(option3.value,output))return[some2(output),outputs];return[some2(output),pipe(outputs,append2(output))]});return flatMap13(write(newChunk),()=>writer(newLast))},onFailure:failCause10,onDone:()=>void_5});return new StreamImpl(pipe(toChannel2(self),pipeTo(writer(none2()))))}),changesWithEffect=dual(2,(self,f)=>{let writer=(last4)=>readWithCause({onInput:(input)=>pipe(input,reduce11([last4,empty2()],([option3,outputs],output)=>{if(isSome2(option3))return pipe(f(option3.value,output),map16((bool)=>bool?[some2(output),outputs]:[some2(output),pipe(outputs,append2(output))]));return succeed9([some2(output),pipe(outputs,append2(output))])}),fromEffect4,flatMap13(([newLast,newChunk])=>pipe(write(newChunk),flatMap13(()=>writer(newLast))))),onFailure:failCause10,onDone:()=>void_5});return new StreamImpl(pipe(toChannel2(self),pipeTo(writer(none2()))))}),chunks=(self)=>pipe(self,mapChunks(of2)),chunksWith=dual(2,(self,f)=>flattenChunks(f(chunks(self)))),unsome=(effect4)=>catchAll3(asSome2(effect4),(o)=>o._tag==="None"?succeedNone2:fail9(o.value)),combine9=dual(4,(self,that,s,f)=>{function producer(handoff,latch){return fromEffect4(take6(latch)).pipe(zipRight6(readWithCause({onInput:(input)=>flatMap13(fromEffect4(offer5(handoff,succeed3(input))),()=>producer(handoff,latch)),onFailure:(cause3)=>fromEffect4(offer5(handoff,failCause3(pipe(cause3,map11(some2))))),onDone:()=>flatMap13(fromEffect4(offer5(handoff,fail4(none2()))),()=>producer(handoff,latch))})))}return new StreamImpl(unwrapScopedWith((scope5)=>all5([make49(),make49(),make49(),make49()]).pipe(tap3(([left3,_,latchL])=>toChannel2(self).pipe(concatMap(writeChunk),pipeTo(producer(left3,latchL)),runIn(scope5),forkIn2(scope5))),tap3(([,right3,_,rightL])=>toChannel2(that).pipe(concatMap(writeChunk),pipeTo(producer(right3,rightL)),runIn(scope5),forkIn2(scope5))),map16(([left3,right3,latchL,latchR])=>{let pullLeft=offer5(latchL,void 0).pipe(zipRight4(take6(left3).pipe(flatMap11(identity)))),pullRight=offer5(latchR,void 0).pipe(zipRight4(take6(right3).pipe(flatMap11(identity))));return toChannel2(unfoldEffect(s,(s2)=>flatMap11(f(s2,pullLeft,pullRight),unsome)))}))))}),combineChunks=dual(4,(self,that,s,f)=>{let producer=(handoff,latch)=>zipRight6(fromEffect4(take6(latch)),readWithCause({onInput:(input)=>flatMap13(fromEffect4(pipe(handoff,offer5(chunk2(input)))),()=>producer(handoff,latch)),onFailure:(cause3)=>fromEffect4(offer5(handoff,failCause11(cause3))),onDone:()=>fromEffect4(offer5(handoff,end4))}));return new StreamImpl(unwrapScopedWith((scope5)=>all5([make49(),make49(),make49(),make49()]).pipe(tap3(([left3,_,latchL])=>pipeTo(toChannel2(self),producer(left3,latchL)).pipe(runIn(scope5),forkIn2(scope5))),tap3(([_,right3,__,latchR])=>pipeTo(toChannel2(that),producer(right3,latchR)).pipe(runIn(scope5),forkIn2(scope5))),map16(([left3,right3,latchL,latchR])=>{let pullLeft=offer5(latchL,void 0).pipe(zipRight4(take6(left3).pipe(flatMap11(done10)))),pullRight=offer5(latchR,void 0).pipe(zipRight4(take6(right3).pipe(flatMap11(done10))));return toChannel2(unfoldChunkEffect(s,(s2)=>flatMap11(f(s2,pullLeft,pullRight),unsome)))}))))}),concat2=dual(2,(self,that)=>new StreamImpl(pipe(toChannel2(self),zipRight6(toChannel2(that))))),concatAll2=(streams)=>suspend9(()=>pipe(streams,reduce2(empty29,(x,y)=>concat2(y)(x)))),cross=dual(2,(left3,right3)=>pipe(left3,crossWith(right3,(a,a2)=>[a,a2]))),crossLeft=dual(2,(left3,right3)=>pipe(left3,crossWith(right3,(a,_)=>a))),crossRight=dual(2,(left3,right3)=>flatMap16(left3,()=>right3)),crossWith=dual(3,(left3,right3,f)=>pipe(left3,flatMap16((a)=>pipe(right3,map22((b)=>f(a,b)))))),debounce=dual(2,(self,duration3)=>unwrapScopedWith3((scope5)=>gen2(function*(){let handoff=yield*make49();function enqueue(last4){return sleep2(duration3).pipe(as4(last4),forkIn2(scope5),map16((fiber)=>consumer(previous(fiber))))}let producer=readWithCause({onInput:(input)=>match2(last2(input),{onNone:()=>producer,onSome:(elem)=>fromEffect4(offer5(handoff,emit(of2(elem)))).pipe(flatMap13(()=>producer))}),onFailure:(cause3)=>fromEffect4(offer5(handoff,halt(cause3))),onDone:()=>fromEffect4(offer5(handoff,end3(UpstreamEnd)))});function consumer(state){switch(state._tag){case OP_NOT_STARTED:return unwrap(take6(handoff).pipe(map16((signal)=>{switch(signal._tag){case OP_EMIT4:return unwrap(enqueue(signal.elements));case OP_HALT:return failCause10(signal.cause);case OP_END:return void_5}})));case OP_PREVIOUS:return unwrap(take6(handoff).pipe(forkIn2(scope5),flatMap11((handoffFiber)=>raceWith2(join3(state.fiber),join3(handoffFiber),{onSelfDone:(leftExit,current2)=>match9(leftExit,{onFailure:(cause3)=>interrupt5(current2).pipe(as4(failCause10(cause3))),onSuccess:(chunk3)=>interrupt5(current2).pipe(zipRight4(succeed9(write(chunk3).pipe(flatMap13(()=>consumer(current(handoffFiber)))))))}),onOtherDone:(rightExit,previous2)=>match9(rightExit,{onFailure:(cause3)=>interrupt5(previous2).pipe(as4(failCause10(cause3))),onSuccess:(signal)=>{switch(signal._tag){case OP_EMIT4:return interrupt5(previous2).pipe(zipRight4(enqueue(signal.elements)));case OP_HALT:return interrupt5(previous2).pipe(as4(failCause10(signal.cause)));case OP_END:return join3(previous2).pipe(map16((chunk3)=>write(chunk3).pipe(zipRight6(void_5))))}}})}))));case OP_CURRENT:return unwrap(join3(state.fiber).pipe(map16((signal)=>{switch(signal._tag){case OP_EMIT4:return unwrap(enqueue(signal.elements));case OP_HALT:return failCause10(signal.cause);case OP_END:return void_5}})))}}return scopedWith4((scope6)=>pipeTo(toChannel2(self),producer).pipe(runIn(scope6),forkIn2(scope6))).pipe(crossRight(new StreamImpl(consumer(notStarted))))}))),die10=(defect)=>fromEffect7(die6(defect)),dieSync6=(evaluate2)=>fromEffect7(dieSync3(evaluate2)),dieMessage4=(message)=>fromEffect7(dieMessage2(message)),distributedWith=dual(2,(self,options)=>pipe(make39(),flatMap11((deferred)=>pipe(self,distributedWithDynamic({maximumLag:options.maximumLag,decide:(a)=>flatMap11(_await3(deferred),(f)=>f(a))}),flatMap11((next4)=>pipe(all5(map4(range(0,options.size-1),(id2)=>map16(next4,([key,queue])=>[[key,id2],queue]))),map16(unsafeFromArray),flatMap11((entries2)=>{let[mappings,queues]=reduceRight2(entries2,[new Map,empty2()],([mappings2,queues2],[mapping,queue])=>[mappings2.set(mapping[0],mapping[1]),pipe(queues2,prepend2(queue))]);return pipe(succeed7(deferred,(a)=>map16(options.decide(a),(f)=>(key)=>f(mappings.get(key)))),as4(Array.from(queues)))}))))))),distributedWithDynamicId={ref:0},newDistributedWithDynamicId=()=>{let current2=distributedWithDynamicId.ref;return distributedWithDynamicId.ref=current2+1,current2},distributedWithDynamic=dual(2,(self,options)=>distributedWithDynamicCallback(self,options.maximumLag,options.decide,()=>_void)),distributedWithDynamicCallback=dual(4,(self,maximumLag,decide,done11)=>pipe(acquireRelease2(make24(new Map),(ref,_)=>pipe(get11(ref),flatMap11((queues)=>pipe(queues.values(),forEach6(shutdown2))))),flatMap11((queuesRef)=>gen2(function*(){let offer6=(a)=>pipe(decide(a),flatMap11((shouldProcess)=>pipe(get11(queuesRef),flatMap11((queues)=>pipe(queues.entries(),reduce11(empty2(),(acc,[id2,queue])=>{if(shouldProcess(id2))return pipe(offer3(queue,succeed3(a)),matchCauseEffect3({onFailure:(cause3)=>isInterrupted2(cause3)?succeed9(pipe(acc,prepend2(id2))):failCause8(cause3),onSuccess:()=>succeed9(acc)}));return succeed9(acc)}),flatMap11((ids3)=>{if(isNonEmpty(ids3))return update3(queuesRef,(map22)=>{for(let id2 of ids3)map22.delete(id2);return map22});return _void}))))),asVoid3),queuesLock=yield*makeSemaphore2(1),newQueue=yield*make24(pipe(bounded3(maximumLag),flatMap11((queue)=>{let id2=newDistributedWithDynamicId();return pipe(update3(queuesRef,(map22)=>map22.set(id2,queue)),as4([id2,queue]))}))),finalize=(endTake)=>queuesLock.withPermits(1)(pipe(set5(newQueue,pipe(bounded3(1),tap3((queue)=>offer3(queue,endTake)),flatMap11((queue)=>{let id2=newDistributedWithDynamicId();return pipe(update3(queuesRef,(map22)=>map22.set(id2,queue)),as4(make3(id2,queue)))}))),zipRight4(pipe(get11(queuesRef),flatMap11((map22)=>pipe(fromIterable2(map22.values()),forEach6((queue)=>pipe(offer3(queue,endTake),catchSomeCause2((cause3)=>isInterrupted2(cause3)?some2(_void):none2()))))))),zipRight4(done11(endTake)),asVoid3));return yield*pipe(self,runForEachScoped(offer6),matchCauseEffect3({onFailure:(cause3)=>finalize(failCause3(pipe(cause3,map11(some2)))),onSuccess:()=>finalize(fail4(none2()))}),forkScoped2),queuesLock.withPermits(1)(flatten8(get11(newQueue)))})))),drain3=(self)=>new StreamImpl(drain(toChannel2(self))),drainFork=dual(2,(self,that)=>fromEffect7(make39()).pipe(flatMap16((backgroundDied)=>scopedWith4((scope5)=>toChannel2(that).pipe(drain,runIn(scope5),catchAllCause3((cause3)=>failCause6(backgroundDied,cause3)),forkIn2(scope5))).pipe(crossRight(interruptWhenDeferred2(self,backgroundDied)))))),drop3=dual(2,(self,n)=>{let loop3=(r)=>readWith({onInput:(input)=>{let dropped=pipe(input,drop2(r)),leftover=Math.max(0,r-input.length);if(isEmpty(input)||leftover>0)return loop3(leftover);return pipe(write(dropped),zipRight6(identityChannel()))},onFailure:fail11,onDone:()=>void_5});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(loop3(n))))}),dropRight=dual(2,(self,n)=>{if(n<=0)return identityStream();return suspend9(()=>{let queue=new RingBuffer(n),reader=readWith({onInput:(input)=>{let outputs=pipe(input,filterMap2((elem)=>{let head6=queue.head();return queue.put(elem),head6}));return pipe(write(outputs),flatMap13(()=>reader))},onFailure:fail11,onDone:()=>void_5});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(reader)))})}),dropUntil3=dual(2,(self,predicate)=>drop3(dropWhile4(self,(a)=>!predicate(a)),1)),dropUntilEffect=dual(2,(self,predicate)=>{let loop3=readWith({onInput:(input)=>pipe(dropUntil2(input,predicate),map16(unsafeFromArray),map16((leftover)=>{if(isEmpty(leftover))return suspend5(()=>loop3);return pipe(write(leftover),zipRight6(identityChannel()))}),unwrap),onFailure:fail11,onDone:()=>void_5});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(loop3)))}),dropWhile4=dual(2,(self,predicate)=>{let loop3=readWith({onInput:(input)=>{let output=dropWhile(input,predicate);if(isEmpty(output))return suspend5(()=>loop3);return zipRight6(write(output),identityChannel())},onFailure:fail11,onDone:succeedNow});return new StreamImpl(pipeToOrFail(toChannel2(self),loop3))}),dropWhileEffect=dual(2,(self,predicate)=>{let loop3=readWith({onInput:(input)=>pipe(dropWhile3(input,predicate),map16(unsafeFromArray),map16((leftover)=>{if(isEmpty(leftover))return suspend5(()=>loop3);return zipRight6(write(leftover),identityChannel())}),unwrap),onFailure:fail11,onDone:()=>void_5});return new StreamImpl(pipeToOrFail(toChannel2(self),loop3))}),either6=(self)=>pipe(self,map22(right2),catchAll7((error2)=>make50(left2(error2)))),empty29=new StreamImpl(void_5),ensuring7=dual(2,(self,finalizer)=>new StreamImpl(pipe(toChannel2(self),ensuring5(finalizer)))),ensuringWith2=dual(2,(self,finalizer)=>new StreamImpl(ensuringWith(toChannel2(self),finalizer))),context5=()=>fromEffect7(context3()),contextWith3=(f)=>pipe(context5(),map22(f)),contextWithEffect3=(f)=>pipe(context5(),mapEffectSequential(f)),contextWithStream=(f)=>pipe(context5(),flatMap16(f)),execute=(effect4)=>drain3(fromEffect7(effect4)),fail15=(error2)=>fromEffectOption(fail9(some2(error2))),failSync7=(evaluate2)=>fromEffectOption(failSync3(()=>some2(evaluate2()))),failCause13=(cause3)=>fromEffect7(failCause8(cause3)),failCauseSync6=(evaluate2)=>fromEffect7(failCauseSync3(evaluate2)),filter8=dual(2,(self,predicate)=>mapChunks(self,filter2(predicate))),filterEffect=dual(2,(self,f)=>{let loop3=(iterator)=>{let next4=iterator.next();if(next4.done)return readWithCause({onInput:(input)=>loop3(input[Symbol.iterator]()),onFailure:failCause10,onDone:succeed12});else return pipe(f(next4.value),map16((bool)=>bool?pipe(write(of2(next4.value)),flatMap13(()=>loop3(iterator))):loop3(iterator)),unwrap)};return new StreamImpl(suspend5(()=>pipe(toChannel2(self),pipeTo(loop3(empty2()[Symbol.iterator]())))))}),filterMap6=dual(2,(self,pf)=>mapChunks(self,filterMap2(pf))),filterMapEffect=dual(2,(self,pf)=>suspend9(()=>{let loop3=(iterator)=>{let next4=iterator.next();if(next4.done)return readWithCause({onInput:(input)=>loop3(input[Symbol.iterator]()),onFailure:failCause10,onDone:succeed12});else return pipe(pf(next4.value),match2({onNone:()=>sync4(()=>loop3(iterator)),onSome:map16((a2)=>flatMap13(write(of2(a2)),()=>loop3(iterator)))}),unwrap)};return new StreamImpl(pipe(toChannel2(self),pipeTo(loop3(empty2()[Symbol.iterator]()))))})),filterMapWhile3=dual(2,(self,pf)=>{let loop3=readWith({onInput:(input)=>{let mapped=filterMapWhile2(input,pf);if(mapped.length===input.length)return pipe(write(mapped),flatMap13(()=>loop3));return write(mapped)},onFailure:fail11,onDone:succeed12});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(loop3)))}),filterMapWhileEffect=dual(2,(self,pf)=>suspend9(()=>{let loop3=(iterator)=>{let next4=iterator.next();if(next4.done)return readWithCause({onInput:(input)=>loop3(input[Symbol.iterator]()),onFailure:failCause10,onDone:succeed12});else return unwrap(match2(pf(next4.value),{onNone:()=>succeed9(void_5),onSome:map16((a2)=>flatMap13(write(of2(a2)),()=>loop3(iterator)))}))};return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(loop3(empty2()[Symbol.iterator]()))))})),finalizer=(finalizer2)=>acquireRelease3(_void,()=>finalizer2),find2=dual(2,(self,predicate)=>{let loop3=readWith({onInput:(input)=>match2(findFirst3(input,predicate),{onNone:()=>loop3,onSome:(n)=>write(of2(n))}),onFailure:fail11,onDone:()=>void_5});return new StreamImpl(pipe(toChannel2(self),pipeTo(loop3)))}),findEffect=dual(2,(self,predicate)=>{let loop3=readWith({onInput:(input)=>pipe(findFirst6(input,predicate),map16(match2({onNone:()=>loop3,onSome:(n)=>write(of2(n))})),unwrap),onFailure:fail11,onDone:()=>void_5});return new StreamImpl(pipe(toChannel2(self),pipeTo(loop3)))}),flatMap16=dual((args2)=>isStream(args2[0]),(self,f,options)=>{let bufferSize=options?.bufferSize??16;if(options?.switch)return matchConcurrency(options?.concurrency,()=>flatMapParSwitchBuffer(self,1,bufferSize,f),(n)=>flatMapParSwitchBuffer(self,n,bufferSize,f));return matchConcurrency(options?.concurrency,()=>new StreamImpl(concatMap(toChannel2(self),(as9)=>pipe(as9,map4((a)=>toChannel2(f(a))),reduce2(void_5,(left3,right3)=>pipe(left3,zipRight6(right3)))))),(_)=>new StreamImpl(pipe(toChannel2(self),concatMap(writeChunk),mergeMap((out)=>toChannel2(f(out)),options))))}),matchConcurrency=(concurrency,sequential4,bounded8)=>{switch(concurrency){case void 0:return sequential4();case"unbounded":return bounded8(Number.MAX_SAFE_INTEGER);default:return concurrency>1?bounded8(concurrency):sequential4()}},flatMapParSwitchBuffer=dual(4,(self,n,bufferSize,f)=>new StreamImpl(pipe(toChannel2(self),concatMap(writeChunk),mergeMap((out)=>toChannel2(f(out)),{concurrency:n,mergeStrategy:BufferSliding(),bufferSize})))),flatten12=dual((args2)=>isStream(args2[0]),(self,options)=>flatMap16(self,identity,options)),flattenChunks=(self)=>{let flatten13=readWithCause({onInput:(chunks2)=>flatMap13(writeChunk(chunks2),()=>flatten13),onFailure:failCause10,onDone:()=>void_5});return new StreamImpl(pipe(toChannel2(self),pipeTo(flatten13)))},flattenEffect=dual((args2)=>isStream(args2[0]),(self,options)=>options?.unordered?flatMap16(self,(a)=>fromEffect7(a),{concurrency:options.concurrency}):matchConcurrency(options?.concurrency,()=>mapEffectSequential(self,identity),(n)=>new StreamImpl(pipe(toChannel2(self),concatMap(writeChunk),mapOutEffectPar(identity,n),mapOut(of2))))),flattenExitOption=(self)=>{let processChunk=(chunk3,cont)=>{let[toEmit,rest]=pipe(chunk3,splitWhere((exit3)=>!isSuccess2(exit3))),next4=pipe(head2(rest),match2({onNone:()=>cont,onSome:match9({onFailure:(cause3)=>match2(flipCauseOption2(cause3),{onNone:()=>void_5,onSome:failCause10}),onSuccess:()=>void_5})}));return pipe(write(pipe(toEmit,filterMap2((exit3)=>isSuccess2(exit3)?some2(exit3.value):none2()))),flatMap13(()=>next4))},process2=readWithCause({onInput:(chunk3)=>processChunk(chunk3,process2),onFailure:(cause3)=>failCause10(cause3),onDone:()=>void_5});return new StreamImpl(pipe(toChannel2(self),pipeTo(process2)))},flattenIterables=(self)=>pipe(self,map22(fromIterable2),flattenChunks),flattenTake=(self)=>flattenChunks(flattenExitOption(pipe(self,map22((take7)=>take7.exit)))),forever5=(self)=>new StreamImpl(repeated(toChannel2(self))),fromAsyncIterable=(iterable,onError3)=>pipe(acquireRelease2(sync4(()=>iterable[Symbol.asyncIterator]()),(iterator)=>iterator.return?promise2(async()=>iterator.return()):_void),map16((iterator)=>repeatEffectOption(pipe(tryPromise2({try:async()=>iterator.next(),catch:(reason)=>some2(onError3(reason))}),flatMap11((result)=>result.done?fail9(none2()):succeed9(result.value))))),unwrapScoped4),fromChannel2=(channel)=>new StreamImpl(channel),toChannel2=(stream)=>{if("channel"in stream)return stream.channel;else if(isEffect2(stream))return toChannel2(fromEffect7(stream));else throw TypeError("Expected a Stream.")},fromChunk=(chunk3)=>new StreamImpl(isEmpty(chunk3)?void_5:write(chunk3)),fromChunkPubSub=(pubsub,options)=>{if(options?.scoped){let effect4=map16(subscribe2(pubsub),fromChunkQueue);return options.shutdown?map16(effect4,ensuring7(shutdown4(pubsub))):effect4}let stream=flatMap16(scoped5(subscribe2(pubsub)),fromChunkQueue);return options?.shutdown?ensuring7(stream,shutdown4(pubsub)):stream},fromChunkQueue=(queue,options)=>pipe(take3(queue),catchAllCause3((cause3)=>pipe(isShutdown2(queue),flatMap11((isShutdown7)=>isShutdown7&&isInterrupted2(cause3)?end5():failCause12(cause3)))),repeatEffectChunkOption,options?.shutdown?ensuring7(shutdown2(queue)):identity),fromChunks=(...chunks2)=>pipe(fromIterable9(chunks2),flatMap16(fromChunk)),fromEffect7=(effect4)=>pipe(effect4,mapError3(some2),fromEffectOption),fromEffectOption=(effect4)=>new StreamImpl(unwrap(match13(effect4,{onFailure:match2({onNone:()=>void_5,onSome:fail11}),onSuccess:(a)=>write(of2(a))}))),fromPubSub=(pubsub,options)=>{let maxChunkSize=options?.maxChunkSize??DefaultChunkSize;if(options?.scoped){let effect4=map16(subscribe2(pubsub),(queue)=>fromQueue2(queue,{maxChunkSize,shutdown:!0}));return options.shutdown?map16(effect4,ensuring7(shutdown4(pubsub))):effect4}let stream=flatMap16(scoped5(subscribe2(pubsub)),(queue)=>fromQueue2(queue,{maxChunkSize}));return options?.shutdown?ensuring7(stream,shutdown4(pubsub)):stream},fromTPubSub=(pubsub)=>{return unwrapScoped4(map16(subscribeScoped2(pubsub),(queue)=>fromTQueue(queue)))},fromIterable9=(iterable)=>suspend9(()=>isChunk(iterable)?fromChunk(iterable):fromIteratorSucceed(iterable[Symbol.iterator]())),fromIterableEffect=(effect4)=>pipe(effect4,map16(fromIterable9),unwrap2),fromIteratorSucceed=(iterator,maxChunkSize=DefaultChunkSize)=>{return pipe(sync4(()=>{let builder=[],loop3=(iterator2)=>pipe(sync4(()=>{let next4=iterator2.next();if(maxChunkSize===1){if(next4.done)return void_5;return pipe(write(of2(next4.value)),flatMap13(()=>loop3(iterator2)))}builder=[];let count5=0;while(next4.done===!1){if(builder.push(next4.value),count5=count5+1,count5>=maxChunkSize)break;next4=iterator2.next()}if(count5>0)return pipe(write(unsafeFromArray(builder)),flatMap13(()=>loop3(iterator2)));return void_5}),unwrap);return new StreamImpl(loop3(iterator))}),unwrap2)},fromPull2=(effect4)=>pipe(effect4,map16(repeatEffectChunkOption),unwrapScoped4),fromQueue2=(queue,options)=>pipe(takeBetween2(queue,1,options?.maxChunkSize??DefaultChunkSize),catchAllCause3((cause3)=>pipe(isShutdown2(queue),flatMap11((isShutdown7)=>isShutdown7&&isInterrupted2(cause3)?end5():failCause12(cause3)))),repeatEffectChunkOption,options?.shutdown?ensuring7(shutdown2(queue)):identity),fromTQueue=(queue)=>pipe(take5(queue),map16(of2),catchAllCause3((cause3)=>pipe(isShutdown6(queue),flatMap11((isShutdown7)=>isShutdown7&&isInterrupted2(cause3)?end5():failCause12(cause3)))),repeatEffectChunkOption),fromSchedule=(schedule2)=>pipe(driver2(schedule2),map16((driver3)=>repeatEffectOption(driver3.next(void 0))),unwrap2),fromReadableStream=(...args2)=>{let evaluate2=args2.length===1?args2[0].evaluate:args2[0],onError3=args2.length===1?args2[0].onError:args2[1],releaseLockOnEnd=args2.length===1?args2[0].releaseLockOnEnd===!0:!1;return unwrapScoped4(map16(acquireRelease2(sync4(()=>evaluate2().getReader()),(reader)=>releaseLockOnEnd?sync4(()=>reader.releaseLock()):promise2(()=>reader.cancel())),(reader)=>repeatEffectOption(flatMap11(tryPromise2({try:()=>reader.read(),catch:(reason)=>some2(onError3(reason))}),({done:done11,value})=>done11?fail9(none2()):succeed9(value)))))},fromReadableStreamByob=(...args2)=>{let evaluate2=args2.length===1?args2[0].evaluate:args2[0],onError3=args2.length===1?args2[0].onError:args2[1],allocSize=(args2.length===1?args2[0].bufferSize:args2[2])??4096,releaseLockOnEnd=args2.length===1?args2[0].releaseLockOnEnd===!0:!1;return unwrapScoped4(map16(acquireRelease2(sync4(()=>evaluate2().getReader({mode:"byob"})),(reader)=>releaseLockOnEnd?sync4(()=>reader.releaseLock()):promise2(()=>reader.cancel())),(reader)=>catchAll7(forever5(readChunkStreamByobReader(reader,onError3,allocSize)),(error2)=>error2===EOF?empty29:fail15(error2))))},EOF=Symbol.for("effect/Stream/EOF"),readChunkStreamByobReader=(reader,onError3,size14)=>{let buffer2=new ArrayBuffer(size14);return paginateEffect(0,(offset)=>flatMap11(tryPromise2({try:()=>reader.read(new Uint8Array(buffer2,offset,buffer2.byteLength-offset)),catch:(reason)=>onError3(reason)}),({done:done11,value})=>{if(done11)return fail9(EOF);let newOffset=offset+value.byteLength;return succeed9([value,newOffset>=buffer2.byteLength?none2():some2(newOffset)])}))},groupAdjacentBy=dual(2,(self,f)=>{let groupAdjacentByChunk=(state,chunk3)=>{if(isEmpty(chunk3))return[state,empty2()];let builder=[],from=0,until=0,key=void 0,previousChunk=empty2();switch(state._tag){case"Some":{let tuple2=state.value;key=tuple2[0];let loop3=!0;while(loop3&&until<chunk3.length){let input=unsafeGet2(chunk3,until),updatedKey=f(input);if(!equals(key,updatedKey)){let previousChunk2=tuple2[1],additionalChunk=unsafeFromArray(Array.from(chunk3).slice(from,until)),group2=appendAll2(previousChunk2,additionalChunk);builder.push([key,group2]),key=updatedKey,from=until,loop3=!1}until=until+1}if(loop3)previousChunk=tuple2[1];break}case"None":{key=f(unsafeGet2(chunk3,until)),until=until+1;break}}while(until<chunk3.length){let input=unsafeGet2(chunk3,until),updatedKey=f(input);if(!equals(key,updatedKey))builder.push([key,unsafeFromArray(Array.from(chunk3).slice(from,until))]),key=updatedKey,from=until;until=until+1}let nonEmptyChunk=appendAll2(previousChunk,unsafeFromArray(Array.from(chunk3).slice(from,until))),output=unsafeFromArray(builder);return[some2([key,nonEmptyChunk]),output]},groupAdjacent=(state)=>readWithCause({onInput:(input)=>{let[updatedState,output]=groupAdjacentByChunk(state,input);return isEmpty(output)?groupAdjacent(updatedState):flatMap13(write(output),()=>groupAdjacent(updatedState))},onFailure:(cause3)=>match2(state,{onNone:()=>failCause10(cause3),onSome:(output)=>flatMap13(write(of2(output)),()=>failCause10(cause3))}),onDone:(done11)=>match2(state,{onNone:()=>succeedNow(done11),onSome:(output)=>flatMap13(write(of2(output)),()=>succeedNow(done11))})});return new StreamImpl(pipeToOrFail(toChannel2(self),groupAdjacent(none2())))}),grouped=dual(2,(self,chunkSize)=>pipe(self,rechunk(chunkSize),chunks)),groupedWithin=dual(3,(self,chunkSize,duration3)=>aggregateWithin(self,collectAllN(chunkSize),spaced2(duration3))),haltWhen=dual(2,(self,effect4)=>{let writer=(fiber)=>pipe(poll2(fiber),map16(match2({onNone:()=>readWith({onInput:(input)=>flatMap13(write(input),()=>writer(fiber)),onFailure:fail11,onDone:()=>void_5}),onSome:match9({onFailure:failCause10,onSuccess:()=>void_5})})),unwrap);return new StreamImpl(unwrapScopedWith((scope5)=>effect4.pipe(forkIn2(scope5),map16((fiber)=>toChannel2(self).pipe(pipeTo(writer(fiber)))))))}),haltAfter=dual(2,(self,duration3)=>pipe(self,haltWhen(sleep2(duration3)))),haltWhenDeferred=dual(2,(self,deferred)=>{let writer=pipe(poll3(deferred),map16(match2({onNone:()=>readWith({onInput:(input)=>pipe(write(input),flatMap13(()=>writer)),onFailure:fail11,onDone:()=>void_5}),onSome:(effect4)=>unwrap(match13(effect4,{onFailure:fail11,onSuccess:()=>void_5}))})),unwrap);return new StreamImpl(pipe(toChannel2(self),pipeTo(writer)))}),identityStream=()=>new StreamImpl(identityChannel()),interleave=dual(2,(self,that)=>pipe(self,interleaveWith(that,forever5(make50(!0,!1))))),interleaveWith=dual(3,(self,that,decider)=>{let producer=(handoff)=>readWithCause({onInput:(value)=>flatMap13(fromEffect4(offer5(handoff,of5(value))),()=>producer(handoff)),onFailure:(cause3)=>fromEffect4(offer5(handoff,failCause11(cause3))),onDone:()=>fromEffect4(offer5(handoff,end4))});return new StreamImpl(unwrapScopedWith((scope5)=>pipe(make49(),zip5(make49()),tap3(([left3])=>toChannel2(self).pipe(concatMap(writeChunk),pipeTo(producer(left3)),runIn(scope5),forkIn2(scope5))),tap3(([_,right3])=>toChannel2(that).pipe(concatMap(writeChunk),pipeTo(producer(right3)),runIn(scope5),forkIn2(scope5))),map16(([left3,right3])=>{let process2=(leftDone,rightDone)=>readWithCause({onInput:(bool)=>{if(bool&&!leftDone)return pipe(fromEffect4(take6(left3)),flatMap13(match18({onEnd:()=>rightDone?void_5:process2(!0,rightDone),onFailure:failCause10,onSuccess:(chunk3)=>pipe(write(chunk3),flatMap13(()=>process2(leftDone,rightDone)))})));if(!bool&&!rightDone)return pipe(fromEffect4(take6(right3)),flatMap13(match18({onEnd:()=>leftDone?void_5:process2(leftDone,!0),onFailure:failCause10,onSuccess:(chunk3)=>pipe(write(chunk3),flatMap13(()=>process2(leftDone,rightDone)))})));return process2(leftDone,rightDone)},onFailure:failCause10,onDone:()=>void_5});return pipe(toChannel2(decider),concatMap(writeChunk),pipeTo(process2(!1,!1)))}))))}),intersperse=dual(2,(self,element)=>new StreamImpl(pipe(toChannel2(self),pipeToOrFail(suspend5(()=>{let writer=(isFirst)=>readWithCause({onInput:(chunk3)=>{let builder=[],flagResult=isFirst;for(let output of chunk3)if(flagResult)flagResult=!1,builder.push(output);else builder.push(element),builder.push(output);return pipe(write(unsafeFromArray(builder)),flatMap13(()=>writer(flagResult)))},onFailure:failCause10,onDone:()=>void_5});return writer(!0)}))))),intersperseAffixes=dual(2,(self,{end:end6,middle,start:start3})=>pipe(make50(start3),concat2(pipe(self,intersperse(middle))),concat2(make50(end6)))),interruptAfter=dual(2,(self,duration3)=>pipe(self,interruptWhen2(sleep2(duration3)))),interruptWhen2=dual(2,(self,effect4)=>new StreamImpl(pipe(toChannel2(self),interruptWhen(effect4)))),interruptWhenDeferred2=dual(2,(self,deferred)=>new StreamImpl(pipe(toChannel2(self),interruptWhenDeferred(deferred)))),iterate3=(value,next4)=>unfold4(value,(a)=>some2([a,next4(a)])),make50=(...as9)=>fromIterable9(as9),map22=dual(2,(self,f)=>new StreamImpl(pipe(toChannel2(self),mapOut(map4(f))))),mapAccum5=dual(3,(self,s,f)=>{let accumulator=(s2)=>readWith({onInput:(input)=>{let[nextS,chunk3]=mapAccum2(input,s2,f);return flatMap13(write(chunk3),()=>accumulator(nextS))},onFailure:fail11,onDone:()=>void_5});return new StreamImpl(pipe(toChannel2(self),pipeTo(accumulator(s))))}),mapAccumEffect=dual(3,(self,s,f)=>suspend9(()=>{let accumulator=(s2)=>readWith({onInput:(input)=>pipe(suspend3(()=>{let outputs=[],emit2=(output)=>sync4(()=>{outputs.push(output)});return pipe(input,reduce11(s2,(s3,a)=>pipe(f(s3,a),flatMap11(([s4,a2])=>pipe(emit2(a2),as4(s4))))),match13({onFailure:(error2)=>{if(outputs.length!==0)return zipRight6(write(unsafeFromArray(outputs)),fail11(error2));return fail11(error2)},onSuccess:(s3)=>flatMap13(write(unsafeFromArray(outputs)),()=>accumulator(s3))}))}),unwrap),onFailure:fail11,onDone:()=>void_5});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(accumulator(s))))})),mapBoth6=dual(2,(self,options)=>pipe(self,mapError6(options.onFailure),map22(options.onSuccess))),mapChunks=dual(2,(self,f)=>new StreamImpl(pipe(toChannel2(self),mapOut(f)))),mapChunksEffect=dual(2,(self,f)=>new StreamImpl(pipe(toChannel2(self),mapOutEffect(f)))),mapConcat=dual(2,(self,f)=>pipe(self,mapConcatChunk((a)=>fromIterable2(f(a))))),mapConcatChunk=dual(2,(self,f)=>pipe(self,mapChunks(flatMap3(f)))),mapConcatChunkEffect=dual(2,(self,f)=>pipe(self,mapEffectSequential(f),mapConcatChunk(identity))),mapConcatEffect=dual(2,(self,f)=>pipe(self,mapEffectSequential((a)=>pipe(f(a),map16(fromIterable2))),mapConcatChunk(identity))),mapEffectSequential=dual(2,(self,f)=>{let loop3=(iterator)=>{let next4=iterator.next();if(next4.done)return readWithCause({onInput:(elem)=>loop3(elem[Symbol.iterator]()),onFailure:failCause10,onDone:succeed12});else{let value=next4.value;return unwrap(map16(f(value),(a2)=>flatMap13(write(of2(a2)),()=>loop3(iterator))))}};return new StreamImpl(pipe(toChannel2(self),pipeTo(suspend5(()=>loop3(empty2()[Symbol.iterator]())))))}),mapEffectPar=dual(3,(self,n,f)=>new StreamImpl(pipe(toChannel2(self),concatMap(writeChunk),mapOutEffectPar(f,n),mapOut(of2)))),mapError6=dual(2,(self,f)=>new StreamImpl(pipe(toChannel2(self),mapError5(f)))),mapErrorCause4=dual(2,(self,f)=>new StreamImpl(pipe(toChannel2(self),mapErrorCause3(f)))),merge9=dual((args2)=>isStream(args2[1]),(self,that,options)=>mergeWith3(self,that,{onSelf:identity,onOther:identity,haltStrategy:options?.haltStrategy})),mergeAll8=dual((args2)=>(Symbol.iterator in args2[0]),(streams,options)=>flatten12(fromIterable9(streams),options)),mergeWithTag=dual(2,(streams,options)=>{let values3=Object.keys(streams).map((key)=>streams[key].pipe(map22((value)=>({_tag:key,value}))));return mergeAll8(values3,options)}),mergeEither=dual(2,(self,that)=>mergeWith3(self,that,{onSelf:left2,onOther:right2})),mergeLeft=dual(2,(left3,right3)=>pipe(left3,merge9(drain3(right3)))),mergeRight=dual(2,(left3,right3)=>pipe(drain3(left3),merge9(right3))),mergeWith3=dual(3,(self,other,options)=>{let strategy=options.haltStrategy?fromInput2(options.haltStrategy):Both2,handler=(terminate)=>(exit3)=>terminate||!isSuccess2(exit3)?Done4(suspend3(()=>exit3)):Await2((exit4)=>suspend3(()=>exit4));return new StreamImpl(mergeWith2(toChannel2(map22(self,options.onSelf)),{other:toChannel2(map22(other,options.onOther)),onSelfDone:handler(strategy._tag==="Either"||strategy._tag==="Left"),onOtherDone:handler(strategy._tag==="Either"||strategy._tag==="Right")}))}),mkString2=(self)=>run4(self,mkString),never4=fromEffect7(never3),onEnd=dual(2,(self,effect4)=>concat2(self,drain3(fromEffect7(effect4)))),onError3=dual(2,(self,cleanup)=>pipe(self,catchAllCause6((cause3)=>fromEffect7(pipe(cleanup(cause3),zipRight4(failCause8(cause3))))))),onDone=dual(2,(self,cleanup)=>new StreamImpl(pipe(toChannel2(self),ensuringWith((exit3)=>isSuccess2(exit3)?cleanup():_void)))),onStart=dual(2,(self,effect4)=>unwrap2(as4(effect4,self))),orDie5=(self)=>pipe(self,orDieWith4(identity)),orDieWith4=dual(2,(self,f)=>new StreamImpl(pipe(toChannel2(self),orDieWith3(f)))),orElse8=dual(2,(self,that)=>new StreamImpl(pipe(toChannel2(self),orElse7(()=>toChannel2(that()))))),orElseEither3=dual(2,(self,that)=>pipe(self,map22(left2),orElse8(()=>pipe(that(),map22(right2))))),orElseFail3=dual(2,(self,error2)=>pipe(self,orElse8(()=>failSync7(error2)))),orElseIfEmpty=dual(2,(self,element)=>pipe(self,orElseIfEmptyChunk(()=>of2(element())))),orElseIfEmptyChunk=dual(2,(self,chunk3)=>pipe(self,orElseIfEmptyStream(()=>new StreamImpl(write(chunk3()))))),orElseIfEmptyStream=dual(2,(self,stream)=>{let writer=readWith({onInput:(input)=>{if(isEmpty(input))return suspend5(()=>writer);return pipe(write(input),zipRight6(identityChannel()))},onFailure:fail11,onDone:()=>suspend5(()=>toChannel2(stream()))});return new StreamImpl(pipe(toChannel2(self),pipeTo(writer)))}),orElseSucceed3=dual(2,(self,value)=>pipe(self,orElse8(()=>sync9(value)))),paginate=(s,f)=>paginateChunk(s,(s2)=>{let page=f(s2);return[of2(page[0]),page[1]]}),paginateChunk=(s,f)=>{let loop3=(s2)=>{let page=f(s2);return match2(page[1],{onNone:()=>zipRight6(write(page[0]),void_5),onSome:(s3)=>flatMap13(write(page[0]),()=>loop3(s3))})};return new StreamImpl(suspend5(()=>loop3(s)))},paginateChunkEffect=(s,f)=>{let loop3=(s2)=>unwrap(map16(f(s2),([chunk3,option3])=>match2(option3,{onNone:()=>zipRight6(write(chunk3),void_5),onSome:(s3)=>flatMap13(write(chunk3),()=>loop3(s3))})));return new StreamImpl(suspend5(()=>loop3(s)))},paginateEffect=(s,f)=>paginateChunkEffect(s,(s2)=>pipe(f(s2),map16(([a,s3])=>[of2(a),s3]))),peel=dual(2,(self,sink)=>{return pipe(make39(),flatMap11((deferred)=>pipe(make49(),map16((handoff)=>{let consumer=foldSink(collectLeftover(sink),{onFailure:(error2)=>zipRight7(fromEffect6(fail7(deferred,error2)),fail12(error2)),onSuccess:([z,leftovers])=>{let loop3=readWithCause({onInput:(elements)=>flatMap13(fromEffect4(offer5(handoff,{_tag:"Emit",elements})),()=>loop3),onFailure:(cause3)=>zipRight6(fromEffect4(offer5(handoff,{_tag:"Halt",cause:cause3})),failCause10(cause3)),onDone:(_)=>zipRight6(fromEffect4(offer5(handoff,{_tag:"End"})),void_5)});return fromChannel(pipe(fromEffect4(succeed7(deferred,z)),zipRight6(fromEffect4(pipe(handoff,offer5({_tag:"Emit",elements:leftovers})))),zipRight6(loop3)))}}),producer=pipe(take6(handoff),map16((signal)=>{switch(signal._tag){case"Emit":return pipe(write(signal.elements),flatMap13(()=>producer));case"Halt":return failCause10(signal.cause);case"End":return void_5}}),unwrap);return pipe(self,tapErrorCause5((cause3)=>failCause6(deferred,cause3)),run4(consumer),forkScoped2,zipRight4(_await3(deferred)),map16((z)=>[z,new StreamImpl(producer)]))}))),flatten8)}),partition5=dual((args2)=>typeof args2[1]==="function",(self,predicate,options)=>partitionEither(self,(a)=>succeed9(predicate(a)?right2(a):left2(a)),options)),partitionEither=dual((args2)=>typeof args2[1]==="function",(self,predicate,options)=>pipe(mapEffectSequential(self,predicate),distributedWith({size:2,maximumLag:options?.bufferSize??16,decide:match({onLeft:()=>succeed9((n)=>n===0),onRight:()=>succeed9((n)=>n===1)})}),flatMap11(([queue1,queue2])=>succeed9([filterMap6(flattenExitOption(fromQueue2(queue1,{shutdown:!0})),(_)=>match(_,{onLeft:some2,onRight:none2})),filterMap6(flattenExitOption(fromQueue2(queue2,{shutdown:!0})),(_)=>match(_,{onLeft:none2,onRight:some2}))])))),pipeThrough=dual(2,(self,sink)=>new StreamImpl(pipe(toChannel2(self),pipeToOrFail(toChannel(sink))))),pipeThroughChannel=dual(2,(self,channel)=>new StreamImpl(pipeTo(toChannel2(self),channel))),pipeThroughChannelOrFail=dual(2,(self,chan)=>new StreamImpl(pipe(toChannel2(self),pipeToOrFail(chan)))),prepend4=dual(2,(self,values3)=>new StreamImpl(zipRight6(write(values3),toChannel2(self)))),provideContext6=dual(2,(self,context6)=>new StreamImpl(pipe(toChannel2(self),provideContext5(context6)))),provideSomeContext2=dual(2,(self,context6)=>mapInputContext6(self,merge3(context6))),provideLayer=dual(2,(self,layer)=>new StreamImpl(unwrapScopedWith((scope5)=>buildWithScope2(layer,scope5).pipe(map16((env)=>pipe(toChannel2(self),provideContext5(env))))))),provideService6=dual(3,(self,tag,resource)=>provideServiceEffect3(self,tag,succeed9(resource))),provideServiceEffect3=dual(3,(self,tag,effect4)=>provideServiceStream(self,tag,fromEffect7(effect4))),provideServiceStream=dual(3,(self,tag,stream)=>contextWithStream((env)=>flatMap16(stream,(service3)=>pipe(self,provideContext6(add4(env,tag,service3)))))),mapInputContext6=dual(2,(self,f)=>contextWithStream((env)=>pipe(self,provideContext6(f(env))))),provideSomeLayer2=dual(2,(self,layer)=>pipe(self,provideLayer(pipe(context4(),merge8(layer))))),range2=(min4,max6,chunkSize=DefaultChunkSize)=>suspend9(()=>{if(min4>max6)return empty29;let go=(min5,max7,chunkSize2)=>{let remaining=max7-min5+1;if(remaining>chunkSize2)return pipe(write(range(min5,min5+chunkSize2-1)),flatMap13(()=>go(min5+chunkSize2,max7,chunkSize2)));return write(range(min5,min5+remaining-1))};return new StreamImpl(go(min4,max6,chunkSize))}),race3=dual(2,(left3,right3)=>raceAll3(left3,right3)),raceAll3=(...streams)=>make39().pipe(map16((halt2)=>{let winner=null;return mergeAll8(streams.map((stream,index)=>stream.pipe(takeWhile4(()=>{if(winner===null)return winner=index,unsafeDone(halt2,void_3),!0;return winner===index}),interruptWhen2(_await3(halt2).pipe(flatMap11(()=>winner===index?never3:_void))))),{concurrency:streams.length})}),unwrap2),rechunk=dual(2,(self,n)=>suspend9(()=>{let target=Math.max(n,1),process2=rechunkProcess(new StreamRechunker(target),target);return new StreamImpl(pipe(toChannel2(self),pipeTo(process2)))})),rechunkProcess=(rechunker,target)=>readWithCause({onInput:(chunk3)=>{if(chunk3.length===target&&rechunker.isEmpty())return flatMap13(write(chunk3),()=>rechunkProcess(rechunker,target));if(chunk3.length>0){let chunks2=[],result=void 0,index=0;while(index<chunk3.length){while(index<chunk3.length&&result===void 0)result=rechunker.write(pipe(chunk3,unsafeGet2(index))),index=index+1;if(result!==void 0)chunks2.push(result),result=void 0}return flatMap13(writeAll(...chunks2),()=>rechunkProcess(rechunker,target))}return suspend5(()=>rechunkProcess(rechunker,target))},onFailure:(cause3)=>zipRight6(rechunker.emitIfNotEmpty(),failCause10(cause3)),onDone:()=>rechunker.emitIfNotEmpty()});class StreamRechunker{n;builder=[];pos=0;constructor(n){this.n=n}isEmpty(){return this.pos===0}write(elem){if(this.builder.push(elem),this.pos+=1,this.pos===this.n){let result=unsafeFromArray(this.builder);return this.builder=[],this.pos=0,result}return}emitIfNotEmpty(){if(this.pos!==0)return write(unsafeFromArray(this.builder));return void_5}}var refineOrDie=dual(2,(self,pf)=>pipe(self,refineOrDieWith(pf,identity))),refineOrDieWith=dual(3,(self,pf,f)=>new StreamImpl(catchAll5(toChannel2(self),(error2)=>match2(pf(error2),{onNone:()=>failCause10(die3(f(error2))),onSome:fail11})))),repeat2=dual(2,(self,schedule2)=>filterMap6(repeatEither(self,schedule2),(_)=>match(_,{onLeft:none2,onRight:some2}))),repeatEffect=(effect4)=>repeatEffectOption(pipe(effect4,mapError3(some2))),repeatEffectChunk=(effect4)=>repeatEffectChunkOption(pipe(effect4,mapError3(some2))),repeatEffectChunkOption=(effect4)=>unfoldChunkEffect(effect4,(effect5)=>pipe(map16(effect5,(chunk3)=>some2([chunk3,effect5])),catchAll3(match2({onNone:()=>succeed9(none2()),onSome:fail9})))),repeatEffectOption=(effect4)=>repeatEffectChunkOption(pipe(effect4,map16(of2))),repeatEither=dual(2,(self,schedule2)=>repeatWith(self,schedule2,{onElement:(a)=>right2(a),onSchedule:left2})),repeatElements=dual(2,(self,schedule2)=>filterMap6(repeatElementsWith(self,schedule2,{onElement:(a)=>some2(a),onSchedule:none2}),identity)),repeatElementsWith=dual(3,(self,schedule2,options)=>{let driver3=pipe(driver2(schedule2),map16((driver4)=>{let feed=(input)=>match2(head2(input),{onNone:()=>loop3,onSome:(a)=>zipRight6(write(of2(options.onElement(a))),step4(pipe(input,drop2(1)),a))}),step4=(input,a)=>{let advance=pipe(driver4.next(a),as4(pipe(write(of2(options.onElement(a))),flatMap13(()=>step4(input,a))))),reset=pipe(driver4.last,orDie3,flatMap11((b)=>pipe(driver4.reset,map16(()=>pipe(write(of2(options.onSchedule(b))),zipRight6(feed(input)))))));return pipe(advance,orElse5(()=>reset),unwrap)},loop3=readWith({onInput:feed,onFailure:fail11,onDone:()=>void_5});return loop3}),unwrap);return new StreamImpl(pipe(toChannel2(self),pipeTo(driver3)))}),repeatValue=(value)=>new StreamImpl(repeated(write(of2(value)))),repeatWith=dual(3,(self,schedule2,options)=>{return pipe(driver2(schedule2),map16((driver3)=>{let provideLastIterationInfo=provideServiceEffect3(CurrentIterationMetadata2,get11(driver3.iterationMeta)),process2=pipe(self,provideLastIterationInfo,map22(options.onElement),toChannel2),loop3=unwrap(match13(driver3.next(void 0),{onFailure:()=>void_5,onSuccess:(output)=>flatMap13(process2,()=>zipRight6(write(of2(options.onSchedule(output))),loop3))}));return new StreamImpl(zipRight6(process2,loop3))}),unwrap2)}),repeatWithSchedule=(value,schedule2)=>repeatEffectWithSchedule(succeed9(value),schedule2),repeatEffectWithSchedule=(effect4,schedule2)=>flatMap16(fromEffect7(zip5(effect4,driver2(schedule2))),([a,driver3])=>{let provideLastIterationInfo=provideServiceEffect2(CurrentIterationMetadata2,get11(driver3.iterationMeta));return concat2(succeed15(a),unfoldEffect(a,(s)=>matchEffect2(driver3.next(s),{onFailure:succeed9,onSuccess:()=>map16(provideLastIterationInfo(effect4),(nextA)=>some2([nextA,nextA]))})))}),retry6=dual(2,(self,policy)=>driver2(policy).pipe(map16((driver3)=>{let provideLastIterationInfo=provideServiceEffect3(CurrentIterationMetadata2,get11(driver3.iterationMeta)),loop3=toChannel2(provideLastIterationInfo(self)).pipe(mapOutEffect((out)=>as4(driver3.reset,out)),catchAll5((error2)=>driver3.next(error2).pipe(match13({onFailure:()=>fail11(error2),onSuccess:()=>loop3}),unwrap)));return loop3}),unwrap,fromChannel2)),withExecutionPlan3=dual((args2)=>isStream(args2[0]),(self,policy,options)=>suspend9(()=>{let preventFallbackOnPartialStream=options?.preventFallbackOnPartialStream??!1,i=0,lastError=none2(),loop3=suspend9(()=>{let step4=policy.steps[i++];if(!step4)return fail15(getOrThrow(lastError));let nextStream=isContext2(step4.provide)?provideSomeContext2(self,step4.provide):provideSomeLayer2(self,step4.provide),receivedElements=!1;if(isSome2(lastError)){let error2=lastError.value,attempted=!1,wrapped=nextStream;nextStream=suspend9(()=>{if(attempted)return wrapped;return attempted=!0,fail15(error2)}),nextStream=scheduleDefectRefail2(retry6(nextStream,scheduleFromStep(step4,!1)))}else{let schedule2=scheduleFromStep(step4,!0);nextStream=schedule2?scheduleDefectRefail2(retry6(nextStream,schedule2)):nextStream}return catchAll7(preventFallbackOnPartialStream?mapChunks(nextStream,(chunk3)=>{return receivedElements=!0,chunk3}):nextStream,(error2)=>{if(preventFallbackOnPartialStream&&receivedElements)return fail15(error2);return lastError=some2(error2),loop3})});return loop3})),scheduleDefectRefail2=(self)=>catchAllCause6(self,(cause3)=>failCause13(scheduleDefectRefailCause(cause3))),run4=dual(2,(self,sink)=>toChannel2(self).pipe(pipeToOrFail(toChannel(sink)),runDrain)),runCollect=(self)=>run4(self,collectAll()),runCount=(self)=>run4(self,count4),runDrain2=(self)=>run4(self,drain2),runFold=dual(3,(self,s,f)=>runFoldWhile(self,s,constTrue,f)),runFoldEffect=dual(3,(self,s,f)=>runFoldWhileEffect(self,s,constTrue,f)),runFoldScoped=dual(3,(self,s,f)=>pipe(self,runFoldWhileScoped(s,constTrue,f))),runFoldScopedEffect=dual(3,(self,s,f)=>pipe(self,runFoldWhileScopedEffect(s,constTrue,f))),runFoldWhile=dual(4,(self,s,cont,f)=>run4(self,fold(s,cont,f))),runFoldWhileEffect=dual(4,(self,s,cont,f)=>run4(self,foldEffect(s,cont,f))),runFoldWhileScoped=dual(4,(self,s,cont,f)=>pipe(self,runScoped2(fold(s,cont,f)))),runFoldWhileScopedEffect=dual(4,(self,s,cont,f)=>pipe(self,runScoped2(foldEffect(s,cont,f)))),runForEach=dual(2,(self,f)=>run4(self,forEach7(f))),runForEachChunk=dual(2,(self,f)=>run4(self,forEachChunk(f))),runForEachChunkScoped=dual(2,(self,f)=>pipe(self,runScoped2(forEachChunk(f)))),runForEachScoped=dual(2,(self,f)=>pipe(self,runScoped2(forEach7(f)))),runForEachWhile=dual(2,(self,f)=>run4(self,forEachWhile(f))),runForEachWhileScoped=dual(2,(self,f)=>pipe(self,runScoped2(forEachWhile(f)))),runHead=(self)=>run4(self,head5()),runIntoPubSub=dual(2,(self,pubsub)=>pipe(self,runIntoQueue(pubsub))),runIntoPubSubScoped=dual(2,(self,pubsub)=>pipe(self,runIntoQueueScoped(pubsub))),runIntoQueue=dual(2,(self,queue)=>pipe(self,runIntoQueueScoped(queue),scoped2)),runIntoQueueElementsScoped=dual(2,(self,queue)=>{let writer=readWithCause({onInput:(input)=>flatMap13(fromEffect4(offerAll3(queue,map4(input,succeed3))),()=>writer),onFailure:(cause3)=>fromEffect4(offer3(queue,failCause3(map11(cause3,some2)))),onDone:()=>fromEffect4(offer3(queue,fail4(none2())))});return pipe(pipeTo(toChannel2(self),writer),drain,runScoped,asVoid3)}),runIntoQueueScoped=dual(2,(self,queue)=>{let writer=readWithCause({onInput:(input)=>flatMap13(write(chunk2(input)),()=>writer),onFailure:(cause3)=>write(failCause11(cause3)),onDone:()=>write(end4)});return pipe(pipeTo(toChannel2(self),writer),mapOutEffect((take7)=>offer3(queue,take7)),drain,runScoped,asVoid3)}),runLast=(self)=>run4(self,last3()),runScoped2=dual(2,(self,sink)=>pipe(toChannel2(self),pipeToOrFail(toChannel(sink)),drain,runScoped)),runSum=(self)=>run4(self,sum2),scan=dual(3,(self,s,f)=>pipe(self,scanEffect(s,(s2,a)=>succeed9(f(s2,a))))),scanReduce=dual(2,(self,f)=>pipe(self,scanReduceEffect((a2,a)=>succeed9(f(a2,a))))),scanReduceEffect=dual(2,(self,f)=>pipe(self,mapAccumEffect(none2(),(option3,a)=>{switch(option3._tag){case"None":return succeed9([some2(a),a]);case"Some":return pipe(f(option3.value,a),map16((b)=>[some2(b),b]))}}))),schedule2=dual(2,(self,schedule3)=>filterMap6(scheduleWith(self,schedule3,{onElement:some2,onSchedule:none2}),identity)),scheduleWith=dual(3,(self,schedule3,options)=>{let loop3=(driver3,iterator)=>{let next4=iterator.next();if(next4.done)return readWithCause({onInput:(chunk3)=>loop3(driver3,chunk3[Symbol.iterator]()),onFailure:failCause10,onDone:succeedNow});return unwrap(matchEffect2(driver3.next(next4.value),{onFailure:()=>pipe(driver3.last,orDie3,map16((b)=>pipe(write(make4(options.onElement(next4.value),options.onSchedule(b))),flatMap13(()=>loop3(driver3,iterator)))),zipLeft3(driver3.reset)),onSuccess:()=>succeed9(pipe(write(of2(options.onElement(next4.value))),flatMap13(()=>loop3(driver3,iterator))))}))};return new StreamImpl(pipe(fromEffect4(driver2(schedule3)),flatMap13((driver3)=>pipe(toChannel2(self),pipeTo(loop3(driver3,empty2()[Symbol.iterator]()))))))}),scanEffect=dual(3,(self,s,f)=>new StreamImpl(pipe(write(of2(s)),flatMap13(()=>toChannel2(pipe(self,mapAccumEffect(s,(s2,a)=>pipe(f(s2,a),map16((s3)=>[s3,s3]))))))))),scoped5=(effect4)=>new StreamImpl(ensuring5(scoped4(pipe(effect4,map16(of2))),_void)),scopedWith4=(f)=>new StreamImpl(scopedWith3((scope5)=>f(scope5).pipe(map16(of2)))),some5=(self)=>pipe(self,mapError6(some2),someOrFail(()=>none2())),someOrElse=dual(2,(self,fallback)=>pipe(self,map22(getOrElse(fallback)))),someOrFail=dual(2,(self,error2)=>mapEffectSequential(self,match2({onNone:()=>failSync3(error2),onSome:succeed9}))),sliding7=dual(2,(self,chunkSize)=>slidingSize(self,chunkSize,1)),slidingSize=dual(3,(self,chunkSize,stepSize)=>{if(chunkSize<=0||stepSize<=0)return die10(new IllegalArgumentException2("Invalid bounds - `chunkSize` and `stepSize` must be greater than zero"));return new StreamImpl(suspend5(()=>{let queue=new RingBuffer(chunkSize),emitOnStreamEnd=(queueSize,channelEnd)=>{if(queueSize<chunkSize){let items=queue.toChunk(),result2=isEmpty(items)?empty2():of2(items);return pipe(write(result2),flatMap13(()=>channelEnd))}let lastEmitIndex=queueSize-(queueSize-chunkSize)%stepSize;if(lastEmitIndex===queueSize)return channelEnd;let leftovers=queueSize-(lastEmitIndex-chunkSize+stepSize),lastItems=pipe(queue.toChunk(),takeRight(leftovers)),result=isEmpty(lastItems)?empty2():of2(lastItems);return pipe(write(result),flatMap13(()=>channelEnd))},reader=(queueSize)=>readWithCause({onInput:(input)=>flatMap13(write(filterMap2(input,(element,index)=>{queue.put(element);let currentIndex=queueSize+index+1;if(currentIndex<chunkSize||(currentIndex-chunkSize)%stepSize>0)return none2();return some2(queue.toChunk())})),()=>reader(queueSize+input.length)),onFailure:(cause3)=>emitOnStreamEnd(queueSize,failCause10(cause3)),onDone:()=>emitOnStreamEnd(queueSize,void_5)});return pipe(toChannel2(self),pipeTo(reader(0)))}))}),split=dual(2,(self,predicate)=>{let split2=(leftovers,input)=>{let[chunk3,remaining]=pipe(leftovers,appendAll2(input),splitWhere(predicate));if(isEmpty(chunk3)||isEmpty(remaining))return loop3(pipe(chunk3,appendAll2(pipe(remaining,drop2(1)))));return pipe(write(of2(chunk3)),flatMap13(()=>split2(empty2(),pipe(remaining,drop2(1)))))},loop3=(leftovers)=>readWith({onInput:(input)=>split2(leftovers,input),onFailure:fail11,onDone:()=>{if(isEmpty(leftovers))return void_5;if(isNone2(pipe(leftovers,findFirst3(predicate))))return zipRight6(write(of2(leftovers)),void_5);return zipRight6(split2(empty2(),leftovers),void_5)}});return new StreamImpl(pipe(toChannel2(self),pipeTo(loop3(empty2()))))}),splitOnChunk=dual(2,(self,delimiter)=>{let next4=(leftover,delimiterIndex)=>readWithCause({onInput:(inputChunk)=>{let buffer2,[carry,delimiterCursor]=pipe(inputChunk,reduce2([pipe(leftover,getOrElse(()=>empty2())),delimiterIndex],([carry2,delimiterCursor2],a)=>{let concatenated=pipe(carry2,append2(a));if(delimiterCursor2<delimiter.length&&equals(a,pipe(delimiter,unsafeGet2(delimiterCursor2)))){if(delimiterCursor2+1===delimiter.length){if(buffer2===void 0)buffer2=[];return buffer2.push(pipe(concatenated,take(concatenated.length-delimiter.length))),[empty2(),0]}return[concatenated,delimiterCursor2+1]}return[concatenated,equals(a,pipe(delimiter,unsafeGet2(0)))?1:0]})),output=buffer2===void 0?empty2():unsafeFromArray(buffer2);return flatMap13(write(output),()=>next4(isNonEmpty(carry)?some2(carry):none2(),delimiterCursor))},onFailure:(cause3)=>match2(leftover,{onNone:()=>failCause10(cause3),onSome:(chunk3)=>zipRight6(write(of2(chunk3)),failCause10(cause3))}),onDone:(done11)=>match2(leftover,{onNone:()=>succeed12(done11),onSome:(chunk3)=>zipRight6(write(of2(chunk3)),succeed12(done11))})});return new StreamImpl(pipe(toChannel2(self),pipeTo(next4(none2(),0))))}),splitLines2=(self)=>pipeThroughChannel(self,splitLines()),succeed15=(value)=>fromChunk(of2(value)),sync9=(evaluate2)=>suspend9(()=>fromChunk(of2(evaluate2()))),suspend9=(stream)=>new StreamImpl(suspend5(()=>toChannel2(stream()))),take7=dual(2,(self,n)=>{if(!Number.isInteger(n))return die10(new IllegalArgumentException2(`${n} must be an integer`));let loop3=(n2)=>readWith({onInput:(input)=>{let taken=pipe(input,take(Math.min(n2,Number.POSITIVE_INFINITY))),leftover=Math.max(0,n2-taken.length);if(leftover>0)return pipe(write(taken),flatMap13(()=>loop3(leftover)));return write(taken)},onFailure:fail11,onDone:succeed12});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(0<n?loop3(n):void_5)))}),takeRight2=dual(2,(self,n)=>{if(n<=0)return empty29;return new StreamImpl(pipe(succeed9(new RingBuffer(n)),map16((queue)=>{let reader=readWith({onInput:(input)=>{for(let element of input)queue.put(element);return reader},onFailure:fail11,onDone:()=>pipe(write(queue.toChunk()),zipRight6(void_5))});return pipe(toChannel2(self),pipeTo(reader))}),unwrap))}),takeUntil3=dual(2,(self,predicate)=>{let loop3=readWith({onInput:(input)=>{let taken=pipe(input,takeWhile((a)=>!predicate(a))),last4=pipe(input,drop2(taken.length),take(1));if(isEmpty(last4))return pipe(write(taken),flatMap13(()=>loop3));return write(pipe(taken,appendAll2(last4)))},onFailure:fail11,onDone:succeed12});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(loop3)))}),takeUntilEffect=dual(2,(self,predicate)=>{let loop3=(iterator)=>{let next4=iterator.next();if(next4.done)return readWithCause({onInput:(elem)=>loop3(elem[Symbol.iterator]()),onFailure:failCause10,onDone:succeed12});return pipe(predicate(next4.value),map16((bool)=>bool?write(of2(next4.value)):pipe(write(of2(next4.value)),flatMap13(()=>loop3(iterator)))),unwrap)};return new StreamImpl(pipe(toChannel2(self),pipeTo(loop3(empty2()[Symbol.iterator]()))))}),takeWhile4=dual(2,(self,predicate)=>{let loop3=readWith({onInput:(input)=>{let taken=pipe(input,takeWhile(predicate));if(taken.length===input.length)return pipe(write(taken),flatMap13(()=>loop3));return write(taken)},onFailure:fail11,onDone:succeed12});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(loop3)))}),tap6=dual(2,(self,f)=>mapEffectSequential(self,(a)=>as4(f(a),a))),tapBoth3=dual(2,(self,options)=>pipe(self,tapError5(options.onFailure),tap6(options.onSuccess))),tapError5=dual(2,(self,f)=>catchAll7(self,(error2)=>fromEffect7(zipRight4(f(error2),fail9(error2))))),tapErrorCause5=dual(2,(self,f)=>{let loop3=readWithCause({onInput:(chunk3)=>flatMap13(write(chunk3),()=>loop3),onFailure:(cause3)=>fromEffect4(zipRight4(f(cause3),failCause8(cause3))),onDone:succeedNow});return new StreamImpl(pipe(toChannel2(self),pipeTo(loop3)))}),tapSink=dual(2,(self,sink)=>pipe(fromEffect7(all5([bounded3(1),make39()])),flatMap16(([queue,deferred])=>{let right3=flattenTake(fromQueue2(queue,{maxChunkSize:1})),loop3=readWithCause({onInput:(chunk3)=>pipe(fromEffect4(offer3(queue,chunk2(chunk3))),foldCauseChannel({onFailure:()=>flatMap13(write(chunk3),()=>identityChannel()),onSuccess:()=>flatMap13(write(chunk3),()=>loop3)})),onFailure:(cause3)=>pipe(fromEffect4(offer3(queue,failCause11(cause3))),foldCauseChannel({onFailure:()=>failCause10(cause3),onSuccess:()=>failCause10(cause3)})),onDone:()=>pipe(fromEffect4(offer3(queue,end4)),foldCauseChannel({onFailure:()=>void_5,onSuccess:()=>void_5}))});return pipe(new StreamImpl(pipe(pipeTo(toChannel2(self),loop3),ensuring5(zipRight4(forkDaemon2(offer3(queue,end4)),_await3(deferred))))),merge9(execute(pipe(run4(right3,sink),ensuring3(zipRight4(shutdown2(queue),succeed7(deferred,void 0)))))))}))),throttle=dual(2,(self,options)=>throttleEffect(self,{...options,cost:(chunk3)=>succeed9(options.cost(chunk3))})),throttleEffect=dual(2,(self,options)=>{if(options.strategy==="enforce")return throttleEnforceEffect(self,options.cost,options.units,options.duration,options.burst??0);return throttleShapeEffect(self,options.cost,options.units,options.duration,options.burst??0)}),throttleEnforceEffect=(self,cost,units,duration3,burst)=>{let loop3=(tokens,timestampMillis)=>readWithCause({onInput:(input)=>pipe(cost(input),zip5(currentTimeMillis2),map16(([weight,currentTimeMillis3])=>{let cycles=(currentTimeMillis3-timestampMillis)/toMillis(duration3),sum3=tokens+cycles*units,max6=units+burst<0?Number.POSITIVE_INFINITY:units+burst,available=sum3<0?max6:Math.min(sum3,max6);if(weight<=available)return pipe(write(input),flatMap13(()=>loop3(available-weight,currentTimeMillis3)));return loop3(tokens,timestampMillis)}),unwrap),onFailure:failCause10,onDone:()=>void_5}),throttled=pipe(currentTimeMillis2,map16((currentTimeMillis3)=>loop3(units,currentTimeMillis3)),unwrap);return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(throttled)))},throttleShapeEffect=(self,costFn,units,duration3,burst)=>{let loop3=(tokens,timestampMillis)=>readWithCause({onInput:(input)=>pipe(costFn(input),zip5(currentTimeMillis2),map16(([weight,currentTimeMillis3])=>{let cycles=(currentTimeMillis3-timestampMillis)/toMillis(duration3),sum3=tokens+cycles*units,max6=units+burst<0?Number.POSITIVE_INFINITY:units+burst,remaining=(sum3<0?max6:Math.min(sum3,max6))-weight,waitCycles=remaining>=0?0:-remaining/units,delay3=millis(Math.max(0,waitCycles*toMillis(duration3)));if(greaterThan2(delay3,zero))return pipe(fromEffect4(sleep2(delay3)),zipRight6(write(input)),flatMap13(()=>loop3(remaining,currentTimeMillis3)));return flatMap13(write(input),()=>loop3(remaining,currentTimeMillis3))}),unwrap),onFailure:failCause10,onDone:()=>void_5}),throttled=pipe(currentTimeMillis2,map16((currentTimeMillis3)=>loop3(units,currentTimeMillis3)),unwrap);return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(throttled)))},tick=(interval)=>repeatWithSchedule(void 0,spaced2(interval)),timeout3=dual(2,(self,duration3)=>pipe(toPull2(self),map16(timeoutFail2({onTimeout:()=>none2(),duration:duration3})),fromPull2)),timeoutFail3=dual(3,(self,error2,duration3)=>pipe(self,timeoutTo3(duration3,failSync7(error2)))),timeoutFailCause3=dual(3,(self,cause3,duration3)=>pipe(toPull2(self),map16(timeoutFailCause2({onTimeout:()=>map11(cause3(),some2),duration:duration3})),fromPull2)),timeoutTo3=dual(3,(self,duration3,that)=>{let StreamTimeout=new RuntimeException2("Stream Timeout");return pipe(self,timeoutFailCause3(()=>die3(StreamTimeout),duration3),catchSomeCause3((cause3)=>isDieType2(cause3)&&isRuntimeException2(cause3.defect)&&cause3.defect.message!==void 0&&cause3.defect.message==="Stream Timeout"?some2(that):none2()))}),pubsubFromOptions=(options)=>{if(typeof options==="number")return bounded5(options);else if(options.capacity==="unbounded")return unbounded5({replay:options.replay});switch(options.strategy){case"dropping":return dropping4(options);case"sliding":return sliding4(options);default:return bounded5(options)}},toPubSub2=dual(2,(self,capacity7)=>pipe(acquireRelease2(pubsubFromOptions(capacity7),(pubsub)=>shutdown4(pubsub)),tap3((pubsub)=>pipe(self,runIntoPubSubScoped(pubsub),forkScoped2)))),toPull2=(self)=>map16(toPull(toChannel2(self)),(pull)=>pipe(pull,mapError3(some2),flatMap11(match({onLeft:()=>fail9(none2()),onRight:succeed9})))),toQueue2=dual((args2)=>isStream(args2[0]),(self,options)=>tap3(acquireRelease2(options?.strategy==="unbounded"?unbounded3():options?.strategy==="dropping"?dropping2(options.capacity??2):options?.strategy==="sliding"?sliding2(options.capacity??2):bounded3(options?.capacity??2),(queue)=>shutdown2(queue)),(queue)=>forkScoped2(runIntoQueueScoped(self,queue)))),toQueueOfElements=dual((args2)=>isStream(args2[0]),(self,options)=>tap3(acquireRelease2(bounded3(options?.capacity??2),(queue)=>shutdown2(queue)),(queue)=>forkScoped2(runIntoQueueElementsScoped(self,queue)))),toReadableStream=dual((args2)=>isStream(args2[0]),(self,options)=>toReadableStreamRuntime(self,defaultRuntime2,options)),toReadableStreamEffect=dual((args2)=>isStream(args2[0]),(self,options)=>map16(runtime3(),(runtime4)=>toReadableStreamRuntime(self,runtime4,options))),toReadableStreamRuntime=dual((args2)=>isStream(args2[0]),(self,runtime4,options)=>{let runFork4=runFork3(runtime4),currentResolve=void 0,fiber=void 0,latch=unsafeMakeLatch2(!1);return new ReadableStream({start(controller){fiber=runFork4(runForEachChunk(self,(chunk3)=>{if(chunk3.length===0)return _void;return latch.whenOpen(sync4(()=>{latch.unsafeClose();for(let item of chunk3)controller.enqueue(item);currentResolve(),currentResolve=void 0}))})),fiber.addObserver((exit3)=>{try{if(exit3._tag==="Failure")controller.error(squash(exit3.cause));else controller.close()}catch{}})},pull(){return new Promise((resolve)=>{currentResolve=resolve,runSync(latch.open)})},cancel(){if(!fiber)return;return runPromise(asVoid3(interrupt5(fiber)))}},options?.strategy)}),transduce=dual(2,(self,sink)=>{let newChannel=suspend5(()=>{let leftovers={ref:empty2()},upstreamDone={ref:!1},buffer2=suspend5(()=>{let leftover=leftovers.ref;if(isEmpty(leftover))return readWith({onInput:(input)=>pipe(write(input),flatMap13(()=>buffer2)),onFailure:fail11,onDone:succeedNow});return leftovers.ref=empty2(),pipe(writeChunk(leftover),flatMap13(()=>buffer2))}),concatAndGet=(chunk3)=>{let leftover=leftovers.ref,concatenated=appendAll2(leftover,filter2(chunk3,(chunk4)=>chunk4.length!==0));return leftovers.ref=concatenated,concatenated},upstreamMarker=readWith({onInput:(input)=>flatMap13(write(input),()=>upstreamMarker),onFailure:fail11,onDone:(done11)=>zipRight6(sync7(()=>{upstreamDone.ref=!0}),succeedNow(done11))}),transducer=pipe(sink,toChannel,collectElements,flatMap13(([leftover,z])=>pipe(succeed12([upstreamDone.ref,concatAndGet(leftover)]),flatMap13(([done11,newLeftovers])=>{let nextChannel=done11&&isEmpty(newLeftovers)?void_5:transducer;return pipe(write(of2(z)),flatMap13(()=>nextChannel))}))));return pipe(toChannel2(self),pipeTo(upstreamMarker),pipeTo(buffer2),pipeToOrFail(transducer))});return new StreamImpl(newChannel)}),toAsyncIterableRuntime=dual((args2)=>isStream(args2[0]),(self,runtime4)=>{let runFork4=runFork3(runtime4);return{[Symbol.asyncIterator](){let currentResolve=void 0,currentReject=void 0,fiber=void 0,latch=unsafeMakeLatch2(!1),returned=!1;return{next(){if(!fiber)fiber=runFork4(runForEach(self,(value)=>latch.whenOpen(sync4(()=>{latch.unsafeClose(),currentResolve({done:!1,value}),currentResolve=currentReject=void 0})))),fiber.addObserver((exit3)=>{if(returned)return;fiber=runFork2(latch.whenOpen(sync4(()=>{if(exit3._tag==="Failure")currentReject(squash(exit3.cause));else currentResolve({done:!0,value:void 0});currentResolve=currentReject=void 0})))});return new Promise((resolve,reject)=>{currentResolve=resolve,currentReject=reject,latch.unsafeOpen()})},return(){if(returned=!0,!fiber)return Promise.resolve({done:!0,value:void 0});return runPromise(as4(interrupt5(fiber),{done:!0,value:void 0}))}}}}}),toAsyncIterable=(self)=>toAsyncIterableRuntime(self,defaultRuntime2),toAsyncIterableEffect=(self)=>map16(runtime3(),(runtime4)=>toAsyncIterableRuntime(self,runtime4)),unfold4=(s,f)=>unfoldChunk(s,(s2)=>pipe(f(s2),map2(([a,s3])=>[of2(a),s3]))),unfoldChunk=(s,f)=>{let loop3=(s2)=>match2(f(s2),{onNone:()=>void_5,onSome:([chunk3,s3])=>flatMap13(write(chunk3),()=>loop3(s3))});return new StreamImpl(suspend5(()=>loop3(s)))},unfoldChunkEffect=(s,f)=>suspend9(()=>{let loop3=(s2)=>unwrap(map16(f(s2),match2({onNone:()=>void_5,onSome:([chunk3,s3])=>flatMap13(write(chunk3),()=>loop3(s3))})));return new StreamImpl(loop3(s))}),unfoldEffect=(s,f)=>unfoldChunkEffect(s,(s2)=>pipe(f(s2),map16(map2(([a,s3])=>[of2(a),s3])))),void_7=succeed15(void 0);var unwrap2=(effect4)=>flatten12(fromEffect7(effect4)),unwrapScoped4=(effect4)=>flatten12(scoped5(effect4)),unwrapScopedWith3=(f)=>flatten12(scopedWith4((scope5)=>f(scope5))),updateService4=dual(3,(self,tag,f)=>pipe(self,mapInputContext6((context6)=>pipe(context6,add4(tag,f(pipe(context6,unsafeGet4(tag)))))))),when3=dual(2,(self,test)=>pipe(self,whenEffect3(sync4(test)))),whenCase=(evaluate2,pf)=>whenCaseEffect(pf)(sync4(evaluate2)),whenCaseEffect=dual(2,(self,pf)=>pipe(fromEffect7(self),flatMap16((a)=>pipe(pf(a),getOrElse(()=>empty29))))),whenEffect3=dual(2,(self,effect4)=>pipe(fromEffect7(effect4),flatMap16((bool)=>bool?self:empty29))),withSpan6=function(){let dataFirst=typeof arguments[0]!=="string",name=dataFirst?arguments[1]:arguments[0],options=addSpanStackTrace(dataFirst?arguments[2]:arguments[1]);if(dataFirst){let self=arguments[0];return new StreamImpl(withSpan5(toChannel2(self),name,options))}return(self)=>new StreamImpl(withSpan5(toChannel2(self),name,options))},zip7=dual(2,(self,that)=>pipe(self,zipWith11(that,(a,a2)=>[a,a2]))),zipFlatten=dual(2,(self,that)=>pipe(self,zipWith11(that,(a,a2)=>[...a,a2]))),zipAll=dual(2,(self,options)=>zipAllWith(self,{other:options.other,onSelf:(a)=>[a,options.defaultOther],onOther:(a2)=>[options.defaultSelf,a2],onBoth:(a,a2)=>[a,a2]})),zipAllLeft=dual(3,(self,other,defaultSelf)=>zipAllWith(self,{other,onSelf:identity,onOther:()=>defaultSelf,onBoth:(a)=>a})),zipAllRight=dual(3,(self,other,defaultRight)=>zipAllWith(self,{other,onSelf:()=>defaultRight,onOther:identity,onBoth:(_,a2)=>a2})),zipAllSortedByKey=dual(2,(self,options)=>zipAllSortedByKeyWith(self,{other:options.other,onSelf:(a)=>[a,options.defaultOther],onOther:(a2)=>[options.defaultSelf,a2],onBoth:(a,a2)=>[a,a2],order:options.order})),zipAllSortedByKeyLeft=dual(2,(self,options)=>zipAllSortedByKeyWith(self,{other:options.other,onSelf:identity,onOther:()=>options.defaultSelf,onBoth:(a)=>a,order:options.order})),zipAllSortedByKeyRight=dual(2,(self,options)=>zipAllSortedByKeyWith(self,{other:options.other,onSelf:()=>options.defaultOther,onOther:identity,onBoth:(_,a2)=>a2,order:options.order})),zipAllSortedByKeyWith=dual(2,(self,options)=>{let pull=(state,pullLeft,pullRight)=>{switch(state._tag){case OP_DRAIN_LEFT:return pipe(pullLeft,match13({onFailure:fail4,onSuccess:(leftChunk)=>succeed3([map4(leftChunk,([k,a])=>[k,options.onSelf(a)]),DrainLeft])}));case OP_DRAIN_RIGHT:return pipe(pullRight,match13({onFailure:fail4,onSuccess:(rightChunk)=>succeed3([map4(rightChunk,([k,a2])=>[k,options.onOther(a2)]),DrainRight])}));case OP_PULL_BOTH:return pipe(unsome(pullLeft),zip5(unsome(pullRight),{concurrent:!0}),matchEffect2({onFailure:(error2)=>succeed9(fail4(some2(error2))),onSuccess:([leftOption,rightOption])=>{if(isSome2(leftOption)&&isSome2(rightOption)){if(isEmpty(leftOption.value)&&isEmpty(rightOption.value))return pull(PullBoth,pullLeft,pullRight);if(isEmpty(leftOption.value))return pull(PullLeft(rightOption.value),pullLeft,pullRight);if(isEmpty(rightOption.value))return pull(PullRight(leftOption.value),pullLeft,pullRight);return succeed9(succeed3(merge10(leftOption.value,rightOption.value)))}if(isSome2(leftOption)&&isNone2(rightOption)){if(isEmpty(leftOption.value))return pull(DrainLeft,pullLeft,pullRight);return succeed9(succeed3([pipe(leftOption.value,map4(([k,a])=>[k,options.onSelf(a)])),DrainLeft]))}if(isNone2(leftOption)&&isSome2(rightOption)){if(isEmpty(rightOption.value))return pull(DrainRight,pullLeft,pullRight);return succeed9(succeed3([pipe(rightOption.value,map4(([k,a2])=>[k,options.onOther(a2)])),DrainRight]))}return succeed9(fail4(none2()))}}));case OP_PULL_LEFT:return matchEffect2(pullLeft,{onFailure:match2({onNone:()=>succeed9(succeed3([pipe(state.rightChunk,map4(([k,a2])=>[k,options.onOther(a2)])),DrainRight])),onSome:(error2)=>succeed9(fail4(some2(error2)))}),onSuccess:(leftChunk)=>isEmpty(leftChunk)?pull(PullLeft(state.rightChunk),pullLeft,pullRight):succeed9(succeed3(merge10(leftChunk,state.rightChunk)))});case OP_PULL_RIGHT:return matchEffect2(pullRight,{onFailure:match2({onNone:()=>succeed9(succeed3([map4(state.leftChunk,([k,a])=>[k,options.onSelf(a)]),DrainLeft])),onSome:(error2)=>succeed9(fail4(some2(error2)))}),onSuccess:(rightChunk)=>isEmpty(rightChunk)?pull(PullRight(state.leftChunk),pullLeft,pullRight):succeed9(succeed3(merge10(state.leftChunk,rightChunk)))})}},merge10=(leftChunk,rightChunk)=>{let hasNext=(chunk3,index)=>index<chunk3.length-1,builder=[],state=void 0,leftIndex=0,rightIndex=0,leftTuple=pipe(leftChunk,unsafeGet2(leftIndex)),rightTuple=pipe(rightChunk,unsafeGet2(rightIndex)),k1=leftTuple[0],a=leftTuple[1],k2=rightTuple[0],a2=rightTuple[1],loop3=!0;while(loop3){let compare=options.order(k1,k2);if(compare===0)if(builder.push([k1,options.onBoth(a,a2)]),hasNext(leftChunk,leftIndex)&&hasNext(rightChunk,rightIndex))leftIndex=leftIndex+1,rightIndex=rightIndex+1,leftTuple=pipe(leftChunk,unsafeGet2(leftIndex)),rightTuple=pipe(rightChunk,unsafeGet2(rightIndex)),k1=leftTuple[0],a=leftTuple[1],k2=rightTuple[0],a2=rightTuple[1];else if(hasNext(leftChunk,leftIndex))state=PullRight(pipe(leftChunk,drop2(leftIndex+1))),loop3=!1;else if(hasNext(rightChunk,rightIndex))state=PullLeft(pipe(rightChunk,drop2(rightIndex+1))),loop3=!1;else state=PullBoth,loop3=!1;else if(compare<0)if(builder.push([k1,options.onSelf(a)]),hasNext(leftChunk,leftIndex))leftIndex=leftIndex+1,leftTuple=pipe(leftChunk,unsafeGet2(leftIndex)),k1=leftTuple[0],a=leftTuple[1];else{let rightBuilder=[];rightBuilder.push(rightTuple);while(hasNext(rightChunk,rightIndex))rightIndex=rightIndex+1,rightTuple=pipe(rightChunk,unsafeGet2(rightIndex)),rightBuilder.push(rightTuple);state=PullLeft(unsafeFromArray(rightBuilder)),loop3=!1}else if(builder.push([k2,options.onOther(a2)]),hasNext(rightChunk,rightIndex))rightIndex=rightIndex+1,rightTuple=pipe(rightChunk,unsafeGet2(rightIndex)),k2=rightTuple[0],a2=rightTuple[1];else{let leftBuilder=[];leftBuilder.push(leftTuple);while(hasNext(leftChunk,leftIndex))leftIndex=leftIndex+1,leftTuple=pipe(leftChunk,unsafeGet2(leftIndex)),leftBuilder.push(leftTuple);state=PullRight(unsafeFromArray(leftBuilder)),loop3=!1}}return[unsafeFromArray(builder),state]};return combineChunks(self,options.other,PullBoth,pull)}),zipAllWith=dual(2,(self,options)=>{let pull=(state,pullLeft,pullRight)=>{switch(state._tag){case OP_DRAIN_LEFT:return matchEffect2(pullLeft,{onFailure:(error2)=>succeed9(fail4(error2)),onSuccess:(leftChunk)=>succeed9(succeed3([map4(leftChunk,options.onSelf),DrainLeft]))});case OP_DRAIN_RIGHT:return matchEffect2(pullRight,{onFailure:(error2)=>succeed9(fail4(error2)),onSuccess:(rightChunk)=>succeed9(succeed3([map4(rightChunk,options.onOther),DrainRight]))});case OP_PULL_BOTH:return pipe(unsome(pullLeft),zip5(unsome(pullRight),{concurrent:!0}),matchEffect2({onFailure:(error2)=>succeed9(fail4(some2(error2))),onSuccess:([leftOption,rightOption])=>{if(isSome2(leftOption)&&isSome2(rightOption)){if(isEmpty(leftOption.value)&&isEmpty(rightOption.value))return pull(PullBoth,pullLeft,pullRight);if(isEmpty(leftOption.value))return pull(PullLeft(rightOption.value),pullLeft,pullRight);if(isEmpty(rightOption.value))return pull(PullRight(leftOption.value),pullLeft,pullRight);return succeed9(succeed3(zip8(leftOption.value,rightOption.value,options.onBoth)))}if(isSome2(leftOption)&&isNone2(rightOption))return succeed9(succeed3([map4(leftOption.value,options.onSelf),DrainLeft]));if(isNone2(leftOption)&&isSome2(rightOption))return succeed9(succeed3([map4(rightOption.value,options.onOther),DrainRight]));return succeed9(fail4(none2()))}}));case OP_PULL_LEFT:return matchEffect2(pullLeft,{onFailure:match2({onNone:()=>succeed9(succeed3([map4(state.rightChunk,options.onOther),DrainRight])),onSome:(error2)=>succeed9(fail4(some2(error2)))}),onSuccess:(leftChunk)=>{if(isEmpty(leftChunk))return pull(PullLeft(state.rightChunk),pullLeft,pullRight);if(isEmpty(state.rightChunk))return pull(PullRight(leftChunk),pullLeft,pullRight);return succeed9(succeed3(zip8(leftChunk,state.rightChunk,options.onBoth)))}});case OP_PULL_RIGHT:return matchEffect2(pullRight,{onFailure:match2({onNone:()=>succeed9(succeed3([map4(state.leftChunk,options.onSelf),DrainLeft])),onSome:(error2)=>succeed9(fail4(some2(error2)))}),onSuccess:(rightChunk)=>{if(isEmpty(rightChunk))return pull(PullRight(state.leftChunk),pullLeft,pullRight);if(isEmpty(state.leftChunk))return pull(PullLeft(rightChunk),pullLeft,pullRight);return succeed9(succeed3(zip8(state.leftChunk,rightChunk,options.onBoth)))}})}},zip8=(leftChunk,rightChunk,f)=>{let[output,either7]=zipChunks(leftChunk,rightChunk,f);switch(either7._tag){case"Left":{if(isEmpty(either7.left))return[output,PullBoth];return[output,PullRight(either7.left)]}case"Right":{if(isEmpty(either7.right))return[output,PullBoth];return[output,PullLeft(either7.right)]}}};return combineChunks(self,options.other,PullBoth,pull)}),zipLatest=dual(2,(left3,right3)=>pipe(left3,zipLatestWith(right3,(a,a2)=>[a,a2]))),zipLatestAll=(...streams)=>{if(streams.length===0)return empty29;else if(streams.length===1)return map22(streams[0],(x)=>[x]);let[head6,...tail]=streams;return zipLatestWith(head6,zipLatestAll(...tail),(first,second)=>[first,...second])},zipLatestWith=dual(3,(left3,right3,f)=>{let pullNonEmpty=(pull)=>pipe(pull,flatMap11((chunk3)=>isEmpty(chunk3)?pullNonEmpty(pull):succeed9(chunk3)));return pipe(toPull2(left3),map16(pullNonEmpty),zip5(pipe(toPull2(right3),map16(pullNonEmpty))),flatMap11(([left4,right4])=>pipe(fromEffectOption(raceWith2(left4,right4,{onSelfDone:(leftDone,rightFiber)=>pipe(suspend3(()=>leftDone),zipWith6(join3(rightFiber),(l,r)=>[l,r,!0])),onOtherDone:(rightDone,leftFiber)=>pipe(suspend3(()=>rightDone),zipWith6(join3(leftFiber),(l,r)=>[r,l,!1]))})),flatMap16(([l,r,leftFirst])=>pipe(fromEffect7(make24([unsafeLast(l),unsafeLast(r)])),flatMap16((latest)=>pipe(fromChunk(leftFirst?pipe(r,map4((a2)=>f(unsafeLast(l),a2))):pipe(l,map4((a)=>f(a,unsafeLast(r))))),concat2(pipe(repeatEffectOption(left4),mergeEither(repeatEffectOption(right4)),mapEffectSequential(match({onLeft:(leftChunk)=>modify4(latest,([_,rightLatest])=>[pipe(leftChunk,map4((a)=>f(a,rightLatest))),[unsafeLast(leftChunk),rightLatest]]),onRight:(rightChunk)=>modify4(latest,([leftLatest,_])=>[pipe(rightChunk,map4((a2)=>f(leftLatest,a2))),[leftLatest,unsafeLast(rightChunk)]])})),flatMap16(fromChunk))))))),toPull2)),fromPull2)}),zipLeft6=dual(2,(left3,right3)=>pipe(left3,zipWithChunks(right3,(left4,right4)=>{if(left4.length>right4.length)return[pipe(left4,take(right4.length)),left2(pipe(left4,take(right4.length)))];return[left4,right2(pipe(right4,drop2(left4.length)))]}))),zipRight9=dual(2,(left3,right3)=>pipe(left3,zipWithChunks(right3,(left4,right4)=>{if(left4.length>right4.length)return[right4,left2(pipe(left4,take(right4.length)))];return[pipe(right4,take(left4.length)),right2(pipe(right4,drop2(left4.length)))]}))),zipWith11=dual(3,(left3,right3,f)=>pipe(left3,zipWithChunks(right3,(leftChunk,rightChunk)=>zipChunks(leftChunk,rightChunk,f)))),zipWithChunks=dual(3,(self,that,f)=>{let pull=(state,pullLeft,pullRight)=>{switch(state._tag){case OP_PULL_BOTH2:return pipe(unsome(pullLeft),zip5(unsome(pullRight),{concurrent:!0}),matchEffect2({onFailure:(error2)=>succeed9(fail4(some2(error2))),onSuccess:([leftOption,rightOption])=>{if(isSome2(leftOption)&&isSome2(rightOption)){if(isEmpty(leftOption.value)&&isEmpty(rightOption.value))return pull(PullBoth2,pullLeft,pullRight);if(isEmpty(leftOption.value))return pull(PullLeft2(rightOption.value),pullLeft,pullRight);if(isEmpty(rightOption.value))return pull(PullRight2(leftOption.value),pullLeft,pullRight);return succeed9(succeed3(zip8(leftOption.value,rightOption.value)))}return succeed9(fail4(none2()))}}));case OP_PULL_LEFT2:return matchEffect2(pullLeft,{onFailure:(error2)=>succeed9(fail4(error2)),onSuccess:(leftChunk)=>{if(isEmpty(leftChunk))return pull(PullLeft2(state.rightChunk),pullLeft,pullRight);if(isEmpty(state.rightChunk))return pull(PullRight2(leftChunk),pullLeft,pullRight);return succeed9(succeed3(zip8(leftChunk,state.rightChunk)))}});case OP_PULL_RIGHT2:return matchEffect2(pullRight,{onFailure:(error2)=>succeed9(fail4(error2)),onSuccess:(rightChunk)=>{if(isEmpty(rightChunk))return pull(PullRight2(state.leftChunk),pullLeft,pullRight);if(isEmpty(state.leftChunk))return pull(PullLeft2(rightChunk),pullLeft,pullRight);return succeed9(succeed3(zip8(state.leftChunk,rightChunk)))}})}},zip8=(leftChunk,rightChunk)=>{let[output,either7]=f(leftChunk,rightChunk);switch(either7._tag){case"Left":{if(isEmpty(either7.left))return[output,PullBoth2];return[output,PullRight2(either7.left)]}case"Right":{if(isEmpty(either7.right))return[output,PullBoth2];return[output,PullLeft2(either7.right)]}}};return pipe(self,combineChunks(that,PullBoth2,pull))}),zipWithIndex=(self)=>pipe(self,mapAccum5(0,(index,a)=>[index+1,[a,index]])),zipWithNext=(self)=>{let process2=(last4)=>readWithCause({onInput:(input)=>{let[newLast,chunk3]=mapAccum2(input,last4,(prev,curr)=>[some2(curr),pipe(prev,map2((a)=>[a,curr]))]),output=filterMap2(chunk3,(option3)=>isSome2(option3)?some2([option3.value[0],some2(option3.value[1])]):none2());return flatMap13(write(output),()=>process2(newLast))},onFailure:failCause10,onDone:()=>match2(last4,{onNone:()=>void_5,onSome:(value)=>zipRight6(write(of2([value,none2()])),void_5)})});return new StreamImpl(pipe(toChannel2(self),pipeToOrFail(process2(none2()))))},zipWithPrevious=(self)=>pipe(self,mapAccum5(none2(),(prev,curr)=>[some2(curr),[prev,curr]])),zipWithPreviousAndNext=(self)=>pipe(zipWithNext(zipWithPrevious(self)),map22(([[prev,curr],next4])=>[prev,curr,pipe(next4,map2((tuple2)=>tuple2[1]))])),zipChunks=(left3,right3,f)=>{if(left3.length>right3.length)return[pipe(left3,take(right3.length),zipWith2(right3,f)),left2(pipe(left3,drop2(right3.length)))];return[pipe(left3,zipWith2(pipe(right3,take(left3.length)),f)),right2(pipe(right3,drop2(left3.length)))]},Do3=succeed15({}),bind4=dual((args2)=>typeof args2[0]!=="string",(self,tag,f,options)=>flatMap16(self,(k)=>map22(f(k),(a)=>({...k,[tag]:a})),options)),bindTo4=bindTo(map22),let_4=let_(map22);var decodeText=dual((args2)=>isStream(args2[0]),(self,encoding="utf-8")=>suspend9(()=>{let decoder=new TextDecoder(encoding);return map22(self,(s)=>decoder.decode(s))})),encodeText=(self)=>suspend9(()=>{let encoder=new TextEncoder;return map22(self,(s)=>encoder.encode(s))}),fromEventListener=(target,type,options)=>asyncPush((emit2)=>acquireRelease2(sync4(()=>target.addEventListener(type,emit2.single,options)),()=>sync4(()=>target.removeEventListener(type,emit2.single,options))),{bufferSize:typeof options==="object"?options.bufferSize:void 0});var GroupBySymbolKey="effect/GroupBy",GroupByTypeId=Symbol.for(GroupBySymbolKey),groupByVariance={_R:(_)=>_,_E:(_)=>_,_K:(_)=>_,_V:(_)=>_},isGroupBy=(u)=>hasProperty(u,GroupByTypeId),evaluate2=dual((args2)=>isGroupBy(args2[0]),(self,f,options)=>flatMap16(self.grouped,([key,queue])=>f(key,flattenTake(fromQueue2(queue,{shutdown:!0}))),{concurrency:"unbounded",bufferSize:options?.bufferSize??16}));var make51=(grouped2)=>({[GroupByTypeId]:groupByVariance,pipe(){return pipeArguments(this,arguments)},grouped:grouped2}),groupBy=dual((args2)=>isStream(args2[0]),(self,f,options)=>make51(unwrapScoped4(gen2(function*(){let decider=yield*make39(),output=yield*acquireRelease2(bounded3(options?.bufferSize??16),(queue)=>shutdown2(queue)),ref=yield*make24(new Map),add5=yield*pipe(mapEffectSequential(self,f),distributedWithDynamicCallback(options?.bufferSize??16,([key,value])=>flatMap11(_await3(decider),(f2)=>f2(key,value)),(exit3)=>offer3(output,exit3)));return yield*succeed7(decider,(key,_)=>pipe(get11(ref),map16((map23)=>fromNullable(map23.get(key))),flatMap11(match2({onNone:()=>flatMap11(add5,([index,queue])=>zipRight4(update3(ref,(map23)=>map23.set(key,index)),pipe(offer3(output,succeed3([key,mapDequeue(queue,(exit3)=>new TakeImpl(pipe(exit3,map12((tuple2)=>of2(tuple2[1])))))])),as4((n)=>n===index)))),onSome:(index)=>succeed9((n)=>n===index)})))),flattenExitOption(fromQueue2(output,{shutdown:!0}))})))),mapEffectOptions=dual((args2)=>typeof args2[0]!=="function",(self,f,options)=>{if(options?.key)return evaluate2(groupByKey(self,options.key,{bufferSize:options.bufferSize}),(_,s)=>mapEffectSequential(s,f));return matchConcurrency(options?.concurrency,()=>mapEffectSequential(self,f),(n)=>options?.unordered?flatMap16(self,(a)=>fromEffect7(f(a)),{concurrency:n}):mapEffectPar(self,n,f))}),bindEffect=dual((args2)=>typeof args2[0]!=="string",(self,tag,f,options)=>mapEffectOptions(self,(k)=>map16(f(k),(a)=>({...k,[tag]:a})),options)),mapDequeue=(dequeue,f)=>new MapDequeue(dequeue,f);class MapDequeue extends Class{dequeue;f;[DequeueTypeId2]={_Out:(_)=>_};constructor(dequeue,f){super();this.dequeue=dequeue,this.f=f}capacity(){return capacity3(this.dequeue)}get size(){return size10(this.dequeue)}unsafeSize(){return this.dequeue.unsafeSize()}get awaitShutdown(){return awaitShutdown2(this.dequeue)}isActive(){return this.dequeue.isActive()}get isShutdown(){return isShutdown2(this.dequeue)}get shutdown(){return shutdown2(this.dequeue)}get isFull(){return isFull2(this.dequeue)}get isEmpty(){return isEmpty11(this.dequeue)}get take(){return pipe(take3(this.dequeue),map16((a)=>this.f(a)))}get takeAll(){return pipe(takeAll2(this.dequeue),map16(map4((a)=>this.f(a))))}takeUpTo(max6){return pipe(takeUpTo2(this.dequeue,max6),map16(map4((a)=>this.f(a))))}takeBetween(min4,max6){return pipe(takeBetween2(this.dequeue,min4,max6),map16(map4((a)=>this.f(a))))}takeN(n){return pipe(takeN2(this.dequeue,n),map16(map4((a)=>this.f(a))))}poll(){return pipe(poll6(this.dequeue),map16(map2((a)=>this.f(a))))}pipe(){return pipeArguments(this,arguments)}commit(){return this.take}}var groupByKey=dual((args2)=>typeof args2[0]!=="function",(self,f,options)=>{let loop3=(map23,outerQueue)=>readWithCause({onInput:(input)=>flatMap13(fromEffect4(forEach6(groupByIterable(input,f),([key,values3])=>{let innerQueue=map23.get(key);if(innerQueue===void 0)return pipe(bounded3(options?.bufferSize??16),flatMap11((innerQueue2)=>pipe(sync4(()=>{map23.set(key,innerQueue2)}),zipRight4(offer3(outerQueue,of5([key,innerQueue2]))),zipRight4(pipe(offer3(innerQueue2,chunk2(values3)),catchSomeCause2((cause3)=>isInterruptedOnly2(cause3)?some2(_void):none2()))))));return catchSomeCause2(offer3(innerQueue,chunk2(values3)),(cause3)=>isInterruptedOnly2(cause3)?some2(_void):none2())},{discard:!0})),()=>loop3(map23,outerQueue)),onFailure:(cause3)=>fromEffect4(offer3(outerQueue,failCause11(cause3))),onDone:()=>fromEffect4(pipe(forEach6(map23.entries(),([_,innerQueue])=>pipe(offer3(innerQueue,end4),catchSomeCause2((cause3)=>isInterruptedOnly2(cause3)?some2(_void):none2())),{discard:!0}),zipRight4(offer3(outerQueue,end4))))});return make51(unwrapScopedWith3((scope5)=>gen2(function*(){let map23=new Map,queue=yield*unbounded3();return yield*addFinalizer2(scope5,shutdown2(queue)),yield*toChannel2(self).pipe(pipeTo(loop3(map23,queue)),drain,runIn(scope5),forkIn2(scope5),as4(flattenTake(fromQueue2(queue,{shutdown:!0}))))})))}),groupByIterable=dual(2,(iterable,f)=>{let builder=[],iterator=iterable[Symbol.iterator](),map23=new Map,next4;while((next4=iterator.next())&&!next4.done){let value=next4.value,key=f(value);if(map23.has(key))map23.get(key).push(value);else{let innerBuilder=[value];builder.push([key,innerBuilder]),map23.set(key,innerBuilder)}}return unsafeFromArray(builder.map((tuple2)=>[tuple2[0],unsafeFromArray(tuple2[1])]))});var StreamTypeId3=StreamTypeId2,DefaultChunkSize2=DefaultChunkSize,accumulate2=accumulate,accumulateChunks2=accumulateChunks,acquireRelease4=acquireRelease3,aggregate2=aggregate,aggregateWithin2=aggregateWithin,aggregateWithinEither2=aggregateWithinEither,as9=as8,_async2=_async;var asyncEffect4=asyncEffect3,asyncPush2=asyncPush,asyncScoped2=asyncScoped,branchAfter2=branchAfter,broadcast2=broadcast,share2=share,broadcastDynamic2=broadcastDynamic,broadcastedQueues2=broadcastedQueues,broadcastedQueuesDynamic2=broadcastedQueuesDynamic,buffer2=buffer,bufferChunks2=bufferChunks,catchAll8=catchAll7,catchAllCause7=catchAllCause6,catchSome4=catchSome3,catchTag4=catchTag3,catchTags4=catchTags3,catchSomeCause4=catchSomeCause3,changes2=changes,changesWith2=changesWith,changesWithEffect2=changesWithEffect,chunks2=chunks,chunksWith2=chunksWith,combine10=combine9,combineChunks2=combineChunks,concat3=concat2,concatAll3=concatAll2,cross2=cross,crossLeft2=crossLeft,crossRight2=crossRight,crossWith2=crossWith,debounce2=debounce,die11=die10,dieSync7=dieSync6,dieMessage5=dieMessage4,distributedWith2=distributedWith,distributedWithDynamic2=distributedWithDynamic,drain4=drain3,drainFork2=drainFork,drop4=drop3,dropRight2=dropRight,dropUntil4=dropUntil3,dropUntilEffect2=dropUntilEffect,dropWhile5=dropWhile4,dropWhileEffect2=dropWhileEffect,either7=either6,empty30=empty29,ensuring8=ensuring7,ensuringWith3=ensuringWith2,context6=context5,contextWith4=contextWith3,contextWithEffect4=contextWithEffect3,contextWithStream2=contextWithStream,execute2=execute,fail16=fail15,failSync8=failSync7,failCause14=failCause13,failCauseSync7=failCauseSync6,filter9=filter8,filterEffect2=filterEffect,filterMap7=filterMap6,filterMapEffect2=filterMapEffect,filterMapWhile4=filterMapWhile3,filterMapWhileEffect2=filterMapWhileEffect,finalizer2=finalizer,find3=find2,findEffect2=findEffect,flatMap17=flatMap16,flatten13=flatten12,flattenChunks2=flattenChunks,flattenEffect2=flattenEffect,flattenExitOption2=flattenExitOption,flattenIterables2=flattenIterables,flattenTake2=flattenTake,forever6=forever5,fromAsyncIterable2=fromAsyncIterable,fromChannel3=fromChannel2,toChannel3=toChannel2,fromChunk2=fromChunk,fromChunkPubSub2=fromChunkPubSub,fromChunkQueue2=fromChunkQueue,fromChunks2=fromChunks,fromEffect8=fromEffect7,fromEffectOption2=fromEffectOption,fromPubSub2=fromPubSub,fromTPubSub2=fromTPubSub,fromIterable10=fromIterable9,fromIterableEffect2=fromIterableEffect,fromIteratorSucceed2=fromIteratorSucceed,fromPull3=fromPull2,fromQueue3=fromQueue2,fromTQueue2=fromTQueue,fromReadableStream2=fromReadableStream,fromReadableStreamByob2=fromReadableStreamByob,fromSchedule2=fromSchedule,groupAdjacentBy2=groupAdjacentBy,groupBy2=groupBy,groupByKey2=groupByKey,grouped2=grouped,groupedWithin2=groupedWithin,haltAfter2=haltAfter,haltWhen2=haltWhen,haltWhenDeferred2=haltWhenDeferred,identity4=identityStream,interleave2=interleave,interleaveWith2=interleaveWith,intersperse2=intersperse,intersperseAffixes2=intersperseAffixes,interruptAfter2=interruptAfter,interruptWhen3=interruptWhen2,interruptWhenDeferred3=interruptWhenDeferred2,iterate4=iterate3,make52=make50,map23=map22,mapAccum6=mapAccum5,mapAccumEffect2=mapAccumEffect,mapBoth7=mapBoth6,mapChunks2=mapChunks,mapChunksEffect2=mapChunksEffect,mapConcat2=mapConcat,mapConcatChunk2=mapConcatChunk,mapConcatChunkEffect2=mapConcatChunkEffect,mapConcatEffect2=mapConcatEffect,mapEffect5=mapEffectOptions,mapError7=mapError6,mapErrorCause5=mapErrorCause4,merge10=merge9,mergeAll9=mergeAll8,mergeWithTag2=mergeWithTag,mergeWith4=mergeWith3,mergeEither2=mergeEither,mergeLeft2=mergeLeft,mergeRight2=mergeRight,mkString3=mkString2,never5=never4,onEnd2=onEnd,onError4=onError3,onDone2=onDone,onStart2=onStart,orDie6=orDie5,orDieWith5=orDieWith4,orElse9=orElse8,orElseEither4=orElseEither3,orElseFail4=orElseFail3,orElseIfEmpty2=orElseIfEmpty,orElseIfEmptyChunk2=orElseIfEmptyChunk,orElseIfEmptyStream2=orElseIfEmptyStream,orElseSucceed4=orElseSucceed3,paginate2=paginate,paginateChunk2=paginateChunk,paginateChunkEffect2=paginateChunkEffect,paginateEffect2=paginateEffect,partition6=partition5,partitionEither2=partitionEither,peel2=peel,pipeThrough2=pipeThrough,pipeThroughChannel2=pipeThroughChannel,pipeThroughChannelOrFail2=pipeThroughChannelOrFail,prepend5=prepend4,provideContext7=provideContext6,provideSomeContext3=provideSomeContext2,provideLayer2=provideLayer,provideService7=provideService6,provideServiceEffect4=provideServiceEffect3,provideServiceStream2=provideServiceStream,mapInputContext7=mapInputContext6,provideSomeLayer3=provideSomeLayer2,race4=race3,raceAll4=raceAll3,range3=range2,rechunk2=rechunk,refineOrDie2=refineOrDie,refineOrDieWith2=refineOrDieWith,repeat3=repeat2,repeatEffect2=repeatEffect,repeatEffectChunk2=repeatEffectChunk,repeatEffectChunkOption2=repeatEffectChunkOption,repeatEffectOption2=repeatEffectOption,repeatEffectWithSchedule2=repeatEffectWithSchedule,repeatEither2=repeatEither,repeatElements2=repeatElements,repeatElementsWith2=repeatElementsWith,repeatValue2=repeatValue,repeatWith2=repeatWith,retry7=retry6,withExecutionPlan4=withExecutionPlan3,run5=run4,runCollect2=runCollect,runCount2=runCount,runDrain3=runDrain2,runFold2=runFold,runFoldEffect2=runFoldEffect,runFoldScoped2=runFoldScoped,runFoldScopedEffect2=runFoldScopedEffect,runFoldWhile2=runFoldWhile,runFoldWhileEffect2=runFoldWhileEffect,runFoldWhileScoped2=runFoldWhileScoped,runFoldWhileScopedEffect2=runFoldWhileScopedEffect,runForEach2=runForEach,runForEachChunk2=runForEachChunk,runForEachChunkScoped2=runForEachChunkScoped,runForEachScoped2=runForEachScoped,runForEachWhile2=runForEachWhile,runForEachWhileScoped2=runForEachWhileScoped,runHead2=runHead,runIntoPubSub2=runIntoPubSub,runIntoPubSubScoped2=runIntoPubSubScoped,runIntoQueue2=runIntoQueue,runIntoQueueElementsScoped2=runIntoQueueElementsScoped,runIntoQueueScoped2=runIntoQueueScoped,runLast2=runLast,runScoped3=runScoped2,runSum2=runSum,scan2=scan,scanEffect2=scanEffect,scanReduce2=scanReduce,scanReduceEffect2=scanReduceEffect,schedule3=schedule2,scheduleWith2=scheduleWith,scoped6=scoped5,scopedWith5=scopedWith4,sliding8=sliding7,slidingSize2=slidingSize,some6=some5,someOrElse2=someOrElse,someOrFail2=someOrFail,split2=split,splitOnChunk2=splitOnChunk,splitLines3=splitLines2,succeed16=succeed15,sync10=sync9,suspend10=suspend9,take8=take7,takeRight3=takeRight2,takeUntil4=takeUntil3,takeUntilEffect2=takeUntilEffect,takeWhile5=takeWhile4,tap7=tap6,tapBoth4=tapBoth3,tapError6=tapError5,tapErrorCause6=tapErrorCause5,tapSink2=tapSink,throttle2=throttle,throttleEffect2=throttleEffect,tick2=tick,timeout4=timeout3,timeoutFail4=timeoutFail3,timeoutFailCause4=timeoutFailCause3,timeoutTo4=timeoutTo3,toPubSub3=toPubSub2,toPull3=toPull2,toQueue3=toQueue2,toQueueOfElements2=toQueueOfElements,toReadableStream2=toReadableStream,toReadableStreamEffect2=toReadableStreamEffect,toReadableStreamRuntime2=toReadableStreamRuntime,toAsyncIterableRuntime2=toAsyncIterableRuntime,toAsyncIterableEffect2=toAsyncIterableEffect,toAsyncIterable2=toAsyncIterable,transduce2=transduce,unfold5=unfold4,unfoldChunk2=unfoldChunk,unfoldChunkEffect2=unfoldChunkEffect,unfoldEffect2=unfoldEffect,void_8=void_7;var unwrap3=unwrap2,unwrapScoped5=unwrapScoped4,unwrapScopedWith4=unwrapScopedWith3,updateService5=updateService4,when4=when3,whenCase2=whenCase,whenCaseEffect2=whenCaseEffect,whenEffect4=whenEffect3,withSpan7=withSpan6,zip8=zip7,zipFlatten2=zipFlatten,zipAll2=zipAll,zipAllLeft2=zipAllLeft,zipAllRight2=zipAllRight,zipAllSortedByKey2=zipAllSortedByKey,zipAllSortedByKeyLeft2=zipAllSortedByKeyLeft,zipAllSortedByKeyRight2=zipAllSortedByKeyRight,zipAllSortedByKeyWith2=zipAllSortedByKeyWith,zipAllWith2=zipAllWith,zipLatest2=zipLatest,zipLatestAll2=zipLatestAll,zipLatestWith2=zipLatestWith,zipLeft7=zipLeft6,zipRight10=zipRight9,zipWith12=zipWith11,zipWithChunks2=zipWithChunks,zipWithNext2=zipWithNext,zipWithPrevious2=zipWithPrevious,zipWithPreviousAndNext2=zipWithPreviousAndNext,zipWithIndex2=zipWithIndex,Do4=Do3,bind5=bind4,bindEffect2=bindEffect,bindTo5=bindTo4,let_5=let_4;var decodeText2=decodeText,encodeText2=encodeText,fromEventListener2=fromEventListener;var exports_Config={};__export(exports_Config,{zipWith:()=>zipWith14,zip:()=>zip10,withDescription:()=>withDescription2,withDefault:()=>withDefault2,validate:()=>validate4,url:()=>url2,unwrap:()=>unwrap5,sync:()=>sync12,suspend:()=>suspend12,succeed:()=>succeed18,string:()=>string3,secret:()=>secret2,repeat:()=>repeat5,redacted:()=>redacted2,primitive:()=>primitive2,port:()=>port2,orElseIf:()=>orElseIf2,orElse:()=>orElse11,option:()=>option4,number:()=>number5,nonEmptyString:()=>nonEmptyString2,nested:()=>nested3,mapOrFail:()=>mapOrFail2,mapAttempt:()=>mapAttempt2,map:()=>map25,logLevel:()=>logLevel2,literal:()=>literal2,isConfig:()=>isConfig2,integer:()=>integer2,hashSet:()=>hashSet3,hashMap:()=>hashMap3,fail:()=>fail18,duration:()=>duration4,date:()=>date2,chunk:()=>chunk4,branded:()=>branded2,boolean:()=>boolean2,array:()=>array5,all:()=>all8,ConfigTypeId:()=>ConfigTypeId2});var isMissingDataOnly2=isMissingDataOnly;var RedactedSymbolKey="effect/Redacted",redactedRegistry=globalValue("effect/Redacted/redactedRegistry",()=>new WeakMap),RedactedTypeId=Symbol.for(RedactedSymbolKey),proto12={[RedactedTypeId]:{_A:(_)=>_},pipe(){return pipeArguments(this,arguments)},toString(){return"<redacted>"},toJSON(){return"<redacted>"},[NodeInspectSymbol](){return"<redacted>"},[symbol](){return pipe(hash(RedactedSymbolKey),combine(hash(redactedRegistry.get(this))),cached(this))},[symbol2](that){return isRedacted(that)&&equals(redactedRegistry.get(this),redactedRegistry.get(that))}},isRedacted=(u)=>hasProperty(u,RedactedTypeId),make53=(value)=>{let redacted=Object.create(proto12);return redactedRegistry.set(redacted,value),redacted};var SecretSymbolKey="effect/Secret",SecretTypeId=Symbol.for(SecretSymbolKey);var SecretProto={...proto12,[SecretTypeId]:SecretTypeId},make54=(bytes)=>{let secret=Object.create(SecretProto);return Object.defineProperty(secret,"toString",{enumerable:!1,value(){return"Secret(<redacted>)"}}),Object.defineProperty(secret,"toJSON",{enumerable:!1,value(){return"<redacted>"}}),Object.defineProperty(secret,"raw",{enumerable:!1,value:bytes}),redactedRegistry.set(secret,bytes.map((byte)=>String.fromCharCode(byte)).join("")),secret};var fromString=(text)=>{return make54(text.split("").map((char)=>char.charCodeAt(0)))};var ConfigSymbolKey="effect/Config",ConfigTypeId=Symbol.for(ConfigSymbolKey),configVariance={_A:(_)=>_},proto13={...CommitPrototype,[ConfigTypeId]:configVariance,commit(){return config(this)}},boolean=(name)=>{let config2=primitive("a boolean property",(text)=>{switch(text){case"true":case"yes":case"on":case"1":return right2(!0);case"false":case"no":case"off":case"0":return right2(!1);default:{let error2=InvalidData([],`Expected a boolean value but received ${formatUnknown(text)}`);return left2(error2)}}});return name===void 0?config2:nested2(config2,name)},url=(name)=>{let config2=primitive("an URL property",(text)=>try_({try:()=>new URL(text),catch:(_)=>InvalidData([],`Expected an URL value but received ${formatUnknown(text)}`)}));return name===void 0?config2:nested2(config2,name)},port=(name)=>{let config2=primitive("a network port property",(text)=>{let result=Number(text);if(Number.isNaN(result)||result.toString()!==text.toString()||!Number.isInteger(result)||result<1||result>65535)return left2(InvalidData([],`Expected a network port value but received ${formatUnknown(text)}`));return right2(result)});return name===void 0?config2:nested2(config2,name)},array4=(config2,name)=>{return pipe(chunk3(config2,name),map24(toArray2))},chunk3=(config2,name)=>{return map24(name===void 0?repeat4(config2):nested2(repeat4(config2),name),unsafeFromArray)},date=(name)=>{let config2=primitive("a date property",(text)=>{let result=Date.parse(text);if(Number.isNaN(result))return left2(InvalidData([],`Expected a Date value but received ${formatUnknown(text)}`));return right2(new Date(result))});return name===void 0?config2:nested2(config2,name)},fail17=(message)=>{let fail18=Object.create(proto13);return fail18._tag=OP_FAIL2,fail18.message=message,fail18.parse=()=>left2(Unsupported([],message)),fail18},number4=(name)=>{let config2=primitive("a number property",(text)=>{let result=Number(text);if(Number.isNaN(result))return left2(InvalidData([],`Expected a number value but received ${formatUnknown(text)}`));return right2(result)});return name===void 0?config2:nested2(config2,name)},integer=(name)=>{let config2=primitive("an integer property",(text)=>{let result=Number(text);if(!Number.isInteger(result))return left2(InvalidData([],`Expected an integer value but received ${formatUnknown(text)}`));return right2(result)});return name===void 0?config2:nested2(config2,name)},literal=(...literals)=>(name)=>{let valuesString=literals.map(String).join(", "),config2=primitive(`one of (${valuesString})`,(text)=>{let found=literals.find((value)=>String(value)===text);if(found===void 0)return left2(InvalidData([],`Expected one of (${valuesString}) but received ${formatUnknown(text)}`));return right2(found)});return name===void 0?config2:nested2(config2,name)},logLevel=(name)=>{let config2=mapOrFail(string2(),(value)=>{let label=value.toUpperCase(),level=allLogLevels.find((level2)=>level2.label===label);return level===void 0?left2(InvalidData([],`Expected a log level but received ${formatUnknown(value)}`)):right2(level)});return name===void 0?config2:nested2(config2,name)},duration3=(name)=>{let config2=mapOrFail(string2(),(value)=>{let duration4=decodeUnknown(value);return fromOption2(duration4,()=>InvalidData([],`Expected a duration but received ${formatUnknown(value)}`))});return name===void 0?config2:nested2(config2,name)},map24=dual(2,(self,f)=>mapOrFail(self,(a)=>right2(f(a)))),mapAttempt=dual(2,(self,f)=>mapOrFail(self,(a)=>{try{return right2(f(a))}catch(error2){return left2(InvalidData([],error2 instanceof Error?error2.message:`${error2}`))}})),mapOrFail=dual(2,(self,f)=>{let mapOrFail2=Object.create(proto13);return mapOrFail2._tag=OP_MAP_OR_FAIL,mapOrFail2.original=self,mapOrFail2.mapOrFail=f,mapOrFail2}),nested2=dual(2,(self,name)=>{let nested3=Object.create(proto13);return nested3._tag=OP_NESTED,nested3.name=name,nested3.config=self,nested3}),orElse10=dual(2,(self,that)=>{let fallback=Object.create(proto13);return fallback._tag=OP_FALLBACK,fallback.first=self,fallback.second=suspend11(that),fallback.condition=constTrue,fallback}),orElseIf=dual(2,(self,options)=>{let fallback=Object.create(proto13);return fallback._tag=OP_FALLBACK,fallback.first=self,fallback.second=suspend11(options.orElse),fallback.condition=options.if,fallback}),option3=(self)=>{return pipe(self,map24(some2),orElseIf({orElse:()=>succeed17(none2()),if:isMissingDataOnly2}))},primitive=(description,parse2)=>{let primitive2=Object.create(proto13);return primitive2._tag=OP_PRIMITIVE,primitive2.description=description,primitive2.parse=parse2,primitive2},repeat4=(self)=>{let repeat5=Object.create(proto13);return repeat5._tag=OP_SEQUENCE,repeat5.config=self,repeat5},secret=(name)=>{let config2=primitive("a secret property",(text)=>right2(fromString(text)));return name===void 0?config2:nested2(config2,name)},redacted=(nameOrConfig)=>{let config2=isConfig(nameOrConfig)?nameOrConfig:string2(nameOrConfig);return map24(config2,make53)},branded=dual(2,(nameOrConfig,constructor)=>{let config2=isConfig(nameOrConfig)?nameOrConfig:string2(nameOrConfig);return mapOrFail(config2,(a)=>constructor.either(a).pipe(mapLeft((brandErrors)=>InvalidData([],brandErrors.map((brandError)=>brandError.message).join(`
41
- `)))))}),hashSet2=(config2,name)=>{let newConfig=map24(chunk3(config2),fromIterable5);return name===void 0?newConfig:nested2(newConfig,name)},string2=(name)=>{let config2=primitive("a text property",right2);return name===void 0?config2:nested2(config2,name)},nonEmptyString=(name)=>{let config2=primitive("a non-empty text property",liftPredicate((text)=>text.length>0,()=>MissingData([],"Expected a non-empty string")));return name===void 0?config2:nested2(config2,name)},all7=(arg)=>{if(Array.isArray(arg))return tuple2(arg);else if(Symbol.iterator in arg)return tuple2([...arg]);return struct3(arg)},struct3=(r)=>{let entries2=Object.entries(r),result=pipe(entries2[0][1],map24((value)=>({[entries2[0][0]]:value})));if(entries2.length===1)return result;let rest=entries2.slice(1);for(let[key,config2]of rest)result=pipe(result,zipWith13(config2,(record,value)=>({...record,[key]:value})));return result},succeed17=(value)=>{let constant2=Object.create(proto13);return constant2._tag=OP_CONSTANT,constant2.value=value,constant2.parse=()=>right2(value),constant2},suspend11=(config2)=>{let lazy=Object.create(proto13);return lazy._tag=OP_LAZY,lazy.config=config2,lazy},sync11=(value)=>{return suspend11(()=>succeed17(value()))},hashMap2=(config2,name)=>{let table2=Object.create(proto13);return table2._tag=OP_HASHMAP,table2.valueConfig=config2,name===void 0?table2:nested2(table2,name)},isConfig=(u)=>hasProperty(u,ConfigTypeId),tuple2=(tuple3)=>{if(tuple3.length===0)return succeed17([]);if(tuple3.length===1)return map24(tuple3[0],(x)=>[x]);let result=map24(tuple3[0],(x)=>[x]);for(let i=1;i<tuple3.length;i++){let config2=tuple3[i];result=pipe(result,zipWith13(config2,(tuple4,value)=>[...tuple4,value]))}return result},unwrap4=(wrapped)=>{if(isConfig(wrapped))return wrapped;return struct3(Object.fromEntries(Object.entries(wrapped).map(([k,a])=>[k,unwrap4(a)])))},validate3=dual(2,(self,{message,validation})=>mapOrFail(self,(a)=>{if(validation(a))return right2(a);return left2(InvalidData([],message))})),withDefault=dual(2,(self,def)=>orElseIf(self,{orElse:()=>succeed17(def),if:isMissingDataOnly2})),withDescription=dual(2,(self,description)=>{let described=Object.create(proto13);return described._tag=OP_DESCRIBED,described.config=self,described.description=description,described}),zip9=dual(2,(self,that)=>zipWith13(self,that,(a,b)=>[a,b])),zipWith13=dual(3,(self,that,f)=>{let zipWith14=Object.create(proto13);return zipWith14._tag=OP_ZIP_WITH,zipWith14.left=self,zipWith14.right=that,zipWith14.zip=f,zipWith14});var ConfigTypeId2=ConfigTypeId,all8=all7,array5=array4,boolean2=boolean,port2=port,url2=url,chunk4=chunk3,date2=date,fail18=fail17,number5=number4,integer2=integer,literal2=literal,logLevel2=logLevel,duration4=duration3,isConfig2=isConfig,map25=map24,mapAttempt2=mapAttempt,mapOrFail2=mapOrFail,nested3=nested2,orElse11=orElse10,orElseIf2=orElseIf,option4=option3,primitive2=primitive,repeat5=repeat4,secret2=secret,redacted2=redacted,branded2=branded,hashSet3=hashSet2,string3=string2,nonEmptyString2=nonEmptyString,succeed18=succeed17,suspend12=suspend11,sync12=sync11,hashMap3=hashMap2,unwrap5=unwrap4,validate4=validate3,withDefault2=withDefault,withDescription2=withDescription,zip10=zip9,zipWith14=zipWith13;var exports_BunRuntime={};__export(exports_BunRuntime,{runMain:()=>runMain3});var defaultLogger2=defaultLogger;var prettyLoggerDefault2=prettyLoggerDefault;var defaultTeardown=(exit3,onExit4)=>{onExit4(isFailure3(exit3)&&!isInterruptedOnly2(exit3.cause)?1:0)},addPrettyLogger=(refs,fiberId3)=>{let loggers=getOrDefault2(refs,currentLoggers2);if(!has3(loggers,defaultLogger2))return refs;return updateAs2(refs,{fiberId:fiberId3,fiberRef:currentLoggers2,value:loggers.pipe(remove4(defaultLogger2),add2(prettyLoggerDefault2))})},makeRunMain=(f)=>dual((args2)=>isEffect2(args2[0]),(effect4,options)=>{let fiber=options?.disableErrorReporting===!0?runFork2(effect4,{updateRefs:options?.disablePrettyLogger===!0?void 0:addPrettyLogger}):runFork2(tapErrorCause3(effect4,(cause3)=>{if(isInterruptedOnly2(cause3))return _void;return logError2(cause3)}),{updateRefs:options?.disablePrettyLogger===!0?void 0:addPrettyLogger}),teardown=options?.teardown??defaultTeardown;return f({fiber,teardown})});var runMain=makeRunMain(({fiber,teardown})=>{let keepAlive=setInterval(constVoid,2147483647),receivedSignal=!1;fiber.addObserver((exit3)=>{if(!receivedSignal)process.removeListener("SIGINT",onSigint),process.removeListener("SIGTERM",onSigint);clearInterval(keepAlive),teardown(exit3,(code)=>{if(receivedSignal||code!==0)process.exit(code)})});function onSigint(){receivedSignal=!0,process.removeListener("SIGINT",onSigint),process.removeListener("SIGTERM",onSigint),fiber.unsafeInterruptAsFork(fiber.id())}process.on("SIGINT",onSigint),process.on("SIGTERM",onSigint)});var runMain2=runMain;var runMain3=runMain2;var exports_Console={};__export(exports_Console,{withTime:()=>withTime2,withGroup:()=>withGroup2,withConsole:()=>withConsole3,warn:()=>warn2,trace:()=>trace2,timeLog:()=>timeLog2,time:()=>time2,table:()=>table2,setConsole:()=>setConsole2,log:()=>log4,info:()=>info2,group:()=>group2,error:()=>error2,dirxml:()=>dirxml2,dir:()=>dir2,debug:()=>debug2,countReset:()=>countReset2,count:()=>count5,consoleWith:()=>consoleWith3,clear:()=>clear2,assert:()=>assert2,TypeId:()=>TypeId18,Console:()=>Console});var TypeId18=TypeId8,Console=consoleTag,withConsole3=withConsole,setConsole2=setConsole,consoleWith3=consoleWith,assert2=assert,clear2=clear,count5=count,countReset2=countReset,debug2=debug,dir2=dir,dirxml2=dirxml,error2=error,group2=group,info2=info,log4=log2,table2=table,time2=time,timeLog2=timeLog,trace2=trace,warn2=warn,withGroup2=withGroup,withTime2=withTime;var BUILD_COMMIT="72aad04",BUILD_VERSION="0.0.3";var CLIConfig=exports_Data.struct,RedistailConfig=exports_Data.struct,PubSubMessage=exports_Data.struct,StreamMessage=exports_Data.struct;class CLIError extends exports_Data.TaggedError("CLIError"){}class ConfigError extends exports_Data.TaggedError("ConfigError"){}class MonitoringError extends exports_Data.TaggedError("MonitoringError"){}var StreamMonitorOptions=exports_Data.struct,isValidConnectionType=(type)=>type==="pubsub"||type==="stream",isValidTopicName=(name)=>typeof name==="string"&&name.trim().length>0,createInvalidArgumentError=(message,context7)=>new CLIError({reason:"InvalidArguments",message,context:context7}),createMissingArgumentError=(message,context7)=>new CLIError({reason:"MissingArguments",message,context:context7}),createEnvironmentError=(message,cause3,context7)=>new ConfigError({reason:"InvalidEnvironment",message,cause:cause3,context:context7});var createConnectionLostError=(message,cause3)=>new MonitoringError({reason:"ConnectionLost",message,retryable:!0,cause:cause3}),createSubscriptionFailedError=(message,retryable=!0,cause3)=>new MonitoringError({reason:"SubscriptionFailed",message,retryable,cause:cause3}),createStreamReadFailedError=(message,retryable=!0,cause3)=>new MonitoringError({reason:"StreamReadFailed",message,retryable,cause:cause3}),DEFAULT_CLI_REDIS_CONFIG={host:"127.0.0.1",port:6379,timeout:5000,retryAttempts:3,retryDelay:1000},DEFAULT_DISPLAY_CONFIG={colors:!0,timestamps:!0,prettyJson:!0},DEFAULT_MONITORING_CONFIG={blockTimeout:5000,maxReconnectAttempts:5};var CLIConfigService=exports_Context.GenericTag("CLIConfigService"),redisHost=exports_Config.withDefault(exports_Config.string("REDIS_HOST"),DEFAULT_CLI_REDIS_CONFIG.host),redisPort=exports_Config.withDefault(exports_Config.integer("REDIS_PORT"),DEFAULT_CLI_REDIS_CONFIG.port),redisUrl=exports_Config.option(exports_Config.string("REDIS_URL")),redisTimeout=exports_Config.withDefault(exports_Config.integer("REDIS_TIMEOUT"),DEFAULT_CLI_REDIS_CONFIG.timeout),redisRetryAttempts=exports_Config.withDefault(exports_Config.integer("REDIS_RETRY_ATTEMPTS"),DEFAULT_CLI_REDIS_CONFIG.retryAttempts),redisRetryDelay=exports_Config.withDefault(exports_Config.integer("REDIS_RETRY_DELAY"),DEFAULT_CLI_REDIS_CONFIG.retryDelay),redistailColors=exports_Config.withDefault(exports_Config.boolean("REDISTAIL_COLORS"),DEFAULT_DISPLAY_CONFIG.colors),redistailTimestamps=exports_Config.withDefault(exports_Config.boolean("REDISTAIL_TIMESTAMPS"),DEFAULT_DISPLAY_CONFIG.timestamps),redistailPrettyJson=exports_Config.withDefault(exports_Config.boolean("REDISTAIL_PRETTY_JSON"),DEFAULT_DISPLAY_CONFIG.prettyJson),redistailBlockTimeout=exports_Config.withDefault(exports_Config.integer("REDISTAIL_BLOCK_TIMEOUT"),DEFAULT_MONITORING_CONFIG.blockTimeout),redistailMaxReconnectAttempts=exports_Config.withDefault(exports_Config.integer("REDISTAIL_MAX_RECONNECT_ATTEMPTS"),DEFAULT_MONITORING_CONFIG.maxReconnectAttempts),parseCommandLineArgs=(args2)=>exports_Effect.gen(function*(){if(args2.includes("--help")||args2.includes("-h"))return CLIConfig({connectionType:"pubsub",topicName:"",help:!0});if(args2.includes("--version")||args2.includes("-v"))return CLIConfig({connectionType:"pubsub",topicName:"",version:!0});if(args2.length<2)return yield*exports_Effect.fail(createMissingArgumentError("Missing required arguments. Usage: redistail <pubsub|stream> <topic-name>","ARGUMENT_PARSING"));let[connectionType,topicName,...extraArgs]=args2;if(!isValidConnectionType(connectionType))return yield*exports_Effect.fail(createInvalidArgumentError(`Invalid connection type: ${connectionType}. Must be 'pubsub' or 'stream'`,"ARGUMENT_PARSING"));if(!isValidTopicName(topicName))return yield*exports_Effect.fail(createInvalidArgumentError("Topic name cannot be empty","ARGUMENT_PARSING"));if(extraArgs.length>0)return yield*exports_Effect.fail(createInvalidArgumentError(`Unexpected arguments: ${extraArgs.join(", ")}. Usage: redistail <pubsub|stream> <topic-name>`,"ARGUMENT_PARSING"));return CLIConfig({connectionType,topicName:topicName.trim()})}),loadRedistailConfig=()=>exports_Effect.gen(function*(){let config2=yield*exports_Effect.all({redisHost,redisPort,redisUrl,redisTimeout,redisRetryAttempts,redisRetryDelay,redistailColors,redistailTimestamps,redistailPrettyJson,redistailBlockTimeout,redistailMaxReconnectAttempts}).pipe(exports_Effect.mapError((configError)=>createEnvironmentError("Failed to load configuration from environment",configError,"CONFIG_LOADING")));if(config2.redisPort<1||config2.redisPort>65535)return yield*exports_Effect.fail(createEnvironmentError(`Invalid REDIS_PORT: ${config2.redisPort}. Must be between 1 and 65535`,void 0,"CONFIG_VALIDATION"));if(config2.redisTimeout<0)return yield*exports_Effect.fail(createEnvironmentError(`Invalid REDIS_TIMEOUT: ${config2.redisTimeout}. Must be non-negative`,void 0,"CONFIG_VALIDATION"));if(config2.redisRetryAttempts<0)return yield*exports_Effect.fail(createEnvironmentError(`Invalid REDIS_RETRY_ATTEMPTS: ${config2.redisRetryAttempts}. Must be non-negative`,void 0,"CONFIG_VALIDATION"));if(config2.redisRetryDelay<0)return yield*exports_Effect.fail(createEnvironmentError(`Invalid REDIS_RETRY_DELAY: ${config2.redisRetryDelay}. Must be non-negative`,void 0,"CONFIG_VALIDATION"));if(config2.redistailBlockTimeout<0)return yield*exports_Effect.fail(createEnvironmentError(`Invalid REDISTAIL_BLOCK_TIMEOUT: ${config2.redistailBlockTimeout}. Must be non-negative`,void 0,"CONFIG_VALIDATION"));if(config2.redistailMaxReconnectAttempts<0)return yield*exports_Effect.fail(createEnvironmentError(`Invalid REDISTAIL_MAX_RECONNECT_ATTEMPTS: ${config2.redistailMaxReconnectAttempts}. Must be non-negative`,void 0,"CONFIG_VALIDATION"));return RedistailConfig({redis:{host:config2.redisHost,port:config2.redisPort,url:config2.redisUrl._tag==="Some"?config2.redisUrl.value:void 0,timeout:config2.redisTimeout,retryAttempts:config2.redisRetryAttempts,retryDelay:config2.redisRetryDelay},display:{colors:config2.redistailColors,timestamps:config2.redistailTimestamps,prettyJson:config2.redistailPrettyJson},monitoring:{blockTimeout:config2.redistailBlockTimeout,maxReconnectAttempts:config2.redistailMaxReconnectAttempts}})}),showHelp=()=>exports_Console.log(`
41
+ `)))))}),hashSet2=(config2,name)=>{let newConfig=map24(chunk3(config2),fromIterable5);return name===void 0?newConfig:nested2(newConfig,name)},string2=(name)=>{let config2=primitive("a text property",right2);return name===void 0?config2:nested2(config2,name)},nonEmptyString=(name)=>{let config2=primitive("a non-empty text property",liftPredicate((text)=>text.length>0,()=>MissingData([],"Expected a non-empty string")));return name===void 0?config2:nested2(config2,name)},all7=(arg)=>{if(Array.isArray(arg))return tuple2(arg);else if(Symbol.iterator in arg)return tuple2([...arg]);return struct3(arg)},struct3=(r)=>{let entries2=Object.entries(r),result=pipe(entries2[0][1],map24((value)=>({[entries2[0][0]]:value})));if(entries2.length===1)return result;let rest=entries2.slice(1);for(let[key,config2]of rest)result=pipe(result,zipWith13(config2,(record,value)=>({...record,[key]:value})));return result},succeed17=(value)=>{let constant2=Object.create(proto13);return constant2._tag=OP_CONSTANT,constant2.value=value,constant2.parse=()=>right2(value),constant2},suspend11=(config2)=>{let lazy=Object.create(proto13);return lazy._tag=OP_LAZY,lazy.config=config2,lazy},sync11=(value)=>{return suspend11(()=>succeed17(value()))},hashMap2=(config2,name)=>{let table2=Object.create(proto13);return table2._tag=OP_HASHMAP,table2.valueConfig=config2,name===void 0?table2:nested2(table2,name)},isConfig=(u)=>hasProperty(u,ConfigTypeId),tuple2=(tuple3)=>{if(tuple3.length===0)return succeed17([]);if(tuple3.length===1)return map24(tuple3[0],(x)=>[x]);let result=map24(tuple3[0],(x)=>[x]);for(let i=1;i<tuple3.length;i++){let config2=tuple3[i];result=pipe(result,zipWith13(config2,(tuple4,value)=>[...tuple4,value]))}return result},unwrap4=(wrapped)=>{if(isConfig(wrapped))return wrapped;return struct3(Object.fromEntries(Object.entries(wrapped).map(([k,a])=>[k,unwrap4(a)])))},validate3=dual(2,(self,{message,validation})=>mapOrFail(self,(a)=>{if(validation(a))return right2(a);return left2(InvalidData([],message))})),withDefault=dual(2,(self,def)=>orElseIf(self,{orElse:()=>succeed17(def),if:isMissingDataOnly2})),withDescription=dual(2,(self,description)=>{let described=Object.create(proto13);return described._tag=OP_DESCRIBED,described.config=self,described.description=description,described}),zip9=dual(2,(self,that)=>zipWith13(self,that,(a,b)=>[a,b])),zipWith13=dual(3,(self,that,f)=>{let zipWith14=Object.create(proto13);return zipWith14._tag=OP_ZIP_WITH,zipWith14.left=self,zipWith14.right=that,zipWith14.zip=f,zipWith14});var ConfigTypeId2=ConfigTypeId,all8=all7,array5=array4,boolean2=boolean,port2=port,url2=url,chunk4=chunk3,date2=date,fail18=fail17,number5=number4,integer2=integer,literal2=literal,logLevel2=logLevel,duration4=duration3,isConfig2=isConfig,map25=map24,mapAttempt2=mapAttempt,mapOrFail2=mapOrFail,nested3=nested2,orElse11=orElse10,orElseIf2=orElseIf,option4=option3,primitive2=primitive,repeat5=repeat4,secret2=secret,redacted2=redacted,branded2=branded,hashSet3=hashSet2,string3=string2,nonEmptyString2=nonEmptyString,succeed18=succeed17,suspend12=suspend11,sync12=sync11,hashMap3=hashMap2,unwrap5=unwrap4,validate4=validate3,withDefault2=withDefault,withDescription2=withDescription,zip10=zip9,zipWith14=zipWith13;var exports_BunRuntime={};__export(exports_BunRuntime,{runMain:()=>runMain3});var defaultLogger2=defaultLogger;var prettyLoggerDefault2=prettyLoggerDefault;var defaultTeardown=(exit3,onExit4)=>{onExit4(isFailure3(exit3)&&!isInterruptedOnly2(exit3.cause)?1:0)},addPrettyLogger=(refs,fiberId3)=>{let loggers=getOrDefault2(refs,currentLoggers2);if(!has3(loggers,defaultLogger2))return refs;return updateAs2(refs,{fiberId:fiberId3,fiberRef:currentLoggers2,value:loggers.pipe(remove4(defaultLogger2),add2(prettyLoggerDefault2))})},makeRunMain=(f)=>dual((args2)=>isEffect2(args2[0]),(effect4,options)=>{let fiber=options?.disableErrorReporting===!0?runFork2(effect4,{updateRefs:options?.disablePrettyLogger===!0?void 0:addPrettyLogger}):runFork2(tapErrorCause3(effect4,(cause3)=>{if(isInterruptedOnly2(cause3))return _void;return logError2(cause3)}),{updateRefs:options?.disablePrettyLogger===!0?void 0:addPrettyLogger}),teardown=options?.teardown??defaultTeardown;return f({fiber,teardown})});var runMain=makeRunMain(({fiber,teardown})=>{let keepAlive=setInterval(constVoid,2147483647),receivedSignal=!1;fiber.addObserver((exit3)=>{if(!receivedSignal)process.removeListener("SIGINT",onSigint),process.removeListener("SIGTERM",onSigint);clearInterval(keepAlive),teardown(exit3,(code)=>{if(receivedSignal||code!==0)process.exit(code)})});function onSigint(){receivedSignal=!0,process.removeListener("SIGINT",onSigint),process.removeListener("SIGTERM",onSigint),fiber.unsafeInterruptAsFork(fiber.id())}process.on("SIGINT",onSigint),process.on("SIGTERM",onSigint)});var runMain2=runMain;var runMain3=runMain2;var exports_Console={};__export(exports_Console,{withTime:()=>withTime2,withGroup:()=>withGroup2,withConsole:()=>withConsole3,warn:()=>warn2,trace:()=>trace2,timeLog:()=>timeLog2,time:()=>time2,table:()=>table2,setConsole:()=>setConsole2,log:()=>log4,info:()=>info2,group:()=>group2,error:()=>error2,dirxml:()=>dirxml2,dir:()=>dir2,debug:()=>debug2,countReset:()=>countReset2,count:()=>count5,consoleWith:()=>consoleWith3,clear:()=>clear2,assert:()=>assert2,TypeId:()=>TypeId18,Console:()=>Console});var TypeId18=TypeId8,Console=consoleTag,withConsole3=withConsole,setConsole2=setConsole,consoleWith3=consoleWith,assert2=assert,clear2=clear,count5=count,countReset2=countReset,debug2=debug,dir2=dir,dirxml2=dirxml,error2=error,group2=group,info2=info,log4=log2,table2=table,time2=time,timeLog2=timeLog,trace2=trace,warn2=warn,withGroup2=withGroup,withTime2=withTime;var BUILD_COMMIT="d18b194",BUILD_VERSION="0.0.4";var CLIConfig=exports_Data.struct,RedistailConfig=exports_Data.struct,PubSubMessage=exports_Data.struct,StreamMessage=exports_Data.struct;class CLIError extends exports_Data.TaggedError("CLIError"){}class ConfigError extends exports_Data.TaggedError("ConfigError"){}class MonitoringError extends exports_Data.TaggedError("MonitoringError"){}var StreamMonitorOptions=exports_Data.struct,isValidConnectionType=(type)=>type==="pubsub"||type==="stream",isValidTopicName=(name)=>typeof name==="string"&&name.trim().length>0,createInvalidArgumentError=(message,context7)=>new CLIError({reason:"InvalidArguments",message,context:context7}),createMissingArgumentError=(message,context7)=>new CLIError({reason:"MissingArguments",message,context:context7}),createEnvironmentError=(message,cause3,context7)=>new ConfigError({reason:"InvalidEnvironment",message,cause:cause3,context:context7});var createConnectionLostError=(message,cause3)=>new MonitoringError({reason:"ConnectionLost",message,retryable:!0,cause:cause3}),createSubscriptionFailedError=(message,retryable=!0,cause3)=>new MonitoringError({reason:"SubscriptionFailed",message,retryable,cause:cause3}),createStreamReadFailedError=(message,retryable=!0,cause3)=>new MonitoringError({reason:"StreamReadFailed",message,retryable,cause:cause3}),DEFAULT_CLI_REDIS_CONFIG={host:"127.0.0.1",port:6379,timeout:5000,retryAttempts:3,retryDelay:1000},DEFAULT_DISPLAY_CONFIG={colors:!0,timestamps:!0,prettyJson:!0},DEFAULT_MONITORING_CONFIG={blockTimeout:5000,maxReconnectAttempts:5};var CLIConfigService=exports_Context.GenericTag("CLIConfigService"),redisHost=exports_Config.withDefault(exports_Config.string("REDIS_HOST"),DEFAULT_CLI_REDIS_CONFIG.host),redisPort=exports_Config.withDefault(exports_Config.integer("REDIS_PORT"),DEFAULT_CLI_REDIS_CONFIG.port),redisUrl=exports_Config.option(exports_Config.string("REDIS_URL")),redisTimeout=exports_Config.withDefault(exports_Config.integer("REDIS_TIMEOUT"),DEFAULT_CLI_REDIS_CONFIG.timeout),redisRetryAttempts=exports_Config.withDefault(exports_Config.integer("REDIS_RETRY_ATTEMPTS"),DEFAULT_CLI_REDIS_CONFIG.retryAttempts),redisRetryDelay=exports_Config.withDefault(exports_Config.integer("REDIS_RETRY_DELAY"),DEFAULT_CLI_REDIS_CONFIG.retryDelay),redistailColors=exports_Config.withDefault(exports_Config.boolean("REDISTAIL_COLORS"),DEFAULT_DISPLAY_CONFIG.colors),redistailTimestamps=exports_Config.withDefault(exports_Config.boolean("REDISTAIL_TIMESTAMPS"),DEFAULT_DISPLAY_CONFIG.timestamps),redistailPrettyJson=exports_Config.withDefault(exports_Config.boolean("REDISTAIL_PRETTY_JSON"),DEFAULT_DISPLAY_CONFIG.prettyJson),redistailBlockTimeout=exports_Config.withDefault(exports_Config.integer("REDISTAIL_BLOCK_TIMEOUT"),DEFAULT_MONITORING_CONFIG.blockTimeout),redistailMaxReconnectAttempts=exports_Config.withDefault(exports_Config.integer("REDISTAIL_MAX_RECONNECT_ATTEMPTS"),DEFAULT_MONITORING_CONFIG.maxReconnectAttempts),parseCommandLineArgs=(args2)=>exports_Effect.gen(function*(){if(args2.includes("--help")||args2.includes("-h"))return CLIConfig({connectionType:"pubsub",topicName:"",help:!0});if(args2.includes("--version")||args2.includes("-v"))return CLIConfig({connectionType:"pubsub",topicName:"",version:!0});if(args2.length<2)return yield*exports_Effect.fail(createMissingArgumentError("Missing required arguments. Usage: redistail <pubsub|stream> <topic-name>","ARGUMENT_PARSING"));let[connectionType,topicName,...extraArgs]=args2;if(!isValidConnectionType(connectionType))return yield*exports_Effect.fail(createInvalidArgumentError(`Invalid connection type: ${connectionType}. Must be 'pubsub' or 'stream'`,"ARGUMENT_PARSING"));if(!isValidTopicName(topicName))return yield*exports_Effect.fail(createInvalidArgumentError("Topic name cannot be empty","ARGUMENT_PARSING"));if(extraArgs.length>0)return yield*exports_Effect.fail(createInvalidArgumentError(`Unexpected arguments: ${extraArgs.join(", ")}. Usage: redistail <pubsub|stream> <topic-name>`,"ARGUMENT_PARSING"));return CLIConfig({connectionType,topicName:topicName.trim()})}),loadRedistailConfig=()=>exports_Effect.gen(function*(){let config2=yield*exports_Effect.all({redisHost,redisPort,redisUrl,redisTimeout,redisRetryAttempts,redisRetryDelay,redistailColors,redistailTimestamps,redistailPrettyJson,redistailBlockTimeout,redistailMaxReconnectAttempts}).pipe(exports_Effect.mapError((configError)=>createEnvironmentError("Failed to load configuration from environment",configError,"CONFIG_LOADING")));if(config2.redisPort<1||config2.redisPort>65535)return yield*exports_Effect.fail(createEnvironmentError(`Invalid REDIS_PORT: ${config2.redisPort}. Must be between 1 and 65535`,void 0,"CONFIG_VALIDATION"));if(config2.redisTimeout<0)return yield*exports_Effect.fail(createEnvironmentError(`Invalid REDIS_TIMEOUT: ${config2.redisTimeout}. Must be non-negative`,void 0,"CONFIG_VALIDATION"));if(config2.redisRetryAttempts<0)return yield*exports_Effect.fail(createEnvironmentError(`Invalid REDIS_RETRY_ATTEMPTS: ${config2.redisRetryAttempts}. Must be non-negative`,void 0,"CONFIG_VALIDATION"));if(config2.redisRetryDelay<0)return yield*exports_Effect.fail(createEnvironmentError(`Invalid REDIS_RETRY_DELAY: ${config2.redisRetryDelay}. Must be non-negative`,void 0,"CONFIG_VALIDATION"));if(config2.redistailBlockTimeout<0)return yield*exports_Effect.fail(createEnvironmentError(`Invalid REDISTAIL_BLOCK_TIMEOUT: ${config2.redistailBlockTimeout}. Must be non-negative`,void 0,"CONFIG_VALIDATION"));if(config2.redistailMaxReconnectAttempts<0)return yield*exports_Effect.fail(createEnvironmentError(`Invalid REDISTAIL_MAX_RECONNECT_ATTEMPTS: ${config2.redistailMaxReconnectAttempts}. Must be non-negative`,void 0,"CONFIG_VALIDATION"));return RedistailConfig({redis:{host:config2.redisHost,port:config2.redisPort,url:config2.redisUrl._tag==="Some"?config2.redisUrl.value:void 0,timeout:config2.redisTimeout,retryAttempts:config2.redisRetryAttempts,retryDelay:config2.redisRetryDelay},display:{colors:config2.redistailColors,timestamps:config2.redistailTimestamps,prettyJson:config2.redistailPrettyJson},monitoring:{blockTimeout:config2.redistailBlockTimeout,maxReconnectAttempts:config2.redistailMaxReconnectAttempts}})}),showHelp=()=>exports_Console.log(`
42
42
  redistail - Redis message monitoring utility
43
43
 
44
44
  USAGE: